diff options
Diffstat (limited to 'editor/plugins')
130 files changed, 10170 insertions, 4178 deletions
diff --git a/editor/plugins/abstract_polygon_2d_editor.cpp b/editor/plugins/abstract_polygon_2d_editor.cpp index 1abba45f9e..876b67fa77 100644 --- a/editor/plugins/abstract_polygon_2d_editor.cpp +++ b/editor/plugins/abstract_polygon_2d_editor.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -31,6 +31,7 @@ #include "abstract_polygon_2d_editor.h" #include "canvas_item_editor_plugin.h" +#include "core/math/geometry_2d.h" #include "core/os/keyboard.h" #include "editor/editor_scale.h" @@ -286,7 +287,7 @@ bool AbstractPolygon2DEditor::forward_gui_input(const Ref<InputEvent> &p_event) pre_move_edit = vertices2; edited_point = PosVertex(insert.polygon, insert.vertex + 1, xform.affine_inverse().xform(insert.pos)); vertices2.insert(edited_point.vertex, edited_point.pos); - selected_point = edited_point; + selected_point = Vertex(edited_point.polygon, edited_point.vertex); edge_point = PosVertex(); undo_redo->create_action(TTR("Insert Point")); @@ -368,7 +369,7 @@ bool AbstractPolygon2DEditor::forward_gui_input(const Ref<InputEvent> &p_event) } else { const real_t grab_threshold = EDITOR_GET("editors/poly_editor/point_grab_radius"); - if (!_is_line() && wip.size() > 1 && xform.xform(wip[0]).distance_to(gpoint) < grab_threshold) { + if (!_is_line() && wip.size() > 1 && xform.xform(wip[0]).distance_to(xform.xform(cpoint)) < grab_threshold) { //wip closed _wip_close(); @@ -550,9 +551,10 @@ void AbstractPolygon2DEditor::forward_canvas_draw_over_viewport(Control *p_overl if (vertex == hover_point) { Ref<Font> font = get_theme_font("font", "Label"); + int font_size = get_theme_font_size("font_size", "Label"); String num = String::num(vertex.vertex); - Size2 num_size = font->get_string_size(num); - p_overlay->draw_string(font, point - num_size * 0.5, num, Color(1.0, 1.0, 1.0, 0.5)); + Size2 num_size = font->get_string_size(num, font_size); + p_overlay->draw_string(font, point - num_size * 0.5, num, HALIGN_LEFT, -1, font_size, Color(1.0, 1.0, 1.0, 0.5)); } } } @@ -671,7 +673,7 @@ AbstractPolygon2DEditor::PosVertex AbstractPolygon2DEditor::closest_edge_point(c Vector2 segment[2] = { xform.xform(points[i] + offset), xform.xform(points[(i + 1) % n_points] + offset) }; - Vector2 cp = Geometry::get_closest_point_to_segment_2d(p_pos, segment); + Vector2 cp = Geometry2D::get_closest_point_to_segment(p_pos, segment); if (cp.distance_squared_to(segment[0]) < eps2 || cp.distance_squared_to(segment[1]) < eps2) { continue; //not valid to reuse point @@ -702,24 +704,27 @@ AbstractPolygon2DEditor::AbstractPolygon2DEditor(EditorNode *p_editor, bool p_wi edge_point = PosVertex(); add_child(memnew(VSeparator)); - button_create = memnew(ToolButton); + button_create = memnew(Button); + button_create->set_flat(true); add_child(button_create); button_create->connect("pressed", callable_mp(this, &AbstractPolygon2DEditor::_menu_option), varray(MODE_CREATE)); button_create->set_toggle_mode(true); - button_edit = memnew(ToolButton); + button_edit = memnew(Button); + button_edit->set_flat(true); add_child(button_edit); button_edit->connect("pressed", callable_mp(this, &AbstractPolygon2DEditor::_menu_option), varray(MODE_EDIT)); button_edit->set_toggle_mode(true); - button_delete = memnew(ToolButton); + button_delete = memnew(Button); + button_delete->set_flat(true); add_child(button_delete); button_delete->connect("pressed", callable_mp(this, &AbstractPolygon2DEditor::_menu_option), varray(MODE_DELETE)); button_delete->set_toggle_mode(true); create_resource = memnew(ConfirmationDialog); add_child(create_resource); - create_resource->get_ok()->set_text(TTR("Create")); + create_resource->get_ok_button()->set_text(TTR("Create")); mode = MODE_EDIT; } diff --git a/editor/plugins/abstract_polygon_2d_editor.h b/editor/plugins/abstract_polygon_2d_editor.h index d5b3a916d1..4f9adfff25 100644 --- a/editor/plugins/abstract_polygon_2d_editor.h +++ b/editor/plugins/abstract_polygon_2d_editor.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -34,16 +34,15 @@ #include "editor/editor_node.h" #include "editor/editor_plugin.h" #include "scene/2d/polygon_2d.h" -#include "scene/gui/tool_button.h" class CanvasItemEditor; class AbstractPolygon2DEditor : public HBoxContainer { GDCLASS(AbstractPolygon2DEditor, HBoxContainer); - ToolButton *button_create; - ToolButton *button_edit; - ToolButton *button_delete; + Button *button_create; + Button *button_edit; + Button *button_delete; struct Vertex { Vertex() {} @@ -157,14 +156,14 @@ class AbstractPolygon2DEditorPlugin : public EditorPlugin { String klass; public: - virtual bool forward_canvas_gui_input(const Ref<InputEvent> &p_event) { return polygon_editor->forward_gui_input(p_event); } - virtual void forward_canvas_draw_over_viewport(Control *p_overlay) { polygon_editor->forward_canvas_draw_over_viewport(p_overlay); } - - bool has_main_screen() const { return false; } - virtual String get_name() const { return klass; } - virtual void edit(Object *p_object); - virtual bool handles(Object *p_object) const; - virtual void make_visible(bool p_visible); + virtual bool forward_canvas_gui_input(const Ref<InputEvent> &p_event) override { return polygon_editor->forward_gui_input(p_event); } + virtual void forward_canvas_draw_over_viewport(Control *p_overlay) override { polygon_editor->forward_canvas_draw_over_viewport(p_overlay); } + + bool has_main_screen() const override { return false; } + virtual String get_name() const override { return klass; } + virtual void edit(Object *p_object) override; + virtual bool handles(Object *p_object) const override; + virtual void make_visible(bool p_visible) override; AbstractPolygon2DEditorPlugin(EditorNode *p_node, AbstractPolygon2DEditor *p_polygon_editor, String p_class); ~AbstractPolygon2DEditorPlugin(); diff --git a/editor/plugins/animation_blend_space_1d_editor.cpp b/editor/plugins/animation_blend_space_1d_editor.cpp index 75eacf56ec..d69913cc46 100644 --- a/editor/plugins/animation_blend_space_1d_editor.cpp +++ b/editor/plugins/animation_blend_space_1d_editor.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -106,7 +106,7 @@ void AnimationNodeBlendSpace1DEditor::_blend_space_gui_input(const Ref<InputEven add_point_pos += blend_space->get_min_space(); if (snap->is_pressed()) { - add_point_pos = Math::stepify(add_point_pos, blend_space->get_snap()); + add_point_pos = Math::snapped(add_point_pos, blend_space->get_snap()); } } @@ -139,7 +139,7 @@ void AnimationNodeBlendSpace1DEditor::_blend_space_gui_input(const Ref<InputEven point += drag_ofs.x; if (snap->is_pressed()) { - point = Math::stepify(point, blend_space->get_snap()); + point = Math::snapped(point, blend_space->get_snap()); } updating = true; @@ -201,6 +201,7 @@ void AnimationNodeBlendSpace1DEditor::_blend_space_draw() { linecolor_soft.a *= 0.5; Ref<Font> font = get_theme_font("font", "Label"); + int font_size = get_theme_font_size("font_size", "Label"); Ref<Texture2D> icon = get_theme_icon("KeyValue", "EditorIcons"); Ref<Texture2D> icon_selected = get_theme_icon("KeySelected", "EditorIcons"); @@ -221,7 +222,7 @@ void AnimationNodeBlendSpace1DEditor::_blend_space_draw() { float x = point; blend_space_draw->draw_line(Point2(x, s.height - 1), Point2(x, s.height - 5 * EDSCALE), linecolor); - blend_space_draw->draw_string(font, Point2(x + 2 * EDSCALE, s.height - 2 * EDSCALE - font->get_height() + font->get_ascent()), "0", linecolor); + blend_space_draw->draw_string(font, Point2(x + 2 * EDSCALE, s.height - 2 * EDSCALE - font->get_height(font_size) + font->get_ascent(font_size)), "0", HALIGN_LEFT, -1, font_size, linecolor); blend_space_draw->draw_line(Point2(x, s.height - 5 * EDSCALE), Point2(x, 0), linecolor_soft); } @@ -252,7 +253,7 @@ void AnimationNodeBlendSpace1DEditor::_blend_space_draw() { if (dragging_selected && selected_point == i) { point += drag_ofs.x; if (snap->is_pressed()) { - point = Math::stepify(point, blend_space->get_snap()); + point = Math::snapped(point, blend_space->get_snap()); } } @@ -375,7 +376,7 @@ void AnimationNodeBlendSpace1DEditor::_add_menu_type(int p_index) { for (List<String>::Element *E = filters.front(); E; E = E->next()) { open_file->add_filter("*." + E->get()); } - open_file->popup_centered_ratio(); + open_file->popup_file_dialog(); return; } else if (p_index == MENU_LOAD_FILE_CONFIRM) { node = file_loaded; @@ -453,7 +454,7 @@ void AnimationNodeBlendSpace1DEditor::_update_edited_point_pos() { pos += drag_ofs.x; if (snap->is_pressed()) { - pos = Math::stepify(pos, blend_space->get_snap()); + pos = Math::snapped(pos, blend_space->get_snap()); } } @@ -595,7 +596,8 @@ AnimationNodeBlendSpace1DEditor::AnimationNodeBlendSpace1DEditor() { Ref<ButtonGroup> bg; bg.instance(); - tool_blend = memnew(ToolButton); + tool_blend = memnew(Button); + tool_blend->set_flat(true); tool_blend->set_toggle_mode(true); tool_blend->set_button_group(bg); top_hb->add_child(tool_blend); @@ -603,14 +605,16 @@ AnimationNodeBlendSpace1DEditor::AnimationNodeBlendSpace1DEditor() { tool_blend->set_tooltip(TTR("Set the blending position within the space")); tool_blend->connect("pressed", callable_mp(this, &AnimationNodeBlendSpace1DEditor::_tool_switch), varray(3)); - tool_select = memnew(ToolButton); + tool_select = memnew(Button); + tool_select->set_flat(true); tool_select->set_toggle_mode(true); tool_select->set_button_group(bg); top_hb->add_child(tool_select); tool_select->set_tooltip(TTR("Select and move points, create points with RMB.")); tool_select->connect("pressed", callable_mp(this, &AnimationNodeBlendSpace1DEditor::_tool_switch), varray(0)); - tool_create = memnew(ToolButton); + tool_create = memnew(Button); + tool_create->set_flat(true); tool_create->set_toggle_mode(true); tool_create->set_button_group(bg); top_hb->add_child(tool_create); @@ -619,14 +623,16 @@ AnimationNodeBlendSpace1DEditor::AnimationNodeBlendSpace1DEditor() { tool_erase_sep = memnew(VSeparator); top_hb->add_child(tool_erase_sep); - tool_erase = memnew(ToolButton); + tool_erase = memnew(Button); + tool_erase->set_flat(true); top_hb->add_child(tool_erase); tool_erase->set_tooltip(TTR("Erase points.")); tool_erase->connect("pressed", callable_mp(this, &AnimationNodeBlendSpace1DEditor::_erase_selected)); top_hb->add_child(memnew(VSeparator)); - snap = memnew(ToolButton); + snap = memnew(Button); + snap->set_flat(true); snap->set_toggle_mode(true); top_hb->add_child(snap); snap->set_pressed(true); diff --git a/editor/plugins/animation_blend_space_1d_editor.h b/editor/plugins/animation_blend_space_1d_editor.h index 8cfd6714ad..24c950fdee 100644 --- a/editor/plugins/animation_blend_space_1d_editor.h +++ b/editor/plugins/animation_blend_space_1d_editor.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -47,15 +47,15 @@ class AnimationNodeBlendSpace1DEditor : public AnimationTreeNodeEditorPlugin { Ref<AnimationNodeBlendSpace1D> blend_space; HBoxContainer *goto_parent_hb; - ToolButton *goto_parent; + Button *goto_parent; PanelContainer *panel; - ToolButton *tool_blend; - ToolButton *tool_select; - ToolButton *tool_create; + Button *tool_blend; + Button *tool_select; + Button *tool_create; VSeparator *tool_erase_sep; - ToolButton *tool_erase; - ToolButton *snap; + Button *tool_erase; + Button *snap; SpinBox *snap_value; LineEdit *label_value; @@ -129,8 +129,8 @@ protected: public: static AnimationNodeBlendSpace1DEditor *get_singleton() { return singleton; } - virtual bool can_edit(const Ref<AnimationNode> &p_node); - virtual void edit(const Ref<AnimationNode> &p_node); + virtual bool can_edit(const Ref<AnimationNode> &p_node) override; + virtual void edit(const Ref<AnimationNode> &p_node) override; AnimationNodeBlendSpace1DEditor(); }; diff --git a/editor/plugins/animation_blend_space_2d_editor.cpp b/editor/plugins/animation_blend_space_2d_editor.cpp index df67482dfb..6a57463dbc 100644 --- a/editor/plugins/animation_blend_space_2d_editor.cpp +++ b/editor/plugins/animation_blend_space_2d_editor.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -30,11 +30,11 @@ #include "animation_blend_space_2d_editor.h" +#include "core/config/project_settings.h" #include "core/input/input.h" #include "core/io/resource_loader.h" -#include "core/math/delaunay_2d.h" +#include "core/math/geometry_2d.h" #include "core/os/keyboard.h" -#include "core/project_settings.h" #include "editor/editor_scale.h" #include "scene/animation/animation_blend_tree.h" #include "scene/animation/animation_player.h" @@ -129,8 +129,8 @@ void AnimationNodeBlendSpace2DEditor::_blend_space_gui_input(const Ref<InputEven add_point_pos += blend_space->get_min_space(); if (snap->is_pressed()) { - add_point_pos.x = Math::stepify(add_point_pos.x, blend_space->get_snap().x); - add_point_pos.y = Math::stepify(add_point_pos.y, blend_space->get_snap().y); + add_point_pos.x = Math::snapped(add_point_pos.x, blend_space->get_snap().x); + add_point_pos.y = Math::snapped(add_point_pos.y, blend_space->get_snap().y); } } @@ -165,7 +165,7 @@ void AnimationNodeBlendSpace2DEditor::_blend_space_gui_input(const Ref<InputEven triangle.push_back(points[idx]); } - if (Geometry::is_point_in_triangle(mb->get_position(), triangle[0], triangle[1], triangle[2])) { + if (Geometry2D::is_point_in_triangle(mb->get_position(), triangle[0], triangle[1], triangle[2])) { selected_triangle = i; _update_tool_erase(); return; @@ -215,8 +215,8 @@ void AnimationNodeBlendSpace2DEditor::_blend_space_gui_input(const Ref<InputEven Vector2 point = blend_space->get_blend_point_position(selected_point); point += drag_ofs; if (snap->is_pressed()) { - point.x = Math::stepify(point.x, blend_space->get_snap().x); - point.y = Math::stepify(point.y, blend_space->get_snap().y); + point.x = Math::snapped(point.x, blend_space->get_snap().x); + point.y = Math::snapped(point.y, blend_space->get_snap().y); } updating = true; @@ -298,7 +298,7 @@ void AnimationNodeBlendSpace2DEditor::_add_menu_type(int p_index) { for (List<String>::Element *E = filters.front(); E; E = E->next()) { open_file->add_filter("*." + E->get()); } - open_file->popup_centered_ratio(); + open_file->popup_file_dialog(); return; } else if (p_index == MENU_LOAD_FILE_CONFIRM) { node = file_loaded; @@ -396,6 +396,7 @@ void AnimationNodeBlendSpace2DEditor::_blend_space_draw() { Color linecolor_soft = linecolor; linecolor_soft.a *= 0.5; Ref<Font> font = get_theme_font("font", "Label"); + int font_size = get_theme_font_size("font_size", "Label"); Ref<Texture2D> icon = get_theme_icon("KeyValue", "EditorIcons"); Ref<Texture2D> icon_selected = get_theme_icon("KeySelected", "EditorIcons"); @@ -412,14 +413,14 @@ void AnimationNodeBlendSpace2DEditor::_blend_space_draw() { if (blend_space->get_min_space().y < 0) { int y = (blend_space->get_max_space().y / (blend_space->get_max_space().y - blend_space->get_min_space().y)) * s.height; blend_space_draw->draw_line(Point2(0, y), Point2(5 * EDSCALE, y), linecolor); - blend_space_draw->draw_string(font, Point2(2 * EDSCALE, y - font->get_height() + font->get_ascent()), "0", linecolor); + blend_space_draw->draw_string(font, Point2(2 * EDSCALE, y - font->get_height(font_size) + font->get_ascent(font_size)), "0", HALIGN_LEFT, -1, font_size, linecolor); blend_space_draw->draw_line(Point2(5 * EDSCALE, y), Point2(s.width, y), linecolor_soft); } if (blend_space->get_min_space().x < 0) { int x = (-blend_space->get_min_space().x / (blend_space->get_max_space().x - blend_space->get_min_space().x)) * s.width; blend_space_draw->draw_line(Point2(x, s.height - 1), Point2(x, s.height - 5 * EDSCALE), linecolor); - blend_space_draw->draw_string(font, Point2(x + 2 * EDSCALE, s.height - 2 * EDSCALE - font->get_height() + font->get_ascent()), "0", linecolor); + blend_space_draw->draw_string(font, Point2(x + 2 * EDSCALE, s.height - 2 * EDSCALE - font->get_height(font_size) + font->get_ascent(font_size)), "0", HALIGN_LEFT, -1, font_size, linecolor); blend_space_draw->draw_line(Point2(x, s.height - 5 * EDSCALE), Point2(x, 0), linecolor_soft); } @@ -466,8 +467,8 @@ void AnimationNodeBlendSpace2DEditor::_blend_space_draw() { if (dragging_selected && selected_point == point_idx) { point += drag_ofs; if (snap->is_pressed()) { - point.x = Math::stepify(point.x, blend_space->get_snap().x); - point.y = Math::stepify(point.y, blend_space->get_snap().y); + point.x = Math::snapped(point.x, blend_space->get_snap().x); + point.y = Math::snapped(point.y, blend_space->get_snap().y); } } point = (point - blend_space->get_min_space()) / (blend_space->get_max_space() - blend_space->get_min_space()); @@ -502,8 +503,8 @@ void AnimationNodeBlendSpace2DEditor::_blend_space_draw() { if (dragging_selected && selected_point == i) { point += drag_ofs; if (snap->is_pressed()) { - point.x = Math::stepify(point.x, blend_space->get_snap().x); - point.y = Math::stepify(point.y, blend_space->get_snap().y); + point.x = Math::snapped(point.x, blend_space->get_snap().x); + point.y = Math::snapped(point.y, blend_space->get_snap().y); } } point = (point - blend_space->get_min_space()) / (blend_space->get_max_space() - blend_space->get_min_space()); @@ -701,8 +702,8 @@ void AnimationNodeBlendSpace2DEditor::_update_edited_point_pos() { if (dragging_selected) { pos += drag_ofs; if (snap->is_pressed()) { - pos.x = Math::stepify(pos.x, blend_space->get_snap().x); - pos.y = Math::stepify(pos.y, blend_space->get_snap().y); + pos.x = Math::snapped(pos.x, blend_space->get_snap().x); + pos.y = Math::snapped(pos.y, blend_space->get_snap().y); } } updating = true; @@ -819,7 +820,8 @@ AnimationNodeBlendSpace2DEditor::AnimationNodeBlendSpace2DEditor() { Ref<ButtonGroup> bg; bg.instance(); - tool_blend = memnew(ToolButton); + tool_blend = memnew(Button); + tool_blend->set_flat(true); tool_blend->set_toggle_mode(true); tool_blend->set_button_group(bg); top_hb->add_child(tool_blend); @@ -827,21 +829,24 @@ AnimationNodeBlendSpace2DEditor::AnimationNodeBlendSpace2DEditor() { tool_blend->set_tooltip(TTR("Set the blending position within the space")); tool_blend->connect("pressed", callable_mp(this, &AnimationNodeBlendSpace2DEditor::_tool_switch), varray(3)); - tool_select = memnew(ToolButton); + tool_select = memnew(Button); + tool_select->set_flat(true); tool_select->set_toggle_mode(true); tool_select->set_button_group(bg); top_hb->add_child(tool_select); tool_select->set_tooltip(TTR("Select and move points, create points with RMB.")); tool_select->connect("pressed", callable_mp(this, &AnimationNodeBlendSpace2DEditor::_tool_switch), varray(0)); - tool_create = memnew(ToolButton); + tool_create = memnew(Button); + tool_create->set_flat(true); tool_create->set_toggle_mode(true); tool_create->set_button_group(bg); top_hb->add_child(tool_create); tool_create->set_tooltip(TTR("Create points.")); tool_create->connect("pressed", callable_mp(this, &AnimationNodeBlendSpace2DEditor::_tool_switch), varray(1)); - tool_triangle = memnew(ToolButton); + tool_triangle = memnew(Button); + tool_triangle->set_flat(true); tool_triangle->set_toggle_mode(true); tool_triangle->set_button_group(bg); top_hb->add_child(tool_triangle); @@ -850,7 +855,8 @@ AnimationNodeBlendSpace2DEditor::AnimationNodeBlendSpace2DEditor() { tool_erase_sep = memnew(VSeparator); top_hb->add_child(tool_erase_sep); - tool_erase = memnew(ToolButton); + tool_erase = memnew(Button); + tool_erase->set_flat(true); top_hb->add_child(tool_erase); tool_erase->set_tooltip(TTR("Erase points and triangles.")); tool_erase->connect("pressed", callable_mp(this, &AnimationNodeBlendSpace2DEditor::_erase_selected)); @@ -858,7 +864,8 @@ AnimationNodeBlendSpace2DEditor::AnimationNodeBlendSpace2DEditor() { top_hb->add_child(memnew(VSeparator)); - auto_triangles = memnew(ToolButton); + auto_triangles = memnew(Button); + auto_triangles->set_flat(true); top_hb->add_child(auto_triangles); auto_triangles->connect("pressed", callable_mp(this, &AnimationNodeBlendSpace2DEditor::_auto_triangles_toggled)); auto_triangles->set_toggle_mode(true); @@ -866,7 +873,8 @@ AnimationNodeBlendSpace2DEditor::AnimationNodeBlendSpace2DEditor() { top_hb->add_child(memnew(VSeparator)); - snap = memnew(ToolButton); + snap = memnew(Button); + snap->set_flat(true); snap->set_toggle_mode(true); top_hb->add_child(snap); snap->set_pressed(true); diff --git a/editor/plugins/animation_blend_space_2d_editor.h b/editor/plugins/animation_blend_space_2d_editor.h index b430a12297..3b8b78b2b5 100644 --- a/editor/plugins/animation_blend_space_2d_editor.h +++ b/editor/plugins/animation_blend_space_2d_editor.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -47,18 +47,18 @@ class AnimationNodeBlendSpace2DEditor : public AnimationTreeNodeEditorPlugin { Ref<AnimationNodeBlendSpace2D> blend_space; PanelContainer *panel; - ToolButton *tool_blend; - ToolButton *tool_select; - ToolButton *tool_create; - ToolButton *tool_triangle; + Button *tool_blend; + Button *tool_select; + Button *tool_create; + Button *tool_triangle; VSeparator *tool_erase_sep; - ToolButton *tool_erase; - ToolButton *snap; + Button *tool_erase; + Button *snap; SpinBox *snap_x; SpinBox *snap_y; OptionButton *interpolation; - ToolButton *auto_triangles; + Button *auto_triangles; LineEdit *label_x; LineEdit *label_y; @@ -142,8 +142,8 @@ protected: public: static AnimationNodeBlendSpace2DEditor *get_singleton() { return singleton; } - virtual bool can_edit(const Ref<AnimationNode> &p_node); - virtual void edit(const Ref<AnimationNode> &p_node); + virtual bool can_edit(const Ref<AnimationNode> &p_node) override; + virtual void edit(const Ref<AnimationNode> &p_node) override; AnimationNodeBlendSpace2DEditor(); }; diff --git a/editor/plugins/animation_blend_tree_editor_plugin.cpp b/editor/plugins/animation_blend_tree_editor_plugin.cpp index 82d942821f..e7e069e8b6 100644 --- a/editor/plugins/animation_blend_tree_editor_plugin.cpp +++ b/editor/plugins/animation_blend_tree_editor_plugin.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -30,10 +30,10 @@ #include "animation_blend_tree_editor_plugin.h" +#include "core/config/project_settings.h" #include "core/input/input.h" #include "core/io/resource_loader.h" #include "core/os/keyboard.h" -#include "core/project_settings.h" #include "editor/editor_inspector.h" #include "editor/editor_scale.h" #include "scene/animation/animation_player.h" @@ -127,7 +127,7 @@ void AnimationNodeBlendTreeEditor::_update_graph() { Ref<AnimationNode> agnode = blend_tree->get_node(E->get()); - node->set_offset(blend_tree->get_node_position(E->get()) * EDSCALE); + node->set_position_offset(blend_tree->get_node_position(E->get()) * EDSCALE); node->set_title(agnode->get_caption()); node->set_name(E->get()); @@ -255,6 +255,9 @@ void AnimationNodeBlendTreeEditor::_update_graph() { graph->connect_node(from, 0, to, to_idx); } + + float graph_minimap_opacity = EditorSettings::get_singleton()->get("editors/visual_editors/minimap_opacity"); + graph->set_minimap_opacity(graph_minimap_opacity); } void AnimationNodeBlendTreeEditor::_file_opened(const String &p_file) { @@ -276,7 +279,7 @@ void AnimationNodeBlendTreeEditor::_add_node(int p_idx) { for (List<String>::Element *E = filters.front(); E; E = E->next()) { open_file->add_filter("*." + E->get()); } - open_file->popup_centered_ratio(); + open_file->popup_file_dialog(); return; } else if (p_idx == MENU_LOAD_FILE_CONFIRM) { anode = file_loaded; @@ -416,7 +419,7 @@ void AnimationNodeBlendTreeEditor::_delete_nodes_request() { } } - if (to_erase.empty()) { + if (to_erase.is_empty()) { return; } @@ -537,7 +540,7 @@ bool AnimationNodeBlendTreeEditor::_update_filters(const Ref<AnimationNode> &ano default: { } break; } - if (!track_type_name.empty()) { + if (!track_type_name.is_empty()) { types[track_path].insert(track_type_name); } } @@ -888,6 +891,8 @@ AnimationNodeBlendTreeEditor::AnimationNodeBlendTreeEditor() { graph->connect("scroll_offset_changed", callable_mp(this, &AnimationNodeBlendTreeEditor::_scroll_changed)); graph->connect("delete_nodes_request", callable_mp(this, &AnimationNodeBlendTreeEditor::_delete_nodes_request)); graph->connect("popup_request", callable_mp(this, &AnimationNodeBlendTreeEditor::_popup_request)); + float graph_minimap_opacity = EditorSettings::get_singleton()->get("editors/visual_editors/minimap_opacity"); + graph->set_minimap_opacity(graph_minimap_opacity); VSeparator *vs = memnew(VSeparator); graph->get_zoom_hbox()->add_child(vs); diff --git a/editor/plugins/animation_blend_tree_editor_plugin.h b/editor/plugins/animation_blend_tree_editor_plugin.h index 6bdb7e7909..9f09069719 100644 --- a/editor/plugins/animation_blend_tree_editor_plugin.h +++ b/editor/plugins/animation_blend_tree_editor_plugin.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -129,10 +129,10 @@ public: void add_custom_type(const String &p_name, const Ref<Script> &p_script); void remove_custom_type(const Ref<Script> &p_script); - virtual Size2 get_minimum_size() const; + virtual Size2 get_minimum_size() const override; - virtual bool can_edit(const Ref<AnimationNode> &p_node); - virtual void edit(const Ref<AnimationNode> &p_node); + virtual bool can_edit(const Ref<AnimationNode> &p_node) override; + virtual void edit(const Ref<AnimationNode> &p_node) override; AnimationNodeBlendTreeEditor(); }; diff --git a/editor/plugins/animation_player_editor_plugin.cpp b/editor/plugins/animation_player_editor_plugin.cpp index 1e0a9535e2..7c623505b5 100644 --- a/editor/plugins/animation_player_editor_plugin.cpp +++ b/editor/plugins/animation_player_editor_plugin.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -30,11 +30,11 @@ #include "animation_player_editor_plugin.h" +#include "core/config/project_settings.h" #include "core/input/input.h" #include "core/io/resource_loader.h" #include "core/io/resource_saver.h" #include "core/os/keyboard.h" -#include "core/project_settings.h" #include "editor/animation_track_editor.h" #include "editor/editor_scale.h" #include "editor/editor_settings.h" @@ -78,7 +78,6 @@ void AnimationPlayerEditor::_notification(int p_what) { } frame->set_value(player->get_current_animation_position()); track_editor->set_anim_pos(player->get_current_animation_position()); - EditorNode::get_singleton()->get_inspector()->refresh(); } else if (!player->is_valid()) { // Reset timeline when the player has been stopped externally @@ -105,6 +104,8 @@ void AnimationPlayerEditor::_notification(int p_what) { case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: { add_theme_style_override("panel", editor->get_gui_base()->get_theme_stylebox("panel", "Panel")); } break; + case NOTIFICATION_TRANSLATION_CHANGED: + case NOTIFICATION_LAYOUT_DIRECTION_CHANGED: case NOTIFICATION_THEME_CHANGED: { autoplay->set_icon(get_theme_icon("AutoPlay", "EditorIcons")); @@ -114,10 +115,23 @@ void AnimationPlayerEditor::_notification(int p_what) { play_bw_from->set_icon(get_theme_icon("PlayBackwards", "EditorIcons")); autoplay_icon = get_theme_icon("AutoPlay", "EditorIcons"); + reset_icon = get_theme_icon("Reload", "EditorIcons"); + { + Ref<Image> autoplay_img = autoplay_icon->get_data(); + Ref<Image> reset_img = reset_icon->get_data(); + Ref<Image> autoplay_reset_img; + Size2 icon_size = Size2(autoplay_img->get_width(), autoplay_img->get_height()); + autoplay_reset_img.instance(); + autoplay_reset_img->create(icon_size.x * 2, icon_size.y, false, autoplay_img->get_format()); + autoplay_reset_img->blit_rect(autoplay_img, Rect2(Point2(), icon_size), Point2()); + autoplay_reset_img->blit_rect(reset_img, Rect2(Point2(), icon_size), Point2(icon_size.x, 0)); + autoplay_reset_icon.instance(); + autoplay_reset_icon->create_from_image(autoplay_reset_img); + } stop->set_icon(get_theme_icon("Stop", "EditorIcons")); onion_toggle->set_icon(get_theme_icon("Onion", "EditorIcons")); - onion_skinning->set_icon(get_theme_icon("GuiTabMenu", "EditorIcons")); + onion_skinning->set_icon(get_theme_icon("GuiTabMenuHl", "EditorIcons")); pin->set_icon(get_theme_icon("Pin", "EditorIcons")); @@ -340,7 +354,7 @@ void AnimationPlayerEditor::_animation_load() { file->add_filter("*." + E->get() + " ; " + E->get().to_upper()); } - file->popup_centered_ratio(); + file->popup_file_dialog(); current_option = RESOURCE_LOAD; } @@ -380,28 +394,27 @@ void AnimationPlayerEditor::_animation_save_as(const Ref<Resource> &p_resource) file->add_filter("*." + extensions[i] + " ; " + extensions[i].to_upper()); } + String path; //file->set_current_path(current_path); if (p_resource->get_path() != "") { - file->set_current_path(p_resource->get_path()); + path = p_resource->get_path(); if (extensions.size()) { - String ext = p_resource->get_path().get_extension().to_lower(); - if (extensions.find(ext) == nullptr) { - file->set_current_path(p_resource->get_path().replacen("." + ext, "." + extensions.front()->get())); + if (extensions.find(p_resource->get_path().get_extension().to_lower()) == nullptr) { + path = p_resource->get_path().get_base_dir() + p_resource->get_name() + "." + extensions.front()->get(); } } } else { - String existing; if (extensions.size()) { if (p_resource->get_name() != "") { - existing = p_resource->get_name() + "." + extensions.front()->get().to_lower(); + path = p_resource->get_name() + "." + extensions.front()->get().to_lower(); } else { - existing = "new_" + p_resource->get_class().to_lower() + "." + extensions.front()->get().to_lower(); + path = "new_" + p_resource->get_class().to_lower() + "." + extensions.front()->get().to_lower(); } } - file->set_current_path(existing); } - file->popup_centered_ratio(); + file->set_current_path(path); file->set_title(TTR("Save Resource As...")); + file->popup_file_dialog(); current_option = RESOURCE_SAVE; } @@ -412,7 +425,7 @@ void AnimationPlayerEditor::_animation_remove() { String current = animation->get_item_text(animation->get_selected()); - delete_dialog->set_text(TTR("Delete Animation '" + current + "'?")); + delete_dialog->set_text(vformat(TTR("Delete Animation '%s'?"), current)); delete_dialog->popup_centered(); } @@ -666,7 +679,7 @@ void AnimationPlayerEditor::set_state(const Dictionary &p_state) { if (p_state.has("animation")) { String anim = p_state["animation"]; - if (!anim.empty() && player->has_animation(anim)) { + if (!anim.is_empty() && player->has_animation(anim)) { _select_anim_by_name(anim); _animation_edit(); } @@ -703,30 +716,26 @@ void AnimationPlayerEditor::_animation_edit() { } } -void AnimationPlayerEditor::_dialog_action(String p_file) { +void AnimationPlayerEditor::_dialog_action(String p_path) { switch (current_option) { case RESOURCE_LOAD: { ERR_FAIL_COND(!player); - Ref<Resource> res = ResourceLoader::load(p_file, "Animation"); - ERR_FAIL_COND_MSG(res.is_null(), "Cannot load Animation from file '" + p_file + "'."); - ERR_FAIL_COND_MSG(!res->is_class("Animation"), "Loaded resource from file '" + p_file + "' is not Animation."); - if (p_file.find_last("/") != -1) { - p_file = p_file.substr(p_file.find_last("/") + 1, p_file.length()); - } - if (p_file.find_last("\\") != -1) { - p_file = p_file.substr(p_file.find_last("\\") + 1, p_file.length()); - } + Ref<Resource> res = ResourceLoader::load(p_path, "Animation"); + ERR_FAIL_COND_MSG(res.is_null(), "Cannot load Animation from file '" + p_path + "'."); + ERR_FAIL_COND_MSG(!res->is_class("Animation"), "Loaded resource from file '" + p_path + "' is not Animation."); - if (p_file.find(".") != -1) { - p_file = p_file.substr(0, p_file.find(".")); + String anim_name = p_path.get_file(); + int ext_pos = anim_name.rfind("."); + if (ext_pos != -1) { + anim_name = anim_name.substr(0, ext_pos); } undo_redo->create_action(TTR("Load Animation")); - undo_redo->add_do_method(player, "add_animation", p_file, res); - undo_redo->add_undo_method(player, "remove_animation", p_file); - if (player->has_animation(p_file)) { - undo_redo->add_undo_method(player, "add_animation", p_file, player->get_animation(p_file)); + undo_redo->add_do_method(player, "add_animation", anim_name, res); + undo_redo->add_undo_method(player, "remove_animation", anim_name); + if (player->has_animation(anim_name)) { + undo_redo->add_undo_method(player, "add_animation", anim_name, player->get_animation(anim_name)); } undo_redo->add_do_method(this, "_animation_player_changed", player); undo_redo->add_undo_method(this, "_animation_player_changed", player); @@ -742,14 +751,14 @@ void AnimationPlayerEditor::_dialog_action(String p_file) { RES current_res = RES(Object::cast_to<Resource>(*anim)); - _animation_save_in_path(current_res, p_file); + _animation_save_in_path(current_res, p_path); } } } } void AnimationPlayerEditor::_scale_changed(const String &p_scale) { - player->set_speed_scale(p_scale.to_double()); + player->set_speed_scale(p_scale.to_float()); } void AnimationPlayerEditor::_update_animation() { @@ -820,11 +829,17 @@ void AnimationPlayerEditor::_update_player() { int active_idx = -1; for (List<StringName>::Element *E = animlist.front(); E; E = E->next()) { - if (player->get_autoplay() == E->get()) { - animation->add_icon_item(autoplay_icon, E->get()); - } else { - animation->add_item(E->get()); + Ref<Texture2D> icon; + if (E->get() == player->get_autoplay()) { + if (E->get() == "RESET") { + icon = autoplay_reset_icon; + } else { + icon = autoplay_icon; + } + } else if (E->get() == "RESET") { + icon = reset_icon; } + animation->add_icon_item(icon, E->get()); if (player->get_assigned_animation() == E->get()) { active_idx = animation->get_item_count() - 1; @@ -997,7 +1012,7 @@ void AnimationPlayerEditor::_seek_value_changed(float p_value, bool p_set) { float pos = CLAMP(anim->get_length() * (p_value / frame->get_max()), 0, anim->get_length()); if (track_editor->is_snap_enabled()) { - pos = Math::stepify(pos, _get_editor_step()); + pos = Math::snapped(pos, _get_editor_step()); } if (player->is_valid() && !p_set) { @@ -1053,11 +1068,9 @@ void AnimationPlayerEditor::_animation_key_editor_seek(float p_pos, bool p_drag) } updating = true; - frame->set_value(Math::stepify(p_pos, _get_editor_step())); + frame->set_value(Math::snapped(p_pos, _get_editor_step())); updating = false; _seek_value_changed(p_pos, !p_drag); - - EditorNode::get_singleton()->get_inspector()->refresh(); } void AnimationPlayerEditor::_animation_tool_menu(int p_option) { @@ -1215,9 +1228,11 @@ void AnimationPlayerEditor::_unhandled_key_input(const Ref<InputEvent> &p_ev) { } else { _play_bw_pressed(); } + accept_event(); } break; case KEY_S: { _stop_pressed(); + accept_event(); } break; case KEY_D: { if (!k->get_shift()) { @@ -1225,6 +1240,7 @@ void AnimationPlayerEditor::_unhandled_key_input(const Ref<InputEvent> &p_ev) { } else { _play_pressed(); } + accept_event(); } break; } } @@ -1375,13 +1391,13 @@ void AnimationPlayerEditor::_prepare_onion_layers_2() { } // Backup current animation state. - AnimatedValuesBackup values_backup = player->backup_animated_values(); + Ref<AnimatedValuesBackup> values_backup = player->backup_animated_values(); float cpos = player->get_current_animation_position(); // Render every past/future step with the capture shader. RS::get_singleton()->canvas_item_set_material(onion.capture.canvas_item, onion.capture.material->get_rid()); - onion.capture.material->set_shader_param("bkg_color", GLOBAL_GET("rendering/environment/default_clear_color")); + onion.capture.material->set_shader_param("bkg_color", GLOBAL_GET("rendering/environment/defaults/default_clear_color")); onion.capture.material->set_shader_param("differences_only", onion.differences_only); onion.capture.material->set_shader_param("present", onion.differences_only ? RS::get_singleton()->viewport_get_texture(present_rid) : RID()); @@ -1405,7 +1421,7 @@ void AnimationPlayerEditor::_prepare_onion_layers_2() { if (valid) { player->seek(pos, true); get_tree()->flush_transform_notifications(); // Needed for transforms of Node3Ds. - values_backup.update_skeletons(); // Needed for Skeletons (2D & 3D). + values_backup->update_skeletons(); // Needed for Skeletons (2D & 3D). RS::get_singleton()->viewport_set_active(onion.captures[cidx], true); RS::get_singleton()->viewport_set_parent_viewport(root_vp, onion.captures[cidx]); @@ -1425,7 +1441,7 @@ void AnimationPlayerEditor::_prepare_onion_layers_2() { // (Seeking with update=true wouldn't do the trick because the current value of the properties // may not match their value for the current point in the animation). player->seek(cpos, false); - player->restore_animated_values(values_backup); + values_backup->restore(); // Restore state of main editors. if (Node3DEditor::get_singleton()->is_visible()) { @@ -1503,24 +1519,29 @@ AnimationPlayerEditor::AnimationPlayerEditor(EditorNode *p_editor, AnimationPlay HBoxContainer *hb = memnew(HBoxContainer); add_child(hb); - play_bw_from = memnew(ToolButton); + play_bw_from = memnew(Button); + play_bw_from->set_flat(true); play_bw_from->set_tooltip(TTR("Play selected animation backwards from current pos. (A)")); hb->add_child(play_bw_from); - play_bw = memnew(ToolButton); + play_bw = memnew(Button); + play_bw->set_flat(true); play_bw->set_tooltip(TTR("Play selected animation backwards from end. (Shift+A)")); hb->add_child(play_bw); - stop = memnew(ToolButton); + stop = memnew(Button); + stop->set_flat(true); stop->set_toggle_mode(true); hb->add_child(stop); stop->set_tooltip(TTR("Stop animation playback. (S)")); - play = memnew(ToolButton); + play = memnew(Button); + play->set_flat(true); play->set_tooltip(TTR("Play selected animation from start. (Shift+D)")); hb->add_child(play); - play_from = memnew(ToolButton); + play_from = memnew(Button); + play_from->set_flat(true); play_from->set_tooltip(TTR("Play selected animation from current pos. (D)")); hb->add_child(play_from); @@ -1545,6 +1566,7 @@ AnimationPlayerEditor::AnimationPlayerEditor(EditorNode *p_editor, AnimationPlay delete_dialog->connect("confirmed", callable_mp(this, &AnimationPlayerEditor::_animation_remove_confirmed)); tool_anim = memnew(MenuButton); + tool_anim->set_shortcut_context(this); tool_anim->set_flat(false); tool_anim->set_tooltip(TTR("Animation Tools")); tool_anim->set_text(TTR("Animation")); @@ -1572,7 +1594,8 @@ AnimationPlayerEditor::AnimationPlayerEditor(EditorNode *p_editor, AnimationPlay animation->set_tooltip(TTR("Display list of animations in player.")); animation->set_clip_text(true); - autoplay = memnew(ToolButton); + autoplay = memnew(Button); + autoplay->set_flat(true); hb->add_child(autoplay); autoplay->set_tooltip(TTR("Autoplay on Load")); @@ -1584,7 +1607,8 @@ AnimationPlayerEditor::AnimationPlayerEditor(EditorNode *p_editor, AnimationPlay hb->add_child(memnew(VSeparator)); - onion_toggle = memnew(ToolButton); + onion_toggle = memnew(Button); + onion_toggle->set_flat(true); onion_toggle->set_toggle_mode(true); onion_toggle->set_tooltip(TTR("Enable Onion Skinning")); onion_toggle->connect("pressed", callable_mp(this, &AnimationPlayerEditor::_onion_skinning_menu), varray(ONION_SKINNING_ENABLE)); @@ -1609,7 +1633,8 @@ AnimationPlayerEditor::AnimationPlayerEditor(EditorNode *p_editor, AnimationPlay hb->add_child(memnew(VSeparator)); - pin = memnew(ToolButton); + pin = memnew(Button); + pin->set_flat(true); pin->set_toggle_mode(true); pin->set_tooltip(TTR("Pin AnimationPlayer")); hb->add_child(pin); @@ -1633,7 +1658,7 @@ AnimationPlayerEditor::AnimationPlayerEditor(EditorNode *p_editor, AnimationPlay name_dialog->register_text_enter(name); error_dialog = memnew(ConfirmationDialog); - error_dialog->get_ok()->set_text(TTR("Close")); + error_dialog->get_ok_button()->set_text(TTR("Close")); error_dialog->set_title(TTR("Error!")); add_child(error_dialog); @@ -1641,7 +1666,7 @@ AnimationPlayerEditor::AnimationPlayerEditor(EditorNode *p_editor, AnimationPlay blend_editor.dialog = memnew(AcceptDialog); add_child(blend_editor.dialog); - blend_editor.dialog->get_ok()->set_text(TTR("Close")); + blend_editor.dialog->get_ok_button()->set_text(TTR("Close")); blend_editor.dialog->set_hide_on_ok(true); VBoxContainer *blend_vb = memnew(VBoxContainer); blend_editor.dialog->add_child(blend_vb); diff --git a/editor/plugins/animation_player_editor_plugin.h b/editor/plugins/animation_player_editor_plugin.h index 18f2d3b25e..2f6bf55e4c 100644 --- a/editor/plugins/animation_player_editor_plugin.h +++ b/editor/plugins/animation_player_editor_plugin.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -96,15 +96,17 @@ class AnimationPlayerEditor : public VBoxContainer { Button *autoplay; MenuButton *tool_anim; - ToolButton *onion_toggle; + Button *onion_toggle; MenuButton *onion_skinning; - ToolButton *pin; + Button *pin; SpinBox *frame; LineEdit *scale; LineEdit *name; Label *name_title; UndoRedo *undo_redo; Ref<Texture2D> autoplay_icon; + Ref<Texture2D> reset_icon; + Ref<ImageTexture> autoplay_reset_icon; bool last_active; float timeline_position; @@ -113,9 +115,9 @@ class AnimationPlayerEditor : public VBoxContainer { int current_option; struct BlendEditor { - AcceptDialog *dialog; - Tree *tree; - OptionButton *next; + AcceptDialog *dialog = nullptr; + Tree *tree = nullptr; + OptionButton *next = nullptr; } blend_editor; @@ -131,13 +133,13 @@ class AnimationPlayerEditor : public VBoxContainer { // Onion skinning. struct { // Settings. - bool enabled; - bool past; - bool future; - int steps; - bool differences_only; - bool force_white_modulate; - bool include_gizmos; + bool enabled = false; + bool past = false; + bool future = false; + int steps = 0; + bool differences_only = false; + bool force_white_modulate = false; + bool include_gizmos = false; int get_needed_capture_count() const { // 'Differences only' needs a capture of the present. @@ -145,8 +147,8 @@ class AnimationPlayerEditor : public VBoxContainer { } // Rendering. - int64_t last_frame; - int can_overlay; + int64_t last_frame = 0; + int can_overlay = 0; Size2 capture_size; Vector<RID> captures; Vector<bool> captures_valid; @@ -251,16 +253,16 @@ protected: void _notification(int p_what); public: - virtual Dictionary get_state() const { return anim_editor->get_state(); } - virtual void set_state(const Dictionary &p_state) { anim_editor->set_state(p_state); } + virtual Dictionary get_state() const override { return anim_editor->get_state(); } + virtual void set_state(const Dictionary &p_state) override { anim_editor->set_state(p_state); } - virtual String get_name() const { return "Anim"; } - bool has_main_screen() const { return false; } - virtual void edit(Object *p_object); - virtual bool handles(Object *p_object) const; - virtual void make_visible(bool p_visible); + virtual String get_name() const override { return "Anim"; } + bool has_main_screen() const override { return false; } + virtual void edit(Object *p_object) override; + virtual bool handles(Object *p_object) const override; + virtual void make_visible(bool p_visible) override; - virtual void forward_canvas_force_draw_over_viewport(Control *p_overlay) { anim_editor->forward_canvas_force_draw_over_viewport(p_overlay); } + virtual void forward_canvas_force_draw_over_viewport(Control *p_overlay) override { anim_editor->forward_canvas_force_draw_over_viewport(p_overlay); } AnimationPlayerEditorPlugin(EditorNode *p_node); ~AnimationPlayerEditorPlugin(); diff --git a/editor/plugins/animation_state_machine_editor.cpp b/editor/plugins/animation_state_machine_editor.cpp index 652754a146..c6d2faf849 100644 --- a/editor/plugins/animation_state_machine_editor.cpp +++ b/editor/plugins/animation_state_machine_editor.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -30,11 +30,11 @@ #include "animation_state_machine_editor.h" +#include "core/config/project_settings.h" #include "core/input/input.h" #include "core/io/resource_loader.h" -#include "core/math/delaunay_2d.h" +#include "core/math/geometry_2d.h" #include "core/os/keyboard.h" -#include "core/project_settings.h" #include "editor/editor_scale.h" #include "scene/animation/animation_blend_tree.h" #include "scene/animation/animation_player.h" @@ -191,7 +191,7 @@ void AnimationNodeStateMachineEditor::_state_machine_gui_input(const Ref<InputEv transition_lines[i].from, transition_lines[i].to }; - Vector2 cpoint = Geometry::get_closest_point_to_segment_2d(mb->get_position(), s); + Vector2 cpoint = Geometry2D::get_closest_point_to_segment(mb->get_position(), s); float d = cpoint.distance_to(mb->get_position()); if (d > transition_lines[i].width) { continue; @@ -386,6 +386,12 @@ void AnimationNodeStateMachineEditor::_state_machine_gui_input(const Ref<InputEv over_text = over_text_now; } } + + Ref<InputEventPanGesture> pan_gesture = p_event; + if (pan_gesture.is_valid()) { + h_scroll->set_value(h_scroll->get_value() + h_scroll->get_page() * pan_gesture->get_delta().x / 8); + v_scroll->set_value(v_scroll->get_value() + v_scroll->get_page() * pan_gesture->get_delta().y / 8); + } } void AnimationNodeStateMachineEditor::_file_opened(const String &p_file) { @@ -406,7 +412,7 @@ void AnimationNodeStateMachineEditor::_add_menu_type(int p_index) { for (List<String>::Element *E = filters.front(); E; E = E->next()) { open_file->add_filter("*." + E->get()); } - open_file->popup_centered_ratio(); + open_file->popup_file_dialog(); return; } else if (p_index == MENU_LOAD_FILE_CONFIRM) { node = file_loaded; @@ -514,7 +520,7 @@ void AnimationNodeStateMachineEditor::_connection_draw(const Vector2 &p_from, co Transform2D xf; xf.elements[0] = (p_to - p_from).normalized(); - xf.elements[1] = xf.elements[0].tangent(); + xf.elements[1] = xf.elements[0].orthogonal(); xf.elements[2] = (p_from + p_to) * 0.5 - xf.elements[1] * icon->get_height() * 0.5 - xf.elements[0] * icon->get_height() * 0.5; state_machine_draw->draw_set_transform_matrix(xf); @@ -553,6 +559,7 @@ void AnimationNodeStateMachineEditor::_state_machine_draw() { Ref<StyleBox> style_selected = get_theme_stylebox("state_machine_selectedframe", "GraphNode"); Ref<Font> font = get_theme_font("title_font", "GraphNode"); + int font_size = get_theme_font_size("title_font_size", "GraphNode"); Color font_color = get_theme_color("title_color", "GraphNode"); Ref<Texture2D> play = get_theme_icon("Play", "EditorIcons"); Ref<Texture2D> auto_play = get_theme_icon("AutoPlay", "EditorIcons"); @@ -606,9 +613,9 @@ void AnimationNodeStateMachineEditor::_state_machine_draw() { Ref<StyleBox> sb = E->get() == selected_node ? style_selected : style; Size2 s = sb->get_minimum_size(); - int strsize = font->get_string_size(name).width; + int strsize = font->get_string_size(name, font_size).width; s.width += strsize; - s.height += MAX(font->get_height(), play->get_height()); + s.height += MAX(font->get_height(font_size), play->get_height()); s.width += sep + play->get_width(); if (needs_editor) { s.width += sep + edit->get_width(); @@ -683,7 +690,7 @@ void AnimationNodeStateMachineEditor::_state_machine_draw() { tl.width = tr_bidi_offset; if (state_machine->has_transition(tl.to_node, tl.from_node)) { //offset if same exists - Vector2 offset = -(tl.from - tl.to).normalized().tangent() * tr_bidi_offset; + Vector2 offset = -(tl.from - tl.to).normalized().orthogonal() * tr_bidi_offset; tl.from += offset; tl.to += offset; } @@ -735,7 +742,7 @@ void AnimationNodeStateMachineEditor::_state_machine_draw() { Ref<AnimationNode> anode = state_machine->get_node(name); bool needs_editor = AnimationTreeEditor::get_singleton()->can_edit(anode); Ref<StyleBox> sb = name == selected_node ? style_selected : style; - int strsize = font->get_string_size(name).width; + int strsize = font->get_string_size(name, font_size).width; NodeRect &nr = node_rects.write[i]; @@ -753,12 +760,12 @@ void AnimationNodeStateMachineEditor::_state_machine_draw() { bool onstart = state_machine->get_start_node() == name; if (onstart) { - state_machine_draw->draw_string(font, offset + Vector2(0, -font->get_height() - 3 * EDSCALE + font->get_ascent()), TTR("Start"), font_color); + state_machine_draw->draw_string(font, offset + Vector2(0, -font->get_height(font_size) - 3 * EDSCALE + font->get_ascent(font_size)), TTR("Start"), HALIGN_LEFT, -1, font_size, font_color); } if (state_machine->get_end_node() == name) { - int endofs = nr.node.size.x - font->get_string_size(TTR("End")).x; - state_machine_draw->draw_string(font, offset + Vector2(endofs, -font->get_height() - 3 * EDSCALE + font->get_ascent()), TTR("End"), font_color); + int endofs = nr.node.size.x - font->get_string_size(TTR("End"), font_size).x; + state_machine_draw->draw_string(font, offset + Vector2(endofs, -font->get_height(font_size) - 3 * EDSCALE + font->get_ascent(font_size)), TTR("End"), HALIGN_LEFT, -1, font_size, font_color); } offset.x += sb->get_offset().x; @@ -775,10 +782,10 @@ void AnimationNodeStateMachineEditor::_state_machine_draw() { } offset.x += sep + play->get_width(); - nr.name.position = offset + Vector2(0, (h - font->get_height()) / 2).floor(); - nr.name.size = Vector2(strsize, font->get_height()); + nr.name.position = offset + Vector2(0, (h - font->get_height(font_size)) / 2).floor(); + nr.name.size = Vector2(strsize, font->get_height(font_size)); - state_machine_draw->draw_string(font, nr.name.position + Vector2(0, font->get_ascent()), name, font_color); + state_machine_draw->draw_string(font, nr.name.position + Vector2(0, font->get_ascent(font_size)), name, HALIGN_LEFT, -1, font_size, font_color); offset.x += strsize + sep; if (needs_editor) { @@ -874,7 +881,7 @@ void AnimationNodeStateMachineEditor::_update_graph() { } void AnimationNodeStateMachineEditor::_notification(int p_what) { - if (p_what == NOTIFICATION_ENTER_TREE || p_what == NOTIFICATION_THEME_CHANGED) { + if (p_what == NOTIFICATION_ENTER_TREE || p_what == NOTIFICATION_THEME_CHANGED || p_what == NOTIFICATION_LAYOUT_DIRECTION_CHANGED || p_what == NOTIFICATION_TRANSLATION_CHANGED) { error_panel->add_theme_style_override("panel", get_theme_stylebox("bg", "Tree")); error_label->add_theme_color_override("font_color", get_theme_color("error_color", "Editor")); panel->add_theme_style_override("panel", get_theme_stylebox("bg", "Tree")); @@ -1208,7 +1215,8 @@ AnimationNodeStateMachineEditor::AnimationNodeStateMachineEditor() { Ref<ButtonGroup> bg; bg.instance(); - tool_select = memnew(ToolButton); + tool_select = memnew(Button); + tool_select->set_flat(true); top_hb->add_child(tool_select); tool_select->set_toggle_mode(true); tool_select->set_button_group(bg); @@ -1216,14 +1224,16 @@ AnimationNodeStateMachineEditor::AnimationNodeStateMachineEditor() { tool_select->set_tooltip(TTR("Select and move nodes.\nRMB to add new nodes.\nShift+LMB to create connections.")); tool_select->connect("pressed", callable_mp(this, &AnimationNodeStateMachineEditor::_update_mode), varray(), CONNECT_DEFERRED); - tool_create = memnew(ToolButton); + tool_create = memnew(Button); + tool_create->set_flat(true); top_hb->add_child(tool_create); tool_create->set_toggle_mode(true); tool_create->set_button_group(bg); tool_create->set_tooltip(TTR("Create new nodes.")); tool_create->connect("pressed", callable_mp(this, &AnimationNodeStateMachineEditor::_update_mode), varray(), CONNECT_DEFERRED); - tool_connect = memnew(ToolButton); + tool_connect = memnew(Button); + tool_connect->set_flat(true); top_hb->add_child(tool_connect); tool_connect->set_toggle_mode(true); tool_connect->set_button_group(bg); @@ -1233,7 +1243,8 @@ AnimationNodeStateMachineEditor::AnimationNodeStateMachineEditor() { tool_erase_hb = memnew(HBoxContainer); top_hb->add_child(tool_erase_hb); tool_erase_hb->add_child(memnew(VSeparator)); - tool_erase = memnew(ToolButton); + tool_erase = memnew(Button); + tool_erase->set_flat(true); tool_erase->set_tooltip(TTR("Remove selected node or transition.")); tool_erase_hb->add_child(tool_erase); tool_erase->connect("pressed", callable_mp(this, &AnimationNodeStateMachineEditor::_erase_selected)); @@ -1241,13 +1252,15 @@ AnimationNodeStateMachineEditor::AnimationNodeStateMachineEditor() { tool_erase_hb->add_child(memnew(VSeparator)); - tool_autoplay = memnew(ToolButton); + tool_autoplay = memnew(Button); + tool_autoplay->set_flat(true); tool_autoplay->set_tooltip(TTR("Toggle autoplay this animation on start, restart or seek to zero.")); tool_erase_hb->add_child(tool_autoplay); tool_autoplay->connect("pressed", callable_mp(this, &AnimationNodeStateMachineEditor::_autoplay_selected)); tool_autoplay->set_disabled(true); - tool_end = memnew(ToolButton); + tool_end = memnew(Button); + tool_end->set_flat(true); tool_end->set_tooltip(TTR("Set the end animation. This is useful for sub-transitions.")); tool_erase_hb->add_child(tool_end); tool_end->connect("pressed", callable_mp(this, &AnimationNodeStateMachineEditor::_end_selected)); @@ -1278,18 +1291,18 @@ AnimationNodeStateMachineEditor::AnimationNodeStateMachineEditor() { state_machine_play_pos = memnew(Control); state_machine_draw->add_child(state_machine_play_pos); state_machine_play_pos->set_mouse_filter(MOUSE_FILTER_PASS); //pass all to parent - state_machine_play_pos->set_anchors_and_margins_preset(PRESET_WIDE); + state_machine_play_pos->set_anchors_and_offsets_preset(PRESET_WIDE); state_machine_play_pos->connect("draw", callable_mp(this, &AnimationNodeStateMachineEditor::_state_machine_pos_draw)); v_scroll = memnew(VScrollBar); state_machine_draw->add_child(v_scroll); - v_scroll->set_anchors_and_margins_preset(PRESET_RIGHT_WIDE); + v_scroll->set_anchors_and_offsets_preset(PRESET_RIGHT_WIDE); v_scroll->connect("value_changed", callable_mp(this, &AnimationNodeStateMachineEditor::_scroll_changed)); h_scroll = memnew(HScrollBar); state_machine_draw->add_child(h_scroll); - h_scroll->set_anchors_and_margins_preset(PRESET_BOTTOM_WIDE); - h_scroll->set_margin(MARGIN_RIGHT, -v_scroll->get_size().x * EDSCALE); + h_scroll->set_anchors_and_offsets_preset(PRESET_BOTTOM_WIDE); + h_scroll->set_offset(SIDE_RIGHT, -v_scroll->get_size().x * EDSCALE); h_scroll->connect("value_changed", callable_mp(this, &AnimationNodeStateMachineEditor::_scroll_changed)); error_panel = memnew(PanelContainer); @@ -1315,7 +1328,7 @@ AnimationNodeStateMachineEditor::AnimationNodeStateMachineEditor() { add_child(name_edit_popup); name_edit = memnew(LineEdit); name_edit_popup->add_child(name_edit); - name_edit->set_anchors_and_margins_preset(PRESET_WIDE); + name_edit->set_anchors_and_offsets_preset(PRESET_WIDE); name_edit->connect("text_entered", callable_mp(this, &AnimationNodeStateMachineEditor::_name_edited)); name_edit->connect("focus_exited", callable_mp(this, &AnimationNodeStateMachineEditor::_name_edited_focus_out)); diff --git a/editor/plugins/animation_state_machine_editor.h b/editor/plugins/animation_state_machine_editor.h index 022c32ef48..a969ddd26b 100644 --- a/editor/plugins/animation_state_machine_editor.h +++ b/editor/plugins/animation_state_machine_editor.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -46,16 +46,16 @@ class AnimationNodeStateMachineEditor : public AnimationTreeNodeEditorPlugin { Ref<AnimationNodeStateMachine> state_machine; - ToolButton *tool_select; - ToolButton *tool_create; - ToolButton *tool_connect; + Button *tool_select; + Button *tool_create; + Button *tool_connect; Popup *name_edit_popup; LineEdit *name_edit; HBoxContainer *tool_erase_hb; - ToolButton *tool_erase; - ToolButton *tool_autoplay; - ToolButton *tool_end; + Button *tool_erase; + Button *tool_autoplay; + Button *tool_end; OptionButton *transition_mode; OptionButton *play_mode; @@ -126,10 +126,10 @@ class AnimationNodeStateMachineEditor : public AnimationTreeNodeEditorPlugin { Vector2 to; AnimationNodeStateMachineTransition::SwitchMode mode; StringName advance_condition_name; - bool advance_condition_state; - bool disabled; - bool auto_advance; - float width; + bool advance_condition_state = false; + bool disabled = false; + bool auto_advance = false; + float width = 0; }; Vector<TransitionLine> transition_lines; @@ -182,8 +182,8 @@ protected: public: static AnimationNodeStateMachineEditor *get_singleton() { return singleton; } - virtual bool can_edit(const Ref<AnimationNode> &p_node); - virtual void edit(const Ref<AnimationNode> &p_node); + virtual bool can_edit(const Ref<AnimationNode> &p_node) override; + virtual void edit(const Ref<AnimationNode> &p_node) override; AnimationNodeStateMachineEditor(); }; diff --git a/editor/plugins/animation_tree_editor_plugin.cpp b/editor/plugins/animation_tree_editor_plugin.cpp index ec3e25f999..c33b06ff32 100644 --- a/editor/plugins/animation_tree_editor_plugin.cpp +++ b/editor/plugins/animation_tree_editor_plugin.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -34,11 +34,11 @@ #include "animation_blend_space_2d_editor.h" #include "animation_blend_tree_editor_plugin.h" #include "animation_state_machine_editor.h" +#include "core/config/project_settings.h" #include "core/input/input.h" #include "core/io/resource_loader.h" #include "core/math/delaunay_2d.h" #include "core/os/keyboard.h" -#include "core/project_settings.h" #include "editor/editor_scale.h" #include "scene/animation/animation_blend_tree.h" #include "scene/animation/animation_player.h" @@ -79,7 +79,7 @@ void AnimationTreeEditor::_update_path() { group.instance(); Button *b = memnew(Button); - b->set_text("root"); + b->set_text("Root"); b->set_toggle_mode(true); b->set_button_group(group); b->set_pressed(true); @@ -142,9 +142,6 @@ void AnimationTreeEditor::enter_editor(const String &p_path) { edit_path(path); } -void AnimationTreeEditor::_about_to_show_root() { -} - void AnimationTreeEditor::_notification(int p_what) { if (p_what == NOTIFICATION_PROCESS) { ObjectID root; @@ -238,7 +235,7 @@ AnimationTreeEditor::AnimationTreeEditor() { add_child(memnew(HSeparator)); singleton = this; - editor_base = memnew(PanelContainer); + editor_base = memnew(MarginContainer); editor_base->set_v_size_flags(SIZE_EXPAND_FILL); add_child(editor_base); diff --git a/editor/plugins/animation_tree_editor_plugin.h b/editor/plugins/animation_tree_editor_plugin.h index 25af81ea9b..de3d89ae17 100644 --- a/editor/plugins/animation_tree_editor_plugin.h +++ b/editor/plugins/animation_tree_editor_plugin.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -55,14 +55,13 @@ class AnimationTreeEditor : public VBoxContainer { HBoxContainer *path_hb; AnimationTree *tree; - PanelContainer *editor_base; + MarginContainer *editor_base; Vector<String> button_path; Vector<String> edited_path; Vector<AnimationTreeNodeEditorPlugin *> editors; void _update_path(); - void _about_to_show_root(); ObjectID current_root; void _path_button_pressed(int p_path); @@ -101,11 +100,11 @@ class AnimationTreeEditorPlugin : public EditorPlugin { Button *button; public: - virtual String get_name() const { return "AnimationTree"; } - bool has_main_screen() const { return false; } - virtual void edit(Object *p_object); - virtual bool handles(Object *p_object) const; - virtual void make_visible(bool p_visible); + virtual String get_name() const override { return "AnimationTree"; } + bool has_main_screen() const override { return false; } + virtual void edit(Object *p_object) override; + virtual bool handles(Object *p_object) const override; + virtual void make_visible(bool p_visible) override; AnimationTreeEditorPlugin(EditorNode *p_node); ~AnimationTreeEditorPlugin(); diff --git a/editor/plugins/asset_library_editor_plugin.cpp b/editor/plugins/asset_library_editor_plugin.cpp index da170cd498..4d9c5625a3 100644 --- a/editor/plugins/asset_library_editor_plugin.cpp +++ b/editor/plugins/asset_library_editor_plugin.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -87,10 +87,10 @@ void EditorAssetLibraryItem::_bind_methods() { EditorAssetLibraryItem::EditorAssetLibraryItem() { Ref<StyleBoxEmpty> border; border.instance(); - border->set_default_margin(MARGIN_LEFT, 5 * EDSCALE); - border->set_default_margin(MARGIN_RIGHT, 5 * EDSCALE); - border->set_default_margin(MARGIN_BOTTOM, 5 * EDSCALE); - border->set_default_margin(MARGIN_TOP, 5 * EDSCALE); + border->set_default_margin(SIDE_LEFT, 5 * EDSCALE); + border->set_default_margin(SIDE_RIGHT, 5 * EDSCALE); + border->set_default_margin(SIDE_BOTTOM, 5 * EDSCALE); + border->set_default_margin(SIDE_TOP, 5 * EDSCALE); add_theme_style_override("panel", border); HBoxContainer *hb = memnew(HBoxContainer); @@ -295,8 +295,8 @@ EditorAssetLibraryItemDescription::EditorAssetLibraryItemDescription() { preview_hb->set_v_size_flags(Control::SIZE_EXPAND_FILL); previews->add_child(preview_hb); - get_ok()->set_text(TTR("Download")); - get_cancel()->set_text(TTR("Close")); + get_ok_button()->set_text(TTR("Download")); + get_cancel_button()->set_text(TTR("Close")); } /////////////////////////////////////////////////////////////////////////////////// @@ -350,7 +350,7 @@ void EditorAssetLibraryItemDownload::_http_download_completed(int p_status, int if (sha256 != download_sha256) { error_text = TTR("Bad download hash, assuming file has been tampered with.") + "\n"; error_text += TTR("Expected:") + " " + sha256 + "\n" + TTR("Got:") + " " + download_sha256; - status->set_text(TTR("Failed sha256 hash check")); + status->set_text(TTR("Failed SHA-256 hash check")); } } } break; @@ -359,6 +359,8 @@ void EditorAssetLibraryItemDownload::_http_download_completed(int p_status, int if (error_text != String()) { download_error->set_text(TTR("Asset Download Error:") + "\n" + error_text); download_error->popup_centered(); + // Let the user retry the download. + retry->show(); return; } @@ -459,6 +461,9 @@ void EditorAssetLibraryItemDownload::_install() { } void EditorAssetLibraryItemDownload::_make_request() { + // Hide the Retry button if we've just pressed it. + retry->hide(); + download->cancel_request(); download->set_download_file(EditorSettings::get_singleton()->get_cache_dir().plus_file("tmp_asset_" + itos(asset_id)) + ".zip"); @@ -516,6 +521,8 @@ EditorAssetLibraryItemDownload::EditorAssetLibraryItemDownload() { retry = memnew(Button); retry->set_text(TTR("Retry")); retry->connect("pressed", callable_mp(this, &EditorAssetLibraryItemDownload::_make_request)); + // Only show the Retry button in case of a failure. + retry->hide(); hb2->add_child(retry); hb2->add_child(install); @@ -580,7 +587,7 @@ void EditorAssetLibrary::_notification(int p_what) { } } -void EditorAssetLibrary::_unhandled_input(const Ref<InputEvent> &p_event) { +void EditorAssetLibrary::_unhandled_key_input(const Ref<InputEvent> &p_event) { const Ref<InputEventKey> key = p_event; if (key.is_valid() && key->is_pressed()) { @@ -702,7 +709,7 @@ void EditorAssetLibrary::_image_update(bool use_cache, bool final, const PackedB } } - if (!image->empty()) { + if (!image->is_empty()) { switch (image_queue[p_queue_id].image_type) { case IMAGE_QUEUE_ICON: @@ -900,7 +907,7 @@ void EditorAssetLibrary::_search(int p_page) { } if (filter->get_text() != String()) { - args += "&filter=" + filter->get_text().http_escape(); + args += "&filter=" + filter->get_text().uri_encode(); } if (p_page > 0) { @@ -910,7 +917,11 @@ void EditorAssetLibrary::_search(int p_page) { _api_request("asset", REQUESTING_SEARCH, args); } -void EditorAssetLibrary::_search_text_entered(const String &p_text) { +void EditorAssetLibrary::_search_text_changed(const String &p_text) { + filter_debounce_timer->start(); +} + +void EditorAssetLibrary::_filter_debounce_timer_timeout() { _search(); } @@ -1147,7 +1158,7 @@ void EditorAssetLibrary::_http_request_completed(int p_status, int p_code, const asset_bottom_page = _make_pages(page, pages, page_len, total_items, result.size()); library_vb->add_child(asset_bottom_page); - if (result.empty()) { + if (result.is_empty()) { if (filter->get_text() != String()) { library_error->set_text( vformat(TTR("No results for \"%s\"."), filter->get_text())); @@ -1183,6 +1194,10 @@ void EditorAssetLibrary::_http_request_completed(int p_status, int p_code, const _request_image(item->get_instance_id(), r["icon_url"], IMAGE_QUEUE_ICON, 0); } } + + if (!result.is_empty()) { + library_scroll->set_v_scroll(0); + } } break; case REQUESTING_ASSET: { Dictionary r = d; @@ -1260,7 +1275,7 @@ void EditorAssetLibrary::_asset_file_selected(const String &p_file) { } void EditorAssetLibrary::_asset_open() { - asset_open->popup_centered_ratio(); + asset_open->popup_file_dialog(); } void EditorAssetLibrary::_manage_plugins() { @@ -1277,7 +1292,7 @@ void EditorAssetLibrary::disable_community_support() { } void EditorAssetLibrary::_bind_methods() { - ClassDB::bind_method("_unhandled_input", &EditorAssetLibrary::_unhandled_input); + ClassDB::bind_method("_unhandled_key_input", &EditorAssetLibrary::_unhandled_key_input); ADD_SIGNAL(MethodInfo("install_asset", PropertyInfo(Variant::STRING, "zip_path"), PropertyInfo(Variant::STRING, "name"))); } @@ -1299,10 +1314,15 @@ EditorAssetLibrary::EditorAssetLibrary(bool p_templates_only) { filter = memnew(LineEdit); search_hb->add_child(filter); filter->set_h_size_flags(Control::SIZE_EXPAND_FILL); - filter->connect("text_entered", callable_mp(this, &EditorAssetLibrary::_search_text_entered)); - search = memnew(Button(TTR("Search"))); - search->connect("pressed", callable_mp(this, &EditorAssetLibrary::_search), make_binds(0)); - search_hb->add_child(search); + filter->connect("text_changed", callable_mp(this, &EditorAssetLibrary::_search_text_changed)); + + // Perform a search automatically if the user hasn't entered any text for a certain duration. + // This way, the user doesn't need to press Enter to initiate their search. + filter_debounce_timer = memnew(Timer); + filter_debounce_timer->set_one_shot(true); + filter_debounce_timer->set_wait_time(0.25); + filter_debounce_timer->connect("timeout", callable_mp(this, &EditorAssetLibrary::_filter_debounce_timer_timeout)); + search_hb->add_child(filter_debounce_timer); if (!p_templates_only) { search_hb->add_child(memnew(VSeparator)); @@ -1351,10 +1371,18 @@ EditorAssetLibrary::EditorAssetLibrary(bool p_templates_only) { search_hb2->add_child(memnew(Label(TTR("Site:") + " "))); repository = memnew(OptionButton); - repository->add_item("godotengine.org"); - repository->set_item_metadata(0, "https://godotengine.org/asset-library/api"); - repository->add_item("localhost"); - repository->set_item_metadata(1, "http://127.0.0.1/asset-library/api"); + { + Dictionary default_urls; + default_urls["godotengine.org"] = "https://godotengine.org/asset-library/api"; + default_urls["localhost"] = "http://127.0.0.1/asset-library/api"; + Dictionary available_urls = _EDITOR_DEF("asset_library/available_urls", default_urls, true); + Array keys = available_urls.keys(); + for (int i = 0; i < available_urls.size(); i++) { + String key = keys[i]; + repository->add_item(key); + repository->set_item_metadata(i, available_urls[key]); + } + } repository->connect("item_selected", callable_mp(this, &EditorAssetLibrary::_repository_changed)); @@ -1387,10 +1415,10 @@ EditorAssetLibrary::EditorAssetLibrary(bool p_templates_only) { Ref<StyleBoxEmpty> border2; border2.instance(); - border2->set_default_margin(MARGIN_LEFT, 15 * EDSCALE); - border2->set_default_margin(MARGIN_RIGHT, 35 * EDSCALE); - border2->set_default_margin(MARGIN_BOTTOM, 15 * EDSCALE); - border2->set_default_margin(MARGIN_TOP, 15 * EDSCALE); + border2->set_default_margin(SIDE_LEFT, 15 * EDSCALE); + border2->set_default_margin(SIDE_RIGHT, 35 * EDSCALE); + border2->set_default_margin(SIDE_BOTTOM, 15 * EDSCALE); + border2->set_default_margin(SIDE_TOP, 15 * EDSCALE); PanelContainer *library_vb_border = memnew(PanelContainer); library_scroll->add_child(library_vb_border); @@ -1445,7 +1473,7 @@ EditorAssetLibrary::EditorAssetLibrary(bool p_templates_only) { description = nullptr; set_process(true); - set_process_unhandled_input(true); + set_process_unhandled_key_input(true); // Global shortcuts since there is no main element to be focused. downloads_scroll = memnew(ScrollContainer); downloads_scroll->set_enable_h_scroll(true); @@ -1479,8 +1507,8 @@ AssetLibraryEditorPlugin::AssetLibraryEditorPlugin(EditorNode *p_node) { editor = p_node; addon_library = memnew(EditorAssetLibrary); addon_library->set_v_size_flags(Control::SIZE_EXPAND_FILL); - editor->get_viewport()->add_child(addon_library); - addon_library->set_anchors_and_margins_preset(Control::PRESET_WIDE); + editor->get_main_control()->add_child(addon_library); + addon_library->set_anchors_and_offsets_preset(Control::PRESET_WIDE); addon_library->hide(); } diff --git a/editor/plugins/asset_library_editor_plugin.h b/editor/plugins/asset_library_editor_plugin.h index d5d381dee3..0509145673 100644 --- a/editor/plugins/asset_library_editor_plugin.h +++ b/editor/plugins/asset_library_editor_plugin.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -89,10 +89,10 @@ class EditorAssetLibraryItemDescription : public ConfirmationDialog { PanelContainer *previews_bg; struct Preview { - int id; - bool is_video; + int id = 0; + bool is_video = false; String video_link; - Button *button; + Button *button = nullptr; Ref<Texture2D> image; }; @@ -183,10 +183,10 @@ class EditorAssetLibrary : public PanelContainer { Label *library_loading; Label *library_error; LineEdit *filter; + Timer *filter_debounce_timer; OptionButton *categories; OptionButton *repository; OptionButton *sort; - Button *search; HBoxContainer *error_hb; TextureRect *error_tr; Label *error_label; @@ -234,12 +234,12 @@ class EditorAssetLibrary : public PanelContainer { }; struct ImageQueue { - bool active; - int queue_id; - ImageType image_type; - int image_index; + bool active = false; + int queue_id = 0; + ImageType image_type = ImageType::IMAGE_QUEUE_ICON; + int image_index = 0; String image_url; - HTTPRequest *request; + HTTPRequest *request = nullptr; ObjectID target; }; @@ -280,10 +280,12 @@ class EditorAssetLibrary : public PanelContainer { void _search(int p_page = 0); void _rerun_search(int p_ignore); + void _search_text_changed(const String &p_text = ""); void _search_text_entered(const String &p_text = ""); void _api_request(const String &p_request, RequestType p_request_type, const String &p_arguments = ""); void _http_request_completed(int p_status, int p_code, const PackedStringArray &headers, const PackedByteArray &p_data); void _http_download_completed(int p_status, int p_code, const PackedStringArray &headers, const PackedByteArray &p_data); + void _filter_debounce_timer_timeout(); void _repository_changed(int p_repository_id); void _support_toggled(int p_support); @@ -296,7 +298,7 @@ class EditorAssetLibrary : public PanelContainer { protected: static void _bind_methods(); void _notification(int p_what); - void _unhandled_input(const Ref<InputEvent> &p_event); + void _unhandled_key_input(const Ref<InputEvent> &p_event); public: void disable_community_support(); @@ -311,11 +313,11 @@ class AssetLibraryEditorPlugin : public EditorPlugin { EditorNode *editor; public: - virtual String get_name() const { return "AssetLib"; } - bool has_main_screen() const { return true; } - virtual void edit(Object *p_object) {} - virtual bool handles(Object *p_object) const { return false; } - virtual void make_visible(bool p_visible); + virtual String get_name() const override { return "AssetLib"; } + bool has_main_screen() const override { return true; } + virtual void edit(Object *p_object) override {} + virtual bool handles(Object *p_object) const override { return false; } + virtual void make_visible(bool p_visible) override; //virtual bool get_remove_list(List<Node*> *p_list) { return canvas_item_editor->get_remove_list(p_list); } //virtual Dictionary get_state() const; //virtual void set_state(const Dictionary& p_state); diff --git a/editor/plugins/audio_stream_editor_plugin.cpp b/editor/plugins/audio_stream_editor_plugin.cpp index 3b7a9320f0..5963092860 100644 --- a/editor/plugins/audio_stream_editor_plugin.cpp +++ b/editor/plugins/audio_stream_editor_plugin.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -30,8 +30,8 @@ #include "audio_stream_editor_plugin.h" +#include "core/config/project_settings.h" #include "core/io/resource_loader.h" -#include "core/project_settings.h" #include "editor/audio_stream_preview.h" #include "editor/editor_scale.h" #include "editor/editor_settings.h" @@ -44,8 +44,8 @@ void AudioStreamEditor::_notification(int p_what) { if (p_what == NOTIFICATION_THEME_CHANGED || p_what == NOTIFICATION_ENTER_TREE) { _play_button->set_icon(get_theme_icon("MainPlay", "EditorIcons")); _stop_button->set_icon(get_theme_icon("Stop", "EditorIcons")); - _preview->set_frame_color(get_theme_color("dark_color_2", "Editor")); - set_frame_color(get_theme_color("dark_color_1", "Editor")); + _preview->set_color(get_theme_color("dark_color_2", "Editor")); + set_color(get_theme_color("dark_color_1", "Editor")); _indicator->update(); _preview->update(); @@ -96,7 +96,7 @@ void AudioStreamEditor::_preview_changed(ObjectID p_which) { } } -void AudioStreamEditor::_changed_callback(Object *p_changed, const char *p_prop) { +void AudioStreamEditor::_audio_changed() { if (!is_visible()) { return; } @@ -172,7 +172,7 @@ void AudioStreamEditor::_seek_to(real_t p_x) { void AudioStreamEditor::edit(Ref<AudioStream> p_stream) { if (!stream.is_null()) { - stream->remove_change_receptor(this); + stream->disconnect("changed", callable_mp(this, &AudioStreamEditor::_audio_changed)); } stream = p_stream; @@ -182,7 +182,7 @@ void AudioStreamEditor::edit(Ref<AudioStream> p_stream) { _duration_label->set_text(text); if (!stream.is_null()) { - stream->add_change_receptor(this); + stream->connect("changed", callable_mp(this, &AudioStreamEditor::_audio_changed)); update(); } else { hide(); @@ -202,7 +202,7 @@ AudioStreamEditor::AudioStreamEditor() { add_child(_player); VBoxContainer *vbox = memnew(VBoxContainer); - vbox->set_anchors_and_margins_preset(PRESET_WIDE, PRESET_MODE_MINSIZE, 0); + vbox->set_anchors_and_offsets_preset(PRESET_WIDE, PRESET_MODE_MINSIZE, 0); add_child(vbox); _preview = memnew(ColorRect); @@ -211,7 +211,7 @@ AudioStreamEditor::AudioStreamEditor() { vbox->add_child(_preview); _indicator = memnew(Control); - _indicator->set_anchors_and_margins_preset(PRESET_WIDE); + _indicator->set_anchors_and_offsets_preset(PRESET_WIDE); _indicator->connect("draw", callable_mp(this, &AudioStreamEditor::_draw_indicator)); _indicator->connect("gui_input", callable_mp(this, &AudioStreamEditor::_on_input_indicator)); _preview->add_child(_indicator); @@ -220,12 +220,14 @@ AudioStreamEditor::AudioStreamEditor() { hbox->add_theme_constant_override("separation", 0); vbox->add_child(hbox); - _play_button = memnew(ToolButton); + _play_button = memnew(Button); + _play_button->set_flat(true); hbox->add_child(_play_button); _play_button->set_focus_mode(Control::FOCUS_NONE); _play_button->connect("pressed", callable_mp(this, &AudioStreamEditor::_play)); - _stop_button = memnew(ToolButton); + _stop_button = memnew(Button); + _stop_button->set_flat(true); hbox->add_child(_stop_button); _stop_button->set_focus_mode(Control::FOCUS_NONE); _stop_button->connect("pressed", callable_mp(this, &AudioStreamEditor::_stop)); @@ -234,11 +236,13 @@ AudioStreamEditor::AudioStreamEditor() { _current_label->set_align(Label::ALIGN_RIGHT); _current_label->set_h_size_flags(SIZE_EXPAND_FILL); _current_label->add_theme_font_override("font", EditorNode::get_singleton()->get_gui_base()->get_theme_font("status_source", "EditorFonts")); + _current_label->add_theme_font_size_override("font_size", EditorNode::get_singleton()->get_gui_base()->get_theme_font_size("status_source_size", "EditorFonts")); _current_label->set_modulate(Color(1, 1, 1, 0.5)); hbox->add_child(_current_label); _duration_label = memnew(Label); _duration_label->add_theme_font_override("font", EditorNode::get_singleton()->get_gui_base()->get_theme_font("status_source", "EditorFonts")); + _duration_label->add_theme_font_size_override("font_size", EditorNode::get_singleton()->get_gui_base()->get_theme_font_size("status_source_size", "EditorFonts")); hbox->add_child(_duration_label); } diff --git a/editor/plugins/audio_stream_editor_plugin.h b/editor/plugins/audio_stream_editor_plugin.h index dd7caaa15e..aa906a6a05 100644 --- a/editor/plugins/audio_stream_editor_plugin.h +++ b/editor/plugins/audio_stream_editor_plugin.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -47,12 +47,14 @@ class AudioStreamEditor : public ColorRect { Label *_current_label; Label *_duration_label; - ToolButton *_play_button; - ToolButton *_stop_button; + Button *_play_button; + Button *_stop_button; float _current; bool _dragging; + void _audio_changed(); + protected: void _notification(int p_what); void _preview_changed(ObjectID p_which); @@ -63,7 +65,6 @@ protected: void _draw_indicator(); void _on_input_indicator(Ref<InputEvent> p_event); void _seek_to(real_t p_x); - void _changed_callback(Object *p_changed, const char *p_prop); static void _bind_methods(); public: @@ -78,11 +79,11 @@ class AudioStreamEditorPlugin : public EditorPlugin { EditorNode *editor; public: - virtual String get_name() const { return "Audio"; } - bool has_main_screen() const { return false; } - virtual void edit(Object *p_object); - virtual bool handles(Object *p_object) const; - virtual void make_visible(bool p_visible); + virtual String get_name() const override { return "Audio"; } + bool has_main_screen() const override { return false; } + virtual void edit(Object *p_object) override; + virtual bool handles(Object *p_object) const override; + virtual void make_visible(bool p_visible) override; AudioStreamEditorPlugin(EditorNode *p_node); ~AudioStreamEditorPlugin(); diff --git a/editor/plugins/baked_lightmap_editor_plugin.cpp b/editor/plugins/baked_lightmap_editor_plugin.cpp index 8fbe1646f7..470b61bf40 100644 --- a/editor/plugins/baked_lightmap_editor_plugin.cpp +++ b/editor/plugins/baked_lightmap_editor_plugin.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -54,7 +54,7 @@ void BakedLightmapEditorPlugin::_bake_select_file(const String &p_file) { scene_path = scene_path.get_basename() + ".lmbake"; file_dialog->set_current_path(scene_path); - file_dialog->popup_centered_ratio(); + file_dialog->popup_file_dialog(); } break; case BakedLightmap::BAKE_ERROR_NO_MESHES: @@ -117,7 +117,8 @@ void BakedLightmapEditorPlugin::_bind_methods() { BakedLightmapEditorPlugin::BakedLightmapEditorPlugin(EditorNode *p_node) { editor = p_node; - bake = memnew(ToolButton); + bake = memnew(Button); + bake->set_flat(true); bake->set_icon(editor->get_gui_base()->get_theme_icon("Bake", "EditorIcons")); bake->set_text(TTR("Bake Lightmaps")); bake->hide(); diff --git a/editor/plugins/baked_lightmap_editor_plugin.h b/editor/plugins/baked_lightmap_editor_plugin.h index 67fb368a86..d291c377d9 100644 --- a/editor/plugins/baked_lightmap_editor_plugin.h +++ b/editor/plugins/baked_lightmap_editor_plugin.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -41,7 +41,7 @@ class BakedLightmapEditorPlugin : public EditorPlugin { BakedLightmap *lightmap; - ToolButton *bake; + Button *bake; EditorNode *editor; EditorFileDialog *file_dialog; @@ -56,11 +56,11 @@ protected: static void _bind_methods(); public: - virtual String get_name() const { return "BakedLightmap"; } - bool has_main_screen() const { return false; } - virtual void edit(Object *p_object); - virtual bool handles(Object *p_object) const; - virtual void make_visible(bool p_visible); + virtual String get_name() const override { return "BakedLightmap"; } + bool has_main_screen() const override { return false; } + virtual void edit(Object *p_object) override; + virtual bool handles(Object *p_object) const override; + virtual void make_visible(bool p_visible) override; BakedLightmapEditorPlugin(EditorNode *p_node); ~BakedLightmapEditorPlugin(); diff --git a/editor/plugins/camera_3d_editor_plugin.cpp b/editor/plugins/camera_3d_editor_plugin.cpp index 48f9f208a5..8583e95b25 100644 --- a/editor/plugins/camera_3d_editor_plugin.cpp +++ b/editor/plugins/camera_3d_editor_plugin.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -69,12 +69,12 @@ Camera3DEditor::Camera3DEditor() { preview->set_text(TTR("Preview")); preview->set_toggle_mode(true); - preview->set_anchor(MARGIN_LEFT, Control::ANCHOR_END); - preview->set_anchor(MARGIN_RIGHT, Control::ANCHOR_END); - preview->set_margin(MARGIN_LEFT, -60); - preview->set_margin(MARGIN_RIGHT, 0); - preview->set_margin(MARGIN_TOP, 0); - preview->set_margin(MARGIN_BOTTOM, 10); + preview->set_anchor(SIDE_LEFT, Control::ANCHOR_END); + preview->set_anchor(SIDE_RIGHT, Control::ANCHOR_END); + preview->set_offset(SIDE_LEFT, -60); + preview->set_offset(SIDE_RIGHT, 0); + preview->set_offset(SIDE_TOP, 0); + preview->set_offset(SIDE_BOTTOM, 10); preview->connect("pressed", callable_mp(this, &Camera3DEditor::_pressed)); } @@ -98,14 +98,14 @@ void Camera3DEditorPlugin::make_visible(bool p_visible) { Camera3DEditorPlugin::Camera3DEditorPlugin(EditorNode *p_node) { editor = p_node; /* camera_editor = memnew( CameraEditor ); - editor->get_viewport()->add_child(camera_editor); - - camera_editor->set_anchor(MARGIN_LEFT,Control::ANCHOR_END); - camera_editor->set_anchor(MARGIN_RIGHT,Control::ANCHOR_END); - camera_editor->set_margin(MARGIN_LEFT,60); - camera_editor->set_margin(MARGIN_RIGHT,0); - camera_editor->set_margin(MARGIN_TOP,0); - camera_editor->set_margin(MARGIN_BOTTOM,10); + editor->get_main_control()->add_child(camera_editor); + + camera_editor->set_anchor(SIDE_LEFT,Control::ANCHOR_END); + camera_editor->set_anchor(SIDE_RIGHT,Control::ANCHOR_END); + camera_editor->set_offset(SIDE_LEFT,60); + camera_editor->set_offset(SIDE_RIGHT,0); + camera_editor->set_offset(SIDE_TOP,0); + camera_editor->set_offset(SIDE_BOTTOM,10); camera_editor->hide(); diff --git a/editor/plugins/camera_3d_editor_plugin.h b/editor/plugins/camera_3d_editor_plugin.h index 2603229a46..e087dd22a8 100644 --- a/editor/plugins/camera_3d_editor_plugin.h +++ b/editor/plugins/camera_3d_editor_plugin.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -60,11 +60,11 @@ class Camera3DEditorPlugin : public EditorPlugin { EditorNode *editor; public: - virtual String get_name() const { return "Camera3D"; } - bool has_main_screen() const { return false; } - virtual void edit(Object *p_object); - virtual bool handles(Object *p_object) const; - virtual void make_visible(bool p_visible); + virtual String get_name() const override { return "Camera3D"; } + bool has_main_screen() const override { return false; } + virtual void edit(Object *p_object) override; + virtual bool handles(Object *p_object) const override; + virtual void make_visible(bool p_visible) override; Camera3DEditorPlugin(EditorNode *p_node); ~Camera3DEditorPlugin(); diff --git a/editor/plugins/canvas_item_editor_plugin.cpp b/editor/plugins/canvas_item_editor_plugin.cpp index 744c7907af..6fa3c923eb 100644 --- a/editor/plugins/canvas_item_editor_plugin.cpp +++ b/editor/plugins/canvas_item_editor_plugin.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -30,10 +30,11 @@ #include "canvas_item_editor_plugin.h" +#include "core/config/project_settings.h" #include "core/input/input.h" +#include "core/math/geometry_2d.h" #include "core/os/keyboard.h" -#include "core/print_string.h" -#include "core/project_settings.h" +#include "core/string/print_string.h" #include "editor/debugger/editor_debugger_node.h" #include "editor/editor_node.h" #include "editor/editor_scale.h" @@ -53,8 +54,10 @@ #include "scene/main/window.h" #include "scene/resources/packed_scene.h" -#define MIN_ZOOM 0.01 -#define MAX_ZOOM 100 +// Min and Max are power of two in order to play nicely with successive increment. +// That way, we can naturally reach a 100% zoom from boundaries. +#define MIN_ZOOM 1. / 128 +#define MAX_ZOOM 128 #define RULER_WIDTH (15 * EDSCALE) #define SCALE_HANDLE_DISTANCE 25 @@ -86,7 +89,6 @@ public: GridContainer *child_container; set_title(TTR("Configure Snap")); - get_ok()->set_text(TTR("Close")); container = memnew(VBoxContainer); add_child(container); @@ -214,8 +216,8 @@ public: grid_step_x->set_value(p_grid_step.x); grid_step_y->set_value(p_grid_step.y); primary_grid_steps->set_value(p_primary_grid_steps); - rotation_offset->set_value(p_rotation_offset * (180 / Math_PI)); - rotation_step->set_value(p_rotation_step * (180 / Math_PI)); + rotation_offset->set_value(Math::rad2deg(p_rotation_offset)); + rotation_step->set_value(Math::rad2deg(p_rotation_step)); scale_step->set_value(p_scale_step); } @@ -223,8 +225,8 @@ public: p_grid_offset = Point2(grid_offset_x->get_value(), grid_offset_y->get_value()); p_grid_step = Point2(grid_step_x->get_value(), grid_step_y->get_value()); p_primary_grid_steps = int(primary_grid_steps->get_value()); - p_rotation_offset = rotation_offset->get_value() / (180 / Math_PI); - p_rotation_step = rotation_step->get_value() / (180 / Math_PI); + p_rotation_offset = Math::deg2rad(rotation_offset->get_value()); + p_rotation_step = Math::deg2rad(rotation_step->get_value()); p_scale_step = scale_step->get_value(); } }; @@ -364,8 +366,8 @@ Point2 CanvasItemEditor::snap_point(Point2 p_target, unsigned int p_modes, unsig // Self anchors if ((is_snap_active && snap_node_anchors && (p_modes & SNAP_NODE_ANCHORS)) || (p_forced_modes & SNAP_NODE_ANCHORS)) { if (const Control *c = Object::cast_to<Control>(p_self_canvas_item)) { - Point2 begin = p_self_canvas_item->get_global_transform_with_canvas().xform(_anchor_to_position(c, Point2(c->get_anchor(MARGIN_LEFT), c->get_anchor(MARGIN_TOP)))); - Point2 end = p_self_canvas_item->get_global_transform_with_canvas().xform(_anchor_to_position(c, Point2(c->get_anchor(MARGIN_RIGHT), c->get_anchor(MARGIN_BOTTOM)))); + Point2 begin = p_self_canvas_item->get_global_transform_with_canvas().xform(_anchor_to_position(c, Point2(c->get_anchor(SIDE_LEFT), c->get_anchor(SIDE_TOP)))); + Point2 end = p_self_canvas_item->get_global_transform_with_canvas().xform(_anchor_to_position(c, Point2(c->get_anchor(SIDE_RIGHT), c->get_anchor(SIDE_BOTTOM)))); _snap_if_closer_point(p_target, output, snap_target, begin, SNAP_TARGET_SELF_ANCHORS, rotation); _snap_if_closer_point(p_target, output, snap_target, end, SNAP_TARGET_SELF_ANCHORS, rotation); } @@ -442,8 +444,8 @@ Point2 CanvasItemEditor::snap_point(Point2 p_target, unsigned int p_modes, unsig } } Point2 grid_output; - grid_output.x = Math::stepify(p_target.x - offset.x, grid_step.x * Math::pow(2.0, grid_step_multiplier)) + offset.x; - grid_output.y = Math::stepify(p_target.y - offset.y, grid_step.y * Math::pow(2.0, grid_step_multiplier)) + offset.y; + grid_output.x = Math::snapped(p_target.x - offset.x, grid_step.x * Math::pow(2.0, grid_step_multiplier)) + offset.x; + grid_output.y = Math::snapped(p_target.y - offset.y, grid_step.y * Math::pow(2.0, grid_step_multiplier)) + offset.y; _snap_if_closer_point(p_target, output, snap_target, grid_output, SNAP_TARGET_GRID, 0.0, -1.0); } @@ -460,9 +462,9 @@ Point2 CanvasItemEditor::snap_point(Point2 p_target, unsigned int p_modes, unsig float CanvasItemEditor::snap_angle(float p_target, float p_start) const { if (((smart_snap_active || snap_rotation) ^ Input::get_singleton()->is_key_pressed(KEY_CONTROL)) && snap_rotation_step != 0) { if (snap_relative) { - return Math::stepify(p_target - snap_rotation_offset, snap_rotation_step) + snap_rotation_offset + (p_start - (int)(p_start / snap_rotation_step) * snap_rotation_step); + return Math::snapped(p_target - snap_rotation_offset, snap_rotation_step) + snap_rotation_offset + (p_start - (int)(p_start / snap_rotation_step) * snap_rotation_step); } else { - return Math::stepify(p_target - snap_rotation_offset, snap_rotation_step) + snap_rotation_offset; + return Math::snapped(p_target - snap_rotation_offset, snap_rotation_step) + snap_rotation_offset; } } else { return p_target; @@ -476,22 +478,24 @@ void CanvasItemEditor::_unhandled_key_input(const Ref<InputEvent> &p_ev) { return; } - if (k->get_keycode() == KEY_CONTROL || k->get_keycode() == KEY_ALT || k->get_keycode() == KEY_SHIFT) { - viewport->update(); - } - - if (k->is_pressed() && !k->get_control() && !k->is_echo()) { - if ((grid_snap_active || show_grid) && multiply_grid_step_shortcut.is_valid() && multiply_grid_step_shortcut->is_shortcut(p_ev)) { - // Multiply the grid size - grid_step_multiplier = MIN(grid_step_multiplier + 1, 12); + if (k.is_valid()) { + if (k->get_keycode() == KEY_CONTROL || k->get_keycode() == KEY_ALT || k->get_keycode() == KEY_SHIFT) { viewport->update(); - } else if ((grid_snap_active || show_grid) && divide_grid_step_shortcut.is_valid() && divide_grid_step_shortcut->is_shortcut(p_ev)) { - // Divide the grid size - Point2 new_grid_step = grid_step * Math::pow(2.0, grid_step_multiplier - 1); - if (new_grid_step.x >= 1.0 && new_grid_step.y >= 1.0) { - grid_step_multiplier--; + } + + if (k->is_pressed() && !k->get_control() && !k->is_echo()) { + if ((grid_snap_active || show_grid) && multiply_grid_step_shortcut.is_valid() && multiply_grid_step_shortcut->is_shortcut(p_ev)) { + // Multiply the grid size + grid_step_multiplier = MIN(grid_step_multiplier + 1, 12); + viewport->update(); + } else if ((grid_snap_active || show_grid) && divide_grid_step_shortcut.is_valid() && divide_grid_step_shortcut->is_shortcut(p_ev)) { + // Divide the grid size + Point2 new_grid_step = grid_step * Math::pow(2.0, grid_step_multiplier - 1); + if (new_grid_step.x >= 1.0 && new_grid_step.y >= 1.0) { + grid_step_multiplier--; + } + viewport->update(); } - viewport->update(); } } } @@ -514,7 +518,7 @@ void CanvasItemEditor::_keying_changed() { } Rect2 CanvasItemEditor::_get_encompassing_rect_from_list(List<CanvasItem *> p_list) { - ERR_FAIL_COND_V(p_list.empty(), Rect2()); + ERR_FAIL_COND_V(p_list.is_empty(), Rect2()); // Handles the first element CanvasItem *canvas_item = p_list.front()->get(); @@ -546,7 +550,7 @@ void CanvasItemEditor::_expand_encompassing_rect_using_children(Rect2 &r_rect, c const CanvasItem *canvas_item = Object::cast_to<CanvasItem>(p_node); for (int i = p_node->get_child_count() - 1; i >= 0; i--) { - if (canvas_item && !canvas_item->is_set_as_toplevel()) { + if (canvas_item && !canvas_item->is_set_as_top_level()) { _expand_encompassing_rect_using_children(r_rect, p_node->get_child(i), r_first, p_parent_xform * canvas_item->get_transform(), p_canvas_xform); } else { const CanvasLayer *canvas_layer = Object::cast_to<CanvasLayer>(p_node); @@ -589,7 +593,7 @@ void CanvasItemEditor::_find_canvas_items_at_pos(const Point2 &p_pos, Node *p_no for (int i = p_node->get_child_count() - 1; i >= 0; i--) { if (canvas_item) { - if (!canvas_item->is_set_as_toplevel()) { + if (!canvas_item->is_set_as_top_level()) { _find_canvas_items_at_pos(p_pos, p_node->get_child(i), r_items, p_parent_xform * canvas_item->get_transform(), p_canvas_xform); } else { _find_canvas_items_at_pos(p_pos, p_node->get_child(i), r_items, canvas_item->get_transform(), p_canvas_xform); @@ -625,9 +629,9 @@ void CanvasItemEditor::_get_canvas_items_at_pos(const Point2 &p_pos, Vector<_Sel Node *node = r_items[i].item; // Make sure the selected node is in the current scene, or editable - while (node && node != get_tree()->get_edited_scene_root() && node->get_owner() != scene && !scene->is_editable_instance(node->get_owner())) { - node = node->get_parent(); - }; + if (node && node != get_tree()->get_edited_scene_root()) { + node = scene->get_deepest_editable_node(node); + } CanvasItem *canvas_item = Object::cast_to<CanvasItem>(node); if (!p_allow_locked) { @@ -672,7 +676,7 @@ void CanvasItemEditor::_get_bones_at_pos(const Point2 &p_pos, Vector<_SelectResu } // Check if the point is inside the Polygon2D - if (Geometry::is_point_in_polygon(screen_pos, bone_shape)) { + if (Geometry2D::is_point_in_polygon(screen_pos, bone_shape)) { // Check if the item is already in the list bool duplicate = false; for (int i = 0; i < r_items.size(); i++) { @@ -723,7 +727,7 @@ bool CanvasItemEditor::_get_bone_shape(Vector<Vector2> *shape, Vector<Vector2> * } Vector2 rel = to - from; - Vector2 relt = rel.tangent().normalized() * bone_width; + Vector2 relt = rel.orthogonal().normalized() * bone_width; Vector2 reln = rel.normalized(); Vector2 reltn = relt.normalized(); @@ -758,14 +762,14 @@ void CanvasItemEditor::_find_canvas_items_in_rect(const Rect2 &p_rect, Node *p_n CanvasItem *canvas_item = Object::cast_to<CanvasItem>(p_node); Node *scene = editor->get_edited_scene(); - bool editable = p_node == scene || p_node->get_owner() == scene || scene->is_editable_instance(p_node->get_owner()); + bool editable = p_node == scene || p_node->get_owner() == scene || p_node == scene->get_deepest_editable_node(p_node); bool lock_children = p_node->has_meta("_edit_group_") && p_node->get_meta("_edit_group_"); bool locked = _is_node_locked(p_node); if (!lock_children || !editable) { for (int i = p_node->get_child_count() - 1; i >= 0; i--) { if (canvas_item) { - if (!canvas_item->is_set_as_toplevel()) { + if (!canvas_item->is_set_as_top_level()) { _find_canvas_items_in_rect(p_rect, p_node->get_child(i), r_items, p_parent_xform * canvas_item->get_transform(), p_canvas_xform); } else { _find_canvas_items_in_rect(p_rect, p_node->get_child(i), r_items, canvas_item->get_transform(), p_canvas_xform); @@ -854,17 +858,26 @@ Vector2 CanvasItemEditor::_anchor_to_position(const Control *p_control, Vector2 Transform2D parent_transform = p_control->get_transform().affine_inverse(); Rect2 parent_rect = p_control->get_parent_anchorable_rect(); - return parent_transform.xform(parent_rect.position + Vector2(parent_rect.size.x * anchor.x, parent_rect.size.y * anchor.y)); + if (p_control->is_layout_rtl()) { + return parent_transform.xform(parent_rect.position + Vector2(parent_rect.size.x - parent_rect.size.x * anchor.x, parent_rect.size.y * anchor.y)); + } else { + return parent_transform.xform(parent_rect.position + Vector2(parent_rect.size.x * anchor.x, parent_rect.size.y * anchor.y)); + } } Vector2 CanvasItemEditor::_position_to_anchor(const Control *p_control, Vector2 position) { ERR_FAIL_COND_V(!p_control, Vector2()); Rect2 parent_rect = p_control->get_parent_anchorable_rect(); - ERR_FAIL_COND_V(parent_rect.size.x == 0, Vector2()); - ERR_FAIL_COND_V(parent_rect.size.y == 0, Vector2()); - return (p_control->get_transform().xform(position) - parent_rect.position) / parent_rect.size; + Vector2 output = Vector2(); + if (p_control->is_layout_rtl()) { + output.x = (parent_rect.size.x == 0) ? 0.0 : (parent_rect.size.x - p_control->get_transform().xform(position).x - parent_rect.position.x) / parent_rect.size.x; + } else { + output.x = (parent_rect.size.x == 0) ? 0.0 : (p_control->get_transform().xform(position).x - parent_rect.position.x) / parent_rect.size.x; + } + output.y = (parent_rect.size.y == 0) ? 0.0 : (p_control->get_transform().xform(position).y - parent_rect.position.y) / parent_rect.size.y; + return output; } void CanvasItemEditor::_save_canvas_item_ik_chain(const CanvasItem *p_canvas_item, List<float> *p_bones_length, List<Dictionary> *p_bones_state) { @@ -950,9 +963,24 @@ void CanvasItemEditor::_restore_canvas_item_state(List<CanvasItem *> p_canvas_it } void CanvasItemEditor::_commit_canvas_item_state(List<CanvasItem *> p_canvas_items, String action_name, bool commit_bones) { - undo_redo->create_action(action_name); + List<CanvasItem *> modified_canvas_items; for (List<CanvasItem *>::Element *E = p_canvas_items.front(); E; E = E->next()) { CanvasItem *canvas_item = E->get(); + Dictionary old_state = editor_selection->get_node_editor_data<CanvasItemEditorSelectedItem>(canvas_item)->undo_state; + Dictionary new_state = canvas_item->_edit_get_state(); + + if (old_state.hash() != new_state.hash()) { + modified_canvas_items.push_back(canvas_item); + } + } + + if (modified_canvas_items.is_empty()) { + return; + } + + undo_redo->create_action(action_name); + for (List<CanvasItem *>::Element *E = modified_canvas_items.front(); E; E = E->next()) { + CanvasItem *canvas_item = E->get(); CanvasItemEditorSelectedItem *se = editor_selection->get_node_editor_data<CanvasItemEditorSelectedItem>(canvas_item); undo_redo->add_do_method(canvas_item, "_edit_set_state", canvas_item->_edit_get_state()); undo_redo->add_undo_method(canvas_item, "_edit_set_state", se->undo_state); @@ -1134,7 +1162,7 @@ bool CanvasItemEditor::_gui_input_rulers_and_guides(const Ref<InputEvent> &p_eve if (dragged_guide_index >= 0) { vguides.remove(dragged_guide_index); undo_redo->create_action(TTR("Remove Vertical Guide")); - if (vguides.empty()) { + if (vguides.is_empty()) { undo_redo->add_do_method(EditorNode::get_singleton()->get_edited_scene(), "remove_meta", "_edit_vertical_guides_"); } else { undo_redo->add_do_method(EditorNode::get_singleton()->get_edited_scene(), "set_meta", "_edit_vertical_guides_", vguides); @@ -1167,7 +1195,7 @@ bool CanvasItemEditor::_gui_input_rulers_and_guides(const Ref<InputEvent> &p_eve if (dragged_guide_index >= 0) { hguides.remove(dragged_guide_index); undo_redo->create_action(TTR("Remove Horizontal Guide")); - if (hguides.empty()) { + if (hguides.is_empty()) { undo_redo->add_do_method(EditorNode::get_singleton()->get_edited_scene(), "remove_meta", "_edit_horizontal_guides_"); } else { undo_redo->add_do_method(EditorNode::get_singleton()->get_edited_scene(), "set_meta", "_edit_horizontal_guides_", hguides); @@ -1205,7 +1233,26 @@ bool CanvasItemEditor::_gui_input_rulers_and_guides(const Ref<InputEvent> &p_eve bool CanvasItemEditor::_gui_input_zoom_or_pan(const Ref<InputEvent> &p_event, bool p_already_accepted) { Ref<InputEventMouseButton> b = p_event; if (b.is_valid() && !p_already_accepted) { - bool pan_on_scroll = bool(EditorSettings::get_singleton()->get("editors/2d/scroll_to_pan")) && !b->get_control(); + const bool pan_on_scroll = bool(EditorSettings::get_singleton()->get("editors/2d/scroll_to_pan")) && !b->get_control(); + + if (pan_on_scroll) { + // Perform horizontal scrolling first so we can check for Shift being held. + if (b->is_pressed() && + (b->get_button_index() == BUTTON_WHEEL_LEFT || (b->get_shift() && b->get_button_index() == BUTTON_WHEEL_UP))) { + // Pan left + view_offset.x -= int(EditorSettings::get_singleton()->get("editors/2d/pan_speed")) / zoom * b->get_factor(); + update_viewport(); + return true; + } + + if (b->is_pressed() && + (b->get_button_index() == BUTTON_WHEEL_RIGHT || (b->get_shift() && b->get_button_index() == BUTTON_WHEEL_DOWN))) { + // Pan right + view_offset.x += int(EditorSettings::get_singleton()->get("editors/2d/pan_speed")) / zoom * b->get_factor(); + update_viewport(); + return true; + } + } if (b->is_pressed() && b->get_button_index() == BUTTON_WHEEL_DOWN) { // Scroll or pan down @@ -1213,7 +1260,11 @@ bool CanvasItemEditor::_gui_input_zoom_or_pan(const Ref<InputEvent> &p_event, bo view_offset.y += int(EditorSettings::get_singleton()->get("editors/2d/pan_speed")) / zoom * b->get_factor(); update_viewport(); } else { - _zoom_on_position(zoom * (1 - (0.05 * b->get_factor())), b->get_position()); + float new_zoom = _get_next_zoom_value(-1); + if (b->get_factor() != 1.f) { + new_zoom = zoom * ((new_zoom / zoom - 1.f) * b->get_factor() + 1.f); + } + _zoom_on_position(new_zoom, b->get_position()); } return true; } @@ -1224,29 +1275,15 @@ bool CanvasItemEditor::_gui_input_zoom_or_pan(const Ref<InputEvent> &p_event, bo view_offset.y -= int(EditorSettings::get_singleton()->get("editors/2d/pan_speed")) / zoom * b->get_factor(); update_viewport(); } else { - _zoom_on_position(zoom * ((0.95 + (0.05 * b->get_factor())) / 0.95), b->get_position()); + float new_zoom = _get_next_zoom_value(1); + if (b->get_factor() != 1.f) { + new_zoom = zoom * ((new_zoom / zoom - 1.f) * b->get_factor() + 1.f); + } + _zoom_on_position(new_zoom, b->get_position()); } return true; } - if (b->is_pressed() && b->get_button_index() == BUTTON_WHEEL_LEFT) { - // Pan left - if (pan_on_scroll) { - view_offset.x -= int(EditorSettings::get_singleton()->get("editors/2d/pan_speed")) / zoom * b->get_factor(); - update_viewport(); - return true; - } - } - - if (b->is_pressed() && b->get_button_index() == BUTTON_WHEEL_RIGHT) { - // Pan right - if (pan_on_scroll) { - view_offset.x += int(EditorSettings::get_singleton()->get("editors/2d/pan_speed")) / zoom * b->get_factor(); - update_viewport(); - return true; - } - } - if (!panning) { if (b->is_pressed() && (b->get_button_index() == BUTTON_MIDDLE || @@ -1315,6 +1352,18 @@ bool CanvasItemEditor::_gui_input_zoom_or_pan(const Ref<InputEvent> &p_event, bo Ref<InputEventPanGesture> pan_gesture = p_event; if (pan_gesture.is_valid() && !p_already_accepted) { + // If control key pressed, then zoom instead of pan + if (pan_gesture->get_control()) { + const float factor = pan_gesture->get_delta().y; + float new_zoom = _get_next_zoom_value(-1); + + if (factor != 1.f) { + new_zoom = zoom * ((new_zoom / zoom - 1.f) * factor + 1.f); + } + _zoom_on_position(new_zoom, pan_gesture->get_position()); + return true; + } + // Pan gesture const Vector2 delta = (int(EditorSettings::get_singleton()->get("editors/2d/pan_speed")) / zoom) * pan_gesture->get_delta(); view_offset.x += delta.x; @@ -1386,9 +1435,16 @@ bool CanvasItemEditor::_gui_input_pivot(const Ref<InputEvent> &p_event) { } // Confirm the pivot move - if ((b.is_valid() && !b->is_pressed() && b->get_button_index() == BUTTON_LEFT && tool == TOOL_EDIT_PIVOT) || - (k.is_valid() && !k->is_pressed() && k->get_keycode() == KEY_V)) { - _commit_canvas_item_state(drag_selection, TTR("Move pivot")); + if (drag_selection.size() >= 1 && + ((b.is_valid() && !b->is_pressed() && b->get_button_index() == BUTTON_LEFT && tool == TOOL_EDIT_PIVOT) || + (k.is_valid() && !k->is_pressed() && k->get_keycode() == KEY_V))) { + _commit_canvas_item_state( + drag_selection, + vformat( + TTR("Set CanvasItem \"%s\" Pivot Offset to (%d, %d)"), + drag_selection[0]->get_name(), + drag_selection[0]->_edit_get_pivot().x, + drag_selection[0]->_edit_get_pivot().y)); drag_type = DRAG_NONE; return true; } @@ -1481,7 +1537,7 @@ bool CanvasItemEditor::_gui_input_rotate(const Ref<InputEvent> &p_event) { // Start rotation if (drag_type == DRAG_NONE) { if (b.is_valid() && b->get_button_index() == BUTTON_LEFT && b->is_pressed()) { - if ((b->get_control() && !b->get_alt() && tool == TOOL_SELECT) || tool == TOOL_ROTATE) { + if ((b->get_command() && !b->get_alt() && tool == TOOL_SELECT) || tool == TOOL_ROTATE) { List<CanvasItem *> selection = _get_edited_canvas_items(); // Remove not movable nodes @@ -1525,7 +1581,20 @@ bool CanvasItemEditor::_gui_input_rotate(const Ref<InputEvent> &p_event) { // Confirms the node rotation if (b.is_valid() && b->get_button_index() == BUTTON_LEFT && !b->is_pressed()) { - _commit_canvas_item_state(drag_selection, TTR("Rotate CanvasItem")); + if (drag_selection.size() != 1) { + _commit_canvas_item_state( + drag_selection, + vformat(TTR("Rotate %d CanvasItems"), drag_selection.size()), + true); + } else { + _commit_canvas_item_state( + drag_selection, + vformat(TTR("Rotate CanvasItem \"%s\" to %d degrees"), + drag_selection[0]->get_name(), + Math::rad2deg(drag_selection[0]->_edit_get_rotation())), + true); + } + if (key_auto_insert_button->is_pressed()) { _insert_animation_keys(false, true, false, true); } @@ -1574,16 +1643,20 @@ bool CanvasItemEditor::_gui_input_anchors(const Ref<InputEvent> &p_event) { Control *control = Object::cast_to<Control>(selection[0]); if (control && _is_node_movable(control)) { Vector2 anchor_pos[4]; - anchor_pos[0] = Vector2(control->get_anchor(MARGIN_LEFT), control->get_anchor(MARGIN_TOP)); - anchor_pos[1] = Vector2(control->get_anchor(MARGIN_RIGHT), control->get_anchor(MARGIN_TOP)); - anchor_pos[2] = Vector2(control->get_anchor(MARGIN_RIGHT), control->get_anchor(MARGIN_BOTTOM)); - anchor_pos[3] = Vector2(control->get_anchor(MARGIN_LEFT), control->get_anchor(MARGIN_BOTTOM)); + anchor_pos[0] = Vector2(control->get_anchor(SIDE_LEFT), control->get_anchor(SIDE_TOP)); + anchor_pos[1] = Vector2(control->get_anchor(SIDE_RIGHT), control->get_anchor(SIDE_TOP)); + anchor_pos[2] = Vector2(control->get_anchor(SIDE_RIGHT), control->get_anchor(SIDE_BOTTOM)); + anchor_pos[3] = Vector2(control->get_anchor(SIDE_LEFT), control->get_anchor(SIDE_BOTTOM)); Rect2 anchor_rects[4]; for (int i = 0; i < 4; i++) { anchor_pos[i] = (transform * control->get_global_transform_with_canvas()).xform(_anchor_to_position(control, anchor_pos[i])); anchor_rects[i] = Rect2(anchor_pos[i], anchor_handle->get_size()); - anchor_rects[i].position -= anchor_handle->get_size() * Vector2(float(i == 0 || i == 3), float(i <= 1)); + if (control->is_layout_rtl()) { + anchor_rects[i].position -= anchor_handle->get_size() * Vector2(float(i == 1 || i == 2), float(i <= 1)); + } else { + anchor_rects[i].position -= anchor_handle->get_size() * Vector2(float(i == 0 || i == 3), float(i <= 1)); + } } DragType dragger[] = { @@ -1623,8 +1696,8 @@ bool CanvasItemEditor::_gui_input_anchors(const Ref<InputEvent> &p_event) { Transform2D xform = control->get_global_transform_with_canvas().affine_inverse(); Point2 previous_anchor; - previous_anchor.x = (drag_type == DRAG_ANCHOR_TOP_LEFT || drag_type == DRAG_ANCHOR_BOTTOM_LEFT) ? control->get_anchor(MARGIN_LEFT) : control->get_anchor(MARGIN_RIGHT); - previous_anchor.y = (drag_type == DRAG_ANCHOR_TOP_LEFT || drag_type == DRAG_ANCHOR_TOP_RIGHT) ? control->get_anchor(MARGIN_TOP) : control->get_anchor(MARGIN_BOTTOM); + previous_anchor.x = (drag_type == DRAG_ANCHOR_TOP_LEFT || drag_type == DRAG_ANCHOR_BOTTOM_LEFT) ? control->get_anchor(SIDE_LEFT) : control->get_anchor(SIDE_RIGHT); + previous_anchor.y = (drag_type == DRAG_ANCHOR_TOP_LEFT || drag_type == DRAG_ANCHOR_TOP_RIGHT) ? control->get_anchor(SIDE_TOP) : control->get_anchor(SIDE_BOTTOM); previous_anchor = xform.affine_inverse().xform(_anchor_to_position(control, previous_anchor)); Vector2 new_anchor = xform.xform(snap_point(previous_anchor + (drag_to - drag_from), SNAP_GRID | SNAP_OTHER_NODES, SNAP_NODE_PARENT | SNAP_NODE_SIDES | SNAP_NODE_CENTER, control)); @@ -1637,44 +1710,44 @@ bool CanvasItemEditor::_gui_input_anchors(const Ref<InputEvent> &p_event) { switch (drag_type) { case DRAG_ANCHOR_TOP_LEFT: if (!use_single_axis || !use_y) { - control->set_anchor(MARGIN_LEFT, new_anchor.x, false, false); + control->set_anchor(SIDE_LEFT, new_anchor.x, false, false); } if (!use_single_axis || use_y) { - control->set_anchor(MARGIN_TOP, new_anchor.y, false, false); + control->set_anchor(SIDE_TOP, new_anchor.y, false, false); } break; case DRAG_ANCHOR_TOP_RIGHT: if (!use_single_axis || !use_y) { - control->set_anchor(MARGIN_RIGHT, new_anchor.x, false, false); + control->set_anchor(SIDE_RIGHT, new_anchor.x, false, false); } if (!use_single_axis || use_y) { - control->set_anchor(MARGIN_TOP, new_anchor.y, false, false); + control->set_anchor(SIDE_TOP, new_anchor.y, false, false); } break; case DRAG_ANCHOR_BOTTOM_RIGHT: if (!use_single_axis || !use_y) { - control->set_anchor(MARGIN_RIGHT, new_anchor.x, false, false); + control->set_anchor(SIDE_RIGHT, new_anchor.x, false, false); } if (!use_single_axis || use_y) { - control->set_anchor(MARGIN_BOTTOM, new_anchor.y, false, false); + control->set_anchor(SIDE_BOTTOM, new_anchor.y, false, false); } break; case DRAG_ANCHOR_BOTTOM_LEFT: if (!use_single_axis || !use_y) { - control->set_anchor(MARGIN_LEFT, new_anchor.x, false, false); + control->set_anchor(SIDE_LEFT, new_anchor.x, false, false); } if (!use_single_axis || use_y) { - control->set_anchor(MARGIN_BOTTOM, new_anchor.y, false, false); + control->set_anchor(SIDE_BOTTOM, new_anchor.y, false, false); } break; case DRAG_ANCHOR_ALL: if (!use_single_axis || !use_y) { - control->set_anchor(MARGIN_LEFT, new_anchor.x, false, true); - control->set_anchor(MARGIN_RIGHT, new_anchor.x, false, true); + control->set_anchor(SIDE_LEFT, new_anchor.x, false, true); + control->set_anchor(SIDE_RIGHT, new_anchor.x, false, true); } if (!use_single_axis || use_y) { - control->set_anchor(MARGIN_TOP, new_anchor.y, false, true); - control->set_anchor(MARGIN_BOTTOM, new_anchor.y, false, true); + control->set_anchor(SIDE_TOP, new_anchor.y, false, true); + control->set_anchor(SIDE_BOTTOM, new_anchor.y, false, true); } break; default: @@ -1684,8 +1757,10 @@ bool CanvasItemEditor::_gui_input_anchors(const Ref<InputEvent> &p_event) { } // Confirms new anchor position - if (b.is_valid() && b->get_button_index() == BUTTON_LEFT && !b->is_pressed()) { - _commit_canvas_item_state(drag_selection, TTR("Move anchor")); + if (drag_selection.size() >= 1 && b.is_valid() && b->get_button_index() == BUTTON_LEFT && !b->is_pressed()) { + _commit_canvas_item_state( + drag_selection, + vformat(TTR("Move CanvasItem \"%s\" Anchor"), drag_selection[0]->get_name())); drag_type = DRAG_NONE; return true; } @@ -1748,7 +1823,7 @@ bool CanvasItemEditor::_gui_input_resize(const Ref<InputEvent> &p_event) { } ofs = (endpoints[i] + endpoints[next]) / 2; - ofs += (endpoints[next] - endpoints[i]).tangent().normalized() * (select_handle->get_size().width / 2); + ofs += (endpoints[next] - endpoints[i]).orthogonal().normalized() * (select_handle->get_size().width / 2); if (ofs.distance_to(b->get_position()) < radius) { resize_drag = dragger[i * 2 + 1]; } @@ -1861,8 +1936,31 @@ bool CanvasItemEditor::_gui_input_resize(const Ref<InputEvent> &p_event) { } // Confirm resize - if (b.is_valid() && b->get_button_index() == BUTTON_LEFT && !b->is_pressed()) { - _commit_canvas_item_state(drag_selection, TTR("Resize CanvasItem")); + if (drag_selection.size() >= 1 && b.is_valid() && b->get_button_index() == BUTTON_LEFT && !b->is_pressed()) { + const Node2D *node2d = Object::cast_to<Node2D>(drag_selection[0]); + if (node2d) { + // Extends from Node2D. + // Node2D doesn't have an actual stored rect size, unlike Controls. + _commit_canvas_item_state( + drag_selection, + vformat( + TTR("Scale Node2D \"%s\" to (%s, %s)"), + drag_selection[0]->get_name(), + Math::snapped(drag_selection[0]->_edit_get_scale().x, 0.01), + Math::snapped(drag_selection[0]->_edit_get_scale().y, 0.01)), + true); + } else { + // Extends from Control. + _commit_canvas_item_state( + drag_selection, + vformat( + TTR("Resize Control \"%s\" to (%d, %d)"), + drag_selection[0]->get_name(), + drag_selection[0]->_edit_get_rect().size.x, + drag_selection[0]->_edit_get_rect().size.y), + true); + } + if (key_auto_insert_button->is_pressed()) { _insert_animation_keys(false, false, true, true); } @@ -1990,7 +2088,20 @@ bool CanvasItemEditor::_gui_input_scale(const Ref<InputEvent> &p_event) { // Confirm resize if (b.is_valid() && b->get_button_index() == BUTTON_LEFT && !b->is_pressed()) { - _commit_canvas_item_state(drag_selection, TTR("Scale CanvasItem")); + if (drag_selection.size() != 1) { + _commit_canvas_item_state( + drag_selection, + vformat(TTR("Scale %d CanvasItems"), drag_selection.size()), + true); + } else { + _commit_canvas_item_state( + drag_selection, + vformat(TTR("Scale CanvasItem \"%s\" to (%s, %s)"), + drag_selection[0]->get_name(), + Math::snapped(drag_selection[0]->_edit_get_scale().x, 0.01), + Math::snapped(drag_selection[0]->_edit_get_scale().y, 0.01)), + true); + } if (key_auto_insert_button->is_pressed()) { _insert_animation_keys(false, false, true, true); } @@ -2022,10 +2133,10 @@ bool CanvasItemEditor::_gui_input_move(const Ref<InputEvent> &p_event) { if ((b->get_alt() && !b->get_control()) || tool == TOOL_MOVE) { List<CanvasItem *> selection = _get_edited_canvas_items(); - // Remove not movable nodes + drag_selection.clear(); for (int i = 0; i < selection.size(); i++) { - if (!_is_node_movable(selection[i], true)) { - selection.erase(selection[i]); + if (_is_node_movable(selection[i], true)) { + drag_selection.push_back(selection[i]); } } @@ -2050,7 +2161,6 @@ bool CanvasItemEditor::_gui_input_move(const Ref<InputEvent> &p_event) { } drag_from = transform.affine_inverse().xform(b->get_position()); - drag_selection = selection; _save_canvas_item_state(drag_selection); } return true; @@ -2122,7 +2232,21 @@ bool CanvasItemEditor::_gui_input_move(const Ref<InputEvent> &p_event) { // Confirm the move (only if it was moved) if (b.is_valid() && !b->is_pressed() && b->get_button_index() == BUTTON_LEFT) { if (transform.affine_inverse().xform(b->get_position()) != drag_from) { - _commit_canvas_item_state(drag_selection, TTR("Move CanvasItem"), true); + if (drag_selection.size() != 1) { + _commit_canvas_item_state( + drag_selection, + vformat(TTR("Move %d CanvasItems"), drag_selection.size()), + true); + } else { + _commit_canvas_item_state( + drag_selection, + vformat( + TTR("Move CanvasItem \"%s\" to (%d, %d)"), + drag_selection[0]->get_name(), + drag_selection[0]->_edit_get_position().x, + drag_selection[0]->_edit_get_position().y), + true); + } } if (key_auto_insert_button->is_pressed()) { @@ -2240,14 +2364,27 @@ bool CanvasItemEditor::_gui_input_move(const Ref<InputEvent> &p_event) { return true; } - if (k.is_valid() && !k->is_pressed() && drag_type == DRAG_KEY_MOVE && tool == TOOL_SELECT && + if (k.is_valid() && !k->is_pressed() && drag_type == DRAG_KEY_MOVE && (tool == TOOL_SELECT || tool == TOOL_MOVE) && (k->get_keycode() == KEY_UP || k->get_keycode() == KEY_DOWN || k->get_keycode() == KEY_LEFT || k->get_keycode() == KEY_RIGHT)) { // Confirm canvas items move by arrow keys if ((!Input::get_singleton()->is_key_pressed(KEY_UP)) && (!Input::get_singleton()->is_key_pressed(KEY_DOWN)) && (!Input::get_singleton()->is_key_pressed(KEY_LEFT)) && (!Input::get_singleton()->is_key_pressed(KEY_RIGHT))) { - _commit_canvas_item_state(drag_selection, TTR("Move CanvasItem"), true); + if (drag_selection.size() > 1) { + _commit_canvas_item_state( + drag_selection, + vformat(TTR("Move %d CanvasItems"), drag_selection.size()), + true); + } else if (drag_selection.size() == 1) { + _commit_canvas_item_state( + drag_selection, + vformat(TTR("Move CanvasItem \"%s\" to (%d, %d)"), + drag_selection[0]->get_name(), + drag_selection[0]->_edit_get_position().x, + drag_selection[0]->_edit_get_position().y), + true); + } drag_type = DRAG_NONE; } viewport->update(); @@ -2278,7 +2415,7 @@ bool CanvasItemEditor::_gui_input_select(const Ref<InputEvent> &p_event) { _select_click_on_item(item, click, b->get_shift()); return true; - } else if (!selection_results.empty()) { + } else if (!selection_results.is_empty()) { // Sorts items according the their z-index selection_results.sort(); @@ -2341,13 +2478,13 @@ bool CanvasItemEditor::_gui_input_select(const Ref<InputEvent> &p_event) { // Retrieve the bones Vector<_SelectResult> selection = Vector<_SelectResult>(); _get_bones_at_pos(click, selection); - if (!selection.empty()) { + if (!selection.is_empty()) { canvas_item = selection[0].item; } else { // Retrieve the canvas items selection = Vector<_SelectResult>(); _get_canvas_items_at_pos(click, selection); - if (!selection.empty()) { + if (!selection.is_empty()) { canvas_item = selection[0].item; } } @@ -2372,16 +2509,15 @@ bool CanvasItemEditor::_gui_input_select(const Ref<InputEvent> &p_event) { // Drag the node(s) if requested List<CanvasItem *> selection2 = _get_edited_canvas_items(); - // Remove not movable nodes + drag_selection.clear(); for (int i = 0; i < selection2.size(); i++) { - if (!_is_node_movable(selection2[i], true)) { - selection2.erase(selection2[i]); + if (_is_node_movable(selection2[i], true)) { + drag_selection.push_back(selection2[i]); } } if (selection2.size() > 0) { drag_type = DRAG_MOVE; - drag_selection = selection2; drag_from = click; _save_canvas_item_state(drag_selection); } @@ -2568,6 +2704,36 @@ void CanvasItemEditor::_gui_input_viewport(const Ref<InputEvent> &p_event) { _gui_input_hover(p_event); // Change the cursor + _update_cursor(); + + // Grab focus + if (!viewport->has_focus() && (!get_focus_owner() || !get_focus_owner()->is_text_field())) { + viewport->call_deferred("grab_focus"); + } +} + +void CanvasItemEditor::_update_cursor() { + // Compute an eventual rotation of the cursor + CursorShape rotation_array[4] = { CURSOR_HSIZE, CURSOR_BDIAGSIZE, CURSOR_VSIZE, CURSOR_FDIAGSIZE }; + int rotation_array_index = 0; + + List<CanvasItem *> selection = _get_edited_canvas_items(); + if (selection.size() == 1) { + float angle = Math::fposmod((double)selection[0]->get_global_transform_with_canvas().get_rotation(), Math_PI); + if (angle > Math_PI * 7.0 / 8.0) { + rotation_array_index = 0; + } else if (angle > Math_PI * 5.0 / 8.0) { + rotation_array_index = 1; + } else if (angle > Math_PI * 3.0 / 8.0) { + rotation_array_index = 2; + } else if (angle > Math_PI * 1.0 / 8.0) { + rotation_array_index = 3; + } else { + rotation_array_index = 0; + } + } + + // Choose the correct cursor CursorShape c = CURSOR_ARROW; switch (drag_type) { case DRAG_NONE: @@ -2590,22 +2756,28 @@ void CanvasItemEditor::_gui_input_viewport(const Ref<InputEvent> &p_event) { break; case DRAG_LEFT: case DRAG_RIGHT: + c = rotation_array[rotation_array_index]; + break; case DRAG_V_GUIDE: c = CURSOR_HSIZE; break; case DRAG_TOP: case DRAG_BOTTOM: + c = rotation_array[(rotation_array_index + 2) % 4]; + break; case DRAG_H_GUIDE: c = CURSOR_VSIZE; break; case DRAG_TOP_LEFT: case DRAG_BOTTOM_RIGHT: + c = rotation_array[(rotation_array_index + 3) % 4]; + break; case DRAG_DOUBLE_GUIDE: c = CURSOR_FDIAGSIZE; break; case DRAG_TOP_RIGHT: case DRAG_BOTTOM_LEFT: - c = CURSOR_BDIAGSIZE; + c = rotation_array[(rotation_array_index + 1) % 4]; break; case DRAG_MOVE: c = CURSOR_MOVE; @@ -2621,44 +2793,40 @@ void CanvasItemEditor::_gui_input_viewport(const Ref<InputEvent> &p_event) { } viewport->set_default_cursor_shape(c); - - // Grab focus - if (!viewport->has_focus() && (!get_focus_owner() || !get_focus_owner()->is_text_field())) { - viewport->call_deferred("grab_focus"); - } } -void CanvasItemEditor::_draw_text_at_position(Point2 p_position, String p_string, Margin p_side) { +void CanvasItemEditor::_draw_text_at_position(Point2 p_position, String p_string, Side p_side) { Color color = get_theme_color("font_color", "Editor"); color.a = 0.8; Ref<Font> font = get_theme_font("font", "Label"); - Size2 text_size = font->get_string_size(p_string); + int font_size = get_theme_font_size("font_size", "Label"); + Size2 text_size = font->get_string_size(p_string, font_size); switch (p_side) { - case MARGIN_LEFT: + case SIDE_LEFT: p_position += Vector2(-text_size.x - 5, text_size.y / 2); break; - case MARGIN_TOP: + case SIDE_TOP: p_position += Vector2(-text_size.x / 2, -5); break; - case MARGIN_RIGHT: + case SIDE_RIGHT: p_position += Vector2(5, text_size.y / 2); break; - case MARGIN_BOTTOM: + case SIDE_BOTTOM: p_position += Vector2(-text_size.x / 2, text_size.y + 5); break; } - viewport->draw_string(font, p_position, p_string, color); + viewport->draw_string(font, p_position, p_string, HALIGN_LEFT, -1, font_size, color); } -void CanvasItemEditor::_draw_margin_at_position(int p_value, Point2 p_position, Margin p_side) { - String str = vformat("%d px", p_value); +void CanvasItemEditor::_draw_margin_at_position(int p_value, Point2 p_position, Side p_side) { + String str = TS->format_number(vformat("%d " + TTR("px"), p_value)); if (p_value != 0) { _draw_text_at_position(p_position, str, p_side); } } -void CanvasItemEditor::_draw_percentage_at_position(float p_value, Point2 p_position, Margin p_side) { - String str = vformat("%.1f %%", p_value * 100.0); +void CanvasItemEditor::_draw_percentage_at_position(float p_value, Point2 p_position, Side p_side) { + String str = TS->format_number(vformat("%.1f ", p_value * 100.0)) + TS->percent_sign(); if (p_value != 0) { _draw_text_at_position(p_position, str, p_side); } @@ -2702,17 +2870,19 @@ void CanvasItemEditor::_draw_guides() { Color text_color = get_theme_color("font_color", "Editor"); text_color.a = 0.5; if (drag_type == DRAG_DOUBLE_GUIDE || drag_type == DRAG_V_GUIDE) { - String str = vformat("%d px", Math::round(xform.affine_inverse().xform(dragged_guide_pos).x)); + String str = TS->format_number(vformat("%d px", Math::round(xform.affine_inverse().xform(dragged_guide_pos).x))); Ref<Font> font = get_theme_font("font", "Label"); - Size2 text_size = font->get_string_size(str); - viewport->draw_string(font, Point2(dragged_guide_pos.x + 10, RULER_WIDTH + text_size.y / 2 + 10), str, text_color); + int font_size = get_theme_font_size("font_size", "Label"); + Size2 text_size = font->get_string_size(str, font_size); + viewport->draw_string(font, Point2(dragged_guide_pos.x + 10, RULER_WIDTH + text_size.y / 2 + 10), str, HALIGN_LEFT, -1, font_size, text_color); viewport->draw_line(Point2(dragged_guide_pos.x, 0), Point2(dragged_guide_pos.x, viewport->get_size().y), guide_color, Math::round(EDSCALE)); } if (drag_type == DRAG_DOUBLE_GUIDE || drag_type == DRAG_H_GUIDE) { - String str = vformat("%d px", Math::round(xform.affine_inverse().xform(dragged_guide_pos).y)); + String str = TS->format_number(vformat("%d px", Math::round(xform.affine_inverse().xform(dragged_guide_pos).y))); Ref<Font> font = get_theme_font("font", "Label"); - Size2 text_size = font->get_string_size(str); - viewport->draw_string(font, Point2(RULER_WIDTH + 10, dragged_guide_pos.y + text_size.y / 2 + 10), str, text_color); + int font_size = get_theme_font_size("font_size", "Label"); + Size2 text_size = font->get_string_size(str, font_size); + viewport->draw_string(font, Point2(RULER_WIDTH + 10, dragged_guide_pos.y + text_size.y / 2 + 10), str, HALIGN_LEFT, -1, font_size, text_color); viewport->draw_line(Point2(0, dragged_guide_pos.y), Point2(viewport->get_size().x, dragged_guide_pos.y), guide_color, Math::round(EDSCALE)); } } @@ -2737,6 +2907,7 @@ void CanvasItemEditor::_draw_rulers() { Color font_color = get_theme_color("font_color", "Editor"); font_color.a = 0.8; Ref<Font> font = get_theme_font("rulers", "EditorFonts"); + int font_size = get_theme_font_size("rulers_size", "EditorFonts"); // The rule transform Transform2D ruler_transform = Transform2D(); @@ -2779,11 +2950,11 @@ void CanvasItemEditor::_draw_rulers() { // Draw top ruler viewport->draw_rect(Rect2(Point2(RULER_WIDTH, 0), Size2(viewport->get_size().x, RULER_WIDTH)), bg_color); for (int i = Math::ceil(first.x); i < last.x; i++) { - Point2 position = (transform * ruler_transform * major_subdivide * minor_subdivide).xform(Point2(i, 0)); + Point2 position = (transform * ruler_transform * major_subdivide * minor_subdivide).xform(Point2(i, 0)).round(); if (i % (major_subdivision * minor_subdivision) == 0) { viewport->draw_line(Point2(position.x, 0), Point2(position.x, RULER_WIDTH), graduation_color, Math::round(EDSCALE)); float val = (ruler_transform * major_subdivide * minor_subdivide).xform(Point2(i, 0)).x; - viewport->draw_string(font, Point2(position.x + 2, font->get_height()), vformat(((int)val == val) ? "%d" : "%.1f", val), font_color); + viewport->draw_string(font, Point2(position.x + 2, font->get_height(font_size)), TS->format_number(vformat(((int)val == val) ? "%d" : "%.1f", val)), HALIGN_LEFT, -1, font_size, font_color); } else { if (i % minor_subdivision == 0) { viewport->draw_line(Point2(position.x, RULER_WIDTH * 0.33), Point2(position.x, RULER_WIDTH), graduation_color, Math::round(EDSCALE)); @@ -2796,14 +2967,14 @@ void CanvasItemEditor::_draw_rulers() { // Draw left ruler viewport->draw_rect(Rect2(Point2(0, RULER_WIDTH), Size2(RULER_WIDTH, viewport->get_size().y)), bg_color); for (int i = Math::ceil(first.y); i < last.y; i++) { - Point2 position = (transform * ruler_transform * major_subdivide * minor_subdivide).xform(Point2(0, i)); + Point2 position = (transform * ruler_transform * major_subdivide * minor_subdivide).xform(Point2(0, i)).round(); if (i % (major_subdivision * minor_subdivision) == 0) { viewport->draw_line(Point2(0, position.y), Point2(RULER_WIDTH, position.y), graduation_color, Math::round(EDSCALE)); float val = (ruler_transform * major_subdivide * minor_subdivide).xform(Point2(0, i)).y; - Transform2D text_xform = Transform2D(-Math_PI / 2.0, Point2(font->get_height(), position.y - 2)); + Transform2D text_xform = Transform2D(-Math_PI / 2.0, Point2(font->get_height(font_size), position.y - 2)); viewport->draw_set_transform_matrix(viewport->get_transform() * text_xform); - viewport->draw_string(font, Point2(), vformat(((int)val == val) ? "%d" : "%.1f", val), font_color); + viewport->draw_string(font, Point2(), TS->format_number(vformat(((int)val == val) ? "%d" : "%.1f", val)), HALIGN_LEFT, -1, font_size, font_color); viewport->draw_set_transform_matrix(viewport->get_transform()); } else { @@ -2915,17 +3086,21 @@ void CanvasItemEditor::_draw_ruler_tool() { } Ref<Font> font = get_theme_font("bold", "EditorFonts"); + int font_size = get_theme_font_size("bold_size", "EditorFonts"); Color font_color = get_theme_color("font_color", "Editor"); Color font_secondary_color = font_color; - font_secondary_color.a = 0.5; - float text_height = font->get_height(); + font_secondary_color.set_v(font_secondary_color.get_v() > 0.5 ? 0.7 : 0.3); + Color outline_color = font_color.inverted(); + float text_height = font->get_height(font_size); + + const float outline_size = 2; const float text_width = 76; const float angle_text_width = 54; Point2 text_pos = (begin + end) / 2 - Vector2(text_width / 2, text_height / 2); text_pos.x = CLAMP(text_pos.x, text_width / 2, viewport->get_rect().size.x - text_width * 1.5); text_pos.y = CLAMP(text_pos.y, text_height * 1.5, viewport->get_rect().size.y - text_height * 1.5); - viewport->draw_string(font, text_pos, vformat("%.2f px", length_vector.length()), font_color); + viewport->draw_string(font, text_pos, TS->format_number(vformat("%.2f " + TTR("px"), length_vector.length())), HALIGN_LEFT, -1, font_size, font_color, outline_size, outline_color); if (draw_secondary_lines) { const float horizontal_angle_rad = atan2(length_vector.y, length_vector.x); @@ -2935,16 +3110,16 @@ void CanvasItemEditor::_draw_ruler_tool() { Point2 text_pos2 = text_pos; text_pos2.x = begin.x < text_pos.x ? MIN(text_pos.x - text_width, begin.x - text_width / 2) : MAX(text_pos.x + text_width, begin.x - text_width / 2); - viewport->draw_string(font, text_pos2, vformat("%.2f px", length_vector.y), font_secondary_color); + viewport->draw_string(font, text_pos2, TS->format_number(vformat("%.2f " + TTR("px"), length_vector.y)), HALIGN_LEFT, -1, font_size, font_secondary_color, outline_size, outline_color); Point2 v_angle_text_pos = Point2(); v_angle_text_pos.x = CLAMP(begin.x - angle_text_width / 2, angle_text_width / 2, viewport->get_rect().size.x - angle_text_width); v_angle_text_pos.y = begin.y < end.y ? MIN(text_pos2.y - 2 * text_height, begin.y - text_height * 0.5) : MAX(text_pos2.y + text_height * 3, begin.y + text_height * 1.5); - viewport->draw_string(font, v_angle_text_pos, vformat("%d deg", vertical_angle), font_secondary_color); + viewport->draw_string(font, v_angle_text_pos, TS->format_number(vformat("%d " + TTR("deg"), vertical_angle)), HALIGN_LEFT, -1, font_size, font_secondary_color, outline_size, outline_color); text_pos2 = text_pos; text_pos2.y = end.y < text_pos.y ? MIN(text_pos.y - text_height * 2, end.y - text_height / 2) : MAX(text_pos.y + text_height * 2, end.y - text_height / 2); - viewport->draw_string(font, text_pos2, vformat("%.2f px", length_vector.x), font_secondary_color); + viewport->draw_string(font, text_pos2, TS->format_number(vformat("%.2f " + TTR("px"), length_vector.x)), HALIGN_LEFT, -1, font_size, font_secondary_color, outline_size, outline_color); Point2 h_angle_text_pos = Point2(); h_angle_text_pos.x = CLAMP(end.x - angle_text_width / 2, angle_text_width / 2, viewport->get_rect().size.x - angle_text_width); @@ -2961,7 +3136,7 @@ void CanvasItemEditor::_draw_ruler_tool() { h_angle_text_pos.y = MIN(text_pos.y - height_multiplier * text_height, MIN(end.y - text_height * 0.5, text_pos2.y - height_multiplier * text_height)); } } - viewport->draw_string(font, h_angle_text_pos, vformat("%d deg", horizontal_angle), font_secondary_color); + viewport->draw_string(font, h_angle_text_pos, TS->format_number(vformat("%d " + TTR("deg"), horizontal_angle)), HALIGN_LEFT, -1, font_size, font_secondary_color, outline_size, outline_color); // Angle arcs int arc_point_count = 8; @@ -2974,16 +3149,16 @@ void CanvasItemEditor::_draw_ruler_tool() { float arc_1_start_angle = end_to_begin.x < 0 ? - (end_to_begin.y < 0 ? 3.0 * Math_PI / 2.0 - vertical_angle_rad : Math_PI / 2.0) : - (end_to_begin.y < 0 ? 3.0 * Math_PI / 2.0 : Math_PI / 2.0 - vertical_angle_rad); + (end_to_begin.y < 0 ? 3.0 * Math_PI / 2.0 - vertical_angle_rad : Math_PI / 2.0) : + (end_to_begin.y < 0 ? 3.0 * Math_PI / 2.0 : Math_PI / 2.0 - vertical_angle_rad); float arc_1_end_angle = arc_1_start_angle + vertical_angle_rad; // Constrain arc to triangle height & max size float arc_1_radius = MIN(MIN(arc_radius_max_length_percent * ruler_length, ABS(end_to_begin.y)), arc_max_radius); float arc_2_start_angle = end_to_begin.x < 0 ? - (end_to_begin.y < 0 ? 0.0 : -horizontal_angle_rad) : - (end_to_begin.y < 0 ? Math_PI - horizontal_angle_rad : Math_PI); + (end_to_begin.y < 0 ? 0.0 : -horizontal_angle_rad) : + (end_to_begin.y < 0 ? Math_PI - horizontal_angle_rad : Math_PI); float arc_2_end_angle = arc_2_start_angle + horizontal_angle_rad; // Constrain arc to triangle width & max size float arc_2_radius = MIN(MIN(arc_radius_max_length_percent * ruler_length, ABS(end_to_begin.x)), arc_max_radius); @@ -2998,17 +3173,17 @@ void CanvasItemEditor::_draw_ruler_tool() { text_pos.y = CLAMP(text_pos.y, text_height * 2.5, viewport->get_rect().size.y - text_height / 2); if (draw_secondary_lines) { - viewport->draw_string(font, text_pos, vformat("%.2f units", (length_vector / grid_step).length()), font_color); + viewport->draw_string(font, text_pos, TS->format_number(vformat("%.2f " + TTR("units"), (length_vector / grid_step).length())), HALIGN_LEFT, -1, font_size, font_color, outline_size, outline_color); Point2 text_pos2 = text_pos; text_pos2.x = begin.x < text_pos.x ? MIN(text_pos.x - text_width, begin.x - text_width / 2) : MAX(text_pos.x + text_width, begin.x - text_width / 2); - viewport->draw_string(font, text_pos2, vformat("%d units", roundf(length_vector.y / grid_step.y)), font_secondary_color); + viewport->draw_string(font, text_pos2, TS->format_number(vformat("%d " + TTR("units"), roundf(length_vector.y / grid_step.y))), HALIGN_LEFT, -1, font_size, font_secondary_color, outline_size, outline_color); text_pos2 = text_pos; text_pos2.y = end.y < text_pos.y ? MIN(text_pos.y - text_height * 2, end.y + text_height / 2) : MAX(text_pos.y + text_height * 2, end.y + text_height / 2); - viewport->draw_string(font, text_pos2, vformat("%d units", roundf(length_vector.x / grid_step.x)), font_secondary_color); + viewport->draw_string(font, text_pos2, TS->format_number(vformat("%d " + TTR("units"), roundf(length_vector.x / grid_step.x))), HALIGN_LEFT, -1, font_size, font_secondary_color, outline_size, outline_color); } else { - viewport->draw_string(font, text_pos, vformat("%d units", roundf((length_vector / grid_step).length())), font_color); + viewport->draw_string(font, text_pos, TS->format_number(vformat("%d " + TTR("units"), roundf((length_vector / grid_step).length()))), HALIGN_LEFT, -1, font_size, font_color, outline_size, outline_color); } } } else { @@ -3025,10 +3200,10 @@ void CanvasItemEditor::_draw_control_anchors(Control *control) { if (tool == TOOL_SELECT && !Object::cast_to<Container>(control->get_parent())) { // Compute the anchors float anchors_values[4]; - anchors_values[0] = control->get_anchor(MARGIN_LEFT); - anchors_values[1] = control->get_anchor(MARGIN_TOP); - anchors_values[2] = control->get_anchor(MARGIN_RIGHT); - anchors_values[3] = control->get_anchor(MARGIN_BOTTOM); + anchors_values[0] = control->get_anchor(SIDE_LEFT); + anchors_values[1] = control->get_anchor(SIDE_TOP); + anchors_values[2] = control->get_anchor(SIDE_RIGHT); + anchors_values[3] = control->get_anchor(SIDE_BOTTOM); Vector2 anchors_pos[4]; for (int i = 0; i < 4; i++) { @@ -3038,10 +3213,17 @@ void CanvasItemEditor::_draw_control_anchors(Control *control) { // Draw the anchors handles Rect2 anchor_rects[4]; - anchor_rects[0] = Rect2(anchors_pos[0] - anchor_handle->get_size(), anchor_handle->get_size()); - anchor_rects[1] = Rect2(anchors_pos[1] - Vector2(0.0, anchor_handle->get_size().y), Point2(-anchor_handle->get_size().x, anchor_handle->get_size().y)); - anchor_rects[2] = Rect2(anchors_pos[2], -anchor_handle->get_size()); - anchor_rects[3] = Rect2(anchors_pos[3] - Vector2(anchor_handle->get_size().x, 0.0), Point2(anchor_handle->get_size().x, -anchor_handle->get_size().y)); + if (control->is_layout_rtl()) { + anchor_rects[0] = Rect2(anchors_pos[0] - Vector2(0.0, anchor_handle->get_size().y), Point2(-anchor_handle->get_size().x, anchor_handle->get_size().y)); + anchor_rects[1] = Rect2(anchors_pos[1] - anchor_handle->get_size(), anchor_handle->get_size()); + anchor_rects[2] = Rect2(anchors_pos[2] - Vector2(anchor_handle->get_size().x, 0.0), Point2(anchor_handle->get_size().x, -anchor_handle->get_size().y)); + anchor_rects[3] = Rect2(anchors_pos[3], -anchor_handle->get_size()); + } else { + anchor_rects[0] = Rect2(anchors_pos[0] - anchor_handle->get_size(), anchor_handle->get_size()); + anchor_rects[1] = Rect2(anchors_pos[1] - Vector2(0.0, anchor_handle->get_size().y), Point2(-anchor_handle->get_size().x, anchor_handle->get_size().y)); + anchor_rects[2] = Rect2(anchors_pos[2], -anchor_handle->get_size()); + anchor_rects[3] = Rect2(anchors_pos[3] - Vector2(anchor_handle->get_size().x, 0.0), Point2(anchor_handle->get_size().x, -anchor_handle->get_size().y)); + } for (int i = 0; i < 4; i++) { anchor_handle->draw_rect(ci, anchor_rects[i]); @@ -3057,10 +3239,10 @@ void CanvasItemEditor::_draw_control_helpers(Control *control) { // Compute the anchors float anchors_values[4]; - anchors_values[0] = control->get_anchor(MARGIN_LEFT); - anchors_values[1] = control->get_anchor(MARGIN_TOP); - anchors_values[2] = control->get_anchor(MARGIN_RIGHT); - anchors_values[3] = control->get_anchor(MARGIN_BOTTOM); + anchors_values[0] = control->get_anchor(SIDE_LEFT); + anchors_values[1] = control->get_anchor(SIDE_TOP); + anchors_values[2] = control->get_anchor(SIDE_RIGHT); + anchors_values[3] = control->get_anchor(SIDE_BOTTOM); Vector2 anchors[4]; Vector2 anchors_pos[4]; @@ -3113,19 +3295,19 @@ void CanvasItemEditor::_draw_control_helpers(Control *control) { float percent_val; percent_val = anchors_values[(dragged_anchor + 2) % 4] - anchors_values[dragged_anchor]; percent_val = (dragged_anchor >= 2) ? -percent_val : percent_val; - _draw_percentage_at_position(percent_val, (anchors_pos[dragged_anchor] + anchors_pos[(dragged_anchor + 1) % 4]) / 2, (Margin)((dragged_anchor + 1) % 4)); + _draw_percentage_at_position(percent_val, (anchors_pos[dragged_anchor] + anchors_pos[(dragged_anchor + 1) % 4]) / 2, (Side)((dragged_anchor + 1) % 4)); percent_val = anchors_values[(dragged_anchor + 3) % 4] - anchors_values[(dragged_anchor + 1) % 4]; percent_val = ((dragged_anchor + 1) % 4 >= 2) ? -percent_val : percent_val; - _draw_percentage_at_position(percent_val, (anchors_pos[dragged_anchor] + anchors_pos[(dragged_anchor + 3) % 4]) / 2, (Margin)(dragged_anchor)); + _draw_percentage_at_position(percent_val, (anchors_pos[dragged_anchor] + anchors_pos[(dragged_anchor + 3) % 4]) / 2, (Side)(dragged_anchor)); percent_val = anchors_values[(dragged_anchor + 1) % 4]; percent_val = ((dragged_anchor + 1) % 4 >= 2) ? ANCHOR_END - percent_val : percent_val; - _draw_percentage_at_position(percent_val, (line_starts[dragged_anchor] + anchors_pos[dragged_anchor]) / 2, (Margin)(dragged_anchor)); + _draw_percentage_at_position(percent_val, (line_starts[dragged_anchor] + anchors_pos[dragged_anchor]) / 2, (Side)(dragged_anchor)); percent_val = anchors_values[dragged_anchor]; percent_val = (dragged_anchor >= 2) ? ANCHOR_END - percent_val : percent_val; - _draw_percentage_at_position(percent_val, (line_ends[(dragged_anchor + 1) % 4] + anchors_pos[dragged_anchor]) / 2, (Margin)((dragged_anchor + 1) % 4)); + _draw_percentage_at_position(percent_val, (line_ends[(dragged_anchor + 1) % 4] + anchors_pos[dragged_anchor]) / 2, (Side)((dragged_anchor + 1) % 4)); } // Draw the margin values and the node width/height when dragging control side @@ -3135,22 +3317,22 @@ void CanvasItemEditor::_draw_control_helpers(Control *control) { Rect2 parent_rect = control->get_parent_anchorable_rect(); - node_pos_in_parent[0] = control->get_anchor(MARGIN_LEFT) * parent_rect.size.width + control->get_margin(MARGIN_LEFT) + parent_rect.position.x; - node_pos_in_parent[1] = control->get_anchor(MARGIN_TOP) * parent_rect.size.height + control->get_margin(MARGIN_TOP) + parent_rect.position.y; - node_pos_in_parent[2] = control->get_anchor(MARGIN_RIGHT) * parent_rect.size.width + control->get_margin(MARGIN_RIGHT) + parent_rect.position.x; - node_pos_in_parent[3] = control->get_anchor(MARGIN_BOTTOM) * parent_rect.size.height + control->get_margin(MARGIN_BOTTOM) + parent_rect.position.y; + node_pos_in_parent[0] = control->get_anchor(SIDE_LEFT) * parent_rect.size.width + control->get_offset(SIDE_LEFT) + parent_rect.position.x; + node_pos_in_parent[1] = control->get_anchor(SIDE_TOP) * parent_rect.size.height + control->get_offset(SIDE_TOP) + parent_rect.position.y; + node_pos_in_parent[2] = control->get_anchor(SIDE_RIGHT) * parent_rect.size.width + control->get_offset(SIDE_RIGHT) + parent_rect.position.x; + node_pos_in_parent[3] = control->get_anchor(SIDE_BOTTOM) * parent_rect.size.height + control->get_offset(SIDE_BOTTOM) + parent_rect.position.y; Point2 start, end; switch (drag_type) { case DRAG_LEFT: case DRAG_TOP_LEFT: case DRAG_BOTTOM_LEFT: - _draw_margin_at_position(control->get_size().width, parent_transform.xform(Vector2((node_pos_in_parent[0] + node_pos_in_parent[2]) / 2, node_pos_in_parent[3])) + Vector2(0, 5), MARGIN_BOTTOM); + _draw_margin_at_position(control->get_size().width, parent_transform.xform(Vector2((node_pos_in_parent[0] + node_pos_in_parent[2]) / 2, node_pos_in_parent[3])) + Vector2(0, 5), SIDE_BOTTOM); [[fallthrough]]; case DRAG_MOVE: start = Vector2(node_pos_in_parent[0], Math::lerp(node_pos_in_parent[1], node_pos_in_parent[3], ratio)); - end = start - Vector2(control->get_margin(MARGIN_LEFT), 0); - _draw_margin_at_position(control->get_margin(MARGIN_LEFT), parent_transform.xform((start + end) / 2), MARGIN_TOP); + end = start - Vector2(control->get_offset(SIDE_LEFT), 0); + _draw_margin_at_position(control->get_offset(SIDE_LEFT), parent_transform.xform((start + end) / 2), SIDE_TOP); viewport->draw_line(parent_transform.xform(start), parent_transform.xform(end), color_base, Math::round(EDSCALE)); break; default: @@ -3160,12 +3342,12 @@ void CanvasItemEditor::_draw_control_helpers(Control *control) { case DRAG_RIGHT: case DRAG_TOP_RIGHT: case DRAG_BOTTOM_RIGHT: - _draw_margin_at_position(control->get_size().width, parent_transform.xform(Vector2((node_pos_in_parent[0] + node_pos_in_parent[2]) / 2, node_pos_in_parent[3])) + Vector2(0, 5), MARGIN_BOTTOM); + _draw_margin_at_position(control->get_size().width, parent_transform.xform(Vector2((node_pos_in_parent[0] + node_pos_in_parent[2]) / 2, node_pos_in_parent[3])) + Vector2(0, 5), SIDE_BOTTOM); [[fallthrough]]; case DRAG_MOVE: start = Vector2(node_pos_in_parent[2], Math::lerp(node_pos_in_parent[3], node_pos_in_parent[1], ratio)); - end = start - Vector2(control->get_margin(MARGIN_RIGHT), 0); - _draw_margin_at_position(control->get_margin(MARGIN_RIGHT), parent_transform.xform((start + end) / 2), MARGIN_BOTTOM); + end = start - Vector2(control->get_offset(SIDE_RIGHT), 0); + _draw_margin_at_position(control->get_offset(SIDE_RIGHT), parent_transform.xform((start + end) / 2), SIDE_BOTTOM); viewport->draw_line(parent_transform.xform(start), parent_transform.xform(end), color_base, Math::round(EDSCALE)); break; default: @@ -3175,12 +3357,12 @@ void CanvasItemEditor::_draw_control_helpers(Control *control) { case DRAG_TOP: case DRAG_TOP_LEFT: case DRAG_TOP_RIGHT: - _draw_margin_at_position(control->get_size().height, parent_transform.xform(Vector2(node_pos_in_parent[2], (node_pos_in_parent[1] + node_pos_in_parent[3]) / 2)) + Vector2(5, 0), MARGIN_RIGHT); + _draw_margin_at_position(control->get_size().height, parent_transform.xform(Vector2(node_pos_in_parent[2], (node_pos_in_parent[1] + node_pos_in_parent[3]) / 2)) + Vector2(5, 0), SIDE_RIGHT); [[fallthrough]]; case DRAG_MOVE: start = Vector2(Math::lerp(node_pos_in_parent[0], node_pos_in_parent[2], ratio), node_pos_in_parent[1]); - end = start - Vector2(0, control->get_margin(MARGIN_TOP)); - _draw_margin_at_position(control->get_margin(MARGIN_TOP), parent_transform.xform((start + end) / 2), MARGIN_LEFT); + end = start - Vector2(0, control->get_offset(SIDE_TOP)); + _draw_margin_at_position(control->get_offset(SIDE_TOP), parent_transform.xform((start + end) / 2), SIDE_LEFT); viewport->draw_line(parent_transform.xform(start), parent_transform.xform(end), color_base, Math::round(EDSCALE)); break; default: @@ -3190,12 +3372,12 @@ void CanvasItemEditor::_draw_control_helpers(Control *control) { case DRAG_BOTTOM: case DRAG_BOTTOM_LEFT: case DRAG_BOTTOM_RIGHT: - _draw_margin_at_position(control->get_size().height, parent_transform.xform(Vector2(node_pos_in_parent[2], (node_pos_in_parent[1] + node_pos_in_parent[3]) / 2) + Vector2(5, 0)), MARGIN_RIGHT); + _draw_margin_at_position(control->get_size().height, parent_transform.xform(Vector2(node_pos_in_parent[2], (node_pos_in_parent[1] + node_pos_in_parent[3]) / 2) + Vector2(5, 0)), SIDE_RIGHT); [[fallthrough]]; case DRAG_MOVE: start = Vector2(Math::lerp(node_pos_in_parent[2], node_pos_in_parent[0], ratio), node_pos_in_parent[3]); - end = start - Vector2(0, control->get_margin(MARGIN_BOTTOM)); - _draw_margin_at_position(control->get_margin(MARGIN_BOTTOM), parent_transform.xform((start + end) / 2), MARGIN_RIGHT); + end = start - Vector2(0, control->get_offset(SIDE_BOTTOM)); + _draw_margin_at_position(control->get_offset(SIDE_BOTTOM), parent_transform.xform((start + end) / 2), SIDE_RIGHT); viewport->draw_line(parent_transform.xform(start), parent_transform.xform(end), color_base, Math::round(EDSCALE)); break; default: @@ -3250,7 +3432,6 @@ void CanvasItemEditor::_draw_selection() { if (canvas_item->_edit_use_rect()) { Vector2 pre_drag_endpoints[4] = { - pre_drag_xform.xform(se->pre_drag_rect.position), pre_drag_xform.xform(se->pre_drag_rect.position + Vector2(se->pre_drag_rect.size.x, 0)), pre_drag_xform.xform(se->pre_drag_rect.position + se->pre_drag_rect.size), @@ -3332,7 +3513,7 @@ void CanvasItemEditor::_draw_selection() { select_handle->draw(ci, (endpoints[i] + ofs - (select_handle->get_size() / 2)).floor()); ofs = (endpoints[i] + endpoints[next]) / 2; - ofs += (endpoints[next] - endpoints[i]).tangent().normalized() * (select_handle->get_size().width / 2); + ofs += (endpoints[next] - endpoints[i]).orthogonal().normalized() * (select_handle->get_size().width / 2); select_handle->draw(ci, (ofs - (select_handle->get_size() / 2)).floor()); } @@ -3573,7 +3754,7 @@ void CanvasItemEditor::_draw_invisible_nodes_positions(Node *p_node, const Trans Transform2D parent_xform = p_parent_xform; Transform2D canvas_xform = p_canvas_xform; - if (canvas_item && !canvas_item->is_set_as_toplevel()) { + if (canvas_item && !canvas_item->is_set_as_top_level()) { parent_xform = parent_xform * canvas_item->get_transform(); } else { CanvasLayer *cl = Object::cast_to<CanvasLayer>(p_node); @@ -3606,6 +3787,7 @@ void CanvasItemEditor::_draw_hover() { String node_name = hovering_results[i].name; Ref<Font> font = get_theme_font("font", "Label"); + int font_size = get_theme_font_size("font_size", "Label"); Size2 node_name_size = font->get_string_size(node_name); Size2 item_size = Size2(node_icon->get_size().x + 4 + node_name_size.x, MAX(node_icon->get_size().y, node_name_size.y - 3)); @@ -3623,7 +3805,7 @@ void CanvasItemEditor::_draw_hover() { viewport->draw_texture(node_icon, pos, Color(1.0, 1.0, 1.0, 0.5)); // Draw name - viewport->draw_string(font, pos + Point2(node_icon->get_size().x + 4, item_size.y - 3), node_name, Color(1.0, 1.0, 1.0, 0.5)); + viewport->draw_string(font, pos + Point2(node_icon->get_size().x + 4, item_size.y - 3), node_name, HALIGN_LEFT, -1, font_size, Color(1.0, 1.0, 1.0, 0.5)); } } @@ -3642,7 +3824,7 @@ void CanvasItemEditor::_draw_locks_and_groups(Node *p_node, const Transform2D &p Transform2D parent_xform = p_parent_xform; Transform2D canvas_xform = p_canvas_xform; - if (canvas_item && !canvas_item->is_set_as_toplevel()) { + if (canvas_item && !canvas_item->is_set_as_top_level()) { parent_xform = parent_xform * canvas_item->get_transform(); } else { CanvasLayer *cl = Object::cast_to<CanvasLayer>(p_node); @@ -3685,7 +3867,7 @@ bool CanvasItemEditor::_build_bones_list(Node *p_node) { CanvasItem *canvas_item = Object::cast_to<CanvasItem>(p_node); Node *scene = editor->get_edited_scene(); - if (!canvas_item || !canvas_item->is_visible() || (canvas_item != scene && canvas_item->get_owner() != scene && !scene->is_editable_instance(canvas_item->get_owner()))) { + if (!canvas_item || !canvas_item->is_visible() || (canvas_item != scene && canvas_item->get_owner() != scene && canvas_item != scene->get_deepest_editable_node(canvas_item))) { return false; } @@ -3749,7 +3931,7 @@ void CanvasItemEditor::_draw_viewport() { bool all_locked = true; bool all_group = true; List<Node *> selection = editor_selection->get_selected_node_list(); - if (selection.empty()) { + if (selection.is_empty()) { all_locked = false; all_group = false; } else { @@ -3768,32 +3950,32 @@ void CanvasItemEditor::_draw_viewport() { } lock_button->set_visible(!all_locked); - lock_button->set_disabled(selection.empty()); + lock_button->set_disabled(selection.is_empty()); unlock_button->set_visible(all_locked); group_button->set_visible(!all_group); - group_button->set_disabled(selection.empty()); + group_button->set_disabled(selection.is_empty()); ungroup_button->set_visible(all_group); - info_overlay->set_margin(MARGIN_LEFT, (show_rulers ? RULER_WIDTH : 0) + 10); + info_overlay->set_offset(SIDE_LEFT, (show_rulers ? RULER_WIDTH : 0) + 10); _draw_grid(); _draw_ruler_tool(); - _draw_selection(); _draw_axis(); if (editor->get_edited_scene()) { _draw_locks_and_groups(editor->get_edited_scene()); _draw_invisible_nodes_positions(editor->get_edited_scene()); } + _draw_selection(); RID ci = viewport->get_canvas_item(); RenderingServer::get_singleton()->canvas_item_add_set_transform(ci, Transform2D()); EditorPluginList *over_plugin_list = editor->get_editor_plugins_over(); - if (!over_plugin_list->empty()) { + if (!over_plugin_list->is_empty()) { over_plugin_list->forward_canvas_draw_over_viewport(viewport); } EditorPluginList *force_over_plugin_list = editor->get_editor_plugins_force_over(); - if (!force_over_plugin_list->empty()) { + if (!force_over_plugin_list->is_empty()) { force_over_plugin_list->forward_canvas_force_draw_over_viewport(viewport); } @@ -3852,17 +4034,17 @@ void CanvasItemEditor::_notification(int p_what) { Vector2 pivot; pivot = control->get_pivot_offset(); - anchors[MARGIN_LEFT] = control->get_anchor(MARGIN_LEFT); - anchors[MARGIN_RIGHT] = control->get_anchor(MARGIN_RIGHT); - anchors[MARGIN_TOP] = control->get_anchor(MARGIN_TOP); - anchors[MARGIN_BOTTOM] = control->get_anchor(MARGIN_BOTTOM); + anchors[SIDE_LEFT] = control->get_anchor(SIDE_LEFT); + anchors[SIDE_RIGHT] = control->get_anchor(SIDE_RIGHT); + anchors[SIDE_TOP] = control->get_anchor(SIDE_TOP); + anchors[SIDE_BOTTOM] = control->get_anchor(SIDE_BOTTOM); - if (pivot != se->prev_pivot || anchors[MARGIN_LEFT] != se->prev_anchors[MARGIN_LEFT] || anchors[MARGIN_RIGHT] != se->prev_anchors[MARGIN_RIGHT] || anchors[MARGIN_TOP] != se->prev_anchors[MARGIN_TOP] || anchors[MARGIN_BOTTOM] != se->prev_anchors[MARGIN_BOTTOM]) { + if (pivot != se->prev_pivot || anchors[SIDE_LEFT] != se->prev_anchors[SIDE_LEFT] || anchors[SIDE_RIGHT] != se->prev_anchors[SIDE_RIGHT] || anchors[SIDE_TOP] != se->prev_anchors[SIDE_TOP] || anchors[SIDE_BOTTOM] != se->prev_anchors[SIDE_BOTTOM]) { se->prev_pivot = pivot; - se->prev_anchors[MARGIN_LEFT] = anchors[MARGIN_LEFT]; - se->prev_anchors[MARGIN_RIGHT] = anchors[MARGIN_RIGHT]; - se->prev_anchors[MARGIN_TOP] = anchors[MARGIN_TOP]; - se->prev_anchors[MARGIN_BOTTOM] = anchors[MARGIN_BOTTOM]; + se->prev_anchors[SIDE_LEFT] = anchors[SIDE_LEFT]; + se->prev_anchors[SIDE_RIGHT] = anchors[SIDE_RIGHT]; + se->prev_anchors[SIDE_TOP] = anchors[SIDE_TOP]; + se->prev_anchors[SIDE_BOTTOM] = anchors[SIDE_BOTTOM]; viewport->update(); } nb_control++; @@ -3933,8 +4115,8 @@ void CanvasItemEditor::_notification(int p_what) { if (p_what == NOTIFICATION_ENTER_TREE) { select_sb->set_texture(get_theme_icon("EditorRect2D", "EditorIcons")); for (int i = 0; i < 4; i++) { - select_sb->set_margin_size(Margin(i), 4); - select_sb->set_default_margin(Margin(i), 4); + select_sb->set_margin_size(Side(i), 4); + select_sb->set_default_margin(Side(i), 4); } AnimationPlayerEditor::singleton->get_track_editor()->connect("visibility_changed", callable_mp(this, &CanvasItemEditor::_keying_changed)); @@ -3959,7 +4141,7 @@ void CanvasItemEditor::_notification(int p_what) { rotate_button->set_icon(get_theme_icon("ToolRotate", "EditorIcons")); smart_snap_button->set_icon(get_theme_icon("Snap", "EditorIcons")); grid_snap_button->set_icon(get_theme_icon("SnapGrid", "EditorIcons")); - snap_config_menu->set_icon(get_theme_icon("GuiTabMenu", "EditorIcons")); + snap_config_menu->set_icon(get_theme_icon("GuiTabMenuHl", "EditorIcons")); skeleton_menu->set_icon(get_theme_icon("Bone", "EditorIcons")); override_camera_button->set_icon(get_theme_icon("Camera2D", "EditorIcons")); pan_button->set_icon(get_theme_icon("ToolPan", "EditorIcons")); @@ -3976,7 +4158,13 @@ void CanvasItemEditor::_notification(int p_what) { key_scale_button->set_icon(get_theme_icon("KeyScale", "EditorIcons")); key_insert_button->set_icon(get_theme_icon("Key", "EditorIcons")); key_auto_insert_button->set_icon(get_theme_icon("AutoKey", "EditorIcons")); - animation_menu->set_icon(get_theme_icon("GuiTabMenu", "EditorIcons")); + // Use a different color for the active autokey icon to make them easier + // to distinguish from the other key icons at the top. On a light theme, + // the icon will be dark, so we need to lighten it before blending it + // with the red color. + const Color key_auto_color = EditorSettings::get_singleton()->is_dark_theme() ? Color(1, 1, 1) : Color(4.25, 4.25, 4.25); + key_auto_insert_button->add_theme_color_override("icon_pressed_color", key_auto_color.lerp(Color(1, 0, 0), 0.55)); + animation_menu->set_icon(get_theme_icon("GuiTabMenuHl", "EditorIcons")); zoom_minus->set_icon(get_theme_icon("ZoomLess", "EditorIcons")); zoom_plus->set_icon(get_theme_icon("ZoomMore", "EditorIcons")); @@ -3985,26 +4173,26 @@ void CanvasItemEditor::_notification(int p_what) { PopupMenu *p = presets_menu->get_popup(); p->clear(); - p->add_icon_item(get_theme_icon("ControlAlignTopLeft", "EditorIcons"), TTR("Top Left"), ANCHORS_AND_MARGINS_PRESET_TOP_LEFT); - p->add_icon_item(get_theme_icon("ControlAlignTopRight", "EditorIcons"), TTR("Top Right"), ANCHORS_AND_MARGINS_PRESET_TOP_RIGHT); - p->add_icon_item(get_theme_icon("ControlAlignBottomRight", "EditorIcons"), TTR("Bottom Right"), ANCHORS_AND_MARGINS_PRESET_BOTTOM_RIGHT); - p->add_icon_item(get_theme_icon("ControlAlignBottomLeft", "EditorIcons"), TTR("Bottom Left"), ANCHORS_AND_MARGINS_PRESET_BOTTOM_LEFT); + p->add_icon_item(get_theme_icon("ControlAlignTopLeft", "EditorIcons"), TTR("Top Left"), ANCHORS_AND_OFFSETS_PRESET_TOP_LEFT); + p->add_icon_item(get_theme_icon("ControlAlignTopRight", "EditorIcons"), TTR("Top Right"), ANCHORS_AND_OFFSETS_PRESET_TOP_RIGHT); + p->add_icon_item(get_theme_icon("ControlAlignBottomRight", "EditorIcons"), TTR("Bottom Right"), ANCHORS_AND_OFFSETS_PRESET_BOTTOM_RIGHT); + p->add_icon_item(get_theme_icon("ControlAlignBottomLeft", "EditorIcons"), TTR("Bottom Left"), ANCHORS_AND_OFFSETS_PRESET_BOTTOM_LEFT); p->add_separator(); - p->add_icon_item(get_theme_icon("ControlAlignLeftCenter", "EditorIcons"), TTR("Center Left"), ANCHORS_AND_MARGINS_PRESET_CENTER_LEFT); - p->add_icon_item(get_theme_icon("ControlAlignTopCenter", "EditorIcons"), TTR("Center Top"), ANCHORS_AND_MARGINS_PRESET_CENTER_TOP); - p->add_icon_item(get_theme_icon("ControlAlignRightCenter", "EditorIcons"), TTR("Center Right"), ANCHORS_AND_MARGINS_PRESET_CENTER_RIGHT); - p->add_icon_item(get_theme_icon("ControlAlignBottomCenter", "EditorIcons"), TTR("Center Bottom"), ANCHORS_AND_MARGINS_PRESET_CENTER_BOTTOM); - p->add_icon_item(get_theme_icon("ControlAlignCenter", "EditorIcons"), TTR("Center"), ANCHORS_AND_MARGINS_PRESET_CENTER); + p->add_icon_item(get_theme_icon("ControlAlignLeftCenter", "EditorIcons"), TTR("Center Left"), ANCHORS_AND_OFFSETS_PRESET_CENTER_LEFT); + p->add_icon_item(get_theme_icon("ControlAlignTopCenter", "EditorIcons"), TTR("Center Top"), ANCHORS_AND_OFFSETS_PRESET_CENTER_TOP); + p->add_icon_item(get_theme_icon("ControlAlignRightCenter", "EditorIcons"), TTR("Center Right"), ANCHORS_AND_OFFSETS_PRESET_CENTER_RIGHT); + p->add_icon_item(get_theme_icon("ControlAlignBottomCenter", "EditorIcons"), TTR("Center Bottom"), ANCHORS_AND_OFFSETS_PRESET_CENTER_BOTTOM); + p->add_icon_item(get_theme_icon("ControlAlignCenter", "EditorIcons"), TTR("Center"), ANCHORS_AND_OFFSETS_PRESET_CENTER); p->add_separator(); - p->add_icon_item(get_theme_icon("ControlAlignLeftWide", "EditorIcons"), TTR("Left Wide"), ANCHORS_AND_MARGINS_PRESET_LEFT_WIDE); - p->add_icon_item(get_theme_icon("ControlAlignTopWide", "EditorIcons"), TTR("Top Wide"), ANCHORS_AND_MARGINS_PRESET_TOP_WIDE); - p->add_icon_item(get_theme_icon("ControlAlignRightWide", "EditorIcons"), TTR("Right Wide"), ANCHORS_AND_MARGINS_PRESET_RIGHT_WIDE); - p->add_icon_item(get_theme_icon("ControlAlignBottomWide", "EditorIcons"), TTR("Bottom Wide"), ANCHORS_AND_MARGINS_PRESET_BOTTOM_WIDE); - p->add_icon_item(get_theme_icon("ControlVcenterWide", "EditorIcons"), TTR("VCenter Wide"), ANCHORS_AND_MARGINS_PRESET_VCENTER_WIDE); - p->add_icon_item(get_theme_icon("ControlHcenterWide", "EditorIcons"), TTR("HCenter Wide"), ANCHORS_AND_MARGINS_PRESET_HCENTER_WIDE); + p->add_icon_item(get_theme_icon("ControlAlignLeftWide", "EditorIcons"), TTR("Left Wide"), ANCHORS_AND_OFFSETS_PRESET_LEFT_WIDE); + p->add_icon_item(get_theme_icon("ControlAlignTopWide", "EditorIcons"), TTR("Top Wide"), ANCHORS_AND_OFFSETS_PRESET_TOP_WIDE); + p->add_icon_item(get_theme_icon("ControlAlignRightWide", "EditorIcons"), TTR("Right Wide"), ANCHORS_AND_OFFSETS_PRESET_RIGHT_WIDE); + p->add_icon_item(get_theme_icon("ControlAlignBottomWide", "EditorIcons"), TTR("Bottom Wide"), ANCHORS_AND_OFFSETS_PRESET_BOTTOM_WIDE); + p->add_icon_item(get_theme_icon("ControlVcenterWide", "EditorIcons"), TTR("VCenter Wide"), ANCHORS_AND_OFFSETS_PRESET_VCENTER_WIDE); + p->add_icon_item(get_theme_icon("ControlHcenterWide", "EditorIcons"), TTR("HCenter Wide"), ANCHORS_AND_OFFSETS_PRESET_HCENTER_WIDE); p->add_separator(); - p->add_icon_item(get_theme_icon("ControlAlignWide", "EditorIcons"), TTR("Full Rect"), ANCHORS_AND_MARGINS_PRESET_WIDE); - p->add_icon_item(get_theme_icon("Anchor", "EditorIcons"), TTR("Keep Ratio"), ANCHORS_AND_MARGINS_PRESET_KEEP_RATIO); + p->add_icon_item(get_theme_icon("ControlAlignWide", "EditorIcons"), TTR("Full Rect"), ANCHORS_AND_OFFSETS_PRESET_WIDE); + p->add_icon_item(get_theme_icon("Anchor", "EditorIcons"), TTR("Keep Ratio"), ANCHORS_AND_OFFSETS_PRESET_KEEP_RATIO); p->add_separator(); p->add_submenu_item(TTR("Anchors only"), "Anchors"); p->set_item_icon(21, get_theme_icon("Anchor", "EditorIcons")); @@ -4198,8 +4386,13 @@ void CanvasItemEditor::_update_scrollbars() { } // Move and resize the scrollbars, avoiding overlap. - v_scroll->set_begin(Point2(size.width - vmin.width, (show_rulers) ? RULER_WIDTH : 0)); - v_scroll->set_end(Point2(size.width, size.height - (h_scroll->is_visible() ? hmin.height : 0))); + if (is_layout_rtl()) { + v_scroll->set_begin(Point2(0, (show_rulers) ? RULER_WIDTH : 0)); + v_scroll->set_end(Point2(vmin.width, size.height - (h_scroll->is_visible() ? hmin.height : 0))); + } else { + v_scroll->set_begin(Point2(size.width - vmin.width, (show_rulers) ? RULER_WIDTH : 0)); + v_scroll->set_end(Point2(size.width, size.height - (h_scroll->is_visible() ? hmin.height : 0))); + } h_scroll->set_begin(Point2((show_rulers) ? RULER_WIDTH : 0, size.height - hmin.height)); h_scroll->set_end(Point2(size.width - (v_scroll->is_visible() ? vmin.width : 0), size.height)); @@ -4218,7 +4411,7 @@ void CanvasItemEditor::_popup_warning_depop(Control *p_control) { timer->queue_delete(); p_control->hide(); popup_temporarily_timers.erase(p_control); - info_overlay->set_margin(MARGIN_LEFT, (show_rulers ? RULER_WIDTH : 0) + 10); + info_overlay->set_offset(SIDE_LEFT, (show_rulers ? RULER_WIDTH : 0) + 10); } void CanvasItemEditor::_popup_warning_temporarily(Control *p_control, const float p_duration) { @@ -4236,7 +4429,7 @@ void CanvasItemEditor::_popup_warning_temporarily(Control *p_control, const floa timer->start(p_duration); p_control->show(); - info_overlay->set_margin(MARGIN_LEFT, (show_rulers ? RULER_WIDTH : 0) + 10); + info_overlay->set_offset(SIDE_LEFT, (show_rulers ? RULER_WIDTH : 0) + 10); } void CanvasItemEditor::_update_scroll(float) { @@ -4249,10 +4442,10 @@ void CanvasItemEditor::_update_scroll(float) { viewport->update(); } -void CanvasItemEditor::_set_anchors_and_margins_preset(Control::LayoutPreset p_preset) { +void CanvasItemEditor::_set_anchors_and_offsets_preset(Control::LayoutPreset p_preset) { List<Node *> selection = editor_selection->get_selected_node_list(); - undo_redo->create_action(TTR("Change Anchors and Margins")); + undo_redo->create_action(TTR("Change Anchors and Offsets")); for (List<Node *>::Element *E = selection.front(); E; E = E->next()) { Control *control = Object::cast_to<Control>(E->get()); @@ -4268,7 +4461,7 @@ void CanvasItemEditor::_set_anchors_and_margins_preset(Control::LayoutPreset p_p case PRESET_CENTER_RIGHT: case PRESET_CENTER_BOTTOM: case PRESET_CENTER: - undo_redo->add_do_method(control, "set_margins_preset", p_preset, Control::PRESET_MODE_KEEP_SIZE); + undo_redo->add_do_method(control, "set_offsets_preset", p_preset, Control::PRESET_MODE_KEEP_SIZE); break; case PRESET_LEFT_WIDE: case PRESET_TOP_WIDE: @@ -4277,7 +4470,7 @@ void CanvasItemEditor::_set_anchors_and_margins_preset(Control::LayoutPreset p_p case PRESET_VCENTER_WIDE: case PRESET_HCENTER_WIDE: case PRESET_WIDE: - undo_redo->add_do_method(control, "set_margins_preset", p_preset, Control::PRESET_MODE_MINSIZE); + undo_redo->add_do_method(control, "set_offsets_preset", p_preset, Control::PRESET_MODE_MINSIZE); break; } undo_redo->add_undo_method(control, "_edit_set_state", control->_edit_get_state()); @@ -4290,20 +4483,20 @@ void CanvasItemEditor::_set_anchors_and_margins_preset(Control::LayoutPreset p_p anchor_mode_button->set_pressed(anchors_mode); } -void CanvasItemEditor::_set_anchors_and_margins_to_keep_ratio() { +void CanvasItemEditor::_set_anchors_and_offsets_to_keep_ratio() { List<Node *> selection = editor_selection->get_selected_node_list(); - undo_redo->create_action(TTR("Change Anchors and Margins")); + undo_redo->create_action(TTR("Change Anchors and Offsets")); for (List<Node *>::Element *E = selection.front(); E; E = E->next()) { Control *control = Object::cast_to<Control>(E->get()); if (control) { Point2 top_left_anchor = _position_to_anchor(control, Point2()); Point2 bottom_right_anchor = _position_to_anchor(control, control->get_size()); - undo_redo->add_do_method(control, "set_anchor", MARGIN_LEFT, top_left_anchor.x, false, true); - undo_redo->add_do_method(control, "set_anchor", MARGIN_RIGHT, bottom_right_anchor.x, false, true); - undo_redo->add_do_method(control, "set_anchor", MARGIN_TOP, top_left_anchor.y, false, true); - undo_redo->add_do_method(control, "set_anchor", MARGIN_BOTTOM, bottom_right_anchor.y, false, true); + undo_redo->add_do_method(control, "set_anchor", SIDE_LEFT, top_left_anchor.x, false, true); + undo_redo->add_do_method(control, "set_anchor", SIDE_RIGHT, bottom_right_anchor.x, false, true); + undo_redo->add_do_method(control, "set_anchor", SIDE_TOP, top_left_anchor.y, false, true); + undo_redo->add_do_method(control, "set_anchor", SIDE_BOTTOM, bottom_right_anchor.y, false, true); undo_redo->add_do_method(control, "set_meta", "_edit_use_anchors_", true); bool use_anchors = control->has_meta("_edit_use_anchors_") && control->get_meta("_edit_use_anchors_"); @@ -4333,8 +4526,37 @@ void CanvasItemEditor::_set_anchors_preset(Control::LayoutPreset p_preset) { undo_redo->commit_action(); } +float CanvasItemEditor::_get_next_zoom_value(int p_increment_count) const { + // Base increment factor defined as the twelveth root of two. + // This allow a smooth geometric evolution of the zoom, with the advantage of + // visiting all integer power of two scale factors. + // note: this is analogous to the 'semitones' interval in the music world + // In order to avoid numerical imprecisions, we compute and edit a zoom index + // with the following relation: zoom = 2 ^ (index / 12) + + if (zoom < CMP_EPSILON || p_increment_count == 0) { + return 1.f; + } + + // Remove Editor scale from the index computation + float zoom_noscale = zoom / MAX(1, EDSCALE); + + // zoom = 2**(index/12) => log2(zoom) = index/12 + float closest_zoom_index = Math::round(Math::log(zoom_noscale) * 12.f / Math::log(2.f)); + + float new_zoom_index = closest_zoom_index + p_increment_count; + float new_zoom = Math::pow(2.f, new_zoom_index / 12.f); + + // Restore Editor scale transformation + new_zoom *= MAX(1, EDSCALE); + + return new_zoom; +} + void CanvasItemEditor::_zoom_on_position(float p_zoom, Point2 p_position) { - if (p_zoom < MIN_ZOOM || p_zoom > MAX_ZOOM) { + p_zoom = CLAMP(p_zoom, MIN_ZOOM, MAX_ZOOM); + + if (p_zoom == zoom) { return; } @@ -4367,16 +4589,16 @@ void CanvasItemEditor::_update_zoom_label() { // even if their display doesn't have a particularly low DPI. if (zoom >= 10) { // Don't show a decimal when the zoom level is higher than 1000 %. - zoom_text = rtos(Math::round((zoom / MAX(1, EDSCALE)) * 100)) + " %"; + zoom_text = TS->format_number(rtos(Math::round((zoom / MAX(1, EDSCALE)) * 100))) + " " + TS->percent_sign(); } else { - zoom_text = rtos(Math::stepify((zoom / MAX(1, EDSCALE)) * 100, 0.1)) + " %"; + zoom_text = TS->format_number(rtos(Math::snapped((zoom / MAX(1, EDSCALE)) * 100, 0.1))) + " " + TS->percent_sign(); } zoom_reset->set_text(zoom_text); } void CanvasItemEditor::_button_zoom_minus() { - _zoom_on_position(zoom / Math_SQRT2, viewport_scrollable->get_size() / 2.0); + _zoom_on_position(_get_next_zoom_value(-6), viewport_scrollable->get_size() / 2.0); } void CanvasItemEditor::_button_zoom_reset() { @@ -4384,7 +4606,7 @@ void CanvasItemEditor::_button_zoom_reset() { } void CanvasItemEditor::_button_zoom_plus() { - _zoom_on_position(zoom * Math_SQRT2, viewport_scrollable->get_size() / 2.0); + _zoom_on_position(_get_next_zoom_value(6), viewport_scrollable->get_size() / 2.0); } void CanvasItemEditor::_button_toggle_smart_snap(bool p_status) { @@ -4408,13 +4630,19 @@ void CanvasItemEditor::_button_override_camera(bool p_pressed) { } void CanvasItemEditor::_button_tool_select(int p_index) { - ToolButton *tb[TOOL_MAX] = { select_button, list_select_button, move_button, scale_button, rotate_button, pivot_button, pan_button, ruler_button }; + Button *tb[TOOL_MAX] = { select_button, list_select_button, move_button, scale_button, rotate_button, pivot_button, pan_button, ruler_button }; for (int i = 0; i < TOOL_MAX; i++) { tb[i]->set_pressed(i == p_index); } tool = (Tool)p_index; + viewport->update(); + _update_cursor(); + + // Request immediate refresh of cursor when using hot-keys to switch between tools + DisplayServer::CursorShape ds_cursor_shape = (DisplayServer::CursorShape)viewport->get_default_cursor_shape(); + DisplayServer::get_singleton()->cursor_set_shape(ds_cursor_shape); } void CanvasItemEditor::_insert_animation_keys(bool p_location, bool p_rotation, bool p_scale, bool p_on_existing) { @@ -4721,56 +4949,56 @@ void CanvasItemEditor::_popup_callback(int p_op) { undo_redo->add_undo_method(viewport, "update", Variant()); undo_redo->commit_action(); } break; - case ANCHORS_AND_MARGINS_PRESET_TOP_LEFT: { - _set_anchors_and_margins_preset(PRESET_TOP_LEFT); + case ANCHORS_AND_OFFSETS_PRESET_TOP_LEFT: { + _set_anchors_and_offsets_preset(PRESET_TOP_LEFT); } break; - case ANCHORS_AND_MARGINS_PRESET_TOP_RIGHT: { - _set_anchors_and_margins_preset(PRESET_TOP_RIGHT); + case ANCHORS_AND_OFFSETS_PRESET_TOP_RIGHT: { + _set_anchors_and_offsets_preset(PRESET_TOP_RIGHT); } break; - case ANCHORS_AND_MARGINS_PRESET_BOTTOM_LEFT: { - _set_anchors_and_margins_preset(PRESET_BOTTOM_LEFT); + case ANCHORS_AND_OFFSETS_PRESET_BOTTOM_LEFT: { + _set_anchors_and_offsets_preset(PRESET_BOTTOM_LEFT); } break; - case ANCHORS_AND_MARGINS_PRESET_BOTTOM_RIGHT: { - _set_anchors_and_margins_preset(PRESET_BOTTOM_RIGHT); + case ANCHORS_AND_OFFSETS_PRESET_BOTTOM_RIGHT: { + _set_anchors_and_offsets_preset(PRESET_BOTTOM_RIGHT); } break; - case ANCHORS_AND_MARGINS_PRESET_CENTER_LEFT: { - _set_anchors_and_margins_preset(PRESET_CENTER_LEFT); + case ANCHORS_AND_OFFSETS_PRESET_CENTER_LEFT: { + _set_anchors_and_offsets_preset(PRESET_CENTER_LEFT); } break; - case ANCHORS_AND_MARGINS_PRESET_CENTER_RIGHT: { - _set_anchors_and_margins_preset(PRESET_CENTER_RIGHT); + case ANCHORS_AND_OFFSETS_PRESET_CENTER_RIGHT: { + _set_anchors_and_offsets_preset(PRESET_CENTER_RIGHT); } break; - case ANCHORS_AND_MARGINS_PRESET_CENTER_TOP: { - _set_anchors_and_margins_preset(PRESET_CENTER_TOP); + case ANCHORS_AND_OFFSETS_PRESET_CENTER_TOP: { + _set_anchors_and_offsets_preset(PRESET_CENTER_TOP); } break; - case ANCHORS_AND_MARGINS_PRESET_CENTER_BOTTOM: { - _set_anchors_and_margins_preset(PRESET_CENTER_BOTTOM); + case ANCHORS_AND_OFFSETS_PRESET_CENTER_BOTTOM: { + _set_anchors_and_offsets_preset(PRESET_CENTER_BOTTOM); } break; - case ANCHORS_AND_MARGINS_PRESET_CENTER: { - _set_anchors_and_margins_preset(PRESET_CENTER); + case ANCHORS_AND_OFFSETS_PRESET_CENTER: { + _set_anchors_and_offsets_preset(PRESET_CENTER); } break; - case ANCHORS_AND_MARGINS_PRESET_TOP_WIDE: { - _set_anchors_and_margins_preset(PRESET_TOP_WIDE); + case ANCHORS_AND_OFFSETS_PRESET_TOP_WIDE: { + _set_anchors_and_offsets_preset(PRESET_TOP_WIDE); } break; - case ANCHORS_AND_MARGINS_PRESET_LEFT_WIDE: { - _set_anchors_and_margins_preset(PRESET_LEFT_WIDE); + case ANCHORS_AND_OFFSETS_PRESET_LEFT_WIDE: { + _set_anchors_and_offsets_preset(PRESET_LEFT_WIDE); } break; - case ANCHORS_AND_MARGINS_PRESET_RIGHT_WIDE: { - _set_anchors_and_margins_preset(PRESET_RIGHT_WIDE); + case ANCHORS_AND_OFFSETS_PRESET_RIGHT_WIDE: { + _set_anchors_and_offsets_preset(PRESET_RIGHT_WIDE); } break; - case ANCHORS_AND_MARGINS_PRESET_BOTTOM_WIDE: { - _set_anchors_and_margins_preset(PRESET_BOTTOM_WIDE); + case ANCHORS_AND_OFFSETS_PRESET_BOTTOM_WIDE: { + _set_anchors_and_offsets_preset(PRESET_BOTTOM_WIDE); } break; - case ANCHORS_AND_MARGINS_PRESET_VCENTER_WIDE: { - _set_anchors_and_margins_preset(PRESET_VCENTER_WIDE); + case ANCHORS_AND_OFFSETS_PRESET_VCENTER_WIDE: { + _set_anchors_and_offsets_preset(PRESET_VCENTER_WIDE); } break; - case ANCHORS_AND_MARGINS_PRESET_HCENTER_WIDE: { - _set_anchors_and_margins_preset(PRESET_HCENTER_WIDE); + case ANCHORS_AND_OFFSETS_PRESET_HCENTER_WIDE: { + _set_anchors_and_offsets_preset(PRESET_HCENTER_WIDE); } break; - case ANCHORS_AND_MARGINS_PRESET_WIDE: { - _set_anchors_and_margins_preset(Control::PRESET_WIDE); + case ANCHORS_AND_OFFSETS_PRESET_WIDE: { + _set_anchors_and_offsets_preset(Control::PRESET_WIDE); } break; - case ANCHORS_AND_MARGINS_PRESET_KEEP_RATIO: { - _set_anchors_and_margins_to_keep_ratio(); + case ANCHORS_AND_OFFSETS_PRESET_KEEP_RATIO: { + _set_anchors_and_offsets_to_keep_ratio(); } break; case ANCHORS_PRESET_TOP_LEFT: { @@ -5359,12 +5587,12 @@ void CanvasItemEditor::add_control_to_info_overlay(Control *p_control) { p_control->set_h_size_flags(p_control->get_h_size_flags() & ~Control::SIZE_EXPAND_FILL); info_overlay->add_child(p_control); - info_overlay->set_margin(MARGIN_LEFT, (show_rulers ? RULER_WIDTH : 0) + 10); + info_overlay->set_offset(SIDE_LEFT, (show_rulers ? RULER_WIDTH : 0) + 10); } void CanvasItemEditor::remove_control_from_info_overlay(Control *p_control) { info_overlay->remove_child(p_control); - info_overlay->set_margin(MARGIN_LEFT, (show_rulers ? RULER_WIDTH : 0) + 10); + info_overlay->set_offset(SIDE_LEFT, (show_rulers ? RULER_WIDTH : 0) + 10); } void CanvasItemEditor::add_control_to_menu_panel(Control *p_control) { @@ -5410,7 +5638,7 @@ CanvasItemEditor::CanvasItemEditor(EditorNode *p_editor) { primary_grid_steps = 8; // A power-of-two value works better as a default grid_step_multiplier = 0; snap_rotation_offset = 0; - snap_rotation_step = 15 / (180 / Math_PI); + snap_rotation_step = Math::deg2rad(15.0); snap_scale_step = 0.1f; smart_snap_active = false; grid_snap_active = false; @@ -5461,7 +5689,7 @@ CanvasItemEditor::CanvasItemEditor(EditorNode *p_editor) { hb = memnew(HBoxContainer); add_child(hb); - hb->set_anchors_and_margins_preset(Control::PRESET_WIDE); + hb->set_anchors_and_offsets_preset(Control::PRESET_WIDE); bottom_split = memnew(VSplitContainer); add_child(bottom_split); @@ -5482,7 +5710,7 @@ CanvasItemEditor::CanvasItemEditor(EditorNode *p_editor) { SubViewportContainer *scene_tree = memnew(SubViewportContainer); viewport_scrollable->add_child(scene_tree); scene_tree->set_stretch(true); - scene_tree->set_anchors_and_margins_preset(Control::PRESET_WIDE); + scene_tree->set_anchors_and_offsets_preset(Control::PRESET_WIDE); scene_tree->add_child(p_editor->get_scene_root()); controls_vb = memnew(VBoxContainer); @@ -5496,16 +5724,16 @@ CanvasItemEditor::CanvasItemEditor(EditorNode *p_editor) { viewport = memnew(CanvasItemEditorViewport(p_editor, this)); viewport_scrollable->add_child(viewport); viewport->set_mouse_filter(MOUSE_FILTER_PASS); - viewport->set_anchors_and_margins_preset(Control::PRESET_WIDE); + viewport->set_anchors_and_offsets_preset(Control::PRESET_WIDE); viewport->set_clip_contents(true); viewport->set_focus_mode(FOCUS_ALL); viewport->connect("draw", callable_mp(this, &CanvasItemEditor::_draw_viewport)); viewport->connect("gui_input", callable_mp(this, &CanvasItemEditor::_gui_input_viewport)); info_overlay = memnew(VBoxContainer); - info_overlay->set_anchors_and_margins_preset(Control::PRESET_BOTTOM_LEFT); - info_overlay->set_margin(MARGIN_LEFT, 10); - info_overlay->set_margin(MARGIN_BOTTOM, -15); + info_overlay->set_anchors_and_offsets_preset(Control::PRESET_BOTTOM_LEFT); + info_overlay->set_offset(SIDE_LEFT, 10); + info_overlay->set_offset(SIDE_BOTTOM, -15); info_overlay->set_v_grow_direction(Control::GROW_DIRECTION_BEGIN); info_overlay->add_theme_constant_override("separation", 10); viewport_scrollable->add_child(info_overlay); @@ -5524,6 +5752,7 @@ CanvasItemEditor::CanvasItemEditor(EditorNode *p_editor) { warning_child_of_container->set_text(TTR("Warning: Children of a container get their position and size determined only by their parent.")); warning_child_of_container->add_theme_color_override("font_color", EditorNode::get_singleton()->get_gui_base()->get_theme_color("warning_color", "Editor")); warning_child_of_container->add_theme_font_override("font", EditorNode::get_singleton()->get_gui_base()->get_theme_font("main", "EditorFonts")); + warning_child_of_container->add_theme_font_size_override("font_size", EditorNode::get_singleton()->get_gui_base()->get_theme_font_size("main_size", "EditorFonts")); add_control_to_info_overlay(warning_child_of_container); h_scroll = memnew(HScrollBar); @@ -5538,104 +5767,133 @@ CanvasItemEditor::CanvasItemEditor(EditorNode *p_editor) { viewport->add_child(controls_vb); - zoom_minus = memnew(ToolButton); + zoom_minus = memnew(Button); + zoom_minus->set_flat(true); zoom_hb->add_child(zoom_minus); zoom_minus->connect("pressed", callable_mp(this, &CanvasItemEditor::_button_zoom_minus)); zoom_minus->set_shortcut(ED_SHORTCUT("canvas_item_editor/zoom_minus", TTR("Zoom Out"), KEY_MASK_CMD | KEY_MINUS)); + zoom_minus->set_shortcut_context(this); zoom_minus->set_focus_mode(FOCUS_NONE); - zoom_reset = memnew(ToolButton); + zoom_reset = memnew(Button); + zoom_reset->set_flat(true); zoom_hb->add_child(zoom_reset); + zoom_reset->add_theme_constant_override("outline_size", 1); + zoom_reset->add_theme_color_override("font_outline_color", Color(0, 0, 0)); + zoom_reset->add_theme_color_override("font_color", Color(1, 1, 1)); zoom_reset->connect("pressed", callable_mp(this, &CanvasItemEditor::_button_zoom_reset)); zoom_reset->set_shortcut(ED_SHORTCUT("canvas_item_editor/zoom_reset", TTR("Zoom Reset"), KEY_MASK_CMD | KEY_0)); + zoom_reset->set_shortcut_context(this); zoom_reset->set_focus_mode(FOCUS_NONE); zoom_reset->set_text_align(Button::TextAlign::ALIGN_CENTER); // Prevent the button's size from changing when the text size changes zoom_reset->set_custom_minimum_size(Size2(75 * EDSCALE, 0)); - zoom_plus = memnew(ToolButton); + zoom_plus = memnew(Button); + zoom_plus->set_flat(true); zoom_hb->add_child(zoom_plus); zoom_plus->connect("pressed", callable_mp(this, &CanvasItemEditor::_button_zoom_plus)); zoom_plus->set_shortcut(ED_SHORTCUT("canvas_item_editor/zoom_plus", TTR("Zoom In"), KEY_MASK_CMD | KEY_EQUAL)); // Usually direct access key for PLUS + zoom_plus->set_shortcut_context(this); zoom_plus->set_focus_mode(FOCUS_NONE); updating_scroll = false; - select_button = memnew(ToolButton); + select_button = memnew(Button); + select_button->set_flat(true); hb->add_child(select_button); select_button->set_toggle_mode(true); select_button->connect("pressed", callable_mp(this, &CanvasItemEditor::_button_tool_select), make_binds(TOOL_SELECT)); select_button->set_pressed(true); select_button->set_shortcut(ED_SHORTCUT("canvas_item_editor/select_mode", TTR("Select Mode"), KEY_Q)); + select_button->set_shortcut_context(this); select_button->set_tooltip(keycode_get_string(KEY_MASK_CMD) + TTR("Drag: Rotate") + "\n" + TTR("Alt+Drag: Move") + "\n" + TTR("Press 'v' to Change Pivot, 'Shift+v' to Drag Pivot (while moving).") + "\n" + TTR("Alt+RMB: Depth list selection")); hb->add_child(memnew(VSeparator)); - move_button = memnew(ToolButton); + move_button = memnew(Button); + move_button->set_flat(true); hb->add_child(move_button); move_button->set_toggle_mode(true); move_button->connect("pressed", callable_mp(this, &CanvasItemEditor::_button_tool_select), make_binds(TOOL_MOVE)); move_button->set_shortcut(ED_SHORTCUT("canvas_item_editor/move_mode", TTR("Move Mode"), KEY_W)); + move_button->set_shortcut_context(this); move_button->set_tooltip(TTR("Move Mode")); - rotate_button = memnew(ToolButton); + rotate_button = memnew(Button); + rotate_button->set_flat(true); hb->add_child(rotate_button); rotate_button->set_toggle_mode(true); rotate_button->connect("pressed", callable_mp(this, &CanvasItemEditor::_button_tool_select), make_binds(TOOL_ROTATE)); rotate_button->set_shortcut(ED_SHORTCUT("canvas_item_editor/rotate_mode", TTR("Rotate Mode"), KEY_E)); + rotate_button->set_shortcut_context(this); rotate_button->set_tooltip(TTR("Rotate Mode")); - scale_button = memnew(ToolButton); + scale_button = memnew(Button); + scale_button->set_flat(true); hb->add_child(scale_button); scale_button->set_toggle_mode(true); scale_button->connect("pressed", callable_mp(this, &CanvasItemEditor::_button_tool_select), make_binds(TOOL_SCALE)); scale_button->set_shortcut(ED_SHORTCUT("canvas_item_editor/scale_mode", TTR("Scale Mode"), KEY_S)); + scale_button->set_shortcut_context(this); scale_button->set_tooltip(TTR("Scale Mode")); hb->add_child(memnew(VSeparator)); - list_select_button = memnew(ToolButton); + list_select_button = memnew(Button); + list_select_button->set_flat(true); hb->add_child(list_select_button); list_select_button->set_toggle_mode(true); list_select_button->connect("pressed", callable_mp(this, &CanvasItemEditor::_button_tool_select), make_binds(TOOL_LIST_SELECT)); list_select_button->set_tooltip(TTR("Show a list of all objects at the position clicked\n(same as Alt+RMB in select mode).")); - pivot_button = memnew(ToolButton); + pivot_button = memnew(Button); + pivot_button->set_flat(true); hb->add_child(pivot_button); pivot_button->set_toggle_mode(true); pivot_button->connect("pressed", callable_mp(this, &CanvasItemEditor::_button_tool_select), make_binds(TOOL_EDIT_PIVOT)); pivot_button->set_tooltip(TTR("Click to change object's rotation pivot.")); - pan_button = memnew(ToolButton); + pan_button = memnew(Button); + pan_button->set_flat(true); hb->add_child(pan_button); pan_button->set_toggle_mode(true); pan_button->connect("pressed", callable_mp(this, &CanvasItemEditor::_button_tool_select), make_binds(TOOL_PAN)); + pan_button->set_shortcut(ED_SHORTCUT("canvas_item_editor/pan_mode", TTR("Pan Mode"), KEY_G)); + pan_button->set_shortcut_context(this); pan_button->set_tooltip(TTR("Pan Mode")); - ruler_button = memnew(ToolButton); + ruler_button = memnew(Button); + ruler_button->set_flat(true); hb->add_child(ruler_button); ruler_button->set_toggle_mode(true); ruler_button->connect("pressed", callable_mp(this, &CanvasItemEditor::_button_tool_select), make_binds(TOOL_RULER)); ruler_button->set_shortcut(ED_SHORTCUT("canvas_item_editor/ruler_mode", TTR("Ruler Mode"), KEY_R)); + ruler_button->set_shortcut_context(this); ruler_button->set_tooltip(TTR("Ruler Mode")); hb->add_child(memnew(VSeparator)); - smart_snap_button = memnew(ToolButton); + smart_snap_button = memnew(Button); + smart_snap_button->set_flat(true); hb->add_child(smart_snap_button); smart_snap_button->set_toggle_mode(true); smart_snap_button->connect("toggled", callable_mp(this, &CanvasItemEditor::_button_toggle_smart_snap)); smart_snap_button->set_tooltip(TTR("Toggle smart snapping.")); smart_snap_button->set_shortcut(ED_SHORTCUT("canvas_item_editor/use_smart_snap", TTR("Use Smart Snap"), KEY_MASK_SHIFT | KEY_S)); + smart_snap_button->set_shortcut_context(this); - grid_snap_button = memnew(ToolButton); + grid_snap_button = memnew(Button); + grid_snap_button->set_flat(true); hb->add_child(grid_snap_button); grid_snap_button->set_toggle_mode(true); grid_snap_button->connect("toggled", callable_mp(this, &CanvasItemEditor::_button_toggle_grid_snap)); grid_snap_button->set_tooltip(TTR("Toggle grid snapping.")); grid_snap_button->set_shortcut(ED_SHORTCUT("canvas_item_editor/use_grid_snap", TTR("Use Grid Snap"), KEY_MASK_SHIFT | KEY_G)); + grid_snap_button->set_shortcut_context(this); snap_config_menu = memnew(MenuButton); + snap_config_menu->set_shortcut_context(this); hb->add_child(snap_config_menu); snap_config_menu->set_h_size_flags(SIZE_SHRINK_END); snap_config_menu->set_tooltip(TTR("Snapping Options")); @@ -5667,23 +5925,27 @@ CanvasItemEditor::CanvasItemEditor(EditorNode *p_editor) { hb->add_child(memnew(VSeparator)); - lock_button = memnew(ToolButton); + lock_button = memnew(Button); + lock_button->set_flat(true); hb->add_child(lock_button); lock_button->connect("pressed", callable_mp(this, &CanvasItemEditor::_popup_callback), varray(LOCK_SELECTED)); lock_button->set_tooltip(TTR("Lock the selected object in place (can't be moved).")); - unlock_button = memnew(ToolButton); + unlock_button = memnew(Button); + unlock_button->set_flat(true); hb->add_child(unlock_button); unlock_button->connect("pressed", callable_mp(this, &CanvasItemEditor::_popup_callback), varray(UNLOCK_SELECTED)); unlock_button->set_tooltip(TTR("Unlock the selected object (can be moved).")); - group_button = memnew(ToolButton); + group_button = memnew(Button); + group_button->set_flat(true); hb->add_child(group_button); group_button->connect("pressed", callable_mp(this, &CanvasItemEditor::_popup_callback), varray(GROUP_SELECTED)); group_button->set_tooltip(TTR("Makes sure the object's children are not selectable.")); - ungroup_button = memnew(ToolButton); + ungroup_button = memnew(Button); + ungroup_button->set_flat(true); hb->add_child(ungroup_button); ungroup_button->connect("pressed", callable_mp(this, &CanvasItemEditor::_popup_callback), varray(UNGROUP_SELECTED)); ungroup_button->set_tooltip(TTR("Restores the object's children's ability to be selected.")); @@ -5691,6 +5953,7 @@ CanvasItemEditor::CanvasItemEditor(EditorNode *p_editor) { hb->add_child(memnew(VSeparator)); skeleton_menu = memnew(MenuButton); + skeleton_menu->set_shortcut_context(this); hb->add_child(skeleton_menu); skeleton_menu->set_tooltip(TTR("Skeleton Options")); skeleton_menu->set_switch_on_hover(true); @@ -5708,7 +5971,8 @@ CanvasItemEditor::CanvasItemEditor(EditorNode *p_editor) { hb->add_child(memnew(VSeparator)); - override_camera_button = memnew(ToolButton); + override_camera_button = memnew(Button); + override_camera_button->set_flat(true); hb->add_child(override_camera_button); override_camera_button->connect("toggled", callable_mp(this, &CanvasItemEditor::_button_override_camera)); override_camera_button->set_toggle_mode(true); @@ -5718,6 +5982,7 @@ CanvasItemEditor::CanvasItemEditor(EditorNode *p_editor) { hb->add_child(memnew(VSeparator)); view_menu = memnew(MenuButton); + view_menu->set_shortcut_context(this); view_menu->set_text(TTR("View")); hb->add_child(view_menu); view_menu->get_popup()->connect("id_pressed", callable_mp(this, &CanvasItemEditor::_popup_callback)); @@ -5725,7 +5990,7 @@ CanvasItemEditor::CanvasItemEditor(EditorNode *p_editor) { p = view_menu->get_popup(); p->set_hide_on_checkable_item_selection(false); - p->add_check_shortcut(ED_SHORTCUT("canvas_item_editor/show_grid", TTR("Always Show Grid"), KEY_G), SHOW_GRID); + p->add_check_shortcut(ED_SHORTCUT("canvas_item_editor/show_grid", TTR("Always Show Grid"), KEY_MASK_CTRL | KEY_G), SHOW_GRID); p->add_check_shortcut(ED_SHORTCUT("canvas_item_editor/show_helpers", TTR("Show Helpers"), KEY_H), SHOW_HELPERS); p->add_check_shortcut(ED_SHORTCUT("canvas_item_editor/show_rulers", TTR("Show Rulers")), SHOW_RULERS); p->add_check_shortcut(ED_SHORTCUT("canvas_item_editor/show_guides", TTR("Show Guides"), KEY_Y), SHOW_GUIDES); @@ -5742,6 +6007,7 @@ CanvasItemEditor::CanvasItemEditor(EditorNode *p_editor) { p->add_check_shortcut(ED_SHORTCUT("canvas_item_editor/preview_canvas_scale", TTR("Preview Canvas Scale"), KEY_MASK_SHIFT | KEY_MASK_CMD | KEY_P), PREVIEW_CANVAS_SCALE); presets_menu = memnew(MenuButton); + presets_menu->set_shortcut_context(this); presets_menu->set_text(TTR("Layout")); hb->add_child(presets_menu); presets_menu->hide(); @@ -5755,7 +6021,8 @@ CanvasItemEditor::CanvasItemEditor(EditorNode *p_editor) { anchors_popup->set_name("Anchors"); anchors_popup->connect("id_pressed", callable_mp(this, &CanvasItemEditor::_popup_callback)); - anchor_mode_button = memnew(ToolButton); + anchor_mode_button = memnew(Button); + anchor_mode_button->set_flat(true); hb->add_child(anchor_mode_button); anchor_mode_button->set_toggle_mode(true); anchor_mode_button->hide(); @@ -5774,6 +6041,7 @@ CanvasItemEditor::CanvasItemEditor(EditorNode *p_editor) { key_loc_button->connect("pressed", callable_mp(this, &CanvasItemEditor::_popup_callback), varray(ANIM_INSERT_POS)); key_loc_button->set_tooltip(TTR("Translation mask for inserting keys.")); animation_hb->add_child(key_loc_button); + key_rot_button = memnew(Button); key_rot_button->set_toggle_mode(true); key_rot_button->set_flat(true); @@ -5782,6 +6050,7 @@ CanvasItemEditor::CanvasItemEditor(EditorNode *p_editor) { key_rot_button->connect("pressed", callable_mp(this, &CanvasItemEditor::_popup_callback), varray(ANIM_INSERT_ROT)); key_rot_button->set_tooltip(TTR("Rotation mask for inserting keys.")); animation_hb->add_child(key_rot_button); + key_scale_button = memnew(Button); key_scale_button->set_toggle_mode(true); key_scale_button->set_flat(true); @@ -5789,23 +6058,27 @@ CanvasItemEditor::CanvasItemEditor(EditorNode *p_editor) { key_scale_button->connect("pressed", callable_mp(this, &CanvasItemEditor::_popup_callback), varray(ANIM_INSERT_SCALE)); key_scale_button->set_tooltip(TTR("Scale mask for inserting keys.")); animation_hb->add_child(key_scale_button); + key_insert_button = memnew(Button); key_insert_button->set_flat(true); key_insert_button->set_focus_mode(FOCUS_NONE); key_insert_button->connect("pressed", callable_mp(this, &CanvasItemEditor::_popup_callback), varray(ANIM_INSERT_KEY)); key_insert_button->set_tooltip(TTR("Insert keys (based on mask).")); key_insert_button->set_shortcut(ED_SHORTCUT("canvas_item_editor/anim_insert_key", TTR("Insert Key"), KEY_INSERT)); + key_insert_button->set_shortcut_context(this); animation_hb->add_child(key_insert_button); + key_auto_insert_button = memnew(Button); key_auto_insert_button->set_flat(true); key_auto_insert_button->set_toggle_mode(true); key_auto_insert_button->set_focus_mode(FOCUS_NONE); - //key_auto_insert_button->connect("pressed", this, "_popup_callback", varray(ANIM_INSERT_KEY)); key_auto_insert_button->set_tooltip(TTR("Auto insert keys when objects are translated, rotated or scaled (based on mask).\nKeys are only added to existing tracks, no new tracks will be created.\nKeys must be inserted manually for the first time.")); key_auto_insert_button->set_shortcut(ED_SHORTCUT("canvas_item_editor/anim_auto_insert_key", TTR("Auto Insert Key"))); + key_auto_insert_button->set_shortcut_context(this); animation_hb->add_child(key_auto_insert_button); animation_menu = memnew(MenuButton); + animation_menu->set_shortcut_context(this); animation_menu->set_tooltip(TTR("Animation Key and Pose Options")); animation_hb->add_child(animation_menu); animation_menu->get_popup()->connect("id_pressed", callable_mp(this, &CanvasItemEditor::_popup_callback)); @@ -5881,8 +6154,8 @@ CanvasItemEditorPlugin::CanvasItemEditorPlugin(EditorNode *p_node) { editor = p_node; canvas_item_editor = memnew(CanvasItemEditor(editor)); canvas_item_editor->set_v_size_flags(Control::SIZE_EXPAND_FILL); - editor->get_viewport()->add_child(canvas_item_editor); - canvas_item_editor->set_anchors_and_margins_preset(Control::PRESET_WIDE); + editor->get_main_control()->add_child(canvas_item_editor); + canvas_item_editor->set_anchors_and_offsets_preset(Control::PRESET_WIDE); canvas_item_editor->hide(); } @@ -6077,6 +6350,11 @@ bool CanvasItemEditorViewport::_create_instance(Node *parent, String &path, cons Vector2 target_pos = canvas_item_editor->get_canvas_transform().affine_inverse().xform(p_point); target_pos = canvas_item_editor->snap_point(target_pos); target_pos = parent_ci->get_global_transform_with_canvas().affine_inverse().xform(target_pos); + // Preserve instance position of the original scene. + CanvasItem *instance_ci = Object::cast_to<CanvasItem>(instanced_scene); + if (instance_ci) { + target_pos += instance_ci->_edit_get_position(); + } editor_data->get_undo_redo().add_do_method(instanced_scene, "set_position", target_pos); } @@ -6150,7 +6428,7 @@ void CanvasItemEditorViewport::_perform_drop_data() { files_str += error_files[i].get_file().get_basename() + ","; } files_str = files_str.substr(0, files_str.length() - 1); - accept->set_text(vformat(TTR("Error instancing scene from %s"), files_str.c_str())); + accept->set_text(vformat(TTR("Error instancing scene from %s"), files_str.get_data())); accept->popup_centered(); } } @@ -6319,7 +6597,7 @@ CanvasItemEditorViewport::CanvasItemEditorViewport(EditorNode *p_node, CanvasIte selector->add_child(vbc); vbc->set_h_size_flags(Control::SIZE_EXPAND_FILL); vbc->set_v_size_flags(Control::SIZE_EXPAND_FILL); - vbc->set_custom_minimum_size(Size2(200, 260) * EDSCALE); + vbc->set_custom_minimum_size(Size2(240, 260) * EDSCALE); btn_group = memnew(VBoxContainer); vbc->add_child(btn_group); @@ -6335,7 +6613,7 @@ CanvasItemEditorViewport::CanvasItemEditorViewport(EditorNode *p_node, CanvasIte } label = memnew(Label); - label->add_theme_color_override("font_color_shadow", Color(0, 0, 0, 1)); + label->add_theme_color_override("font_shadow_color", Color(0, 0, 0, 1)); label->add_theme_constant_override("shadow_as_outline", 1 * EDSCALE); label->hide(); canvas_item_editor->get_controls_container()->add_child(label); @@ -6343,7 +6621,7 @@ CanvasItemEditorViewport::CanvasItemEditorViewport(EditorNode *p_node, CanvasIte label_desc = memnew(Label); label_desc->set_text(TTR("Drag & drop + Shift : Add node as sibling\nDrag & drop + Alt : Change node type")); label_desc->add_theme_color_override("font_color", Color(0.6f, 0.6f, 0.6f, 1)); - label_desc->add_theme_color_override("font_color_shadow", Color(0.2f, 0.2f, 0.2f, 1)); + label_desc->add_theme_color_override("font_shadow_color", Color(0.2f, 0.2f, 0.2f, 1)); label_desc->add_theme_constant_override("shadow_as_outline", 1 * EDSCALE); label_desc->add_theme_constant_override("line_spacing", 0); label_desc->hide(); diff --git a/editor/plugins/canvas_item_editor_plugin.h b/editor/plugins/canvas_item_editor_plugin.h index a686c98f65..24149a57b0 100644 --- a/editor/plugins/canvas_item_editor_plugin.h +++ b/editor/plugins/canvas_item_editor_plugin.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -119,23 +119,23 @@ private: UNLOCK_SELECTED, GROUP_SELECTED, UNGROUP_SELECTED, - ANCHORS_AND_MARGINS_PRESET_TOP_LEFT, - ANCHORS_AND_MARGINS_PRESET_TOP_RIGHT, - ANCHORS_AND_MARGINS_PRESET_BOTTOM_LEFT, - ANCHORS_AND_MARGINS_PRESET_BOTTOM_RIGHT, - ANCHORS_AND_MARGINS_PRESET_CENTER_LEFT, - ANCHORS_AND_MARGINS_PRESET_CENTER_RIGHT, - ANCHORS_AND_MARGINS_PRESET_CENTER_TOP, - ANCHORS_AND_MARGINS_PRESET_CENTER_BOTTOM, - ANCHORS_AND_MARGINS_PRESET_CENTER, - ANCHORS_AND_MARGINS_PRESET_TOP_WIDE, - ANCHORS_AND_MARGINS_PRESET_LEFT_WIDE, - ANCHORS_AND_MARGINS_PRESET_RIGHT_WIDE, - ANCHORS_AND_MARGINS_PRESET_BOTTOM_WIDE, - ANCHORS_AND_MARGINS_PRESET_VCENTER_WIDE, - ANCHORS_AND_MARGINS_PRESET_HCENTER_WIDE, - ANCHORS_AND_MARGINS_PRESET_WIDE, - ANCHORS_AND_MARGINS_PRESET_KEEP_RATIO, + ANCHORS_AND_OFFSETS_PRESET_TOP_LEFT, + ANCHORS_AND_OFFSETS_PRESET_TOP_RIGHT, + ANCHORS_AND_OFFSETS_PRESET_BOTTOM_LEFT, + ANCHORS_AND_OFFSETS_PRESET_BOTTOM_RIGHT, + ANCHORS_AND_OFFSETS_PRESET_CENTER_LEFT, + ANCHORS_AND_OFFSETS_PRESET_CENTER_RIGHT, + ANCHORS_AND_OFFSETS_PRESET_CENTER_TOP, + ANCHORS_AND_OFFSETS_PRESET_CENTER_BOTTOM, + ANCHORS_AND_OFFSETS_PRESET_CENTER, + ANCHORS_AND_OFFSETS_PRESET_TOP_WIDE, + ANCHORS_AND_OFFSETS_PRESET_LEFT_WIDE, + ANCHORS_AND_OFFSETS_PRESET_RIGHT_WIDE, + ANCHORS_AND_OFFSETS_PRESET_BOTTOM_WIDE, + ANCHORS_AND_OFFSETS_PRESET_VCENTER_WIDE, + ANCHORS_AND_OFFSETS_PRESET_HCENTER_WIDE, + ANCHORS_AND_OFFSETS_PRESET_WIDE, + ANCHORS_AND_OFFSETS_PRESET_KEEP_RATIO, ANCHORS_PRESET_TOP_LEFT, ANCHORS_PRESET_TOP_RIGHT, ANCHORS_PRESET_BOTTOM_LEFT, @@ -152,22 +152,22 @@ private: ANCHORS_PRESET_VCENTER_WIDE, ANCHORS_PRESET_HCENTER_WIDE, ANCHORS_PRESET_WIDE, - MARGINS_PRESET_TOP_LEFT, - MARGINS_PRESET_TOP_RIGHT, - MARGINS_PRESET_BOTTOM_LEFT, - MARGINS_PRESET_BOTTOM_RIGHT, - MARGINS_PRESET_CENTER_LEFT, - MARGINS_PRESET_CENTER_RIGHT, - MARGINS_PRESET_CENTER_TOP, - MARGINS_PRESET_CENTER_BOTTOM, - MARGINS_PRESET_CENTER, - MARGINS_PRESET_TOP_WIDE, - MARGINS_PRESET_LEFT_WIDE, - MARGINS_PRESET_RIGHT_WIDE, - MARGINS_PRESET_BOTTOM_WIDE, - MARGINS_PRESET_VCENTER_WIDE, - MARGINS_PRESET_HCENTER_WIDE, - MARGINS_PRESET_WIDE, + OFFSETS_PRESET_TOP_LEFT, + OFFSETS_PRESET_TOP_RIGHT, + OFFSETS_PRESET_BOTTOM_LEFT, + OFFSETS_PRESET_BOTTOM_RIGHT, + OFFSETS_PRESET_CENTER_LEFT, + OFFSETS_PRESET_CENTER_RIGHT, + OFFSETS_PRESET_CENTER_TOP, + OFFSETS_PRESET_CENTER_BOTTOM, + OFFSETS_PRESET_CENTER, + OFFSETS_PRESET_TOP_WIDE, + OFFSETS_PRESET_LEFT_WIDE, + OFFSETS_PRESET_RIGHT_WIDE, + OFFSETS_PRESET_BOTTOM_WIDE, + OFFSETS_PRESET_VCENTER_WIDE, + OFFSETS_PRESET_HCENTER_WIDE, + OFFSETS_PRESET_WIDE, ANIM_INSERT_KEY, ANIM_INSERT_KEY_EXISTING, ANIM_INSERT_POS, @@ -228,9 +228,9 @@ private: VScrollBar *v_scroll; HBoxContainer *hb; - ToolButton *zoom_minus; - ToolButton *zoom_reset; - ToolButton *zoom_plus; + Button *zoom_minus; + Button *zoom_reset; + Button *zoom_plus; Map<Control *, Timer *> popup_temporarily_timers; @@ -288,9 +288,9 @@ private: MenuOption last_option; struct _SelectResult { - CanvasItem *item; - float z_index; - bool has_z; + CanvasItem *item = nullptr; + float z_index = 0; + bool has_z = true; _FORCE_INLINE_ bool operator<(const _SelectResult &p_rr) const { return has_z && p_rr.has_z ? p_rr.z_index < z_index : p_rr.has_z; } @@ -308,8 +308,6 @@ private: Transform2D xform; float length = 0.f; uint64_t last_pass = 0; - - BoneList() {} }; uint64_t bone_last_frame; @@ -331,36 +329,36 @@ private: struct PoseClipboard { Vector2 pos; Vector2 scale; - float rot; + float rot = 0; ObjectID id; }; List<PoseClipboard> pose_clipboard; - ToolButton *select_button; + Button *select_button; - ToolButton *move_button; - ToolButton *scale_button; - ToolButton *rotate_button; + Button *move_button; + Button *scale_button; + Button *rotate_button; - ToolButton *list_select_button; - ToolButton *pivot_button; - ToolButton *pan_button; + Button *list_select_button; + Button *pivot_button; + Button *pan_button; - ToolButton *ruler_button; + Button *ruler_button; - ToolButton *smart_snap_button; - ToolButton *grid_snap_button; + Button *smart_snap_button; + Button *grid_snap_button; MenuButton *snap_config_menu; PopupMenu *smartsnap_config_popup; - ToolButton *lock_button; - ToolButton *unlock_button; + Button *lock_button; + Button *unlock_button; - ToolButton *group_button; - ToolButton *ungroup_button; + Button *group_button; + Button *ungroup_button; MenuButton *skeleton_menu; - ToolButton *override_camera_button; + Button *override_camera_button; MenuButton *view_menu; HBoxContainer *animation_hb; MenuButton *animation_menu; @@ -369,7 +367,7 @@ private: PopupMenu *anchors_and_margins_popup; PopupMenu *anchors_popup; - ToolButton *anchor_mode_button; + Button *anchor_mode_button; Button *key_loc_button; Button *key_rot_button; @@ -400,11 +398,11 @@ private: Ref<Texture2D> select_handle; Ref<Texture2D> anchor_handle; - Ref<ShortCut> drag_pivot_shortcut; - Ref<ShortCut> set_pivot_shortcut; - Ref<ShortCut> multiply_grid_step_shortcut; - Ref<ShortCut> divide_grid_step_shortcut; - Ref<ShortCut> pan_view_shortcut; + Ref<Shortcut> drag_pivot_shortcut; + Ref<Shortcut> set_pivot_shortcut; + Ref<Shortcut> multiply_grid_step_shortcut; + Ref<Shortcut> divide_grid_step_shortcut; + Ref<Shortcut> pan_view_shortcut; bool _is_node_locked(const Node *p_node); bool _is_node_movable(const Node *p_node, bool p_popup_warning = false); @@ -456,9 +454,9 @@ private: void _unhandled_key_input(const Ref<InputEvent> &p_ev); - void _draw_text_at_position(Point2 p_position, String p_string, Margin p_side); - void _draw_margin_at_position(int p_value, Point2 p_position, Margin p_side); - void _draw_percentage_at_position(float p_value, Point2 p_position, Margin p_side); + void _draw_text_at_position(Point2 p_position, String p_string, Side p_side); + void _draw_margin_at_position(int p_value, Point2 p_position, Side p_side); + void _draw_percentage_at_position(float p_value, Point2 p_position, Side p_side); void _draw_straight_line(Point2 p_from, Point2 p_to, Color p_color); void _draw_smart_snapping(); @@ -492,6 +490,7 @@ private: bool _gui_input_hover(const Ref<InputEvent> &p_event); void _gui_input_viewport(const Ref<InputEvent> &p_event); + void _update_cursor(); void _selection_changed(); @@ -520,14 +519,15 @@ private: const Node *p_current); void _set_anchors_preset(Control::LayoutPreset p_preset); - void _set_margins_preset(Control::LayoutPreset p_preset); - void _set_anchors_and_margins_preset(Control::LayoutPreset p_preset); - void _set_anchors_and_margins_to_keep_ratio(); + void _set_offsets_preset(Control::LayoutPreset p_preset); + void _set_anchors_and_offsets_preset(Control::LayoutPreset p_preset); + void _set_anchors_and_offsets_to_keep_ratio(); void _button_toggle_anchor_mode(bool p_status); VBoxContainer *controls_vb; HBoxContainer *zoom_hb; + float _get_next_zoom_value(int p_increment_count) const; void _zoom_on_position(float p_zoom, Point2 p_position = Point2()); void _update_zoom_label(); void _button_zoom_minus(); @@ -648,13 +648,13 @@ class CanvasItemEditorPlugin : public EditorPlugin { EditorNode *editor; public: - virtual String get_name() const { return "2D"; } - bool has_main_screen() const { return true; } - virtual void edit(Object *p_object); - virtual bool handles(Object *p_object) const; - virtual void make_visible(bool p_visible); - virtual Dictionary get_state() const; - virtual void set_state(const Dictionary &p_state); + virtual String get_name() const override { return "2D"; } + bool has_main_screen() const override { return true; } + virtual void edit(Object *p_object) override; + virtual bool handles(Object *p_object) const override; + virtual void make_visible(bool p_visible) override; + virtual Dictionary get_state() const override; + virtual void set_state(const Dictionary &p_state) override; CanvasItemEditor *get_canvas_item_editor() { return canvas_item_editor; } @@ -705,8 +705,8 @@ protected: void _notification(int p_what); public: - virtual bool can_drop_data(const Point2 &p_point, const Variant &p_data) const; - virtual void drop_data(const Point2 &p_point, const Variant &p_data); + virtual bool can_drop_data(const Point2 &p_point, const Variant &p_data) const override; + virtual void drop_data(const Point2 &p_point, const Variant &p_data) override; CanvasItemEditorViewport(EditorNode *p_node, CanvasItemEditor *p_canvas_item_editor); ~CanvasItemEditorViewport(); diff --git a/editor/plugins/collision_polygon_2d_editor_plugin.cpp b/editor/plugins/collision_polygon_2d_editor_plugin.cpp index 08d6fc966d..8e340b28ef 100644 --- a/editor/plugins/collision_polygon_2d_editor_plugin.cpp +++ b/editor/plugins/collision_polygon_2d_editor_plugin.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ diff --git a/editor/plugins/collision_polygon_2d_editor_plugin.h b/editor/plugins/collision_polygon_2d_editor_plugin.h index b0be92db44..e78c486a39 100644 --- a/editor/plugins/collision_polygon_2d_editor_plugin.h +++ b/editor/plugins/collision_polygon_2d_editor_plugin.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -40,8 +40,8 @@ class CollisionPolygon2DEditor : public AbstractPolygon2DEditor { CollisionPolygon2D *node; protected: - virtual Node2D *_get_node() const; - virtual void _set_node(Node *p_polygon); + virtual Node2D *_get_node() const override; + virtual void _set_node(Node *p_polygon) override; public: CollisionPolygon2DEditor(EditorNode *p_editor); diff --git a/editor/plugins/collision_polygon_3d_editor_plugin.cpp b/editor/plugins/collision_polygon_3d_editor_plugin.cpp index c61d410d38..0c18975258 100644 --- a/editor/plugins/collision_polygon_3d_editor_plugin.cpp +++ b/editor/plugins/collision_polygon_3d_editor_plugin.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -32,6 +32,7 @@ #include "canvas_item_editor_plugin.h" #include "core/input/input.h" +#include "core/math/geometry_2d.h" #include "core/os/file_access.h" #include "core/os/keyboard.h" #include "editor/editor_settings.h" @@ -196,7 +197,7 @@ bool CollisionPolygon3DEditor::forward_spatial_gui_input(Camera3D *p_camera, con p_camera->unproject_position(gt.xform(Vector3(poly[(i + 1) % poly.size()].x, poly[(i + 1) % poly.size()].y, depth))) }; - Vector2 cp = Geometry::get_closest_point_to_segment_2d(gpoint, points); + Vector2 cp = Geometry2D::get_closest_point_to_segment(gpoint, points); if (cp.distance_squared_to(points[0]) < CMP_EPSILON2 || cp.distance_squared_to(points[1]) < CMP_EPSILON2) { continue; //not valid to reuse point } @@ -500,12 +501,14 @@ CollisionPolygon3DEditor::CollisionPolygon3DEditor(EditorNode *p_editor) { undo_redo = EditorNode::get_undo_redo(); add_child(memnew(VSeparator)); - button_create = memnew(ToolButton); + button_create = memnew(Button); + button_create->set_flat(true); add_child(button_create); button_create->connect("pressed", callable_mp(this, &CollisionPolygon3DEditor::_menu_option), varray(MODE_CREATE)); button_create->set_toggle_mode(true); - button_edit = memnew(ToolButton); + button_edit = memnew(Button); + button_edit->set_flat(true); add_child(button_edit); button_edit->connect("pressed", callable_mp(this, &CollisionPolygon3DEditor::_menu_option), varray(MODE_EDIT)); button_edit->set_toggle_mode(true); diff --git a/editor/plugins/collision_polygon_3d_editor_plugin.h b/editor/plugins/collision_polygon_3d_editor_plugin.h index 5215cbb678..c66518e3e5 100644 --- a/editor/plugins/collision_polygon_3d_editor_plugin.h +++ b/editor/plugins/collision_polygon_3d_editor_plugin.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -36,7 +36,6 @@ #include "scene/3d/collision_polygon_3d.h" #include "scene/3d/immediate_geometry_3d.h" #include "scene/3d/mesh_instance_3d.h" -#include "scene/gui/tool_button.h" class CanvasItemEditor; @@ -45,7 +44,6 @@ class CollisionPolygon3DEditor : public HBoxContainer { UndoRedo *undo_redo; enum Mode { - MODE_CREATE, MODE_EDIT, @@ -53,8 +51,8 @@ class CollisionPolygon3DEditor : public HBoxContainer { Mode mode; - ToolButton *button_create; - ToolButton *button_edit; + Button *button_create; + Button *button_edit; Ref<StandardMaterial3D> line_material; Ref<StandardMaterial3D> handle_material; @@ -102,13 +100,13 @@ class Polygon3DEditorPlugin : public EditorPlugin { EditorNode *editor; public: - virtual bool forward_spatial_gui_input(Camera3D *p_camera, const Ref<InputEvent> &p_event) { return collision_polygon_editor->forward_spatial_gui_input(p_camera, p_event); } + virtual bool forward_spatial_gui_input(Camera3D *p_camera, const Ref<InputEvent> &p_event) override { return collision_polygon_editor->forward_spatial_gui_input(p_camera, p_event); } - virtual String get_name() const { return "Polygon3DEditor"; } - bool has_main_screen() const { return false; } - virtual void edit(Object *p_object); - virtual bool handles(Object *p_object) const; - virtual void make_visible(bool p_visible); + virtual String get_name() const override { return "Polygon3DEditor"; } + bool has_main_screen() const override { return false; } + virtual void edit(Object *p_object) override; + virtual bool handles(Object *p_object) const override; + virtual void make_visible(bool p_visible) override; Polygon3DEditorPlugin(EditorNode *p_node); ~Polygon3DEditorPlugin(); diff --git a/editor/plugins/collision_shape_2d_editor_plugin.cpp b/editor/plugins/collision_shape_2d_editor_plugin.cpp index 0f381c06b4..141ee35cdb 100644 --- a/editor/plugins/collision_shape_2d_editor_plugin.cpp +++ b/editor/plugins/collision_shape_2d_editor_plugin.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -36,6 +36,7 @@ #include "scene/resources/concave_polygon_shape_2d.h" #include "scene/resources/convex_polygon_shape_2d.h" #include "scene/resources/line_shape_2d.h" +#include "scene/resources/ray_shape_2d.h" #include "scene/resources/rectangle_shape_2d.h" #include "scene/resources/segment_shape_2d.h" @@ -97,7 +98,7 @@ Variant CollisionShape2DEditor::get_handle_value(int idx) const { Ref<RectangleShape2D> rect = node->get_shape(); if (idx < 3) { - return rect->get_extents().abs(); + return rect->get_size().abs(); } } break; @@ -178,13 +179,13 @@ void CollisionShape2DEditor::set_handle(int idx, Point2 &p_point) { if (idx < 3) { Ref<RectangleShape2D> rect = node->get_shape(); - Vector2 extents = rect->get_extents(); + Vector2 size = rect->get_size(); if (idx == 2) { - extents = p_point; + size = p_point * 2; } else { - extents[idx] = p_point[idx]; + size[idx] = p_point[idx] * 2; } - rect->set_extents(extents.abs()); + rect->set_size(size.abs()); canvas_item_editor->update_viewport(); } @@ -206,7 +207,7 @@ void CollisionShape2DEditor::set_handle(int idx, Point2 &p_point) { } break; } - node->get_shape()->_change_notify(); + node->get_shape()->notify_property_list_changed(); } void CollisionShape2DEditor::commit_handle(int idx, Variant &p_org) { @@ -241,9 +242,11 @@ void CollisionShape2DEditor::commit_handle(int idx, Variant &p_org) { } break; case CONCAVE_POLYGON_SHAPE: { + // Cannot be edited directly, use CollisionPolygon2D instead. } break; case CONVEX_POLYGON_SHAPE: { + // Cannot be edited directly, use CollisionPolygon2D instead. } break; case LINE_SHAPE: { @@ -276,9 +279,9 @@ void CollisionShape2DEditor::commit_handle(int idx, Variant &p_org) { case RECTANGLE_SHAPE: { Ref<RectangleShape2D> rect = node->get_shape(); - undo_redo->add_do_method(rect.ptr(), "set_extents", rect->get_extents()); + undo_redo->add_do_method(rect.ptr(), "set_size", rect->get_size()); undo_redo->add_do_method(canvas_item_editor, "update_viewport"); - undo_redo->add_undo_method(rect.ptr(), "set_extents", p_org); + undo_redo->add_undo_method(rect.ptr(), "set_size", p_org); undo_redo->add_undo_method(canvas_item_editor, "update_viewport"); } break; @@ -490,7 +493,7 @@ void CollisionShape2DEditor::forward_canvas_draw_over_viewport(Control *p_overla Ref<RectangleShape2D> shape = node->get_shape(); handles.resize(3); - Vector2 ext = shape->get_extents(); + Vector2 ext = shape->get_size() / 2; handles.write[0] = Point2(ext.x, 0); handles.write[1] = Point2(0, ext.y); handles.write[2] = Point2(ext.x, ext.y); @@ -560,6 +563,8 @@ CollisionShape2DEditor::CollisionShape2DEditor(EditorNode *p_editor) { edit_handle = -1; pressed = false; + + shape_type = 0; } void CollisionShape2DEditorPlugin::edit(Object *p_obj) { diff --git a/editor/plugins/collision_shape_2d_editor_plugin.h b/editor/plugins/collision_shape_2d_editor_plugin.h index 6bb621c476..054db1a61b 100644 --- a/editor/plugins/collision_shape_2d_editor_plugin.h +++ b/editor/plugins/collision_shape_2d_editor_plugin.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -90,14 +90,14 @@ class CollisionShape2DEditorPlugin : public EditorPlugin { EditorNode *editor; public: - virtual bool forward_canvas_gui_input(const Ref<InputEvent> &p_event) { return collision_shape_2d_editor->forward_canvas_gui_input(p_event); } - virtual void forward_canvas_draw_over_viewport(Control *p_overlay) { collision_shape_2d_editor->forward_canvas_draw_over_viewport(p_overlay); } - - virtual String get_name() const { return "CollisionShape2D"; } - bool has_main_screen() const { return false; } - virtual void edit(Object *p_obj); - virtual bool handles(Object *p_obj) const; - virtual void make_visible(bool visible); + virtual bool forward_canvas_gui_input(const Ref<InputEvent> &p_event) override { return collision_shape_2d_editor->forward_canvas_gui_input(p_event); } + virtual void forward_canvas_draw_over_viewport(Control *p_overlay) override { collision_shape_2d_editor->forward_canvas_draw_over_viewport(p_overlay); } + + virtual String get_name() const override { return "CollisionShape2D"; } + bool has_main_screen() const override { return false; } + virtual void edit(Object *p_obj) override; + virtual bool handles(Object *p_obj) const override; + virtual void make_visible(bool visible) override; CollisionShape2DEditorPlugin(EditorNode *p_editor); ~CollisionShape2DEditorPlugin(); diff --git a/editor/plugins/cpu_particles_2d_editor_plugin.cpp b/editor/plugins/cpu_particles_2d_editor_plugin.cpp index 008de7cfb4..3403aeceba 100644 --- a/editor/plugins/cpu_particles_2d_editor_plugin.cpp +++ b/editor/plugins/cpu_particles_2d_editor_plugin.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -60,7 +60,7 @@ void CPUParticles2DEditorPlugin::_file_selected(const String &p_file) { void CPUParticles2DEditorPlugin::_menu_callback(int p_idx) { switch (p_idx) { case MENU_LOAD_EMISSION_MASK: { - file->popup_centered_ratio(); + file->popup_file_dialog(); } break; case MENU_CLEAR_EMISSION_MASK: { diff --git a/editor/plugins/cpu_particles_2d_editor_plugin.h b/editor/plugins/cpu_particles_2d_editor_plugin.h index fecbb8b1cd..b188df8e96 100644 --- a/editor/plugins/cpu_particles_2d_editor_plugin.h +++ b/editor/plugins/cpu_particles_2d_editor_plugin.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -79,11 +79,11 @@ protected: static void _bind_methods(); public: - virtual String get_name() const { return "CPUParticles2D"; } - bool has_main_screen() const { return false; } - virtual void edit(Object *p_object); - virtual bool handles(Object *p_object) const; - virtual void make_visible(bool p_visible); + virtual String get_name() const override { return "CPUParticles2D"; } + bool has_main_screen() const override { return false; } + virtual void edit(Object *p_object) override; + virtual bool handles(Object *p_object) const override; + virtual void make_visible(bool p_visible) override; CPUParticles2DEditorPlugin(EditorNode *p_node); ~CPUParticles2DEditorPlugin(); diff --git a/editor/plugins/cpu_particles_3d_editor_plugin.cpp b/editor/plugins/cpu_particles_3d_editor_plugin.cpp index ef26ecd767..f41ccfa86b 100644 --- a/editor/plugins/cpu_particles_3d_editor_plugin.cpp +++ b/editor/plugins/cpu_particles_3d_editor_plugin.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -48,7 +48,7 @@ void CPUParticles3DEditor::_notification(int p_notification) { void CPUParticles3DEditor::_menu_option(int p_option) { switch (p_option) { case MENU_OPTION_CREATE_EMISSION_VOLUME_FROM_NODE: { - emission_tree_dialog->popup_centered_ratio(); + emission_tree_dialog->popup_scenetree_dialog(); } break; @@ -122,7 +122,7 @@ void CPUParticles3DEditorPlugin::make_visible(bool p_visible) { CPUParticles3DEditorPlugin::CPUParticles3DEditorPlugin(EditorNode *p_node) { editor = p_node; particles_editor = memnew(CPUParticles3DEditor); - editor->get_viewport()->add_child(particles_editor); + editor->get_main_control()->add_child(particles_editor); particles_editor->hide(); } diff --git a/editor/plugins/cpu_particles_3d_editor_plugin.h b/editor/plugins/cpu_particles_3d_editor_plugin.h index d9680496ba..9dced3ea86 100644 --- a/editor/plugins/cpu_particles_3d_editor_plugin.h +++ b/editor/plugins/cpu_particles_3d_editor_plugin.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -38,7 +38,6 @@ class CPUParticles3DEditor : public GPUParticles3DEditorBase { GDCLASS(CPUParticles3DEditor, GPUParticles3DEditorBase); enum Menu { - MENU_OPTION_CREATE_EMISSION_VOLUME_FROM_NODE, MENU_OPTION_CLEAR_EMISSION_VOLUME, MENU_OPTION_RESTART @@ -51,7 +50,7 @@ class CPUParticles3DEditor : public GPUParticles3DEditorBase { friend class CPUParticles3DEditorPlugin; - virtual void _generate_emission_points(); + virtual void _generate_emission_points() override; protected: void _notification(int p_notification); @@ -70,11 +69,11 @@ class CPUParticles3DEditorPlugin : public EditorPlugin { EditorNode *editor; public: - virtual String get_name() const { return "CPUParticles3D"; } - bool has_main_screen() const { return false; } - virtual void edit(Object *p_object); - virtual bool handles(Object *p_object) const; - virtual void make_visible(bool p_visible); + virtual String get_name() const override { return "CPUParticles3D"; } + bool has_main_screen() const override { return false; } + virtual void edit(Object *p_object) override; + virtual bool handles(Object *p_object) const override; + virtual void make_visible(bool p_visible) override; CPUParticles3DEditorPlugin(EditorNode *p_node); ~CPUParticles3DEditorPlugin(); diff --git a/editor/plugins/curve_editor_plugin.cpp b/editor/plugins/curve_editor_plugin.cpp index 539ab03f5b..bff5cb8d2a 100644 --- a/editor/plugins/curve_editor_plugin.cpp +++ b/editor/plugins/curve_editor_plugin.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -353,8 +353,8 @@ void CurveEditor::open_context_menu(Vector2 pos) { _context_menu->add_check_item(TTR("Linear"), CONTEXT_LINEAR); bool is_linear = _selected_tangent == TANGENT_LEFT ? - _curve_ref->get_point_left_mode(_selected_point) == Curve::TANGENT_LINEAR : - _curve_ref->get_point_right_mode(_selected_point) == Curve::TANGENT_LINEAR; + _curve_ref->get_point_left_mode(_selected_point) == Curve::TANGENT_LINEAR : + _curve_ref->get_point_right_mode(_selected_point) == Curve::TANGENT_LINEAR; _context_menu->set_item_checked(_context_menu->get_item_index(CONTEXT_LINEAR), is_linear); @@ -518,7 +518,9 @@ void CurveEditor::set_hover_point_index(int index) { void CurveEditor::update_view_transform() { Ref<Font> font = get_theme_font("font", "Label"); - const real_t margin = font->get_height() + 2 * EDSCALE; + int font_size = get_theme_font_size("font_size", "Label"); + + const real_t margin = font->get_height(font_size) + 2 * EDSCALE; float min_y = 0; float max_y = 1; @@ -662,18 +664,19 @@ void CurveEditor::_draw() { draw_set_transform_matrix(Transform2D()); Ref<Font> font = get_theme_font("font", "Label"); - float font_height = font->get_height(); + int font_size = get_theme_font_size("font_size", "Label"); + float font_height = font->get_height(font_size); Color text_color = get_theme_color("font_color", "Editor"); { // X axis float y = curve.get_min_value(); Vector2 off(0, font_height - 1); - draw_string(font, get_view_pos(Vector2(0, y)) + off, "0.0", text_color); - draw_string(font, get_view_pos(Vector2(0.25, y)) + off, "0.25", text_color); - draw_string(font, get_view_pos(Vector2(0.5, y)) + off, "0.5", text_color); - draw_string(font, get_view_pos(Vector2(0.75, y)) + off, "0.75", text_color); - draw_string(font, get_view_pos(Vector2(1, y)) + off, "1.0", text_color); + draw_string(font, get_view_pos(Vector2(0, y)) + off, "0.0", HALIGN_LEFT, -1, font_size, text_color); + draw_string(font, get_view_pos(Vector2(0.25, y)) + off, "0.25", HALIGN_LEFT, -1, font_size, text_color); + draw_string(font, get_view_pos(Vector2(0.5, y)) + off, "0.5", HALIGN_LEFT, -1, font_size, text_color); + draw_string(font, get_view_pos(Vector2(0.75, y)) + off, "0.75", HALIGN_LEFT, -1, font_size, text_color); + draw_string(font, get_view_pos(Vector2(1, y)) + off, "1.0", HALIGN_LEFT, -1, font_size, text_color); } { @@ -682,9 +685,9 @@ void CurveEditor::_draw() { float m1 = 0.5 * (curve.get_min_value() + curve.get_max_value()); float m2 = curve.get_max_value(); Vector2 off(1, -1); - draw_string(font, get_view_pos(Vector2(0, m0)) + off, String::num(m0, 2), text_color); - draw_string(font, get_view_pos(Vector2(0, m1)) + off, String::num(m1, 2), text_color); - draw_string(font, get_view_pos(Vector2(0, m2)) + off, String::num(m2, 3), text_color); + draw_string(font, get_view_pos(Vector2(0, m0)) + off, String::num(m0, 2), HALIGN_LEFT, -1, font_size, text_color); + draw_string(font, get_view_pos(Vector2(0, m1)) + off, String::num(m1, 2), HALIGN_LEFT, -1, font_size, text_color); + draw_string(font, get_view_pos(Vector2(0, m2)) + off, String::num(m2, 3), HALIGN_LEFT, -1, font_size, text_color); } // Draw tangents for current point @@ -744,10 +747,10 @@ void CurveEditor::_draw() { if (_selected_point > 0 && _selected_point + 1 < curve.get_point_count()) { text_color.a *= 0.4; - draw_string(font, Vector2(50 * EDSCALE, font_height), TTR("Hold Shift to edit tangents individually"), text_color); + draw_string(font, Vector2(50 * EDSCALE, font_height), TTR("Hold Shift to edit tangents individually"), HALIGN_LEFT, -1, font_size, text_color); } else if (curve.get_point_count() == 0) { text_color.a *= 0.4; - draw_string(font, Vector2(50 * EDSCALE, font_height), TTR("Right click to add point"), text_color); + draw_string(font, Vector2(50 * EDSCALE, font_height), TTR("Right click to add point"), HALIGN_LEFT, -1, font_size, text_color); } } diff --git a/editor/plugins/curve_editor_plugin.h b/editor/plugins/curve_editor_plugin.h index c00aa3eca5..2e8dd43d7e 100644 --- a/editor/plugins/curve_editor_plugin.h +++ b/editor/plugins/curve_editor_plugin.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -43,7 +43,7 @@ class CurveEditor : public Control { public: CurveEditor(); - Size2 get_minimum_size() const; + Size2 get_minimum_size() const override; void set_curve(Ref<Curve> curve); @@ -123,8 +123,8 @@ class EditorInspectorPluginCurve : public EditorInspectorPlugin { GDCLASS(EditorInspectorPluginCurve, EditorInspectorPlugin); public: - virtual bool can_handle(Object *p_object); - virtual void parse_begin(Object *p_object); + virtual bool can_handle(Object *p_object) override; + virtual void parse_begin(Object *p_object) override; }; class CurveEditorPlugin : public EditorPlugin { @@ -133,15 +133,15 @@ class CurveEditorPlugin : public EditorPlugin { public: CurveEditorPlugin(EditorNode *p_node); - virtual String get_name() const { return "Curve"; } + virtual String get_name() const override { return "Curve"; } }; class CurvePreviewGenerator : public EditorResourcePreviewGenerator { GDCLASS(CurvePreviewGenerator, EditorResourcePreviewGenerator); public: - virtual bool handles(const String &p_type) const; - virtual Ref<Texture2D> generate(const Ref<Resource> &p_from, const Size2 &p_size) const; + virtual bool handles(const String &p_type) const override; + virtual Ref<Texture2D> generate(const Ref<Resource> &p_from, const Size2 &p_size) const override; }; #endif // CURVE_EDITOR_PLUGIN_H diff --git a/editor/plugins/debugger_editor_plugin.cpp b/editor/plugins/debugger_editor_plugin.cpp index 0ca479555d..1512e1817a 100644 --- a/editor/plugins/debugger_editor_plugin.cpp +++ b/editor/plugins/debugger_editor_plugin.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -47,7 +47,7 @@ DebuggerEditorPlugin::DebuggerEditorPlugin(EditorNode *p_editor, MenuButton *p_d ED_SHORTCUT("debugger/keep_debugger_open", TTR("Keep Debugger Open")); ED_SHORTCUT("debugger/debug_with_external_editor", TTR("Debug with External Editor")); - // File Server for deploy with remote fs. + // File Server for deploy with remote filesystem. file_server = memnew(EditorFileServer); EditorDebuggerNode *debugger = memnew(EditorDebuggerNode); @@ -59,22 +59,31 @@ DebuggerEditorPlugin::DebuggerEditorPlugin(EditorNode *p_editor, MenuButton *p_d PopupMenu *p = debug_menu->get_popup(); p->set_hide_on_checkable_item_selection(false); p->add_check_shortcut(ED_SHORTCUT("editor/deploy_with_remote_debug", TTR("Deploy with Remote Debug")), RUN_DEPLOY_REMOTE_DEBUG); - p->set_item_tooltip(p->get_item_count() - 1, TTR("When exporting or deploying, the resulting executable will attempt to connect to the IP of this computer in order to be debugged.")); - p->add_check_shortcut(ED_SHORTCUT("editor/small_deploy_with_network_fs", TTR("Small Deploy with Network FS")), RUN_FILE_SERVER); - p->set_item_tooltip(p->get_item_count() - 1, TTR("When this option is enabled, export or deploy will produce a minimal executable.\nThe filesystem will be provided from the project by the editor over the network.\nOn Android, deploy will use the USB cable for faster performance. This option speeds up testing for games with a large footprint.")); + p->set_item_tooltip( + p->get_item_count() - 1, + TTR("When this option is enabled, using one-click deploy will make the executable attempt to connect to this computer's IP so the running project can be debugged.\nThis option is intended to be used for remote debugging (typically with a mobile device).\nYou don't need to enable it to use the GDScript debugger locally.")); + p->add_check_shortcut(ED_SHORTCUT("editor/small_deploy_with_network_fs", TTR("Small Deploy with Network Filesystem")), RUN_FILE_SERVER); + p->set_item_tooltip( + p->get_item_count() - 1, + TTR("When this option is enabled, using one-click deploy for Android will only export an executable without the project data.\nThe filesystem will be provided from the project by the editor over the network.\nOn Android, deploying will use the USB cable for faster performance. This option speeds up testing for projects with large assets.")); p->add_separator(); p->add_check_shortcut(ED_SHORTCUT("editor/visible_collision_shapes", TTR("Visible Collision Shapes")), RUN_DEBUG_COLLISONS); - p->set_item_tooltip(p->get_item_count() - 1, TTR("Collision shapes and raycast nodes (for 2D and 3D) will be visible on the running game if this option is turned on.")); + p->set_item_tooltip( + p->get_item_count() - 1, + TTR("When this option is enabled, collision shapes and raycast nodes (for 2D and 3D) will be visible in the running project.")); p->add_check_shortcut(ED_SHORTCUT("editor/visible_navigation", TTR("Visible Navigation")), RUN_DEBUG_NAVIGATION); - p->set_item_tooltip(p->get_item_count() - 1, TTR("Navigation meshes and polygons will be visible on the running game if this option is turned on.")); + p->set_item_tooltip( + p->get_item_count() - 1, + TTR("When this option is enabled, navigation meshes and polygons will be visible in the running project.")); p->add_separator(); - //those are now on by default, since they are harmless - p->add_check_shortcut(ED_SHORTCUT("editor/sync_scene_changes", TTR("Sync Scene Changes")), RUN_LIVE_DEBUG); - p->set_item_tooltip(p->get_item_count() - 1, TTR("When this option is turned on, any changes made to the scene in the editor will be replicated in the running game.\nWhen used remotely on a device, this is more efficient with network filesystem.")); - p->set_item_checked(p->get_item_count() - 1, true); - p->add_check_shortcut(ED_SHORTCUT("editor/sync_script_changes", TTR("Sync Script Changes")), RUN_RELOAD_SCRIPTS); - p->set_item_tooltip(p->get_item_count() - 1, TTR("When this option is turned on, any script that is saved will be reloaded on the running game.\nWhen used remotely on a device, this is more efficient with network filesystem.")); - p->set_item_checked(p->get_item_count() - 1, true); + p->add_check_shortcut(ED_SHORTCUT("editor/sync_scene_changes", TTR("Synchronize Scene Changes")), RUN_LIVE_DEBUG); + p->set_item_tooltip( + p->get_item_count() - 1, + TTR("When this option is enabled, any changes made to the scene in the editor will be replicated in the running project.\nWhen used remotely on a device, this is more efficient when the network filesystem option is enabled.")); + p->add_check_shortcut(ED_SHORTCUT("editor/sync_script_changes", TTR("Synchronize Script Changes")), RUN_RELOAD_SCRIPTS); + p->set_item_tooltip( + p->get_item_count() - 1, + TTR("When this option is enabled, any script that is saved will be reloaded in the running project.\nWhen used remotely on a device, this is more efficient when the network filesystem option is enabled.")); // Multi-instance, start/stop instances_menu = memnew(PopupMenu); @@ -174,8 +183,8 @@ void DebuggerEditorPlugin::_update_debug_options() { bool check_file_server = EditorSettings::get_singleton()->get_project_metadata("debug_options", "run_file_server", false); bool check_debug_collisions = EditorSettings::get_singleton()->get_project_metadata("debug_options", "run_debug_collisons", false); bool check_debug_navigation = EditorSettings::get_singleton()->get_project_metadata("debug_options", "run_debug_navigation", false); - bool check_live_debug = EditorSettings::get_singleton()->get_project_metadata("debug_options", "run_live_debug", false); - bool check_reload_scripts = EditorSettings::get_singleton()->get_project_metadata("debug_options", "run_reload_scripts", false); + bool check_live_debug = EditorSettings::get_singleton()->get_project_metadata("debug_options", "run_live_debug", true); + bool check_reload_scripts = EditorSettings::get_singleton()->get_project_metadata("debug_options", "run_reload_scripts", true); int instances = EditorSettings::get_singleton()->get_project_metadata("debug_options", "run_debug_instances", 1); if (check_deploy_remote) { diff --git a/editor/plugins/debugger_editor_plugin.h b/editor/plugins/debugger_editor_plugin.h index 465041b5a7..a6fab01c29 100644 --- a/editor/plugins/debugger_editor_plugin.h +++ b/editor/plugins/debugger_editor_plugin.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -61,8 +61,8 @@ private: void _menu_option(int p_option); public: - virtual String get_name() const { return "Debugger"; } - bool has_main_screen() const { return false; } + virtual String get_name() const override { return "Debugger"; } + bool has_main_screen() const override { return false; } DebuggerEditorPlugin(EditorNode *p_node, MenuButton *p_menu); ~DebuggerEditorPlugin(); diff --git a/editor/plugins/editor_debugger_plugin.cpp b/editor/plugins/editor_debugger_plugin.cpp new file mode 100644 index 0000000000..85114d88ae --- /dev/null +++ b/editor/plugins/editor_debugger_plugin.cpp @@ -0,0 +1,124 @@ +/*************************************************************************/ +/* editor_debugger_plugin.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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_debugger_plugin.h" + +#include "editor/debugger/script_editor_debugger.h" + +void EditorDebuggerPlugin::_breaked(bool p_really_did, bool p_can_debug) { + if (p_really_did) { + emit_signal("breaked", p_can_debug); + } else { + emit_signal("continued"); + } +} + +void EditorDebuggerPlugin::_started() { + emit_signal("started"); +} + +void EditorDebuggerPlugin::_stopped() { + emit_signal("stopped"); +} + +void EditorDebuggerPlugin::_bind_methods() { + ClassDB::bind_method(D_METHOD("send_message", "message", "data"), &EditorDebuggerPlugin::send_message); + ClassDB::bind_method(D_METHOD("register_message_capture", "name", "callable"), &EditorDebuggerPlugin::register_message_capture); + ClassDB::bind_method(D_METHOD("unregister_message_capture", "name"), &EditorDebuggerPlugin::unregister_message_capture); + ClassDB::bind_method(D_METHOD("has_capture", "name"), &EditorDebuggerPlugin::has_capture); + ClassDB::bind_method(D_METHOD("is_breaked"), &EditorDebuggerPlugin::is_breaked); + ClassDB::bind_method(D_METHOD("is_debuggable"), &EditorDebuggerPlugin::is_debuggable); + ClassDB::bind_method(D_METHOD("is_session_active"), &EditorDebuggerPlugin::is_session_active); + + ADD_SIGNAL(MethodInfo("started")); + ADD_SIGNAL(MethodInfo("stopped")); + ADD_SIGNAL(MethodInfo("breaked", PropertyInfo(Variant::BOOL, "can_debug"))); + ADD_SIGNAL(MethodInfo("continued")); +} + +void EditorDebuggerPlugin::attach_debugger(ScriptEditorDebugger *p_debugger) { + debugger = p_debugger; + if (debugger) { + debugger->connect("started", callable_mp(this, &EditorDebuggerPlugin::_started)); + debugger->connect("stopped", callable_mp(this, &EditorDebuggerPlugin::_stopped)); + debugger->connect("breaked", callable_mp(this, &EditorDebuggerPlugin::_breaked)); + } +} + +void EditorDebuggerPlugin::detach_debugger(bool p_call_debugger) { + if (debugger) { + debugger->disconnect("started", callable_mp(this, &EditorDebuggerPlugin::_started)); + debugger->disconnect("stopped", callable_mp(this, &EditorDebuggerPlugin::_stopped)); + debugger->disconnect("breaked", callable_mp(this, &EditorDebuggerPlugin::_breaked)); + if (p_call_debugger && get_script_instance()) { + debugger->remove_debugger_plugin(get_script_instance()->get_script()); + } + debugger = nullptr; + } +} + +void EditorDebuggerPlugin::send_message(const String &p_message, const Array &p_args) { + ERR_FAIL_COND_MSG(!debugger, "Plugin is not attached to debugger"); + debugger->send_message(p_message, p_args); +} + +void EditorDebuggerPlugin::register_message_capture(const StringName &p_name, const Callable &p_callable) { + ERR_FAIL_COND_MSG(!debugger, "Plugin is not attached to debugger"); + debugger->register_message_capture(p_name, p_callable); +} + +void EditorDebuggerPlugin::unregister_message_capture(const StringName &p_name) { + ERR_FAIL_COND_MSG(!debugger, "Plugin is not attached to debugger"); + debugger->unregister_message_capture(p_name); +} + +bool EditorDebuggerPlugin::has_capture(const StringName &p_name) { + ERR_FAIL_COND_V_MSG(!debugger, false, "Plugin is not attached to debugger"); + return debugger->has_capture(p_name); +} + +bool EditorDebuggerPlugin::is_breaked() { + ERR_FAIL_COND_V_MSG(!debugger, false, "Plugin is not attached to debugger"); + return debugger->is_breaked(); +} + +bool EditorDebuggerPlugin::is_debuggable() { + ERR_FAIL_COND_V_MSG(!debugger, false, "Plugin is not attached to debugger"); + return debugger->is_debuggable(); +} + +bool EditorDebuggerPlugin::is_session_active() { + ERR_FAIL_COND_V_MSG(!debugger, false, "Plugin is not attached to debugger"); + return debugger->is_session_active(); +} + +EditorDebuggerPlugin::~EditorDebuggerPlugin() { + detach_debugger(true); +} diff --git a/editor/plugins/editor_debugger_plugin.h b/editor/plugins/editor_debugger_plugin.h new file mode 100644 index 0000000000..b33a8ed925 --- /dev/null +++ b/editor/plugins/editor_debugger_plugin.h @@ -0,0 +1,64 @@ +/*************************************************************************/ +/* editor_debugger_plugin.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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_DEBUGGER_PLUGIN_H +#define EDITOR_DEBUGGER_PLUGIN_H + +#include "scene/gui/control.h" + +class ScriptEditorDebugger; + +class EditorDebuggerPlugin : public Control { + GDCLASS(EditorDebuggerPlugin, Control); + +private: + ScriptEditorDebugger *debugger = nullptr; + + void _breaked(bool p_really_did, bool p_can_debug); + void _started(); + void _stopped(); + +protected: + static void _bind_methods(); + +public: + void attach_debugger(ScriptEditorDebugger *p_debugger); + void detach_debugger(bool p_call_debugger); + void send_message(const String &p_message, const Array &p_args); + void register_message_capture(const StringName &p_name, const Callable &p_callable); + void unregister_message_capture(const StringName &p_name); + bool has_capture(const StringName &p_name); + bool is_breaked(); + bool is_debuggable(); + bool is_session_active(); + ~EditorDebuggerPlugin(); +}; + +#endif // EDITOR_DEBUGGER_PLUGIN_H diff --git a/editor/plugins/editor_preview_plugins.cpp b/editor/plugins/editor_preview_plugins.cpp index 9cb167b41c..eb3c06fba1 100644 --- a/editor/plugins/editor_preview_plugins.cpp +++ b/editor/plugins/editor_preview_plugins.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -37,7 +37,7 @@ #include "editor/editor_scale.h" #include "editor/editor_settings.h" #include "scene/resources/bit_map.h" -#include "scene/resources/dynamic_font.h" +#include "scene/resources/font.h" #include "scene/resources/material.h" #include "scene/resources/mesh.h" #include "servers/audio/audio_stream.h" @@ -106,7 +106,7 @@ Ref<Texture2D> EditorTexturePreviewPlugin::generate(const RES &p_from, const Siz } } - if (img.is_null() || img->empty()) { + if (img.is_null() || img->is_empty()) { return Ref<Texture2D>(); } @@ -127,7 +127,8 @@ Ref<Texture2D> EditorTexturePreviewPlugin::generate(const RES &p_from, const Siz if (new_size.y > p_size.y) { new_size = Vector2(new_size.x * p_size.y / new_size.y, p_size.y); } - img->resize(new_size.x, new_size.y, Image::INTERPOLATE_CUBIC); + Vector2i new_size_i(MAX(1, (int)new_size.x), MAX(1, (int)new_size.y)); + img->resize(new_size_i.x, new_size_i.y, Image::INTERPOLATE_CUBIC); post_process_preview(img); @@ -149,7 +150,7 @@ bool EditorImagePreviewPlugin::handles(const String &p_type) const { Ref<Texture2D> EditorImagePreviewPlugin::generate(const RES &p_from, const Size2 &p_size) const { Ref<Image> img = p_from; - if (img.is_null() || img->empty()) { + if (img.is_null() || img->is_empty()) { return Ref<Image>(); } @@ -300,7 +301,7 @@ EditorPackedScenePreviewPlugin::EditorPackedScenePreviewPlugin() { ////////////////////////////////////////////////////////////////// void EditorMaterialPreviewPlugin::_preview_done(const Variant &p_udata) { - preview_done = true; + preview_done.set(); } void EditorMaterialPreviewPlugin::_bind_methods() { @@ -324,10 +325,10 @@ Ref<Texture2D> EditorMaterialPreviewPlugin::generate(const RES &p_from, const Si RS::get_singleton()->viewport_set_update_mode(viewport, RS::VIEWPORT_UPDATE_ONCE); //once used for capture - preview_done = false; + preview_done.clear(); RS::get_singleton()->request_frame_drawn_callback(const_cast<EditorMaterialPreviewPlugin *>(this), "_preview_done", Variant()); - while (!preview_done) { + while (!preview_done.is_set()) { OS::get_singleton()->delay_usec(10); } @@ -381,7 +382,9 @@ EditorMaterialPreviewPlugin::EditorMaterialPreviewPlugin() { int lats = 32; int lons = 32; - float radius = 1.0; + const double lat_step = Math_TAU / lats; + const double lon_step = Math_TAU / lons; + real_t radius = 1.0; Vector<Vector3> vertices; Vector<Vector3> normals; @@ -390,20 +393,20 @@ EditorMaterialPreviewPlugin::EditorMaterialPreviewPlugin() { Basis tt = Basis(Vector3(0, 1, 0), Math_PI * 0.5); for (int i = 1; i <= lats; i++) { - double lat0 = Math_PI * (-0.5 + (double)(i - 1) / lats); + double lat0 = lat_step * (i - 1) - Math_TAU / 4; double z0 = Math::sin(lat0); double zr0 = Math::cos(lat0); - double lat1 = Math_PI * (-0.5 + (double)i / lats); + double lat1 = lat_step * i - Math_TAU / 4; double z1 = Math::sin(lat1); double zr1 = Math::cos(lat1); for (int j = lons; j >= 1; j--) { - double lng0 = 2 * Math_PI * (double)(j - 1) / lons; + double lng0 = lon_step * (j - 1); double x0 = Math::cos(lng0); double y0 = Math::sin(lng0); - double lng1 = 2 * Math_PI * (double)(j) / lons; + double lng1 = lon_step * j; double x1 = Math::cos(lng1); double y1 = Math::sin(lng1); @@ -465,7 +468,7 @@ EditorMaterialPreviewPlugin::~EditorMaterialPreviewPlugin() { /////////////////////////////////////////////////////////////////////////// -static bool _is_text_char(CharType c) { +static bool _is_text_char(char32_t c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_'; } @@ -524,7 +527,7 @@ Ref<Texture2D> EditorScriptPreviewPlugin::generate(const RES &p_from, const Size bool prev_is_text = false; bool in_keyword = false; for (int i = 0; i < code.length(); i++) { - CharType c = code[i]; + char32_t c = code[i]; if (c > 32) { if (col < thumbnail_size) { Color color = text_color; @@ -674,7 +677,7 @@ EditorAudioStreamPreviewPlugin::EditorAudioStreamPreviewPlugin() { /////////////////////////////////////////////////////////////////////////// void EditorMeshPreviewPlugin::_preview_done(const Variant &p_udata) { - preview_done = true; + preview_done.set(); } void EditorMeshPreviewPlugin::_bind_methods() { @@ -711,10 +714,10 @@ Ref<Texture2D> EditorMeshPreviewPlugin::generate(const RES &p_from, const Size2 RS::get_singleton()->viewport_set_update_mode(viewport, RS::VIEWPORT_UPDATE_ONCE); //once used for capture - preview_done = false; + preview_done.clear(); RS::get_singleton()->request_frame_drawn_callback(const_cast<EditorMeshPreviewPlugin *>(this), "_preview_done", Variant()); - while (!preview_done) { + while (!preview_done.is_set()) { OS::get_singleton()->delay_usec(10); } @@ -789,7 +792,7 @@ EditorMeshPreviewPlugin::~EditorMeshPreviewPlugin() { /////////////////////////////////////////////////////////////////////////// void EditorFontPreviewPlugin::_preview_done(const Variant &p_udata) { - preview_done = true; + preview_done.set(); } void EditorFontPreviewPlugin::_bind_methods() { @@ -797,25 +800,79 @@ void EditorFontPreviewPlugin::_bind_methods() { } bool EditorFontPreviewPlugin::handles(const String &p_type) const { - return ClassDB::is_parent_class(p_type, "DynamicFontData") || ClassDB::is_parent_class(p_type, "DynamicFont"); -} + return ClassDB::is_parent_class(p_type, "FontData") || ClassDB::is_parent_class(p_type, "Font"); +} + +struct FSample { + String script; + String sample; +}; + +static FSample _samples[] = { + { "hani", U"漢語" }, + { "armn", U"Աբ" }, + { "copt", U"Αα" }, + { "cyrl", U"Аб" }, + { "grek", U"Αα" }, + { "hebr", U"אב" }, + { "arab", U"اب" }, + { "syrc", U"ܐܒ" }, + { "thaa", U"ހށ" }, + { "deva", U"आ" }, + { "beng", U"আ" }, + { "guru", U"ਆ" }, + { "gujr", U"આ" }, + { "orya", U"ଆ" }, + { "taml", U"ஆ" }, + { "telu", U"ఆ" }, + { "knda", U"ಆ" }, + { "mylm", U"ആ" }, + { "sinh", U"ආ" }, + { "thai", U"กิ" }, + { "laoo", U"ກິ" }, + { "tibt", U"ༀ" }, + { "mymr", U"က" }, + { "geor", U"Ⴀა" }, + { "hang", U"한글" }, + { "ethi", U"ሀ" }, + { "cher", U"Ꭳ" }, + { "cans", U"ᐁ" }, + { "ogam", U"ᚁ" }, + { "runr", U"ᚠ" }, + { "tglg", U"ᜀ" }, + { "hano", U"ᜠ" }, + { "buhd", U"ᝀ" }, + { "tagb", U"ᝠ" }, + { "khmr", U"ក" }, + { "mong", U"ᠠ" }, + { "limb", U"ᤁ" }, + { "tale", U"ᥐ" }, + { "latn", U"Ab" }, + { "zyyy", U"😀" }, + { "", U"" } +}; Ref<Texture2D> EditorFontPreviewPlugin::generate_from_path(const String &p_path, const Size2 &p_size) const { RES res = ResourceLoader::load(p_path); - Ref<DynamicFont> sampled_font; - if (res->is_class("DynamicFont")) { + Ref<Font> sampled_font; + if (res->is_class("Font")) { sampled_font = res->duplicate(); - if (sampled_font->get_outline_color() == Color(1, 1, 1, 1)) { - sampled_font->set_outline_color(Color(0, 0, 0, 1)); - } - } else if (res->is_class("DynamicFontData")) { + } else if (res->is_class("FontData")) { sampled_font.instance(); - sampled_font->set_font_data(res); + sampled_font->add_data(res->duplicate()); } - sampled_font->set_size(50); - String sampled_text = "Abg"; - Vector2 size = sampled_font->get_string_size(sampled_text); + String sample; + for (int j = 0; j < sampled_font->get_data_count(); j++) { + for (int i = 0; _samples[i].script != String(); i++) { + if (sampled_font->get_data(j)->is_script_supported(_samples[i].script)) { + if (sampled_font->get_data(j)->has_char(_samples[i].sample[0])) { + sample += _samples[i].sample; + } + } + } + } + Vector2 size = sampled_font->get_string_size(sample, 50); Vector2 pos; @@ -824,13 +881,13 @@ Ref<Texture2D> EditorFontPreviewPlugin::generate_from_path(const String &p_path, Ref<Font> font = sampled_font; - font->draw(canvas_item, pos, sampled_text); + font->draw_string(canvas_item, pos, sample, HALIGN_LEFT, -1.f, 50, Color(1, 1, 1)); - preview_done = false; + preview_done.clear(); RS::get_singleton()->viewport_set_update_mode(viewport, RS::VIEWPORT_UPDATE_ONCE); //once used for capture RS::get_singleton()->request_frame_drawn_callback(const_cast<EditorFontPreviewPlugin *>(this), "_preview_done", Variant()); - while (!preview_done) { + while (!preview_done.is_set()) { OS::get_singleton()->delay_usec(10); } diff --git a/editor/plugins/editor_preview_plugins.h b/editor/plugins/editor_preview_plugins.h index 8a9d6a93fb..6e8b9a34cf 100644 --- a/editor/plugins/editor_preview_plugins.h +++ b/editor/plugins/editor_preview_plugins.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -33,15 +33,17 @@ #include "editor/editor_resource_preview.h" +#include "core/templates/safe_refcount.h" + void post_process_preview(Ref<Image> p_image); class EditorTexturePreviewPlugin : public EditorResourcePreviewGenerator { GDCLASS(EditorTexturePreviewPlugin, EditorResourcePreviewGenerator); public: - virtual bool handles(const String &p_type) const; - virtual bool generate_small_preview_automatically() const; - virtual Ref<Texture2D> generate(const RES &p_from, const Size2 &p_size) const; + virtual bool handles(const String &p_type) const override; + virtual bool generate_small_preview_automatically() const override; + virtual Ref<Texture2D> generate(const RES &p_from, const Size2 &p_size) const override; EditorTexturePreviewPlugin(); }; @@ -50,9 +52,9 @@ class EditorImagePreviewPlugin : public EditorResourcePreviewGenerator { GDCLASS(EditorImagePreviewPlugin, EditorResourcePreviewGenerator); public: - virtual bool handles(const String &p_type) const; - virtual bool generate_small_preview_automatically() const; - virtual Ref<Texture2D> generate(const RES &p_from, const Size2 &p_size) const; + virtual bool handles(const String &p_type) const override; + virtual bool generate_small_preview_automatically() const override; + virtual Ref<Texture2D> generate(const RES &p_from, const Size2 &p_size) const override; EditorImagePreviewPlugin(); }; @@ -61,9 +63,9 @@ class EditorBitmapPreviewPlugin : public EditorResourcePreviewGenerator { GDCLASS(EditorBitmapPreviewPlugin, EditorResourcePreviewGenerator); public: - virtual bool handles(const String &p_type) const; - virtual bool generate_small_preview_automatically() const; - virtual Ref<Texture2D> generate(const RES &p_from, const Size2 &p_size) const; + virtual bool handles(const String &p_type) const override; + virtual bool generate_small_preview_automatically() const override; + virtual Ref<Texture2D> generate(const RES &p_from, const Size2 &p_size) const override; EditorBitmapPreviewPlugin(); }; @@ -90,7 +92,7 @@ class EditorMaterialPreviewPlugin : public EditorResourcePreviewGenerator { RID light2; RID light_instance2; RID camera; - mutable volatile bool preview_done; + mutable SafeFlag preview_done; void _preview_done(const Variant &p_udata); @@ -98,9 +100,9 @@ protected: static void _bind_methods(); public: - virtual bool handles(const String &p_type) const; - virtual bool generate_small_preview_automatically() const; - virtual Ref<Texture2D> generate(const RES &p_from, const Size2 &p_size) const; + virtual bool handles(const String &p_type) const override; + virtual bool generate_small_preview_automatically() const override; + virtual Ref<Texture2D> generate(const RES &p_from, const Size2 &p_size) const override; EditorMaterialPreviewPlugin(); ~EditorMaterialPreviewPlugin(); @@ -134,7 +136,7 @@ class EditorMeshPreviewPlugin : public EditorResourcePreviewGenerator { RID light2; RID light_instance2; RID camera; - mutable volatile bool preview_done; + mutable SafeFlag preview_done; void _preview_done(const Variant &p_udata); @@ -142,8 +144,8 @@ protected: static void _bind_methods(); public: - virtual bool handles(const String &p_type) const; - virtual Ref<Texture2D> generate(const RES &p_from, const Size2 &p_size) const; + virtual bool handles(const String &p_type) const override; + virtual Ref<Texture2D> generate(const RES &p_from, const Size2 &p_size) const override; EditorMeshPreviewPlugin(); ~EditorMeshPreviewPlugin(); @@ -156,7 +158,7 @@ class EditorFontPreviewPlugin : public EditorResourcePreviewGenerator { RID viewport_texture; RID canvas; RID canvas_item; - mutable volatile bool preview_done; + mutable SafeFlag preview_done; void _preview_done(const Variant &p_udata); @@ -164,9 +166,9 @@ protected: static void _bind_methods(); public: - virtual bool handles(const String &p_type) const; - virtual Ref<Texture2D> generate(const RES &p_from, const Size2 &p_size) const; - virtual Ref<Texture2D> generate_from_path(const String &p_path, const Size2 &p_size) const; + virtual bool handles(const String &p_type) const override; + virtual Ref<Texture2D> generate(const RES &p_from, const Size2 &p_size) const override; + virtual Ref<Texture2D> generate_from_path(const String &p_path, const Size2 &p_size) const override; EditorFontPreviewPlugin(); ~EditorFontPreviewPlugin(); diff --git a/editor/plugins/font_editor_plugin.cpp b/editor/plugins/font_editor_plugin.cpp new file mode 100644 index 0000000000..fa58eb5480 --- /dev/null +++ b/editor/plugins/font_editor_plugin.cpp @@ -0,0 +1,331 @@ +/*************************************************************************/ +/* font_editor_plugin.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 "font_editor_plugin.h" + +#include "editor/editor_scale.h" + +void FontDataPreview::_notification(int p_what) { + if (p_what == NOTIFICATION_DRAW) { + Color text_color = get_theme_color("font_color", "Label"); + Color line_color = text_color; + line_color.a *= 0.6; + Vector2 pos = (get_size() - line->get_size()) / 2; + line->draw(get_canvas_item(), pos, text_color); + draw_line(Vector2(0, pos.y + line->get_line_ascent()), Vector2(pos.x - 5, pos.y + line->get_line_ascent()), line_color); + draw_line(Vector2(pos.x + line->get_size().x + 5, pos.y + line->get_line_ascent()), Vector2(get_size().x, pos.y + line->get_line_ascent()), line_color); + } +} + +void FontDataPreview::_bind_methods() {} + +Size2 FontDataPreview::get_minimum_size() const { + return Vector2(64, 64) * EDSCALE; +} + +struct FSample { + String script; + String sample; +}; + +static FSample _samples[] = { + { "hani", U"漢語" }, + { "armn", U"Աբ" }, + { "copt", U"Αα" }, + { "cyrl", U"Аб" }, + { "grek", U"Αα" }, + { "hebr", U"אב" }, + { "arab", U"اب" }, + { "syrc", U"ܐܒ" }, + { "thaa", U"ހށ" }, + { "deva", U"आ" }, + { "beng", U"আ" }, + { "guru", U"ਆ" }, + { "gujr", U"આ" }, + { "orya", U"ଆ" }, + { "taml", U"ஆ" }, + { "telu", U"ఆ" }, + { "knda", U"ಆ" }, + { "mylm", U"ആ" }, + { "sinh", U"ආ" }, + { "thai", U"กิ" }, + { "laoo", U"ກິ" }, + { "tibt", U"ༀ" }, + { "mymr", U"က" }, + { "geor", U"Ⴀა" }, + { "hang", U"한글" }, + { "ethi", U"ሀ" }, + { "cher", U"Ꭳ" }, + { "cans", U"ᐁ" }, + { "ogam", U"ᚁ" }, + { "runr", U"ᚠ" }, + { "tglg", U"ᜀ" }, + { "hano", U"ᜠ" }, + { "buhd", U"ᝀ" }, + { "tagb", U"ᝠ" }, + { "khmr", U"ក" }, + { "mong", U"ᠠ" }, + { "limb", U"ᤁ" }, + { "tale", U"ᥐ" }, + { "latn", U"Ab" }, + { "zyyy", U"😀" }, + { "", U"" } +}; + +void FontDataPreview::set_data(const Ref<FontData> &p_data) { + Ref<Font> f = memnew(Font); + f->add_data(p_data); + + line->clear(); + + String sample; + for (int i = 0; _samples[i].script != String(); i++) { + if (p_data->is_script_supported(_samples[i].script)) { + if (p_data->has_char(_samples[i].sample[0])) { + sample += _samples[i].sample; + } + } + } + line->add_string(sample, f, 72); + + update(); +} + +FontDataPreview::FontDataPreview() { + line.instance(); +} + +/*************************************************************************/ + +void FontDataEditor::_notification(int p_what) { + if (p_what == NOTIFICATION_SORT_CHILDREN) { + int split_width = get_name_split_ratio() * get_size().width; + button->set_size(Size2(get_theme_icon("Add", "EditorIcons")->get_width(), get_size().height)); + if (is_layout_rtl()) { + if (le != nullptr) { + fit_child_in_rect(le, Rect2(Vector2(split_width, 0), Size2(split_width, get_size().height))); + } + fit_child_in_rect(chk, Rect2(Vector2(split_width - chk->get_size().x, 0), Size2(chk->get_size().x, get_size().height))); + fit_child_in_rect(button, Rect2(Vector2(0, 0), Size2(button->get_size().width, get_size().height))); + } else { + if (le != nullptr) { + fit_child_in_rect(le, Rect2(Vector2(0, 0), Size2(split_width, get_size().height))); + } + fit_child_in_rect(chk, Rect2(Vector2(split_width, 0), Size2(chk->get_size().x, get_size().height))); + fit_child_in_rect(button, Rect2(Vector2(get_size().width - button->get_size().width, 0), Size2(button->get_size().width, get_size().height))); + } + update(); + } + if (p_what == NOTIFICATION_DRAW) { + int split_width = get_name_split_ratio() * get_size().width; + Color dark_color = get_theme_color("dark_color_2", "Editor"); + if (is_layout_rtl()) { + draw_rect(Rect2(Vector2(0, 0), Size2(split_width, get_size().height)), dark_color); + } else { + draw_rect(Rect2(Vector2(split_width, 0), Size2(split_width, get_size().height)), dark_color); + } + } + if (p_what == NOTIFICATION_THEME_CHANGED) { + if (le != nullptr) { + button->set_icon(get_theme_icon("Add", "EditorIcons")); + } else { + button->set_icon(get_theme_icon("Remove", "EditorIcons")); + } + queue_sort(); + } + if (p_what == NOTIFICATION_RESIZED) { + queue_sort(); + } +} + +void FontDataEditor::update_property() { + if (le == nullptr) { + bool c = get_edited_object()->get(get_edited_property()); + chk->set_pressed(c); + chk->set_disabled(is_read_only()); + } +} + +Size2 FontDataEditor::get_minimum_size() const { + return Size2(0, 60); +} + +void FontDataEditor::_bind_methods() { +} + +void FontDataEditor::init_lang_add() { + le = memnew(LineEdit); + le->set_placeholder("Language code"); + le->set_custom_minimum_size(Size2(get_size().width / 2, 0)); + le->set_editable(true); + add_child(le); + + button->set_icon(get_theme_icon("Add", "EditorIcons")); + button->connect("pressed", callable_mp(this, &FontDataEditor::add_lang)); +} + +void FontDataEditor::init_lang_edit() { + button->set_icon(get_theme_icon("Remove", "EditorIcons")); + button->connect("pressed", callable_mp(this, &FontDataEditor::remove_lang)); + chk->connect("toggled", callable_mp(this, &FontDataEditor::toggle_lang)); +} + +void FontDataEditor::init_script_add() { + le = memnew(LineEdit); + le->set_placeholder("Script code"); + le->set_custom_minimum_size(Size2(get_size().width / 2, 0)); + le->set_editable(true); + add_child(le); + + button->set_icon(get_theme_icon("Add", "EditorIcons")); + button->connect("pressed", callable_mp(this, &FontDataEditor::add_script)); +} + +void FontDataEditor::init_script_edit() { + button->set_icon(get_theme_icon("Remove", "EditorIcons")); + button->connect("pressed", callable_mp(this, &FontDataEditor::remove_script)); + chk->connect("toggled", callable_mp(this, &FontDataEditor::toggle_script)); +} + +void FontDataEditor::add_lang() { + FontData *fd = Object::cast_to<FontData>(get_edited_object()); + if (fd != nullptr && !le->get_text().is_empty()) { + fd->set_language_support_override(le->get_text(), chk->is_pressed()); + le->set_text(""); + chk->set_pressed(false); + } +} + +void FontDataEditor::add_script() { + FontData *fd = Object::cast_to<FontData>(get_edited_object()); + if (fd != nullptr && le->get_text().length() == 4) { + fd->set_script_support_override(le->get_text(), chk->is_pressed()); + le->set_text(""); + chk->set_pressed(false); + } +} + +void FontDataEditor::toggle_lang(bool p_pressed) { + FontData *fd = Object::cast_to<FontData>(get_edited_object()); + if (fd != nullptr) { + String lang = String(get_edited_property()).replace("language_support_override/", ""); + fd->set_language_support_override(lang, p_pressed); + } +} + +void FontDataEditor::toggle_script(bool p_pressed) { + FontData *fd = Object::cast_to<FontData>(get_edited_object()); + if (fd != nullptr) { + String script = String(get_edited_property()).replace("script_support_override/", ""); + fd->set_script_support_override(script, p_pressed); + } +} + +void FontDataEditor::remove_lang() { + FontData *fd = Object::cast_to<FontData>(get_edited_object()); + if (fd != nullptr) { + String lang = String(get_edited_property()).replace("language_support_override/", ""); + fd->remove_language_support_override(lang); + } +} + +void FontDataEditor::remove_script() { + FontData *fd = Object::cast_to<FontData>(get_edited_object()); + if (fd != nullptr) { + String script = String(get_edited_property()).replace("script_support_override/", ""); + fd->remove_script_support_override(script); + } +} + +FontDataEditor::FontDataEditor() { + chk = memnew(CheckBox); + chk->set_text(TTR("On")); + chk->set_flat(true); + add_child(chk); + + button = memnew(Button); + button->set_flat(true); + add_child(button); +} + +/*************************************************************************/ + +bool EditorInspectorPluginFont::can_handle(Object *p_object) { + return Object::cast_to<FontData>(p_object) != nullptr; +} + +void EditorInspectorPluginFont::parse_begin(Object *p_object) { + FontData *fd = Object::cast_to<FontData>(p_object); + ERR_FAIL_COND(!fd); + + FontDataPreview *editor = memnew(FontDataPreview); + editor->set_data(fd); + add_custom_control(editor); +} + +bool EditorInspectorPluginFont::parse_property(Object *p_object, Variant::Type p_type, const String &p_path, PropertyHint p_hint, const String &p_hint_text, int p_usage, bool p_wide) { + if (p_path.begins_with("language_support_override/") && p_object->is_class("FontData")) { + String lang = p_path.replace("language_support_override/", ""); + + FontDataEditor *editor = memnew(FontDataEditor); + if (lang != "_new") { + editor->init_lang_edit(); + } else { + editor->init_lang_add(); + } + add_property_editor(p_path, editor); + + return true; + } + + if (p_path.begins_with("script_support_override/") && p_object->is_class("FontData")) { + String script = p_path.replace("script_support_override/", ""); + + FontDataEditor *editor = memnew(FontDataEditor); + if (script != "_new") { + editor->init_script_edit(); + } else { + editor->init_script_add(); + } + add_property_editor(p_path, editor); + + return true; + } + + return false; +} + +/*************************************************************************/ + +FontEditorPlugin::FontEditorPlugin(EditorNode *p_node) { + Ref<EditorInspectorPluginFont> fd_plugin; + fd_plugin.instance(); + EditorInspector::add_inspector_plugin(fd_plugin); +} diff --git a/editor/plugins/font_editor_plugin.h b/editor/plugins/font_editor_plugin.h new file mode 100644 index 0000000000..04e6c1dac7 --- /dev/null +++ b/editor/plugins/font_editor_plugin.h @@ -0,0 +1,111 @@ +/*************************************************************************/ +/* font_editor_plugin.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 FONT_EDITOR_PLUGIN_H +#define FONT_EDITOR_PLUGIN_H + +#include "editor/editor_node.h" +#include "editor/editor_plugin.h" +#include "scene/resources/font.h" +#include "scene/resources/text_line.h" + +class FontDataPreview : public Control { + GDCLASS(FontDataPreview, Control); + +protected: + void _notification(int p_what); + static void _bind_methods(); + + Ref<TextLine> line; + +public: + virtual Size2 get_minimum_size() const override; + + void set_data(const Ref<FontData> &p_data); + + FontDataPreview(); +}; + +/*************************************************************************/ + +class FontDataEditor : public EditorProperty { + GDCLASS(FontDataEditor, EditorProperty); + + LineEdit *le = nullptr; + CheckBox *chk = nullptr; + Button *button = nullptr; + + void toggle_lang(bool p_pressed); + void toggle_script(bool p_pressed); + void add_lang(); + void add_script(); + void remove_lang(); + void remove_script(); + +protected: + void _notification(int p_what); + + static void _bind_methods(); + +public: + virtual Size2 get_minimum_size() const override; + virtual void update_property() override; + + void init_lang_add(); + void init_lang_edit(); + void init_script_add(); + void init_script_edit(); + + FontDataEditor(); +}; + +/*************************************************************************/ + +class EditorInspectorPluginFont : public EditorInspectorPlugin { + GDCLASS(EditorInspectorPluginFont, EditorInspectorPlugin); + +public: + virtual bool can_handle(Object *p_object) override; + virtual void parse_begin(Object *p_object) override; + virtual bool parse_property(Object *p_object, Variant::Type p_type, const String &p_path, PropertyHint p_hint, const String &p_hint_text, int p_usage, bool p_wide) override; +}; + +/*************************************************************************/ + +class FontEditorPlugin : public EditorPlugin { + GDCLASS(FontEditorPlugin, EditorPlugin); + +public: + FontEditorPlugin(EditorNode *p_node); + + virtual String get_name() const override { return "Font"; } +}; + +#endif // FONT_EDITOR_PLUGIN_H diff --git a/editor/plugins/gi_probe_editor_plugin.cpp b/editor/plugins/gi_probe_editor_plugin.cpp index 94f771e643..f309c5da01 100644 --- a/editor/plugins/gi_probe_editor_plugin.cpp +++ b/editor/plugins/gi_probe_editor_plugin.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -41,7 +41,7 @@ void GIProbeEditorPlugin::_bake() { path = path.get_basename() + "." + gi_probe->get_name() + "_data.res"; } probe_file->set_current_path(path); - probe_file->popup_centered_ratio(); + probe_file->popup_file_dialog(); return; } gi_probe->bake(); @@ -144,7 +144,8 @@ GIProbeEditorPlugin::GIProbeEditorPlugin(EditorNode *p_node) { bake_hb = memnew(HBoxContainer); bake_hb->set_h_size_flags(Control::SIZE_EXPAND_FILL); bake_hb->hide(); - bake = memnew(ToolButton); + bake = memnew(Button); + bake->set_flat(true); bake->set_icon(editor->get_gui_base()->get_theme_icon("Bake", "EditorIcons")); bake->set_text(TTR("Bake GI Probe")); bake->connect("pressed", callable_mp(this, &GIProbeEditorPlugin::_bake)); diff --git a/editor/plugins/gi_probe_editor_plugin.h b/editor/plugins/gi_probe_editor_plugin.h index 508c3d825b..fdf0623561 100644 --- a/editor/plugins/gi_probe_editor_plugin.h +++ b/editor/plugins/gi_probe_editor_plugin.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -43,7 +43,7 @@ class GIProbeEditorPlugin : public EditorPlugin { HBoxContainer *bake_hb; Label *bake_info; - ToolButton *bake; + Button *bake; EditorNode *editor; EditorFileDialog *probe_file; @@ -61,11 +61,11 @@ protected: void _notification(int p_what); public: - virtual String get_name() const { return "GIProbe"; } - bool has_main_screen() const { return false; } - virtual void edit(Object *p_object); - virtual bool handles(Object *p_object) const; - virtual void make_visible(bool p_visible); + virtual String get_name() const override { return "GIProbe"; } + bool has_main_screen() const override { return false; } + virtual void edit(Object *p_object) override; + virtual bool handles(Object *p_object) const override; + virtual void make_visible(bool p_visible) override; GIProbeEditorPlugin(EditorNode *p_node); ~GIProbeEditorPlugin(); diff --git a/editor/plugins/gpu_particles_2d_editor_plugin.cpp b/editor/plugins/gpu_particles_2d_editor_plugin.cpp index 01420dac3e..b447304a3f 100644 --- a/editor/plugins/gpu_particles_2d_editor_plugin.cpp +++ b/editor/plugins/gpu_particles_2d_editor_plugin.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -69,7 +69,7 @@ void GPUParticles2DEditorPlugin::_menu_callback(int p_idx) { generate_visibility_rect->popup_centered(); } break; case MENU_LOAD_EMISSION_MASK: { - file->popup_centered_ratio(); + file->popup_file_dialog(); } break; case MENU_CLEAR_EMISSION_MASK: { @@ -81,7 +81,7 @@ void GPUParticles2DEditorPlugin::_menu_callback(int p_idx) { cpu_particles->set_name(particles->get_name()); cpu_particles->set_transform(particles->get_transform()); cpu_particles->set_visible(particles->is_visible()); - cpu_particles->set_pause_mode(particles->get_pause_mode()); + cpu_particles->set_process_mode(particles->get_process_mode()); cpu_particles->set_z_index(particles->get_z_index()); UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo(); diff --git a/editor/plugins/gpu_particles_2d_editor_plugin.h b/editor/plugins/gpu_particles_2d_editor_plugin.h index c76cecb3a2..0b2028b745 100644 --- a/editor/plugins/gpu_particles_2d_editor_plugin.h +++ b/editor/plugins/gpu_particles_2d_editor_plugin.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -42,7 +42,6 @@ class GPUParticles2DEditorPlugin : public EditorPlugin { GDCLASS(GPUParticles2DEditorPlugin, EditorPlugin); enum { - MENU_GENERATE_VISIBILITY_RECT, MENU_LOAD_EMISSION_MASK, MENU_CLEAR_EMISSION_MASK, @@ -86,11 +85,11 @@ protected: static void _bind_methods(); public: - virtual String get_name() const { return "GPUParticles2D"; } - bool has_main_screen() const { return false; } - virtual void edit(Object *p_object); - virtual bool handles(Object *p_object) const; - virtual void make_visible(bool p_visible); + virtual String get_name() const override { return "GPUParticles2D"; } + bool has_main_screen() const override { return false; } + virtual void edit(Object *p_object) override; + virtual bool handles(Object *p_object) const override; + virtual void make_visible(bool p_visible) override; GPUParticles2DEditorPlugin(EditorNode *p_node); ~GPUParticles2DEditorPlugin(); diff --git a/editor/plugins/gpu_particles_3d_editor_plugin.cpp b/editor/plugins/gpu_particles_3d_editor_plugin.cpp index fa507dd3d7..433a5ae51c 100644 --- a/editor/plugins/gpu_particles_3d_editor_plugin.cpp +++ b/editor/plugins/gpu_particles_3d_editor_plugin.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -213,7 +213,7 @@ GPUParticles3DEditorBase::GPUParticles3DEditorBase() { emission_fill->add_item(TTR("Volume")); emd_vb->add_margin_child(TTR("Emission Source: "), emission_fill); - emission_dialog->get_ok()->set_text(TTR("Create")); + emission_dialog->get_ok_button()->set_text(TTR("Create")); emission_dialog->connect("confirmed", callable_mp(this, &GPUParticles3DEditorBase::_generate_emission_points)); emission_tree_dialog = memnew(SceneTreeDialog); @@ -254,7 +254,7 @@ void GPUParticles3DEditor::_menu_option(int p_option) { return; } - emission_tree_dialog->popup_centered_ratio(); + emission_tree_dialog->popup_scenetree_dialog(); } break; case MENU_OPTION_CONVERT_TO_CPU_PARTICLES: { @@ -263,7 +263,7 @@ void GPUParticles3DEditor::_menu_option(int p_option) { cpu_particles->set_name(node->get_name()); cpu_particles->set_transform(node->get_transform()); cpu_particles->set_visible(node->is_visible()); - cpu_particles->set_pause_mode(node->get_pause_mode()); + cpu_particles->set_process_mode(node->get_process_mode()); UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo(); ur->create_action(TTR("Convert to CPUParticles3D")); @@ -454,7 +454,7 @@ void GPUParticles3DEditorPlugin::make_visible(bool p_visible) { GPUParticles3DEditorPlugin::GPUParticles3DEditorPlugin(EditorNode *p_node) { editor = p_node; particles_editor = memnew(GPUParticles3DEditor); - editor->get_viewport()->add_child(particles_editor); + editor->get_main_control()->add_child(particles_editor); particles_editor->hide(); } diff --git a/editor/plugins/gpu_particles_3d_editor_plugin.h b/editor/plugins/gpu_particles_3d_editor_plugin.h index 7838a63436..bd10895459 100644 --- a/editor/plugins/gpu_particles_3d_editor_plugin.h +++ b/editor/plugins/gpu_particles_3d_editor_plugin.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -71,7 +71,6 @@ class GPUParticles3DEditor : public GPUParticles3DEditorBase { GPUParticles3D *node; enum Menu { - MENU_OPTION_GENERATE_AABB, MENU_OPTION_CREATE_EMISSION_VOLUME_FROM_NODE, MENU_OPTION_CLEAR_EMISSION_VOLUME, @@ -86,7 +85,7 @@ class GPUParticles3DEditor : public GPUParticles3DEditorBase { friend class GPUParticles3DEditorPlugin; - virtual void _generate_emission_points(); + virtual void _generate_emission_points() override; protected: void _notification(int p_notification); @@ -105,11 +104,11 @@ class GPUParticles3DEditorPlugin : public EditorPlugin { EditorNode *editor; public: - virtual String get_name() const { return "GPUParticles3D"; } - bool has_main_screen() const { return false; } - virtual void edit(Object *p_object); - virtual bool handles(Object *p_object) const; - virtual void make_visible(bool p_visible); + virtual String get_name() const override { return "GPUParticles3D"; } + bool has_main_screen() const override { return false; } + virtual void edit(Object *p_object) override; + virtual bool handles(Object *p_object) const override; + virtual void make_visible(bool p_visible) override; GPUParticles3DEditorPlugin(EditorNode *p_node); ~GPUParticles3DEditorPlugin(); diff --git a/editor/plugins/gpu_particles_collision_sdf_editor_plugin.cpp b/editor/plugins/gpu_particles_collision_sdf_editor_plugin.cpp new file mode 100644 index 0000000000..8c4928b7cb --- /dev/null +++ b/editor/plugins/gpu_particles_collision_sdf_editor_plugin.cpp @@ -0,0 +1,201 @@ +/*************************************************************************/ +/* gpu_particles_collision_sdf_editor_plugin.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 "gpu_particles_collision_sdf_editor_plugin.h" + +void GPUParticlesCollisionSDFEditorPlugin::_bake() { + if (col_sdf) { + if (col_sdf->get_texture().is_null() || !col_sdf->get_texture()->get_path().is_resource_file()) { + String path = get_tree()->get_edited_scene_root()->get_filename(); + if (path == String()) { + path = "res://" + col_sdf->get_name() + "_data.exr"; + } else { + String ext = path.get_extension(); + path = path.get_basename() + "." + col_sdf->get_name() + "_data.exr"; + } + probe_file->set_current_path(path); + probe_file->popup_file_dialog(); + return; + } + + _sdf_save_path_and_bake(col_sdf->get_texture()->get_path()); + } +} + +void GPUParticlesCollisionSDFEditorPlugin::edit(Object *p_object) { + GPUParticlesCollisionSDF *s = Object::cast_to<GPUParticlesCollisionSDF>(p_object); + if (!s) { + return; + } + + col_sdf = s; +} + +bool GPUParticlesCollisionSDFEditorPlugin::handles(Object *p_object) const { + return p_object->is_class("GPUParticlesCollisionSDF"); +} + +void GPUParticlesCollisionSDFEditorPlugin::_notification(int p_what) { + if (p_what == NOTIFICATION_PROCESS) { + if (!col_sdf) { + return; + } + + const Vector3i size = col_sdf->get_estimated_cell_size(); + String text = vformat(String::utf8("%d × %d × %d"), size.x, size.y, size.z); + int data_size = 2; + + const double size_mb = size.x * size.y * size.z * data_size / (1024.0 * 1024.0); + text += " - " + vformat(TTR("VRAM Size: %s MB"), String::num(size_mb, 2)); + + if (bake_info->get_text() == text) { + return; + } + + // Color the label depending on the estimated performance level. + Color color; + if (size_mb <= 16.0 + CMP_EPSILON) { + // Fast. + color = bake_info->get_theme_color("success_color", "Editor"); + } else if (size_mb <= 64.0 + CMP_EPSILON) { + // Medium. + color = bake_info->get_theme_color("warning_color", "Editor"); + } else { + // Slow. + color = bake_info->get_theme_color("error_color", "Editor"); + } + bake_info->add_theme_color_override("font_color", color); + + bake_info->set_text(text); + } +} + +void GPUParticlesCollisionSDFEditorPlugin::make_visible(bool p_visible) { + if (p_visible) { + bake_hb->show(); + set_process(true); + } else { + bake_hb->hide(); + set_process(false); + } +} + +EditorProgress *GPUParticlesCollisionSDFEditorPlugin::tmp_progress = nullptr; + +void GPUParticlesCollisionSDFEditorPlugin::bake_func_begin(int p_steps) { + ERR_FAIL_COND(tmp_progress != nullptr); + + tmp_progress = memnew(EditorProgress("bake_sdf", TTR("Bake SDF"), p_steps)); +} + +void GPUParticlesCollisionSDFEditorPlugin::bake_func_step(int p_step, const String &p_description) { + ERR_FAIL_COND(tmp_progress == nullptr); + tmp_progress->step(p_description, p_step, false); +} + +void GPUParticlesCollisionSDFEditorPlugin::bake_func_end() { + ERR_FAIL_COND(tmp_progress == nullptr); + memdelete(tmp_progress); + tmp_progress = nullptr; +} + +void GPUParticlesCollisionSDFEditorPlugin::_sdf_save_path_and_bake(const String &p_path) { + probe_file->hide(); + if (col_sdf) { + Ref<Image> bake_img = col_sdf->bake(); + if (bake_img.is_null()) { + EditorNode::get_singleton()->show_warning("Bake Error."); + return; + } + + Ref<ConfigFile> config; + + config.instance(); + if (FileAccess::exists(p_path + ".import")) { + config->load(p_path + ".import"); + } + + config->set_value("remap", "importer", "3d_texture"); + config->set_value("remap", "type", "StreamTexture3D"); + if (!config->has_section_key("params", "compress/mode")) { + config->set_value("params", "compress/mode", 3); //user may want another compression, so leave it be + } + config->set_value("params", "compress/channel_pack", 1); + config->set_value("params", "mipmaps/generate", false); + config->set_value("params", "slices/horizontal", 1); + config->set_value("params", "slices/vertical", bake_img->get_meta("depth")); + + config->save(p_path + ".import"); + + Error err = bake_img->save_exr(p_path, false); + ERR_FAIL_COND(err); + ResourceLoader::import(p_path); + Ref<Texture> t = ResourceLoader::load(p_path); //if already loaded, it will be updated on refocus? + ERR_FAIL_COND(t.is_null()); + + col_sdf->set_texture(t); + } +} + +void GPUParticlesCollisionSDFEditorPlugin::_bind_methods() { +} + +GPUParticlesCollisionSDFEditorPlugin::GPUParticlesCollisionSDFEditorPlugin(EditorNode *p_node) { + editor = p_node; + bake_hb = memnew(HBoxContainer); + bake_hb->set_h_size_flags(Control::SIZE_EXPAND_FILL); + bake_hb->hide(); + bake = memnew(Button); + bake->set_flat(true); + bake->set_icon(editor->get_gui_base()->get_theme_icon("Bake", "EditorIcons")); + bake->set_text(TTR("Bake SDF")); + bake->connect("pressed", callable_mp(this, &GPUParticlesCollisionSDFEditorPlugin::_bake)); + bake_hb->add_child(bake); + bake_info = memnew(Label); + bake_info->set_h_size_flags(Control::SIZE_EXPAND_FILL); + bake_info->set_clip_text(true); + bake_hb->add_child(bake_info); + + add_control_to_container(CONTAINER_SPATIAL_EDITOR_MENU, bake_hb); + col_sdf = nullptr; + probe_file = memnew(EditorFileDialog); + probe_file->set_file_mode(EditorFileDialog::FILE_MODE_SAVE_FILE); + probe_file->add_filter("*.exr"); + probe_file->connect("file_selected", callable_mp(this, &GPUParticlesCollisionSDFEditorPlugin::_sdf_save_path_and_bake)); + get_editor_interface()->get_base_control()->add_child(probe_file); + probe_file->set_title(TTR("Select path for SDF Texture")); + + GPUParticlesCollisionSDF::bake_begin_function = bake_func_begin; + GPUParticlesCollisionSDF::bake_step_function = bake_func_step; + GPUParticlesCollisionSDF::bake_end_function = bake_func_end; +} + +GPUParticlesCollisionSDFEditorPlugin::~GPUParticlesCollisionSDFEditorPlugin() { +} diff --git a/editor/plugins/gpu_particles_collision_sdf_editor_plugin.h b/editor/plugins/gpu_particles_collision_sdf_editor_plugin.h new file mode 100644 index 0000000000..5a71fc44ef --- /dev/null +++ b/editor/plugins/gpu_particles_collision_sdf_editor_plugin.h @@ -0,0 +1,74 @@ +/*************************************************************************/ +/* gpu_particles_collision_sdf_editor_plugin.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 GPU_PARTICLES_COLLISION_SDF_EDITOR_PLUGIN_H +#define GPU_PARTICLES_COLLISION_SDF_EDITOR_PLUGIN_H + +#include "editor/editor_node.h" +#include "editor/editor_plugin.h" +#include "scene/3d/gpu_particles_collision_3d.h" +#include "scene/resources/material.h" + +class GPUParticlesCollisionSDFEditorPlugin : public EditorPlugin { + GDCLASS(GPUParticlesCollisionSDFEditorPlugin, EditorPlugin); + + GPUParticlesCollisionSDF *col_sdf; + + HBoxContainer *bake_hb; + Label *bake_info; + Button *bake; + EditorNode *editor; + + EditorFileDialog *probe_file; + + static EditorProgress *tmp_progress; + static void bake_func_begin(int p_steps); + static void bake_func_step(int p_step, const String &p_description); + static void bake_func_end(); + + void _bake(); + void _sdf_save_path_and_bake(const String &p_path); + +protected: + static void _bind_methods(); + void _notification(int p_what); + +public: + virtual String get_name() const override { return "GPUParticlesCollisionSDF"; } + bool has_main_screen() const override { return false; } + virtual void edit(Object *p_object) override; + virtual bool handles(Object *p_object) const override; + virtual void make_visible(bool p_visible) override; + + GPUParticlesCollisionSDFEditorPlugin(EditorNode *p_node); + ~GPUParticlesCollisionSDFEditorPlugin(); +}; + +#endif // GPU_PARTICLES_COLLISION_SDF_EDITOR_PLUGIN_H diff --git a/editor/plugins/gradient_editor_plugin.cpp b/editor/plugins/gradient_editor_plugin.cpp index 13b5c8cef5..46fa00f730 100644 --- a/editor/plugins/gradient_editor_plugin.cpp +++ b/editor/plugins/gradient_editor_plugin.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ diff --git a/editor/plugins/gradient_editor_plugin.h b/editor/plugins/gradient_editor_plugin.h index 0641d54d5c..bcbb86e422 100644 --- a/editor/plugins/gradient_editor_plugin.h +++ b/editor/plugins/gradient_editor_plugin.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -28,8 +28,8 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#ifndef TOOLS_EDITOR_PLUGINS_COLOR_RAMP_EDITOR_PLUGIN_H_ -#define TOOLS_EDITOR_PLUGINS_COLOR_RAMP_EDITOR_PLUGIN_H_ +#ifndef GRADIENT_EDITOR_PLUGIN_H +#define GRADIENT_EDITOR_PLUGIN_H #include "editor/editor_node.h" #include "editor/editor_plugin.h" @@ -48,7 +48,7 @@ protected: static void _bind_methods(); public: - virtual Size2 get_minimum_size() const; + virtual Size2 get_minimum_size() const override; void set_gradient(const Ref<Gradient> &p_gradient); GradientEditor(); }; @@ -57,17 +57,17 @@ class EditorInspectorPluginGradient : public EditorInspectorPlugin { GDCLASS(EditorInspectorPluginGradient, EditorInspectorPlugin); public: - virtual bool can_handle(Object *p_object); - virtual void parse_begin(Object *p_object); + virtual bool can_handle(Object *p_object) override; + virtual void parse_begin(Object *p_object) override; }; class GradientEditorPlugin : public EditorPlugin { GDCLASS(GradientEditorPlugin, EditorPlugin); public: - virtual String get_name() const { return "ColorRamp"; } + virtual String get_name() const override { return "Gradient"; } GradientEditorPlugin(EditorNode *p_node); }; -#endif /* TOOLS_EDITOR_PLUGINS_COLOR_RAMP_EDITOR_PLUGIN_H_ */ +#endif // GRADIENT_EDITOR_PLUGIN_H diff --git a/editor/plugins/item_list_editor_plugin.cpp b/editor/plugins/item_list_editor_plugin.cpp index 7402baad57..1ea6630622 100644 --- a/editor/plugins/item_list_editor_plugin.cpp +++ b/editor/plugins/item_list_editor_plugin.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -145,7 +145,7 @@ int ItemListOptionButtonPlugin::get_flags() const { void ItemListOptionButtonPlugin::add_item() { ob->add_item(vformat(TTR("Item %d"), ob->get_item_count())); - _change_notify(); + notify_property_list_changed(); } int ItemListOptionButtonPlugin::get_item_count() const { @@ -154,7 +154,7 @@ int ItemListOptionButtonPlugin::get_item_count() const { void ItemListOptionButtonPlugin::erase(int p_idx) { ob->remove_item(p_idx); - _change_notify(); + notify_property_list_changed(); } ItemListOptionButtonPlugin::ItemListOptionButtonPlugin() { @@ -181,7 +181,7 @@ int ItemListPopupMenuPlugin::get_flags() const { void ItemListPopupMenuPlugin::add_item() { pp->add_item(vformat(TTR("Item %d"), pp->get_item_count())); - _change_notify(); + notify_property_list_changed(); } int ItemListPopupMenuPlugin::get_item_count() const { @@ -190,7 +190,7 @@ int ItemListPopupMenuPlugin::get_item_count() const { void ItemListPopupMenuPlugin::erase(int p_idx) { pp->remove_item(p_idx); - _change_notify(); + notify_property_list_changed(); } ItemListPopupMenuPlugin::ItemListPopupMenuPlugin() { @@ -213,7 +213,7 @@ int ItemListItemListPlugin::get_flags() const { void ItemListItemListPlugin::add_item() { pp->add_item(vformat(TTR("Item %d"), pp->get_item_count())); - _change_notify(); + notify_property_list_changed(); } int ItemListItemListPlugin::get_item_count() const { @@ -222,7 +222,7 @@ int ItemListItemListPlugin::get_item_count() const { void ItemListItemListPlugin::erase(int p_idx) { pp->remove_item(p_idx); - _change_notify(); + notify_property_list_changed(); } ItemListItemListPlugin::ItemListItemListPlugin() { @@ -325,7 +325,8 @@ ItemListEditor::ItemListEditor() { selected_idx = -1; item_list = nullptr; - toolbar_button = memnew(ToolButton); + toolbar_button = memnew(Button); + toolbar_button->set_flat(true); toolbar_button->set_text(TTR("Items")); add_child(toolbar_button); toolbar_button->connect("pressed", callable_mp(this, &ItemListEditor::_edit_items)); diff --git a/editor/plugins/item_list_editor_plugin.h b/editor/plugins/item_list_editor_plugin.h index 61dd617e3b..8c77f3d952 100644 --- a/editor/plugins/item_list_editor_plugin.h +++ b/editor/plugins/item_list_editor_plugin.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -49,7 +49,6 @@ protected: public: enum Flags { - FLAG_ICON = 1, FLAG_CHECKABLE = 2, FLAG_ID = 4, @@ -100,25 +99,25 @@ class ItemListOptionButtonPlugin : public ItemListPlugin { OptionButton *ob; public: - virtual void set_object(Object *p_object); - virtual bool handles(Object *p_object) const; - virtual int get_flags() const; + virtual void set_object(Object *p_object) override; + virtual bool handles(Object *p_object) const override; + virtual int get_flags() const override; - virtual void set_item_text(int p_idx, const String &p_text) { ob->set_item_text(p_idx, p_text); } - virtual String get_item_text(int p_idx) const { return ob->get_item_text(p_idx); } + virtual void set_item_text(int p_idx, const String &p_text) override { ob->set_item_text(p_idx, p_text); } + virtual String get_item_text(int p_idx) const override { return ob->get_item_text(p_idx); } - virtual void set_item_icon(int p_idx, const Ref<Texture2D> &p_tex) { ob->set_item_icon(p_idx, p_tex); } - virtual Ref<Texture2D> get_item_icon(int p_idx) const { return ob->get_item_icon(p_idx); } + virtual void set_item_icon(int p_idx, const Ref<Texture2D> &p_tex) override { ob->set_item_icon(p_idx, p_tex); } + virtual Ref<Texture2D> get_item_icon(int p_idx) const override { return ob->get_item_icon(p_idx); } - virtual void set_item_enabled(int p_idx, int p_enabled) { ob->set_item_disabled(p_idx, !p_enabled); } - virtual bool is_item_enabled(int p_idx) const { return !ob->is_item_disabled(p_idx); } + virtual void set_item_enabled(int p_idx, int p_enabled) override { ob->set_item_disabled(p_idx, !p_enabled); } + virtual bool is_item_enabled(int p_idx) const override { return !ob->is_item_disabled(p_idx); } - virtual void set_item_id(int p_idx, int p_id) { ob->set_item_id(p_idx, p_id); } - virtual int get_item_id(int p_idx) const { return ob->get_item_id(p_idx); } + virtual void set_item_id(int p_idx, int p_id) override { ob->set_item_id(p_idx, p_id); } + virtual int get_item_id(int p_idx) const override { return ob->get_item_id(p_idx); } - virtual void add_item(); - virtual int get_item_count() const; - virtual void erase(int p_idx); + virtual void add_item() override; + virtual int get_item_count() const override; + virtual void erase(int p_idx) override; ItemListOptionButtonPlugin(); }; @@ -129,36 +128,36 @@ class ItemListPopupMenuPlugin : public ItemListPlugin { PopupMenu *pp; public: - virtual void set_object(Object *p_object); - virtual bool handles(Object *p_object) const; - virtual int get_flags() const; + virtual void set_object(Object *p_object) override; + virtual bool handles(Object *p_object) const override; + virtual int get_flags() const override; - virtual void set_item_text(int p_idx, const String &p_text) { pp->set_item_text(p_idx, p_text); } - virtual String get_item_text(int p_idx) const { return pp->get_item_text(p_idx); } + virtual void set_item_text(int p_idx, const String &p_text) override { pp->set_item_text(p_idx, p_text); } + virtual String get_item_text(int p_idx) const override { return pp->get_item_text(p_idx); } - virtual void set_item_icon(int p_idx, const Ref<Texture2D> &p_tex) { pp->set_item_icon(p_idx, p_tex); } - virtual Ref<Texture2D> get_item_icon(int p_idx) const { return pp->get_item_icon(p_idx); } + virtual void set_item_icon(int p_idx, const Ref<Texture2D> &p_tex) override { pp->set_item_icon(p_idx, p_tex); } + virtual Ref<Texture2D> get_item_icon(int p_idx) const override { return pp->get_item_icon(p_idx); } - virtual void set_item_checkable(int p_idx, bool p_check) { pp->set_item_as_checkable(p_idx, p_check); } - virtual void set_item_radio_checkable(int p_idx, bool p_check) { pp->set_item_as_radio_checkable(p_idx, p_check); } - virtual bool is_item_checkable(int p_idx) const { return pp->is_item_checkable(p_idx); } - virtual bool is_item_radio_checkable(int p_idx) const { return pp->is_item_radio_checkable(p_idx); } + virtual void set_item_checkable(int p_idx, bool p_check) override { pp->set_item_as_checkable(p_idx, p_check); } + virtual void set_item_radio_checkable(int p_idx, bool p_check) override { pp->set_item_as_radio_checkable(p_idx, p_check); } + virtual bool is_item_checkable(int p_idx) const override { return pp->is_item_checkable(p_idx); } + virtual bool is_item_radio_checkable(int p_idx) const override { return pp->is_item_radio_checkable(p_idx); } - virtual void set_item_checked(int p_idx, bool p_checked) { pp->set_item_checked(p_idx, p_checked); } - virtual bool is_item_checked(int p_idx) const { return pp->is_item_checked(p_idx); } + virtual void set_item_checked(int p_idx, bool p_checked) override { pp->set_item_checked(p_idx, p_checked); } + virtual bool is_item_checked(int p_idx) const override { return pp->is_item_checked(p_idx); } - virtual void set_item_enabled(int p_idx, int p_enabled) { pp->set_item_disabled(p_idx, !p_enabled); } - virtual bool is_item_enabled(int p_idx) const { return !pp->is_item_disabled(p_idx); } + virtual void set_item_enabled(int p_idx, int p_enabled) override { pp->set_item_disabled(p_idx, !p_enabled); } + virtual bool is_item_enabled(int p_idx) const override { return !pp->is_item_disabled(p_idx); } - virtual void set_item_id(int p_idx, int p_id) { pp->set_item_id(p_idx, p_id); } - virtual int get_item_id(int p_idx) const { return pp->get_item_id(p_idx); } + virtual void set_item_id(int p_idx, int p_id) override { pp->set_item_id(p_idx, p_id); } + virtual int get_item_id(int p_idx) const override { return pp->get_item_id(p_idx); } - virtual void set_item_separator(int p_idx, bool p_separator) { pp->set_item_as_separator(p_idx, p_separator); } - virtual bool is_item_separator(int p_idx) const { return pp->is_item_separator(p_idx); } + virtual void set_item_separator(int p_idx, bool p_separator) override { pp->set_item_as_separator(p_idx, p_separator); } + virtual bool is_item_separator(int p_idx) const override { return pp->is_item_separator(p_idx); } - virtual void add_item(); - virtual int get_item_count() const; - virtual void erase(int p_idx); + virtual void add_item() override; + virtual int get_item_count() const override; + virtual void erase(int p_idx) override; ItemListPopupMenuPlugin(); }; @@ -171,22 +170,22 @@ class ItemListItemListPlugin : public ItemListPlugin { ItemList *pp; public: - virtual void set_object(Object *p_object); - virtual bool handles(Object *p_object) const; - virtual int get_flags() const; + virtual void set_object(Object *p_object) override; + virtual bool handles(Object *p_object) const override; + virtual int get_flags() const override; - virtual void set_item_text(int p_idx, const String &p_text) { pp->set_item_text(p_idx, p_text); } - virtual String get_item_text(int p_idx) const { return pp->get_item_text(p_idx); } + virtual void set_item_text(int p_idx, const String &p_text) override { pp->set_item_text(p_idx, p_text); } + virtual String get_item_text(int p_idx) const override { return pp->get_item_text(p_idx); } - virtual void set_item_icon(int p_idx, const Ref<Texture2D> &p_tex) { pp->set_item_icon(p_idx, p_tex); } - virtual Ref<Texture2D> get_item_icon(int p_idx) const { return pp->get_item_icon(p_idx); } + virtual void set_item_icon(int p_idx, const Ref<Texture2D> &p_tex) override { pp->set_item_icon(p_idx, p_tex); } + virtual Ref<Texture2D> get_item_icon(int p_idx) const override { return pp->get_item_icon(p_idx); } - virtual void set_item_enabled(int p_idx, int p_enabled) { pp->set_item_disabled(p_idx, !p_enabled); } - virtual bool is_item_enabled(int p_idx) const { return !pp->is_item_disabled(p_idx); } + virtual void set_item_enabled(int p_idx, int p_enabled) override { pp->set_item_disabled(p_idx, !p_enabled); } + virtual bool is_item_enabled(int p_idx) const override { return !pp->is_item_disabled(p_idx); } - virtual void add_item(); - virtual int get_item_count() const; - virtual void erase(int p_idx); + virtual void add_item() override; + virtual int get_item_count() const override; + virtual void erase(int p_idx) override; ItemListItemListPlugin(); }; @@ -198,7 +197,7 @@ class ItemListEditor : public HBoxContainer { Node *item_list; - ToolButton *toolbar_button; + Button *toolbar_button; AcceptDialog *dialog; EditorInspector *property_editor; @@ -236,11 +235,11 @@ class ItemListEditorPlugin : public EditorPlugin { EditorNode *editor; public: - virtual String get_name() const { return "ItemList"; } - bool has_main_screen() const { return false; } - virtual void edit(Object *p_object); - virtual bool handles(Object *p_object) const; - virtual void make_visible(bool p_visible); + virtual String get_name() const override { return "ItemList"; } + bool has_main_screen() const override { return false; } + virtual void edit(Object *p_object) override; + virtual bool handles(Object *p_object) const override; + virtual void make_visible(bool p_visible) override; ItemListEditorPlugin(EditorNode *p_node); ~ItemListEditorPlugin(); diff --git a/editor/plugins/light_occluder_2d_editor_plugin.cpp b/editor/plugins/light_occluder_2d_editor_plugin.cpp index e422140efa..3d555d7eba 100644 --- a/editor/plugins/light_occluder_2d_editor_plugin.cpp +++ b/editor/plugins/light_occluder_2d_editor_plugin.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ diff --git a/editor/plugins/light_occluder_2d_editor_plugin.h b/editor/plugins/light_occluder_2d_editor_plugin.h index 11c9f2b2a4..eb1ce04788 100644 --- a/editor/plugins/light_occluder_2d_editor_plugin.h +++ b/editor/plugins/light_occluder_2d_editor_plugin.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -42,18 +42,18 @@ class LightOccluder2DEditor : public AbstractPolygon2DEditor { Ref<OccluderPolygon2D> _ensure_occluder() const; protected: - virtual Node2D *_get_node() const; - virtual void _set_node(Node *p_polygon); + virtual Node2D *_get_node() const override; + virtual void _set_node(Node *p_polygon) override; - virtual bool _is_line() const; - virtual int _get_polygon_count() const; - virtual Variant _get_polygon(int p_idx) const; - virtual void _set_polygon(int p_idx, const Variant &p_polygon) const; + virtual bool _is_line() const override; + virtual int _get_polygon_count() const override; + virtual Variant _get_polygon(int p_idx) const override; + virtual void _set_polygon(int p_idx, const Variant &p_polygon) const override; - virtual void _action_set_polygon(int p_idx, const Variant &p_previous, const Variant &p_polygon); + virtual void _action_set_polygon(int p_idx, const Variant &p_previous, const Variant &p_polygon) override; - virtual bool _has_resource() const; - virtual void _create_resource(); + virtual bool _has_resource() const override; + virtual void _create_resource() override; public: LightOccluder2DEditor(EditorNode *p_editor); diff --git a/editor/plugins/line_2d_editor_plugin.cpp b/editor/plugins/line_2d_editor_plugin.cpp index 77eeb19d26..08c5ef02a4 100644 --- a/editor/plugins/line_2d_editor_plugin.cpp +++ b/editor/plugins/line_2d_editor_plugin.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ diff --git a/editor/plugins/line_2d_editor_plugin.h b/editor/plugins/line_2d_editor_plugin.h index bf411a070a..769109583a 100644 --- a/editor/plugins/line_2d_editor_plugin.h +++ b/editor/plugins/line_2d_editor_plugin.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -40,13 +40,13 @@ class Line2DEditor : public AbstractPolygon2DEditor { Line2D *node; protected: - virtual Node2D *_get_node() const; - virtual void _set_node(Node *p_line); + virtual Node2D *_get_node() const override; + virtual void _set_node(Node *p_line) override; - virtual bool _is_line() const; - virtual Variant _get_polygon(int p_idx) const; - virtual void _set_polygon(int p_idx, const Variant &p_polygon) const; - virtual void _action_set_polygon(int p_idx, const Variant &p_previous, const Variant &p_polygon); + virtual bool _is_line() const override; + virtual Variant _get_polygon(int p_idx) const override; + virtual void _set_polygon(int p_idx, const Variant &p_polygon) const override; + virtual void _action_set_polygon(int p_idx, const Variant &p_previous, const Variant &p_polygon) override; public: Line2DEditor(EditorNode *p_editor); diff --git a/editor/plugins/material_editor_plugin.cpp b/editor/plugins/material_editor_plugin.cpp index e49cfd51f7..ad99ad7808 100644 --- a/editor/plugins/material_editor_plugin.cpp +++ b/editor/plugins/material_editor_plugin.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -108,7 +108,7 @@ MaterialEditor::MaterialEditor() { vc = memnew(SubViewportContainer); vc->set_stretch(true); add_child(vc); - vc->set_anchors_and_margins_preset(PRESET_WIDE); + vc->set_anchors_and_offsets_preset(PRESET_WIDE); viewport = memnew(SubViewport); Ref<World3D> world_3d; world_3d.instance(); @@ -155,7 +155,7 @@ MaterialEditor::MaterialEditor() { HBoxContainer *hb = memnew(HBoxContainer); add_child(hb); - hb->set_anchors_and_margins_preset(Control::PRESET_WIDE, Control::PRESET_MODE_MINSIZE, 2); + hb->set_anchors_and_offsets_preset(Control::PRESET_WIDE, Control::PRESET_MODE_MINSIZE, 2); VBoxContainer *vb_shape = memnew(VBoxContainer); hb->add_child(vb_shape); diff --git a/editor/plugins/material_editor_plugin.h b/editor/plugins/material_editor_plugin.h index e03cb1b3ab..a4532b58b3 100644 --- a/editor/plugins/material_editor_plugin.h +++ b/editor/plugins/material_editor_plugin.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -55,7 +55,7 @@ class MaterialEditor : public Control { Camera3D *camera; Ref<SphereMesh> sphere_mesh; - Ref<CubeMesh> box_mesh; + Ref<BoxMesh> box_mesh; TextureButton *sphere_switch; TextureButton *box_switch; @@ -83,8 +83,8 @@ class EditorInspectorPluginMaterial : public EditorInspectorPlugin { Ref<Environment> env; public: - virtual bool can_handle(Object *p_object); - virtual void parse_begin(Object *p_object); + virtual bool can_handle(Object *p_object) override; + virtual void parse_begin(Object *p_object) override; EditorInspectorPluginMaterial(); }; @@ -93,7 +93,7 @@ class MaterialEditorPlugin : public EditorPlugin { GDCLASS(MaterialEditorPlugin, EditorPlugin); public: - virtual String get_name() const { return "Material"; } + virtual String get_name() const override { return "Material"; } MaterialEditorPlugin(EditorNode *p_node); }; @@ -102,54 +102,54 @@ class StandardMaterial3DConversionPlugin : public EditorResourceConversionPlugin GDCLASS(StandardMaterial3DConversionPlugin, EditorResourceConversionPlugin); public: - virtual String converts_to() const; - virtual bool handles(const Ref<Resource> &p_resource) const; - virtual Ref<Resource> convert(const Ref<Resource> &p_resource) const; + virtual String converts_to() const override; + virtual bool handles(const Ref<Resource> &p_resource) const override; + virtual Ref<Resource> convert(const Ref<Resource> &p_resource) const override; }; class ParticlesMaterialConversionPlugin : public EditorResourceConversionPlugin { GDCLASS(ParticlesMaterialConversionPlugin, EditorResourceConversionPlugin); public: - virtual String converts_to() const; - virtual bool handles(const Ref<Resource> &p_resource) const; - virtual Ref<Resource> convert(const Ref<Resource> &p_resource) const; + virtual String converts_to() const override; + virtual bool handles(const Ref<Resource> &p_resource) const override; + virtual Ref<Resource> convert(const Ref<Resource> &p_resource) const override; }; class CanvasItemMaterialConversionPlugin : public EditorResourceConversionPlugin { GDCLASS(CanvasItemMaterialConversionPlugin, EditorResourceConversionPlugin); public: - virtual String converts_to() const; - virtual bool handles(const Ref<Resource> &p_resource) const; - virtual Ref<Resource> convert(const Ref<Resource> &p_resource) const; + virtual String converts_to() const override; + virtual bool handles(const Ref<Resource> &p_resource) const override; + virtual Ref<Resource> convert(const Ref<Resource> &p_resource) const override; }; class ProceduralSkyMaterialConversionPlugin : public EditorResourceConversionPlugin { GDCLASS(ProceduralSkyMaterialConversionPlugin, EditorResourceConversionPlugin); public: - virtual String converts_to() const; - virtual bool handles(const Ref<Resource> &p_resource) const; - virtual Ref<Resource> convert(const Ref<Resource> &p_resource) const; + virtual String converts_to() const override; + virtual bool handles(const Ref<Resource> &p_resource) const override; + virtual Ref<Resource> convert(const Ref<Resource> &p_resource) const override; }; class PanoramaSkyMaterialConversionPlugin : public EditorResourceConversionPlugin { GDCLASS(PanoramaSkyMaterialConversionPlugin, EditorResourceConversionPlugin); public: - virtual String converts_to() const; - virtual bool handles(const Ref<Resource> &p_resource) const; - virtual Ref<Resource> convert(const Ref<Resource> &p_resource) const; + virtual String converts_to() const override; + virtual bool handles(const Ref<Resource> &p_resource) const override; + virtual Ref<Resource> convert(const Ref<Resource> &p_resource) const override; }; class PhysicalSkyMaterialConversionPlugin : public EditorResourceConversionPlugin { GDCLASS(PhysicalSkyMaterialConversionPlugin, EditorResourceConversionPlugin); public: - virtual String converts_to() const; - virtual bool handles(const Ref<Resource> &p_resource) const; - virtual Ref<Resource> convert(const Ref<Resource> &p_resource) const; + virtual String converts_to() const override; + virtual bool handles(const Ref<Resource> &p_resource) const override; + virtual Ref<Resource> convert(const Ref<Resource> &p_resource) const override; }; #endif // MATERIAL_EDITOR_PLUGIN_H diff --git a/editor/plugins/mesh_editor_plugin.cpp b/editor/plugins/mesh_editor_plugin.cpp index 9d396467c3..1e4553a967 100644 --- a/editor/plugins/mesh_editor_plugin.cpp +++ b/editor/plugins/mesh_editor_plugin.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -137,7 +137,7 @@ MeshEditor::MeshEditor() { HBoxContainer *hb = memnew(HBoxContainer); add_child(hb); - hb->set_anchors_and_margins_preset(Control::PRESET_WIDE, Control::PRESET_MODE_MINSIZE, 2); + hb->set_anchors_and_offsets_preset(Control::PRESET_WIDE, Control::PRESET_MODE_MINSIZE, 2); hb->add_spacer(); diff --git a/editor/plugins/mesh_editor_plugin.h b/editor/plugins/mesh_editor_plugin.h index 6f171a0eab..455fcb5fe9 100644 --- a/editor/plugins/mesh_editor_plugin.h +++ b/editor/plugins/mesh_editor_plugin.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -76,15 +76,15 @@ class EditorInspectorPluginMesh : public EditorInspectorPlugin { GDCLASS(EditorInspectorPluginMesh, EditorInspectorPlugin); public: - virtual bool can_handle(Object *p_object); - virtual void parse_begin(Object *p_object); + virtual bool can_handle(Object *p_object) override; + virtual void parse_begin(Object *p_object) override; }; class MeshEditorPlugin : public EditorPlugin { GDCLASS(MeshEditorPlugin, EditorPlugin); public: - virtual String get_name() const { return "Mesh"; } + virtual String get_name() const override { return "Mesh"; } MeshEditorPlugin(EditorNode *p_node); }; diff --git a/editor/plugins/mesh_instance_3d_editor_plugin.cpp b/editor/plugins/mesh_instance_3d_editor_plugin.cpp index 1b65987af0..0d2b2ea2f5 100644 --- a/editor/plugins/mesh_instance_3d_editor_plugin.cpp +++ b/editor/plugins/mesh_instance_3d_editor_plugin.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -63,7 +63,7 @@ void MeshInstance3DEditor::_menu_option(int p_option) { List<Node *> selection = editor_selection->get_selected_node_list(); - if (selection.empty()) { + if (selection.is_empty()) { Ref<Shape3D> shape = mesh->create_trimesh_shape(); if (shape.is_null()) { err_dialog->set_text(TTR("Couldn't create a Trimesh collision shape.")); @@ -138,6 +138,7 @@ void MeshInstance3DEditor::_menu_option(int p_option) { CollisionShape3D *cshape = memnew(CollisionShape3D); cshape->set_shape(shape); + cshape->set_transform(node->get_transform()); Node *owner = node->get_owner(); @@ -456,7 +457,7 @@ MeshInstance3DEditor::MeshInstance3DEditor() { outline_dialog = memnew(ConfirmationDialog); outline_dialog->set_title(TTR("Create Outline Mesh")); - outline_dialog->get_ok()->set_text(TTR("Create")); + outline_dialog->get_ok_button()->set_text(TTR("Create")); VBoxContainer *outline_dialog_vbc = memnew(VBoxContainer); outline_dialog->add_child(outline_dialog_vbc); @@ -504,7 +505,7 @@ void MeshInstance3DEditorPlugin::make_visible(bool p_visible) { MeshInstance3DEditorPlugin::MeshInstance3DEditorPlugin(EditorNode *p_node) { editor = p_node; mesh_editor = memnew(MeshInstance3DEditor); - editor->get_viewport()->add_child(mesh_editor); + editor->get_main_control()->add_child(mesh_editor); mesh_editor->options->hide(); } diff --git a/editor/plugins/mesh_instance_3d_editor_plugin.h b/editor/plugins/mesh_instance_3d_editor_plugin.h index 3350a792bc..69f494de7f 100644 --- a/editor/plugins/mesh_instance_3d_editor_plugin.h +++ b/editor/plugins/mesh_instance_3d_editor_plugin.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -40,7 +40,6 @@ class MeshInstance3DEditor : public Control { GDCLASS(MeshInstance3DEditor, Control); enum Menu { - MENU_OPTION_CREATE_STATIC_TRIMESH_BODY, MENU_OPTION_CREATE_TRIMESH_COLLISION_SHAPE, MENU_OPTION_CREATE_SINGLE_CONVEX_COLLISION_SHAPE, @@ -89,11 +88,11 @@ class MeshInstance3DEditorPlugin : public EditorPlugin { EditorNode *editor; public: - virtual String get_name() const { return "MeshInstance3D"; } - bool has_main_screen() const { return false; } - virtual void edit(Object *p_object); - virtual bool handles(Object *p_object) const; - virtual void make_visible(bool p_visible); + virtual String get_name() const override { return "MeshInstance3D"; } + bool has_main_screen() const override { return false; } + virtual void edit(Object *p_object) override; + virtual bool handles(Object *p_object) const override; + virtual void make_visible(bool p_visible) override; MeshInstance3DEditorPlugin(EditorNode *p_node); ~MeshInstance3DEditorPlugin(); diff --git a/editor/plugins/mesh_library_editor_plugin.cpp b/editor/plugins/mesh_library_editor_plugin.cpp index 7690beeee8..f8932cd534 100644 --- a/editor/plugins/mesh_library_editor_plugin.cpp +++ b/editor/plugins/mesh_library_editor_plugin.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -224,7 +224,7 @@ void MeshLibraryEditor::_menu_cbk(int p_option) { } } break; case MENU_OPTION_IMPORT_FROM_SCENE: { - file->popup_centered_ratio(); + file->popup_file_dialog(); } break; case MENU_OPTION_UPDATE_FROM_SCENE: { cd->set_text(vformat(TTR("Update from existing scene?:\n%s"), String(mesh_library->get_meta("_editor_source_scene")))); @@ -267,7 +267,7 @@ MeshLibraryEditor::MeshLibraryEditor(EditorNode *p_editor) { editor = p_editor; cd = memnew(ConfirmationDialog); add_child(cd); - cd->get_ok()->connect("pressed", callable_mp(this, &MeshLibraryEditor::_menu_confirm)); + cd->get_ok_button()->connect("pressed", callable_mp(this, &MeshLibraryEditor::_menu_confirm)); } void MeshLibraryEditorPlugin::edit(Object *p_node) { @@ -297,8 +297,10 @@ MeshLibraryEditorPlugin::MeshLibraryEditorPlugin(EditorNode *p_node) { EDITOR_DEF("editors/grid_map/preview_size", 64); mesh_library_editor = memnew(MeshLibraryEditor(p_node)); - p_node->get_viewport()->add_child(mesh_library_editor); - mesh_library_editor->set_anchors_and_margins_preset(Control::PRESET_TOP_WIDE); + p_node->get_main_control()->add_child(mesh_library_editor); + mesh_library_editor->set_anchors_and_offsets_preset(Control::PRESET_TOP_WIDE); mesh_library_editor->set_end(Point2(0, 22)); mesh_library_editor->hide(); + + editor = nullptr; } diff --git a/editor/plugins/mesh_library_editor_plugin.h b/editor/plugins/mesh_library_editor_plugin.h index 61ce5692bc..6c33c8bb9e 100644 --- a/editor/plugins/mesh_library_editor_plugin.h +++ b/editor/plugins/mesh_library_editor_plugin.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -46,7 +46,6 @@ class MeshLibraryEditor : public Control { int to_erase; enum { - MENU_OPTION_ADD_ITEM, MENU_OPTION_REMOVE_ITEM, MENU_OPTION_UPDATE_FROM_SCENE, @@ -79,11 +78,11 @@ class MeshLibraryEditorPlugin : public EditorPlugin { EditorNode *editor; public: - virtual String get_name() const { return "MeshLibrary"; } - bool has_main_screen() const { return false; } - virtual void edit(Object *p_node); - virtual bool handles(Object *p_node) const; - virtual void make_visible(bool p_visible); + virtual String get_name() const override { return "MeshLibrary"; } + bool has_main_screen() const override { return false; } + virtual void edit(Object *p_node) override; + virtual bool handles(Object *p_node) const override; + virtual void make_visible(bool p_visible) override; MeshLibraryEditorPlugin(EditorNode *p_node); }; diff --git a/editor/plugins/multimesh_editor_plugin.cpp b/editor/plugins/multimesh_editor_plugin.cpp index 3904389e09..19c6dcf402 100644 --- a/editor/plugins/multimesh_editor_plugin.cpp +++ b/editor/plugins/multimesh_editor_plugin.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -251,7 +251,7 @@ void MultiMeshEditor::edit(MultiMeshInstance3D *p_multimesh) { void MultiMeshEditor::_browse(bool p_source) { browsing_source = p_source; std->get_scene_tree()->set_marked(node, false); - std->popup_centered_ratio(); + std->popup_scenetree_dialog(); if (p_source) { std->set_title(TTR("Select a Source Mesh:")); } else { @@ -337,7 +337,7 @@ MultiMeshEditor::MultiMeshEditor() { vbc->add_margin_child(TTR("Scale:"), populate_scale); populate_amount = memnew(SpinBox); - populate_amount->set_anchor(MARGIN_RIGHT, ANCHOR_END); + populate_amount->set_anchor(SIDE_RIGHT, ANCHOR_END); populate_amount->set_begin(Point2(20, 232)); populate_amount->set_end(Point2(-5, 237)); populate_amount->set_min(1); @@ -345,9 +345,9 @@ MultiMeshEditor::MultiMeshEditor() { populate_amount->set_value(128); vbc->add_margin_child(TTR("Amount:"), populate_amount); - populate_dialog->get_ok()->set_text(TTR("Populate")); + populate_dialog->get_ok_button()->set_text(TTR("Populate")); - populate_dialog->get_ok()->connect("pressed", callable_mp(this, &MultiMeshEditor::_populate)); + populate_dialog->get_ok_button()->connect("pressed", callable_mp(this, &MultiMeshEditor::_populate)); std = memnew(SceneTreeDialog); populate_dialog->add_child(std); std->connect("selected", callable_mp(this, &MultiMeshEditor::_browsed)); @@ -378,7 +378,7 @@ void MultiMeshEditorPlugin::make_visible(bool p_visible) { MultiMeshEditorPlugin::MultiMeshEditorPlugin(EditorNode *p_node) { editor = p_node; multimesh_editor = memnew(MultiMeshEditor); - editor->get_viewport()->add_child(multimesh_editor); + editor->get_main_control()->add_child(multimesh_editor); multimesh_editor->options->hide(); } diff --git a/editor/plugins/multimesh_editor_plugin.h b/editor/plugins/multimesh_editor_plugin.h index 2b0a0c137f..2cdd7cf504 100644 --- a/editor/plugins/multimesh_editor_plugin.h +++ b/editor/plugins/multimesh_editor_plugin.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -63,7 +63,6 @@ class MultiMeshEditor : public Control { SpinBox *populate_amount; enum Menu { - MENU_OPTION_POPULATE }; @@ -88,11 +87,11 @@ class MultiMeshEditorPlugin : public EditorPlugin { EditorNode *editor; public: - virtual String get_name() const { return "MultiMesh"; } - bool has_main_screen() const { return false; } - virtual void edit(Object *p_object); - virtual bool handles(Object *p_object) const; - virtual void make_visible(bool p_visible); + virtual String get_name() const override { return "MultiMesh"; } + bool has_main_screen() const override { return false; } + virtual void edit(Object *p_object) override; + virtual bool handles(Object *p_object) const override; + virtual void make_visible(bool p_visible) override; MultiMeshEditorPlugin(EditorNode *p_node); ~MultiMeshEditorPlugin(); diff --git a/editor/plugins/navigation_polygon_editor_plugin.cpp b/editor/plugins/navigation_polygon_editor_plugin.cpp index 8cf9f01fa0..9971d3111d 100644 --- a/editor/plugins/navigation_polygon_editor_plugin.cpp +++ b/editor/plugins/navigation_polygon_editor_plugin.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ diff --git a/editor/plugins/navigation_polygon_editor_plugin.h b/editor/plugins/navigation_polygon_editor_plugin.h index 0767322c17..0f5928d416 100644 --- a/editor/plugins/navigation_polygon_editor_plugin.h +++ b/editor/plugins/navigation_polygon_editor_plugin.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -42,19 +42,19 @@ class NavigationPolygonEditor : public AbstractPolygon2DEditor { Ref<NavigationPolygon> _ensure_navpoly() const; protected: - virtual Node2D *_get_node() const; - virtual void _set_node(Node *p_polygon); + virtual Node2D *_get_node() const override; + virtual void _set_node(Node *p_polygon) override; - virtual int _get_polygon_count() const; - virtual Variant _get_polygon(int p_idx) const; - virtual void _set_polygon(int p_idx, const Variant &p_polygon) const; + virtual int _get_polygon_count() const override; + virtual Variant _get_polygon(int p_idx) const override; + virtual void _set_polygon(int p_idx, const Variant &p_polygon) const override; - virtual void _action_add_polygon(const Variant &p_polygon); - virtual void _action_remove_polygon(int p_idx); - virtual void _action_set_polygon(int p_idx, const Variant &p_previous, const Variant &p_polygon); + virtual void _action_add_polygon(const Variant &p_polygon) override; + virtual void _action_remove_polygon(int p_idx) override; + virtual void _action_set_polygon(int p_idx, const Variant &p_previous, const Variant &p_polygon) override; - virtual bool _has_resource() const; - virtual void _create_resource(); + virtual bool _has_resource() const override; + virtual void _create_resource() override; public: NavigationPolygonEditor(EditorNode *p_editor); diff --git a/editor/plugins/node_3d_editor_plugin.cpp b/editor/plugins/node_3d_editor_plugin.cpp index 3c12022854..66c4890c45 100644 --- a/editor/plugins/node_3d_editor_plugin.cpp +++ b/editor/plugins/node_3d_editor_plugin.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -30,12 +30,12 @@ #include "node_3d_editor_plugin.h" +#include "core/config/project_settings.h" #include "core/input/input.h" #include "core/math/camera_matrix.h" #include "core/os/keyboard.h" -#include "core/print_string.h" -#include "core/project_settings.h" -#include "core/sort_array.h" +#include "core/string/print_string.h" +#include "core/templates/sort_array.h" #include "editor/debugger/editor_debugger_node.h" #include "editor/editor_node.h" #include "editor/editor_scale.h" @@ -48,6 +48,7 @@ #include "scene/3d/mesh_instance_3d.h" #include "scene/3d/physics_body_3d.h" #include "scene/3d/visual_instance_3d.h" +#include "scene/gui/center_container.h" #include "scene/gui/subviewport_container.h" #include "scene/resources/packed_scene.h" #include "scene/resources/surface_tool.h" @@ -63,12 +64,15 @@ #define GIZMO_SCALE_OFFSET (GIZMO_CIRCLE_SIZE + 0.3) #define GIZMO_ARROW_OFFSET (GIZMO_CIRCLE_SIZE + 0.3) -#define ZOOM_MIN_DISTANCE 0.001 -#define ZOOM_MULTIPLIER 1.08 -#define ZOOM_INDICATOR_DELAY_S 1.5 +#define ZOOM_FREELOOK_MIN 0.01 +#define ZOOM_FREELOOK_MULTIPLIER 1.08 +#define ZOOM_FREELOOK_INDICATOR_DELAY_S 1.5 -#define FREELOOK_MIN_SPEED 0.01 -#define FREELOOK_SPEED_MULTIPLIER 1.08 +#ifdef REAL_T_IS_DOUBLE +#define ZOOM_FREELOOK_MAX 1'000'000'000'000 +#else +#define ZOOM_FREELOOK_MAX 10'000 +#endif #define MIN_Z 0.01 #define MAX_Z 1000000.0 @@ -138,7 +142,7 @@ void ViewportRotationControl::_draw_axis(const Axis2D &p_axis) { if (front) { String axis_name = direction == 0 ? "X" : (direction == 1 ? "Y" : "Z"); draw_circle(p_axis.screen_point, AXIS_CIRCLE_RADIUS, c); - draw_char(get_theme_font("rotation_control", "EditorFonts"), p_axis.screen_point + Vector2i(-4, 5) * EDSCALE, axis_name, "", Color(0.3, 0.3, 0.3)); + draw_char(get_theme_font("rotation_control", "EditorFonts"), p_axis.screen_point + Vector2i(-4, 5) * EDSCALE, axis_name, "", get_theme_font_size("rotation_control_size", "EditorFonts"), Color(0.3, 0.3, 0.3)); } else { draw_circle(p_axis.screen_point, AXIS_CIRCLE_RADIUS * (0.55 + (0.2 * (1.0 + p_axis.z_axis))), c); } @@ -328,17 +332,13 @@ void Node3DEditorViewport::_update_camera(float p_interp_delta) { //------- // Apply camera transform - float tolerance = 0.001; + real_t tolerance = 0.001; bool equal = true; - if (Math::abs(old_camera_cursor.x_rot - camera_cursor.x_rot) > tolerance || Math::abs(old_camera_cursor.y_rot - camera_cursor.y_rot) > tolerance) { + if (!Math::is_equal_approx(old_camera_cursor.x_rot, camera_cursor.x_rot, tolerance) || !Math::is_equal_approx(old_camera_cursor.y_rot, camera_cursor.y_rot, tolerance)) { equal = false; - } - - if (equal && old_camera_cursor.pos.distance_squared_to(camera_cursor.pos) > tolerance * tolerance) { + } else if (!old_camera_cursor.pos.is_equal_approx(camera_cursor.pos)) { equal = false; - } - - if (equal && Math::abs(old_camera_cursor.distance - camera_cursor.distance) > tolerance) { + } else if (!Math::is_equal_approx(old_camera_cursor.distance, camera_cursor.distance, tolerance)) { equal = false; } @@ -355,6 +355,7 @@ void Node3DEditorViewport::_update_camera(float p_interp_delta) { update_transform_gizmo_view(); rotation_control->update(); + spatial_editor->update_grid(); } } @@ -490,6 +491,10 @@ ObjectID Node3DEditorViewport::_select_ray(const Point2 &p_pos, bool p_append, b Vector3 pos = _get_ray_pos(p_pos); Vector2 shrinked_pos = p_pos / subviewport_container->get_stretch_shrink(); + if (viewport->get_debug_draw() == Viewport::DEBUG_DRAW_SDFGI_PROBES) { + RS::get_singleton()->sdfgi_set_debug_probe_select(pos, ray); + } + Vector<ObjectID> instances = RenderingServer::get_singleton()->instances_cull_ray(pos, ray, get_tree()->get_root()->get_world_3d()->get_scenario()); Set<Ref<EditorNode3DGizmo>> found_gizmos; @@ -530,10 +535,7 @@ ObjectID Node3DEditorViewport::_select_ray(const Point2 &p_pos, bool p_append, b } if (dist < closest_dist) { - item = Object::cast_to<Node>(spat); - while (item->get_owner() && item->get_owner() != edited_scene && !edited_scene->is_editable_instance(item->get_owner())) { - item = item->get_owner(); - } + item = edited_scene->get_deepest_editable_node(Object::cast_to<Node>(spat)); closest = item->get_instance_id(); closest_dist = dist; @@ -608,7 +610,7 @@ void Node3DEditorViewport::_find_items_at_pos(const Point2 &p_pos, bool &r_inclu results.push_back(res); } - if (results.empty()) { + if (results.is_empty()) { return; } @@ -692,10 +694,7 @@ void Node3DEditorViewport::_select_region() { continue; } - Node *item = Object::cast_to<Node>(sp); - while (item->get_owner() && item->get_owner() != edited_scene && !edited_scene->is_editable_instance(item->get_owner())) { - item = item->get_owner(); - } + Node *item = edited_scene->get_deepest_editable_node(Object::cast_to<Node>(sp)); // Replace the node by the group if grouped if (item->is_class("Node3D")) { @@ -835,7 +834,7 @@ bool Node3DEditorViewport::_gizmo_select(const Vector2 &p_screenpos, bool p_high Vector3 r; - if (Geometry::segment_intersects_sphere(ray_pos, ray_pos + ray * MAX_Z, grabber_pos, grabber_radius, &r)) { + if (Geometry3D::segment_intersects_sphere(ray_pos, ray_pos + ray * MAX_Z, grabber_pos, grabber_radius, &r)) { float d = r.distance_to(ray_pos); if (d < col_d) { col_d = d; @@ -899,12 +898,15 @@ bool Node3DEditorViewport::_gizmo_select(const Vector2 &p_screenpos, bool p_high } float dist = r.distance_to(gt.origin); - - if (dist > gs * (GIZMO_CIRCLE_SIZE - GIZMO_RING_HALF_WIDTH) && dist < gs * (GIZMO_CIRCLE_SIZE + GIZMO_RING_HALF_WIDTH)) { - float d = ray_pos.distance_to(r); - if (d < col_d) { - col_d = d; - col_axis = i; + Vector3 r_dir = (r - gt.origin).normalized(); + + if (_get_camera_normal().dot(r_dir) <= 0.005) { + if (dist > gs * (GIZMO_CIRCLE_SIZE - GIZMO_RING_HALF_WIDTH) && dist < gs * (GIZMO_CIRCLE_SIZE + GIZMO_RING_HALF_WIDTH)) { + float d = ray_pos.distance_to(r); + if (d < col_d) { + col_d = d; + col_axis = i; + } } } } @@ -932,7 +934,7 @@ bool Node3DEditorViewport::_gizmo_select(const Vector2 &p_screenpos, bool p_high Vector3 r; - if (Geometry::segment_intersects_sphere(ray_pos, ray_pos + ray * MAX_Z, grabber_pos, grabber_radius, &r)) { + if (Geometry3D::segment_intersects_sphere(ray_pos, ray_pos + ray * MAX_Z, grabber_pos, grabber_radius, &r)) { float d = r.distance_to(ray_pos); if (d < col_d) { col_d = d; @@ -1020,7 +1022,7 @@ void Node3DEditorViewport::_list_select(Ref<InputEventMouseButton> b) { for (int i = 0; i < selection_results.size(); i++) { Node3D *item = selection_results[i].item; - if (item != scene && item->get_owner() != scene && !scene->is_editable_instance(item->get_owner())) { + if (item != scene && item->get_owner() != scene && item != scene->get_deepest_editable_node(item)) { //invalid result selection_results.remove(i); i--; @@ -1038,7 +1040,7 @@ void Node3DEditorViewport::_list_select(Ref<InputEventMouseButton> b) { clicked = ObjectID(); } - } else if (!selection_results.empty()) { + } else if (!selection_results.is_empty()) { NodePath root_path = get_tree()->get_edited_scene_root()->get_path(); StringName root_name = root_path.get_name(root_path.get_name_count() - 1); @@ -1090,7 +1092,7 @@ void Node3DEditorViewport::_sinput(const Ref<InputEvent> &p_event) { { EditorNode *en = editor; EditorPluginList *force_input_forwarding_list = en->get_editor_plugins_force_input_forwarding(); - if (!force_input_forwarding_list->empty()) { + if (!force_input_forwarding_list->is_empty()) { bool discard = force_input_forwarding_list->forward_spatial_gui_input(camera, p_event, true); if (discard) { return; @@ -1100,7 +1102,7 @@ void Node3DEditorViewport::_sinput(const Ref<InputEvent> &p_event) { { EditorNode *en = editor; EditorPluginList *over_plugin_list = en->get_editor_plugins_over(); - if (!over_plugin_list->empty()) { + if (!over_plugin_list->is_empty()) { bool discard = over_plugin_list->forward_spatial_gui_input(camera, p_event, false); if (discard) { return; @@ -1113,7 +1115,7 @@ void Node3DEditorViewport::_sinput(const Ref<InputEvent> &p_event) { if (b.is_valid()) { emit_signal("clicked", this); - float zoom_factor = 1 + (ZOOM_MULTIPLIER - 1) * b->get_factor(); + float zoom_factor = 1 + (ZOOM_FREELOOK_MULTIPLIER - 1) * b->get_factor(); switch (b->get_button_index()) { case BUTTON_WHEEL_UP: { if (is_freelook_active()) { @@ -1927,22 +1929,22 @@ void Node3DEditorViewport::_sinput(const Ref<InputEvent> &p_event) { switch (nav_mode) { case NAVIGATION_PAN: { - _nav_pan(m, pan_gesture->get_delta()); + _nav_pan(pan_gesture, pan_gesture->get_delta()); } break; case NAVIGATION_ZOOM: { - _nav_zoom(m, pan_gesture->get_delta()); + _nav_zoom(pan_gesture, pan_gesture->get_delta()); } break; case NAVIGATION_ORBIT: { - _nav_orbit(m, pan_gesture->get_delta()); + _nav_orbit(pan_gesture, pan_gesture->get_delta()); } break; case NAVIGATION_LOOK: { - _nav_look(m, pan_gesture->get_delta()); + _nav_look(pan_gesture, pan_gesture->get_delta()); } break; @@ -2058,7 +2060,12 @@ void Node3DEditorViewport::_nav_pan(Ref<InputEventWithModifiers> p_event, const camera_transform.translate(cursor.pos); camera_transform.basis.rotate(Vector3(1, 0, 0), -cursor.x_rot); camera_transform.basis.rotate(Vector3(0, 1, 0), -cursor.y_rot); - Vector3 translation(-p_relative.x * pan_speed, p_relative.y * pan_speed, 0); + const bool invert_x_axis = EditorSettings::get_singleton()->get("editors/3d/navigation/invert_x_axis"); + const bool invert_y_axis = EditorSettings::get_singleton()->get("editors/3d/navigation/invert_y_axis"); + Vector3 translation( + (invert_x_axis ? -1 : 1) * -p_relative.x * pan_speed, + (invert_y_axis ? -1 : 1) * p_relative.y * pan_speed, + 0); translation *= cursor.distance / DISTANCE_DEFAULT; camera_transform.translate(translation); cursor.pos = camera_transform.origin; @@ -2099,21 +2106,23 @@ void Node3DEditorViewport::_nav_orbit(Ref<InputEventWithModifiers> p_event, cons _menu_option(VIEW_PERSPECTIVE); } - real_t degrees_per_pixel = EditorSettings::get_singleton()->get("editors/3d/navigation_feel/orbit_sensitivity"); - real_t radians_per_pixel = Math::deg2rad(degrees_per_pixel); - bool invert_y_axis = EditorSettings::get_singleton()->get("editors/3d/navigation/invert_y_axis"); + const real_t degrees_per_pixel = EditorSettings::get_singleton()->get("editors/3d/navigation_feel/orbit_sensitivity"); + const real_t radians_per_pixel = Math::deg2rad(degrees_per_pixel); + const bool invert_y_axis = EditorSettings::get_singleton()->get("editors/3d/navigation/invert_y_axis"); + const bool invert_x_axis = EditorSettings::get_singleton()->get("editors/3d/navigation/invert_x_axis"); if (invert_y_axis) { cursor.x_rot -= p_relative.y * radians_per_pixel; } else { cursor.x_rot += p_relative.y * radians_per_pixel; } - cursor.y_rot += p_relative.x * radians_per_pixel; - if (cursor.x_rot > Math_PI / 2.0) { - cursor.x_rot = Math_PI / 2.0; - } - if (cursor.x_rot < -Math_PI / 2.0) { - cursor.x_rot = -Math_PI / 2.0; + // Clamp the Y rotation to roughly -90..90 degrees so the user can't look upside-down and end up disoriented. + cursor.x_rot = CLAMP(cursor.x_rot, -1.57, 1.57); + + if (invert_x_axis) { + cursor.y_rot -= p_relative.x * radians_per_pixel; + } else { + cursor.y_rot += p_relative.x * radians_per_pixel; } name = ""; _update_name(); @@ -2129,25 +2138,22 @@ void Node3DEditorViewport::_nav_look(Ref<InputEventWithModifiers> p_event, const _menu_option(VIEW_PERSPECTIVE); } - real_t degrees_per_pixel = EditorSettings::get_singleton()->get("editors/3d/freelook/freelook_sensitivity"); - real_t radians_per_pixel = Math::deg2rad(degrees_per_pixel); - bool invert_y_axis = EditorSettings::get_singleton()->get("editors/3d/navigation/invert_y_axis"); + const real_t degrees_per_pixel = EditorSettings::get_singleton()->get("editors/3d/freelook/freelook_sensitivity"); + const real_t radians_per_pixel = Math::deg2rad(degrees_per_pixel); + const bool invert_y_axis = EditorSettings::get_singleton()->get("editors/3d/navigation/invert_y_axis"); // Note: do NOT assume the camera has the "current" transform, because it is interpolated and may have "lag". - Transform prev_camera_transform = to_camera_transform(cursor); + const Transform prev_camera_transform = to_camera_transform(cursor); if (invert_y_axis) { cursor.x_rot -= p_relative.y * radians_per_pixel; } else { cursor.x_rot += p_relative.y * radians_per_pixel; } + // Clamp the Y rotation to roughly -90..90 degrees so the user can't look upside-down and end up disoriented. + cursor.x_rot = CLAMP(cursor.x_rot, -1.57, 1.57); + cursor.y_rot += p_relative.x * radians_per_pixel; - if (cursor.x_rot > Math_PI / 2.0) { - cursor.x_rot = Math_PI / 2.0; - } - if (cursor.x_rot < -Math_PI / 2.0) { - cursor.x_rot = -Math_PI / 2.0; - } // Look is like the opposite of Orbit: the focus point rotates around the camera Transform camera_transform = to_camera_transform(cursor); @@ -2177,6 +2183,8 @@ void Node3DEditorViewport::set_freelook_active(bool active_now) { freelook_speed = base_speed * cursor.distance; } + previous_mouse_position = get_local_mouse_position(); + // Hide mouse like in an FPS (warping doesn't work) Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_CAPTURED); @@ -2186,40 +2194,39 @@ void Node3DEditorViewport::set_freelook_active(bool active_now) { // Restore mouse Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_VISIBLE); + + // Restore the previous mouse position when leaving freelook mode. + // This is done because leaving `Input.MOUSE_MODE_CAPTURED` will center the cursor + // due to OS limitations. + warp_mouse(previous_mouse_position); } freelook_active = active_now; } void Node3DEditorViewport::scale_cursor_distance(real_t scale) { - // Prevents zero distance which would short-circuit any scaling - if (cursor.distance < ZOOM_MIN_DISTANCE) { - cursor.distance = ZOOM_MIN_DISTANCE; - } - - cursor.distance *= scale; - - if (cursor.distance < ZOOM_MIN_DISTANCE) { - cursor.distance = ZOOM_MIN_DISTANCE; + real_t min_distance = MAX(camera->get_near() * 4, ZOOM_FREELOOK_MIN); + real_t max_distance = MIN(camera->get_far() / 4, ZOOM_FREELOOK_MAX); + if (unlikely(min_distance > max_distance)) { + cursor.distance = (min_distance + max_distance) / 2; + } else { + cursor.distance = CLAMP(cursor.distance * scale, min_distance, max_distance); } - zoom_indicator_delay = ZOOM_INDICATOR_DELAY_S; + zoom_indicator_delay = ZOOM_FREELOOK_INDICATOR_DELAY_S; surface->update(); } void Node3DEditorViewport::scale_freelook_speed(real_t scale) { - // Prevents zero distance which would short-circuit any scaling - if (freelook_speed < FREELOOK_MIN_SPEED) { - freelook_speed = FREELOOK_MIN_SPEED; - } - - freelook_speed *= scale; - - if (freelook_speed < FREELOOK_MIN_SPEED) { - freelook_speed = FREELOOK_MIN_SPEED; + real_t min_speed = MAX(camera->get_near() * 4, ZOOM_FREELOOK_MIN); + real_t max_speed = MIN(camera->get_far() / 4, ZOOM_FREELOOK_MAX); + if (unlikely(min_speed > max_speed)) { + freelook_speed = (min_speed + max_speed) / 2; + } else { + freelook_speed = CLAMP(freelook_speed * scale, min_speed, max_speed); } - zoom_indicator_delay = ZOOM_INDICATOR_DELAY_S; + zoom_indicator_delay = ZOOM_FREELOOK_INDICATOR_DELAY_S; surface->update(); } @@ -2234,7 +2241,7 @@ Point2i Node3DEditorViewport::_get_warped_mouse_motion(const Ref<InputEventMouse } static bool is_shortcut_pressed(const String &p_path) { - Ref<ShortCut> shortcut = ED_GET_SHORTCUT(p_path); + Ref<Shortcut> shortcut = ED_GET_SHORTCUT(p_path); if (shortcut.is_null()) { return false; } @@ -2323,7 +2330,43 @@ void Node3DEditorPlugin::edited_scene_changed() { } } +void Node3DEditorViewport::_project_settings_changed() { + //update shadow atlas if changed + int shadowmap_size = ProjectSettings::get_singleton()->get("rendering/shadows/shadow_atlas/size"); + bool shadowmap_16_bits = ProjectSettings::get_singleton()->get("rendering/shadows/shadow_atlas/16_bits"); + int atlas_q0 = ProjectSettings::get_singleton()->get("rendering/shadows/shadow_atlas/quadrant_0_subdiv"); + int atlas_q1 = ProjectSettings::get_singleton()->get("rendering/shadows/shadow_atlas/quadrant_1_subdiv"); + int atlas_q2 = ProjectSettings::get_singleton()->get("rendering/shadows/shadow_atlas/quadrant_2_subdiv"); + int atlas_q3 = ProjectSettings::get_singleton()->get("rendering/shadows/shadow_atlas/quadrant_3_subdiv"); + + viewport->set_shadow_atlas_size(shadowmap_size); + viewport->set_shadow_atlas_16_bits(shadowmap_16_bits); + viewport->set_shadow_atlas_quadrant_subdiv(0, Viewport::ShadowAtlasQuadrantSubdiv(atlas_q0)); + viewport->set_shadow_atlas_quadrant_subdiv(1, Viewport::ShadowAtlasQuadrantSubdiv(atlas_q1)); + viewport->set_shadow_atlas_quadrant_subdiv(2, Viewport::ShadowAtlasQuadrantSubdiv(atlas_q2)); + viewport->set_shadow_atlas_quadrant_subdiv(3, Viewport::ShadowAtlasQuadrantSubdiv(atlas_q3)); + + bool shrink = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_HALF_RESOLUTION)); + + if (shrink != (subviewport_container->get_stretch_shrink() > 1)) { + subviewport_container->set_stretch_shrink(shrink ? 2 : 1); + } + + // Update MSAA, screen-space AA and debanding if changed + + const int msaa_mode = ProjectSettings::get_singleton()->get("rendering/anti_aliasing/quality/msaa"); + viewport->set_msaa(Viewport::MSAA(msaa_mode)); + const int ssaa_mode = GLOBAL_GET("rendering/anti_aliasing/quality/screen_space_aa"); + viewport->set_screen_space_aa(Viewport::ScreenSpaceAA(ssaa_mode)); + const bool use_debanding = GLOBAL_GET("rendering/anti_aliasing/quality/use_debanding"); + viewport->set_use_debanding(use_debanding); +} + void Node3DEditorViewport::_notification(int p_what) { + if (p_what == NOTIFICATION_READY) { + EditorNode::get_singleton()->connect("project_settings_changed", callable_mp(this, &Node3DEditorViewport::_project_settings_changed)); + } + if (p_what == NOTIFICATION_VISIBILITY_CHANGED) { bool visible = is_visible_in_tree(); @@ -2344,13 +2387,6 @@ void Node3DEditorViewport::_notification(int p_what) { call_deferred("update_transform_gizmo_view"); } - if (p_what == NOTIFICATION_READY) { - // The crosshair icon doesn't depend on the editor theme. - crosshair->set_texture(get_theme_icon("Crosshair", "EditorIcons")); - // Set the anchors and margins after changing the icon to ensure it's centered correctly. - crosshair->set_anchors_and_margins_preset(PRESET_CENTER); - } - if (p_what == NOTIFICATION_PROCESS) { real_t delta = get_process_delta_time(); @@ -2397,18 +2433,18 @@ void Node3DEditorViewport::_notification(int p_what) { } Transform t = sp->get_global_gizmo_transform(); + VisualInstance3D *vi = Object::cast_to<VisualInstance3D>(sp); + AABB new_aabb = vi ? vi->get_aabb() : _calculate_spatial_bounds(sp); exist = true; - if (se->last_xform == t && !se->last_xform_dirty) { + if (se->last_xform == t && se->aabb == new_aabb && !se->last_xform_dirty) { continue; } changed = true; se->last_xform_dirty = false; se->last_xform = t; - VisualInstance3D *vi = Object::cast_to<VisualInstance3D>(sp); - - se->aabb = vi ? vi->get_aabb() : _calculate_spatial_bounds(sp); + se->aabb = new_aabb; t.translate(se->aabb.position); @@ -2418,6 +2454,7 @@ void Node3DEditorViewport::_notification(int p_what) { t.basis = t.basis * aabb_s; RenderingServer::get_singleton()->instance_set_transform(se->sbox_instance, t); + RenderingServer::get_singleton()->instance_set_transform(se->sbox_instance_xray, t); } if (changed || (spatial_editor->is_gizmo_visible() && !exist)) { @@ -2436,33 +2473,6 @@ void Node3DEditorViewport::_notification(int p_what) { } } - //update shadow atlas if changed - - int shadowmap_size = ProjectSettings::get_singleton()->get("rendering/quality/shadow_atlas/size"); - int atlas_q0 = ProjectSettings::get_singleton()->get("rendering/quality/shadow_atlas/quadrant_0_subdiv"); - int atlas_q1 = ProjectSettings::get_singleton()->get("rendering/quality/shadow_atlas/quadrant_1_subdiv"); - int atlas_q2 = ProjectSettings::get_singleton()->get("rendering/quality/shadow_atlas/quadrant_2_subdiv"); - int atlas_q3 = ProjectSettings::get_singleton()->get("rendering/quality/shadow_atlas/quadrant_3_subdiv"); - - viewport->set_shadow_atlas_size(shadowmap_size); - viewport->set_shadow_atlas_quadrant_subdiv(0, Viewport::ShadowAtlasQuadrantSubdiv(atlas_q0)); - viewport->set_shadow_atlas_quadrant_subdiv(1, Viewport::ShadowAtlasQuadrantSubdiv(atlas_q1)); - viewport->set_shadow_atlas_quadrant_subdiv(2, Viewport::ShadowAtlasQuadrantSubdiv(atlas_q2)); - viewport->set_shadow_atlas_quadrant_subdiv(3, Viewport::ShadowAtlasQuadrantSubdiv(atlas_q3)); - - bool shrink = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_HALF_RESOLUTION)); - - if (shrink != (subviewport_container->get_stretch_shrink() > 1)) { - subviewport_container->set_stretch_shrink(shrink ? 2 : 1); - } - - //update msaa if changed - - int msaa_mode = ProjectSettings::get_singleton()->get("rendering/quality/screen_filters/msaa"); - viewport->set_msaa(Viewport::MSAA(msaa_mode)); - int ssaa_mode = GLOBAL_GET("rendering/quality/screen_filters/screen_space_aa"); - viewport->set_screen_space_aa(Viewport::ScreenSpaceAA(ssaa_mode)); - bool show_info = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_INFORMATION)); if (show_info != info_label->is_visible()) { info_label->set_visible(show_info); @@ -2476,10 +2486,6 @@ void Node3DEditorViewport::_notification(int p_what) { current_camera = camera; } - // Display the crosshair only while freelooking. Hide it otherwise, - // as the crosshair can be distracting. - crosshair->set_visible(freelook_active); - if (show_info) { String text; text += "X: " + rtos(current_camera->get_translation().x).pad_decimals(1) + "\n"; @@ -2487,6 +2493,13 @@ void Node3DEditorViewport::_notification(int p_what) { text += "Z: " + rtos(current_camera->get_translation().z).pad_decimals(1) + "\n"; text += TTR("Pitch") + ": " + itos(Math::round(current_camera->get_rotation_degrees().x)) + "\n"; text += TTR("Yaw") + ": " + itos(Math::round(current_camera->get_rotation_degrees().y)) + "\n\n"; + + text += TTR("Size") + + vformat( + ": %dx%d (%.1fMP)\n", + viewport->get_size().x, + viewport->get_size().y, + viewport->get_size().x * viewport->get_size().y * 0.000'001); text += TTR("Objects Drawn") + ": " + itos(viewport->get_render_info(Viewport::RENDER_INFO_OBJECTS_IN_FRAME)) + "\n"; text += TTR("Material Changes") + ": " + itos(viewport->get_render_info(Viewport::RENDER_INFO_MATERIAL_CHANGES_IN_FRAME)) + "\n"; text += TTR("Shader Changes") + ": " + itos(viewport->get_render_info(Viewport::RENDER_INFO_SHADER_CHANGES_IN_FRAME)) + "\n"; @@ -2501,6 +2514,8 @@ void Node3DEditorViewport::_notification(int p_what) { bool show_fps = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_FRAME_TIME)); if (show_fps != fps_label->is_visible()) { + cpu_time_label->set_visible(show_fps); + gpu_time_label->set_visible(show_fps); fps_label->set_visible(show_fps); RS::get_singleton()->viewport_set_measure_render_time(viewport->get_viewport_rid(), show_fps); for (int i = 0; i < FRAME_TIME_HISTORY; i++) { @@ -2508,7 +2523,7 @@ void Node3DEditorViewport::_notification(int p_what) { gpu_time_history[i] = 0; } cpu_time_history_index = 0; - cpu_time_history_index = 0; + gpu_time_history_index = 0; } if (show_fps) { cpu_time_history[cpu_time_history_index] = RS::get_singleton()->viewport_get_measured_render_time_cpu(viewport->get_viewport_rid()); @@ -2527,24 +2542,40 @@ void Node3DEditorViewport::_notification(int p_what) { } gpu_time /= FRAME_TIME_HISTORY; - String text; - text += TTR("CPU Time") + ": " + String::num(cpu_time, 1) + " ms\n"; - text += TTR("GPU Time") + ": " + String::num(gpu_time, 1) + " ms\n"; - text += TTR("FPS") + ": " + itos(1000.0 / gpu_time); - - fps_label->set_text(text); + // Color labels depending on performance level ("good" = green, "OK" = yellow, "bad" = red). + // Middle point is at 15 ms. + cpu_time_label->set_text(vformat(TTR("CPU Time: %s ms"), String::num(cpu_time, 1))); + cpu_time_label->add_theme_color_override( + "font_color", + frame_time_gradient->get_color_at_offset( + Math::range_lerp(cpu_time, 0, 30, 0, 1))); + + gpu_time_label->set_text(vformat(TTR("GPU Time: %s ms"), String::num(gpu_time, 1))); + // Middle point is at 15 ms. + gpu_time_label->add_theme_color_override( + "font_color", + frame_time_gradient->get_color_at_offset( + Math::range_lerp(gpu_time, 0, 30, 0, 1))); + + const float fps = 1000.0 / gpu_time; + fps_label->set_text(vformat(TTR("FPS: %d"), fps)); + // Middle point is at 60 FPS. + fps_label->add_theme_color_override( + "font_color", + frame_time_gradient->get_color_at_offset( + Math::range_lerp(fps, 110, 10, 0, 1))); } bool show_cinema = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(VIEW_CINEMATIC_PREVIEW)); cinema_label->set_visible(show_cinema); if (show_cinema) { float cinema_half_width = cinema_label->get_size().width / 2.0f; - cinema_label->set_anchor_and_margin(MARGIN_LEFT, 0.5f, -cinema_half_width); + cinema_label->set_anchor_and_offset(SIDE_LEFT, 0.5f, -cinema_half_width); } if (lock_rotation) { float locked_half_width = locked_label->get_size().width / 2.0f; - locked_label->set_anchor_and_margin(MARGIN_LEFT, 0.5f, -locked_half_width); + locked_label->set_anchor_and_offset(SIDE_LEFT, 0.5f, -locked_half_width); } } @@ -2564,7 +2595,7 @@ void Node3DEditorViewport::_notification(int p_what) { } if (p_what == NOTIFICATION_THEME_CHANGED) { - view_menu->set_icon(get_theme_icon("GuiTabMenu", "EditorIcons")); + view_menu->set_icon(get_theme_icon("GuiTabMenuHl", "EditorIcons")); preview_camera->set_icon(get_theme_icon("Camera3D", "EditorIcons")); view_menu->add_theme_style_override("normal", editor->get_gui_base()->get_theme_stylebox("Information3dViewport", "EditorStyles")); @@ -2579,21 +2610,27 @@ void Node3DEditorViewport::_notification(int p_what) { preview_camera->add_theme_style_override("focus", editor->get_gui_base()->get_theme_stylebox("Information3dViewport", "EditorStyles")); preview_camera->add_theme_style_override("disabled", editor->get_gui_base()->get_theme_stylebox("Information3dViewport", "EditorStyles")); + frame_time_gradient->set_color(0, get_theme_color("success_color", "Editor")); + frame_time_gradient->set_color(1, get_theme_color("warning_color", "Editor")); + frame_time_gradient->set_color(2, get_theme_color("error_color", "Editor")); + info_label->add_theme_style_override("normal", editor->get_gui_base()->get_theme_stylebox("Information3dViewport", "EditorStyles")); + cpu_time_label->add_theme_style_override("normal", editor->get_gui_base()->get_theme_stylebox("Information3dViewport", "EditorStyles")); + gpu_time_label->add_theme_style_override("normal", editor->get_gui_base()->get_theme_stylebox("Information3dViewport", "EditorStyles")); fps_label->add_theme_style_override("normal", editor->get_gui_base()->get_theme_stylebox("Information3dViewport", "EditorStyles")); cinema_label->add_theme_style_override("normal", editor->get_gui_base()->get_theme_stylebox("Information3dViewport", "EditorStyles")); locked_label->add_theme_style_override("normal", editor->get_gui_base()->get_theme_stylebox("Information3dViewport", "EditorStyles")); } } -static void draw_indicator_bar(Control &surface, real_t fill, Ref<Texture2D> icon) { +static void draw_indicator_bar(Control &surface, real_t fill, const Ref<Texture2D> icon, const Ref<Font> font, int font_size, const String &text) { // Adjust bar size from control height - Vector2 surface_size = surface.get_size(); - real_t h = surface_size.y / 2.0; - real_t y = (surface_size.y - h) / 2.0; + const Vector2 surface_size = surface.get_size(); + const real_t h = surface_size.y / 2.0; + const real_t y = (surface_size.y - h) / 2.0; - Rect2 r(10, y, 6, h); - real_t sy = r.size.y * fill; + const Rect2 r(10 * EDSCALE, y, 6 * EDSCALE, h); + const real_t sy = r.size.y * fill; // Note: because this bar appears over the viewport, it has to stay readable for any background color // Draw both neutral dark and bright colors to account this @@ -2601,19 +2638,22 @@ static void draw_indicator_bar(Control &surface, real_t fill, Ref<Texture2D> ico surface.draw_rect(Rect2(r.position.x, r.position.y + r.size.y - sy, r.size.x, sy), Color(1, 1, 1, 0.6)); surface.draw_rect(r.grow(1), Color(0, 0, 0, 0.7), false, Math::round(EDSCALE)); - Vector2 icon_size = icon->get_size(); - Vector2 icon_pos = Vector2(r.position.x - (icon_size.x - r.size.x) / 2, r.position.y + r.size.y + 2); + const Vector2 icon_size = icon->get_size(); + const Vector2 icon_pos = Vector2(r.position.x - (icon_size.x - r.size.x) / 2, r.position.y + r.size.y + 2 * EDSCALE); surface.draw_texture(icon, icon_pos); + + // Draw text below the bar (for speed/zoom information). + surface.draw_string(font, Vector2(icon_pos.x, icon_pos.y + icon_size.y + 16 * EDSCALE), text, HALIGN_LEFT, -1.f, font_size); } void Node3DEditorViewport::_draw() { EditorPluginList *over_plugin_list = EditorNode::get_singleton()->get_editor_plugins_over(); - if (!over_plugin_list->empty()) { + if (!over_plugin_list->is_empty()) { over_plugin_list->forward_spatial_draw_over_viewport(surface); } EditorPluginList *force_over_plugin_list = editor->get_editor_plugins_force_over(); - if (!force_over_plugin_list->empty()) { + if (!force_over_plugin_list->is_empty()) { force_over_plugin_list->forward_spatial_force_draw_over_viewport(surface); } @@ -2641,19 +2681,40 @@ void Node3DEditorViewport::_draw() { if (message_time > 0) { Ref<Font> font = get_theme_font("font", "Label"); + int font_size = get_theme_font_size("font_size", "Label"); Point2 msgpos = Point2(5, get_size().y - 20); - font->draw(ci, msgpos + Point2(1, 1), message, Color(0, 0, 0, 0.8)); - font->draw(ci, msgpos + Point2(-1, -1), message, Color(0, 0, 0, 0.8)); - font->draw(ci, msgpos, message, Color(1, 1, 1, 1)); + font->draw_string(ci, msgpos + Point2(1, 1), message, HALIGN_LEFT, -1, font_size, Color(0, 0, 0, 0.8)); + font->draw_string(ci, msgpos + Point2(-1, -1), message, HALIGN_LEFT, -1, font_size, Color(0, 0, 0, 0.8)); + font->draw_string(ci, msgpos, message, HALIGN_LEFT, -1, font_size, Color(1, 1, 1, 1)); } if (_edit.mode == TRANSFORM_ROTATE) { Point2 center = _point_to_screen(_edit.center); + + Color handle_color; + switch (_edit.plane) { + case TRANSFORM_X_AXIS: + handle_color = get_theme_color("axis_x_color", "Editor"); + break; + case TRANSFORM_Y_AXIS: + handle_color = get_theme_color("axis_y_color", "Editor"); + break; + case TRANSFORM_Z_AXIS: + handle_color = get_theme_color("axis_z_color", "Editor"); + break; + default: + handle_color = get_theme_color("accent_color", "Editor"); + break; + } + handle_color.a = 1.0; + const float brightness = 1.3; + handle_color *= Color(brightness, brightness, brightness); + RenderingServer::get_singleton()->canvas_item_add_line( ci, _edit.mouse_pos, center, - get_theme_color("accent_color", "Editor") * Color(1, 1, 1, 0.6), + handle_color, Math::round(2 * EDSCALE)); } if (previewing) { @@ -2678,7 +2739,7 @@ void Node3DEditorViewport::_draw() { } break; } - draw_rect = Rect2(Vector2(), s).clip(draw_rect); + draw_rect = Rect2(Vector2(), s).intersection(draw_rect); surface->draw_rect(draw_rect, Color(0.6, 0.6, 0.1, 0.5), false, Math::round(2 * EDSCALE)); @@ -2687,39 +2748,43 @@ void Node3DEditorViewport::_draw() { if (is_freelook_active()) { // Show speed - real_t min_speed = FREELOOK_MIN_SPEED; - real_t max_speed = camera->get_zfar(); + real_t min_speed = MAX(camera->get_near() * 4, ZOOM_FREELOOK_MIN); + real_t max_speed = MIN(camera->get_far() / 4, ZOOM_FREELOOK_MAX); real_t scale_length = (max_speed - min_speed); if (!Math::is_zero_approx(scale_length)) { real_t logscale_t = 1.0 - Math::log(1 + freelook_speed - min_speed) / Math::log(1 + scale_length); - // There is no real maximum speed so that factor can become negative, - // Let's make it look asymptotic instead (will decrease slower and slower). - if (logscale_t < 0.25) { - logscale_t = 0.25 * Math::exp(4.0 * logscale_t - 1.0); - } - - draw_indicator_bar(*surface, 1.0 - logscale_t, get_theme_icon("ViewportSpeed", "EditorIcons")); + // Display the freelook speed to help the user get a better sense of scale. + const int precision = freelook_speed < 1.0 ? 2 : 1; + draw_indicator_bar( + *surface, + 1.0 - logscale_t, + get_theme_icon("ViewportSpeed", "EditorIcons"), + get_theme_font("font", "Label"), + get_theme_font_size("font_size", "Label"), + vformat("%s u/s", String::num(freelook_speed).pad_decimals(precision))); } } else { // Show zoom - real_t min_distance = ZOOM_MIN_DISTANCE; // TODO Why not pick znear to limit zoom? - real_t max_distance = camera->get_zfar(); + real_t min_distance = MAX(camera->get_near() * 4, ZOOM_FREELOOK_MIN); + real_t max_distance = MIN(camera->get_far() / 4, ZOOM_FREELOOK_MAX); real_t scale_length = (max_distance - min_distance); if (!Math::is_zero_approx(scale_length)) { real_t logscale_t = 1.0 - Math::log(1 + cursor.distance - min_distance) / Math::log(1 + scale_length); - // There is no real maximum distance so that factor can become negative, - // Let's make it look asymptotic instead (will decrease slower and slower). - if (logscale_t < 0.25) { - logscale_t = 0.25 * Math::exp(4.0 * logscale_t - 1.0); - } - - draw_indicator_bar(*surface, logscale_t, get_theme_icon("ViewportZoom", "EditorIcons")); + // Display the zoom center distance to help the user get a better sense of scale. + const int precision = cursor.distance < 1.0 ? 2 : 1; + draw_indicator_bar( + *surface, + logscale_t, + get_theme_icon("ViewportZoom", "EditorIcons"), + get_theme_font("font", "Label"), + get_theme_font_size("font_size", "Label"), + vformat("%s u", String::num(cursor.distance).pad_decimals(precision))); } } } @@ -2766,7 +2831,7 @@ void Node3DEditorViewport::_menu_option(int p_option) { } break; case VIEW_FRONT: { cursor.x_rot = 0; - cursor.y_rot = 0; + cursor.y_rot = Math_PI; set_message(TTR("Front View."), 2); name = TTR("Front"); _set_auto_orthogonal(); @@ -2775,7 +2840,7 @@ void Node3DEditorViewport::_menu_option(int p_option) { } break; case VIEW_REAR: { cursor.x_rot = 0; - cursor.y_rot = Math_PI; + cursor.y_rot = 0; set_message(TTR("Rear View."), 2); name = TTR("Rear"); _set_auto_orthogonal(); @@ -2943,11 +3008,11 @@ void Node3DEditorViewport::_menu_option(int p_option) { int idx = view_menu->get_popup()->get_item_index(VIEW_GIZMOS); bool current = view_menu->get_popup()->is_item_checked(idx); current = !current; + uint32_t layers = ((1 << 20) - 1) | (1 << (GIZMO_BASE_LAYER + index)) | (1 << GIZMO_GRID_LAYER) | (1 << MISC_TOOL_LAYER); if (current) { - camera->set_cull_mask(((1 << 20) - 1) | (1 << (GIZMO_BASE_LAYER + index)) | (1 << GIZMO_EDIT_LAYER) | (1 << GIZMO_GRID_LAYER)); - } else { - camera->set_cull_mask(((1 << 20) - 1) | (1 << (GIZMO_BASE_LAYER + index)) | (1 << GIZMO_GRID_LAYER)); + layers |= (1 << GIZMO_EDIT_LAYER); } + camera->set_cull_mask(layers); view_menu->get_popup()->set_item_checked(idx, current); } break; @@ -2984,7 +3049,14 @@ void Node3DEditorViewport::_menu_option(int p_option) { case VIEW_DISPLAY_DEBUG_SSAO: case VIEW_DISPLAY_DEBUG_PSSM_SPLITS: case VIEW_DISPLAY_DEBUG_DECAL_ATLAS: - case VIEW_DISPLAY_DEBUG_ROUGHNESS_LIMITER: { + case VIEW_DISPLAY_DEBUG_SDFGI: + case VIEW_DISPLAY_DEBUG_SDFGI_PROBES: + case VIEW_DISPLAY_DEBUG_GI_BUFFER: + case VIEW_DISPLAY_DEBUG_DISABLE_LOD: + case VIEW_DISPLAY_DEBUG_CLUSTER_OMNI_LIGHTS: + case VIEW_DISPLAY_DEBUG_CLUSTER_SPOT_LIGHTS: + case VIEW_DISPLAY_DEBUG_CLUSTER_DECALS: + case VIEW_DISPLAY_DEBUG_CLUSTER_REFLECTION_PROBES: { static const int display_options[] = { VIEW_DISPLAY_NORMAL, VIEW_DISPLAY_WIREFRAME, @@ -3000,9 +3072,16 @@ void Node3DEditorViewport::_menu_option(int p_option) { VIEW_DISPLAY_DEBUG_GIPROBE_EMISSION, VIEW_DISPLAY_DEBUG_SCENE_LUMINANCE, VIEW_DISPLAY_DEBUG_SSAO, - VIEW_DISPLAY_DEBUG_ROUGHNESS_LIMITER, + VIEW_DISPLAY_DEBUG_GI_BUFFER, + VIEW_DISPLAY_DEBUG_DISABLE_LOD, VIEW_DISPLAY_DEBUG_PSSM_SPLITS, VIEW_DISPLAY_DEBUG_DECAL_ATLAS, + VIEW_DISPLAY_DEBUG_SDFGI, + VIEW_DISPLAY_DEBUG_SDFGI_PROBES, + VIEW_DISPLAY_DEBUG_CLUSTER_OMNI_LIGHTS, + VIEW_DISPLAY_DEBUG_CLUSTER_SPOT_LIGHTS, + VIEW_DISPLAY_DEBUG_CLUSTER_DECALS, + VIEW_DISPLAY_DEBUG_CLUSTER_REFLECTION_PROBES, VIEW_MAX }; static const Viewport::DebugDraw debug_draw_modes[] = { @@ -3020,9 +3099,16 @@ void Node3DEditorViewport::_menu_option(int p_option) { Viewport::DEBUG_DRAW_GI_PROBE_EMISSION, Viewport::DEBUG_DRAW_SCENE_LUMINANCE, Viewport::DEBUG_DRAW_SSAO, - Viewport::DEBUG_DRAW_ROUGHNESS_LIMITER, + Viewport::DEBUG_DRAW_GI_BUFFER, + Viewport::DEBUG_DRAW_DISABLE_LOD, Viewport::DEBUG_DRAW_PSSM_SPLITS, Viewport::DEBUG_DRAW_DECAL_ATLAS, + Viewport::DEBUG_DRAW_SDFGI, + Viewport::DEBUG_DRAW_SDFGI_PROBES, + Viewport::DEBUG_DRAW_CLUSTER_OMNI_LIGHTS, + Viewport::DEBUG_DRAW_CLUSTER_SPOT_LIGHTS, + Viewport::DEBUG_DRAW_CLUSTER_DECALS, + Viewport::DEBUG_DRAW_CLUSTER_REFLECTION_PROBES, }; int idx = 0; @@ -3101,6 +3187,14 @@ void Node3DEditorViewport::_init_gizmo_instance(int p_idx) { RS::get_singleton()->instance_geometry_set_cast_shadows_setting(scale_plane_gizmo_instance[i], RS::SHADOW_CASTING_SETTING_OFF); RS::get_singleton()->instance_set_layer_mask(scale_plane_gizmo_instance[i], layer); } + + // Rotation white outline + rotate_gizmo_instance[3] = RS::get_singleton()->instance_create(); + RS::get_singleton()->instance_set_base(rotate_gizmo_instance[3], spatial_editor->get_rotate_gizmo(3)->get_rid()); + RS::get_singleton()->instance_set_scenario(rotate_gizmo_instance[3], get_tree()->get_root()->get_world_3d()->get_scenario()); + RS::get_singleton()->instance_set_visible(rotate_gizmo_instance[3], false); + RS::get_singleton()->instance_geometry_set_cast_shadows_setting(rotate_gizmo_instance[3], RS::SHADOW_CASTING_SETTING_OFF); + RS::get_singleton()->instance_set_layer_mask(rotate_gizmo_instance[3], layer); } void Node3DEditorViewport::_finish_gizmo_instances() { @@ -3111,6 +3205,8 @@ void Node3DEditorViewport::_finish_gizmo_instances() { RS::get_singleton()->free(scale_gizmo_instance[i]); RS::get_singleton()->free(scale_plane_gizmo_instance[i]); } + // Rotation white outline + RS::get_singleton()->free(rotate_gizmo_instance[3]); } void Node3DEditorViewport::_toggle_camera_preview(bool p_activate) { @@ -3140,6 +3236,8 @@ void Node3DEditorViewport::_toggle_camera_preview(bool p_activate) { void Node3DEditorViewport::_toggle_cinema_preview(bool p_activate) { previewing_cinema = p_activate; + rotation_control->set_visible(!p_activate); + if (!previewing_cinema) { if (previewing != nullptr) { previewing->disconnect("tree_exited", callable_mp(this, &Node3DEditorViewport::_preview_exited_scene)); @@ -3202,13 +3300,15 @@ void Node3DEditorViewport::update_transform_gizmo_view() { RenderingServer::get_singleton()->instance_set_visible(scale_gizmo_instance[i], false); RenderingServer::get_singleton()->instance_set_visible(scale_plane_gizmo_instance[i], false); } + // Rotation white outline + RenderingServer::get_singleton()->instance_set_visible(rotate_gizmo_instance[3], false); return; } Vector3 camz = -camera_xform.get_basis().get_axis(2).normalized(); Vector3 camy = -camera_xform.get_basis().get_axis(1).normalized(); Plane p(camera_xform.origin, camz); - float gizmo_d = Math::abs(p.distance_to(xform.origin)); + float gizmo_d = MAX(Math::abs(p.distance_to(xform.origin)), CMP_EPSILON); float d0 = camera->unproject_position(camera_xform.origin + camz * gizmo_d).y; float d1 = camera->unproject_position(camera_xform.origin + camz * gizmo_d + camy).y; float dd = Math::abs(d0 - d1); @@ -3228,6 +3328,21 @@ void Node3DEditorViewport::update_transform_gizmo_view() { xform.basis.scale(scale); + // if the determinant is zero, we should disable the gizmo from being rendered + // this prevents supplying bad values to the renderer and then having to filter it out again + if (xform.basis.determinant() == 0) { + for (int i = 0; i < 3; i++) { + RenderingServer::get_singleton()->instance_set_visible(move_gizmo_instance[i], false); + RenderingServer::get_singleton()->instance_set_visible(move_plane_gizmo_instance[i], false); + RenderingServer::get_singleton()->instance_set_visible(rotate_gizmo_instance[i], false); + RenderingServer::get_singleton()->instance_set_visible(scale_gizmo_instance[i], false); + RenderingServer::get_singleton()->instance_set_visible(scale_plane_gizmo_instance[i], false); + } + // Rotation white outline + RenderingServer::get_singleton()->instance_set_visible(rotate_gizmo_instance[3], false); + return; + } + for (int i = 0; i < 3; i++) { RenderingServer::get_singleton()->instance_set_transform(move_gizmo_instance[i], xform); RenderingServer::get_singleton()->instance_set_visible(move_gizmo_instance[i], spatial_editor->is_gizmo_visible() && (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_SELECT || spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_MOVE)); @@ -3240,6 +3355,9 @@ void Node3DEditorViewport::update_transform_gizmo_view() { RenderingServer::get_singleton()->instance_set_transform(scale_plane_gizmo_instance[i], xform); RenderingServer::get_singleton()->instance_set_visible(scale_plane_gizmo_instance[i], spatial_editor->is_gizmo_visible() && (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_SCALE)); } + // Rotation white outline + RenderingServer::get_singleton()->instance_set_transform(rotate_gizmo_instance[3], xform); + RenderingServer::get_singleton()->instance_set_visible(rotate_gizmo_instance[3], spatial_editor->is_gizmo_visible() && (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_SELECT || spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_ROTATE)); } void Node3DEditorViewport::set_state(const Dictionary &p_state) { @@ -3422,11 +3540,7 @@ void Node3DEditorViewport::reset() { last_message = ""; name = ""; - cursor.x_rot = 0.5; - cursor.y_rot = 0.5; - cursor.distance = 4; - cursor.region_select = false; - cursor.pos = Vector3(); + cursor = Cursor(); _update_name(); } @@ -3528,7 +3642,7 @@ Vector3 Node3DEditorViewport::_get_instance_position(const Point2 &p_pos) const return point + offset; } -AABB Node3DEditorViewport::_calculate_spatial_bounds(const Node3D *p_parent, bool p_exclude_toplevel_transform) { +AABB Node3DEditorViewport::_calculate_spatial_bounds(const Node3D *p_parent, bool p_exclude_top_level_transform) { AABB bounds; const MeshInstance3D *mesh_instance = Object::cast_to<MeshInstance3D>(p_parent); @@ -3553,7 +3667,7 @@ AABB Node3DEditorViewport::_calculate_spatial_bounds(const Node3D *p_parent, boo bounds = AABB(Vector3(-0.2, -0.2, -0.2), Vector3(0.4, 0.4, 0.4)); } - if (!p_exclude_toplevel_transform) { + if (!p_exclude_top_level_transform) { bounds = p_parent->get_transform().xform(bounds); } @@ -3661,15 +3775,19 @@ bool Node3DEditorViewport::_create_instance(Node *parent, String &path, const Po editor_data->get_undo_redo().add_do_method(ed, "live_debug_instance_node", editor->get_edited_scene()->get_path_to(parent), path, new_name); editor_data->get_undo_redo().add_undo_method(ed, "live_debug_remove_node", NodePath(String(editor->get_edited_scene()->get_path_to(parent)) + "/" + new_name)); - Transform global_transform; - Node3D *parent_spatial = Object::cast_to<Node3D>(parent); - if (parent_spatial) { - global_transform = parent_spatial->get_global_gizmo_transform(); - } + Node3D *node3d = Object::cast_to<Node3D>(instanced_scene); + if (node3d) { + Transform global_transform; + Node3D *parent_node3d = Object::cast_to<Node3D>(parent); + if (parent_node3d) { + global_transform = parent_node3d->get_global_gizmo_transform(); + } - global_transform.origin = spatial_editor->snap_point(_get_instance_position(p_point)); + global_transform.origin = spatial_editor->snap_point(_get_instance_position(p_point)); + global_transform.basis *= node3d->get_transform().basis; - editor_data->get_undo_redo().add_do_method(instanced_scene, "set_global_transform", global_transform); + editor_data->get_undo_redo().add_do_method(instanced_scene, "set_global_transform", global_transform); + } return true; } @@ -3705,7 +3823,7 @@ void Node3DEditorViewport::_perform_drop_data() { files_str += error_files[i].get_file().get_basename() + ","; } files_str = files_str.substr(0, files_str.length() - 1); - accept->set_text(vformat(TTR("Error instancing scene from %s"), files_str.c_str())); + accept->set_text(vformat(TTR("Error instancing scene from %s"), files_str.get_data())); accept->popup_centered(); } } @@ -3835,7 +3953,7 @@ Node3DEditorViewport::Node3DEditorViewport(Node3DEditor *p_spatial_editor, Edito subviewport_container = c; c->set_stretch(true); add_child(c); - c->set_anchors_and_margins_preset(Control::PRESET_WIDE); + c->set_anchors_and_offsets_preset(Control::PRESET_WIDE); viewport = memnew(SubViewport); viewport->set_disable_input(true); @@ -3843,27 +3961,24 @@ Node3DEditorViewport::Node3DEditorViewport(Node3DEditor *p_spatial_editor, Edito surface = memnew(Control); surface->set_drag_forwarding(this); add_child(surface); - surface->set_anchors_and_margins_preset(Control::PRESET_WIDE); + surface->set_anchors_and_offsets_preset(Control::PRESET_WIDE); surface->set_clip_contents(true); camera = memnew(Camera3D); camera->set_disable_gizmo(true); - camera->set_cull_mask(((1 << 20) - 1) | (1 << (GIZMO_BASE_LAYER + p_index)) | (1 << GIZMO_EDIT_LAYER) | (1 << GIZMO_GRID_LAYER)); + camera->set_cull_mask(((1 << 20) - 1) | (1 << (GIZMO_BASE_LAYER + p_index)) | (1 << GIZMO_EDIT_LAYER) | (1 << GIZMO_GRID_LAYER) | (1 << MISC_TOOL_LAYER)); viewport->add_child(camera); camera->make_current(); surface->set_focus_mode(FOCUS_ALL); - crosshair = memnew(TextureRect); - crosshair->set_mouse_filter(MOUSE_FILTER_IGNORE); - surface->add_child(crosshair); - VBoxContainer *vbox = memnew(VBoxContainer); surface->add_child(vbox); vbox->set_position(Point2(10, 10) * EDSCALE); view_menu = memnew(MenuButton); view_menu->set_flat(false); - vbox->add_child(view_menu); view_menu->set_h_size_flags(0); + view_menu->set_shortcut_context(this); + vbox->add_child(view_menu); display_submenu = memnew(PopupMenu); view_menu->get_popup()->add_child(display_submenu); @@ -3902,11 +4017,22 @@ Node3DEditorViewport::Node3DEditorViewport(Node3DEditor *p_spatial_editor, Edito display_submenu->add_radio_check_item(TTR("GIProbe Albedo"), VIEW_DISPLAY_DEBUG_GIPROBE_ALBEDO); display_submenu->add_radio_check_item(TTR("GIProbe Emission"), VIEW_DISPLAY_DEBUG_GIPROBE_EMISSION); display_submenu->add_separator(); + display_submenu->add_radio_check_item(TTR("SDFGI Cascades"), VIEW_DISPLAY_DEBUG_SDFGI); + display_submenu->add_radio_check_item(TTR("SDFGI Probes"), VIEW_DISPLAY_DEBUG_SDFGI_PROBES); + display_submenu->add_separator(); display_submenu->add_radio_check_item(TTR("Scene Luminance"), VIEW_DISPLAY_DEBUG_SCENE_LUMINANCE); display_submenu->add_separator(); display_submenu->add_radio_check_item(TTR("SSAO"), VIEW_DISPLAY_DEBUG_SSAO); display_submenu->add_separator(); - display_submenu->add_radio_check_item(TTR("Roughness Limiter"), VIEW_DISPLAY_DEBUG_ROUGHNESS_LIMITER); + display_submenu->add_radio_check_item(TTR("GI Buffer"), VIEW_DISPLAY_DEBUG_GI_BUFFER); + display_submenu->add_separator(); + display_submenu->add_radio_check_item(TTR("Disable LOD"), VIEW_DISPLAY_DEBUG_DISABLE_LOD); + display_submenu->add_separator(); + display_submenu->add_radio_check_item(TTR("Omni Light Cluster"), VIEW_DISPLAY_DEBUG_CLUSTER_OMNI_LIGHTS); + display_submenu->add_radio_check_item(TTR("Spot Light Cluster"), VIEW_DISPLAY_DEBUG_CLUSTER_SPOT_LIGHTS); + display_submenu->add_radio_check_item(TTR("Decal Cluster"), VIEW_DISPLAY_DEBUG_CLUSTER_DECALS); + display_submenu->add_radio_check_item(TTR("Reflection Probe Cluster"), VIEW_DISPLAY_DEBUG_CLUSTER_REFLECTION_PROBES); + display_submenu->set_name("display_advanced"); view_menu->get_popup()->add_submenu_item(TTR("Display Advanced..."), "display_advanced", VIEW_DISPLAY_ADVANCED); view_menu->get_popup()->add_separator(); @@ -3976,27 +4102,17 @@ Node3DEditorViewport::Node3DEditorViewport(Node3DEditor *p_spatial_editor, Edito preview_node = nullptr; info_label = memnew(Label); - info_label->set_anchor_and_margin(MARGIN_LEFT, ANCHOR_END, -90 * EDSCALE); - info_label->set_anchor_and_margin(MARGIN_TOP, ANCHOR_END, -90 * EDSCALE); - info_label->set_anchor_and_margin(MARGIN_RIGHT, ANCHOR_END, -10 * EDSCALE); - info_label->set_anchor_and_margin(MARGIN_BOTTOM, ANCHOR_END, -10 * EDSCALE); + info_label->set_anchor_and_offset(SIDE_LEFT, ANCHOR_END, -90 * EDSCALE); + info_label->set_anchor_and_offset(SIDE_TOP, ANCHOR_END, -90 * EDSCALE); + info_label->set_anchor_and_offset(SIDE_RIGHT, ANCHOR_END, -10 * EDSCALE); + info_label->set_anchor_and_offset(SIDE_BOTTOM, ANCHOR_END, -10 * EDSCALE); info_label->set_h_grow_direction(GROW_DIRECTION_BEGIN); info_label->set_v_grow_direction(GROW_DIRECTION_BEGIN); surface->add_child(info_label); info_label->hide(); - fps_label = memnew(Label); - fps_label->set_anchor_and_margin(MARGIN_LEFT, ANCHOR_END, -90 * EDSCALE); - fps_label->set_anchor_and_margin(MARGIN_TOP, ANCHOR_BEGIN, 10 * EDSCALE); - fps_label->set_anchor_and_margin(MARGIN_RIGHT, ANCHOR_END, -10 * EDSCALE); - fps_label->set_h_grow_direction(GROW_DIRECTION_BEGIN); - fps_label->set_tooltip(TTR("Note: The FPS is estimated on a 60hz refresh rate.")); - fps_label->set_mouse_filter(MOUSE_FILTER_PASS); // Otherwise tooltip doesn't show. - surface->add_child(fps_label); - fps_label->hide(); - cinema_label = memnew(Label); - cinema_label->set_anchor_and_margin(MARGIN_TOP, ANCHOR_BEGIN, 10 * EDSCALE); + cinema_label->set_anchor_and_offset(SIDE_TOP, ANCHOR_BEGIN, 10 * EDSCALE); cinema_label->set_h_grow_direction(GROW_DIRECTION_END); cinema_label->set_align(Label::ALIGN_CENTER); surface->add_child(cinema_label); @@ -4005,8 +4121,8 @@ Node3DEditorViewport::Node3DEditorViewport(Node3DEditor *p_spatial_editor, Edito previewing_cinema = false; locked_label = memnew(Label); - locked_label->set_anchor_and_margin(MARGIN_TOP, ANCHOR_END, -20 * EDSCALE); - locked_label->set_anchor_and_margin(MARGIN_BOTTOM, ANCHOR_END, -10 * EDSCALE); + locked_label->set_anchor_and_offset(SIDE_TOP, ANCHOR_END, -20 * EDSCALE); + locked_label->set_anchor_and_offset(SIDE_BOTTOM, ANCHOR_END, -10 * EDSCALE); locked_label->set_h_grow_direction(GROW_DIRECTION_END); locked_label->set_v_grow_direction(GROW_DIRECTION_BEGIN); locked_label->set_align(Label::ALIGN_CENTER); @@ -4014,9 +4130,17 @@ Node3DEditorViewport::Node3DEditorViewport(Node3DEditor *p_spatial_editor, Edito locked_label->set_text(TTR("View Rotation Locked")); locked_label->hide(); + frame_time_gradient = memnew(Gradient); + // The color is set when the theme changes. + frame_time_gradient->add_point(0.5, Color()); + top_right_vbox = memnew(VBoxContainer); - top_right_vbox->set_anchors_and_margins_preset(PRESET_TOP_RIGHT, PRESET_MODE_MINSIZE, 2.0 * EDSCALE); + top_right_vbox->set_anchors_and_offsets_preset(PRESET_TOP_RIGHT, PRESET_MODE_MINSIZE, 2.0 * EDSCALE); top_right_vbox->set_h_grow_direction(GROW_DIRECTION_BEGIN); + // Make sure frame time labels don't touch the viewport's edge. + top_right_vbox->set_custom_minimum_size(Size2(100, 0) * EDSCALE); + // Prevent visible spacing between frame time labels. + top_right_vbox->add_theme_constant_override("separation", 0); rotation_control = memnew(ViewportRotationControl); rotation_control->set_custom_minimum_size(Size2(80, 80) * EDSCALE); @@ -4024,13 +4148,16 @@ Node3DEditorViewport::Node3DEditorViewport(Node3DEditor *p_spatial_editor, Edito rotation_control->set_viewport(this); top_right_vbox->add_child(rotation_control); + // Individual Labels are used to allow coloring each label with its own color. + cpu_time_label = memnew(Label); + top_right_vbox->add_child(cpu_time_label); + cpu_time_label->hide(); + + gpu_time_label = memnew(Label); + top_right_vbox->add_child(gpu_time_label); + gpu_time_label->hide(); + fps_label = memnew(Label); - fps_label->set_anchor_and_margin(MARGIN_LEFT, ANCHOR_END, -90 * EDSCALE); - fps_label->set_anchor_and_margin(MARGIN_TOP, ANCHOR_BEGIN, 10 * EDSCALE); - fps_label->set_anchor_and_margin(MARGIN_RIGHT, ANCHOR_END, -10 * EDSCALE); - fps_label->set_h_grow_direction(GROW_DIRECTION_BEGIN); - fps_label->set_tooltip(TTR("Note: The FPS value displayed is the editor's framerate.\nIt cannot be used as a reliable indication of in-game performance.")); - fps_label->set_mouse_filter(MOUSE_FILTER_PASS); // Otherwise tooltip doesn't show. top_right_vbox->add_child(fps_label); fps_label->hide(); @@ -4058,6 +4185,10 @@ Node3DEditorViewport::Node3DEditorViewport(Node3DEditor *p_spatial_editor, Edito EditorSettings::get_singleton()->connect("settings_changed", callable_mp(this, &Node3DEditorViewport::update_transform_gizmo_view)); } +Node3DEditorViewport::~Node3DEditorViewport() { + memdelete(frame_time_gradient); +} + ////////////////////////////////////////////////////////////// void Node3DEditorViewportContainer::_gui_input(const Ref<InputEvent> &p_event) { @@ -4374,13 +4505,16 @@ Node3DEditorSelectedItem::~Node3DEditorSelectedItem() { if (sbox_instance.is_valid()) { RenderingServer::get_singleton()->free(sbox_instance); } + if (sbox_instance_xray.is_valid()) { + RenderingServer::get_singleton()->free(sbox_instance_xray); + } } void Node3DEditor::select_gizmo_highlight_axis(int p_axis) { for (int i = 0; i < 3; i++) { move_gizmo[i]->surface_set_material(0, i == p_axis ? gizmo_color_hl[i] : gizmo_color[i]); move_plane_gizmo[i]->surface_set_material(0, (i + 6) == p_axis ? plane_gizmo_color_hl[i] : plane_gizmo_color[i]); - rotate_gizmo[i]->surface_set_material(0, (i + 3) == p_axis ? gizmo_color_hl[i] : gizmo_color[i]); + rotate_gizmo[i]->surface_set_material(0, (i + 3) == p_axis ? rotate_gizmo_color_hl[i] : rotate_gizmo_color[i]); scale_gizmo[i]->surface_set_material(0, (i + 9) == p_axis ? gizmo_color_hl[i] : gizmo_color[i]); scale_plane_gizmo[i]->surface_set_material(0, (i + 12) == p_axis ? plane_gizmo_color_hl[i] : plane_gizmo_color[i]); } @@ -4457,42 +4591,75 @@ Object *Node3DEditor::_get_editor_data(Object *p_what) { Node3DEditorSelectedItem *si = memnew(Node3DEditorSelectedItem); si->sp = sp; - si->sbox_instance = RenderingServer::get_singleton()->instance_create2(selection_box->get_rid(), sp->get_world_3d()->get_scenario()); - RS::get_singleton()->instance_geometry_set_cast_shadows_setting(si->sbox_instance, RS::SHADOW_CASTING_SETTING_OFF); + si->sbox_instance = RenderingServer::get_singleton()->instance_create2( + selection_box->get_rid(), + sp->get_world_3d()->get_scenario()); + RS::get_singleton()->instance_geometry_set_cast_shadows_setting( + si->sbox_instance, + RS::SHADOW_CASTING_SETTING_OFF); + RS::get_singleton()->instance_set_layer_mask(si->sbox_instance, 1 << Node3DEditorViewport::MISC_TOOL_LAYER); + si->sbox_instance_xray = RenderingServer::get_singleton()->instance_create2( + selection_box_xray->get_rid(), + sp->get_world_3d()->get_scenario()); + RS::get_singleton()->instance_geometry_set_cast_shadows_setting( + si->sbox_instance_xray, + RS::SHADOW_CASTING_SETTING_OFF); + RS::get_singleton()->instance_set_layer_mask(si->sbox_instance_xray, 1 << Node3DEditorViewport::MISC_TOOL_LAYER); return si; } -void Node3DEditor::_generate_selection_box() { +void Node3DEditor::_generate_selection_boxes() { + // Use two AABBs to create the illusion of a slightly thicker line. AABB aabb(Vector3(), Vector3(1, 1, 1)); - aabb.grow_by(aabb.get_longest_axis_size() / 20.0); - + AABB aabb_offset(Vector3(), Vector3(1, 1, 1)); + // Grow the bounding boxes slightly to avoid Z-fighting with the mesh's edges. + aabb.grow_by(0.005); + aabb_offset.grow_by(0.01); + + // Create a x-ray (visible through solid surfaces) and standard version of the selection box. + // Both will be drawn at the same position, but with different opacity. + // This lets the user see where the selection is while still having a sense of depth. Ref<SurfaceTool> st = memnew(SurfaceTool); + Ref<SurfaceTool> st_xray = memnew(SurfaceTool); st->begin(Mesh::PRIMITIVE_LINES); + st_xray->begin(Mesh::PRIMITIVE_LINES); for (int i = 0; i < 12; i++) { Vector3 a, b; aabb.get_edge(i, a, b); - st->add_color(Color(1.0, 1.0, 0.8, 0.8)); st->add_vertex(a); - st->add_color(Color(1.0, 1.0, 0.8, 0.4)); - st->add_vertex(a.lerp(b, 0.2)); + st->add_vertex(b); + st_xray->add_vertex(a); + st_xray->add_vertex(b); + } + + for (int i = 0; i < 12; i++) { + Vector3 a, b; + aabb_offset.get_edge(i, a, b); - st->add_color(Color(1.0, 1.0, 0.8, 0.4)); - st->add_vertex(a.lerp(b, 0.8)); - st->add_color(Color(1.0, 1.0, 0.8, 0.8)); + st->add_vertex(a); st->add_vertex(b); + st_xray->add_vertex(a); + st_xray->add_vertex(b); } Ref<StandardMaterial3D> mat = memnew(StandardMaterial3D); mat->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED); - mat->set_albedo(Color(1, 1, 1)); + const Color selection_box_color = EDITOR_GET("editors/3d/selection_box_color"); + mat->set_albedo(selection_box_color); mat->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA); - mat->set_flag(StandardMaterial3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true); - mat->set_flag(StandardMaterial3D::FLAG_SRGB_VERTEX_COLOR, true); st->set_material(mat); selection_box = st->commit(); + + Ref<StandardMaterial3D> mat_xray = memnew(StandardMaterial3D); + mat_xray->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED); + mat_xray->set_flag(StandardMaterial3D::FLAG_DISABLE_DEPTH_TEST, true); + mat_xray->set_albedo(selection_box_color * Color(1, 1, 1, 0.15)); + mat_xray->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA); + st_xray->set_material(mat_xray); + selection_box_xray = st_xray->commit(); } Dictionary Node3DEditor::get_state() const { @@ -4545,6 +4712,28 @@ Dictionary Node3DEditor::get_state() const { } d["gizmos_status"] = gizmos_status; + { + Dictionary pd; + + pd["sun_rotation"] = sun_rotation; + + pd["environ_sky_color"] = environ_sky_color->get_pick_color(); + pd["environ_ground_color"] = environ_ground_color->get_pick_color(); + pd["environ_energy"] = environ_energy->get_value(); + pd["environ_glow_enabled"] = environ_glow_button->is_pressed(); + pd["environ_tonemap_enabled"] = environ_tonemap_button->is_pressed(); + pd["environ_ao_enabled"] = environ_ao_button->is_pressed(); + pd["environ_gi_enabled"] = environ_gi_button->is_pressed(); + pd["sun_max_distance"] = sun_max_distance->get_value(); + + pd["sun_color"] = sun_color->get_pick_color(); + pd["sun_energy"] = sun_energy->get_value(); + + pd["sun_disabled"] = sun_button->is_pressed(); + pd["environ_disabled"] = environ_button->is_pressed(); + + d["preview_sun_env"] = pd; + } return d; } @@ -4644,7 +4833,7 @@ void Node3DEditor::set_state(const Dictionary &p_state) { } int state = EditorNode3DGizmoPlugin::VISIBLE; for (int i = 0; i < keys.size(); i++) { - if (gizmo_plugins_by_name.write[j]->get_name() == keys[i]) { + if (gizmo_plugins_by_name.write[j]->get_name() == String(keys[i])) { state = gizmos_status[keys[i]]; break; } @@ -4654,6 +4843,38 @@ void Node3DEditor::set_state(const Dictionary &p_state) { } _update_gizmos_menu(); } + + if (d.has("preview_sun_env")) { + sun_environ_updating = true; + Dictionary pd = d["preview_sun_env"]; + sun_rotation = pd["sun_rotation"]; + + environ_sky_color->set_pick_color(pd["environ_sky_color"]); + environ_ground_color->set_pick_color(pd["environ_ground_color"]); + environ_energy->set_value(pd["environ_energy"]); + environ_glow_button->set_pressed(pd["environ_glow_enabled"]); + environ_tonemap_button->set_pressed(pd["environ_tonemap_enabled"]); + environ_ao_button->set_pressed(pd["environ_ao_enabled"]); + environ_gi_button->set_pressed(pd["environ_gi_enabled"]); + sun_max_distance->set_value(pd["sun_max_distance"]); + + sun_color->set_pick_color(pd["sun_color"]); + sun_energy->set_value(pd["sun_energy"]); + + sun_button->set_pressed(pd["sun_disabled"]); + environ_button->set_pressed(pd["environ_disabled"]); + + sun_environ_updating = false; + + _preview_settings_changed(); + _update_preview_environment(); + } else { + _load_default_preview_settings(); + sun_button->set_pressed(false); + environ_button->set_pressed(false); + _preview_settings_changed(); + _update_preview_environment(); + } } void Node3DEditor::edit(Node3D *p_spatial) { @@ -4680,9 +4901,9 @@ void Node3DEditor::edit(Node3D *p_spatial) { } void Node3DEditor::_snap_changed() { - snap_translate_value = snap_translate->get_text().to_double(); - snap_rotate_value = snap_rotate->get_text().to_double(); - snap_scale_value = snap_scale->get_text().to_double(); + snap_translate_value = snap_translate->get_text().to_float(); + snap_rotate_value = snap_rotate->get_text().to_float(); + snap_scale_value = snap_scale->get_text().to_float(); } void Node3DEditor::_snap_update() { @@ -4699,9 +4920,9 @@ void Node3DEditor::_xform_dialog_action() { Vector3 translate; for (int i = 0; i < 3; i++) { - translate[i] = xform_translate[i]->get_text().to_double(); - rotate[i] = Math::deg2rad(xform_rotate[i]->get_text().to_double()); - scale[i] = xform_scale[i]->get_text().to_double(); + translate[i] = xform_translate[i]->get_text().to_float(); + rotate[i] = Math::deg2rad(xform_rotate[i]->get_text().to_float()); + scale[i] = xform_scale[i]->get_text().to_float(); } t.basis.scale(scale); @@ -4929,10 +5150,11 @@ void Node3DEditor::_menu_item_pressed(int p_option) { for (int i = 0; i < 3; ++i) { if (grid_enable[i]) { - RenderingServer::get_singleton()->instance_set_visible(grid_instance[i], grid_enabled); grid_visible[i] = grid_enabled; } } + _finish_grid(); + _init_grid(); view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(p_option), grid_enabled); @@ -4950,7 +5172,7 @@ void Node3DEditor::_menu_item_pressed(int p_option) { for (List<Node *>::Element *E = selection.front(); E; E = E->next()) { Node3D *spatial = Object::cast_to<Node3D>(E->get()); - if (!spatial || !spatial->is_visible_in_tree()) { + if (!spatial || !spatial->is_inside_tree()) { continue; } @@ -4964,8 +5186,8 @@ void Node3DEditor::_menu_item_pressed(int p_option) { undo_redo->add_undo_method(this, "emit_signal", "item_lock_status_changed"); } - undo_redo->add_do_method(this, "_refresh_menu_icons", Variant()); - undo_redo->add_undo_method(this, "_refresh_menu_icons", Variant()); + undo_redo->add_do_method(this, "_refresh_menu_icons"); + undo_redo->add_undo_method(this, "_refresh_menu_icons"); undo_redo->commit_action(); } break; case MENU_UNLOCK_SELECTED: { @@ -4975,7 +5197,7 @@ void Node3DEditor::_menu_item_pressed(int p_option) { for (List<Node *>::Element *E = selection.front(); E; E = E->next()) { Node3D *spatial = Object::cast_to<Node3D>(E->get()); - if (!spatial || !spatial->is_visible_in_tree()) { + if (!spatial || !spatial->is_inside_tree()) { continue; } @@ -4989,8 +5211,8 @@ void Node3DEditor::_menu_item_pressed(int p_option) { undo_redo->add_undo_method(this, "emit_signal", "item_lock_status_changed"); } - undo_redo->add_do_method(this, "_refresh_menu_icons", Variant()); - undo_redo->add_undo_method(this, "_refresh_menu_icons", Variant()); + undo_redo->add_do_method(this, "_refresh_menu_icons"); + undo_redo->add_undo_method(this, "_refresh_menu_icons"); undo_redo->commit_action(); } break; case MENU_GROUP_SELECTED: { @@ -5000,7 +5222,7 @@ void Node3DEditor::_menu_item_pressed(int p_option) { for (List<Node *>::Element *E = selection.front(); E; E = E->next()) { Node3D *spatial = Object::cast_to<Node3D>(E->get()); - if (!spatial || !spatial->is_visible_in_tree()) { + if (!spatial || !spatial->is_inside_tree()) { continue; } @@ -5014,8 +5236,8 @@ void Node3DEditor::_menu_item_pressed(int p_option) { undo_redo->add_undo_method(this, "emit_signal", "item_group_status_changed"); } - undo_redo->add_do_method(this, "_refresh_menu_icons", Variant()); - undo_redo->add_undo_method(this, "_refresh_menu_icons", Variant()); + undo_redo->add_do_method(this, "_refresh_menu_icons"); + undo_redo->add_undo_method(this, "_refresh_menu_icons"); undo_redo->commit_action(); } break; case MENU_UNGROUP_SELECTED: { @@ -5024,7 +5246,7 @@ void Node3DEditor::_menu_item_pressed(int p_option) { for (List<Node *>::Element *E = selection.front(); E; E = E->next()) { Node3D *spatial = Object::cast_to<Node3D>(E->get()); - if (!spatial || !spatial->is_visible_in_tree()) { + if (!spatial || !spatial->is_inside_tree()) { continue; } @@ -5038,8 +5260,8 @@ void Node3DEditor::_menu_item_pressed(int p_option) { undo_redo->add_undo_method(this, "emit_signal", "item_group_status_changed"); } - undo_redo->add_do_method(this, "_refresh_menu_icons", Variant()); - undo_redo->add_undo_method(this, "_refresh_menu_icons", Variant()); + undo_redo->add_do_method(this, "_refresh_menu_icons"); + undo_redo->add_undo_method(this, "_refresh_menu_icons"); undo_redo->commit_action(); } break; } @@ -5054,6 +5276,7 @@ void Node3DEditor::_init_indicators() { indicator_mat->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED); indicator_mat->set_flag(StandardMaterial3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true); indicator_mat->set_flag(StandardMaterial3D::FLAG_SRGB_VERTEX_COLOR, true); + indicator_mat->set_transparency(StandardMaterial3D::Transparency::TRANSPARENCY_ALPHA_DEPTH_PRE_PASS); Vector<Color> origin_colors; Vector<Vector3> origin_points; @@ -5082,12 +5305,63 @@ void Node3DEditor::_init_indicators() { origin_colors.push_back(origin_color); origin_colors.push_back(origin_color); - origin_points.push_back(axis * 4096); - origin_points.push_back(axis * -4096); + origin_colors.push_back(origin_color); + origin_colors.push_back(origin_color); + origin_colors.push_back(origin_color); + origin_colors.push_back(origin_color); + // To both allow having a large origin size and avoid jitter + // at small scales, we should segment the line into pieces. + // 3 pieces seems to do the trick, and let's use powers of 2. + origin_points.push_back(axis * 1048576); + origin_points.push_back(axis * 1024); + origin_points.push_back(axis * 1024); + origin_points.push_back(axis * -1024); + origin_points.push_back(axis * -1024); + origin_points.push_back(axis * -1048576); + } + + Ref<Shader> grid_shader = memnew(Shader); + grid_shader->set_code( + "\n" + "shader_type spatial; \n" + "render_mode unshaded; \n" + "uniform bool orthogonal; \n" + "uniform float grid_size; \n" + "\n" + "void vertex() { \n" + " // From FLAG_SRGB_VERTEX_COLOR \n" + " if (!OUTPUT_IS_SRGB) { \n" + " COLOR.rgb = mix(pow((COLOR.rgb + vec3(0.055)) * (1.0 / (1.0 + 0.055)), vec3(2.4)), COLOR.rgb * (1.0 / 12.92), lessThan(COLOR.rgb, vec3(0.04045))); \n" + " } \n" + "} \n" + "\n" + "void fragment() { \n" + " ALBEDO = COLOR.rgb; \n" + " vec3 dir = orthogonal ? -vec3(0, 0, 1) : VIEW; \n" + " float angle_fade = abs(dot(dir, NORMAL)); \n" + " angle_fade = smoothstep(0.05, 0.2, angle_fade); \n" + " \n" + " vec3 world_pos = (CAMERA_MATRIX * vec4(VERTEX, 1.0)).xyz; \n" + " vec3 world_normal = (CAMERA_MATRIX * vec4(NORMAL, 0.0)).xyz; \n" + " vec3 camera_world_pos = CAMERA_MATRIX[3].xyz; \n" + " vec3 camera_world_pos_on_plane = camera_world_pos * (1.0 - world_normal); \n" + " float dist_fade = 1.0 - (distance(world_pos, camera_world_pos_on_plane) / grid_size); \n" + " dist_fade = smoothstep(0.02, 0.3, dist_fade); \n" + " \n" + " ALPHA = COLOR.a * dist_fade * angle_fade; \n" + "}"); + + for (int i = 0; i < 3; i++) { + grid_mat[i].instance(); + grid_mat[i]->set_shader(grid_shader); } - grid_enable[1] = true; - grid_visible[1] = true; + grid_enable[0] = EditorSettings::get_singleton()->get("editors/3d/grid_xy_plane"); + grid_enable[1] = EditorSettings::get_singleton()->get("editors/3d/grid_yz_plane"); + grid_enable[2] = EditorSettings::get_singleton()->get("editors/3d/grid_xz_plane"); + grid_visible[0] = grid_enable[0]; + grid_visible[1] = grid_enable[1]; + grid_visible[2] = grid_enable[2]; _init_grid(); @@ -5142,7 +5416,9 @@ void Node3DEditor::_init_indicators() { gizmo_color[i] = mat; Ref<StandardMaterial3D> mat_hl = mat->duplicate(); - mat_hl->set_albedo(Color(col.r, col.g, col.b, 1.0)); + const float brightness = 1.3; + const Color albedo = Color(col.r * brightness, col.g * brightness, col.b * brightness); + mat_hl->set_albedo(albedo); gizmo_color_hl[i] = mat_hl; Vector3 ivec; @@ -5172,9 +5448,10 @@ void Node3DEditor::_init_indicators() { int arrow_sides = 16; + const real_t arrow_sides_step = Math_TAU / arrow_sides; for (int k = 0; k < arrow_sides; k++) { - Basis ma(ivec, Math_PI * 2 * float(k) / arrow_sides); - Basis mb(ivec, Math_PI * 2 * float(k + 1) / arrow_sides); + Basis ma(ivec, k * arrow_sides_step); + Basis mb(ivec, (k + 1) * arrow_sides_step); for (int j = 0; j < arrow_points - 1; j++) { Vector3 points[4] = { @@ -5237,7 +5514,7 @@ void Node3DEditor::_init_indicators() { surftool->commit(move_plane_gizmo[i]); Ref<StandardMaterial3D> plane_mat_hl = plane_mat->duplicate(); - plane_mat_hl->set_albedo(Color(col.r, col.g, col.b, 1.0)); + plane_mat_hl->set_albedo(albedo); plane_gizmo_color_hl[i] = plane_mat_hl; // needed, so we can draw planes from both sides } @@ -5246,37 +5523,125 @@ void Node3DEditor::_init_indicators() { Ref<SurfaceTool> surftool = memnew(SurfaceTool); surftool->begin(Mesh::PRIMITIVE_TRIANGLES); - Vector3 circle[5] = { - ivec * 0.02 + ivec2 * 0.02 + ivec2 * GIZMO_CIRCLE_SIZE, - ivec * -0.02 + ivec2 * 0.02 + ivec2 * GIZMO_CIRCLE_SIZE, - ivec * -0.02 + ivec2 * -0.02 + ivec2 * GIZMO_CIRCLE_SIZE, - ivec * 0.02 + ivec2 * -0.02 + ivec2 * GIZMO_CIRCLE_SIZE, - ivec * 0.02 + ivec2 * 0.02 + ivec2 * GIZMO_CIRCLE_SIZE, - }; + int n = 128; // number of circle segments + int m = 6; // number of thickness segments - for (int k = 0; k < 64; k++) { - Basis ma(ivec, Math_PI * 2 * float(k) / 64); - Basis mb(ivec, Math_PI * 2 * float(k + 1) / 64); + real_t step = Math_TAU / n; + for (int j = 0; j < n; ++j) { + Basis basis = Basis(ivec, j * step); - for (int j = 0; j < 4; j++) { - Vector3 points[4] = { - ma.xform(circle[j]), - mb.xform(circle[j]), - mb.xform(circle[j + 1]), - ma.xform(circle[j + 1]), - }; - surftool->add_vertex(points[0]); - surftool->add_vertex(points[1]); - surftool->add_vertex(points[2]); + Vector3 vertex = basis.xform(ivec2 * GIZMO_CIRCLE_SIZE); - surftool->add_vertex(points[0]); - surftool->add_vertex(points[2]); - surftool->add_vertex(points[3]); + for (int k = 0; k < m; ++k) { + Vector2 ofs = Vector2(Math::cos((Math_TAU * k) / m), Math::sin((Math_TAU * k) / m)); + Vector3 normal = ivec * ofs.x + ivec2 * ofs.y; + + surftool->set_normal(basis.xform(normal)); + surftool->add_vertex(vertex); } } - surftool->set_material(mat); - surftool->commit(rotate_gizmo[i]); + for (int j = 0; j < n; ++j) { + for (int k = 0; k < m; ++k) { + int current_ring = j * m; + int next_ring = ((j + 1) % n) * m; + int current_segment = k; + int next_segment = (k + 1) % m; + + surftool->add_index(current_ring + next_segment); + surftool->add_index(current_ring + current_segment); + surftool->add_index(next_ring + current_segment); + + surftool->add_index(next_ring + current_segment); + surftool->add_index(next_ring + next_segment); + surftool->add_index(current_ring + next_segment); + } + } + + Ref<Shader> rotate_shader = memnew(Shader); + + rotate_shader->set_code( + "\n" + "shader_type spatial; \n" + "render_mode unshaded, depth_test_disabled; \n" + "uniform vec4 albedo; \n" + "\n" + "mat3 orthonormalize(mat3 m) { \n" + " vec3 x = normalize(m[0]); \n" + " vec3 y = normalize(m[1] - x * dot(x, m[1])); \n" + " vec3 z = m[2] - x * dot(x, m[2]); \n" + " z = normalize(z - y * (dot(y,m[2]))); \n" + " return mat3(x,y,z); \n" + "} \n" + "\n" + "void vertex() { \n" + " mat3 mv = orthonormalize(mat3(MODELVIEW_MATRIX)); \n" + " vec3 n = mv * VERTEX; \n" + " float orientation = dot(vec3(0,0,-1),n); \n" + " if (orientation <= 0.005) { \n" + " VERTEX += NORMAL*0.02; \n" + " } \n" + "} \n" + "\n" + "void fragment() { \n" + " ALBEDO = albedo.rgb; \n" + " ALPHA = albedo.a; \n" + "}"); + + Ref<ShaderMaterial> rotate_mat = memnew(ShaderMaterial); + rotate_mat->set_render_priority(Material::RENDER_PRIORITY_MAX); + rotate_mat->set_shader(rotate_shader); + rotate_mat->set_shader_param("albedo", col); + rotate_gizmo_color[i] = rotate_mat; + + Array arrays = surftool->commit_to_arrays(); + rotate_gizmo[i]->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, arrays); + rotate_gizmo[i]->surface_set_material(0, rotate_mat); + + Ref<ShaderMaterial> rotate_mat_hl = rotate_mat->duplicate(); + rotate_mat_hl->set_shader_param("albedo", albedo); + rotate_gizmo_color_hl[i] = rotate_mat_hl; + + if (i == 2) { // Rotation white outline + Ref<ShaderMaterial> border_mat = rotate_mat->duplicate(); + + Ref<Shader> border_shader = memnew(Shader); + border_shader->set_code( + "\n" + "shader_type spatial; \n" + "render_mode unshaded, depth_test_disabled; \n" + "uniform vec4 albedo; \n" + "\n" + "mat3 orthonormalize(mat3 m) { \n" + " vec3 x = normalize(m[0]); \n" + " vec3 y = normalize(m[1] - x * dot(x, m[1])); \n" + " vec3 z = m[2] - x * dot(x, m[2]); \n" + " z = normalize(z - y * (dot(y,m[2]))); \n" + " return mat3(x,y,z); \n" + "} \n" + "\n" + "void vertex() { \n" + " mat3 mv = orthonormalize(mat3(MODELVIEW_MATRIX)); \n" + " mv = inverse(mv); \n" + " VERTEX += NORMAL*0.008; \n" + " vec3 camera_dir_local = mv * vec3(0,0,1); \n" + " vec3 camera_up_local = mv * vec3(0,1,0); \n" + " mat3 rotation_matrix = mat3(cross(camera_dir_local, camera_up_local), camera_up_local, camera_dir_local); \n" + " VERTEX = rotation_matrix * VERTEX; \n" + "} \n" + "\n" + "void fragment() { \n" + " ALBEDO = albedo.rgb; \n" + " ALPHA = albedo.a; \n" + "}"); + + border_mat->set_shader(border_shader); + border_mat->set_shader_param("albedo", Color(0.75, 0.75, 0.75, col.a / 3.0)); + + rotate_gizmo[3] = Ref<ArrayMesh>(memnew(ArrayMesh)); + rotate_gizmo[3]->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, arrays); + rotate_gizmo[3]->surface_set_material(0, border_mat); + } } // Scale @@ -5297,9 +5662,10 @@ void Node3DEditor::_init_indicators() { int arrow_sides = 4; + const real_t arrow_sides_step = Math_TAU / arrow_sides; for (int k = 0; k < 4; k++) { - Basis ma(ivec, Math_PI * 2 * float(k) / arrow_sides); - Basis mb(ivec, Math_PI * 2 * float(k + 1) / arrow_sides); + Basis ma(ivec, k * arrow_sides_step); + Basis mb(ivec, (k + 1) * arrow_sides_step); for (int j = 0; j < arrow_points - 1; j++) { Vector3 points[4] = { @@ -5362,13 +5728,13 @@ void Node3DEditor::_init_indicators() { surftool->commit(scale_plane_gizmo[i]); Ref<StandardMaterial3D> plane_mat_hl = plane_mat->duplicate(); - plane_mat_hl->set_albedo(Color(col.r, col.g, col.b, 1.0)); + plane_mat_hl->set_albedo(Color(col.r * 1.3, col.g * 1.3, col.b * 1.3)); plane_gizmo_color_hl[i] = plane_mat_hl; // needed, so we can draw planes from both sides } } } - _generate_selection_box(); + _generate_selection_boxes(); } void Node3DEditor::_update_gizmos_menu() { @@ -5380,8 +5746,11 @@ void Node3DEditor::_update_gizmos_menu() { } String plugin_name = gizmo_plugins_by_name[i]->get_name(); const int plugin_state = gizmo_plugins_by_name[i]->get_state(); - gizmos_menu->add_multistate_item(TTR(plugin_name), 3, plugin_state, i); + gizmos_menu->add_multistate_item(plugin_name, 3, plugin_state, i); const int idx = gizmos_menu->get_item_index(i); + gizmos_menu->set_item_tooltip( + idx, + TTR("Click to toggle between visibility states.\n\nOpen eye: Gizmo is visible.\nClosed eye: Gizmo is hidden.\nHalf-open eye: Gizmo is also visible through opaque surfaces (\"x-ray\").")); switch (plugin_state) { case EditorNode3DGizmoPlugin::VISIBLE: gizmos_menu->set_item_icon(idx, gizmos_menu->get_theme_icon("visibility_visible")); @@ -5418,60 +5787,156 @@ void Node3DEditor::_update_gizmos_menu_theme() { } void Node3DEditor::_init_grid() { + if (!grid_enabled) { + return; + } + Camera3D *camera = get_editor_viewport(0)->camera; + Vector3 camera_position = camera->get_translation(); + if (camera_position == Vector3()) { + return; // Camera3D is invalid, don't draw the grid. + } + + bool orthogonal = camera->get_projection() == Camera3D::PROJECTION_ORTHOGONAL; + Vector<Color> grid_colors[3]; Vector<Vector3> grid_points[3]; + Vector<Vector3> grid_normals[3]; Color primary_grid_color = EditorSettings::get_singleton()->get("editors/3d/primary_grid_color"); Color secondary_grid_color = EditorSettings::get_singleton()->get("editors/3d/secondary_grid_color"); int grid_size = EditorSettings::get_singleton()->get("editors/3d/grid_size"); int primary_grid_steps = EditorSettings::get_singleton()->get("editors/3d/primary_grid_steps"); - for (int i = 0; i < 3; i++) { - Vector3 axis; - axis[i] = 1; - Vector3 axis_n1; - axis_n1[(i + 1) % 3] = 1; - Vector3 axis_n2; - axis_n2[(i + 2) % 3] = 1; - - for (int j = -grid_size; j <= grid_size; j++) { - Vector3 p1 = axis_n1 * j + axis_n2 * -grid_size; - Vector3 p1_dest = p1 * (-axis_n2 + axis_n1); - Vector3 p2 = axis_n2 * j + axis_n1 * -grid_size; - Vector3 p2_dest = p2 * (-axis_n1 + axis_n2); - - Color line_color = secondary_grid_color; - if (origin_enabled && j == 0) { - // Don't draw the center lines of the grid if the origin is enabled - // The origin would overlap the grid lines in this case, causing flickering - continue; - } else if (j % primary_grid_steps == 0) { - line_color = primary_grid_color; + // Which grid planes are enabled? Which should we generate? + grid_enable[0] = grid_visible[0] = EditorSettings::get_singleton()->get("editors/3d/grid_xy_plane"); + grid_enable[1] = grid_visible[1] = EditorSettings::get_singleton()->get("editors/3d/grid_yz_plane"); + grid_enable[2] = grid_visible[2] = EditorSettings::get_singleton()->get("editors/3d/grid_xz_plane"); + + // Offsets division_level for bigger or smaller grids. + // Default value is -0.2. -1.0 gives Blender-like behavior, 0.5 gives huge grids. + real_t division_level_bias = EditorSettings::get_singleton()->get("editors/3d/grid_division_level_bias"); + // Default largest grid size is 100m, 10^2 (default value is 2). + int division_level_max = EditorSettings::get_singleton()->get("editors/3d/grid_division_level_max"); + // Default smallest grid size is 1cm, 10^-2 (default value is -2). + int division_level_min = EditorSettings::get_singleton()->get("editors/3d/grid_division_level_min"); + ERR_FAIL_COND_MSG(division_level_max < division_level_min, "The 3D grid's maximum division level cannot be lower than its minimum division level."); + + if (primary_grid_steps != 10) { // Log10 of 10 is 1. + // Change of base rule, divide by ln(10). + real_t div = Math::log((real_t)primary_grid_steps) / (real_t)2.302585092994045901094; + // Trucation (towards zero) is intentional. + division_level_max = (int)(division_level_max / div); + division_level_min = (int)(division_level_min / div); + } + + for (int a = 0; a < 3; a++) { + if (!grid_enable[a]) { + continue; // If this grid plane is disabled, skip generation. + } + int b = (a + 1) % 3; + int c = (a + 2) % 3; + + Vector3 normal; + normal[c] = 1.0; + + real_t camera_distance = Math::abs(camera_position[c]); + + if (orthogonal) { + camera_distance = camera->get_size() / 2.0; + Vector3 camera_direction = -camera->get_global_transform().get_basis().get_axis(2); + Plane grid_plane = Plane(Vector3(), normal); + Vector3 intersection; + if (grid_plane.intersects_ray(camera_position, camera_direction, &intersection)) { + camera_position = intersection; } + } + + real_t division_level = Math::log(Math::abs(camera_distance)) / Math::log((double)primary_grid_steps) + division_level_bias; - grid_points[i].push_back(p1); - grid_points[i].push_back(p1_dest); - grid_colors[i].push_back(line_color); - grid_colors[i].push_back(line_color); + real_t clamped_division_level = CLAMP(division_level, division_level_min, division_level_max); + real_t division_level_floored = Math::floor(clamped_division_level); + real_t division_level_decimals = clamped_division_level - division_level_floored; - grid_points[i].push_back(p2); - grid_points[i].push_back(p2_dest); - grid_colors[i].push_back(line_color); - grid_colors[i].push_back(line_color); + real_t small_step_size = Math::pow(primary_grid_steps, division_level_floored); + real_t large_step_size = small_step_size * primary_grid_steps; + real_t center_a = large_step_size * (int)(camera_position[a] / large_step_size); + real_t center_b = large_step_size * (int)(camera_position[b] / large_step_size); + + real_t bgn_a = center_a - grid_size * small_step_size; + real_t end_a = center_a + grid_size * small_step_size; + real_t bgn_b = center_b - grid_size * small_step_size; + real_t end_b = center_b + grid_size * small_step_size; + + real_t fade_size = Math::pow(primary_grid_steps, division_level - 1.0); + real_t min_fade_size = Math::pow(primary_grid_steps, float(division_level_min)); + real_t max_fade_size = Math::pow(primary_grid_steps, float(division_level_max)); + fade_size = CLAMP(fade_size, min_fade_size, max_fade_size); + + real_t grid_fade_size = (grid_size - primary_grid_steps) * fade_size; + grid_mat[c]->set_shader_param("grid_size", grid_fade_size); + grid_mat[c]->set_shader_param("orthogonal", orthogonal); + + // In each iteration of this loop, draw one line in each direction (so two lines per loop, in each if statement). + for (int i = -grid_size; i <= grid_size; i++) { + Color line_color; + // Is this a primary line? Set the appropriate color. + if (i % primary_grid_steps == 0) { + line_color = primary_grid_color.lerp(secondary_grid_color, division_level_decimals); + } else { + line_color = secondary_grid_color; + line_color.a = line_color.a * (1 - division_level_decimals); + } + + real_t position_a = center_a + i * small_step_size; + real_t position_b = center_b + i * small_step_size; + + // Don't draw lines over the origin if it's enabled. + if (!(origin_enabled && Math::is_zero_approx(position_a))) { + Vector3 line_bgn = Vector3(); + Vector3 line_end = Vector3(); + line_bgn[a] = position_a; + line_end[a] = position_a; + line_bgn[b] = bgn_b; + line_end[b] = end_b; + grid_points[c].push_back(line_bgn); + grid_points[c].push_back(line_end); + grid_colors[c].push_back(line_color); + grid_colors[c].push_back(line_color); + grid_normals[c].push_back(normal); + grid_normals[c].push_back(normal); + } + + if (!(origin_enabled && Math::is_zero_approx(position_b))) { + Vector3 line_bgn = Vector3(); + Vector3 line_end = Vector3(); + line_bgn[b] = position_b; + line_end[b] = position_b; + line_bgn[a] = bgn_a; + line_end[a] = end_a; + grid_points[c].push_back(line_bgn); + grid_points[c].push_back(line_end); + grid_colors[c].push_back(line_color); + grid_colors[c].push_back(line_color); + grid_normals[c].push_back(normal); + grid_normals[c].push_back(normal); + } } - grid[i] = RenderingServer::get_singleton()->mesh_create(); + // Create a mesh from the pushed vector points and colors. + grid[c] = RenderingServer::get_singleton()->mesh_create(); Array d; d.resize(RS::ARRAY_MAX); - d[RenderingServer::ARRAY_VERTEX] = grid_points[i]; - d[RenderingServer::ARRAY_COLOR] = grid_colors[i]; - RenderingServer::get_singleton()->mesh_add_surface_from_arrays(grid[i], RenderingServer::PRIMITIVE_LINES, d); - RenderingServer::get_singleton()->mesh_surface_set_material(grid[i], 0, indicator_mat->get_rid()); - grid_instance[i] = RenderingServer::get_singleton()->instance_create2(grid[i], get_tree()->get_root()->get_world_3d()->get_scenario()); + d[RenderingServer::ARRAY_VERTEX] = grid_points[c]; + d[RenderingServer::ARRAY_COLOR] = grid_colors[c]; + d[RenderingServer::ARRAY_NORMAL] = grid_normals[c]; + RenderingServer::get_singleton()->mesh_add_surface_from_arrays(grid[c], RenderingServer::PRIMITIVE_LINES, d); + RenderingServer::get_singleton()->mesh_surface_set_material(grid[c], 0, grid_mat[c]->get_rid()); + grid_instance[c] = RenderingServer::get_singleton()->instance_create2(grid[c], get_tree()->get_root()->get_world_3d()->get_scenario()); - RenderingServer::get_singleton()->instance_set_visible(grid_instance[i], grid_visible[i]); - RenderingServer::get_singleton()->instance_geometry_set_cast_shadows_setting(grid_instance[i], RS::SHADOW_CASTING_SETTING_OFF); - RS::get_singleton()->instance_set_layer_mask(grid_instance[i], 1 << Node3DEditorViewport::GIZMO_GRID_LAYER); + // Yes, the end of this line is supposed to be a. + RenderingServer::get_singleton()->instance_set_visible(grid_instance[c], grid_visible[a]); + RenderingServer::get_singleton()->instance_geometry_set_cast_shadows_setting(grid_instance[c], RS::SHADOW_CASTING_SETTING_OFF); + RS::get_singleton()->instance_set_layer_mask(grid_instance[c], 1 << Node3DEditorViewport::GIZMO_GRID_LAYER); } } @@ -5489,6 +5954,11 @@ void Node3DEditor::_finish_grid() { } } +void Node3DEditor::update_grid() { + _finish_grid(); + _init_grid(); +} + bool Node3DEditor::is_any_freelook_active() const { for (unsigned int i = 0; i < VIEWPORTS_COUNT; ++i) { if (viewports[i]->is_freelook_active()) { @@ -5504,7 +5974,7 @@ void Node3DEditor::_refresh_menu_icons() { List<Node *> &selection = editor_selection->get_selected_node_list(); - if (selection.empty()) { + if (selection.is_empty()) { all_locked = false; all_grouped = false; } else { @@ -5523,11 +5993,11 @@ void Node3DEditor::_refresh_menu_icons() { } tool_button[TOOL_LOCK_SELECTED]->set_visible(!all_locked); - tool_button[TOOL_LOCK_SELECTED]->set_disabled(selection.empty()); + tool_button[TOOL_LOCK_SELECTED]->set_disabled(selection.is_empty()); tool_button[TOOL_UNLOCK_SELECTED]->set_visible(all_locked); tool_button[TOOL_GROUP_SELECTED]->set_visible(!all_grouped); - tool_button[TOOL_GROUP_SELECTED]->set_disabled(selection.empty()); + tool_button[TOOL_GROUP_SELECTED]->set_disabled(selection.is_empty()); tool_button[TOOL_UNGROUP_SELECTED]->set_visible(all_grouped); } @@ -5577,16 +6047,30 @@ void Node3DEditor::snap_selected_nodes_to_floor() { // Priorities for snapping to floor are CollisionShapes, VisualInstances and then origin Set<VisualInstance3D *> vi = _get_child_nodes<VisualInstance3D>(sp); Set<CollisionShape3D *> cs = _get_child_nodes<CollisionShape3D>(sp); + bool found_valid_shape = false; if (cs.size()) { - AABB aabb = sp->get_global_transform().xform(cs.front()->get()->get_shape()->get_debug_mesh()->get_aabb()); - for (Set<CollisionShape3D *>::Element *I = cs.front(); I; I = I->next()) { - aabb.merge_with(sp->get_global_transform().xform(I->get()->get_shape()->get_debug_mesh()->get_aabb())); + AABB aabb; + Set<CollisionShape3D *>::Element *I = cs.front(); + if (I->get()->get_shape().is_valid()) { + CollisionShape3D *collision_shape = cs.front()->get(); + aabb = collision_shape->get_global_transform().xform(collision_shape->get_shape()->get_debug_mesh()->get_aabb()); + found_valid_shape = true; } - Vector3 size = aabb.size * Vector3(0.5, 0.0, 0.5); - from = aabb.position + size; - position_offset.y = from.y - sp->get_global_transform().origin.y; - } else if (vi.size()) { + for (I = I->next(); I; I = I->next()) { + CollisionShape3D *col_shape = I->get(); + if (col_shape->get_shape().is_valid()) { + aabb.merge_with(col_shape->get_global_transform().xform(col_shape->get_shape()->get_debug_mesh()->get_aabb())); + found_valid_shape = true; + } + } + if (found_valid_shape) { + Vector3 size = aabb.size * Vector3(0.5, 0.0, 0.5); + from = aabb.position + size; + position_offset.y = from.y - sp->get_global_transform().origin.y; + } + } + if (!found_valid_shape && vi.size()) { AABB aabb = vi.front()->get()->get_transformed_aabb(); for (Set<VisualInstance3D *>::Element *I = vi.front(); I; I = I->next()) { aabb.merge_with(I->get()->get_transformed_aabb()); @@ -5594,7 +6078,7 @@ void Node3DEditor::snap_selected_nodes_to_floor() { Vector3 size = aabb.size * Vector3(0.5, 0.0, 0.5); from = aabb.position + size; position_offset.y = from.y - sp->get_global_transform().origin.y; - } else { + } else if (!found_valid_shape) { from = sp->get_global_transform().origin; } @@ -5677,6 +6161,51 @@ void Node3DEditor::_unhandled_key_input(Ref<InputEvent> p_event) { snap_key_enabled = Input::get_singleton()->is_key_pressed(KEY_CONTROL); } +void Node3DEditor::_sun_environ_settings_pressed() { + Vector2 pos = sun_environ_settings->get_screen_position() + sun_environ_settings->get_size(); + sun_environ_popup->set_position(pos - Vector2(sun_environ_popup->get_contents_minimum_size().width / 2, 0)); + sun_environ_popup->popup(); +} + +void Node3DEditor::_add_sun_to_scene() { + sun_environ_popup->hide(); + + Node *base = get_tree()->get_edited_scene_root(); + if (!base) { + EditorNode::get_singleton()->show_warning(TTR("A root node is needed for this operation")); + return; + } + ERR_FAIL_COND(!base); + Node *new_sun = preview_sun->duplicate(); + + undo_redo->create_action("Add Preview Sun to Scene"); + undo_redo->add_do_method(base, "add_child", new_sun); + undo_redo->add_do_method(new_sun, "set_owner", base); + undo_redo->add_undo_method(base, "remove_child", new_sun); + undo_redo->add_do_reference(new_sun); + undo_redo->commit_action(); +} +void Node3DEditor::_add_environment_to_scene() { + sun_environ_popup->hide(); + + Node *base = get_tree()->get_edited_scene_root(); + if (!base) { + EditorNode::get_singleton()->show_warning(TTR("A root node is needed for this operation")); + return; + } + ERR_FAIL_COND(!base); + + WorldEnvironment *new_env = memnew(WorldEnvironment); + new_env->set_environment(preview_environment->get_environment()->duplicate(true)); + + undo_redo->create_action("Add Preview Environment to Scene"); + undo_redo->add_do_method(base, "add_child", new_env); + undo_redo->add_do_method(new_env, "set_owner", base); + undo_redo->add_undo_method(base, "remove_child", new_env); + undo_redo->add_do_reference(new_env); + undo_redo->commit_action(); +} + void Node3DEditor::_notification(int p_what) { if (p_what == NOTIFICATION_READY) { tool_button[Node3DEditor::TOOL_MODE_SELECT]->set_icon(get_theme_icon("ToolSelect", "EditorIcons")); @@ -5705,17 +6234,31 @@ void Node3DEditor::_notification(int p_what) { _refresh_menu_icons(); get_tree()->connect("node_removed", callable_mp(this, &Node3DEditor::_node_removed)); + get_tree()->connect("node_added", callable_mp(this, &Node3DEditor::_node_added)); EditorNode::get_singleton()->get_scene_tree_dock()->get_tree_editor()->connect("node_changed", callable_mp(this, &Node3DEditor::_refresh_menu_icons)); editor_selection->connect("selection_changed", callable_mp(this, &Node3DEditor::_refresh_menu_icons)); editor->connect("stop_pressed", callable_mp(this, &Node3DEditor::_update_camera_override_button), make_binds(false)); editor->connect("play_pressed", callable_mp(this, &Node3DEditor::_update_camera_override_button), make_binds(true)); + + sun_button->set_icon(get_theme_icon("DirectionalLight3D", "EditorIcons")); + environ_button->set_icon(get_theme_icon("WorldEnvironment", "EditorIcons")); + sun_environ_settings->set_icon(get_theme_icon("GuiTabMenuHl", "EditorIcons")); + + _update_preview_environment(); + sun_title->add_theme_font_override("font", get_theme_font("title_font", "Window")); + environ_title->add_theme_font_override("font", get_theme_font("title_font", "Window")); + + sun_state->set_custom_minimum_size(sun_vb->get_combined_minimum_size()); + environ_state->set_custom_minimum_size(environ_vb->get_combined_minimum_size()); } else if (p_what == NOTIFICATION_ENTER_TREE) { _register_all_gizmos(); _update_gizmos_menu(); _init_indicators(); } else if (p_what == NOTIFICATION_THEME_CHANGED) { _update_gizmos_menu_theme(); + sun_title->add_theme_font_override("font", get_theme_font("title_font", "Window")); + environ_title->add_theme_font_override("font", get_theme_font("title_font", "Window")); } else if (p_what == NOTIFICATION_EXIT_TREE) { _finish_indicators(); } else if (p_what == EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED) { @@ -5826,7 +6369,7 @@ void Node3DEditor::_toggle_maximize_view(Object *p_viewport) { if (!maximized) { for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) { if (i == (uint32_t)index) { - viewports[i]->set_anchors_and_margins_preset(Control::PRESET_WIDE); + viewports[i]->set_anchors_and_offsets_preset(Control::PRESET_WIDE); } else { viewports[i]->hide(); } @@ -5852,7 +6395,37 @@ void Node3DEditor::_toggle_maximize_view(Object *p_viewport) { } } +void Node3DEditor::_node_added(Node *p_node) { + if (EditorNode::get_singleton()->get_scene_root()->is_a_parent_of(p_node)) { + if (Object::cast_to<WorldEnvironment>(p_node)) { + world_env_count++; + if (world_env_count == 1) { + _update_preview_environment(); + } + } else if (Object::cast_to<DirectionalLight3D>(p_node)) { + directional_light_count++; + if (directional_light_count == 1) { + _update_preview_environment(); + } + } + } +} + void Node3DEditor::_node_removed(Node *p_node) { + if (EditorNode::get_singleton()->get_scene_root()->is_a_parent_of(p_node)) { + if (Object::cast_to<WorldEnvironment>(p_node)) { + world_env_count--; + if (world_env_count == 0) { + _update_preview_environment(); + } + } else if (Object::cast_to<DirectionalLight3D>(p_node)) { + directional_light_count--; + if (directional_light_count == 0) { + _update_preview_environment(); + } + } + } + if (p_node == selected) { selected = nullptr; } @@ -5872,12 +6445,14 @@ void Node3DEditor::_register_all_gizmos() { add_gizmo_plugin(Ref<VehicleWheel3DGizmoPlugin>(memnew(VehicleWheel3DGizmoPlugin))); add_gizmo_plugin(Ref<VisibilityNotifier3DGizmoPlugin>(memnew(VisibilityNotifier3DGizmoPlugin))); add_gizmo_plugin(Ref<GPUParticles3DGizmoPlugin>(memnew(GPUParticles3DGizmoPlugin))); + add_gizmo_plugin(Ref<GPUParticlesCollision3DGizmoPlugin>(memnew(GPUParticlesCollision3DGizmoPlugin))); add_gizmo_plugin(Ref<CPUParticles3DGizmoPlugin>(memnew(CPUParticles3DGizmoPlugin))); add_gizmo_plugin(Ref<ReflectionProbeGizmoPlugin>(memnew(ReflectionProbeGizmoPlugin))); add_gizmo_plugin(Ref<DecalGizmoPlugin>(memnew(DecalGizmoPlugin))); add_gizmo_plugin(Ref<GIProbeGizmoPlugin>(memnew(GIProbeGizmoPlugin))); add_gizmo_plugin(Ref<BakedLightmapGizmoPlugin>(memnew(BakedLightmapGizmoPlugin))); add_gizmo_plugin(Ref<LightmapProbeGizmoPlugin>(memnew(LightmapProbeGizmoPlugin))); + add_gizmo_plugin(Ref<CollisionObject3DGizmoPlugin>(memnew(CollisionObject3DGizmoPlugin))); add_gizmo_plugin(Ref<CollisionShape3DGizmoPlugin>(memnew(CollisionShape3DGizmoPlugin))); add_gizmo_plugin(Ref<CollisionPolygon3DGizmoPlugin>(memnew(CollisionPolygon3DGizmoPlugin))); add_gizmo_plugin(Ref<NavigationRegion3DGizmoPlugin>(memnew(NavigationRegion3DGizmoPlugin))); @@ -5889,6 +6464,7 @@ void Node3DEditor::_bind_methods() { ClassDB::bind_method("_unhandled_key_input", &Node3DEditor::_unhandled_key_input); ClassDB::bind_method("_get_editor_data", &Node3DEditor::_get_editor_data); ClassDB::bind_method("_request_gizmo", &Node3DEditor::_request_gizmo); + ClassDB::bind_method("_refresh_menu_icons", &Node3DEditor::_refresh_menu_icons); ADD_SIGNAL(MethodInfo("transform_key_request")); ADD_SIGNAL(MethodInfo("item_lock_status_changed")); @@ -5896,9 +6472,9 @@ void Node3DEditor::_bind_methods() { } void Node3DEditor::clear() { - settings_fov->set_value(EDITOR_DEF("editors/3d/default_fov", 70.0)); - settings_znear->set_value(EDITOR_DEF("editors/3d/default_z_near", 0.05)); - settings_zfar->set_value(EDITOR_DEF("editors/3d/default_z_far", 1500.0)); + settings_fov->set_value(EDITOR_GET("editors/3d/default_fov")); + settings_znear->set_value(EDITOR_GET("editors/3d/default_z_near")); + settings_zfar->set_value(EDITOR_GET("editors/3d/default_z_far")); for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) { viewports[i]->reset(); @@ -5908,7 +6484,6 @@ void Node3DEditor::clear() { view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_ORIGIN), true); for (int i = 0; i < 3; ++i) { if (grid_enable[i]) { - RenderingServer::get_singleton()->instance_set_visible(grid_instance[i], true); grid_visible[i] = true; } } @@ -5921,6 +6496,128 @@ void Node3DEditor::clear() { view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_GRID), true); } +void Node3DEditor::_sun_direction_draw() { + sun_direction->draw_rect(Rect2(Vector2(), sun_direction->get_size()), Color(1, 1, 1, 1)); + sun_direction_material->set_shader_param("sun_direction", -preview_sun->get_transform().basis.get_axis(Vector3::AXIS_Z)); + float nrg = sun_energy->get_value(); + sun_direction_material->set_shader_param("sun_color", Vector3(sun_color->get_pick_color().r * nrg, sun_color->get_pick_color().g * nrg, sun_color->get_pick_color().b * nrg)); +} + +void Node3DEditor::_preview_settings_changed() { + if (sun_environ_updating) { + return; + } + + { // preview sun + Transform t; + t.basis = sun_rotation; + preview_sun->set_transform(t); + sun_direction->update(); + preview_sun->set_param(Light3D::PARAM_ENERGY, sun_energy->get_value()); + preview_sun->set_param(Light3D::PARAM_SHADOW_MAX_DISTANCE, sun_max_distance->get_value()); + preview_sun->set_color(sun_color->get_pick_color()); + } + + { //preview env + sky_material->set_sky_energy(environ_energy->get_value()); + Color hz_color = environ_sky_color->get_pick_color().lerp(environ_ground_color->get_pick_color(), 0.5).lerp(Color(1, 1, 1), 0.5); + sky_material->set_sky_top_color(environ_sky_color->get_pick_color()); + sky_material->set_sky_horizon_color(hz_color); + sky_material->set_ground_bottom_color(environ_ground_color->get_pick_color()); + sky_material->set_ground_horizon_color(hz_color); + + environment->set_ssao_enabled(environ_ao_button->is_pressed()); + environment->set_glow_enabled(environ_glow_button->is_pressed()); + environment->set_sdfgi_enabled(environ_gi_button->is_pressed()); + environment->set_tonemapper(environ_tonemap_button->is_pressed() ? Environment::TONE_MAPPER_FILMIC : Environment::TONE_MAPPER_LINEAR); + } +} +void Node3DEditor::_load_default_preview_settings() { + sun_environ_updating = true; + + sun_rotation = Basis(Vector3(0, 1, 0), Math_PI * 3.0 / 4) * Basis(Vector3(1, 0, 0), -Math_PI / 4); + + sun_direction->update(); + environ_sky_color->set_pick_color(Color::hex(0x91b2ceff)); + environ_ground_color->set_pick_color(Color::hex(0x1f1f21ff)); + environ_energy->set_value(1.0); + environ_glow_button->set_pressed(true); + environ_tonemap_button->set_pressed(true); + environ_ao_button->set_pressed(false); + environ_gi_button->set_pressed(false); + sun_max_distance->set_value(250); + + sun_color->set_pick_color(Color(1, 1, 1)); + sun_energy->set_value(1.0); + + sun_environ_updating = false; +} + +void Node3DEditor::_update_preview_environment() { + bool disable_light = directional_light_count > 0 || sun_button->is_pressed(); + + sun_button->set_disabled(directional_light_count > 0); + + if (disable_light) { + if (preview_sun->get_parent()) { + preview_sun->get_parent()->remove_child(preview_sun); + sun_state->show(); + sun_vb->hide(); + } + + if (directional_light_count > 0) { + sun_state->set_text(TTR("Scene contains\nDirectionalLight3D.\nPreview disabled.")); + } else { + sun_state->set_text(TTR("Preview disabled.")); + } + + } else { + if (!preview_sun->get_parent()) { + add_child(preview_sun); + sun_state->hide(); + sun_vb->show(); + } + } + + bool disable_env = world_env_count > 0 || environ_button->is_pressed(); + + environ_button->set_disabled(world_env_count > 0); + + if (disable_env) { + if (preview_environment->get_parent()) { + preview_environment->get_parent()->remove_child(preview_environment); + environ_state->show(); + environ_vb->hide(); + } + if (world_env_count > 0) { + environ_state->set_text(TTR("Scene contains\nWorldEnvironment.\nPreview disabled.")); + } else { + environ_state->set_text(TTR("Preview disabled.")); + } + + } else { + if (!preview_environment->get_parent()) { + add_child(preview_environment); + environ_state->hide(); + environ_vb->show(); + } + } +} + +void Node3DEditor::_sun_direction_input(const Ref<InputEvent> &p_event) { + Ref<InputEventMouseMotion> mm = p_event; + if (mm.is_valid() && mm->get_button_mask() & BUTTON_MASK_LEFT) { + float x = -mm->get_relative().y * 0.02 * EDSCALE; + float y = mm->get_relative().x * 0.02 * EDSCALE; + + Basis rot = Basis(Vector3(0, 1, 0), y) * Basis(Vector3(1, 0, 0), x); + + sun_rotation = rot * sun_rotation; + sun_rotation.orthonormalize(); + _preview_settings_changed(); + } +} + Node3DEditor::Node3DEditor(EditorNode *p_editor) { gizmo.visible = true; gizmo.scale = 1.0; @@ -5948,7 +6645,7 @@ Node3DEditor::Node3DEditor(EditorNode *p_editor) { button_binds.resize(1); String sct; - tool_button[TOOL_MODE_SELECT] = memnew(ToolButton); + tool_button[TOOL_MODE_SELECT] = memnew(Button); hbc_menu->add_child(tool_button[TOOL_MODE_SELECT]); tool_button[TOOL_MODE_SELECT]->set_toggle_mode(true); tool_button[TOOL_MODE_SELECT]->set_flat(true); @@ -5956,37 +6653,41 @@ Node3DEditor::Node3DEditor(EditorNode *p_editor) { button_binds.write[0] = MENU_TOOL_SELECT; tool_button[TOOL_MODE_SELECT]->connect("pressed", callable_mp(this, &Node3DEditor::_menu_item_pressed), button_binds); tool_button[TOOL_MODE_SELECT]->set_shortcut(ED_SHORTCUT("spatial_editor/tool_select", TTR("Select Mode"), KEY_Q)); + tool_button[TOOL_MODE_SELECT]->set_shortcut_context(this); tool_button[TOOL_MODE_SELECT]->set_tooltip(keycode_get_string(KEY_MASK_CMD) + TTR("Drag: Rotate\nAlt+Drag: Move\nAlt+RMB: Depth list selection")); hbc_menu->add_child(memnew(VSeparator)); - tool_button[TOOL_MODE_MOVE] = memnew(ToolButton); + tool_button[TOOL_MODE_MOVE] = memnew(Button); hbc_menu->add_child(tool_button[TOOL_MODE_MOVE]); tool_button[TOOL_MODE_MOVE]->set_toggle_mode(true); tool_button[TOOL_MODE_MOVE]->set_flat(true); button_binds.write[0] = MENU_TOOL_MOVE; tool_button[TOOL_MODE_MOVE]->connect("pressed", callable_mp(this, &Node3DEditor::_menu_item_pressed), button_binds); tool_button[TOOL_MODE_MOVE]->set_shortcut(ED_SHORTCUT("spatial_editor/tool_move", TTR("Move Mode"), KEY_W)); + tool_button[TOOL_MODE_MOVE]->set_shortcut_context(this); - tool_button[TOOL_MODE_ROTATE] = memnew(ToolButton); + tool_button[TOOL_MODE_ROTATE] = memnew(Button); hbc_menu->add_child(tool_button[TOOL_MODE_ROTATE]); tool_button[TOOL_MODE_ROTATE]->set_toggle_mode(true); tool_button[TOOL_MODE_ROTATE]->set_flat(true); button_binds.write[0] = MENU_TOOL_ROTATE; tool_button[TOOL_MODE_ROTATE]->connect("pressed", callable_mp(this, &Node3DEditor::_menu_item_pressed), button_binds); tool_button[TOOL_MODE_ROTATE]->set_shortcut(ED_SHORTCUT("spatial_editor/tool_rotate", TTR("Rotate Mode"), KEY_E)); + tool_button[TOOL_MODE_ROTATE]->set_shortcut_context(this); - tool_button[TOOL_MODE_SCALE] = memnew(ToolButton); + tool_button[TOOL_MODE_SCALE] = memnew(Button); hbc_menu->add_child(tool_button[TOOL_MODE_SCALE]); tool_button[TOOL_MODE_SCALE]->set_toggle_mode(true); tool_button[TOOL_MODE_SCALE]->set_flat(true); button_binds.write[0] = MENU_TOOL_SCALE; tool_button[TOOL_MODE_SCALE]->connect("pressed", callable_mp(this, &Node3DEditor::_menu_item_pressed), button_binds); tool_button[TOOL_MODE_SCALE]->set_shortcut(ED_SHORTCUT("spatial_editor/tool_scale", TTR("Scale Mode"), KEY_R)); + tool_button[TOOL_MODE_SCALE]->set_shortcut_context(this); hbc_menu->add_child(memnew(VSeparator)); - tool_button[TOOL_MODE_LIST_SELECT] = memnew(ToolButton); + tool_button[TOOL_MODE_LIST_SELECT] = memnew(Button); hbc_menu->add_child(tool_button[TOOL_MODE_LIST_SELECT]); tool_button[TOOL_MODE_LIST_SELECT]->set_toggle_mode(true); tool_button[TOOL_MODE_LIST_SELECT]->set_flat(true); @@ -5994,51 +6695,57 @@ Node3DEditor::Node3DEditor(EditorNode *p_editor) { tool_button[TOOL_MODE_LIST_SELECT]->connect("pressed", callable_mp(this, &Node3DEditor::_menu_item_pressed), button_binds); tool_button[TOOL_MODE_LIST_SELECT]->set_tooltip(TTR("Show a list of all objects at the position clicked\n(same as Alt+RMB in select mode).")); - tool_button[TOOL_LOCK_SELECTED] = memnew(ToolButton); + tool_button[TOOL_LOCK_SELECTED] = memnew(Button); hbc_menu->add_child(tool_button[TOOL_LOCK_SELECTED]); + tool_button[TOOL_LOCK_SELECTED]->set_flat(true); button_binds.write[0] = MENU_LOCK_SELECTED; tool_button[TOOL_LOCK_SELECTED]->connect("pressed", callable_mp(this, &Node3DEditor::_menu_item_pressed), button_binds); tool_button[TOOL_LOCK_SELECTED]->set_tooltip(TTR("Lock the selected object in place (can't be moved).")); - tool_button[TOOL_UNLOCK_SELECTED] = memnew(ToolButton); + tool_button[TOOL_UNLOCK_SELECTED] = memnew(Button); hbc_menu->add_child(tool_button[TOOL_UNLOCK_SELECTED]); + tool_button[TOOL_UNLOCK_SELECTED]->set_flat(true); button_binds.write[0] = MENU_UNLOCK_SELECTED; tool_button[TOOL_UNLOCK_SELECTED]->connect("pressed", callable_mp(this, &Node3DEditor::_menu_item_pressed), button_binds); tool_button[TOOL_UNLOCK_SELECTED]->set_tooltip(TTR("Unlock the selected object (can be moved).")); - tool_button[TOOL_GROUP_SELECTED] = memnew(ToolButton); + tool_button[TOOL_GROUP_SELECTED] = memnew(Button); hbc_menu->add_child(tool_button[TOOL_GROUP_SELECTED]); + tool_button[TOOL_GROUP_SELECTED]->set_flat(true); button_binds.write[0] = MENU_GROUP_SELECTED; tool_button[TOOL_GROUP_SELECTED]->connect("pressed", callable_mp(this, &Node3DEditor::_menu_item_pressed), button_binds); tool_button[TOOL_GROUP_SELECTED]->set_tooltip(TTR("Makes sure the object's children are not selectable.")); - tool_button[TOOL_UNGROUP_SELECTED] = memnew(ToolButton); + tool_button[TOOL_UNGROUP_SELECTED] = memnew(Button); hbc_menu->add_child(tool_button[TOOL_UNGROUP_SELECTED]); + tool_button[TOOL_UNGROUP_SELECTED]->set_flat(true); button_binds.write[0] = MENU_UNGROUP_SELECTED; tool_button[TOOL_UNGROUP_SELECTED]->connect("pressed", callable_mp(this, &Node3DEditor::_menu_item_pressed), button_binds); tool_button[TOOL_UNGROUP_SELECTED]->set_tooltip(TTR("Restores the object's children's ability to be selected.")); hbc_menu->add_child(memnew(VSeparator)); - tool_option_button[TOOL_OPT_LOCAL_COORDS] = memnew(ToolButton); + tool_option_button[TOOL_OPT_LOCAL_COORDS] = memnew(Button); hbc_menu->add_child(tool_option_button[TOOL_OPT_LOCAL_COORDS]); tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_toggle_mode(true); tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_flat(true); button_binds.write[0] = MENU_TOOL_LOCAL_COORDS; tool_option_button[TOOL_OPT_LOCAL_COORDS]->connect("toggled", callable_mp(this, &Node3DEditor::_menu_item_toggled), button_binds); tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_shortcut(ED_SHORTCUT("spatial_editor/local_coords", TTR("Use Local Space"), KEY_T)); + tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_shortcut_context(this); - tool_option_button[TOOL_OPT_USE_SNAP] = memnew(ToolButton); + tool_option_button[TOOL_OPT_USE_SNAP] = memnew(Button); hbc_menu->add_child(tool_option_button[TOOL_OPT_USE_SNAP]); tool_option_button[TOOL_OPT_USE_SNAP]->set_toggle_mode(true); tool_option_button[TOOL_OPT_USE_SNAP]->set_flat(true); button_binds.write[0] = MENU_TOOL_USE_SNAP; tool_option_button[TOOL_OPT_USE_SNAP]->connect("toggled", callable_mp(this, &Node3DEditor::_menu_item_toggled), button_binds); tool_option_button[TOOL_OPT_USE_SNAP]->set_shortcut(ED_SHORTCUT("spatial_editor/snap", TTR("Use Snap"), KEY_Y)); + tool_option_button[TOOL_OPT_USE_SNAP]->set_shortcut_context(this); hbc_menu->add_child(memnew(VSeparator)); - tool_option_button[TOOL_OPT_OVERRIDE_CAMERA] = memnew(ToolButton); + tool_option_button[TOOL_OPT_OVERRIDE_CAMERA] = memnew(Button); hbc_menu->add_child(tool_option_button[TOOL_OPT_OVERRIDE_CAMERA]); tool_option_button[TOOL_OPT_OVERRIDE_CAMERA]->set_toggle_mode(true); tool_option_button[TOOL_OPT_OVERRIDE_CAMERA]->set_flat(true); @@ -6048,6 +6755,32 @@ Node3DEditor::Node3DEditor(EditorNode *p_editor) { _update_camera_override_button(false); hbc_menu->add_child(memnew(VSeparator)); + sun_button = memnew(Button); + sun_button->set_tooltip(TTR("Toggle preview sunlight.\nIf a DirectionalLight3D node is added to the scene, preview sunlight is disabled.")); + sun_button->set_toggle_mode(true); + sun_button->set_flat(true); + sun_button->connect("pressed", callable_mp(this, &Node3DEditor::_update_preview_environment), varray(), CONNECT_DEFERRED); + sun_button->set_disabled(true); + + hbc_menu->add_child(sun_button); + + environ_button = memnew(Button); + environ_button->set_tooltip(TTR("Toggle preview environment.\nIf a WorldEnvironment node is added to the scene, preview environment is disabled.")); + environ_button->set_toggle_mode(true); + environ_button->set_flat(true); + environ_button->connect("pressed", callable_mp(this, &Node3DEditor::_update_preview_environment), varray(), CONNECT_DEFERRED); + environ_button->set_disabled(true); + + hbc_menu->add_child(environ_button); + + sun_environ_settings = memnew(Button); + sun_environ_settings->set_tooltip(TTR("Edit Sun and Environment settings.")); + sun_environ_settings->set_flat(true); + sun_environ_settings->connect("pressed", callable_mp(this, &Node3DEditor::_sun_environ_settings_pressed)); + + hbc_menu->add_child(sun_environ_settings); + + hbc_menu->add_child(memnew(VSeparator)); // Drag and drop support; preview_node = memnew(Node3D); @@ -6072,6 +6805,7 @@ Node3DEditor::Node3DEditor(EditorNode *p_editor) { transform_menu = memnew(MenuButton); transform_menu->set_text(TTR("Transform")); transform_menu->set_switch_on_hover(true); + transform_menu->set_shortcut_context(this); hbc_menu->add_child(transform_menu); p = transform_menu->get_popup(); @@ -6086,6 +6820,7 @@ Node3DEditor::Node3DEditor(EditorNode *p_editor) { view_menu = memnew(MenuButton); view_menu->set_text(TTR("View")); view_menu->set_switch_on_hover(true); + view_menu->set_shortcut_context(this); hbc_menu->add_child(view_menu); p = view_menu->get_popup(); @@ -6151,7 +6886,7 @@ Node3DEditor::Node3DEditor(EditorNode *p_editor) { snap_dialog->set_title(TTR("Snap Settings")); add_child(snap_dialog); snap_dialog->connect("confirmed", callable_mp(this, &Node3DEditor::_snap_changed)); - snap_dialog->get_cancel()->connect("pressed", callable_mp(this, &Node3DEditor::_snap_update)); + snap_dialog->get_cancel_button()->connect("pressed", callable_mp(this, &Node3DEditor::_snap_update)); VBoxContainer *snap_dialog_vbc = memnew(VBoxContainer); snap_dialog->add_child(snap_dialog_vbc); @@ -6179,22 +6914,22 @@ Node3DEditor::Node3DEditor(EditorNode *p_editor) { settings_fov = memnew(SpinBox); settings_fov->set_max(MAX_FOV); settings_fov->set_min(MIN_FOV); - settings_fov->set_step(0.01); - settings_fov->set_value(EDITOR_DEF("editors/3d/default_fov", 70.0)); + settings_fov->set_step(0.1); + settings_fov->set_value(EDITOR_GET("editors/3d/default_fov")); settings_vbc->add_margin_child(TTR("Perspective FOV (deg.):"), settings_fov); settings_znear = memnew(SpinBox); settings_znear->set_max(MAX_Z); settings_znear->set_min(MIN_Z); settings_znear->set_step(0.01); - settings_znear->set_value(EDITOR_DEF("editors/3d/default_z_near", 0.05)); + settings_znear->set_value(EDITOR_GET("editors/3d/default_z_near")); settings_vbc->add_margin_child(TTR("View Z-Near:"), settings_znear); settings_zfar = memnew(SpinBox); settings_zfar->set_max(MAX_Z); settings_zfar->set_min(MIN_Z); - settings_zfar->set_step(0.01); - settings_zfar->set_value(EDITOR_DEF("editors/3d/default_z_far", 1500)); + settings_zfar->set_step(0.1); + settings_zfar->set_value(EDITOR_GET("editors/3d/default_z_far")); settings_vbc->add_margin_child(TTR("View Z-Far:"), settings_zfar); for (uint32_t i = 0; i < VIEWPORTS_COUNT; ++i) { @@ -6269,12 +7004,158 @@ Node3DEditor::Node3DEditor(EditorNode *p_editor) { add_to_group("_spatial_editor_group"); EDITOR_DEF("editors/3d/manipulator_gizmo_size", 80); - EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::INT, "editors/3d/manipulator_gizmo_size", PROPERTY_HINT_RANGE, "16,1024,1")); - EDITOR_DEF("editors/3d/manipulator_gizmo_opacity", 0.4); + EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::INT, "editors/3d/manipulator_gizmo_size", PROPERTY_HINT_RANGE, "16,160,1")); + EDITOR_DEF("editors/3d/manipulator_gizmo_opacity", 0.9); EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::FLOAT, "editors/3d/manipulator_gizmo_opacity", PROPERTY_HINT_RANGE, "0,1,0.01")); EDITOR_DEF("editors/3d/navigation/show_viewport_rotation_gizmo", true); over_gizmo_handle = -1; + { + //sun popup + + sun_environ_popup = memnew(PopupPanel); + add_child(sun_environ_popup); + + HBoxContainer *sun_environ_hb = memnew(HBoxContainer); + + sun_environ_popup->add_child(sun_environ_hb); + + sun_vb = memnew(VBoxContainer); + sun_environ_hb->add_child(sun_vb); + sun_vb->set_custom_minimum_size(Size2(200 * EDSCALE, 0)); + sun_vb->hide(); + + sun_title = memnew(Label); + sun_vb->add_child(sun_title); + sun_title->set_text(TTR("Preview Sun")); + sun_title->set_align(Label::ALIGN_CENTER); + + CenterContainer *sun_direction_center = memnew(CenterContainer); + sun_direction = memnew(Control); + sun_direction->set_custom_minimum_size(Size2i(128, 128) * EDSCALE); + sun_direction_center->add_child(sun_direction); + sun_vb->add_margin_child(TTR("Sun Direction"), sun_direction_center); + sun_direction->connect("gui_input", callable_mp(this, &Node3DEditor::_sun_direction_input)); + sun_direction->connect("draw", callable_mp(this, &Node3DEditor::_sun_direction_draw)); + sun_direction->set_default_cursor_shape(CURSOR_MOVE); + + String sun_dir_shader_code = "shader_type canvas_item; uniform vec3 sun_direction; uniform vec3 sun_color; void fragment() { vec3 n; n.xy = UV * 2.0 - 1.0; n.z = sqrt(max(0.0, 1.0 - dot(n.xy, n.xy))); COLOR.rgb = dot(n,sun_direction) * sun_color; COLOR.a = 1.0 - smoothstep(0.99,1.0,length(n.xy)); }"; + sun_direction_shader.instance(); + sun_direction_shader->set_code(sun_dir_shader_code); + sun_direction_material.instance(); + sun_direction_material->set_shader(sun_direction_shader); + sun_direction_material->set_shader_param("sun_direction", Vector3(0, 0, 1)); + sun_direction_material->set_shader_param("sun_color", Vector3(1, 1, 1)); + sun_direction->set_material(sun_direction_material); + + sun_color = memnew(ColorPickerButton); + sun_color->set_edit_alpha(false); + sun_vb->add_margin_child(TTR("Sun Color"), sun_color); + sun_color->connect("color_changed", callable_mp(this, &Node3DEditor::_preview_settings_changed).unbind(1)); + + sun_energy = memnew(EditorSpinSlider); + sun_vb->add_margin_child(TTR("Sun Energy"), sun_energy); + sun_energy->connect("value_changed", callable_mp(this, &Node3DEditor::_preview_settings_changed).unbind(1)); + sun_energy->set_max(64.0); + + sun_max_distance = memnew(EditorSpinSlider); + sun_vb->add_margin_child(TTR("Shadow Max Distance"), sun_max_distance); + sun_max_distance->connect("value_changed", callable_mp(this, &Node3DEditor::_preview_settings_changed).unbind(1)); + sun_max_distance->set_min(1); + sun_max_distance->set_max(4096); + + sun_add_to_scene = memnew(Button); + sun_add_to_scene->set_text(TTR("Add Sun to Scene")); + sun_add_to_scene->connect("pressed", callable_mp(this, &Node3DEditor::_add_sun_to_scene)); + sun_vb->add_spacer(); + sun_vb->add_child(sun_add_to_scene); + + sun_state = memnew(Label); + sun_environ_hb->add_child(sun_state); + sun_state->set_align(Label::ALIGN_CENTER); + sun_state->set_valign(Label::VALIGN_CENTER); + sun_state->set_h_size_flags(SIZE_EXPAND_FILL); + + VSeparator *sc = memnew(VSeparator); + sc->set_custom_minimum_size(Size2(50 * EDSCALE, 0)); + sc->set_v_size_flags(SIZE_EXPAND_FILL); + sun_environ_hb->add_child(sc); + + environ_vb = memnew(VBoxContainer); + sun_environ_hb->add_child(environ_vb); + environ_vb->set_custom_minimum_size(Size2(200 * EDSCALE, 0)); + environ_vb->hide(); + + environ_title = memnew(Label); + environ_vb->add_child(environ_title); + environ_title->set_text(TTR("Preview Environment")); + environ_title->set_align(Label::ALIGN_CENTER); + + environ_sky_color = memnew(ColorPickerButton); + environ_sky_color->set_edit_alpha(false); + environ_sky_color->connect("color_changed", callable_mp(this, &Node3DEditor::_preview_settings_changed).unbind(1)); + environ_vb->add_margin_child(TTR("Sky Color"), environ_sky_color); + environ_ground_color = memnew(ColorPickerButton); + environ_ground_color->connect("color_changed", callable_mp(this, &Node3DEditor::_preview_settings_changed).unbind(1)); + environ_ground_color->set_edit_alpha(false); + environ_vb->add_margin_child(TTR("Ground Color"), environ_ground_color); + environ_energy = memnew(EditorSpinSlider); + environ_energy->connect("value_changed", callable_mp(this, &Node3DEditor::_preview_settings_changed).unbind(1)); + environ_energy->set_max(8.0); + environ_vb->add_margin_child(TTR("Sky Energy"), environ_energy); + HBoxContainer *fx_vb = memnew(HBoxContainer); + fx_vb->set_h_size_flags(SIZE_EXPAND_FILL); + + environ_ao_button = memnew(Button); + environ_ao_button->set_text(TTR("AO")); + environ_ao_button->set_toggle_mode(true); + environ_ao_button->connect("pressed", callable_mp(this, &Node3DEditor::_preview_settings_changed), varray(), CONNECT_DEFERRED); + fx_vb->add_child(environ_ao_button); + environ_glow_button = memnew(Button); + environ_glow_button->set_text(TTR("Glow")); + environ_glow_button->set_toggle_mode(true); + environ_glow_button->connect("pressed", callable_mp(this, &Node3DEditor::_preview_settings_changed), varray(), CONNECT_DEFERRED); + fx_vb->add_child(environ_glow_button); + environ_tonemap_button = memnew(Button); + environ_tonemap_button->set_text(TTR("Tonemap")); + environ_tonemap_button->set_toggle_mode(true); + environ_tonemap_button->connect("pressed", callable_mp(this, &Node3DEditor::_preview_settings_changed), varray(), CONNECT_DEFERRED); + fx_vb->add_child(environ_tonemap_button); + environ_gi_button = memnew(Button); + environ_gi_button->set_text(TTR("GI")); + environ_gi_button->set_toggle_mode(true); + environ_gi_button->connect("pressed", callable_mp(this, &Node3DEditor::_preview_settings_changed), varray(), CONNECT_DEFERRED); + fx_vb->add_child(environ_gi_button); + environ_vb->add_margin_child(TTR("Post Process"), fx_vb); + + environ_add_to_scene = memnew(Button); + environ_add_to_scene->set_text(TTR("Add Environment to Scene")); + environ_add_to_scene->connect("pressed", callable_mp(this, &Node3DEditor::_add_environment_to_scene)); + environ_vb->add_spacer(); + environ_vb->add_child(environ_add_to_scene); + + environ_state = memnew(Label); + sun_environ_hb->add_child(environ_state); + environ_state->set_align(Label::ALIGN_CENTER); + environ_state->set_valign(Label::VALIGN_CENTER); + environ_state->set_h_size_flags(SIZE_EXPAND_FILL); + + preview_sun = memnew(DirectionalLight3D); + preview_sun->set_shadow(true); + preview_sun->set_shadow_mode(DirectionalLight3D::SHADOW_PARALLEL_4_SPLITS); + preview_environment = memnew(WorldEnvironment); + environment.instance(); + preview_environment->set_environment(environment); + Ref<Sky> sky; + sky.instance(); + sky_material.instance(); + sky->set_material(sky_material); + environment->set_sky(sky); + environment->set_background(Environment::BG_SKY); + + _load_default_preview_settings(); + _preview_settings_changed(); + } } Node3DEditor::~Node3DEditor() { @@ -6324,9 +7205,9 @@ Vector3 Node3DEditor::snap_point(Vector3 p_target, Vector3 p_start) const { float Node3DEditor::get_translate_snap() const { float snap_value; if (Input::get_singleton()->is_key_pressed(KEY_SHIFT)) { - snap_value = snap_translate->get_text().to_double() / 10.0; + snap_value = snap_translate->get_text().to_float() / 10.0; } else { - snap_value = snap_translate->get_text().to_double(); + snap_value = snap_translate->get_text().to_float(); } return snap_value; @@ -6335,9 +7216,9 @@ float Node3DEditor::get_translate_snap() const { float Node3DEditor::get_rotate_snap() const { float snap_value; if (Input::get_singleton()->is_key_pressed(KEY_SHIFT)) { - snap_value = snap_rotate->get_text().to_double() / 3.0; + snap_value = snap_rotate->get_text().to_float() / 3.0; } else { - snap_value = snap_rotate->get_text().to_double(); + snap_value = snap_rotate->get_text().to_float(); } return snap_value; @@ -6346,9 +7227,9 @@ float Node3DEditor::get_rotate_snap() const { float Node3DEditor::get_scale_snap() const { float snap_value; if (Input::get_singleton()->is_key_pressed(KEY_SHIFT)) { - snap_value = snap_scale->get_text().to_double() / 2.0; + snap_value = snap_scale->get_text().to_float() / 2.0; } else { - snap_value = snap_scale->get_text().to_double(); + snap_value = snap_scale->get_text().to_float(); } return snap_value; @@ -6400,10 +7281,10 @@ Node3DEditorPlugin::Node3DEditorPlugin(EditorNode *p_node) { editor = p_node; spatial_editor = memnew(Node3DEditor(p_node)); spatial_editor->set_v_size_flags(Control::SIZE_EXPAND_FILL); - editor->get_viewport()->add_child(spatial_editor); + editor->get_main_control()->add_child(spatial_editor); spatial_editor->hide(); - spatial_editor->connect_compat("transform_key_request", editor->get_inspector_dock(), "_transform_keyed"); + spatial_editor->connect("transform_key_request", Callable(editor->get_inspector_dock(), "_transform_keyed")); } Node3DEditorPlugin::~Node3DEditorPlugin() { @@ -6490,16 +7371,15 @@ void EditorNode3DGizmoPlugin::create_icon_material(const String &p_name, const R materials[p_name] = icons; } -void EditorNode3DGizmoPlugin::create_handle_material(const String &p_name, bool p_billboard) { +void EditorNode3DGizmoPlugin::create_handle_material(const String &p_name, bool p_billboard, const Ref<Texture2D> &p_icon) { Ref<StandardMaterial3D> handle_material = Ref<StandardMaterial3D>(memnew(StandardMaterial3D)); handle_material->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED); handle_material->set_flag(StandardMaterial3D::FLAG_USE_POINT_SIZE, true); - Ref<Texture2D> handle_t = Node3DEditor::get_singleton()->get_theme_icon("Editor3DHandle", "EditorIcons"); + Ref<Texture2D> handle_t = p_icon != nullptr ? p_icon : Node3DEditor::get_singleton()->get_theme_icon("Editor3DHandle", "EditorIcons"); handle_material->set_point_size(handle_t->get_width()); handle_material->set_texture(StandardMaterial3D::TEXTURE_ALBEDO, handle_t); handle_material->set_albedo(Color(1, 1, 1)); - handle_material->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA); handle_material->set_flag(StandardMaterial3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true); handle_material->set_flag(StandardMaterial3D::FLAG_SRGB_VERTEX_COLOR, true); handle_material->set_on_top_of_alpha(); @@ -6507,6 +7387,7 @@ void EditorNode3DGizmoPlugin::create_handle_material(const String &p_name, bool handle_material->set_billboard_mode(StandardMaterial3D::BILLBOARD_ENABLED); handle_material->set_on_top_of_alpha(); } + handle_material->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA); materials[p_name] = Vector<Ref<StandardMaterial3D>>(); materials[p_name].push_back(handle_material); @@ -6538,9 +7419,9 @@ Ref<StandardMaterial3D> EditorNode3DGizmoPlugin::get_material(const String &p_na return mat; } -String EditorNode3DGizmoPlugin::get_name() const { - if (get_script_instance() && get_script_instance()->has_method("get_name")) { - return get_script_instance()->call("get_name"); +String EditorNode3DGizmoPlugin::get_gizmo_name() const { + if (get_script_instance() && get_script_instance()->has_method("get_gizmo_name")) { + return get_script_instance()->call("get_gizmo_name"); } return TTR("Nameless gizmo"); } @@ -6579,13 +7460,13 @@ void EditorNode3DGizmoPlugin::_bind_methods() { ClassDB::bind_method(D_METHOD("create_material", "name", "color", "billboard", "on_top", "use_vertex_color"), &EditorNode3DGizmoPlugin::create_material, DEFVAL(false), DEFVAL(false), DEFVAL(false)); ClassDB::bind_method(D_METHOD("create_icon_material", "name", "texture", "on_top", "color"), &EditorNode3DGizmoPlugin::create_icon_material, DEFVAL(false), DEFVAL(Color(1, 1, 1, 1))); - ClassDB::bind_method(D_METHOD("create_handle_material", "name", "billboard"), &EditorNode3DGizmoPlugin::create_handle_material, DEFVAL(false)); + ClassDB::bind_method(D_METHOD("create_handle_material", "name", "billboard", "texture"), &EditorNode3DGizmoPlugin::create_handle_material, DEFVAL(false), DEFVAL(Variant())); ClassDB::bind_method(D_METHOD("add_material", "name", "material"), &EditorNode3DGizmoPlugin::add_material); - ClassDB::bind_method(D_METHOD("get_material", "name", "gizmo"), &EditorNode3DGizmoPlugin::get_material); //, DEFVAL(Ref<EditorNode3DGizmo>())); + ClassDB::bind_method(D_METHOD("get_material", "name", "gizmo"), &EditorNode3DGizmoPlugin::get_material, DEFVAL(Ref<EditorNode3DGizmo>())); BIND_VMETHOD(MethodInfo(Variant::STRING, "get_name")); - BIND_VMETHOD(MethodInfo(Variant::STRING, "get_priority")); + BIND_VMETHOD(MethodInfo(Variant::INT, "get_priority")); BIND_VMETHOD(MethodInfo(Variant::BOOL, "can_be_hidden")); BIND_VMETHOD(MethodInfo(Variant::BOOL, "is_selectable_when_hidden")); diff --git a/editor/plugins/node_3d_editor_plugin.h b/editor/plugins/node_3d_editor_plugin.h index 3d92e7e7e1..cf4aa33257 100644 --- a/editor/plugins/node_3d_editor_plugin.h +++ b/editor/plugins/node_3d_editor_plugin.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -28,8 +28,8 @@ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ -#ifndef SPATIAL_EDITOR_PLUGIN_H -#define SPATIAL_EDITOR_PLUGIN_H +#ifndef NODE_3D_EDITOR_PLUGIN_H +#define NODE_3D_EDITOR_PLUGIN_H #include "editor/editor_node.h" #include "editor/editor_plugin.h" @@ -37,7 +37,10 @@ #include "scene/3d/immediate_geometry_3d.h" #include "scene/3d/light_3d.h" #include "scene/3d/visual_instance_3d.h" +#include "scene/3d/world_environment.h" #include "scene/gui/panel_container.h" +#include "scene/resources/environment.h" +#include "scene/resources/sky_material.h" class Camera3D; class Node3DEditor; @@ -61,16 +64,10 @@ public: Ref<Material> material; Ref<SkinReference> skin_reference; RID skeleton; - bool billboard; - bool unscaled; - bool can_intersect; - bool extra_margin; - Instance() { - billboard = false; - unscaled = false; - can_intersect = false; - extra_margin = false; - } + bool billboard = false; + bool unscaled = false; + bool can_intersect = false; + bool extra_margin = false; void create_instance(Node3D *p_base, bool p_hidden = false); }; @@ -80,7 +77,7 @@ public: struct Handle { Vector3 pos; - bool billboard; + bool billboard = false; }; Vector<Vector3> handles; @@ -122,11 +119,11 @@ public: bool intersect_frustum(const Camera3D *p_camera, const Vector<Plane> &p_frustum); bool intersect_ray(Camera3D *p_camera, const Point2 &p_point, Vector3 &r_pos, Vector3 &r_normal, int *r_gizmo_handle = nullptr, bool p_sec_first = false); - virtual void clear(); - virtual void create(); - virtual void transform(); - virtual void redraw(); - virtual void free(); + virtual void clear() override; + virtual void create() override; + virtual void transform() override; + virtual void redraw() override; + virtual void free() override; virtual bool is_editable() const; @@ -180,7 +177,6 @@ class Node3DEditorViewport : public Control { friend class Node3DEditor; friend class ViewportRotationControl; enum { - VIEW_TOP, VIEW_BOTTOM, VIEW_LEFT, @@ -214,9 +210,17 @@ class Node3DEditorViewport : public Control { VIEW_DISPLAY_DEBUG_GIPROBE_EMISSION, VIEW_DISPLAY_DEBUG_SCENE_LUMINANCE, VIEW_DISPLAY_DEBUG_SSAO, - VIEW_DISPLAY_DEBUG_ROUGHNESS_LIMITER, VIEW_DISPLAY_DEBUG_PSSM_SPLITS, VIEW_DISPLAY_DEBUG_DECAL_ATLAS, + VIEW_DISPLAY_DEBUG_SDFGI, + VIEW_DISPLAY_DEBUG_SDFGI_PROBES, + VIEW_DISPLAY_DEBUG_GI_BUFFER, + VIEW_DISPLAY_DEBUG_DISABLE_LOD, + VIEW_DISPLAY_DEBUG_CLUSTER_OMNI_LIGHTS, + VIEW_DISPLAY_DEBUG_CLUSTER_SPOT_LIGHTS, + VIEW_DISPLAY_DEBUG_CLUSTER_DECALS, + VIEW_DISPLAY_DEBUG_CLUSTER_REFLECTION_PROBES, + VIEW_LOCK_ROTATION, VIEW_CINEMATIC_PREVIEW, VIEW_AUTO_ORTHOGONAL, @@ -228,6 +232,7 @@ public: GIZMO_BASE_LAYER = 27, GIZMO_EDIT_LAYER = 26, GIZMO_GRID_LAYER = 25, + MISC_TOOL_LAYER = 24, FRAME_TIME_HISTORY = 20, }; @@ -284,20 +289,23 @@ private: bool freelook_active; real_t freelook_speed; + Vector2 previous_mouse_position; - TextureRect *crosshair; Label *info_label; Label *cinema_label; Label *locked_label; VBoxContainer *top_right_vbox; ViewportRotationControl *rotation_control; + Gradient *frame_time_gradient; + Label *cpu_time_label; + Label *gpu_time_label; Label *fps_label; struct _RayResult { - Node3D *item; - float depth; - int handle; + Node3D *item = nullptr; + float depth = 0; + int handle = 0; _FORCE_INLINE_ bool operator<(const _RayResult &p_rr) const { return depth < p_rr.depth; } }; @@ -374,11 +382,11 @@ private: Vector3 click_ray_pos; Vector3 center; Vector3 orig_gizmo_pos; - int edited_gizmo; + int edited_gizmo = 0; Point2 mouse_pos; - bool snap; + bool snap = false; Ref<EditorNode3DGizmo> gizmo; - int gizmo_handle; + int gizmo_handle = 0; Variant gizmo_initial_value; Vector3 gizmo_initial_pos; } _edit; @@ -391,7 +399,9 @@ private: Point2 region_begin, region_end; Cursor() { - x_rot = y_rot = 0.5; + // These rotations place the camera in +X +Y +Z, aka south east, facing north west. + x_rot = 0.5; + y_rot = -0.5; distance = 4; region_select = false; } @@ -408,7 +418,7 @@ private: real_t zoom_indicator_delay; - RID move_gizmo_instance[3], move_plane_gizmo_instance[3], rotate_gizmo_instance[3], scale_gizmo_instance[3], scale_plane_gizmo_instance[3]; + RID move_gizmo_instance[3], move_plane_gizmo_instance[3], rotate_gizmo_instance[4], scale_gizmo_instance[3], scale_plane_gizmo_instance[3]; String last_message; String message; @@ -446,7 +456,7 @@ private: Point2i _get_warped_mouse_motion(const Ref<InputEventMouseMotion> &p_ev_mouse_motion) const; Vector3 _get_instance_position(const Point2 &p_pos) const; - static AABB _calculate_spatial_bounds(const Node3D *p_parent, bool p_exclude_toplevel_transform = true); + static AABB _calculate_spatial_bounds(const Node3D *p_parent, bool p_exclude_top_level_transform = true); void _create_preview(const Vector<String> &files) const; void _remove_preview(); bool _cyclical_dependency_exists(const String &p_target_scene_path, Node *p_desired_node); @@ -456,6 +466,8 @@ private: bool can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const; void drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from); + void _project_settings_changed(); + protected: void _notification(int p_what); static void _bind_methods(); @@ -481,6 +493,7 @@ public: Camera3D *get_camera() { return camera; } // return the default camera object. Node3DEditorViewport(Node3DEditor *p_spatial_editor, EditorNode *p_editor, int p_index); + ~Node3DEditorViewport(); }; class Node3DEditorSelectedItem : public Object { @@ -494,6 +507,7 @@ public: bool last_xform_dirty; Node3D *sp; RID sbox_instance; + RID sbox_instance_xray; Node3DEditorSelectedItem() { sp = nullptr; @@ -549,7 +563,6 @@ public: static const unsigned int VIEWPORTS_COUNT = 4; enum ToolMode { - TOOL_MODE_SELECT, TOOL_MODE_MOVE, TOOL_MODE_ROTATE, @@ -563,7 +576,6 @@ public: }; enum ToolOptions { - TOOL_OPT_LOCAL_COORDS, TOOL_OPT_USE_SNAP, TOOL_OPT_OVERRIDE_CAMERA, @@ -583,7 +595,6 @@ private: ///// ToolMode tool_mode; - bool orthogonal; RenderingServer::ScenarioDebugMode scenario_debug; @@ -596,23 +607,27 @@ private: bool grid_enable[3]; //should be always visible if true bool grid_enabled; - Ref<ArrayMesh> move_gizmo[3], move_plane_gizmo[3], rotate_gizmo[3], scale_gizmo[3], scale_plane_gizmo[3]; + Ref<ArrayMesh> move_gizmo[3], move_plane_gizmo[3], rotate_gizmo[4], scale_gizmo[3], scale_plane_gizmo[3]; Ref<StandardMaterial3D> gizmo_color[3]; Ref<StandardMaterial3D> plane_gizmo_color[3]; + Ref<ShaderMaterial> rotate_gizmo_color[3]; Ref<StandardMaterial3D> gizmo_color_hl[3]; Ref<StandardMaterial3D> plane_gizmo_color_hl[3]; + Ref<ShaderMaterial> rotate_gizmo_color_hl[3]; int over_gizmo_handle; float snap_translate_value; float snap_rotate_value; float snap_scale_value; + Ref<ArrayMesh> selection_box_xray; Ref<ArrayMesh> selection_box; RID indicators; RID indicators_instance; RID cursor_mesh; RID cursor_instance; Ref<StandardMaterial3D> indicator_mat; + Ref<ShaderMaterial> grid_mat[3]; Ref<StandardMaterial3D> cursor_material; // Scene drag and drop support @@ -620,13 +635,12 @@ private: AABB preview_bounds; struct Gizmo { - bool visible; - float scale; + bool visible = false; + float scale = 0; Transform transform; } gizmo; enum MenuOption { - MENU_TOOL_SELECT, MENU_TOOL_MOVE, MENU_TOOL_ROTATE, @@ -695,7 +709,7 @@ private: HBoxContainer *hbc_menu; - void _generate_selection_box(); + void _generate_selection_boxes(); UndoRedo *undo_redo; int camera_override_viewport_id; @@ -721,6 +735,7 @@ private: static Node3DEditor *singleton; + void _node_added(Node *p_node); void _node_removed(Node *p_node); Vector<Ref<EditorNode3DGizmoPlugin>> gizmo_plugins_by_priority; Vector<Ref<EditorNode3DGizmoPlugin>> gizmo_plugins_by_name; @@ -733,6 +748,61 @@ private: void _refresh_menu_icons(); + // Preview Sun and Environment + + uint32_t world_env_count = 0; + uint32_t directional_light_count = 0; + + Button *sun_button; + Label *sun_state; + Label *sun_title; + VBoxContainer *sun_vb; + Popup *sun_environ_popup; + Control *sun_direction; + ColorPickerButton *sun_color; + EditorSpinSlider *sun_energy; + EditorSpinSlider *sun_max_distance; + Button *sun_add_to_scene; + + void _sun_direction_draw(); + void _sun_direction_input(const Ref<InputEvent> &p_event); + + Basis sun_rotation; + + Ref<Shader> sun_direction_shader; + Ref<ShaderMaterial> sun_direction_material; + + Button *environ_button; + Label *environ_state; + Label *environ_title; + VBoxContainer *environ_vb; + ColorPickerButton *environ_sky_color; + ColorPickerButton *environ_ground_color; + EditorSpinSlider *environ_energy; + Button *environ_ao_button; + Button *environ_glow_button; + Button *environ_tonemap_button; + Button *environ_gi_button; + Button *environ_add_to_scene; + + Button *sun_environ_settings; + + DirectionalLight3D *preview_sun; + WorldEnvironment *preview_environment; + Ref<Environment> environment; + Ref<ProceduralSkyMaterial> sky_material; + + bool sun_environ_updating = false; + + void _load_default_preview_settings(); + void _update_preview_environment(); + + void _preview_settings_changed(); + void _sun_environ_settings_pressed(); + + void _add_sun_to_scene(); + void _add_environment_to_scene(); + protected: void _notification(int p_what); //void _gui_input(InputEvent p_event); @@ -766,6 +836,7 @@ public: Ref<ArrayMesh> get_scale_gizmo(int idx) const { return scale_gizmo[idx]; } Ref<ArrayMesh> get_scale_plane_gizmo(int idx) const { return scale_plane_gizmo[idx]; } + void update_grid(); void update_transform_gizmo(); void update_all_gizmos(Node *p_node = nullptr); void snap_selected_nodes_to_floor(); @@ -821,17 +892,17 @@ public: void snap_cursor_to_plane(const Plane &p_plane); Node3DEditor *get_spatial_editor() { return spatial_editor; } - virtual String get_name() const { return "3D"; } - bool has_main_screen() const { return true; } - virtual void make_visible(bool p_visible); - virtual void edit(Object *p_object); - virtual bool handles(Object *p_object) const; + virtual String get_name() const override { return "3D"; } + bool has_main_screen() const override { return true; } + virtual void make_visible(bool p_visible) override; + virtual void edit(Object *p_object) override; + virtual bool handles(Object *p_object) const override; - virtual Dictionary get_state() const; - virtual void set_state(const Dictionary &p_state); - virtual void clear() { spatial_editor->clear(); } + virtual Dictionary get_state() const override; + virtual void set_state(const Dictionary &p_state) override; + virtual void clear() override { spatial_editor->clear(); } - virtual void edited_scene_changed(); + virtual void edited_scene_changed() override; Node3DEditorPlugin(EditorNode *p_node); ~Node3DEditorPlugin(); @@ -857,12 +928,12 @@ protected: public: void create_material(const String &p_name, const Color &p_color, bool p_billboard = false, bool p_on_top = false, bool p_use_vertex_color = false); void create_icon_material(const String &p_name, const Ref<Texture2D> &p_texture, bool p_on_top = false, const Color &p_albedo = Color(1, 1, 1, 1)); - void create_handle_material(const String &p_name, bool p_billboard = false); + void create_handle_material(const String &p_name, bool p_billboard = false, const Ref<Texture2D> &p_texture = nullptr); void add_material(const String &p_name, Ref<StandardMaterial3D> p_material); Ref<StandardMaterial3D> get_material(const String &p_name, const Ref<EditorNode3DGizmo> &p_gizmo = Ref<EditorNode3DGizmo>()); - virtual String get_name() const; + virtual String get_gizmo_name() const; virtual int get_priority() const; virtual bool can_be_hidden() const; virtual bool is_selectable_when_hidden() const; @@ -883,4 +954,4 @@ public: virtual ~EditorNode3DGizmoPlugin(); }; -#endif +#endif // NODE_3D_EDITOR_PLUGIN_H diff --git a/editor/plugins/ot_features_plugin.cpp b/editor/plugins/ot_features_plugin.cpp new file mode 100644 index 0000000000..ebfdf2c7cd --- /dev/null +++ b/editor/plugins/ot_features_plugin.cpp @@ -0,0 +1,213 @@ +/*************************************************************************/ +/* ot_features_plugin.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 "ot_features_plugin.h" + +#include "editor/editor_scale.h" + +void OpenTypeFeaturesEditor::_value_changed(double val) { + if (setting) { + return; + } + + emit_changed(get_edited_property(), spin->get_value()); +} + +void OpenTypeFeaturesEditor::update_property() { + double val = get_edited_object()->get(get_edited_property()); + setting = true; + spin->set_value(val); + setting = false; +} + +void OpenTypeFeaturesEditor::_notification(int p_what) { + if (p_what == NOTIFICATION_ENTER_TREE || p_what == NOTIFICATION_THEME_CHANGED) { + Color base = get_theme_color("accent_color", "Editor"); + + button->set_icon(get_theme_icon("Remove", "EditorIcons")); + button->set_size(get_theme_icon("Remove", "EditorIcons")->get_size()); + spin->set_custom_label_color(true, base); + } +} + +void OpenTypeFeaturesEditor::_remove_feature() { + get_edited_object()->set(get_edited_property(), -1); +} + +void OpenTypeFeaturesEditor::_bind_methods() { +} + +OpenTypeFeaturesEditor::OpenTypeFeaturesEditor() { + HBoxContainer *bc = memnew(HBoxContainer); + add_child(bc); + + spin = memnew(EditorSpinSlider); + spin->set_flat(true); + bc->add_child(spin); + add_focusable(spin); + spin->connect("value_changed", callable_mp(this, &OpenTypeFeaturesEditor::_value_changed)); + spin->set_h_size_flags(SIZE_EXPAND_FILL); + + spin->set_min(0); + spin->set_max(65536); + spin->set_step(1); + spin->set_hide_slider(false); + spin->set_allow_greater(false); + spin->set_allow_lesser(false); + + button = memnew(Button); + button->set_tooltip(RTR("Remove feature")); + button->set_flat(true); + bc->add_child(button); + + button->connect("pressed", callable_mp(this, &OpenTypeFeaturesEditor::_remove_feature)); + + setting = false; +} + +/*************************************************************************/ + +void OpenTypeFeaturesAdd::_add_feature(int p_option) { + get_edited_object()->set("opentype_features/" + TS->tag_to_name(p_option), 1); +} + +void OpenTypeFeaturesAdd::update_property() { + menu->clear(); + menu_ss->clear(); + menu_cv->clear(); + menu_cu->clear(); + bool have_ss = false; + bool have_cv = false; + bool have_cu = false; + Dictionary features = Object::cast_to<Control>(get_edited_object())->get_theme_font("font")->get_feature_list(); + for (const Variant *ftr = features.next(nullptr); ftr != nullptr; ftr = features.next(ftr)) { + String ftr_name = TS->tag_to_name(*ftr); + if (ftr_name.begins_with("stylistic_set_")) { + menu_ss->add_item(ftr_name.capitalize(), (int32_t)*ftr); + have_ss = true; + } else if (ftr_name.begins_with("character_variant_")) { + menu_cv->add_item(ftr_name.capitalize(), (int32_t)*ftr); + have_cv = true; + } else if (ftr_name.begins_with("custom_")) { + menu_cu->add_item(ftr_name.replace("custom_", ""), (int32_t)*ftr); + have_cu = true; + } else { + menu->add_item(ftr_name.capitalize(), (int32_t)*ftr); + } + } + if (have_ss) { + menu->add_submenu_item(RTR("Stylistic Sets"), "SSMenu"); + } + if (have_cv) { + menu->add_submenu_item(RTR("Character Variants"), "CVMenu"); + } + if (have_cu) { + menu->add_submenu_item(RTR("Custom"), "CUMenu"); + } +} + +void OpenTypeFeaturesAdd::_features_menu() { + Size2 size = get_size(); + menu->set_position(get_screen_position() + Size2(0, size.height * get_global_transform().get_scale().y)); + menu->popup(); +} + +void OpenTypeFeaturesAdd::_notification(int p_what) { + if (p_what == NOTIFICATION_THEME_CHANGED || p_what == NOTIFICATION_ENTER_TREE) { + set_label(""); + button->set_icon(get_theme_icon("Add", "EditorIcons")); + button->set_size(get_theme_icon("Add", "EditorIcons")->get_size()); + } +} + +void OpenTypeFeaturesAdd::_bind_methods() { +} + +OpenTypeFeaturesAdd::OpenTypeFeaturesAdd() { + menu = memnew(PopupMenu); + add_child(menu); + + menu_cv = memnew(PopupMenu); + menu_cv->set_name("CVMenu"); + menu->add_child(menu_cv); + + menu_ss = memnew(PopupMenu); + menu_ss->set_name("SSMenu"); + menu->add_child(menu_ss); + + menu_cu = memnew(PopupMenu); + menu_cu->set_name("CUMenu"); + menu->add_child(menu_cu); + + button = memnew(Button); + button->set_flat(true); + button->set_text(RTR("Add feature...")); + button->set_tooltip(RTR("Add feature...")); + add_child(button); + + button->connect("pressed", callable_mp(this, &OpenTypeFeaturesAdd::_features_menu)); + menu->connect("id_pressed", callable_mp(this, &OpenTypeFeaturesAdd::_add_feature)); + menu_cv->connect("id_pressed", callable_mp(this, &OpenTypeFeaturesAdd::_add_feature)); + menu_ss->connect("id_pressed", callable_mp(this, &OpenTypeFeaturesAdd::_add_feature)); + menu_cu->connect("id_pressed", callable_mp(this, &OpenTypeFeaturesAdd::_add_feature)); +} + +/*************************************************************************/ + +bool EditorInspectorPluginOpenTypeFeatures::can_handle(Object *p_object) { + return (Object::cast_to<Control>(p_object) != nullptr); +} + +void EditorInspectorPluginOpenTypeFeatures::parse_begin(Object *p_object) { +} + +void EditorInspectorPluginOpenTypeFeatures::parse_category(Object *p_object, const String &p_parse_category) { +} + +bool EditorInspectorPluginOpenTypeFeatures::parse_property(Object *p_object, Variant::Type p_type, const String &p_path, PropertyHint p_hint, const String &p_hint_text, int p_usage, bool p_wide) { + if (p_path == "opentype_features/_new") { + OpenTypeFeaturesAdd *editor = memnew(OpenTypeFeaturesAdd); + add_property_editor(p_path, editor); + return true; + } else if (p_path.begins_with("opentype_features")) { + OpenTypeFeaturesEditor *editor = memnew(OpenTypeFeaturesEditor); + add_property_editor(p_path, editor); + return true; + } + return false; +} + +/*************************************************************************/ + +OpenTypeFeaturesEditorPlugin::OpenTypeFeaturesEditorPlugin(EditorNode *p_node) { + Ref<EditorInspectorPluginOpenTypeFeatures> ftr_plugin; + ftr_plugin.instance(); + EditorInspector::add_inspector_plugin(ftr_plugin); +} diff --git a/editor/plugins/ot_features_plugin.h b/editor/plugins/ot_features_plugin.h new file mode 100644 index 0000000000..9559a6c0c3 --- /dev/null +++ b/editor/plugins/ot_features_plugin.h @@ -0,0 +1,105 @@ +/*************************************************************************/ +/* ot_features_plugin.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 OT_FEATURES_PLUGIN_H +#define OT_FEATURES_PLUGIN_H + +#include "editor/editor_node.h" +#include "editor/editor_plugin.h" +#include "editor/editor_properties.h" + +/*************************************************************************/ + +class OpenTypeFeaturesEditor : public EditorProperty { + GDCLASS(OpenTypeFeaturesEditor, EditorProperty); + EditorSpinSlider *spin; + bool setting = true; + void _value_changed(double p_val); + Button *button = nullptr; + + void _remove_feature(); + +protected: + void _notification(int p_what); + static void _bind_methods(); + +public: + virtual void update_property() override; + OpenTypeFeaturesEditor(); +}; + +/*************************************************************************/ + +class OpenTypeFeaturesAdd : public EditorProperty { + GDCLASS(OpenTypeFeaturesAdd, EditorProperty); + + Button *button = nullptr; + PopupMenu *menu = nullptr; + PopupMenu *menu_ss = nullptr; + PopupMenu *menu_cv = nullptr; + PopupMenu *menu_cu = nullptr; + + void _add_feature(int p_option); + void _features_menu(); + +protected: + void _notification(int p_what); + static void _bind_methods(); + +public: + virtual void update_property() override; + + OpenTypeFeaturesAdd(); +}; + +/*************************************************************************/ + +class EditorInspectorPluginOpenTypeFeatures : public EditorInspectorPlugin { + GDCLASS(EditorInspectorPluginOpenTypeFeatures, EditorInspectorPlugin); + +public: + virtual bool can_handle(Object *p_object) override; + virtual void parse_begin(Object *p_object) override; + virtual void parse_category(Object *p_object, const String &p_parse_category) override; + virtual bool parse_property(Object *p_object, Variant::Type p_type, const String &p_path, PropertyHint p_hint, const String &p_hint_text, int p_usage, bool p_wide) override; +}; + +/*************************************************************************/ + +class OpenTypeFeaturesEditorPlugin : public EditorPlugin { + GDCLASS(OpenTypeFeaturesEditorPlugin, EditorPlugin); + +public: + OpenTypeFeaturesEditorPlugin(EditorNode *p_node); + + virtual String get_name() const override { return "OpenTypeFeatures"; } +}; + +#endif // OT_FEATURES_PLUGIN_H diff --git a/editor/plugins/packed_scene_translation_parser_plugin.cpp b/editor/plugins/packed_scene_translation_parser_plugin.cpp new file mode 100644 index 0000000000..0a949c8610 --- /dev/null +++ b/editor/plugins/packed_scene_translation_parser_plugin.cpp @@ -0,0 +1,116 @@ +/*************************************************************************/ +/* packed_scene_translation_parser_plugin.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 "packed_scene_translation_parser_plugin.h" + +#include "core/io/resource_loader.h" +#include "scene/resources/packed_scene.h" + +void PackedSceneEditorTranslationParserPlugin::get_recognized_extensions(List<String> *r_extensions) const { + ResourceLoader::get_recognized_extensions_for_type("PackedScene", r_extensions); +} + +Error PackedSceneEditorTranslationParserPlugin::parse_file(const String &p_path, Vector<String> *r_ids, Vector<Vector<String>> *r_ids_ctx_plural) { + // Parse specific scene Node's properties (see in constructor) that are auto-translated by the engine when set. E.g Label's text property. + // These properties are translated with the tr() function in the C++ code when being set or updated. + + Error err; + RES loaded_res = ResourceLoader::load(p_path, "PackedScene", ResourceFormatLoader::CACHE_MODE_REUSE, &err); + if (err) { + ERR_PRINT("Failed to load " + p_path); + return err; + } + Ref<SceneState> state = Ref<PackedScene>(loaded_res)->get_state(); + + Vector<String> parsed_strings; + String property_name; + Variant property_value; + for (int i = 0; i < state->get_node_count(); i++) { + if (!ClassDB::is_parent_class(state->get_node_type(i), "Control") && !ClassDB::is_parent_class(state->get_node_type(i), "Viewport")) { + continue; + } + + for (int j = 0; j < state->get_node_property_count(i); j++) { + property_name = state->get_node_property_name(i, j); + if (!lookup_properties.has(property_name)) { + continue; + } + + property_value = state->get_node_property_value(i, j); + + if (property_name == "script" && property_value.get_type() == Variant::OBJECT && !property_value.is_null()) { + // Parse built-in script. + Ref<Script> s = Object::cast_to<Script>(property_value); + String extension = s->get_language()->get_extension(); + if (EditorTranslationParser::get_singleton()->can_parse(extension)) { + Vector<String> temp; + Vector<Vector<String>> ids_context_plural; + EditorTranslationParser::get_singleton()->get_parser(extension)->parse_file(s->get_path(), &temp, &ids_context_plural); + parsed_strings.append_array(temp); + r_ids_ctx_plural->append_array(ids_context_plural); + } + } else if (property_name == "filters") { + // Extract FileDialog's filters property with values in format "*.png ; PNG Images","*.gd ; GDScript Files". + Vector<String> str_values = property_value; + for (int k = 0; k < str_values.size(); k++) { + String desc = str_values[k].get_slice(";", 1).strip_edges(); + if (!desc.is_empty()) { + parsed_strings.push_back(desc); + } + } + } else if (property_value.get_type() == Variant::STRING) { + String str_value = String(property_value); + // Prevent reading text containing only spaces. + if (!str_value.strip_edges().is_empty()) { + parsed_strings.push_back(str_value); + } + } + } + } + + r_ids->append_array(parsed_strings); + + return OK; +} + +PackedSceneEditorTranslationParserPlugin::PackedSceneEditorTranslationParserPlugin() { + // Scene Node's properties containing strings that will be fetched for translation. + lookup_properties.insert("text"); + lookup_properties.insert("hint_tooltip"); + lookup_properties.insert("placeholder_text"); + lookup_properties.insert("dialog_text"); + lookup_properties.insert("filters"); + lookup_properties.insert("script"); + + //Add exception list (to prevent false positives) + //line edit, text edit, richtextlabel + //Set<String> exception_list; + //exception_list.insert("RichTextLabel"); +} diff --git a/editor/plugins/packed_scene_translation_parser_plugin.h b/editor/plugins/packed_scene_translation_parser_plugin.h new file mode 100644 index 0000000000..e51d65414e --- /dev/null +++ b/editor/plugins/packed_scene_translation_parser_plugin.h @@ -0,0 +1,49 @@ +/*************************************************************************/ +/* packed_scene_translation_parser_plugin.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 PACKED_SCENE_TRANSLATION_PARSER_PLUGIN_H +#define PACKED_SCENE_TRANSLATION_PARSER_PLUGIN_H + +#include "editor/editor_translation_parser.h" + +class PackedSceneEditorTranslationParserPlugin : public EditorTranslationParserPlugin { + GDCLASS(PackedSceneEditorTranslationParserPlugin, EditorTranslationParserPlugin); + + // Scene Node's properties that contain translation strings. + Set<String> lookup_properties; + +public: + virtual Error parse_file(const String &p_path, Vector<String> *r_ids, Vector<Vector<String>> *r_ids_ctx_plural) override; + virtual void get_recognized_extensions(List<String> *r_extensions) const override; + + PackedSceneEditorTranslationParserPlugin(); +}; + +#endif // PACKED_SCENE_TRANSLATION_PARSER_PLUGIN_H diff --git a/editor/plugins/path_2d_editor_plugin.cpp b/editor/plugins/path_2d_editor_plugin.cpp index a3dab665b8..908235f89f 100644 --- a/editor/plugins/path_2d_editor_plugin.cpp +++ b/editor/plugins/path_2d_editor_plugin.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -532,35 +532,40 @@ Path2DEditor::Path2DEditor(EditorNode *p_editor) { sep = memnew(VSeparator); base_hb->add_child(sep); - curve_edit = memnew(ToolButton); + curve_edit = memnew(Button); + curve_edit->set_flat(true); curve_edit->set_icon(EditorNode::get_singleton()->get_gui_base()->get_theme_icon("CurveEdit", "EditorIcons")); curve_edit->set_toggle_mode(true); curve_edit->set_focus_mode(Control::FOCUS_NONE); curve_edit->set_tooltip(TTR("Select Points") + "\n" + TTR("Shift+Drag: Select Control Points") + "\n" + keycode_get_string(KEY_MASK_CMD) + TTR("Click: Add Point") + "\n" + TTR("Left Click: Split Segment (in curve)") + "\n" + TTR("Right Click: Delete Point")); curve_edit->connect("pressed", callable_mp(this, &Path2DEditor::_mode_selected), varray(MODE_EDIT)); base_hb->add_child(curve_edit); - curve_edit_curve = memnew(ToolButton); + curve_edit_curve = memnew(Button); + curve_edit_curve->set_flat(true); curve_edit_curve->set_icon(EditorNode::get_singleton()->get_gui_base()->get_theme_icon("CurveCurve", "EditorIcons")); curve_edit_curve->set_toggle_mode(true); curve_edit_curve->set_focus_mode(Control::FOCUS_NONE); curve_edit_curve->set_tooltip(TTR("Select Control Points (Shift+Drag)")); curve_edit_curve->connect("pressed", callable_mp(this, &Path2DEditor::_mode_selected), varray(MODE_EDIT_CURVE)); base_hb->add_child(curve_edit_curve); - curve_create = memnew(ToolButton); + curve_create = memnew(Button); + curve_create->set_flat(true); curve_create->set_icon(EditorNode::get_singleton()->get_gui_base()->get_theme_icon("CurveCreate", "EditorIcons")); curve_create->set_toggle_mode(true); curve_create->set_focus_mode(Control::FOCUS_NONE); curve_create->set_tooltip(TTR("Add Point (in empty space)")); curve_create->connect("pressed", callable_mp(this, &Path2DEditor::_mode_selected), varray(MODE_CREATE)); base_hb->add_child(curve_create); - curve_del = memnew(ToolButton); + curve_del = memnew(Button); + curve_del->set_flat(true); curve_del->set_icon(EditorNode::get_singleton()->get_gui_base()->get_theme_icon("CurveDelete", "EditorIcons")); curve_del->set_toggle_mode(true); curve_del->set_focus_mode(Control::FOCUS_NONE); curve_del->set_tooltip(TTR("Delete Point")); curve_del->connect("pressed", callable_mp(this, &Path2DEditor::_mode_selected), varray(MODE_DELETE)); base_hb->add_child(curve_del); - curve_close = memnew(ToolButton); + curve_close = memnew(Button); + curve_close->set_flat(true); curve_close->set_icon(EditorNode::get_singleton()->get_gui_base()->get_theme_icon("CurveClose", "EditorIcons")); curve_close->set_focus_mode(Control::FOCUS_NONE); curve_close->set_tooltip(TTR("Close Curve")); diff --git a/editor/plugins/path_2d_editor_plugin.h b/editor/plugins/path_2d_editor_plugin.h index 390dfdfdf7..867e0ce74f 100644 --- a/editor/plugins/path_2d_editor_plugin.h +++ b/editor/plugins/path_2d_editor_plugin.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -34,7 +34,6 @@ #include "editor/editor_node.h" #include "editor/editor_plugin.h" #include "scene/2d/path_2d.h" -#include "scene/gui/tool_button.h" class CanvasItemEditor; @@ -60,11 +59,11 @@ class Path2DEditor : public HBoxContainer { }; Mode mode; - ToolButton *curve_create; - ToolButton *curve_edit; - ToolButton *curve_edit_curve; - ToolButton *curve_del; - ToolButton *curve_close; + Button *curve_create; + Button *curve_edit; + Button *curve_edit_curve; + Button *curve_del; + Button *curve_close; MenuButton *handle_menu; bool mirror_handle_angle; @@ -77,7 +76,6 @@ class Path2DEditor : public HBoxContainer { }; enum Action { - ACTION_NONE, ACTION_MOVING_POINT, ACTION_MOVING_IN, @@ -117,14 +115,14 @@ class Path2DEditorPlugin : public EditorPlugin { EditorNode *editor; public: - virtual bool forward_canvas_gui_input(const Ref<InputEvent> &p_event) { return path2d_editor->forward_gui_input(p_event); } - virtual void forward_canvas_draw_over_viewport(Control *p_overlay) { path2d_editor->forward_canvas_draw_over_viewport(p_overlay); } - - virtual String get_name() const { return "Path2D"; } - bool has_main_screen() const { return false; } - virtual void edit(Object *p_object); - virtual bool handles(Object *p_object) const; - virtual void make_visible(bool p_visible); + virtual bool forward_canvas_gui_input(const Ref<InputEvent> &p_event) override { return path2d_editor->forward_gui_input(p_event); } + virtual void forward_canvas_draw_over_viewport(Control *p_overlay) override { path2d_editor->forward_canvas_draw_over_viewport(p_overlay); } + + virtual String get_name() const override { return "Path2D"; } + bool has_main_screen() const override { return false; } + virtual void edit(Object *p_object) override; + virtual bool handles(Object *p_object) const override; + virtual void make_visible(bool p_visible) override; Path2DEditorPlugin(EditorNode *p_node); ~Path2DEditorPlugin(); diff --git a/editor/plugins/path_3d_editor_plugin.cpp b/editor/plugins/path_3d_editor_plugin.cpp index a44fe69ff6..3783af8fc6 100644 --- a/editor/plugins/path_3d_editor_plugin.cpp +++ b/editor/plugins/path_3d_editor_plugin.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -30,6 +30,8 @@ #include "path_3d_editor_plugin.h" +#include "core/math/geometry_2d.h" +#include "core/math/geometry_3d.h" #include "core/os/keyboard.h" #include "node_3d_editor_plugin.h" #include "scene/resources/curve.h" @@ -222,6 +224,7 @@ void Path3DGizmo::redraw() { Ref<StandardMaterial3D> path_material = gizmo_plugin->get_material("path_material", this); Ref<StandardMaterial3D> path_thin_material = gizmo_plugin->get_material("path_thin_material", this); Ref<StandardMaterial3D> handles_material = gizmo_plugin->get_material("handles"); + Ref<StandardMaterial3D> sec_handles_material = gizmo_plugin->get_material("sec_handles"); Ref<Curve3D> c = path->get_curve(); if (c.is_null()) { @@ -279,7 +282,7 @@ void Path3DGizmo::redraw() { add_handles(handles, handles_material); } if (sec_handles.size()) { - add_handles(sec_handles, handles_material, false, true); + add_handles(sec_handles, sec_handles_material, false, true); } } } @@ -287,6 +290,8 @@ void Path3DGizmo::redraw() { Path3DGizmo::Path3DGizmo(Path3D *p_path) { path = p_path; set_spatial_node(p_path); + orig_in_length = 0; + orig_out_length = 0; } bool Path3DEditorPlugin::forward_spatial_gui_input(Camera3D *p_camera, const Ref<InputEvent> &p_event) { @@ -344,7 +349,7 @@ bool Path3DEditorPlugin::forward_spatial_gui_input(Camera3D *p_camera, const Ref Vector2 s[2]; s[0] = p_camera->unproject_position(from); s[1] = p_camera->unproject_position(to); - Vector2 inters = Geometry::get_closest_point_to_segment_2d(mbpos, s); + Vector2 inters = Geometry2D::get_closest_point_to_segment(mbpos, s); float d = inters.distance_to(mbpos); if (d < 10 && d < closest_d) { @@ -354,7 +359,7 @@ bool Path3DEditorPlugin::forward_spatial_gui_input(Camera3D *p_camera, const Ref Vector3 ray_dir = p_camera->project_ray_normal(mbpos); Vector3 ra, rb; - Geometry::get_closest_points_between_segments(ray_from, ray_from + ray_dir * 4096, from, to, ra, rb); + Geometry3D::get_closest_points_between_segments(ray_from, ray_from + ray_dir * 4096, from, to, ra, rb); closest_seg_point = it.xform(rb); } @@ -555,28 +560,32 @@ Path3DEditorPlugin::Path3DEditorPlugin(EditorNode *p_node) { sep = memnew(VSeparator); sep->hide(); Node3DEditor::get_singleton()->add_control_to_menu_panel(sep); - curve_edit = memnew(ToolButton); + curve_edit = memnew(Button); + curve_edit->set_flat(true); curve_edit->set_icon(EditorNode::get_singleton()->get_gui_base()->get_theme_icon("CurveEdit", "EditorIcons")); curve_edit->set_toggle_mode(true); curve_edit->hide(); curve_edit->set_focus_mode(Control::FOCUS_NONE); curve_edit->set_tooltip(TTR("Select Points") + "\n" + TTR("Shift+Drag: Select Control Points") + "\n" + keycode_get_string(KEY_MASK_CMD) + TTR("Click: Add Point") + "\n" + TTR("Right Click: Delete Point")); Node3DEditor::get_singleton()->add_control_to_menu_panel(curve_edit); - curve_create = memnew(ToolButton); + curve_create = memnew(Button); + curve_create->set_flat(true); curve_create->set_icon(EditorNode::get_singleton()->get_gui_base()->get_theme_icon("CurveCreate", "EditorIcons")); curve_create->set_toggle_mode(true); curve_create->hide(); curve_create->set_focus_mode(Control::FOCUS_NONE); curve_create->set_tooltip(TTR("Add Point (in empty space)") + "\n" + TTR("Split Segment (in curve)")); Node3DEditor::get_singleton()->add_control_to_menu_panel(curve_create); - curve_del = memnew(ToolButton); + curve_del = memnew(Button); + curve_del->set_flat(true); curve_del->set_icon(EditorNode::get_singleton()->get_gui_base()->get_theme_icon("CurveDelete", "EditorIcons")); curve_del->set_toggle_mode(true); curve_del->hide(); curve_del->set_focus_mode(Control::FOCUS_NONE); curve_del->set_tooltip(TTR("Delete Point")); Node3DEditor::get_singleton()->add_control_to_menu_panel(curve_del); - curve_close = memnew(ToolButton); + curve_close = memnew(Button); + curve_close->set_flat(true); curve_close->set_icon(EditorNode::get_singleton()->get_gui_base()->get_theme_icon("CurveClose", "EditorIcons")); curve_close->hide(); curve_close->set_focus_mode(Control::FOCUS_NONE); @@ -600,7 +609,7 @@ Path3DEditorPlugin::Path3DEditorPlugin(EditorNode *p_node) { curve_edit->set_pressed(true); /* collision_polygon_editor = memnew( PathEditor(p_node) ); - editor->get_viewport()->add_child(collision_polygon_editor); + editor->get_main_control()->add_child(collision_polygon_editor); collision_polygon_editor->set_margin(MARGIN_LEFT,200); collision_polygon_editor->set_margin(MARGIN_RIGHT,230); collision_polygon_editor->set_margin(MARGIN_TOP,0); @@ -623,7 +632,7 @@ Ref<EditorNode3DGizmo> Path3DGizmoPlugin::create_gizmo(Node3D *p_spatial) { return ref; } -String Path3DGizmoPlugin::get_name() const { +String Path3DGizmoPlugin::get_gizmo_name() const { return "Path3D"; } @@ -635,5 +644,6 @@ Path3DGizmoPlugin::Path3DGizmoPlugin() { Color path_color = EDITOR_DEF("editors/3d_gizmos/gizmo_colors/path", Color(0.5, 0.5, 1.0, 0.8)); create_material("path_material", path_color); create_material("path_thin_material", Color(0.5, 0.5, 0.5)); - create_handle_material("handles"); + create_handle_material("handles", false, Node3DEditor::get_singleton()->get_theme_icon("EditorPathSmoothHandle", "EditorIcons")); + create_handle_material("sec_handles", false, Node3DEditor::get_singleton()->get_theme_icon("EditorCurveHandle", "EditorIcons")); } diff --git a/editor/plugins/path_3d_editor_plugin.h b/editor/plugins/path_3d_editor_plugin.h index 8bec5df797..13870d7591 100644 --- a/editor/plugins/path_3d_editor_plugin.h +++ b/editor/plugins/path_3d_editor_plugin.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -43,12 +43,12 @@ class Path3DGizmo : public EditorNode3DGizmo { mutable float orig_out_length; public: - virtual String get_handle_name(int p_idx) const; - virtual Variant get_handle_value(int p_idx); - virtual void set_handle(int p_idx, Camera3D *p_camera, const Point2 &p_point); - virtual void commit_handle(int p_idx, const Variant &p_restore, bool p_cancel = false); + virtual String get_handle_name(int p_idx) const override; + virtual Variant get_handle_value(int p_idx) override; + virtual void set_handle(int p_idx, Camera3D *p_camera, const Point2 &p_point) override; + virtual void commit_handle(int p_idx, const Variant &p_restore, bool p_cancel = false) override; - virtual void redraw(); + virtual void redraw() override; Path3DGizmo(Path3D *p_path = nullptr); }; @@ -56,11 +56,11 @@ class Path3DGizmoPlugin : public EditorNode3DGizmoPlugin { GDCLASS(Path3DGizmoPlugin, EditorNode3DGizmoPlugin); protected: - Ref<EditorNode3DGizmo> create_gizmo(Node3D *p_spatial); + Ref<EditorNode3DGizmo> create_gizmo(Node3D *p_spatial) override; public: - String get_name() const; - int get_priority() const; + String get_gizmo_name() const override; + int get_priority() const override; Path3DGizmoPlugin(); }; @@ -68,10 +68,10 @@ class Path3DEditorPlugin : public EditorPlugin { GDCLASS(Path3DEditorPlugin, EditorPlugin); Separator *sep; - ToolButton *curve_create; - ToolButton *curve_edit; - ToolButton *curve_del; - ToolButton *curve_close; + Button *curve_create; + Button *curve_edit; + Button *curve_del; + Button *curve_close; MenuButton *handle_menu; EditorNode *editor; @@ -98,13 +98,13 @@ public: Path3D *get_edited_path() { return path; } static Path3DEditorPlugin *singleton; - virtual bool forward_spatial_gui_input(Camera3D *p_camera, const Ref<InputEvent> &p_event); + virtual bool forward_spatial_gui_input(Camera3D *p_camera, const Ref<InputEvent> &p_event) override; - virtual String get_name() const { return "Path3D"; } - bool has_main_screen() const { return false; } - virtual void edit(Object *p_object); - virtual bool handles(Object *p_object) const; - virtual void make_visible(bool p_visible); + virtual String get_name() const override { return "Path3D"; } + bool has_main_screen() const override { return false; } + virtual void edit(Object *p_object) override; + virtual bool handles(Object *p_object) const override; + virtual void make_visible(bool p_visible) override; bool mirror_angle_enabled() { return mirror_handle_angle; } bool mirror_length_enabled() { return mirror_handle_length; } diff --git a/editor/plugins/physical_bone_3d_editor_plugin.cpp b/editor/plugins/physical_bone_3d_editor_plugin.cpp index bcbf88e7dc..4b52512933 100644 --- a/editor/plugins/physical_bone_3d_editor_plugin.cpp +++ b/editor/plugins/physical_bone_3d_editor_plugin.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -55,7 +55,8 @@ PhysicalBone3DEditor::PhysicalBone3DEditor(EditorNode *p_editor) : spatial_editor_hb->add_child(memnew(VSeparator)); - button_transform_joint = memnew(ToolButton); + button_transform_joint = memnew(Button); + button_transform_joint->set_flat(true); spatial_editor_hb->add_child(button_transform_joint); button_transform_joint->set_text(TTR("Move Joint")); diff --git a/editor/plugins/physical_bone_3d_editor_plugin.h b/editor/plugins/physical_bone_3d_editor_plugin.h index 79c7cc4bb1..248aad9298 100644 --- a/editor/plugins/physical_bone_3d_editor_plugin.h +++ b/editor/plugins/physical_bone_3d_editor_plugin.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -38,7 +38,7 @@ class PhysicalBone3DEditor : public Object { EditorNode *editor; HBoxContainer *spatial_editor_hb; - ToolButton *button_transform_joint; + Button *button_transform_joint; PhysicalBone3D *selected = nullptr; @@ -67,10 +67,10 @@ class PhysicalBone3DEditorPlugin : public EditorPlugin { PhysicalBone3DEditor physical_bone_editor; public: - virtual String get_name() const { return "PhysicalBone3D"; } - virtual bool handles(Object *p_object) const { return p_object->is_class("PhysicalBone3D"); } - virtual void make_visible(bool p_visible); - virtual void edit(Object *p_node); + virtual String get_name() const override { return "PhysicalBone3D"; } + virtual bool handles(Object *p_object) const override { return p_object->is_class("PhysicalBone3D"); } + virtual void make_visible(bool p_visible) override; + virtual void edit(Object *p_node) override; PhysicalBone3DEditorPlugin(EditorNode *p_editor); }; diff --git a/editor/plugins/polygon_2d_editor_plugin.cpp b/editor/plugins/polygon_2d_editor_plugin.cpp index 7ee695b9fe..3d7b01c149 100644 --- a/editor/plugins/polygon_2d_editor_plugin.cpp +++ b/editor/plugins/polygon_2d_editor_plugin.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -32,6 +32,7 @@ #include "canvas_item_editor_plugin.h" #include "core/input/input.h" +#include "core/math/geometry_2d.h" #include "core/os/file_access.h" #include "core/os/keyboard.h" #include "editor/editor_scale.h" @@ -78,15 +79,15 @@ void Polygon2DEditor::_notification(int p_what) { uv_button[UV_MODE_SCALE]->set_icon(get_theme_icon("ToolScale", "EditorIcons")); uv_button[UV_MODE_ADD_POLYGON]->set_icon(get_theme_icon("Edit", "EditorIcons")); uv_button[UV_MODE_REMOVE_POLYGON]->set_icon(get_theme_icon("Close", "EditorIcons")); - uv_button[UV_MODE_PAINT_WEIGHT]->set_icon(get_theme_icon("PaintVertex", "EditorIcons")); - uv_button[UV_MODE_CLEAR_WEIGHT]->set_icon(get_theme_icon("UnpaintVertex", "EditorIcons")); + uv_button[UV_MODE_PAINT_WEIGHT]->set_icon(get_theme_icon("Bucket", "EditorIcons")); + uv_button[UV_MODE_CLEAR_WEIGHT]->set_icon(get_theme_icon("Clear", "EditorIcons")); b_snap_grid->set_icon(get_theme_icon("Grid", "EditorIcons")); b_snap_enable->set_icon(get_theme_icon("SnapGrid", "EditorIcons")); uv_icon_zoom->set_texture(get_theme_icon("Zoom", "EditorIcons")); - uv_vscroll->set_anchors_and_margins_preset(PRESET_RIGHT_WIDE); - uv_hscroll->set_anchors_and_margins_preset(PRESET_BOTTOM_WIDE); + uv_vscroll->set_anchors_and_offsets_preset(PRESET_RIGHT_WIDE); + uv_hscroll->set_anchors_and_offsets_preset(PRESET_BOTTOM_WIDE); } break; case NOTIFICATION_VISIBILITY_CHANGED: { if (!is_visible()) { @@ -198,7 +199,7 @@ void Polygon2DEditor::_uv_edit_mode_select(int p_mode) { uv_button[UV_MODE_CREATE]->hide(); uv_button[UV_MODE_CREATE_INTERNAL]->hide(); uv_button[UV_MODE_REMOVE_INTERNAL]->hide(); - for (int i = UV_MODE_MOVE; i <= UV_MODE_SCALE; i++) { + for (int i = UV_MODE_EDIT_POINT; i <= UV_MODE_SCALE; i++) { uv_button[i]->show(); } uv_button[UV_MODE_ADD_POLYGON]->hide(); @@ -484,7 +485,8 @@ void Polygon2DEditor::_uv_input(const Ref<InputEvent> &p_input) { } else { Vector2 tuv = mtx.affine_inverse().xform(snap_point(Vector2(mb->get_position().x, mb->get_position().y))); - if (points_prev.size() > 2 && tuv.distance_to(points_prev[0]) < 8) { + // Close the polygon if selected point is near start. Threshold for closing scaled by zoom level + if (points_prev.size() > 2 && tuv.distance_to(points_prev[0]) < (8 / uv_draw_zoom)) { undo_redo->create_action(TTR("Create Polygon & UV")); undo_redo->add_do_method(node, "set_uv", node->get_uv()); undo_redo->add_undo_method(node, "set_uv", uv_create_uv_prev); @@ -693,7 +695,7 @@ void Polygon2DEditor::_uv_input(const Ref<InputEvent> &p_input) { polys.write[j] = mtx.xform(points_prev[idx]); } - if (Geometry::is_point_in_polygon(Vector2(mb->get_position().x, mb->get_position().y), polys)) { + if (Geometry2D::is_point_in_polygon(Vector2(mb->get_position().x, mb->get_position().y), polys)) { erase_index = i; break; } @@ -726,35 +728,37 @@ void Polygon2DEditor::_uv_input(const Ref<InputEvent> &p_input) { bone_painting_bone = bone_selected; } } + } else { + if (uv_drag && !uv_create) { + if (uv_edit_mode[0]->is_pressed()) { // Edit UV. + undo_redo->create_action(TTR("Transform UV Map")); + undo_redo->add_do_method(node, "set_uv", node->get_uv()); + undo_redo->add_undo_method(node, "set_uv", points_prev); + undo_redo->add_do_method(uv_edit_draw, "update"); + undo_redo->add_undo_method(uv_edit_draw, "update"); + undo_redo->commit_action(); + } else if (uv_edit_mode[1]->is_pressed() && uv_move_current == UV_MODE_EDIT_POINT) { // Edit polygon. + undo_redo->create_action(TTR("Transform Polygon")); + undo_redo->add_do_method(node, "set_polygon", node->get_polygon()); + undo_redo->add_undo_method(node, "set_polygon", points_prev); + undo_redo->add_do_method(uv_edit_draw, "update"); + undo_redo->add_undo_method(uv_edit_draw, "update"); + undo_redo->commit_action(); + } - } else if (uv_drag && !uv_create) { - if (uv_edit_mode[0]->is_pressed()) { // Edit UV. - undo_redo->create_action(TTR("Transform UV Map")); - undo_redo->add_do_method(node, "set_uv", node->get_uv()); - undo_redo->add_undo_method(node, "set_uv", points_prev); - undo_redo->add_do_method(uv_edit_draw, "update"); - undo_redo->add_undo_method(uv_edit_draw, "update"); - undo_redo->commit_action(); - } else if (uv_edit_mode[1]->is_pressed() && uv_move_current == UV_MODE_EDIT_POINT) { // Edit polygon. - undo_redo->create_action(TTR("Transform Polygon")); - undo_redo->add_do_method(node, "set_polygon", node->get_polygon()); - undo_redo->add_undo_method(node, "set_polygon", points_prev); + uv_drag = false; + } + + if (bone_painting) { + undo_redo->create_action(TTR("Paint Bone Weights")); + undo_redo->add_do_method(node, "set_bone_weights", bone_painting_bone, node->get_bone_weights(bone_painting_bone)); + undo_redo->add_undo_method(node, "set_bone_weights", bone_painting_bone, prev_weights); undo_redo->add_do_method(uv_edit_draw, "update"); undo_redo->add_undo_method(uv_edit_draw, "update"); undo_redo->commit_action(); + bone_painting = false; } - - uv_drag = false; - } else if (bone_painting) { - undo_redo->create_action(TTR("Paint Bone Weights")); - undo_redo->add_do_method(node, "set_bone_weights", bone_painting_bone, node->get_bone_weights(bone_painting_bone)); - undo_redo->add_undo_method(node, "set_bone_weights", bone_painting_bone, prev_weights); - undo_redo->add_do_method(uv_edit_draw, "update"); - undo_redo->add_undo_method(uv_edit_draw, "update"); - undo_redo->commit_action(); - bone_painting = false; } - } else if (mb->get_button_index() == BUTTON_RIGHT && mb->is_pressed()) { _cancel_editing(); @@ -1048,8 +1052,6 @@ void Polygon2DEditor::_uv_draw() { if (i < uv_draw_max /*&& polygons.size() == 0 && polygon_create.size() == 0*/) { //if using or creating polygons, do not show outline (will show polygons instead) uv_edit_draw->draw_line(mtx.xform(uvs[i]), mtx.xform(next_point), poly_line_color, Math::round(EDSCALE)); } - - rect.expand_to(mtx.basis_xform(uvs[i])); } for (int i = 0; i < polygons.size(); i++) { @@ -1156,8 +1158,8 @@ void Polygon2DEditor::_uv_draw() { uv_edit_draw->draw_circle(bone_paint_pos, bone_paint_radius->get_value() * EDSCALE, Color(1, 1, 1, 0.1)); } - rect.position -= uv_edit_draw->get_size(); - rect.size += uv_edit_draw->get_size() * 2.0; + rect.position = -uv_edit_draw->get_size(); + rect.size = uv_edit_draw->get_size() * 2.0 + base_tex->get_size() * uv_draw_zoom; updating_uv_scroll = true; @@ -1185,8 +1187,8 @@ void Polygon2DEditor::_uv_draw() { Size2 vmin = uv_vscroll->get_combined_minimum_size(); // Avoid scrollbar overlapping. - uv_hscroll->set_anchor_and_margin(MARGIN_RIGHT, ANCHOR_END, uv_vscroll->is_visible() ? -vmin.width : 0); - uv_vscroll->set_anchor_and_margin(MARGIN_BOTTOM, ANCHOR_END, uv_hscroll->is_visible() ? -hmin.height : 0); + uv_hscroll->set_anchor_and_offset(SIDE_RIGHT, ANCHOR_END, uv_vscroll->is_visible() ? -vmin.width : 0); + uv_vscroll->set_anchor_and_offset(SIDE_BOTTOM, ANCHOR_END, uv_hscroll->is_visible() ? -hmin.height : 0); updating_uv_scroll = false; } @@ -1213,7 +1215,8 @@ Polygon2DEditor::Polygon2DEditor(EditorNode *p_editor) : use_snap = EditorSettings::get_singleton()->get_project_metadata("polygon_2d_uv_editor", "snap_enabled", false); snap_show_grid = EditorSettings::get_singleton()->get_project_metadata("polygon_2d_uv_editor", "show_grid", false); - button_uv = memnew(ToolButton); + button_uv = memnew(Button); + button_uv->set_flat(true); add_child(button_uv); button_uv->set_tooltip(TTR("Open Polygon 2D UV editor.")); button_uv->connect("pressed", callable_mp(this, &Polygon2DEditor::_menu_option), varray(MODE_EDIT_UV)); @@ -1230,16 +1233,16 @@ Polygon2DEditor::Polygon2DEditor(EditorNode *p_editor) : uv_edit_group.instance(); - uv_edit_mode[0] = memnew(ToolButton); + uv_edit_mode[0] = memnew(Button); uv_mode_hb->add_child(uv_edit_mode[0]); uv_edit_mode[0]->set_toggle_mode(true); - uv_edit_mode[1] = memnew(ToolButton); + uv_edit_mode[1] = memnew(Button); uv_mode_hb->add_child(uv_edit_mode[1]); uv_edit_mode[1]->set_toggle_mode(true); - uv_edit_mode[2] = memnew(ToolButton); + uv_edit_mode[2] = memnew(Button); uv_mode_hb->add_child(uv_edit_mode[2]); uv_edit_mode[2]->set_toggle_mode(true); - uv_edit_mode[3] = memnew(ToolButton); + uv_edit_mode[3] = memnew(Button); uv_mode_hb->add_child(uv_edit_mode[3]); uv_edit_mode[3]->set_toggle_mode(true); @@ -1263,7 +1266,8 @@ Polygon2DEditor::Polygon2DEditor(EditorNode *p_editor) : uv_main_vb->add_child(uv_mode_hb); for (int i = 0; i < UV_MODE_MAX; i++) { - uv_button[i] = memnew(ToolButton); + uv_button[i] = memnew(Button); + uv_button[i]->set_flat(true); uv_button[i]->set_toggle_mode(true); uv_mode_hb->add_child(uv_button[i]); uv_button[i]->connect("pressed", callable_mp(this, &Polygon2DEditor::_uv_mode), varray(i)); @@ -1320,11 +1324,16 @@ Polygon2DEditor::Polygon2DEditor(EditorNode *p_editor) : uv_main_hsc->add_child(uv_edit_draw); uv_edit_draw->set_h_size_flags(SIZE_EXPAND_FILL); uv_edit_draw->set_custom_minimum_size(Size2(200, 200) * EDSCALE); + + Control *space = memnew(Control); + uv_mode_hb->add_child(space); + space->set_h_size_flags(SIZE_EXPAND_FILL); + uv_menu = memnew(MenuButton); uv_mode_hb->add_child(uv_menu); uv_menu->set_text(TTR("Edit")); - uv_menu->get_popup()->add_item(TTR("Polygon->UV"), UVEDIT_POLYGON_TO_UV); - uv_menu->get_popup()->add_item(TTR("UV->Polygon"), UVEDIT_UV_TO_POLYGON); + uv_menu->get_popup()->add_item(TTR("Copy Polygon to UV"), UVEDIT_POLYGON_TO_UV); + uv_menu->get_popup()->add_item(TTR("Copy UV to Polygon"), UVEDIT_UV_TO_POLYGON); uv_menu->get_popup()->add_separator(); uv_menu->get_popup()->add_item(TTR("Clear UV"), UVEDIT_UV_CLEAR); uv_menu->get_popup()->add_separator(); @@ -1333,7 +1342,8 @@ Polygon2DEditor::Polygon2DEditor(EditorNode *p_editor) : uv_mode_hb->add_child(memnew(VSeparator)); - b_snap_enable = memnew(ToolButton); + b_snap_enable = memnew(Button); + b_snap_enable->set_flat(true); uv_mode_hb->add_child(b_snap_enable); b_snap_enable->set_text(TTR("Snap")); b_snap_enable->set_focus_mode(FOCUS_NONE); @@ -1342,7 +1352,8 @@ Polygon2DEditor::Polygon2DEditor(EditorNode *p_editor) : b_snap_enable->set_tooltip(TTR("Enable Snap")); b_snap_enable->connect("toggled", callable_mp(this, &Polygon2DEditor::_set_use_snap)); - b_snap_grid = memnew(ToolButton); + b_snap_grid = memnew(Button); + b_snap_grid->set_flat(true); uv_mode_hb->add_child(b_snap_grid); b_snap_grid->set_text(TTR("Grid")); b_snap_grid->set_focus_mode(FOCUS_NONE); diff --git a/editor/plugins/polygon_2d_editor_plugin.h b/editor/plugins/polygon_2d_editor_plugin.h index b94ae53e2b..af3b2f5aef 100644 --- a/editor/plugins/polygon_2d_editor_plugin.h +++ b/editor/plugins/polygon_2d_editor_plugin.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -60,16 +60,16 @@ class Polygon2DEditor : public AbstractPolygon2DEditor { UV_MODE_MAX }; - ToolButton *uv_edit_mode[4]; + Button *uv_edit_mode[4]; Ref<ButtonGroup> uv_edit_group; Polygon2D *node; UVMode uv_mode; AcceptDialog *uv_edit; - ToolButton *uv_button[UV_MODE_MAX]; - ToolButton *b_snap_enable; - ToolButton *b_snap_grid; + Button *uv_button[UV_MODE_MAX]; + Button *b_snap_enable; + Button *b_snap_grid; Panel *uv_edit_draw; HSlider *uv_zoom; SpinBox *uv_zoom_value; @@ -115,14 +115,14 @@ class Polygon2DEditor : public AbstractPolygon2DEditor { AcceptDialog *error; - ToolButton *button_uv; + Button *button_uv; bool use_snap; bool snap_show_grid; Vector2 snap_offset; Vector2 snap_step; - virtual void _menu_option(int p_option); + virtual void _menu_option(int p_option) override; void _cancel_editing(); void _update_polygon_editing_state(); @@ -143,16 +143,16 @@ class Polygon2DEditor : public AbstractPolygon2DEditor { void _uv_edit_popup_hide(); void _bone_paint_selected(int p_index); - int _get_polygon_count() const; + int _get_polygon_count() const override; protected: - virtual Node2D *_get_node() const; - virtual void _set_node(Node *p_polygon); + virtual Node2D *_get_node() const override; + virtual void _set_node(Node *p_polygon) override; - virtual Vector2 _get_offset(int p_idx) const; + virtual Vector2 _get_offset(int p_idx) const override; - virtual bool _has_uv() const { return true; }; - virtual void _commit_action(); + virtual bool _has_uv() const override { return true; }; + virtual void _commit_action() override; void _notification(int p_what); static void _bind_methods(); diff --git a/editor/plugins/resource_preloader_editor_plugin.cpp b/editor/plugins/resource_preloader_editor_plugin.cpp index 75cb93ee76..b4b8e82124 100644 --- a/editor/plugins/resource_preloader_editor_plugin.cpp +++ b/editor/plugins/resource_preloader_editor_plugin.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -30,8 +30,8 @@ #include "resource_preloader_editor_plugin.h" +#include "core/config/project_settings.h" #include "core/io/resource_loader.h" -#include "core/project_settings.h" #include "editor/editor_scale.h" #include "editor/editor_settings.h" @@ -62,7 +62,7 @@ void ResourcePreloaderEditor::_files_load_request(const Vector<String> &p_paths) dialog->set_text(TTR("ERROR: Couldn't load resource!")); dialog->set_title(TTR("Error!")); //dialog->get_cancel()->set_text("Close"); - dialog->get_ok()->set_text(TTR("Close")); + dialog->get_ok_button()->set_text(TTR("Close")); dialog->popup_centered(); return; ///beh should show an error i guess } @@ -95,8 +95,7 @@ void ResourcePreloaderEditor::_load_pressed() { } file->set_file_mode(EditorFileDialog::FILE_MODE_OPEN_FILES); - - file->popup_centered_ratio(); + file->popup_file_dialog(); } void ResourcePreloaderEditor::_item_edited() { @@ -145,7 +144,7 @@ void ResourcePreloaderEditor::_paste_pressed() { if (!r.is_valid()) { dialog->set_text(TTR("Resource clipboard is empty!")); dialog->set_title(TTR("Error!")); - dialog->get_ok()->set_text(TTR("Close")); + dialog->get_ok_button()->set_text(TTR("Close")); dialog->popup_centered(); return; ///beh should show an error i guess } diff --git a/editor/plugins/resource_preloader_editor_plugin.h b/editor/plugins/resource_preloader_editor_plugin.h index 2d7a54eda5..bc10b48a16 100644 --- a/editor/plugins/resource_preloader_editor_plugin.h +++ b/editor/plugins/resource_preloader_editor_plugin.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -93,11 +93,11 @@ class ResourcePreloaderEditorPlugin : public EditorPlugin { Button *button; public: - virtual String get_name() const { return "ResourcePreloader"; } - bool has_main_screen() const { return false; } - virtual void edit(Object *p_object); - virtual bool handles(Object *p_object) const; - virtual void make_visible(bool p_visible); + virtual String get_name() const override { return "ResourcePreloader"; } + bool has_main_screen() const override { return false; } + virtual void edit(Object *p_object) override; + virtual bool handles(Object *p_object) const override; + virtual void make_visible(bool p_visible) override; ResourcePreloaderEditorPlugin(EditorNode *p_node); ~ResourcePreloaderEditorPlugin(); diff --git a/editor/plugins/root_motion_editor_plugin.cpp b/editor/plugins/root_motion_editor_plugin.cpp index e107435373..50f4d8493f 100644 --- a/editor/plugins/root_motion_editor_plugin.cpp +++ b/editor/plugins/root_motion_editor_plugin.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ diff --git a/editor/plugins/root_motion_editor_plugin.h b/editor/plugins/root_motion_editor_plugin.h index f72ad1ec05..c70fff7db7 100644 --- a/editor/plugins/root_motion_editor_plugin.h +++ b/editor/plugins/root_motion_editor_plugin.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -54,7 +54,7 @@ protected: void _notification(int p_what); public: - virtual void update_property(); + virtual void update_property() override; void setup(const NodePath &p_base_hint); EditorPropertyRootMotion(); }; @@ -63,10 +63,10 @@ class EditorInspectorRootMotionPlugin : public EditorInspectorPlugin { GDCLASS(EditorInspectorRootMotionPlugin, EditorInspectorPlugin); public: - virtual bool can_handle(Object *p_object); - virtual void parse_begin(Object *p_object); - virtual bool parse_property(Object *p_object, Variant::Type p_type, const String &p_path, PropertyHint p_hint, const String &p_hint_text, int p_usage, bool p_wide = false); - virtual void parse_end(); + virtual bool can_handle(Object *p_object) override; + virtual void parse_begin(Object *p_object) override; + virtual bool parse_property(Object *p_object, Variant::Type p_type, const String &p_path, PropertyHint p_hint, const String &p_hint_text, int p_usage, bool p_wide = false) override; + virtual void parse_end() override; }; #endif // ROOT_MOTION_EDITOR_PLUGIN_H diff --git a/editor/plugins/script_editor_plugin.cpp b/editor/plugins/script_editor_plugin.cpp index 8d6dac3907..a6afd45686 100644 --- a/editor/plugins/script_editor_plugin.cpp +++ b/editor/plugins/script_editor_plugin.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -30,12 +30,12 @@ #include "script_editor_plugin.h" +#include "core/config/project_settings.h" #include "core/input/input.h" #include "core/io/resource_loader.h" #include "core/os/file_access.h" #include "core/os/keyboard.h" #include "core/os/os.h" -#include "core/project_settings.h" #include "editor/debugger/editor_debugger_node.h" #include "editor/editor_node.h" #include "editor/editor_run_script.h" @@ -51,6 +51,165 @@ #include "servers/display_server.h" #include "text_editor.h" +/*** SYNTAX HIGHLIGHTER ****/ + +String EditorSyntaxHighlighter::_get_name() const { + ScriptInstance *si = get_script_instance(); + if (si && si->has_method("_get_name")) { + return si->call("_get_name"); + } + return "Unnamed"; +} + +Array EditorSyntaxHighlighter::_get_supported_languages() const { + ScriptInstance *si = get_script_instance(); + if (si && si->has_method("_get_supported_languages")) { + return si->call("_get_supported_languages"); + } + return Array(); +} + +Ref<EditorSyntaxHighlighter> EditorSyntaxHighlighter::_create() const { + Ref<EditorSyntaxHighlighter> syntax_highlighter; + syntax_highlighter.instance(); + if (get_script_instance()) { + syntax_highlighter->set_script(get_script_instance()->get_script()); + } + return syntax_highlighter; +} + +void EditorSyntaxHighlighter::_bind_methods() { + ClassDB::bind_method(D_METHOD("_get_edited_resource"), &EditorSyntaxHighlighter::_get_edited_resource); + + BIND_VMETHOD(MethodInfo(Variant::STRING, "_get_name")); + BIND_VMETHOD(MethodInfo(Variant::ARRAY, "_get_supported_languages")); + BIND_VMETHOD(MethodInfo(Variant::ARRAY, "_get_supported_extentions")); +} + +//// + +void EditorStandardSyntaxHighlighter::_update_cache() { + highlighter->set_text_edit(text_edit); + highlighter->clear_keyword_colors(); + highlighter->clear_member_keyword_colors(); + highlighter->clear_color_regions(); + + highlighter->set_symbol_color(EDITOR_GET("text_editor/highlighting/symbol_color")); + highlighter->set_function_color(EDITOR_GET("text_editor/highlighting/function_color")); + highlighter->set_number_color(EDITOR_GET("text_editor/highlighting/number_color")); + highlighter->set_member_variable_color(EDITOR_GET("text_editor/highlighting/member_variable_color")); + + /* Engine types. */ + const Color type_color = EDITOR_GET("text_editor/highlighting/engine_type_color"); + List<StringName> types; + ClassDB::get_class_list(&types); + for (List<StringName>::Element *E = types.front(); E; E = E->next()) { + String n = E->get(); + if (n.begins_with("_")) { + n = n.substr(1, n.length()); + } + highlighter->add_keyword_color(n, type_color); + } + + /* User types. */ + const Color usertype_color = EDITOR_GET("text_editor/highlighting/user_type_color"); + List<StringName> global_classes; + ScriptServer::get_global_class_list(&global_classes); + for (List<StringName>::Element *E = global_classes.front(); E; E = E->next()) { + highlighter->add_keyword_color(E->get(), usertype_color); + } + + /* Autoloads. */ + Map<StringName, ProjectSettings::AutoloadInfo> autoloads = ProjectSettings::get_singleton()->get_autoload_list(); + for (Map<StringName, ProjectSettings::AutoloadInfo>::Element *E = autoloads.front(); E; E = E->next()) { + const ProjectSettings::AutoloadInfo &info = E->value(); + if (info.is_singleton) { + highlighter->add_keyword_color(info.name, usertype_color); + } + } + + const Ref<Script> script = _get_edited_resource(); + if (script.is_valid()) { + /* Core types. */ + const Color basetype_color = EDITOR_GET("text_editor/highlighting/base_type_color"); + List<String> core_types; + script->get_language()->get_core_type_words(&core_types); + for (List<String>::Element *E = core_types.front(); E; E = E->next()) { + highlighter->add_keyword_color(E->get(), basetype_color); + } + + /* Reserved words. */ + const Color keyword_color = EDITOR_GET("text_editor/highlighting/keyword_color"); + List<String> keywords; + script->get_language()->get_reserved_words(&keywords); + for (List<String>::Element *E = keywords.front(); E; E = E->next()) { + highlighter->add_keyword_color(E->get(), keyword_color); + } + + /* Member types. */ + const Color member_variable_color = EDITOR_GET("text_editor/highlighting/member_variable_color"); + StringName instance_base = script->get_instance_base_type(); + if (instance_base != StringName()) { + List<PropertyInfo> plist; + ClassDB::get_property_list(instance_base, &plist); + for (List<PropertyInfo>::Element *E = plist.front(); E; E = E->next()) { + String name = E->get().name; + if (E->get().usage & PROPERTY_USAGE_CATEGORY || E->get().usage & PROPERTY_USAGE_GROUP || E->get().usage & PROPERTY_USAGE_SUBGROUP) { + continue; + } + if (name.find("/") != -1) { + continue; + } + highlighter->add_member_keyword_color(name, member_variable_color); + } + + List<String> clist; + ClassDB::get_integer_constant_list(instance_base, &clist); + for (List<String>::Element *E = clist.front(); E; E = E->next()) { + highlighter->add_member_keyword_color(E->get(), member_variable_color); + } + } + + /* Comments */ + const Color comment_color = EDITOR_GET("text_editor/highlighting/comment_color"); + List<String> comments; + script->get_language()->get_comment_delimiters(&comments); + for (List<String>::Element *E = comments.front(); E; E = E->next()) { + String comment = E->get(); + String beg = comment.get_slice(" ", 0); + String end = comment.get_slice_count(" ") > 1 ? comment.get_slice(" ", 1) : String(); + highlighter->add_color_region(beg, end, comment_color, end == ""); + } + + /* Strings */ + const Color string_color = EDITOR_GET("text_editor/highlighting/string_color"); + List<String> strings; + script->get_language()->get_string_delimiters(&strings); + for (List<String>::Element *E = strings.front(); E; E = E->next()) { + String string = E->get(); + String beg = string.get_slice(" ", 0); + String end = string.get_slice_count(" ") > 1 ? string.get_slice(" ", 1) : String(); + highlighter->add_color_region(beg, end, string_color, end == ""); + } + } +} + +Ref<EditorSyntaxHighlighter> EditorStandardSyntaxHighlighter::_create() const { + Ref<EditorStandardSyntaxHighlighter> syntax_highlighter; + syntax_highlighter.instance(); + return syntax_highlighter; +} + +//// + +Ref<EditorSyntaxHighlighter> EditorPlainTextSyntaxHighlighter::_create() const { + Ref<EditorPlainTextSyntaxHighlighter> syntax_highlighter; + syntax_highlighter.instance(); + return syntax_highlighter; +} + +//////////////////////////////////////////////////////////////////////////////// + /*** SCRIPT EDITOR ****/ void ScriptEditorBase::_bind_methods() { @@ -63,6 +222,8 @@ void ScriptEditorBase::_bind_methods() { // TODO: This signal is no use for VisualScript. ADD_SIGNAL(MethodInfo("search_in_files_requested", PropertyInfo(Variant::STRING, "text"))); ADD_SIGNAL(MethodInfo("replace_in_files_requested", PropertyInfo(Variant::STRING, "text"))); + + BIND_VMETHOD(MethodInfo("add_syntax_highlighter", PropertyInfo(Variant::OBJECT, "highlighter"))); } static bool _is_built_in_script(Script *p_script) { @@ -73,15 +234,15 @@ static bool _is_built_in_script(Script *p_script) { class EditorScriptCodeCompletionCache : public ScriptCodeCompletionCache { struct Cache { - uint64_t time_loaded; + uint64_t time_loaded = 0; RES cache; }; Map<String, Cache> cached; public: - uint64_t max_time_cache; - int max_cache_size; + uint64_t max_time_cache = 5 * 60 * 1000; //minutes, five + int max_cache_size = 128; void cleanup() { List<Map<String, Cache>::Element *> to_clean; @@ -131,11 +292,6 @@ public: return E->get().cache; } - EditorScriptCodeCompletionCache() { - max_cache_size = 128; - max_time_cache = 5 * 60 * 1000; //minutes, five - } - virtual ~EditorScriptCodeCompletionCache() {} }; @@ -182,7 +338,7 @@ void ScriptEditorQuickOpen::_update_search() { } } - get_ok()->set_disabled(root->get_children() == nullptr); + get_ok_button()->set_disabled(root->get_children() == nullptr); } void ScriptEditorQuickOpen::_confirmed() { @@ -226,8 +382,8 @@ ScriptEditorQuickOpen::ScriptEditorQuickOpen() { search_box->connect("gui_input", callable_mp(this, &ScriptEditorQuickOpen::_sbox_input)); search_options = memnew(Tree); vbc->add_margin_child(TTR("Matches:"), search_options, true); - get_ok()->set_text(TTR("Open")); - get_ok()->set_disabled(true); + get_ok_button()->set_text(TTR("Open")); + get_ok_button()->set_disabled(true); register_text_enter(search_box); set_hide_on_ok(false); search_options->connect("item_activated", callable_mp(this, &ScriptEditorQuickOpen::_confirmed)); @@ -431,7 +587,7 @@ void ScriptEditor::_go_to_tab(int p_idx) { } void ScriptEditor::_add_recent_script(String p_path) { - if (p_path.empty()) { + if (p_path.is_empty()) { return; } @@ -535,15 +691,21 @@ void ScriptEditor::_close_tab(int p_idx, bool p_save, bool p_history_back) { Node *tselected = tab_container->get_child(selected); - ScriptEditorBase *current = Object::cast_to<ScriptEditorBase>(tab_container->get_child(selected)); + ScriptEditorBase *current = Object::cast_to<ScriptEditorBase>(tselected); if (current) { - if (p_save) { - apply_scripts(); - } - Ref<Script> script = current->get_edited_resource(); - if (script != nullptr) { - previous_scripts.push_back(script->get_path()); + if (p_save && script.is_valid()) { + // Do not try to save internal scripts, but prompt to save in-memory + // scripts which are not saved to disk yet (have empty path). + if (script->get_path().find("local://") == -1 && script->get_path().find("::") == -1) { + _menu_option(FILE_SAVE); + } + } + if (script.is_valid()) { + if (!script->get_path().is_empty()) { + // Only saved scripts can be restored. + previous_scripts.push_back(script->get_path()); + } notify_script_close(script); } } @@ -615,8 +777,10 @@ void ScriptEditor::_close_docs_tab() { void ScriptEditor::_copy_script_path() { ScriptEditorBase *se = _get_current_editor(); - RES script = se->get_edited_resource(); - DisplayServer::get_singleton()->clipboard_set(script->get_path()); + if (se) { + RES script = se->get_edited_resource(); + DisplayServer::get_singleton()->clipboard_set(script->get_path()); + } } void ScriptEditor::_close_other_tabs() { @@ -730,7 +894,7 @@ void ScriptEditor::_reload_scripts() { Ref<Script> script = edited_res; if (script != nullptr) { - Ref<Script> rel_script = ResourceLoader::load(script->get_path(), script->get_class(), true); + Ref<Script> rel_script = ResourceLoader::load(script->get_path(), script->get_class(), ResourceFormatLoader::CACHE_MODE_IGNORE); ERR_CONTINUE(!rel_script.is_valid()); script->set_source_code(rel_script->get_source_code()); script->set_last_modified_time(rel_script->get_last_modified_time()); @@ -837,7 +1001,6 @@ void ScriptEditor::_file_dialog_action(String p_file) { Error err; FileAccess *file = FileAccess::open(p_file, FileAccess::WRITE, &err); if (err) { - memdelete(file); editor->show_warning(TTR("Error writing TextFile:") + "\n" + p_file, TTR("Error!")); break; } @@ -875,17 +1038,19 @@ void ScriptEditor::_file_dialog_action(String p_file) { } break; case FILE_SAVE_AS: { ScriptEditorBase *current = _get_current_editor(); + if (current) { + RES resource = current->get_edited_resource(); + String path = ProjectSettings::get_singleton()->localize_path(p_file); + Error err = _save_text_file(resource, path); - String path = ProjectSettings::get_singleton()->localize_path(p_file); - Error err = _save_text_file(current->get_edited_resource(), path); + if (err != OK) { + editor->show_accept(TTR("Error saving file!"), TTR("OK")); + return; + } - if (err != OK) { - editor->show_accept(TTR("Error saving file!"), TTR("OK")); - return; + resource->set_path(path); + _update_script_names(); } - - ((Resource *)current->get_edited_resource().ptr())->set_path(path); - _update_script_names(); } break; case THEME_SAVE_AS: { if (!EditorSettings::get_singleton()->save_text_editor_theme_as(p_file)) { @@ -944,7 +1109,7 @@ void ScriptEditor::_menu_option(int p_option) { file_dialog_option = FILE_NEW_TEXTFILE; file_dialog->clear_filters(); - file_dialog->popup_centered_ratio(); + file_dialog->popup_file_dialog(); file_dialog->set_title(TTR("New Text File...")); } break; case FILE_OPEN: { @@ -959,12 +1124,12 @@ void ScriptEditor::_menu_option(int p_option) { file_dialog->add_filter("*." + extensions[i] + " ; " + extensions[i].to_upper()); } - file_dialog->popup_centered_ratio(); + file_dialog->popup_file_dialog(); file_dialog->set_title(TTR("Open File")); return; } break; case FILE_REOPEN_CLOSED: { - if (previous_scripts.empty()) { + if (previous_scripts.is_empty()) { return; } @@ -1077,13 +1242,36 @@ void ScriptEditor::_menu_option(int p_option) { } } - Ref<TextFile> text_file = current->get_edited_resource(); + RES resource = current->get_edited_resource(); + Ref<TextFile> text_file = resource; + Ref<Script> script = resource; + if (text_file != nullptr) { current->apply_code(); _save_text_file(text_file, text_file->get_path()); break; } - editor->save_resource(current->get_edited_resource()); + + if (script != nullptr) { + const Vector<DocData::ClassDoc> &documentations = script->get_documentation(); + for (int j = 0; j < documentations.size(); j++) { + const DocData::ClassDoc &doc = documentations.get(j); + if (EditorHelp::get_doc_data()->has_doc(doc.name)) { + EditorHelp::get_doc_data()->remove_doc(doc.name); + } + } + } + + editor->save_resource(resource); + + if (script != nullptr) { + const Vector<DocData::ClassDoc> &documentations = script->get_documentation(); + for (int j = 0; j < documentations.size(); j++) { + const DocData::ClassDoc &doc = documentations.get(j); + EditorHelp::get_doc_data()->add_doc(doc); + update_doc(doc.name); + } + } } break; case FILE_SAVE_AS: { @@ -1101,7 +1289,10 @@ void ScriptEditor::_menu_option(int p_option) { } } - Ref<TextFile> text_file = current->get_edited_resource(); + RES resource = current->get_edited_resource(); + Ref<TextFile> text_file = resource; + Ref<Script> script = resource; + if (text_file != nullptr) { file_dialog->set_file_mode(EditorFileDialog::FILE_MODE_SAVE_FILE); file_dialog->set_access(EditorFileDialog::ACCESS_FILESYSTEM); @@ -1112,14 +1303,32 @@ void ScriptEditor::_menu_option(int p_option) { file_dialog->clear_filters(); file_dialog->set_current_dir(text_file->get_path().get_base_dir()); file_dialog->set_current_file(text_file->get_path().get_file()); - file_dialog->popup_centered_ratio(); + file_dialog->popup_file_dialog(); file_dialog->set_title(TTR("Save File As...")); break; } - editor->push_item(Object::cast_to<Object>(current->get_edited_resource().ptr())); - editor->save_resource_as(current->get_edited_resource()); + if (script != nullptr) { + const Vector<DocData::ClassDoc> &documentations = script->get_documentation(); + for (int j = 0; j < documentations.size(); j++) { + const DocData::ClassDoc &doc = documentations.get(j); + if (EditorHelp::get_doc_data()->has_doc(doc.name)) { + EditorHelp::get_doc_data()->remove_doc(doc.name); + } + } + } + + editor->push_item(resource.ptr()); + editor->save_resource_as(resource); + if (script != nullptr) { + const Vector<DocData::ClassDoc> &documentations = script->get_documentation(); + for (int j = 0; j < documentations.size(); j++) { + const DocData::ClassDoc &doc = documentations.get(j); + EditorHelp::get_doc_data()->add_doc(doc); + update_doc(doc.name); + } + } } break; case FILE_TOOL_RELOAD: @@ -1172,7 +1381,7 @@ void ScriptEditor::_menu_option(int p_option) { case SHOW_IN_FILE_SYSTEM: { const RES script = current->get_edited_resource(); const String path = script->get_path(); - if (!path.empty()) { + if (!path.is_empty()) { FileSystemDock *file_system_dock = EditorNode::get_singleton()->get_filesystem_dock(); file_system_dock->navigate_to_path(path); // Ensure that the FileSystem dock is visible. @@ -1262,7 +1471,7 @@ void ScriptEditor::_theme_option(int p_option) { file_dialog_option = THEME_IMPORT; file_dialog->clear_filters(); file_dialog->add_filter("*.tet"); - file_dialog->popup_centered_ratio(); + file_dialog->popup_file_dialog(); file_dialog->set_title(TTR("Import Theme")); } break; case THEME_RELOAD: { @@ -1288,7 +1497,7 @@ void ScriptEditor::_show_save_theme_as_dialog() { file_dialog->clear_filters(); file_dialog->add_filter("*.tet"); file_dialog->set_current_path(EditorSettings::get_singleton()->get_text_editor_themes_dir().plus_file(EditorSettings::get_singleton()->get("text_editor/theme/color_theme"))); - file_dialog->popup_centered_ratio(); + file_dialog->popup_file_dialog(); file_dialog->set_title(TTR("Save Theme As...")); } @@ -1302,6 +1511,7 @@ void ScriptEditor::_notification(int p_what) { editor->connect("stop_pressed", callable_mp(this, &ScriptEditor::_editor_stop)); editor->connect("script_add_function_request", callable_mp(this, &ScriptEditor::_add_callback)); editor->connect("resource_saved", callable_mp(this, &ScriptEditor::_res_saved_callback)); + editor->get_filesystem_dock()->connect("file_removed", callable_mp(this, &ScriptEditor::_file_removed)); script_list->connect("item_selected", callable_mp(this, &ScriptEditor::_script_selected)); members_overview->connect("item_selected", callable_mp(this, &ScriptEditor::_members_overview_selected)); @@ -1309,14 +1519,22 @@ void ScriptEditor::_notification(int p_what) { script_split->connect("dragged", callable_mp(this, &ScriptEditor::_script_split_dragged)); EditorSettings::get_singleton()->connect("settings_changed", callable_mp(this, &ScriptEditor::_editor_settings_changed)); + EditorFileSystem::get_singleton()->connect("filesystem_changed", callable_mp(this, &ScriptEditor::_filesystem_changed)); [[fallthrough]]; } + case NOTIFICATION_TRANSLATION_CHANGED: + case NOTIFICATION_LAYOUT_DIRECTION_CHANGED: case NOTIFICATION_THEME_CHANGED: { help_search->set_icon(get_theme_icon("HelpSearch", "EditorIcons")); site_search->set_icon(get_theme_icon("Instance", "EditorIcons")); - script_forward->set_icon(get_theme_icon("Forward", "EditorIcons")); - script_back->set_icon(get_theme_icon("Back", "EditorIcons")); + if (is_layout_rtl()) { + script_forward->set_icon(get_theme_icon("Back", "EditorIcons")); + script_back->set_icon(get_theme_icon("Forward", "EditorIcons")); + } else { + script_forward->set_icon(get_theme_icon("Forward", "EditorIcons")); + script_back->set_icon(get_theme_icon("Back", "EditorIcons")); + } members_overview_alphabeta_sort_button->set_icon(get_theme_icon("Sort", "EditorIcons")); @@ -1338,7 +1556,7 @@ void ScriptEditor::_notification(int p_what) { editor->disconnect("stop_pressed", callable_mp(this, &ScriptEditor::_editor_stop)); } break; - case NOTIFICATION_WM_FOCUS_IN: { + case NOTIFICATION_WM_WINDOW_FOCUS_IN: { _test_script_times_on_disk(); _update_modified_scripts_for_external_editor(); } break; @@ -1411,25 +1629,15 @@ void ScriptEditor::get_breakpoints(List<String> *p_breakpoints) { continue; } - List<int> bpoints; - se->get_breakpoints(&bpoints); String base = script->get_path(); - ERR_CONTINUE(base.begins_with("local://") || base == ""); - - for (List<int>::Element *E = bpoints.front(); E; E = E->next()) { - p_breakpoints->push_back(base + ":" + itos(E->get() + 1)); + if (base.begins_with("local://") || base == "") { + continue; } - } -} -void ScriptEditor::ensure_focus_current() { - if (!is_inside_tree()) { - return; - } - - ScriptEditorBase *current = _get_current_editor(); - if (current) { - current->ensure_focus(); + Array bpoints = se->get_breakpoints(); + for (int j = 0; j < bpoints.size(); j++) { + p_breakpoints->push_back(base + ":" + itos((int)bpoints[j] + 1)); + } } } @@ -1467,6 +1675,8 @@ void ScriptEditor::ensure_select_current() { if (tab_container->get_child_count() && tab_container->get_current_tab() >= 0) { ScriptEditorBase *se = _get_current_editor(); if (se) { + se->enable_editor(); + if (!grab_focus_block && is_visible_in_tree()) { se->ensure_focus(); } @@ -1497,11 +1707,11 @@ struct _ScriptEditorItemData { String name; String sort_key; Ref<Texture2D> icon; - int index; + int index = 0; String tooltip; - bool used; - int category; - Node *ref; + bool used = false; + int category = 0; + Node *ref = nullptr; bool operator<(const _ScriptEditorItemData &id) const { if (category == id.category) { @@ -1677,6 +1887,12 @@ void ScriptEditor::_update_script_names() { if (se) { Ref<Texture2D> icon = se->get_theme_icon(); String path = se->get_edited_resource()->get_path(); + bool saved = !path.is_empty(); + if (saved) { + // The script might be deleted, moved, or renamed, so make sure + // to update original path to previously edited resource. + se->set_meta("_edit_res_path", path); + } bool built_in = !path.is_resource_file(); String name; @@ -1695,7 +1911,7 @@ void ScriptEditor::_update_script_names() { _ScriptEditorItemData sd; sd.icon = icon; sd.name = name; - sd.tooltip = path; + sd.tooltip = saved ? path : TTR("Unsaved file."); sd.index = i; sd.used = used.has(se->get_edited_resource()); sd.category = 0; @@ -1718,7 +1934,7 @@ void ScriptEditor::_update_script_names() { sd.name = name; } break; case DISPLAY_DIR_AND_NAME: { - if (!path.get_base_dir().get_file().empty()) { + if (!path.get_base_dir().get_file().is_empty()) { sd.name = path.get_base_dir().get_file().plus_file(name); } else { sd.name = name; @@ -1728,10 +1944,43 @@ void ScriptEditor::_update_script_names() { sd.name = path; } break; } + if (!saved) { + sd.name = se->get_name(); + } sedata.push_back(sd); } + Vector<String> disambiguated_script_names; + Vector<String> full_script_paths; + for (int j = 0; j < sedata.size(); j++) { + String name = sedata[j].name.replace("(*)", ""); + ScriptListName script_display = (ScriptListName)(int)EditorSettings::get_singleton()->get("text_editor/script_list/list_script_names_as"); + switch (script_display) { + case DISPLAY_NAME: { + name = name.get_file(); + } break; + case DISPLAY_DIR_AND_NAME: { + name = name.get_base_dir().get_file().plus_file(name.get_file()); + } break; + default: + break; + } + + disambiguated_script_names.append(name); + full_script_paths.append(sedata[j].tooltip); + } + + EditorNode::disambiguate_filenames(full_script_paths, disambiguated_script_names); + + for (int j = 0; j < sedata.size(); j++) { + if (sedata[j].name.ends_with("(*)")) { + sedata.write[j].name = disambiguated_script_names[j] + "(*)"; + } else { + sedata.write[j].name = disambiguated_script_names[j]; + } + } + EditorHelp *eh = Object::cast_to<EditorHelp>(tab_container->get_child(i)); if (eh) { String name = eh->get_class(); @@ -1752,7 +2001,7 @@ void ScriptEditor::_update_script_names() { } } - if (_sort_list_on_update && !sedata.empty()) { + if (_sort_list_on_update && !sedata.is_empty()) { sedata.sort(); // change actual order of tab_container so that the order can be rearranged by user @@ -1798,6 +2047,11 @@ void ScriptEditor::_update_script_names() { script_list->select(index); script_name_label->set_text(sedata_filtered[i].name); script_icon->set_texture(sedata_filtered[i].icon); + ScriptEditorBase *se = _get_current_editor(); + if (se) { + se->enable_editor(); + _update_selected_editor_menu(); + } } } @@ -1811,7 +2065,7 @@ void ScriptEditor::_update_script_names() { _update_help_overview_visibility(); _update_script_colors(); - file_menu->get_popup()->set_item_disabled(file_menu->get_popup()->get_item_index(FILE_REOPEN_CLOSED), previous_scripts.empty()); + file_menu->get_popup()->set_item_disabled(file_menu->get_popup()->get_item_index(FILE_REOPEN_CLOSED), previous_scripts.is_empty()); } void ScriptEditor::_update_script_connections() { @@ -1886,15 +2140,15 @@ bool ScriptEditor::edit(const RES &p_resource, int p_line, int p_col, bool p_gra Ref<Script> script = p_resource; - // refuse to open built-in if scene is not loaded - - // see if already has it + // Don't open dominant script if using an external editor. + const bool use_external_editor = + EditorSettings::get_singleton()->get("text_editor/external/use_external_editor") || + (script.is_valid() && script->get_language()->overrides_external_editor()); + const bool open_dominant = EditorSettings::get_singleton()->get("text_editor/files/open_dominant_script_on_scene_change"); - bool open_dominant = EditorSettings::get_singleton()->get("text_editor/files/open_dominant_script_on_scene_change"); + const bool should_open = (open_dominant && !use_external_editor) || !EditorNode::get_singleton()->is_changing_scene(); - const bool should_open = open_dominant || !EditorNode::get_singleton()->is_changing_scene(); - - if (script != nullptr && script->get_language()->overrides_external_editor()) { + if (script.is_valid() && script->get_language()->overrides_external_editor()) { if (should_open) { Error err = script->get_language()->open_in_external_editor(script, p_line >= 0 ? p_line : 0, p_col); if (err != OK) { @@ -1904,10 +2158,10 @@ bool ScriptEditor::edit(const RES &p_resource, int p_line, int p_col, bool p_gra return false; } - if ((EditorDebuggerNode::get_singleton()->get_dump_stack_script() != p_resource || EditorDebuggerNode::get_singleton()->get_debug_with_external_editor()) && + if (use_external_editor && + (EditorDebuggerNode::get_singleton()->get_dump_stack_script() != p_resource || EditorDebuggerNode::get_singleton()->get_debug_with_external_editor()) && p_resource->get_path().is_resource_file() && - p_resource->get_class_name() != StringName("VisualScript") && - bool(EditorSettings::get_singleton()->get("text_editor/external/use_external_editor"))) { + p_resource->get_class_name() != StringName("VisualScript")) { String path = EditorSettings::get_singleton()->get("text_editor/external/exec_path"); String flags = EditorSettings::get_singleton()->get("text_editor/external/exec_flags"); @@ -1957,7 +2211,7 @@ bool ScriptEditor::edit(const RES &p_resource, int p_line, int p_col, bool p_gra args.push_back(script_path); } - Error err = OS::get_singleton()->execute(path, args, false); + Error err = OS::get_singleton()->create_process(path, args); if (err == OK) { return false; } @@ -1972,6 +2226,8 @@ bool ScriptEditor::edit(const RES &p_resource, int p_line, int p_col, bool p_gra if ((script != nullptr && se->get_edited_resource() == p_resource) || se->get_edited_resource()->get_path() == p_resource->get_path()) { if (should_open) { + se->enable_editor(); + if (tab_container->get_current_tab() != i) { _go_to_tab(i); _update_script_names(); @@ -2002,15 +2258,20 @@ bool ScriptEditor::edit(const RES &p_resource, int p_line, int p_col, bool p_gra } ERR_FAIL_COND_V(!se, false); + se->set_edited_resource(p_resource); + if (p_resource->get_class_name() != StringName("VisualScript")) { bool highlighter_set = false; - for (int i = 0; i < syntax_highlighters_func_count; i++) { - SyntaxHighlighter *highlighter = syntax_highlighters_funcs[i](); + for (int i = 0; i < syntax_highlighters.size(); i++) { + Ref<EditorSyntaxHighlighter> highlighter = syntax_highlighters[i]->_create(); + if (highlighter.is_null()) { + continue; + } se->add_syntax_highlighter(highlighter); if (script != nullptr && !highlighter_set) { - List<String> languages = highlighter->get_supported_languages(); - if (languages.find(script->get_language()->get_name())) { + Array languages = highlighter->_get_supported_languages(); + if (languages.find(script->get_language()->get_name()) > -1) { se->set_syntax_highlighter(highlighter); highlighter_set = true; } @@ -2019,7 +2280,14 @@ bool ScriptEditor::edit(const RES &p_resource, int p_line, int p_col, bool p_gra } tab_container->add_child(se); - se->set_edited_resource(p_resource); + + if (p_grab_focus) { + se->enable_editor(); + } + + // If we delete a script within the filesystem, the original resource path + // is lost, so keep it as metadata to figure out the exact tab to delete. + se->set_meta("_edit_res_path", p_resource->get_path()); se->set_tooltip_request_func("_get_debug_tooltip", this); if (se->get_edit_menu()) { se->get_edit_menu()->hide(); @@ -2029,6 +2297,7 @@ bool ScriptEditor::edit(const RES &p_resource, int p_line, int p_col, bool p_gra if (p_grab_focus) { _go_to_tab(tab_container->get_tab_count() - 1); + _add_recent_script(p_resource->get_path()); } _sort_list_on_update = true; @@ -2053,7 +2322,6 @@ bool ScriptEditor::edit(const RES &p_resource, int p_line, int p_col, bool p_gra } notify_script_changed(p_resource); - _add_recent_script(p_resource->get_path()); return true; } @@ -2089,11 +2357,33 @@ void ScriptEditor::save_all_scripts() { if (edited_res->get_path() != "" && edited_res->get_path().find("local://") == -1 && edited_res->get_path().find("::") == -1) { Ref<TextFile> text_file = edited_res; + Ref<Script> script = edited_res; + if (text_file != nullptr) { _save_text_file(text_file, text_file->get_path()); continue; } + + if (script != nullptr) { + const Vector<DocData::ClassDoc> &documentations = script->get_documentation(); + for (int j = 0; j < documentations.size(); j++) { + const DocData::ClassDoc &doc = documentations.get(j); + if (EditorHelp::get_doc_data()->has_doc(doc.name)) { + EditorHelp::get_doc_data()->remove_doc(doc.name); + } + } + } + editor->save_resource(edited_res); //external script, save it + + if (script != nullptr) { + const Vector<DocData::ClassDoc> &documentations = script->get_documentation(); + for (int j = 0; j < documentations.size(); j++) { + const DocData::ClassDoc &doc = documentations.get(j); + EditorHelp::get_doc_data()->add_doc(doc); + update_doc(doc.name); + } + } } } @@ -2175,7 +2465,7 @@ void ScriptEditor::_editor_settings_changed() { if (current_theme == "") { current_theme = EditorSettings::get_singleton()->get("text_editor/theme/color_theme"); - } else if (current_theme != EditorSettings::get_singleton()->get("text_editor/theme/color_theme")) { + } else if (current_theme != String(EditorSettings::get_singleton()->get("text_editor/theme/color_theme"))) { current_theme = EditorSettings::get_singleton()->get("text_editor/theme/color_theme"); EditorSettings::get_singleton()->load_text_editor_theme(); } @@ -2194,6 +2484,23 @@ void ScriptEditor::_editor_settings_changed() { ScriptServer::set_reload_scripts_on_save(EDITOR_DEF("text_editor/files/auto_reload_and_parse_scripts_on_save", true)); } +void ScriptEditor::_filesystem_changed() { + _update_script_names(); +} + +void ScriptEditor::_file_removed(const String &p_removed_file) { + for (int i = 0; i < tab_container->get_child_count(); i++) { + ScriptEditorBase *se = Object::cast_to<ScriptEditorBase>(tab_container->get_child(i)); + if (!se) { + continue; + } + if (se->get_meta("_edit_res_path") == p_removed_file) { + // The script is deleted with no undo, so just close the tab. + _close_tab(i, false, false); + } + } +} + void ScriptEditor::_autosave_scripts() { save_all_scripts(); } @@ -2398,7 +2705,7 @@ void ScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_data, Co } } -void ScriptEditor::_unhandled_input(const Ref<InputEvent> &p_event) { +void ScriptEditor::_unhandled_key_input(const Ref<InputEvent> &p_event) { if (!is_visible_in_tree() || !p_event->is_pressed() || p_event->is_echo()) { return; } @@ -2512,7 +2819,7 @@ void ScriptEditor::set_window_layout(Ref<ConfigFile> p_layout) { String path = scripts[i]; Dictionary script_info = scripts[i]; - if (!script_info.empty()) { + if (!script_info.is_empty()) { path = script_info["path"]; } @@ -2525,7 +2832,7 @@ void ScriptEditor::set_window_layout(Ref<ConfigFile> p_layout) { if (!scr.is_valid()) { continue; } - if (!edit(scr)) { + if (!edit(scr, false)) { continue; } } else { @@ -2534,12 +2841,12 @@ void ScriptEditor::set_window_layout(Ref<ConfigFile> p_layout) { if (error != OK || !text_file.is_valid()) { continue; } - if (!edit(text_file)) { + if (!edit(text_file, false)) { continue; } } - if (!script_info.empty()) { + if (!script_info.is_empty()) { ScriptEditorBase *se = Object::cast_to<ScriptEditorBase>(tab_container->get_child(tab_container->get_tab_count() - 1)); if (se) { se->set_edit_state(script_info["state"]); @@ -2654,6 +2961,18 @@ void ScriptEditor::_help_class_goto(const String &p_desc) { _save_layout(); } +void ScriptEditor::update_doc(const String &p_name) { + ERR_FAIL_COND(!EditorHelp::get_doc_data()->has_doc(p_name)); + + for (int i = 0; i < tab_container->get_child_count(); i++) { + EditorHelp *eh = Object::cast_to<EditorHelp>(tab_container->get_child(i)); + if (eh && eh->get_class() == p_name) { + eh->update_doc(); + return; + } + } +} + void ScriptEditor::_update_selected_editor_menu() { for (int i = 0; i < tab_container->get_child_count(); i++) { bool current = tab_container->get_current_tab() == i; @@ -2753,14 +3072,26 @@ Vector<Ref<Script>> ScriptEditor::get_open_scripts() const { return out_scripts; } -void ScriptEditor::set_scene_root_script(Ref<Script> p_script) { - bool open_dominant = EditorSettings::get_singleton()->get("text_editor/files/open_dominant_script_on_scene_change"); - - if (bool(EditorSettings::get_singleton()->get("text_editor/external/use_external_editor"))) { - return; +Array ScriptEditor::_get_open_script_editors() const { + Array script_editors; + for (int i = 0; i < tab_container->get_child_count(); i++) { + ScriptEditorBase *se = Object::cast_to<ScriptEditorBase>(tab_container->get_child(i)); + if (!se) { + continue; + } + script_editors.push_back(se); } + return script_editors; +} + +void ScriptEditor::set_scene_root_script(Ref<Script> p_script) { + // Don't open dominant script if using an external editor. + const bool use_external_editor = + EditorSettings::get_singleton()->get("text_editor/external/use_external_editor") || + (p_script.is_valid() && p_script->get_language()->overrides_external_editor()); + const bool open_dominant = EditorSettings::get_singleton()->get("text_editor/files/open_dominant_script_on_scene_change"); - if (open_dominant && p_script.is_valid()) { + if (open_dominant && !use_external_editor && p_script.is_valid()) { edit(p_script); } } @@ -2798,12 +3129,18 @@ void ScriptEditor::_open_script_request(const String &p_path) { } } -int ScriptEditor::syntax_highlighters_func_count = 0; -CreateSyntaxHighlighterFunc ScriptEditor::syntax_highlighters_funcs[ScriptEditor::SYNTAX_HIGHLIGHTER_FUNC_MAX]; +void ScriptEditor::register_syntax_highlighter(const Ref<EditorSyntaxHighlighter> &p_syntax_highlighter) { + ERR_FAIL_COND(p_syntax_highlighter.is_null()); -void ScriptEditor::register_create_syntax_highlighter_function(CreateSyntaxHighlighterFunc p_func) { - ERR_FAIL_COND(syntax_highlighters_func_count == SYNTAX_HIGHLIGHTER_FUNC_MAX); - syntax_highlighters_funcs[syntax_highlighters_func_count++] = p_func; + if (syntax_highlighters.find(p_syntax_highlighter) == -1) { + syntax_highlighters.push_back(p_syntax_highlighter); + } +} + +void ScriptEditor::unregister_syntax_highlighter(const Ref<EditorSyntaxHighlighter> &p_syntax_highlighter) { + ERR_FAIL_COND(p_syntax_highlighter.is_null()); + + syntax_highlighters.erase(p_syntax_highlighter); } int ScriptEditor::script_editor_func_count = 0; @@ -2908,10 +3245,16 @@ void ScriptEditor::_bind_methods() { ClassDB::bind_method("_update_script_connections", &ScriptEditor::_update_script_connections); ClassDB::bind_method("_help_class_open", &ScriptEditor::_help_class_open); ClassDB::bind_method("_live_auto_reload_running_scripts", &ScriptEditor::_live_auto_reload_running_scripts); - ClassDB::bind_method("_unhandled_input", &ScriptEditor::_unhandled_input); + ClassDB::bind_method("_unhandled_key_input", &ScriptEditor::_unhandled_key_input); ClassDB::bind_method("_update_members_overview", &ScriptEditor::_update_members_overview); ClassDB::bind_method("_update_recent_scripts", &ScriptEditor::_update_recent_scripts); + ClassDB::bind_method("get_current_editor", &ScriptEditor::_get_current_editor); + ClassDB::bind_method("get_open_script_editors", &ScriptEditor::_get_open_script_editors); + + ClassDB::bind_method(D_METHOD("register_syntax_highlighter", "syntax_highlighter"), &ScriptEditor::register_syntax_highlighter); + ClassDB::bind_method(D_METHOD("unregister_syntax_highlighter", "syntax_highlighter"), &ScriptEditor::unregister_syntax_highlighter); + ClassDB::bind_method(D_METHOD("get_drag_data_fw", "point", "from"), &ScriptEditor::get_drag_data_fw); ClassDB::bind_method(D_METHOD("can_drop_data_fw", "point", "data", "from"), &ScriptEditor::can_drop_data_fw); ClassDB::bind_method(D_METHOD("drop_data_fw", "point", "data", "from"), &ScriptEditor::drop_data_fw); @@ -2989,7 +3332,8 @@ ScriptEditor::ScriptEditor(EditorNode *p_editor) { filename->add_theme_style_override("normal", EditorNode::get_singleton()->get_gui_base()->get_theme_stylebox("normal", "LineEdit")); buttons_hbox->add_child(filename); - members_overview_alphabeta_sort_button = memnew(ToolButton); + members_overview_alphabeta_sort_button = memnew(Button); + members_overview_alphabeta_sort_button->set_flat(true); members_overview_alphabeta_sort_button->set_tooltip(TTR("Toggle alphabetical sorting of the method list.")); members_overview_alphabeta_sort_button->set_toggle_mode(true); members_overview_alphabeta_sort_button->set_pressed(EditorSettings::get_singleton()->get("text_editor/tools/sort_members_outline_alphabetically")); @@ -3028,12 +3372,13 @@ ScriptEditor::ScriptEditor(EditorNode *p_editor) { ED_SHORTCUT("script_editor/window_move_down", TTR("Move Down"), KEY_MASK_SHIFT | KEY_MASK_ALT | KEY_DOWN); ED_SHORTCUT("script_editor/next_script", TTR("Next script"), KEY_MASK_CMD | KEY_MASK_SHIFT | KEY_PERIOD); // these should be KEY_GREATER and KEY_LESS but those don't work ED_SHORTCUT("script_editor/prev_script", TTR("Previous script"), KEY_MASK_CMD | KEY_MASK_SHIFT | KEY_COMMA); - set_process_unhandled_input(true); + set_process_unhandled_key_input(true); file_menu = memnew(MenuButton); - menu_hb->add_child(file_menu); file_menu->set_text(TTR("File")); file_menu->set_switch_on_hover(true); + file_menu->set_shortcut_context(this); + menu_hb->add_child(file_menu); file_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/new", TTR("New Script...")), FILE_NEW); file_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/new_textfile", TTR("New Text File...")), FILE_NEW_TEXTFILE); @@ -3050,7 +3395,7 @@ ScriptEditor::ScriptEditor(EditorNode *p_editor) { file_menu->get_popup()->add_separator(); file_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/save", TTR("Save"), KEY_MASK_ALT | KEY_MASK_CMD | KEY_S), FILE_SAVE); file_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/save_as", TTR("Save As...")), FILE_SAVE_AS); - file_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/save_all", TTR("Save All"), KEY_MASK_CMD | KEY_MASK_SHIFT | KEY_MASK_ALT | KEY_S), FILE_SAVE_ALL); + file_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/save_all", TTR("Save All"), KEY_MASK_SHIFT | KEY_MASK_ALT | KEY_S), FILE_SAVE_ALL); file_menu->get_popup()->add_separator(); file_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/reload_script_soft", TTR("Soft Reload Script"), KEY_MASK_CMD | KEY_MASK_ALT | KEY_R), FILE_TOOL_RELOAD_SOFT); file_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/copy_path", TTR("Copy Script Path")), FILE_COPY_PATH); @@ -3088,10 +3433,11 @@ ScriptEditor::ScriptEditor(EditorNode *p_editor) { file_menu->get_popup()->connect("id_pressed", callable_mp(this, &ScriptEditor::_menu_option)); script_search_menu = memnew(MenuButton); - menu_hb->add_child(script_search_menu); script_search_menu->set_text(TTR("Search")); script_search_menu->set_switch_on_hover(true); + script_search_menu->set_shortcut_context(this); script_search_menu->get_popup()->connect("id_pressed", callable_mp(this, &ScriptEditor::_menu_option)); + menu_hb->add_child(script_search_menu); MenuButton *debug_menu = memnew(MenuButton); menu_hb->add_child(debug_menu); @@ -3116,13 +3462,15 @@ ScriptEditor::ScriptEditor(EditorNode *p_editor) { menu_hb->add_spacer(); - site_search = memnew(ToolButton); + site_search = memnew(Button); + site_search->set_flat(true); site_search->set_text(TTR("Online Docs")); site_search->connect("pressed", callable_mp(this, &ScriptEditor::_menu_option), varray(SEARCH_WEBSITE)); menu_hb->add_child(site_search); site_search->set_tooltip(TTR("Open Godot online documentation.")); - help_search = memnew(ToolButton); + help_search = memnew(Button); + help_search->set_flat(true); help_search->set_text(TTR("Search Help")); help_search->connect("pressed", callable_mp(this, &ScriptEditor::_menu_option), varray(SEARCH_HELP)); menu_hb->add_child(help_search); @@ -3130,13 +3478,15 @@ ScriptEditor::ScriptEditor(EditorNode *p_editor) { menu_hb->add_child(memnew(VSeparator)); - script_back = memnew(ToolButton); + script_back = memnew(Button); + script_back->set_flat(true); script_back->connect("pressed", callable_mp(this, &ScriptEditor::_history_back)); menu_hb->add_child(script_back); script_back->set_disabled(true); script_back->set_tooltip(TTR("Go to previous edited document.")); - script_forward = memnew(ToolButton); + script_forward = memnew(Button); + script_forward->set_flat(true); script_forward->connect("pressed", callable_mp(this, &ScriptEditor::_history_forward)); menu_hb->add_child(script_forward); script_forward->set_disabled(true); @@ -3145,8 +3495,8 @@ ScriptEditor::ScriptEditor(EditorNode *p_editor) { tab_container->connect("tab_changed", callable_mp(this, &ScriptEditor::_tab_changed)); erase_tab_confirm = memnew(ConfirmationDialog); - erase_tab_confirm->get_ok()->set_text(TTR("Save")); - erase_tab_confirm->add_button(TTR("Discard"), DisplayServer::get_singleton()->get_swap_ok_cancel(), "discard"); + erase_tab_confirm->get_ok_button()->set_text(TTR("Save")); + erase_tab_confirm->add_button(TTR("Discard"), DisplayServer::get_singleton()->get_swap_cancel_ok(), "discard"); erase_tab_confirm->connect("confirmed", callable_mp(this, &ScriptEditor::_close_current_tab)); erase_tab_confirm->connect("custom_action", callable_mp(this, &ScriptEditor::_close_discard_current_tab)); add_child(erase_tab_confirm); @@ -3178,9 +3528,9 @@ ScriptEditor::ScriptEditor(EditorNode *p_editor) { disk_changed_list->set_v_size_flags(SIZE_EXPAND_FILL); disk_changed->connect("confirmed", callable_mp(this, &ScriptEditor::_reload_scripts)); - disk_changed->get_ok()->set_text(TTR("Reload")); + disk_changed->get_ok_button()->set_text(TTR("Reload")); - disk_changed->add_button(TTR("Resave"), !DisplayServer::get_singleton()->get_swap_ok_cancel(), "resave"); + disk_changed->add_button(TTR("Resave"), !DisplayServer::get_singleton()->get_swap_cancel_ok(), "resave"); disk_changed->connect("custom_action", callable_mp(this, &ScriptEditor::_resave_scripts)); } @@ -3309,7 +3659,7 @@ void ScriptEditorPlugin::edited_scene_changed() { ScriptEditorPlugin::ScriptEditorPlugin(EditorNode *p_node) { editor = p_node; script_editor = memnew(ScriptEditor(p_node)); - editor->get_viewport()->add_child(script_editor); + editor->get_main_control()->add_child(script_editor); script_editor->set_v_size_flags(Control::SIZE_EXPAND_FILL); script_editor->hide(); diff --git a/editor/plugins/script_editor_plugin.h b/editor/plugins/script_editor_plugin.h index f7352be7e8..09ed3854ea 100644 --- a/editor/plugins/script_editor_plugin.h +++ b/editor/plugins/script_editor_plugin.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -31,7 +31,7 @@ #ifndef SCRIPT_EDITOR_PLUGIN_H #define SCRIPT_EDITOR_PLUGIN_H -#include "core/script_language.h" +#include "core/object/script_language.h" #include "editor/code_editor.h" #include "editor/editor_help.h" #include "editor/editor_help_search.h" @@ -43,11 +43,57 @@ #include "scene/gui/split_container.h" #include "scene/gui/tab_container.h" #include "scene/gui/text_edit.h" -#include "scene/gui/tool_button.h" #include "scene/gui/tree.h" #include "scene/main/timer.h" #include "scene/resources/text_file.h" +class EditorSyntaxHighlighter : public SyntaxHighlighter { + GDCLASS(EditorSyntaxHighlighter, SyntaxHighlighter) + +private: + REF edited_resourse; + +protected: + static void _bind_methods(); + +public: + virtual String _get_name() const; + virtual Array _get_supported_languages() const; + + void _set_edited_resource(const RES &p_res) { edited_resourse = p_res; } + REF _get_edited_resource() { return edited_resourse; } + + virtual Ref<EditorSyntaxHighlighter> _create() const; +}; + +class EditorStandardSyntaxHighlighter : public EditorSyntaxHighlighter { + GDCLASS(EditorStandardSyntaxHighlighter, EditorSyntaxHighlighter) + +private: + Ref<CodeHighlighter> highlighter; + +public: + virtual void _update_cache() override; + virtual Dictionary _get_line_syntax_highlighting(int p_line) override { return highlighter->get_line_syntax_highlighting(p_line); } + + virtual String _get_name() const override { return TTR("Standard"); } + + virtual Ref<EditorSyntaxHighlighter> _create() const override; + + EditorStandardSyntaxHighlighter() { highlighter.instance(); } +}; + +class EditorPlainTextSyntaxHighlighter : public EditorSyntaxHighlighter { + GDCLASS(EditorPlainTextSyntaxHighlighter, EditorSyntaxHighlighter) + +public: + virtual String _get_name() const override { return TTR("Plain Text"); } + + virtual Ref<EditorSyntaxHighlighter> _create() const override; +}; + +/////////////////////////////////////////////////////////////////////////////// + class ScriptEditorQuickOpen : public ConfirmationDialog { GDCLASS(ScriptEditorQuickOpen, ConfirmationDialog); @@ -81,13 +127,14 @@ protected: static void _bind_methods(); public: - virtual void add_syntax_highlighter(SyntaxHighlighter *p_highlighter) = 0; - virtual void set_syntax_highlighter(SyntaxHighlighter *p_highlighter) = 0; + virtual void add_syntax_highlighter(Ref<EditorSyntaxHighlighter> p_highlighter) = 0; + virtual void set_syntax_highlighter(Ref<EditorSyntaxHighlighter> p_highlighter) = 0; virtual void apply_code() = 0; virtual RES get_edited_resource() const = 0; virtual Vector<String> get_functions() = 0; virtual void set_edited_resource(const RES &p_res) = 0; + virtual void enable_editor() = 0; virtual void reload_text() = 0; virtual String get_name() = 0; virtual Ref<Texture2D> get_theme_icon() = 0; @@ -104,7 +151,7 @@ public: virtual void ensure_focus() = 0; virtual void tag_saved_version() = 0; virtual void reload(bool p_soft) {} - virtual void get_breakpoints(List<int> *p_breakpoints) = 0; + virtual Array get_breakpoints() = 0; virtual void add_callback(const String &p_function, PackedStringArray p_args) = 0; virtual void update_settings() = 0; virtual void set_debugger_active(bool p_active) = 0; @@ -121,7 +168,6 @@ public: ScriptEditorBase() {} }; -typedef SyntaxHighlighter *(*CreateSyntaxHighlighterFunc)(); typedef ScriptEditorBase *(*CreateScriptEditorFunc)(const RES &p_resource); class EditorScriptCodeCompletionCache; @@ -211,7 +257,7 @@ class ScriptEditor : public PanelContainer { VBoxContainer *overview_vbox; HBoxContainer *buttons_hbox; Label *filename; - ToolButton *members_overview_alphabeta_sort_button; + Button *members_overview_alphabeta_sort_button; bool members_overview_enabled; ItemList *help_overview; bool help_overview_enabled; @@ -221,15 +267,15 @@ class ScriptEditor : public PanelContainer { AcceptDialog *error_dialog; ConfirmationDialog *erase_tab_confirm; ScriptCreateDialog *script_create_dialog; - ToolButton *scripts_visible; + Button *scripts_visible; String current_theme; TextureRect *script_icon; Label *script_name_label; - ToolButton *script_back; - ToolButton *script_forward; + Button *script_back; + Button *script_forward; FindInFilesDialog *find_in_files_dialog; FindInFilesPanel *find_in_files; @@ -237,17 +283,15 @@ class ScriptEditor : public PanelContainer { enum { SCRIPT_EDITOR_FUNC_MAX = 32, - SYNTAX_HIGHLIGHTER_FUNC_MAX = 32 }; static int script_editor_func_count; static CreateScriptEditorFunc script_editor_funcs[SCRIPT_EDITOR_FUNC_MAX]; - static int syntax_highlighters_func_count; - static CreateSyntaxHighlighterFunc syntax_highlighters_funcs[SYNTAX_HIGHLIGHTER_FUNC_MAX]; + Vector<Ref<EditorSyntaxHighlighter>> syntax_highlighters; struct ScriptHistory { - Control *control; + Control *control = nullptr; Variant state; }; @@ -323,9 +367,12 @@ class ScriptEditor : public PanelContainer { void _script_created(Ref<Script> p_script); ScriptEditorBase *_get_current_editor() const; + Array _get_open_script_editors() const; void _save_layout(); void _editor_settings_changed(); + void _filesystem_changed(); + void _file_removed(const String &p_file); void _autosave_scripts(); void _update_autosave_timer(); @@ -355,7 +402,7 @@ class ScriptEditor : public PanelContainer { bool can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const; void drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from); - void _unhandled_input(const Ref<InputEvent> &p_event); + void _unhandled_key_input(const Ref<InputEvent> &p_event); void _script_list_gui_input(const Ref<InputEvent> &ev); void _make_script_list_context_menu(); @@ -406,7 +453,6 @@ public: bool toggle_scripts_panel(); bool is_scripts_panel_toggled(); - void ensure_focus_current(); void apply_scripts() const; void open_script_create_dialog(const String &p_base_name, const String &p_base_path); @@ -435,6 +481,7 @@ public: void close_builtin_scripts_from_scene(const String &p_scene); void goto_help(const String &p_desc) { _help_class_goto(p_desc); } + void update_doc(const String &p_name); bool can_take_away_focus() const; @@ -442,7 +489,9 @@ public: void set_live_auto_reload_running_scripts(bool p_enabled); - static void register_create_syntax_highlighter_function(CreateSyntaxHighlighterFunc p_func); + void register_syntax_highlighter(const Ref<EditorSyntaxHighlighter> &p_syntax_highlighter); + void unregister_syntax_highlighter(const Ref<EditorSyntaxHighlighter> &p_syntax_highlighter); + static void register_create_script_editor_function(CreateScriptEditorFunc p_func); ScriptEditor(EditorNode *p_editor); @@ -456,25 +505,25 @@ class ScriptEditorPlugin : public EditorPlugin { EditorNode *editor; public: - virtual String get_name() const { return "Script"; } - bool has_main_screen() const { return true; } - virtual void edit(Object *p_object); - virtual bool handles(Object *p_object) const; - virtual void make_visible(bool p_visible); - virtual void selected_notify(); + virtual String get_name() const override { return "Script"; } + bool has_main_screen() const override { return true; } + virtual void edit(Object *p_object) override; + virtual bool handles(Object *p_object) const override; + virtual void make_visible(bool p_visible) override; + virtual void selected_notify() override; - virtual void save_external_data(); - virtual void apply_changes(); + virtual void save_external_data() override; + virtual void apply_changes() override; - virtual void restore_global_state(); - virtual void save_global_state(); + virtual void restore_global_state() override; + virtual void save_global_state() override; - virtual void set_window_layout(Ref<ConfigFile> p_layout); - virtual void get_window_layout(Ref<ConfigFile> p_layout); + virtual void set_window_layout(Ref<ConfigFile> p_layout) override; + virtual void get_window_layout(Ref<ConfigFile> p_layout) override; - virtual void get_breakpoints(List<String> *p_breakpoints); + virtual void get_breakpoints(List<String> *p_breakpoints) override; - virtual void edited_scene_changed(); + virtual void edited_scene_changed() override; ScriptEditorPlugin(EditorNode *p_node); ~ScriptEditorPlugin(); diff --git a/editor/plugins/script_text_editor.cpp b/editor/plugins/script_text_editor.cpp index e7f8a56e5e..b6df66b8af 100644 --- a/editor/plugins/script_text_editor.cpp +++ b/editor/plugins/script_text_editor.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -84,10 +84,10 @@ ConnectionInfoDialog::ConnectionInfoDialog() { set_title(TTR("Connections to method:")); VBoxContainer *vbc = memnew(VBoxContainer); - vbc->set_anchor_and_margin(MARGIN_LEFT, Control::ANCHOR_BEGIN, 8 * EDSCALE); - vbc->set_anchor_and_margin(MARGIN_TOP, Control::ANCHOR_BEGIN, 8 * EDSCALE); - vbc->set_anchor_and_margin(MARGIN_RIGHT, Control::ANCHOR_END, -8 * EDSCALE); - vbc->set_anchor_and_margin(MARGIN_BOTTOM, Control::ANCHOR_END, -8 * EDSCALE); + vbc->set_anchor_and_offset(SIDE_LEFT, Control::ANCHOR_BEGIN, 8 * EDSCALE); + vbc->set_anchor_and_offset(SIDE_TOP, Control::ANCHOR_BEGIN, 8 * EDSCALE); + vbc->set_anchor_and_offset(SIDE_RIGHT, Control::ANCHOR_END, -8 * EDSCALE); + vbc->set_anchor_and_offset(SIDE_BOTTOM, Control::ANCHOR_END, -8 * EDSCALE); add_child(vbc); method = memnew(Label); @@ -111,7 +111,7 @@ ConnectionInfoDialog::ConnectionInfoDialog() { Vector<String> ScriptTextEditor::get_functions() { String errortxt; int line = -1, col; - TextEdit *te = code_editor->get_text_edit(); + CodeEdit *te = code_editor->get_text_editor(); String text = te->get_text(); List<String> fnc; @@ -130,9 +130,9 @@ void ScriptTextEditor::apply_code() { if (script.is_null()) { return; } - script->set_source_code(code_editor->get_text_edit()->get_text()); + script->set_source_code(code_editor->get_text_editor()->get_text()); script->update_exports(); - _update_member_keywords(); + code_editor->get_text_editor()->get_syntax_highlighter()->update_cache(); } RES ScriptTextEditor::get_edited_resource() const { @@ -140,58 +140,45 @@ RES ScriptTextEditor::get_edited_resource() const { } void ScriptTextEditor::set_edited_resource(const RES &p_res) { - ERR_FAIL_COND(!script.is_null()); + ERR_FAIL_COND(script.is_valid()); + ERR_FAIL_COND(p_res.is_null()); script = p_res; - _set_theme_for_script(); - code_editor->get_text_edit()->set_text(script->get_source_code()); - code_editor->get_text_edit()->clear_undo_history(); - code_editor->get_text_edit()->tag_saved_version(); + code_editor->get_text_editor()->set_text(script->get_source_code()); + code_editor->get_text_editor()->clear_undo_history(); + code_editor->get_text_editor()->tag_saved_version(); emit_signal("name_changed"); code_editor->update_line_and_column(); - - _validate_script(); } -void ScriptTextEditor::_update_member_keywords() { - member_keywords.clear(); - code_editor->get_text_edit()->clear_member_keywords(); - Color member_variable_color = EDITOR_GET("text_editor/highlighting/member_variable_color"); - - StringName instance_base = script->get_instance_base_type(); - - if (instance_base == StringName()) { +void ScriptTextEditor::enable_editor() { + if (editor_enabled) { return; } - List<PropertyInfo> plist; - ClassDB::get_property_list(instance_base, &plist); - for (List<PropertyInfo>::Element *E = plist.front(); E; E = E->next()) { - String name = E->get().name; - if (E->get().usage & PROPERTY_USAGE_CATEGORY || E->get().usage & PROPERTY_USAGE_GROUP || E->get().usage & PROPERTY_USAGE_SUBGROUP) { - continue; - } - if (name.find("/") != -1) { - continue; - } - - code_editor->get_text_edit()->add_member_keyword(name, member_variable_color); - } + editor_enabled = true; - List<String> clist; - ClassDB::get_integer_constant_list(instance_base, &clist); + _enable_code_editor(); + _set_theme_for_script(); - for (List<String>::Element *E = clist.front(); E; E = E->next()) { - code_editor->get_text_edit()->add_member_keyword(E->get(), member_variable_color); - } + _validate_script(); } void ScriptTextEditor::_load_theme_settings() { - TextEdit *text_edit = code_editor->get_text_edit(); - - text_edit->clear_colors(); + CodeEdit *text_edit = code_editor->get_text_editor(); + text_edit->clear_keywords(); + + Color updated_safe_line_number_color = EDITOR_GET("text_editor/highlighting/safe_line_number_color"); + if (updated_safe_line_number_color != safe_line_number_color) { + safe_line_number_color = updated_safe_line_number_color; + for (int i = 0; i < text_edit->get_line_count(); i++) { + if (text_edit->get_line_gutter_item_color(i, line_number_gutter) != default_line_number_color) { + text_edit->set_line_gutter_item_color(i, line_number_gutter, safe_line_number_color); + } + } + } Color background_color = EDITOR_GET("text_editor/highlighting/background_color"); Color completion_background_color = EDITOR_GET("text_editor/highlighting/completion_background_color"); @@ -201,7 +188,6 @@ void ScriptTextEditor::_load_theme_settings() { Color completion_font_color = EDITOR_GET("text_editor/highlighting/completion_font_color"); Color text_color = EDITOR_GET("text_editor/highlighting/text_color"); Color line_number_color = EDITOR_GET("text_editor/highlighting/line_number_color"); - Color safe_line_number_color = EDITOR_GET("text_editor/highlighting/safe_line_number_color"); Color caret_color = EDITOR_GET("text_editor/highlighting/caret_color"); Color caret_background_color = EDITOR_GET("text_editor/highlighting/caret_background_color"); Color text_selected_color = EDITOR_GET("text_editor/highlighting/text_selected_color"); @@ -210,9 +196,6 @@ void ScriptTextEditor::_load_theme_settings() { Color current_line_color = EDITOR_GET("text_editor/highlighting/current_line_color"); Color line_length_guideline_color = EDITOR_GET("text_editor/highlighting/line_length_guideline_color"); Color word_highlighted_color = EDITOR_GET("text_editor/highlighting/word_highlighted_color"); - Color number_color = EDITOR_GET("text_editor/highlighting/number_color"); - Color function_color = EDITOR_GET("text_editor/highlighting/function_color"); - Color member_variable_color = EDITOR_GET("text_editor/highlighting/member_variable_color"); Color mark_color = EDITOR_GET("text_editor/highlighting/mark_color"); Color bookmark_color = EDITOR_GET("text_editor/highlighting/bookmark_color"); Color breakpoint_color = EDITOR_GET("text_editor/highlighting/breakpoint_color"); @@ -220,13 +203,6 @@ void ScriptTextEditor::_load_theme_settings() { Color code_folding_color = EDITOR_GET("text_editor/highlighting/code_folding_color"); Color search_result_color = EDITOR_GET("text_editor/highlighting/search_result_color"); Color search_result_border_color = EDITOR_GET("text_editor/highlighting/search_result_border_color"); - Color symbol_color = EDITOR_GET("text_editor/highlighting/symbol_color"); - Color keyword_color = EDITOR_GET("text_editor/highlighting/keyword_color"); - Color basetype_color = EDITOR_GET("text_editor/highlighting/base_type_color"); - Color type_color = EDITOR_GET("text_editor/highlighting/engine_type_color"); - Color usertype_color = EDITOR_GET("text_editor/highlighting/user_type_color"); - Color comment_color = EDITOR_GET("text_editor/highlighting/comment_color"); - Color string_color = EDITOR_GET("text_editor/highlighting/string_color"); text_edit->add_theme_color_override("background_color", background_color); text_edit->add_theme_color_override("completion_background_color", completion_background_color); @@ -236,18 +212,14 @@ void ScriptTextEditor::_load_theme_settings() { text_edit->add_theme_color_override("completion_font_color", completion_font_color); text_edit->add_theme_color_override("font_color", text_color); text_edit->add_theme_color_override("line_number_color", line_number_color); - text_edit->add_theme_color_override("safe_line_number_color", safe_line_number_color); text_edit->add_theme_color_override("caret_color", caret_color); text_edit->add_theme_color_override("caret_background_color", caret_background_color); - text_edit->add_theme_color_override("font_color_selected", text_selected_color); + text_edit->add_theme_color_override("font_selected_color", text_selected_color); text_edit->add_theme_color_override("selection_color", selection_color); text_edit->add_theme_color_override("brace_mismatch_color", brace_mismatch_color); text_edit->add_theme_color_override("current_line_color", current_line_color); text_edit->add_theme_color_override("line_length_guideline_color", line_length_guideline_color); text_edit->add_theme_color_override("word_highlighted_color", word_highlighted_color); - text_edit->add_theme_color_override("number_color", number_color); - text_edit->add_theme_color_override("function_color", function_color); - text_edit->add_theme_color_override("member_variable_color", member_variable_color); text_edit->add_theme_color_override("bookmark_color", bookmark_color); text_edit->add_theme_color_override("breakpoint_color", breakpoint_color); text_edit->add_theme_color_override("executing_line_color", executing_line_color); @@ -255,18 +227,9 @@ void ScriptTextEditor::_load_theme_settings() { text_edit->add_theme_color_override("code_folding_color", code_folding_color); text_edit->add_theme_color_override("search_result_color", search_result_color); text_edit->add_theme_color_override("search_result_border_color", search_result_border_color); - text_edit->add_theme_color_override("symbol_color", symbol_color); text_edit->add_theme_constant_override("line_spacing", EDITOR_DEF("text_editor/theme/line_spacing", 6)); - colors_cache.symbol_color = symbol_color; - colors_cache.keyword_color = keyword_color; - colors_cache.basetype_color = basetype_color; - colors_cache.type_color = type_color; - colors_cache.usertype_color = usertype_color; - colors_cache.comment_color = comment_color; - colors_cache.string_color = string_color; - theme_loaded = true; if (!script.is_null()) { _set_theme_for_script(); @@ -278,104 +241,48 @@ void ScriptTextEditor::_set_theme_for_script() { return; } - TextEdit *text_edit = code_editor->get_text_edit(); + CodeEdit *text_edit = code_editor->get_text_editor(); + text_edit->get_syntax_highlighter()->update_cache(); - List<String> keywords; - script->get_language()->get_reserved_words(&keywords); + /* add keywords for auto completion */ + // singleton autoloads (as types, just as engine singletons are) + Map<StringName, ProjectSettings::AutoloadInfo> autoloads = ProjectSettings::get_singleton()->get_autoload_list(); + for (Map<StringName, ProjectSettings::AutoloadInfo>::Element *E = autoloads.front(); E; E = E->next()) { + const ProjectSettings::AutoloadInfo &info = E->value(); + if (info.is_singleton) { + text_edit->add_keyword(info.name); + } + } - for (List<String>::Element *E = keywords.front(); E; E = E->next()) { - text_edit->add_keyword_color(E->get(), colors_cache.keyword_color); - } - - //colorize core types - const Color basetype_color = colors_cache.basetype_color; - text_edit->add_keyword_color("String", basetype_color); - text_edit->add_keyword_color("Vector2", basetype_color); - text_edit->add_keyword_color("Vector2i", basetype_color); - text_edit->add_keyword_color("Rect2", basetype_color); - text_edit->add_keyword_color("Rect2i", basetype_color); - text_edit->add_keyword_color("Vector3", basetype_color); - text_edit->add_keyword_color("Vector3i", basetype_color); - text_edit->add_keyword_color("Transform2D", basetype_color); - text_edit->add_keyword_color("Plane", basetype_color); - text_edit->add_keyword_color("Quat", basetype_color); - text_edit->add_keyword_color("AABB", basetype_color); - text_edit->add_keyword_color("Basis", basetype_color); - text_edit->add_keyword_color("Transform", basetype_color); - text_edit->add_keyword_color("Color", basetype_color); - text_edit->add_keyword_color("StringName", basetype_color); - text_edit->add_keyword_color("NodePath", basetype_color); - text_edit->add_keyword_color("RID", basetype_color); - text_edit->add_keyword_color("Object", basetype_color); - text_edit->add_keyword_color("Callable", basetype_color); - text_edit->add_keyword_color("Dictionary", basetype_color); - text_edit->add_keyword_color("Array", basetype_color); - text_edit->add_keyword_color("PackedByteArray", basetype_color); - text_edit->add_keyword_color("PackedInt32Array", basetype_color); - text_edit->add_keyword_color("PackedInt64Array", basetype_color); - text_edit->add_keyword_color("PackedFloat32Array", basetype_color); - text_edit->add_keyword_color("PackedFloat64Array", basetype_color); - text_edit->add_keyword_color("PackedStringArray", basetype_color); - text_edit->add_keyword_color("PackedVector2Array", basetype_color); - text_edit->add_keyword_color("PackedVector3Array", basetype_color); - text_edit->add_keyword_color("PackedColorArray", basetype_color); - - //colorize engine types + // engine types List<StringName> types; ClassDB::get_class_list(&types); - for (List<StringName>::Element *E = types.front(); E; E = E->next()) { String n = E->get(); if (n.begins_with("_")) { n = n.substr(1, n.length()); } - - text_edit->add_keyword_color(n, colors_cache.type_color); + text_edit->add_keyword(n); } - _update_member_keywords(); - //colorize user types + // user types List<StringName> global_classes; ScriptServer::get_global_class_list(&global_classes); - for (List<StringName>::Element *E = global_classes.front(); E; E = E->next()) { - text_edit->add_keyword_color(E->get(), colors_cache.usertype_color); - } - - //colorize singleton autoloads (as types, just as engine singletons are) - List<PropertyInfo> props; - ProjectSettings::get_singleton()->get_property_list(&props); - for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) { - String s = E->get().name; - if (!s.begins_with("autoload/")) { - continue; - } - String path = ProjectSettings::get_singleton()->get(s); - if (path.begins_with("*")) { - text_edit->add_keyword_color(s.get_slice("/", 1), colors_cache.usertype_color); - } + text_edit->add_keyword(E->get()); } - //colorize comments - List<String> comments; - script->get_language()->get_comment_delimiters(&comments); - - for (List<String>::Element *E = comments.front(); E; E = E->next()) { - String comment = E->get(); - String beg = comment.get_slice(" ", 0); - String end = comment.get_slice_count(" ") > 1 ? comment.get_slice(" ", 1) : String(); - - text_edit->add_color_region(beg, end, colors_cache.comment_color, end == ""); + List<String> keywords; + script->get_language()->get_reserved_words(&keywords); + for (List<String>::Element *E = keywords.front(); E; E = E->next()) { + text_edit->add_keyword(E->get()); } - //colorize strings - List<String> strings; - script->get_language()->get_string_delimiters(&strings); - for (List<String>::Element *E = strings.front(); E; E = E->next()) { - String string = E->get(); - String beg = string.get_slice(" ", 0); - String end = string.get_slice_count(" ") > 1 ? string.get_slice(" ", 1) : String(); - text_edit->add_color_region(beg, end, colors_cache.string_color, end == ""); + // core types + List<String> core_types; + script->get_language()->get_core_type_words(&core_types); + for (List<String>::Element *E = core_types.front(); E; E = E->next()) { + text_edit->add_keyword(E->get()); } } @@ -383,16 +290,12 @@ void ScriptTextEditor::_show_warnings_panel(bool p_show) { warnings_panel->set_visible(p_show); } -void ScriptTextEditor::_error_pressed() { - code_editor->goto_error(); -} - void ScriptTextEditor::_warning_clicked(Variant p_line) { if (p_line.get_type() == Variant::INT) { - code_editor->get_text_edit()->cursor_set_line(p_line.operator int64_t()); + code_editor->get_text_editor()->cursor_set_line(p_line.operator int64_t()); } else if (p_line.get_type() == Variant::DICTIONARY) { Dictionary meta = p_line.operator Dictionary(); - code_editor->get_text_edit()->insert_at("# warning-ignore:" + meta["code"].operator String(), meta["line"].operator int64_t() - 1); + code_editor->get_text_editor()->insert_at("# warning-ignore:" + meta["code"].operator String(), meta["line"].operator int64_t() - 1); _validate_script(); } } @@ -400,7 +303,7 @@ void ScriptTextEditor::_warning_clicked(Variant p_line) { void ScriptTextEditor::reload_text() { ERR_FAIL_COND(script.is_null()); - TextEdit *te = code_editor->get_text_edit(); + CodeEdit *te = code_editor->get_text_editor(); int column = te->cursor_get_column(); int row = te->cursor_get_line(); int h = te->get_h_scroll(); @@ -417,29 +320,21 @@ void ScriptTextEditor::reload_text() { code_editor->update_line_and_column(); } -void ScriptTextEditor::_notification(int p_what) { - switch (p_what) { - case NOTIFICATION_READY: - _load_theme_settings(); - break; - } -} - void ScriptTextEditor::add_callback(const String &p_function, PackedStringArray p_args) { - String code = code_editor->get_text_edit()->get_text(); + String code = code_editor->get_text_editor()->get_text(); int pos = script->get_language()->find_function(p_function, code); if (pos == -1) { //does not exist - code_editor->get_text_edit()->deselect(); - pos = code_editor->get_text_edit()->get_line_count() + 2; + code_editor->get_text_editor()->deselect(); + pos = code_editor->get_text_editor()->get_line_count() + 2; String func = script->get_language()->make_function("", p_function, p_args); //code=code+func; - code_editor->get_text_edit()->cursor_set_line(pos + 1); - code_editor->get_text_edit()->cursor_set_column(1000000); //none shall be that big - code_editor->get_text_edit()->insert_text_at_cursor("\n\n" + func); + code_editor->get_text_editor()->cursor_set_line(pos + 1); + code_editor->get_text_editor()->cursor_set_column(1000000); //none shall be that big + code_editor->get_text_editor()->insert_text_at_cursor("\n\n" + func); } - code_editor->get_text_edit()->cursor_set_line(pos); - code_editor->get_text_edit()->cursor_set_column(1); + code_editor->get_text_editor()->cursor_set_line(pos); + code_editor->get_text_editor()->cursor_set_column(1); } bool ScriptTextEditor::show_members_overview() { @@ -447,11 +342,15 @@ bool ScriptTextEditor::show_members_overview() { } void ScriptTextEditor::update_settings() { + code_editor->get_text_editor()->set_gutter_draw(connection_gutter, EditorSettings::get_singleton()->get("text_editor/appearance/show_info_gutter")); code_editor->update_editor_settings(); } bool ScriptTextEditor::is_unsaved() { - return code_editor->get_text_edit()->get_version() != code_editor->get_text_edit()->get_saved_version(); + const bool unsaved = + code_editor->get_text_editor()->get_version() != code_editor->get_text_editor()->get_saved_version() || + script->get_path().is_empty(); // In memory. + return unsaved; } Variant ScriptTextEditor::get_edit_state() { @@ -468,6 +367,10 @@ void ScriptTextEditor::set_edit_state(const Variant &p_state) { _change_syntax_highlighter(idx); } } + + if (editor_enabled) { + ensure_focus(); + } } void ScriptTextEditor::_convert_case(CodeTextEditor::CaseStyle p_case) { @@ -491,7 +394,7 @@ void ScriptTextEditor::convert_indent_to_tabs() { } void ScriptTextEditor::tag_saved_version() { - code_editor->get_text_edit()->tag_saved_version(); + code_editor->get_text_editor()->tag_saved_version(); } void ScriptTextEditor::goto_line(int p_line, bool p_with_error) { @@ -515,7 +418,7 @@ void ScriptTextEditor::clear_executing_line() { } void ScriptTextEditor::ensure_focus() { - code_editor->get_text_edit()->grab_focus(); + code_editor->get_text_editor()->grab_focus(); } String ScriptTextEditor::get_name() { @@ -524,6 +427,9 @@ String ScriptTextEditor::get_name() { if (script->get_path().find("local://") == -1 && script->get_path().find("::") == -1) { name = script->get_path().get_file(); if (is_unsaved()) { + if (script->get_path().is_empty()) { + name = TTR("[unsaved]"); + } name += "(*)"; } } else if (script->get_name() != "") { @@ -546,7 +452,7 @@ Ref<Texture2D> ScriptTextEditor::get_theme_icon() { void ScriptTextEditor::_validate_script() { String errortxt; int line = -1, col; - TextEdit *te = code_editor->get_text_edit(); + CodeEdit *te = code_editor->get_text_editor(); String text = te->get_text(); List<String> fnc; @@ -564,7 +470,7 @@ void ScriptTextEditor::_validate_script() { if (!script->is_tool()) { script->set_source_code(text); script->update_exports(); - _update_member_keywords(); + te->get_syntax_highlighter()->update_cache(); } functions.clear(); @@ -609,10 +515,22 @@ void ScriptTextEditor::_validate_script() { for (List<ScriptLanguage::Warning>::Element *E = warnings.front(); E; E = E->next()) { ScriptLanguage::Warning w = E->get(); + Dictionary ignore_meta; + ignore_meta["line"] = w.start_line; + ignore_meta["code"] = w.string_code.to_lower(); warnings_panel->push_cell(); - warnings_panel->push_meta(w.line - 1); + warnings_panel->push_meta(ignore_meta); + warnings_panel->push_color( + warnings_panel->get_theme_color("accent_color", "Editor").lerp(warnings_panel->get_theme_color("mono_color", "Editor"), 0.5)); + warnings_panel->add_text(TTR("[Ignore]")); + warnings_panel->pop(); // Color. + warnings_panel->pop(); // Meta ignore. + warnings_panel->pop(); // Cell. + + warnings_panel->push_cell(); + warnings_panel->push_meta(w.start_line - 1); warnings_panel->push_color(warnings_panel->get_theme_color("warning_color", "Editor")); - warnings_panel->add_text(TTR("Line") + " " + itos(w.line)); + warnings_panel->add_text(TTR("Line") + " " + itos(w.start_line)); warnings_panel->add_text(" (" + w.string_code + "):"); warnings_panel->pop(); // Color. warnings_panel->pop(); // Meta goto. @@ -621,15 +539,6 @@ void ScriptTextEditor::_validate_script() { warnings_panel->push_cell(); warnings_panel->add_text(w.message); warnings_panel->pop(); // Cell. - - Dictionary ignore_meta; - ignore_meta["line"] = w.line; - ignore_meta["code"] = w.string_code.to_lower(); - warnings_panel->push_cell(); - warnings_panel->push_meta(ignore_meta); - warnings_panel->add_text(TTR("(ignore)")); - warnings_panel->pop(); // Meta ignore. - warnings_panel->pop(); // Cell. } warnings_panel->pop(); // Table. @@ -640,16 +549,16 @@ void ScriptTextEditor::_validate_script() { te->set_line_as_marked(i, line == i); if (highlight_safe) { if (safe_lines.has(i + 1)) { - te->set_line_as_safe(i, true); + te->set_line_gutter_item_color(i, line_number_gutter, safe_line_number_color); last_is_safe = true; - } else if (last_is_safe && (te->is_line_comment(i) || te->get_line(i).strip_edges().empty())) { - te->set_line_as_safe(i, true); + } else if (last_is_safe && (te->is_line_comment(i) || te->get_line(i).strip_edges().is_empty())) { + te->set_line_gutter_item_color(i, line_number_gutter, safe_line_number_color); } else { - te->set_line_as_safe(i, false); + te->set_line_gutter_item_color(i, line_number_gutter, default_line_number_color); last_is_safe = false; } } else { - te->set_line_as_safe(i, false); + te->set_line_gutter_item_color(line, 1, default_line_number_color); } } @@ -666,7 +575,7 @@ void ScriptTextEditor::_update_bookmark_list() { bookmarks_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/goto_next_bookmark"), BOOKMARK_GOTO_NEXT); bookmarks_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/goto_previous_bookmark"), BOOKMARK_GOTO_PREV); - Array bookmark_list = code_editor->get_text_edit()->get_bookmarks_array(); + Array bookmark_list = code_editor->get_text_editor()->get_bookmarked_lines(); if (bookmark_list.size() == 0) { return; } @@ -676,7 +585,7 @@ void ScriptTextEditor::_update_bookmark_list() { for (int i = 0; i < bookmark_list.size(); i++) { // Strip edges to remove spaces or tabs. // Also replace any tabs by spaces, since we can't print tabs in the menu. - String line = code_editor->get_text_edit()->get_line(bookmark_list[i]).replace("\t", " ").strip_edges(); + String line = code_editor->get_text_editor()->get_line(bookmark_list[i]).replace("\t", " ").strip_edges(); // Limit the size of the line if too big. if (line.length() > 50) { @@ -693,7 +602,7 @@ void ScriptTextEditor::_bookmark_item_pressed(int p_idx) { _edit_option(bookmarks_menu->get_item_id(p_idx)); } else { code_editor->goto_line(bookmarks_menu->get_item_metadata(p_idx)); - code_editor->get_text_edit()->call_deferred("center_viewport_to_cursor"); //Need to be deferred, because goto uses call_deferred(). + code_editor->get_text_editor()->call_deferred("center_viewport_to_cursor"); //Need to be deferred, because goto uses call_deferred(). } } @@ -779,7 +688,7 @@ void ScriptEditor::_update_modified_scripts_for_external_editor(Ref<Script> p_fo uint64_t date = FileAccess::get_modified_time(script->get_path()); if (last_date != date) { - Ref<Script> rel_script = ResourceLoader::load(script->get_path(), script->get_class(), true); + Ref<Script> rel_script = ResourceLoader::load(script->get_path(), script->get_class(), ResourceFormatLoader::CACHE_MODE_IGNORE); ERR_CONTINUE(!rel_script.is_valid()); script->set_source_code(rel_script->get_source_code()); script->set_last_modified_time(rel_script->get_last_modified_time()); @@ -804,7 +713,7 @@ void ScriptTextEditor::_code_complete_script(const String &p_code, List<ScriptCo String hint; Error err = script->get_language()->complete_code(p_code, script->get_path(), base, r_options, r_force, hint); if (err == OK) { - code_editor->get_text_edit()->set_code_hint(hint); + code_editor->get_text_editor()->set_code_hint(hint); } } @@ -817,7 +726,7 @@ void ScriptTextEditor::_update_breakpoint_list() { breakpoints_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/goto_next_breakpoint"), DEBUG_GOTO_NEXT_BREAKPOINT); breakpoints_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/goto_previous_breakpoint"), DEBUG_GOTO_PREV_BREAKPOINT); - Array breakpoint_list = code_editor->get_text_edit()->get_breakpoints_array(); + Array breakpoint_list = code_editor->get_text_editor()->get_breakpointed_lines(); if (breakpoint_list.size() == 0) { return; } @@ -827,7 +736,7 @@ void ScriptTextEditor::_update_breakpoint_list() { for (int i = 0; i < breakpoint_list.size(); i++) { // Strip edges to remove spaces or tabs. // Also replace any tabs by spaces, since we can't print tabs in the menu. - String line = code_editor->get_text_edit()->get_line(breakpoint_list[i]).replace("\t", " ").strip_edges(); + String line = code_editor->get_text_editor()->get_line(breakpoint_list[i]).replace("\t", " ").strip_edges(); // Limit the size of the line if too big. if (line.length() > 50) { @@ -844,12 +753,12 @@ void ScriptTextEditor::_breakpoint_item_pressed(int p_idx) { _edit_option(breakpoints_menu->get_item_id(p_idx)); } else { code_editor->goto_line(breakpoints_menu->get_item_metadata(p_idx)); - code_editor->get_text_edit()->call_deferred("center_viewport_to_cursor"); //Need to be deferred, because goto uses call_deferred(). + code_editor->get_text_editor()->call_deferred("center_viewport_to_cursor"); //Need to be deferred, because goto uses call_deferred(). } } void ScriptTextEditor::_breakpoint_toggled(int p_row) { - EditorDebuggerNode::get_singleton()->set_breakpoint(script->get_path(), p_row + 1, code_editor->get_text_edit()->is_line_set_as_breakpoint(p_row)); + EditorDebuggerNode::get_singleton()->set_breakpoint(script->get_path(), p_row + 1, code_editor->get_text_editor()->is_line_breakpointed(p_row)); } void ScriptTextEditor::_lookup_symbol(const String &p_symbol, int p_row, int p_column) { @@ -871,7 +780,7 @@ void ScriptTextEditor::_lookup_symbol(const String &p_symbol, int p_row, int p_c EditorNode::get_singleton()->load_resource(p_symbol); } - } else if (script->get_language()->lookup_code(code_editor->get_text_edit()->get_text_for_lookup_completion(), p_symbol, script->get_path(), base, result) == OK) { + } else if (script->get_language()->lookup_code(code_editor->get_text_editor()->get_text_for_lookup_completion(), p_symbol, script->get_path(), base, result) == OK) { _goto_line(p_row); result.class_name = result.class_name.trim_prefix("_"); @@ -943,12 +852,11 @@ void ScriptTextEditor::_lookup_symbol(const String &p_symbol, int p_row, int p_c emit_signal("go_to_help", "class_global:" + result.class_name + ":" + result.class_member); } break; } - } else if (ProjectSettings::get_singleton()->has_setting("autoload/" + p_symbol)) { - //check for Autoload scenes - String path = ProjectSettings::get_singleton()->get("autoload/" + p_symbol); - if (path.begins_with("*")) { - path = path.substr(1, path.length()); - EditorNode::get_singleton()->load_scene(path); + } else if (ProjectSettings::get_singleton()->has_autoload(p_symbol)) { + // Check for Autoload scenes. + const ProjectSettings::AutoloadInfo &info = ProjectSettings::get_singleton()->get_autoload(p_symbol); + if (info.is_singleton) { + EditorNode::get_singleton()->load_scene(info.path); } } else if (p_symbol.is_rel_path()) { // Every symbol other than absolute path is relative path so keep this condition at last. @@ -967,7 +875,7 @@ void ScriptTextEditor::_lookup_symbol(const String &p_symbol, int p_row, int p_c } void ScriptTextEditor::_validate_symbol(const String &p_symbol) { - TextEdit *text_edit = code_editor->get_text_edit(); + CodeEdit *text_edit = code_editor->get_text_editor(); Node *base = get_tree()->get_edited_scene_root(); if (base) { @@ -975,7 +883,7 @@ void ScriptTextEditor::_validate_symbol(const String &p_symbol) { } ScriptLanguage::LookupResult result; - if (ScriptServer::is_global_class(p_symbol) || p_symbol.is_resource_file() || script->get_language()->lookup_code(code_editor->get_text_edit()->get_text_for_lookup_completion(), p_symbol, script->get_path(), base, result) == OK || ProjectSettings::get_singleton()->has_setting("autoload/" + p_symbol)) { + if (ScriptServer::is_global_class(p_symbol) || p_symbol.is_resource_file() || script->get_language()->lookup_code(code_editor->get_text_editor()->get_text_for_lookup_completion(), p_symbol, script->get_path(), base, result) == OK || (ProjectSettings::get_singleton()->has_autoload(p_symbol) && ProjectSettings::get_singleton()->get_autoload(p_symbol).is_singleton)) { text_edit->set_highlighted_word(p_symbol); } else if (p_symbol.is_rel_path()) { String path = _get_absolute_path(p_symbol); @@ -1003,8 +911,16 @@ void ScriptTextEditor::update_toggle_scripts_button() { } void ScriptTextEditor::_update_connected_methods() { - TextEdit *text_edit = code_editor->get_text_edit(); - text_edit->clear_info_icons(); + CodeEdit *text_edit = code_editor->get_text_editor(); + text_edit->set_gutter_width(connection_gutter, text_edit->get_row_height()); + for (int i = 0; i < text_edit->get_line_count(); i++) { + if (text_edit->get_line_gutter_metadata(i, connection_gutter) == "") { + continue; + } + text_edit->set_line_gutter_metadata(i, connection_gutter, ""); + text_edit->set_line_gutter_icon(i, connection_gutter, nullptr); + text_edit->set_line_gutter_clickable(i, connection_gutter, false); + } missing_connections.clear(); if (!script_is_valid) { @@ -1044,8 +960,10 @@ void ScriptTextEditor::_update_connected_methods() { for (int j = 0; j < functions.size(); j++) { String name = functions[j].get_slice(":", 0); if (name == connection.callable.get_method()) { - line = functions[j].get_slice(":", 1).to_int(); - text_edit->set_line_info_icon(line - 1, get_parent_control()->get_theme_icon("Slot", "EditorIcons"), connection.callable.get_method()); + line = functions[j].get_slice(":", 1).to_int() - 1; + text_edit->set_line_gutter_metadata(line, connection_gutter, connection.callable.get_method()); + text_edit->set_line_gutter_icon(line, connection_gutter, get_parent_control()->get_theme_icon("Slot", "EditorIcons")); + text_edit->set_line_gutter_clickable(line, connection_gutter, true); methods_found.insert(connection.callable.get_method()); break; } @@ -1075,18 +993,41 @@ void ScriptTextEditor::_update_connected_methods() { } } -void ScriptTextEditor::_lookup_connections(int p_row, String p_method) { +void ScriptTextEditor::_update_gutter_indexes() { + for (int i = 0; i < code_editor->get_text_editor()->get_gutter_count(); i++) { + if (code_editor->get_text_editor()->get_gutter_name(i) == "connection_gutter") { + connection_gutter = i; + continue; + } + + if (code_editor->get_text_editor()->get_gutter_name(i) == "line_numbers") { + line_number_gutter = i; + continue; + } + } +} + +void ScriptTextEditor::_gutter_clicked(int p_line, int p_gutter) { + if (p_gutter != connection_gutter) { + return; + } + + String method = code_editor->get_text_editor()->get_line_gutter_metadata(p_line, p_gutter); + if (method == "") { + return; + } + Node *base = get_tree()->get_edited_scene_root(); if (!base) { return; } Vector<Node *> nodes = _find_all_node_for_script(base, base, script); - connection_info_dialog->popup_connections(p_method, nodes); + connection_info_dialog->popup_connections(method, nodes); } void ScriptTextEditor::_edit_option(int p_op) { - TextEdit *tx = code_editor->get_text_edit(); + CodeEdit *tx = code_editor->get_text_editor(); switch (p_op) { case EDIT_UNDO: { @@ -1125,7 +1066,7 @@ void ScriptTextEditor::_edit_option(int p_op) { return; } - tx->indent_left(); + tx->indent_selected_lines_left(); } break; case EDIT_INDENT_RIGHT: { Ref<Script> scr = script; @@ -1133,7 +1074,7 @@ void ScriptTextEditor::_edit_option(int p_op) { return; } - tx->indent_right(); + tx->indent_selected_lines_right(); } break; case EDIT_DELETE_LINE: { code_editor->delete_lines(); @@ -1210,7 +1151,7 @@ void ScriptTextEditor::_edit_option(int p_op) { } break; case EDIT_EVALUATE: { Expression expression; - Vector<String> lines = code_editor->get_text_edit()->get_selection_text().split("\n"); + Vector<String> lines = code_editor->get_text_editor()->get_selection_text().split("\n"); PackedStringArray results; for (int i = 0; i < lines.size(); i++) { @@ -1229,9 +1170,9 @@ void ScriptTextEditor::_edit_option(int p_op) { } } - code_editor->get_text_edit()->begin_complex_operation(); //prevents creating a two-step undo - code_editor->get_text_edit()->insert_text_at_cursor(String("\n").join(results)); - code_editor->get_text_edit()->end_complex_operation(); + code_editor->get_text_editor()->begin_complex_operation(); //prevents creating a two-step undo + code_editor->get_text_editor()->insert_text_at_cursor(String("\n").join(results)); + code_editor->get_text_editor()->end_complex_operation(); } break; case SEARCH_FIND: { code_editor->get_find_replace_bar()->popup_search(); @@ -1246,14 +1187,14 @@ void ScriptTextEditor::_edit_option(int p_op) { code_editor->get_find_replace_bar()->popup_replace(); } break; case SEARCH_IN_FILES: { - String selected_text = code_editor->get_text_edit()->get_selection_text(); + String selected_text = code_editor->get_text_editor()->get_selection_text(); // Yep, because it doesn't make sense to instance this dialog for every single script open... // So this will be delegated to the ScriptEditor. emit_signal("search_in_files_requested", selected_text); } break; case REPLACE_IN_FILES: { - String selected_text = code_editor->get_text_edit()->get_selection_text(); + String selected_text = code_editor->get_text_editor()->get_selection_text(); emit_signal("replace_in_files_requested", selected_text); } break; @@ -1278,24 +1219,22 @@ void ScriptTextEditor::_edit_option(int p_op) { } break; case DEBUG_TOGGLE_BREAKPOINT: { int line = tx->cursor_get_line(); - bool dobreak = !tx->is_line_set_as_breakpoint(line); + bool dobreak = !tx->is_line_breakpointed(line); tx->set_line_as_breakpoint(line, dobreak); EditorDebuggerNode::get_singleton()->set_breakpoint(script->get_path(), line + 1, dobreak); } break; case DEBUG_REMOVE_ALL_BREAKPOINTS: { - List<int> bpoints; - tx->get_breakpoints(&bpoints); + Array bpoints = tx->get_breakpointed_lines(); - for (List<int>::Element *E = bpoints.front(); E; E = E->next()) { - int line = E->get(); - bool dobreak = !tx->is_line_set_as_breakpoint(line); + for (int i = 0; i < bpoints.size(); i++) { + int line = bpoints[i]; + bool dobreak = !tx->is_line_breakpointed(line); tx->set_line_as_breakpoint(line, dobreak); EditorDebuggerNode::get_singleton()->set_breakpoint(script->get_path(), line + 1, dobreak); } } break; case DEBUG_GOTO_NEXT_BREAKPOINT: { - List<int> bpoints; - tx->get_breakpoints(&bpoints); + Array bpoints = tx->get_breakpointed_lines(); if (bpoints.size() <= 0) { return; } @@ -1303,13 +1242,13 @@ void ScriptTextEditor::_edit_option(int p_op) { int line = tx->cursor_get_line(); // wrap around - if (line >= bpoints[bpoints.size() - 1]) { + if (line >= (int)bpoints[bpoints.size() - 1]) { tx->unfold_line(bpoints[0]); tx->cursor_set_line(bpoints[0]); tx->center_viewport_to_cursor(); } else { - for (List<int>::Element *E = bpoints.front(); E; E = E->next()) { - int bline = E->get(); + for (int i = 0; i < bpoints.size(); i++) { + int bline = bpoints[i]; if (bline > line) { tx->unfold_line(bline); tx->cursor_set_line(bline); @@ -1321,21 +1260,20 @@ void ScriptTextEditor::_edit_option(int p_op) { } break; case DEBUG_GOTO_PREV_BREAKPOINT: { - List<int> bpoints; - tx->get_breakpoints(&bpoints); + Array bpoints = tx->get_breakpointed_lines(); if (bpoints.size() <= 0) { return; } int line = tx->cursor_get_line(); // wrap around - if (line <= bpoints[0]) { + if (line <= (int)bpoints[0]) { tx->unfold_line(bpoints[bpoints.size() - 1]); tx->cursor_set_line(bpoints[bpoints.size() - 1]); tx->center_viewport_to_cursor(); } else { - for (List<int>::Element *E = bpoints.back(); E; E = E->prev()) { - int bline = E->get(); + for (int i = bpoints.size(); i >= 0; i--) { + int bline = bpoints[i]; if (bline < line) { tx->unfold_line(bline); tx->cursor_set_line(bline); @@ -1387,37 +1325,51 @@ void ScriptTextEditor::_edit_option_toggle_inline_comment() { code_editor->toggle_inline_comment(delimiter); } -void ScriptTextEditor::add_syntax_highlighter(SyntaxHighlighter *p_highlighter) { - highlighters[p_highlighter->get_name()] = p_highlighter; - highlighter_menu->add_radio_check_item(p_highlighter->get_name()); -} +void ScriptTextEditor::add_syntax_highlighter(Ref<EditorSyntaxHighlighter> p_highlighter) { + ERR_FAIL_COND(p_highlighter.is_null()); -void ScriptTextEditor::set_syntax_highlighter(SyntaxHighlighter *p_highlighter) { - TextEdit *te = code_editor->get_text_edit(); - te->_set_syntax_highlighting(p_highlighter); - if (p_highlighter != nullptr) { - highlighter_menu->set_item_checked(highlighter_menu->get_item_idx_from_text(p_highlighter->get_name()), true); - } else { - highlighter_menu->set_item_checked(highlighter_menu->get_item_idx_from_text(TTR("Standard")), true); - } + highlighters[p_highlighter->_get_name()] = p_highlighter; + highlighter_menu->add_radio_check_item(p_highlighter->_get_name()); } -void ScriptTextEditor::_change_syntax_highlighter(int p_idx) { - Map<String, SyntaxHighlighter *>::Element *el = highlighters.front(); +void ScriptTextEditor::set_syntax_highlighter(Ref<EditorSyntaxHighlighter> p_highlighter) { + ERR_FAIL_COND(p_highlighter.is_null()); + + Map<String, Ref<EditorSyntaxHighlighter>>::Element *el = highlighters.front(); while (el != nullptr) { - highlighter_menu->set_item_checked(highlighter_menu->get_item_idx_from_text(el->key()), false); + int highlighter_index = highlighter_menu->get_item_idx_from_text(el->key()); + highlighter_menu->set_item_checked(highlighter_index, el->value() == p_highlighter); el = el->next(); } - // highlighter_menu->set_item_checked(p_idx, true); + + CodeEdit *te = code_editor->get_text_editor(); + p_highlighter->_set_edited_resource(script); + te->set_syntax_highlighter(p_highlighter); +} + +void ScriptTextEditor::_change_syntax_highlighter(int p_idx) { set_syntax_highlighter(highlighters[highlighter_menu->get_item_text(p_idx)]); } +void ScriptTextEditor::_notification(int p_what) { + switch (p_what) { + case NOTIFICATION_THEME_CHANGED: + case NOTIFICATION_ENTER_TREE: { + code_editor->get_text_editor()->set_gutter_width(connection_gutter, code_editor->get_text_editor()->get_row_height()); + } break; + default: + break; + } +} + void ScriptTextEditor::_bind_methods() { ClassDB::bind_method("_update_connected_methods", &ScriptTextEditor::_update_connected_methods); ClassDB::bind_method("get_drag_data_fw", &ScriptTextEditor::get_drag_data_fw); ClassDB::bind_method("can_drop_data_fw", &ScriptTextEditor::can_drop_data_fw); ClassDB::bind_method("drop_data_fw", &ScriptTextEditor::drop_data_fw); + + ClassDB::bind_method(D_METHOD("add_syntax_highlighter", "highlighter"), &ScriptTextEditor::add_syntax_highlighter); } Control *ScriptTextEditor::get_edit_menu() { @@ -1429,7 +1381,7 @@ void ScriptTextEditor::clear_edit_menu() { } void ScriptTextEditor::reload(bool p_soft) { - TextEdit *te = code_editor->get_text_edit(); + CodeEdit *te = code_editor->get_text_editor(); Ref<Script> scr = script; if (scr.is_null()) { return; @@ -1440,12 +1392,12 @@ void ScriptTextEditor::reload(bool p_soft) { scr->get_language()->reload_tool_script(scr, soft); } -void ScriptTextEditor::get_breakpoints(List<int> *p_breakpoints) { - code_editor->get_text_edit()->get_breakpoints(p_breakpoints); +Array ScriptTextEditor::get_breakpoints() { + return code_editor->get_text_editor()->get_breakpointed_lines(); } void ScriptTextEditor::set_tooltip_request_func(String p_method, Object *p_obj) { - code_editor->get_text_edit()->set_tooltip_request_func(p_obj, p_method, this); + code_editor->get_text_editor()->set_tooltip_request_func(p_obj, p_method, this); } void ScriptTextEditor::set_debugger_active(bool p_active) { @@ -1491,7 +1443,7 @@ static Node *_find_script_node(Node *p_edited_scene, Node *p_current_node, const void ScriptTextEditor::drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) { Dictionary d = p_data; - TextEdit *te = code_editor->get_text_edit(); + CodeEdit *te = code_editor->get_text_editor(); int row, col; te->_get_mouse_pos(p_point, row, col); @@ -1564,7 +1516,7 @@ void ScriptTextEditor::_text_edit_gui_input(const Ref<InputEvent> &ev) { Point2 local_pos; bool create_menu = false; - TextEdit *tx = code_editor->get_text_edit(); + CodeEdit *tx = code_editor->get_text_editor(); if (mb.is_valid() && mb->get_button_index() == BUTTON_RIGHT && mb->is_pressed()) { local_pos = mb->get_global_position() - tx->get_global_position(); create_menu = true; @@ -1617,7 +1569,7 @@ void ScriptTextEditor::_text_edit_gui_input(const Ref<InputEvent> &ev) { base = _find_node_for_script(base, base, script); } ScriptLanguage::LookupResult result; - if (script->get_language()->lookup_code(code_editor->get_text_edit()->get_text_for_lookup_completion(), word_at_pos, script->get_path(), base, result) == OK) { + if (script->get_language()->lookup_code(code_editor->get_text_editor()->get_text_for_lookup_completion(), word_at_pos, script->get_path(), base, result) == OK) { open_docs = true; } } @@ -1665,31 +1617,31 @@ void ScriptTextEditor::_color_changed(const Color &p_color) { new_args = String("(" + rtos(p_color.r) + ", " + rtos(p_color.g) + ", " + rtos(p_color.b) + ", " + rtos(p_color.a) + ")"); } - String line = code_editor->get_text_edit()->get_line(color_position.x); + String line = code_editor->get_text_editor()->get_line(color_position.x); int color_args_pos = line.find(color_args, color_position.y); String line_with_replaced_args = line; line_with_replaced_args.erase(color_args_pos, color_args.length()); line_with_replaced_args = line_with_replaced_args.insert(color_args_pos, new_args); color_args = new_args; - code_editor->get_text_edit()->begin_complex_operation(); - code_editor->get_text_edit()->set_line(color_position.x, line_with_replaced_args); - code_editor->get_text_edit()->end_complex_operation(); - code_editor->get_text_edit()->update(); + code_editor->get_text_editor()->begin_complex_operation(); + code_editor->get_text_editor()->set_line(color_position.x, line_with_replaced_args); + code_editor->get_text_editor()->end_complex_operation(); + code_editor->get_text_editor()->update(); } void ScriptTextEditor::_make_context_menu(bool p_selection, bool p_color, bool p_foldable, bool p_open_docs, bool p_goto_definition, Vector2 p_pos) { context_menu->clear(); - context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/undo"), EDIT_UNDO); - context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/redo"), EDIT_REDO); + context_menu->add_shortcut(ED_GET_SHORTCUT("ui_undo"), EDIT_UNDO); + context_menu->add_shortcut(ED_GET_SHORTCUT("ui_redo"), EDIT_REDO); context_menu->add_separator(); - context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/cut"), EDIT_CUT); - context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/copy"), EDIT_COPY); - context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/paste"), EDIT_PASTE); + context_menu->add_shortcut(ED_GET_SHORTCUT("ui_cut"), EDIT_CUT); + context_menu->add_shortcut(ED_GET_SHORTCUT("ui_copy"), EDIT_COPY); + context_menu->add_shortcut(ED_GET_SHORTCUT("ui_paste"), EDIT_PASTE); context_menu->add_separator(); - context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/select_all"), EDIT_SELECT_ALL); + context_menu->add_shortcut(ED_GET_SHORTCUT("ui_text_select_all"), EDIT_SELECT_ALL); context_menu->add_separator(); context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/indent_left"), EDIT_INDENT_LEFT); @@ -1722,63 +1674,46 @@ void ScriptTextEditor::_make_context_menu(bool p_selection, bool p_color, bool p context_menu->popup(); } -ScriptTextEditor::ScriptTextEditor() { - theme_loaded = false; - script_is_valid = false; +void ScriptTextEditor::_enable_code_editor() { + ERR_FAIL_COND(code_editor->get_parent()); VSplitContainer *editor_box = memnew(VSplitContainer); add_child(editor_box); - editor_box->set_anchors_and_margins_preset(Control::PRESET_WIDE); + editor_box->set_anchors_and_offsets_preset(Control::PRESET_WIDE); editor_box->set_v_size_flags(SIZE_EXPAND_FILL); - code_editor = memnew(CodeTextEditor); editor_box->add_child(code_editor); - code_editor->add_theme_constant_override("separation", 2); - code_editor->set_anchors_and_margins_preset(Control::PRESET_WIDE); + code_editor->connect("show_warnings_panel", callable_mp(this, &ScriptTextEditor::_show_warnings_panel)); code_editor->connect("validate_script", callable_mp(this, &ScriptTextEditor::_validate_script)); code_editor->connect("load_theme_settings", callable_mp(this, &ScriptTextEditor::_load_theme_settings)); - code_editor->set_code_complete_func(_code_complete_scripts, this); - code_editor->get_text_edit()->connect("breakpoint_toggled", callable_mp(this, &ScriptTextEditor::_breakpoint_toggled)); - code_editor->get_text_edit()->connect("symbol_lookup", callable_mp(this, &ScriptTextEditor::_lookup_symbol)); - code_editor->get_text_edit()->connect("symbol_validate", callable_mp(this, &ScriptTextEditor::_validate_symbol)); - code_editor->get_text_edit()->connect("info_clicked", callable_mp(this, &ScriptTextEditor::_lookup_connections)); - code_editor->set_v_size_flags(SIZE_EXPAND_FILL); + code_editor->get_text_editor()->connect("breakpoint_toggled", callable_mp(this, &ScriptTextEditor::_breakpoint_toggled)); + code_editor->get_text_editor()->connect("symbol_lookup", callable_mp(this, &ScriptTextEditor::_lookup_symbol)); + code_editor->get_text_editor()->connect("symbol_validate", callable_mp(this, &ScriptTextEditor::_validate_symbol)); + code_editor->get_text_editor()->connect("gutter_added", callable_mp(this, &ScriptTextEditor::_update_gutter_indexes)); + code_editor->get_text_editor()->connect("gutter_removed", callable_mp(this, &ScriptTextEditor::_update_gutter_indexes)); + code_editor->get_text_editor()->connect("gutter_clicked", callable_mp(this, &ScriptTextEditor::_gutter_clicked)); + code_editor->get_text_editor()->connect("gui_input", callable_mp(this, &ScriptTextEditor::_text_edit_gui_input)); code_editor->show_toggle_scripts_button(); + _update_gutter_indexes(); - warnings_panel = memnew(RichTextLabel); editor_box->add_child(warnings_panel); - warnings_panel->set_custom_minimum_size(Size2(0, 100 * EDSCALE)); - warnings_panel->set_h_size_flags(SIZE_EXPAND_FILL); - warnings_panel->set_meta_underline(true); - warnings_panel->set_selection_enabled(true); - warnings_panel->set_focus_mode(FOCUS_CLICK); - warnings_panel->hide(); - - code_editor->connect("error_pressed", callable_mp(this, &ScriptTextEditor::_error_pressed)); - code_editor->connect("show_warnings_panel", callable_mp(this, &ScriptTextEditor::_show_warnings_panel)); + warnings_panel->add_theme_font_override( + "normal_font", EditorNode::get_singleton()->get_gui_base()->get_theme_font("main", "EditorFonts")); + warnings_panel->add_theme_font_size_override( + "normal_font_size", EditorNode::get_singleton()->get_gui_base()->get_theme_font_size("main_size", "EditorFonts")); warnings_panel->connect("meta_clicked", callable_mp(this, &ScriptTextEditor::_warning_clicked)); - update_settings(); - - code_editor->get_text_edit()->set_callhint_settings( - EditorSettings::get_singleton()->get("text_editor/completion/put_callhint_tooltip_below_current_line"), - EditorSettings::get_singleton()->get("text_editor/completion/callhint_tooltip_offset")); - - code_editor->get_text_edit()->set_select_identifiers_on_hover(true); - code_editor->get_text_edit()->set_context_menu_enabled(false); - code_editor->get_text_edit()->connect("gui_input", callable_mp(this, &ScriptTextEditor::_text_edit_gui_input)); - - context_menu = memnew(PopupMenu); add_child(context_menu); context_menu->connect("id_pressed", callable_mp(this, &ScriptTextEditor::_edit_option)); - color_panel = memnew(PopupPanel); add_child(color_panel); + color_picker = memnew(ColorPicker); color_picker->set_deferred_mode(true); - color_panel->add_child(color_picker); color_picker->connect("color_changed", callable_mp(this, &ScriptTextEditor::_color_changed)); + color_panel->add_child(color_picker); + // get default color picker mode from editor settings int default_color_mode = EDITOR_GET("interface/inspector/default_color_picker_mode"); if (default_color_mode == 1) { @@ -1787,20 +1722,35 @@ ScriptTextEditor::ScriptTextEditor() { color_picker->set_raw_mode(true); } - edit_hb = memnew(HBoxContainer); + quick_open = memnew(ScriptEditorQuickOpen); + quick_open->connect("goto_line", callable_mp(this, &ScriptTextEditor::_goto_line)); + add_child(quick_open); - edit_menu = memnew(MenuButton); - edit_menu->set_text(TTR("Edit")); - edit_menu->set_switch_on_hover(true); + goto_line_dialog = memnew(GotoLineDialog); + add_child(goto_line_dialog); + + add_child(connection_info_dialog); - edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/undo"), EDIT_UNDO); - edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/redo"), EDIT_REDO); + edit_hb->add_child(search_menu); + search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/find"), SEARCH_FIND); + search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/find_next"), SEARCH_FIND_NEXT); + search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/find_previous"), SEARCH_FIND_PREV); + search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/replace"), SEARCH_REPLACE); + search_menu->get_popup()->add_separator(); + search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/find_in_files"), SEARCH_IN_FILES); + search_menu->get_popup()->add_separator(); + search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/contextual_help"), HELP_CONTEXTUAL); + search_menu->get_popup()->connect("id_pressed", callable_mp(this, &ScriptTextEditor::_edit_option)); + + edit_hb->add_child(edit_menu); + edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("ui_undo"), EDIT_UNDO); + edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("ui_redo"), EDIT_REDO); edit_menu->get_popup()->add_separator(); - edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/cut"), EDIT_CUT); - edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/copy"), EDIT_COPY); - edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/paste"), EDIT_PASTE); + edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("ui_cut"), EDIT_CUT); + edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("ui_copy"), EDIT_COPY); + edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("ui_paste"), EDIT_PASTE); edit_menu->get_popup()->add_separator(); - edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/select_all"), EDIT_SELECT_ALL); + edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("ui_text_select_all"), EDIT_SELECT_ALL); edit_menu->get_popup()->add_separator(); edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/move_up"), EDIT_MOVE_LINE_UP); edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/move_down"), EDIT_MOVE_LINE_DOWN); @@ -1813,7 +1763,7 @@ ScriptTextEditor::ScriptTextEditor() { edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/unfold_all_lines"), EDIT_UNFOLD_ALL_LINES); edit_menu->get_popup()->add_separator(); edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/clone_down"), EDIT_CLONE_DOWN); - edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/complete_symbol"), EDIT_COMPLETE); + edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("ui_text_completion_query"), EDIT_COMPLETE); edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/evaluate_selection"), EDIT_EVALUATE); edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/trim_trailing_whitespace"), EDIT_TRIM_TRAILING_WHITESAPCE); edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/convert_indent_to_spaces"), EDIT_CONVERT_INDENT_TO_SPACES); @@ -1822,8 +1772,6 @@ ScriptTextEditor::ScriptTextEditor() { edit_menu->get_popup()->connect("id_pressed", callable_mp(this, &ScriptTextEditor::_edit_option)); edit_menu->get_popup()->add_separator(); - PopupMenu *convert_case = memnew(PopupMenu); - convert_case->set_name("convert_case"); edit_menu->get_popup()->add_child(convert_case); edit_menu->get_popup()->add_submenu_item(TTR("Convert Case"), "convert_case"); convert_case->add_shortcut(ED_SHORTCUT("script_text_editor/convert_to_uppercase", TTR("Uppercase"), KEY_MASK_SHIFT | KEY_F4), EDIT_TO_UPPERCASE); @@ -1831,78 +1779,132 @@ ScriptTextEditor::ScriptTextEditor() { convert_case->add_shortcut(ED_SHORTCUT("script_text_editor/capitalize", TTR("Capitalize"), KEY_MASK_SHIFT | KEY_F6), EDIT_CAPITALIZE); convert_case->connect("id_pressed", callable_mp(this, &ScriptTextEditor::_edit_option)); - highlighters[TTR("Standard")] = nullptr; - highlighter_menu = memnew(PopupMenu); - highlighter_menu->set_name("highlighter_menu"); edit_menu->get_popup()->add_child(highlighter_menu); edit_menu->get_popup()->add_submenu_item(TTR("Syntax Highlighter"), "highlighter_menu"); - highlighter_menu->add_radio_check_item(TTR("Standard")); highlighter_menu->connect("id_pressed", callable_mp(this, &ScriptTextEditor::_change_syntax_highlighter)); - search_menu = memnew(MenuButton); - edit_hb->add_child(search_menu); - search_menu->set_text(TTR("Search")); - search_menu->set_switch_on_hover(true); + _load_theme_settings(); - search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/find"), SEARCH_FIND); - search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/find_next"), SEARCH_FIND_NEXT); - search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/find_previous"), SEARCH_FIND_PREV); - search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/replace"), SEARCH_REPLACE); - search_menu->get_popup()->add_separator(); - search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/find_in_files"), SEARCH_IN_FILES); search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/replace_in_files"), REPLACE_IN_FILES); - search_menu->get_popup()->add_separator(); - search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/contextual_help"), HELP_CONTEXTUAL); - search_menu->get_popup()->connect("id_pressed", callable_mp(this, &ScriptTextEditor::_edit_option)); - - edit_hb->add_child(edit_menu); - - MenuButton *goto_menu = memnew(MenuButton); edit_hb->add_child(goto_menu); - goto_menu->set_text(TTR("Go To")); - goto_menu->set_switch_on_hover(true); - goto_menu->get_popup()->connect("id_pressed", callable_mp(this, &ScriptTextEditor::_edit_option)); - goto_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/goto_function"), SEARCH_LOCATE_FUNCTION); goto_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/goto_line"), SEARCH_GOTO_LINE); goto_menu->get_popup()->add_separator(); - bookmarks_menu = memnew(PopupMenu); - bookmarks_menu->set_name("Bookmarks"); goto_menu->get_popup()->add_child(bookmarks_menu); goto_menu->get_popup()->add_submenu_item(TTR("Bookmarks"), "Bookmarks"); _update_bookmark_list(); bookmarks_menu->connect("about_to_popup", callable_mp(this, &ScriptTextEditor::_update_bookmark_list)); bookmarks_menu->connect("index_pressed", callable_mp(this, &ScriptTextEditor::_bookmark_item_pressed)); - breakpoints_menu = memnew(PopupMenu); - breakpoints_menu->set_name("Breakpoints"); goto_menu->get_popup()->add_child(breakpoints_menu); goto_menu->get_popup()->add_submenu_item(TTR("Breakpoints"), "Breakpoints"); _update_breakpoint_list(); breakpoints_menu->connect("about_to_popup", callable_mp(this, &ScriptTextEditor::_update_breakpoint_list)); breakpoints_menu->connect("index_pressed", callable_mp(this, &ScriptTextEditor::_breakpoint_item_pressed)); - quick_open = memnew(ScriptEditorQuickOpen); - add_child(quick_open); - quick_open->connect("goto_line", callable_mp(this, &ScriptTextEditor::_goto_line)); + goto_menu->get_popup()->connect("id_pressed", callable_mp(this, &ScriptTextEditor::_edit_option)); +} - goto_line_dialog = memnew(GotoLineDialog); - add_child(goto_line_dialog); +ScriptTextEditor::ScriptTextEditor() { + code_editor = memnew(CodeTextEditor); + code_editor->add_theme_constant_override("separation", 2); + code_editor->set_anchors_and_offsets_preset(Control::PRESET_WIDE); + code_editor->set_code_complete_func(_code_complete_scripts, this); + code_editor->set_v_size_flags(SIZE_EXPAND_FILL); + + code_editor->get_text_editor()->set_draw_breakpoints_gutter(true); + code_editor->get_text_editor()->set_draw_executing_lines_gutter(true); + + connection_gutter = 1; + code_editor->get_text_editor()->add_gutter(connection_gutter); + code_editor->get_text_editor()->set_gutter_name(connection_gutter, "connection_gutter"); + code_editor->get_text_editor()->set_gutter_draw(connection_gutter, false); + code_editor->get_text_editor()->set_gutter_overwritable(connection_gutter, true); + code_editor->get_text_editor()->set_gutter_type(connection_gutter, TextEdit::GUTTER_TPYE_ICON); + + warnings_panel = memnew(RichTextLabel); + warnings_panel->set_custom_minimum_size(Size2(0, 100 * EDSCALE)); + warnings_panel->set_h_size_flags(SIZE_EXPAND_FILL); + warnings_panel->set_meta_underline(true); + warnings_panel->set_selection_enabled(true); + warnings_panel->set_focus_mode(FOCUS_CLICK); + warnings_panel->hide(); + + update_settings(); + + code_editor->get_text_editor()->set_callhint_settings( + EditorSettings::get_singleton()->get("text_editor/completion/put_callhint_tooltip_below_current_line"), + EditorSettings::get_singleton()->get("text_editor/completion/callhint_tooltip_offset")); + + code_editor->get_text_editor()->set_select_identifiers_on_hover(true); + code_editor->get_text_editor()->set_context_menu_enabled(false); + + context_menu = memnew(PopupMenu); + + color_panel = memnew(PopupPanel); + + edit_hb = memnew(HBoxContainer); + + edit_menu = memnew(MenuButton); + edit_menu->set_text(TTR("Edit")); + edit_menu->set_switch_on_hover(true); + edit_menu->set_shortcut_context(this); + + convert_case = memnew(PopupMenu); + convert_case->set_name("convert_case"); + + highlighter_menu = memnew(PopupMenu); + highlighter_menu->set_name("highlighter_menu"); + + Ref<EditorPlainTextSyntaxHighlighter> plain_highlighter; + plain_highlighter.instance(); + add_syntax_highlighter(plain_highlighter); + + Ref<EditorStandardSyntaxHighlighter> highlighter; + highlighter.instance(); + add_syntax_highlighter(highlighter); + set_syntax_highlighter(highlighter); + + search_menu = memnew(MenuButton); + search_menu->set_text(TTR("Search")); + search_menu->set_switch_on_hover(true); + search_menu->set_shortcut_context(this); + + goto_menu = memnew(MenuButton); + goto_menu->set_text(TTR("Go To")); + goto_menu->set_switch_on_hover(true); + goto_menu->set_shortcut_context(this); + + bookmarks_menu = memnew(PopupMenu); + bookmarks_menu->set_name("Bookmarks"); + + breakpoints_menu = memnew(PopupMenu); + breakpoints_menu->set_name("Breakpoints"); connection_info_dialog = memnew(ConnectionInfoDialog); - add_child(connection_info_dialog); - code_editor->get_text_edit()->set_drag_forwarding(this); + code_editor->get_text_editor()->set_drag_forwarding(this); } ScriptTextEditor::~ScriptTextEditor() { - for (const Map<String, SyntaxHighlighter *>::Element *E = highlighters.front(); E; E = E->next()) { - if (E->get() != nullptr) { - memdelete(E->get()); - } - } highlighters.clear(); + + if (!editor_enabled) { + memdelete(code_editor); + memdelete(warnings_panel); + memdelete(context_menu); + memdelete(color_panel); + memdelete(edit_hb); + memdelete(edit_menu); + memdelete(convert_case); + memdelete(highlighter_menu); + memdelete(search_menu); + memdelete(goto_menu); + memdelete(bookmarks_menu); + memdelete(breakpoints_menu); + memdelete(connection_info_dialog); + } } static ScriptEditorBase *create_editor(const RES &p_resource) { @@ -1913,12 +1915,6 @@ static ScriptEditorBase *create_editor(const RES &p_resource) { } void ScriptTextEditor::register_editor() { - ED_SHORTCUT("script_text_editor/undo", TTR("Undo"), KEY_MASK_CMD | KEY_Z); - ED_SHORTCUT("script_text_editor/redo", TTR("Redo"), KEY_MASK_CMD | KEY_Y); - ED_SHORTCUT("script_text_editor/cut", TTR("Cut"), KEY_MASK_CMD | KEY_X); - ED_SHORTCUT("script_text_editor/copy", TTR("Copy"), KEY_MASK_CMD | KEY_C); - ED_SHORTCUT("script_text_editor/paste", TTR("Paste"), KEY_MASK_CMD | KEY_V); - ED_SHORTCUT("script_text_editor/select_all", TTR("Select All"), KEY_MASK_CMD | KEY_A); ED_SHORTCUT("script_text_editor/move_up", TTR("Move Up"), KEY_MASK_ALT | KEY_UP); ED_SHORTCUT("script_text_editor/move_down", TTR("Move Down"), KEY_MASK_ALT | KEY_DOWN); ED_SHORTCUT("script_text_editor/delete_line", TTR("Delete Line"), KEY_MASK_CMD | KEY_MASK_SHIFT | KEY_K); @@ -1934,10 +1930,8 @@ void ScriptTextEditor::register_editor() { ED_SHORTCUT("script_text_editor/unfold_all_lines", TTR("Unfold All Lines"), 0); #ifdef OSX_ENABLED ED_SHORTCUT("script_text_editor/clone_down", TTR("Clone Down"), KEY_MASK_SHIFT | KEY_MASK_CMD | KEY_C); - ED_SHORTCUT("script_text_editor/complete_symbol", TTR("Complete Symbol"), KEY_MASK_CTRL | KEY_SPACE); #else ED_SHORTCUT("script_text_editor/clone_down", TTR("Clone Down"), KEY_MASK_CMD | KEY_D); - ED_SHORTCUT("script_text_editor/complete_symbol", TTR("Complete Symbol"), KEY_MASK_CMD | KEY_SPACE); #endif ED_SHORTCUT("script_text_editor/evaluate_selection", TTR("Evaluate Selection"), KEY_MASK_CMD | KEY_MASK_SHIFT | KEY_E); ED_SHORTCUT("script_text_editor/trim_trailing_whitespace", TTR("Trim Trailing Whitespace"), KEY_MASK_CMD | KEY_MASK_ALT | KEY_T); diff --git a/editor/plugins/script_text_editor.h b/editor/plugins/script_text_editor.h index adcd0218bc..17abfcf4cc 100644 --- a/editor/plugins/script_text_editor.h +++ b/editor/plugins/script_text_editor.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -39,10 +39,10 @@ class ConnectionInfoDialog : public AcceptDialog { GDCLASS(ConnectionInfoDialog, AcceptDialog); - Label *method; - Tree *tree; + Label *method = nullptr; + Tree *tree = nullptr; - virtual void ok_pressed(); + virtual void ok_pressed() override; public: void popup_connections(String p_method, Vector<Node *> p_nodes); @@ -53,11 +53,12 @@ public: class ScriptTextEditor : public ScriptEditorBase { GDCLASS(ScriptTextEditor, ScriptEditorBase); - CodeTextEditor *code_editor; - RichTextLabel *warnings_panel; + CodeTextEditor *code_editor = nullptr; + RichTextLabel *warnings_panel = nullptr; Ref<Script> script; - bool script_is_valid; + bool script_is_valid = false; + bool editor_enabled = false; Vector<String> functions; @@ -65,37 +66,35 @@ class ScriptTextEditor : public ScriptEditorBase { Vector<String> member_keywords; - HBoxContainer *edit_hb; + HBoxContainer *edit_hb = nullptr; - MenuButton *edit_menu; - MenuButton *search_menu; - PopupMenu *bookmarks_menu; - PopupMenu *breakpoints_menu; - PopupMenu *highlighter_menu; - PopupMenu *context_menu; + MenuButton *edit_menu = nullptr; + MenuButton *search_menu = nullptr; + MenuButton *goto_menu = nullptr; + PopupMenu *bookmarks_menu = nullptr; + PopupMenu *breakpoints_menu = nullptr; + PopupMenu *highlighter_menu = nullptr; + PopupMenu *context_menu = nullptr; + PopupMenu *convert_case = nullptr; - GotoLineDialog *goto_line_dialog; - ScriptEditorQuickOpen *quick_open; - ConnectionInfoDialog *connection_info_dialog; + GotoLineDialog *goto_line_dialog = nullptr; + ScriptEditorQuickOpen *quick_open = nullptr; + ConnectionInfoDialog *connection_info_dialog = nullptr; - PopupPanel *color_panel; - ColorPicker *color_picker; - Vector2 color_position; - String color_args; + int connection_gutter = -1; + void _gutter_clicked(int p_line, int p_gutter); + void _update_gutter_indexes(); - void _update_member_keywords(); + int line_number_gutter = -1; + Color default_line_number_color = Color(1, 1, 1); + Color safe_line_number_color = Color(1, 1, 1); - struct ColorsCache { - Color symbol_color; - Color keyword_color; - Color basetype_color; - Color type_color; - Color usertype_color; - Color comment_color; - Color string_color; - } colors_cache; + PopupPanel *color_panel = nullptr; + ColorPicker *color_picker = nullptr; + Vector2 color_position; + String color_args; - bool theme_loaded; + bool theme_loaded = false; enum { EDIT_UNDO, @@ -144,6 +143,8 @@ class ScriptTextEditor : public ScriptEditorBase { LOOKUP_SYMBOL, }; + void _enable_code_editor(); + protected: void _update_breakpoint_list(); void _breakpoint_item_pressed(int p_idx); @@ -159,13 +160,12 @@ protected: void _load_theme_settings(); void _set_theme_for_script(); void _show_warnings_panel(bool p_show); - void _error_pressed(); void _warning_clicked(Variant p_line); void _notification(int p_what); static void _bind_methods(); - Map<String, SyntaxHighlighter *> highlighters; + Map<String, Ref<EditorSyntaxHighlighter>> highlighters; void _change_syntax_highlighter(int p_idx); void _edit_option(int p_op); @@ -178,8 +178,6 @@ protected: void _lookup_symbol(const String &p_symbol, int p_row, int p_column); void _validate_symbol(const String &p_symbol); - void _lookup_connections(int p_row, String p_method); - void _convert_case(CodeTextEditor::CaseStyle p_case); Variant get_drag_data_fw(const Point2 &p_point, Control *p_from); @@ -191,50 +189,51 @@ protected: public: void _update_connected_methods(); - virtual void add_syntax_highlighter(SyntaxHighlighter *p_highlighter); - virtual void set_syntax_highlighter(SyntaxHighlighter *p_highlighter); + virtual void add_syntax_highlighter(Ref<EditorSyntaxHighlighter> p_highlighter) override; + virtual void set_syntax_highlighter(Ref<EditorSyntaxHighlighter> p_highlighter) override; void update_toggle_scripts_button(); - virtual void apply_code(); - virtual RES get_edited_resource() const; - virtual void set_edited_resource(const RES &p_res); - virtual Vector<String> get_functions(); - virtual void reload_text(); - virtual String get_name(); - virtual Ref<Texture2D> get_theme_icon(); - virtual bool is_unsaved(); - virtual Variant get_edit_state(); - virtual void set_edit_state(const Variant &p_state); - virtual void ensure_focus(); - virtual void trim_trailing_whitespace(); - virtual void insert_final_newline(); - virtual void convert_indent_to_spaces(); - virtual void convert_indent_to_tabs(); - virtual void tag_saved_version(); - - virtual void goto_line(int p_line, bool p_with_error = false); + virtual void apply_code() override; + virtual RES get_edited_resource() const override; + virtual void set_edited_resource(const RES &p_res) override; + virtual void enable_editor() override; + virtual Vector<String> get_functions() override; + virtual void reload_text() override; + virtual String get_name() override; + virtual Ref<Texture2D> get_theme_icon() override; + virtual bool is_unsaved() override; + virtual Variant get_edit_state() override; + virtual void set_edit_state(const Variant &p_state) override; + virtual void ensure_focus() override; + virtual void trim_trailing_whitespace() override; + virtual void insert_final_newline() override; + virtual void convert_indent_to_spaces() override; + virtual void convert_indent_to_tabs() override; + virtual void tag_saved_version() override; + + virtual void goto_line(int p_line, bool p_with_error = false) override; void goto_line_selection(int p_line, int p_begin, int p_end); void goto_line_centered(int p_line); - virtual void set_executing_line(int p_line); - virtual void clear_executing_line(); + virtual void set_executing_line(int p_line) override; + virtual void clear_executing_line() override; - virtual void reload(bool p_soft); - virtual void get_breakpoints(List<int> *p_breakpoints); + virtual void reload(bool p_soft) override; + virtual Array get_breakpoints() override; - virtual void add_callback(const String &p_function, PackedStringArray p_args); - virtual void update_settings(); + virtual void add_callback(const String &p_function, PackedStringArray p_args) override; + virtual void update_settings() override; - virtual bool show_members_overview(); + virtual bool show_members_overview() override; - virtual void set_tooltip_request_func(String p_method, Object *p_obj); + virtual void set_tooltip_request_func(String p_method, Object *p_obj) override; - virtual void set_debugger_active(bool p_active); + virtual void set_debugger_active(bool p_active) override; - Control *get_edit_menu(); - virtual void clear_edit_menu(); + Control *get_edit_menu() override; + virtual void clear_edit_menu() override; static void register_editor(); - virtual void validate(); + virtual void validate() override; ScriptTextEditor(); ~ScriptTextEditor(); diff --git a/editor/plugins/shader_editor_plugin.cpp b/editor/plugins/shader_editor_plugin.cpp index 0c3a44e4cd..c8a46715ad 100644 --- a/editor/plugins/shader_editor_plugin.cpp +++ b/editor/plugins/shader_editor_plugin.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -55,8 +55,8 @@ void ShaderTextEditor::set_edited_shader(const Ref<Shader> &p_shader) { _load_theme_settings(); - get_text_edit()->set_text(p_shader->get_code()); - get_text_edit()->clear_undo_history(); + get_text_editor()->set_text(p_shader->get_code()); + get_text_editor()->clear_undo_history(); _validate_script(); _line_col_changed(); @@ -65,7 +65,7 @@ void ShaderTextEditor::set_edited_shader(const Ref<Shader> &p_shader) { void ShaderTextEditor::reload_text() { ERR_FAIL_COND(shader.is_null()); - TextEdit *te = get_text_edit(); + CodeEdit *te = get_text_editor(); int column = te->cursor_get_column(); int row = te->cursor_get_line(); int h = te->get_h_scroll(); @@ -83,8 +83,6 @@ void ShaderTextEditor::reload_text() { } void ShaderTextEditor::_load_theme_settings() { - get_text_edit()->clear_colors(); - Color background_color = EDITOR_GET("text_editor/highlighting/background_color"); Color completion_background_color = EDITOR_GET("text_editor/highlighting/completion_background_color"); Color completion_selected_color = EDITOR_GET("text_editor/highlighting/completion_selected_color"); @@ -101,9 +99,6 @@ void ShaderTextEditor::_load_theme_settings() { Color current_line_color = EDITOR_GET("text_editor/highlighting/current_line_color"); Color line_length_guideline_color = EDITOR_GET("text_editor/highlighting/line_length_guideline_color"); Color word_highlighted_color = EDITOR_GET("text_editor/highlighting/word_highlighted_color"); - Color number_color = EDITOR_GET("text_editor/highlighting/number_color"); - Color function_color = EDITOR_GET("text_editor/highlighting/function_color"); - Color member_variable_color = EDITOR_GET("text_editor/highlighting/member_variable_color"); Color mark_color = EDITOR_GET("text_editor/highlighting/mark_color"); Color bookmark_color = EDITOR_GET("text_editor/highlighting/bookmark_color"); Color breakpoint_color = EDITOR_GET("text_editor/highlighting/breakpoint_color"); @@ -111,64 +106,77 @@ void ShaderTextEditor::_load_theme_settings() { Color code_folding_color = EDITOR_GET("text_editor/highlighting/code_folding_color"); Color search_result_color = EDITOR_GET("text_editor/highlighting/search_result_color"); Color search_result_border_color = EDITOR_GET("text_editor/highlighting/search_result_border_color"); - Color symbol_color = EDITOR_GET("text_editor/highlighting/symbol_color"); - Color keyword_color = EDITOR_GET("text_editor/highlighting/keyword_color"); - Color comment_color = EDITOR_GET("text_editor/highlighting/comment_color"); - - get_text_edit()->add_theme_color_override("background_color", background_color); - get_text_edit()->add_theme_color_override("completion_background_color", completion_background_color); - get_text_edit()->add_theme_color_override("completion_selected_color", completion_selected_color); - get_text_edit()->add_theme_color_override("completion_existing_color", completion_existing_color); - get_text_edit()->add_theme_color_override("completion_scroll_color", completion_scroll_color); - get_text_edit()->add_theme_color_override("completion_font_color", completion_font_color); - get_text_edit()->add_theme_color_override("font_color", text_color); - get_text_edit()->add_theme_color_override("line_number_color", line_number_color); - get_text_edit()->add_theme_color_override("caret_color", caret_color); - get_text_edit()->add_theme_color_override("caret_background_color", caret_background_color); - get_text_edit()->add_theme_color_override("font_color_selected", text_selected_color); - get_text_edit()->add_theme_color_override("selection_color", selection_color); - get_text_edit()->add_theme_color_override("brace_mismatch_color", brace_mismatch_color); - get_text_edit()->add_theme_color_override("current_line_color", current_line_color); - get_text_edit()->add_theme_color_override("line_length_guideline_color", line_length_guideline_color); - get_text_edit()->add_theme_color_override("word_highlighted_color", word_highlighted_color); - get_text_edit()->add_theme_color_override("number_color", number_color); - get_text_edit()->add_theme_color_override("function_color", function_color); - get_text_edit()->add_theme_color_override("member_variable_color", member_variable_color); - get_text_edit()->add_theme_color_override("mark_color", mark_color); - get_text_edit()->add_theme_color_override("bookmark_color", bookmark_color); - get_text_edit()->add_theme_color_override("breakpoint_color", breakpoint_color); - get_text_edit()->add_theme_color_override("executing_line_color", executing_line_color); - get_text_edit()->add_theme_color_override("code_folding_color", code_folding_color); - get_text_edit()->add_theme_color_override("search_result_color", search_result_color); - get_text_edit()->add_theme_color_override("search_result_border_color", search_result_border_color); - get_text_edit()->add_theme_color_override("symbol_color", symbol_color); + + get_text_editor()->add_theme_color_override("background_color", background_color); + get_text_editor()->add_theme_color_override("completion_background_color", completion_background_color); + get_text_editor()->add_theme_color_override("completion_selected_color", completion_selected_color); + get_text_editor()->add_theme_color_override("completion_existing_color", completion_existing_color); + get_text_editor()->add_theme_color_override("completion_scroll_color", completion_scroll_color); + get_text_editor()->add_theme_color_override("completion_font_color", completion_font_color); + get_text_editor()->add_theme_color_override("font_color", text_color); + get_text_editor()->add_theme_color_override("line_number_color", line_number_color); + get_text_editor()->add_theme_color_override("caret_color", caret_color); + get_text_editor()->add_theme_color_override("caret_background_color", caret_background_color); + get_text_editor()->add_theme_color_override("font_selected_color", text_selected_color); + get_text_editor()->add_theme_color_override("selection_color", selection_color); + get_text_editor()->add_theme_color_override("brace_mismatch_color", brace_mismatch_color); + get_text_editor()->add_theme_color_override("current_line_color", current_line_color); + get_text_editor()->add_theme_color_override("line_length_guideline_color", line_length_guideline_color); + get_text_editor()->add_theme_color_override("word_highlighted_color", word_highlighted_color); + get_text_editor()->add_theme_color_override("mark_color", mark_color); + get_text_editor()->add_theme_color_override("bookmark_color", bookmark_color); + get_text_editor()->add_theme_color_override("breakpoint_color", breakpoint_color); + get_text_editor()->add_theme_color_override("executing_line_color", executing_line_color); + get_text_editor()->add_theme_color_override("code_folding_color", code_folding_color); + get_text_editor()->add_theme_color_override("search_result_color", search_result_color); + get_text_editor()->add_theme_color_override("search_result_border_color", search_result_border_color); + + syntax_highlighter->set_number_color(EDITOR_GET("text_editor/highlighting/number_color")); + syntax_highlighter->set_symbol_color(EDITOR_GET("text_editor/highlighting/symbol_color")); + syntax_highlighter->set_function_color(EDITOR_GET("text_editor/highlighting/function_color")); + syntax_highlighter->set_member_variable_color(EDITOR_GET("text_editor/highlighting/member_variable_color")); + + syntax_highlighter->clear_keyword_colors(); List<String> keywords; ShaderLanguage::get_keyword_list(&keywords); + const Color keyword_color = EDITOR_GET("text_editor/highlighting/keyword_color"); + + for (List<String>::Element *E = keywords.front(); E; E = E->next()) { + syntax_highlighter->add_keyword_color(E->get(), keyword_color); + } + + // Colorize built-ins like `COLOR` differently to make them easier + // to distinguish from keywords at a quick glance. + List<String> built_ins; if (shader.is_valid()) { for (const Map<StringName, ShaderLanguage::FunctionInfo>::Element *E = ShaderTypes::get_singleton()->get_functions(RenderingServer::ShaderMode(shader->get_mode())).front(); E; E = E->next()) { for (const Map<StringName, ShaderLanguage::BuiltInInfo>::Element *F = E->get().built_ins.front(); F; F = F->next()) { - keywords.push_back(F->key()); + built_ins.push_back(F->key()); } } for (int i = 0; i < ShaderTypes::get_singleton()->get_modes(RenderingServer::ShaderMode(shader->get_mode())).size(); i++) { - keywords.push_back(ShaderTypes::get_singleton()->get_modes(RenderingServer::ShaderMode(shader->get_mode()))[i]); + built_ins.push_back(ShaderTypes::get_singleton()->get_modes(RenderingServer::ShaderMode(shader->get_mode()))[i]); } } - for (List<String>::Element *E = keywords.front(); E; E = E->next()) { - get_text_edit()->add_keyword_color(E->get(), keyword_color); + const Color member_variable_color = EDITOR_GET("text_editor/highlighting/member_variable_color"); + + for (List<String>::Element *E = built_ins.front(); E; E = E->next()) { + syntax_highlighter->add_keyword_color(E->get(), member_variable_color); } - //colorize comments - get_text_edit()->add_color_region("/*", "*/", comment_color, false); - get_text_edit()->add_color_region("//", "", comment_color, false); + // Colorize comments. + const Color comment_color = EDITOR_GET("text_editor/highlighting/comment_color"); + syntax_highlighter->clear_color_regions(); + syntax_highlighter->add_color_region("/*", "*/", comment_color, false); + syntax_highlighter->add_color_region("//", "", comment_color, true); } void ShaderTextEditor::_check_shader_mode() { - String type = ShaderLanguage::get_shader_type(get_text_edit()->get_text()); + String type = ShaderLanguage::get_shader_type(get_text_editor()->get_text()); Shader::Mode mode; @@ -181,7 +189,7 @@ void ShaderTextEditor::_check_shader_mode() { } if (shader->get_mode() != mode) { - shader->set_code(get_text_edit()->get_text()); + shader->set_code(get_text_editor()->get_text()); _load_theme_settings(); } } @@ -199,13 +207,13 @@ void ShaderTextEditor::_code_complete_script(const String &p_code, List<ScriptCo sl.complete(p_code, ShaderTypes::get_singleton()->get_functions(RenderingServer::ShaderMode(shader->get_mode())), ShaderTypes::get_singleton()->get_modes(RenderingServer::ShaderMode(shader->get_mode())), ShaderTypes::get_singleton()->get_types(), _get_global_variable_type, r_options, calltip); - get_text_edit()->set_code_hint(calltip); + get_text_editor()->set_code_hint(calltip); } void ShaderTextEditor::_validate_script() { _check_shader_mode(); - String code = get_text_edit()->get_text(); + String code = get_text_editor()->get_text(); //List<StringName> params; //shader->get_param_list(¶ms); @@ -217,14 +225,14 @@ void ShaderTextEditor::_validate_script() { String error_text = "error(" + itos(sl.get_error_line()) + "): " + sl.get_error_text(); set_error(error_text); set_error_pos(sl.get_error_line() - 1, 0); - for (int i = 0; i < get_text_edit()->get_line_count(); i++) { - get_text_edit()->set_line_as_marked(i, false); + for (int i = 0; i < get_text_editor()->get_line_count(); i++) { + get_text_editor()->set_line_as_marked(i, false); } - get_text_edit()->set_line_as_marked(sl.get_error_line() - 1, true); + get_text_editor()->set_line_as_marked(sl.get_error_line() - 1, true); } else { - for (int i = 0; i < get_text_edit()->get_line_count(); i++) { - get_text_edit()->set_line_as_marked(i, false); + for (int i = 0; i < get_text_editor()->get_line_count(); i++) { + get_text_editor()->set_line_as_marked(i, false); } set_error(""); } @@ -236,6 +244,8 @@ void ShaderTextEditor::_bind_methods() { } ShaderTextEditor::ShaderTextEditor() { + syntax_highlighter.instance(); + get_text_editor()->set_syntax_highlighter(syntax_highlighter); } /*** SCRIPT EDITOR ******/ @@ -243,22 +253,22 @@ ShaderTextEditor::ShaderTextEditor() { void ShaderEditor::_menu_option(int p_option) { switch (p_option) { case EDIT_UNDO: { - shader_editor->get_text_edit()->undo(); + shader_editor->get_text_editor()->undo(); } break; case EDIT_REDO: { - shader_editor->get_text_edit()->redo(); + shader_editor->get_text_editor()->redo(); } break; case EDIT_CUT: { - shader_editor->get_text_edit()->cut(); + shader_editor->get_text_editor()->cut(); } break; case EDIT_COPY: { - shader_editor->get_text_edit()->copy(); + shader_editor->get_text_editor()->copy(); } break; case EDIT_PASTE: { - shader_editor->get_text_edit()->paste(); + shader_editor->get_text_editor()->paste(); } break; case EDIT_SELECT_ALL: { - shader_editor->get_text_edit()->select_all(); + shader_editor->get_text_editor()->select_all(); } break; case EDIT_MOVE_LINE_UP: { shader_editor->move_lines_up(); @@ -271,8 +281,8 @@ void ShaderEditor::_menu_option(int p_option) { return; } - TextEdit *tx = shader_editor->get_text_edit(); - tx->indent_left(); + CodeEdit *tx = shader_editor->get_text_editor(); + tx->indent_selected_lines_left(); } break; case EDIT_INDENT_RIGHT: { @@ -280,8 +290,8 @@ void ShaderEditor::_menu_option(int p_option) { return; } - TextEdit *tx = shader_editor->get_text_edit(); - tx->indent_right(); + CodeEdit *tx = shader_editor->get_text_editor(); + tx->indent_selected_lines_right(); } break; case EDIT_DELETE_LINE: { @@ -299,7 +309,7 @@ void ShaderEditor::_menu_option(int p_option) { } break; case EDIT_COMPLETE: { - shader_editor->get_text_edit()->query_code_comple(); + shader_editor->get_text_editor()->query_code_comple(); } break; case SEARCH_FIND: { shader_editor->get_find_replace_bar()->popup_search(); @@ -314,7 +324,7 @@ void ShaderEditor::_menu_option(int p_option) { shader_editor->get_find_replace_bar()->popup_replace(); } break; case SEARCH_GOTO_LINE: { - goto_line_dialog->popup_find_line(shader_editor->get_text_edit()); + goto_line_dialog->popup_find_line(shader_editor->get_text_editor()); } break; case BOOKMARK_TOGGLE: { shader_editor->toggle_bookmark(); @@ -329,16 +339,16 @@ void ShaderEditor::_menu_option(int p_option) { shader_editor->remove_all_bookmarks(); } break; case HELP_DOCS: { - OS::get_singleton()->shell_open("https://docs.godotengine.org/en/stable/tutorials/shading/shading_reference/index.html"); + OS::get_singleton()->shell_open("https://docs.godotengine.org/en/latest/tutorials/shaders/shader_reference/index.html"); } break; } if (p_option != SEARCH_FIND && p_option != SEARCH_REPLACE && p_option != SEARCH_GOTO_LINE) { - shader_editor->get_text_edit()->call_deferred("grab_focus"); + shader_editor->get_text_editor()->call_deferred("grab_focus"); } } void ShaderEditor::_notification(int p_what) { - if (p_what == NOTIFICATION_WM_FOCUS_IN) { + if (p_what == NOTIFICATION_WM_WINDOW_FOCUS_IN) { _check_for_external_edit(); } } @@ -348,29 +358,11 @@ void ShaderEditor::_params_changed() { } void ShaderEditor::_editor_settings_changed() { - shader_editor->get_text_edit()->set_auto_brace_completion(EditorSettings::get_singleton()->get("text_editor/completion/auto_brace_complete")); - shader_editor->get_text_edit()->set_scroll_pass_end_of_file(EditorSettings::get_singleton()->get("text_editor/cursor/scroll_past_end_of_file")); - shader_editor->get_text_edit()->set_indent_size(EditorSettings::get_singleton()->get("text_editor/indent/size")); - shader_editor->get_text_edit()->set_indent_using_spaces(EditorSettings::get_singleton()->get("text_editor/indent/type")); - shader_editor->get_text_edit()->set_auto_indent(EditorSettings::get_singleton()->get("text_editor/indent/auto_indent")); - shader_editor->get_text_edit()->set_draw_tabs(EditorSettings::get_singleton()->get("text_editor/indent/draw_tabs")); - shader_editor->get_text_edit()->set_draw_spaces(EditorSettings::get_singleton()->get("text_editor/indent/draw_spaces")); - shader_editor->get_text_edit()->set_show_line_numbers(EditorSettings::get_singleton()->get("text_editor/appearance/show_line_numbers")); - shader_editor->get_text_edit()->set_syntax_coloring(EditorSettings::get_singleton()->get("text_editor/highlighting/syntax_highlighting")); - shader_editor->get_text_edit()->set_highlight_all_occurrences(EditorSettings::get_singleton()->get("text_editor/highlighting/highlight_all_occurrences")); - shader_editor->get_text_edit()->set_highlight_current_line(EditorSettings::get_singleton()->get("text_editor/highlighting/highlight_current_line")); - shader_editor->get_text_edit()->cursor_set_blink_enabled(EditorSettings::get_singleton()->get("text_editor/cursor/caret_blink")); - shader_editor->get_text_edit()->cursor_set_blink_speed(EditorSettings::get_singleton()->get("text_editor/cursor/caret_blink_speed")); - shader_editor->get_text_edit()->add_theme_constant_override("line_spacing", EditorSettings::get_singleton()->get("text_editor/theme/line_spacing")); - shader_editor->get_text_edit()->cursor_set_block_mode(EditorSettings::get_singleton()->get("text_editor/cursor/block_caret")); - shader_editor->get_text_edit()->set_smooth_scroll_enabled(EditorSettings::get_singleton()->get("text_editor/navigation/smooth_scrolling")); - shader_editor->get_text_edit()->set_v_scroll_speed(EditorSettings::get_singleton()->get("text_editor/navigation/v_scroll_speed")); - shader_editor->get_text_edit()->set_draw_minimap(EditorSettings::get_singleton()->get("text_editor/navigation/show_minimap")); - shader_editor->get_text_edit()->set_minimap_width((int)EditorSettings::get_singleton()->get("text_editor/navigation/minimap_width") * EDSCALE); - shader_editor->get_text_edit()->set_show_line_length_guidelines(EditorSettings::get_singleton()->get("text_editor/appearance/show_line_length_guidelines")); - shader_editor->get_text_edit()->set_line_length_guideline_soft_column(EditorSettings::get_singleton()->get("text_editor/appearance/line_length_guideline_soft_column")); - shader_editor->get_text_edit()->set_line_length_guideline_hard_column(EditorSettings::get_singleton()->get("text_editor/appearance/line_length_guideline_hard_column")); - shader_editor->get_text_edit()->set_breakpoint_gutter_enabled(false); + shader_editor->update_editor_settings(); + + shader_editor->get_text_editor()->add_theme_constant_override("line_spacing", EditorSettings::get_singleton()->get("text_editor/theme/line_spacing")); + shader_editor->get_text_editor()->set_draw_breakpoints_gutter(false); + shader_editor->get_text_editor()->set_draw_executing_lines_gutter(false); } void ShaderEditor::_bind_methods() { @@ -380,7 +372,6 @@ void ShaderEditor::_bind_methods() { void ShaderEditor::ensure_select_current() { /* if (tab_container->get_child_count() && tab_container->get_current_tab()>=0) { - ShaderTextEditor *ste = Object::cast_to<ShaderTextEditor>(tab_container->get_child(tab_container->get_current_tab())); if (!ste) return; @@ -414,7 +405,7 @@ void ShaderEditor::_check_for_external_edit() { } void ShaderEditor::_reload_shader_from_disk() { - Ref<Shader> rel_shader = ResourceLoader::load(shader->get_path(), shader->get_class(), true); + Ref<Shader> rel_shader = ResourceLoader::load(shader->get_path(), shader->get_class(), ResourceFormatLoader::CACHE_MODE_IGNORE); ERR_FAIL_COND(!rel_shader.is_valid()); shader->set_code(rel_shader->get_code()); @@ -457,7 +448,7 @@ void ShaderEditor::save_external_data(const String &p_str) { void ShaderEditor::apply_shaders() { if (shader.is_valid()) { String shader_code = shader->get_code(); - String editor_code = shader_editor->get_text_edit()->get_text(); + String editor_code = shader_editor->get_text_editor()->get_text(); if (shader_code != editor_code) { shader->set_code(editor_code); shader->set_edited(true); @@ -471,7 +462,7 @@ void ShaderEditor::_text_edit_gui_input(const Ref<InputEvent> &ev) { if (mb.is_valid()) { if (mb->get_button_index() == BUTTON_RIGHT && mb->is_pressed()) { int col, row; - TextEdit *tx = shader_editor->get_text_edit(); + CodeEdit *tx = shader_editor->get_text_editor(); tx->_get_mouse_pos(mb->get_global_position() - tx->get_global_position(), row, col); tx->set_right_click_moves_caret(EditorSettings::get_singleton()->get("text_editor/cursor/right_click_moves_caret")); @@ -498,7 +489,7 @@ void ShaderEditor::_text_edit_gui_input(const Ref<InputEvent> &ev) { Ref<InputEventKey> k = ev; if (k.is_valid() && k->is_pressed() && k->get_keycode() == KEY_MENU) { - TextEdit *tx = shader_editor->get_text_edit(); + CodeEdit *tx = shader_editor->get_text_editor(); _make_context_menu(tx->is_selection_active(), (get_global_transform().inverse() * tx->get_global_transform()).xform(tx->_get_cursor_pixel_pos())); context_menu->grab_focus(); } @@ -512,7 +503,7 @@ void ShaderEditor::_update_bookmark_list() { bookmarks_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/goto_next_bookmark"), BOOKMARK_GOTO_NEXT); bookmarks_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/goto_previous_bookmark"), BOOKMARK_GOTO_PREV); - Array bookmark_list = shader_editor->get_text_edit()->get_bookmarks_array(); + Array bookmark_list = shader_editor->get_text_editor()->get_bookmarked_lines(); if (bookmark_list.size() == 0) { return; } @@ -520,7 +511,7 @@ void ShaderEditor::_update_bookmark_list() { bookmarks_menu->add_separator(); for (int i = 0; i < bookmark_list.size(); i++) { - String line = shader_editor->get_text_edit()->get_line(bookmark_list[i]).strip_edges(); + String line = shader_editor->get_text_editor()->get_line(bookmark_list[i]).strip_edges(); // Limit the size of the line if too big. if (line.length() > 50) { line = line.substr(0, 50); @@ -542,15 +533,15 @@ void ShaderEditor::_bookmark_item_pressed(int p_idx) { void ShaderEditor::_make_context_menu(bool p_selection, Vector2 p_position) { context_menu->clear(); if (p_selection) { - context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/cut"), EDIT_CUT); - context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/copy"), EDIT_COPY); + context_menu->add_shortcut(ED_GET_SHORTCUT("ui_cut"), EDIT_CUT); + context_menu->add_shortcut(ED_GET_SHORTCUT("ui_copy"), EDIT_COPY); } - context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/paste"), EDIT_PASTE); + context_menu->add_shortcut(ED_GET_SHORTCUT("ui_paste"), EDIT_PASTE); context_menu->add_separator(); - context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/select_all"), EDIT_SELECT_ALL); - context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/undo"), EDIT_UNDO); - context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/redo"), EDIT_REDO); + context_menu->add_shortcut(ED_GET_SHORTCUT("ui_text_select_all"), EDIT_SELECT_ALL); + context_menu->add_shortcut(ED_GET_SHORTCUT("ui_undo"), EDIT_UNDO); + context_menu->add_shortcut(ED_GET_SHORTCUT("ui_redo"), EDIT_REDO); context_menu->add_separator(); context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/indent_left"), EDIT_INDENT_LEFT); @@ -567,18 +558,18 @@ ShaderEditor::ShaderEditor(EditorNode *p_node) { shader_editor = memnew(ShaderTextEditor); shader_editor->set_v_size_flags(SIZE_EXPAND_FILL); shader_editor->add_theme_constant_override("separation", 0); - shader_editor->set_anchors_and_margins_preset(Control::PRESET_WIDE); + shader_editor->set_anchors_and_offsets_preset(Control::PRESET_WIDE); shader_editor->connect("script_changed", callable_mp(this, &ShaderEditor::apply_shaders)); EditorSettings::get_singleton()->connect("settings_changed", callable_mp(this, &ShaderEditor::_editor_settings_changed)); - shader_editor->get_text_edit()->set_callhint_settings( + shader_editor->get_text_editor()->set_callhint_settings( EditorSettings::get_singleton()->get("text_editor/completion/put_callhint_tooltip_below_current_line"), EditorSettings::get_singleton()->get("text_editor/completion/callhint_tooltip_offset")); - shader_editor->get_text_edit()->set_select_identifiers_on_hover(true); - shader_editor->get_text_edit()->set_context_menu_enabled(false); - shader_editor->get_text_edit()->connect("gui_input", callable_mp(this, &ShaderEditor::_text_edit_gui_input)); + shader_editor->get_text_editor()->set_select_identifiers_on_hover(true); + shader_editor->get_text_editor()->set_context_menu_enabled(false); + shader_editor->get_text_editor()->connect("gui_input", callable_mp(this, &ShaderEditor::_text_edit_gui_input)); shader_editor->update_editor_settings(); @@ -590,17 +581,18 @@ ShaderEditor::ShaderEditor(EditorNode *p_node) { HBoxContainer *hbc = memnew(HBoxContainer); edit_menu = memnew(MenuButton); + edit_menu->set_shortcut_context(this); edit_menu->set_text(TTR("Edit")); edit_menu->set_switch_on_hover(true); - edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/undo"), EDIT_UNDO); - edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/redo"), EDIT_REDO); + edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("ui_undo"), EDIT_UNDO); + edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("ui_redo"), EDIT_REDO); edit_menu->get_popup()->add_separator(); - edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/cut"), EDIT_CUT); - edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/copy"), EDIT_COPY); - edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/paste"), EDIT_PASTE); + edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("ui_cut"), EDIT_CUT); + edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("ui_copy"), EDIT_COPY); + edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("ui_paste"), EDIT_PASTE); edit_menu->get_popup()->add_separator(); - edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/select_all"), EDIT_SELECT_ALL); + edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("ui_text_select_all"), EDIT_SELECT_ALL); edit_menu->get_popup()->add_separator(); edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/move_up"), EDIT_MOVE_LINE_UP); edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/move_down"), EDIT_MOVE_LINE_DOWN); @@ -610,10 +602,11 @@ ShaderEditor::ShaderEditor(EditorNode *p_node) { edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/toggle_comment"), EDIT_TOGGLE_COMMENT); edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/clone_down"), EDIT_CLONE_DOWN); edit_menu->get_popup()->add_separator(); - edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/complete_symbol"), EDIT_COMPLETE); + edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("ui_text_completion_query"), EDIT_COMPLETE); edit_menu->get_popup()->connect("id_pressed", callable_mp(this, &ShaderEditor::_menu_option)); search_menu = memnew(MenuButton); + search_menu->set_shortcut_context(this); search_menu->set_text(TTR("Search")); search_menu->set_switch_on_hover(true); @@ -624,6 +617,7 @@ ShaderEditor::ShaderEditor(EditorNode *p_node) { search_menu->get_popup()->connect("id_pressed", callable_mp(this, &ShaderEditor::_menu_option)); MenuButton *goto_menu = memnew(MenuButton); + goto_menu->set_shortcut_context(this); goto_menu->set_text(TTR("Go To")); goto_menu->set_switch_on_hover(true); goto_menu->get_popup()->connect("id_pressed", callable_mp(this, &ShaderEditor::_menu_option)); @@ -667,9 +661,9 @@ ShaderEditor::ShaderEditor(EditorNode *p_node) { vbc->add_child(dl); disk_changed->connect("confirmed", callable_mp(this, &ShaderEditor::_reload_shader_from_disk)); - disk_changed->get_ok()->set_text(TTR("Reload")); + disk_changed->get_ok_button()->set_text(TTR("Reload")); - disk_changed->add_button(TTR("Resave"), !DisplayServer::get_singleton()->get_swap_ok_cancel(), "resave"); + disk_changed->add_button(TTR("Resave"), !DisplayServer::get_singleton()->get_swap_cancel_ok(), "resave"); disk_changed->connect("custom_action", callable_mp(this, &ShaderEditor::save_external_data)); add_child(disk_changed); @@ -720,6 +714,8 @@ ShaderEditorPlugin::ShaderEditorPlugin(EditorNode *p_node) { shader_editor->set_custom_minimum_size(Size2(0, 300) * EDSCALE); button = editor->add_bottom_panel_item(TTR("Shader"), shader_editor); button->hide(); + + _2d = false; } ShaderEditorPlugin::~ShaderEditorPlugin() { diff --git a/editor/plugins/shader_editor_plugin.h b/editor/plugins/shader_editor_plugin.h index 0208b43e13..731c0a5b7e 100644 --- a/editor/plugins/shader_editor_plugin.h +++ b/editor/plugins/shader_editor_plugin.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -44,18 +44,19 @@ class ShaderTextEditor : public CodeTextEditor { GDCLASS(ShaderTextEditor, CodeTextEditor); + Ref<CodeHighlighter> syntax_highlighter; Ref<Shader> shader; void _check_shader_mode(); protected: static void _bind_methods(); - virtual void _load_theme_settings(); + virtual void _load_theme_settings() override; - virtual void _code_complete_script(const String &p_code, List<ScriptCodeCompletionOption> *r_options); + virtual void _code_complete_script(const String &p_code, List<ScriptCodeCompletionOption> *r_options) override; public: - virtual void _validate_script(); + virtual void _validate_script() override; void reload_text(); @@ -68,7 +69,6 @@ class ShaderEditor : public PanelContainer { GDCLASS(ShaderEditor, PanelContainer); enum { - EDIT_UNDO, EDIT_REDO, EDIT_CUT, @@ -134,7 +134,7 @@ public: void goto_line_selection(int p_line, int p_begin, int p_end); - virtual Size2 get_minimum_size() const { return Size2(0, 200); } + virtual Size2 get_minimum_size() const override { return Size2(0, 200); } void save_external_data(const String &p_str = ""); ShaderEditor(EditorNode *p_node); @@ -149,17 +149,17 @@ class ShaderEditorPlugin : public EditorPlugin { Button *button; public: - virtual String get_name() const { return "Shader"; } - bool has_main_screen() const { return false; } - virtual void edit(Object *p_object); - virtual bool handles(Object *p_object) const; - virtual void make_visible(bool p_visible); - virtual void selected_notify(); + virtual String get_name() const override { return "Shader"; } + bool has_main_screen() const override { return false; } + virtual void edit(Object *p_object) override; + virtual bool handles(Object *p_object) const override; + virtual void make_visible(bool p_visible) override; + virtual void selected_notify() override; ShaderEditor *get_shader_editor() const { return shader_editor; } - virtual void save_external_data(); - virtual void apply_changes(); + virtual void save_external_data() override; + virtual void apply_changes() override; ShaderEditorPlugin(EditorNode *p_node); ~ShaderEditorPlugin(); diff --git a/editor/plugins/shader_file_editor_plugin.cpp b/editor/plugins/shader_file_editor_plugin.cpp index 0ac29f68f6..47d7f8204b 100644 --- a/editor/plugins/shader_file_editor_plugin.cpp +++ b/editor/plugins/shader_file_editor_plugin.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -59,7 +59,7 @@ void ShaderFileEditor::_version_selected(int p_option) { ERR_FAIL_COND(bytecode.is_null()); for (int i = 0; i < RD::SHADER_STAGE_MAX; i++) { - if (bytecode->get_stage_bytecode(RD::ShaderStage(i)).empty() && bytecode->get_stage_compile_error(RD::ShaderStage(i)) == String()) { + if (bytecode->get_stage_bytecode(RD::ShaderStage(i)).is_empty() && bytecode->get_stage_compile_error(RD::ShaderStage(i)) == String()) { stages[i]->set_icon(Ref<Texture2D>()); continue; } @@ -182,7 +182,7 @@ void ShaderFileEditor::_update_options() { for (int i = 0; i < RD::SHADER_STAGE_MAX; i++) { Vector<uint8_t> bc = bytecode->get_stage_bytecode(RD::ShaderStage(i)); String error = bytecode->get_stage_compile_error(RD::ShaderStage(i)); - bool disable = error == String() && bc.empty(); + bool disable = error == String() && bc.is_empty(); stages[i]->set_disabled(disable); if (!disable) { if (stages[i]->is_pressed()) { @@ -200,7 +200,7 @@ void ShaderFileEditor::_update_options() { } void ShaderFileEditor::_notification(int p_what) { - if (p_what == NOTIFICATION_WM_FOCUS_IN) { + if (p_what == NOTIFICATION_WM_WINDOW_FOCUS_IN) { if (is_visible_in_tree() && shader_file.is_valid()) { _update_options(); } diff --git a/editor/plugins/shader_file_editor_plugin.h b/editor/plugins/shader_file_editor_plugin.h index 19617366b2..7d6e503b6c 100644 --- a/editor/plugins/shader_file_editor_plugin.h +++ b/editor/plugins/shader_file_editor_plugin.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -77,11 +77,11 @@ class ShaderFileEditorPlugin : public EditorPlugin { Button *button; public: - virtual String get_name() const { return "ShaderFile"; } - bool has_main_screen() const { return false; } - virtual void edit(Object *p_object); - virtual bool handles(Object *p_object) const; - virtual void make_visible(bool p_visible); + virtual String get_name() const override { return "ShaderFile"; } + bool has_main_screen() const override { return false; } + virtual void edit(Object *p_object) override; + virtual bool handles(Object *p_object) const override; + virtual void make_visible(bool p_visible) override; ShaderFileEditor *get_shader_editor() const { return shader_editor; } diff --git a/editor/plugins/skeleton_2d_editor_plugin.cpp b/editor/plugins/skeleton_2d_editor_plugin.cpp index a198e4ff8f..44916e1d46 100644 --- a/editor/plugins/skeleton_2d_editor_plugin.cpp +++ b/editor/plugins/skeleton_2d_editor_plugin.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -129,7 +129,7 @@ void Skeleton2DEditorPlugin::make_visible(bool p_visible) { Skeleton2DEditorPlugin::Skeleton2DEditorPlugin(EditorNode *p_node) { editor = p_node; sprite_editor = memnew(Skeleton2DEditor); - editor->get_viewport()->add_child(sprite_editor); + editor->get_main_control()->add_child(sprite_editor); make_visible(false); //sprite_editor->options->hide(); diff --git a/editor/plugins/skeleton_2d_editor_plugin.h b/editor/plugins/skeleton_2d_editor_plugin.h index f1ba1a3612..dacd8fe43f 100644 --- a/editor/plugins/skeleton_2d_editor_plugin.h +++ b/editor/plugins/skeleton_2d_editor_plugin.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -70,11 +70,11 @@ class Skeleton2DEditorPlugin : public EditorPlugin { EditorNode *editor; public: - virtual String get_name() const { return "Skeleton2D"; } - bool has_main_screen() const { return false; } - virtual void edit(Object *p_object); - virtual bool handles(Object *p_object) const; - virtual void make_visible(bool p_visible); + virtual String get_name() const override { return "Skeleton2D"; } + bool has_main_screen() const override { return false; } + virtual void edit(Object *p_object) override; + virtual bool handles(Object *p_object) const override; + virtual void make_visible(bool p_visible) override; Skeleton2DEditorPlugin(EditorNode *p_node); ~Skeleton2DEditorPlugin(); diff --git a/editor/plugins/skeleton_3d_editor_plugin.cpp b/editor/plugins/skeleton_3d_editor_plugin.cpp index c256acd17b..121ccfa417 100644 --- a/editor/plugins/skeleton_3d_editor_plugin.cpp +++ b/editor/plugins/skeleton_3d_editor_plugin.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -30,13 +30,285 @@ #include "skeleton_3d_editor_plugin.h" +#include "core/io/resource_saver.h" +#include "editor/editor_file_dialog.h" +#include "editor/editor_properties.h" +#include "editor/editor_scale.h" +#include "editor/plugins/animation_player_editor_plugin.h" #include "node_3d_editor_plugin.h" #include "scene/3d/collision_shape_3d.h" +#include "scene/3d/mesh_instance_3d.h" #include "scene/3d/physics_body_3d.h" #include "scene/3d/physics_joint_3d.h" #include "scene/resources/capsule_shape_3d.h" #include "scene/resources/sphere_shape_3d.h" +void BoneTransformEditor::create_editors() { + const Color section_color = get_theme_color("prop_subsection", "Editor"); + + section = memnew(EditorInspectorSection); + section->setup("trf_properties", label, this, section_color, true); + add_child(section); + + key_button = memnew(Button); + key_button->set_text(TTR("Key Transform")); + key_button->set_visible(keyable); + key_button->set_icon(get_theme_icon("Key", "EditorIcons")); + key_button->set_flat(true); + section->get_vbox()->add_child(key_button); + + enabled_checkbox = memnew(CheckBox(TTR("Pose Enabled"))); + enabled_checkbox->set_flat(true); + enabled_checkbox->set_visible(toggle_enabled); + section->get_vbox()->add_child(enabled_checkbox); + + // Translation property + translation_property = memnew(EditorPropertyVector3()); + translation_property->setup(-10000, 10000, 0.001f, true); + translation_property->set_label("Translation"); + translation_property->set_use_folding(true); + translation_property->set_read_only(false); + translation_property->connect("property_changed", callable_mp(this, &BoneTransformEditor::_value_changed_vector3)); + section->get_vbox()->add_child(translation_property); + + // Rotation property + rotation_property = memnew(EditorPropertyVector3()); + rotation_property->setup(-10000, 10000, 0.001f, true); + rotation_property->set_label("Rotation Degrees"); + rotation_property->set_use_folding(true); + rotation_property->set_read_only(false); + rotation_property->connect("property_changed", callable_mp(this, &BoneTransformEditor::_value_changed_vector3)); + section->get_vbox()->add_child(rotation_property); + + // Scale property + scale_property = memnew(EditorPropertyVector3()); + scale_property->setup(-10000, 10000, 0.001f, true); + scale_property->set_label("Scale"); + scale_property->set_use_folding(true); + scale_property->set_read_only(false); + scale_property->connect("property_changed", callable_mp(this, &BoneTransformEditor::_value_changed_vector3)); + section->get_vbox()->add_child(scale_property); + + // Transform/Matrix section + transform_section = memnew(EditorInspectorSection); + transform_section->setup("trf_properties_transform", "Matrix", this, section_color, true); + section->get_vbox()->add_child(transform_section); + + // Transform/Matrix property + transform_property = memnew(EditorPropertyTransform()); + transform_property->setup(-10000, 10000, 0.001f, true); + transform_property->set_label("Transform"); + transform_property->set_use_folding(true); + transform_property->set_read_only(false); + transform_property->connect("property_changed", callable_mp(this, &BoneTransformEditor::_value_changed_transform)); + transform_section->get_vbox()->add_child(transform_property); +} + +void BoneTransformEditor::_notification(int p_what) { + switch (p_what) { + case NOTIFICATION_ENTER_TREE: { + create_editors(); + key_button->connect("pressed", callable_mp(this, &BoneTransformEditor::_key_button_pressed)); + enabled_checkbox->connect("toggled", callable_mp(this, &BoneTransformEditor::_checkbox_toggled)); + [[fallthrough]]; + } + case NOTIFICATION_SORT_CHILDREN: { + const Ref<Font> font = get_theme_font("font", "Tree"); + int font_size = get_theme_font_size("font_size", "Tree"); + + Point2 buffer; + buffer.x += get_theme_constant("inspector_margin", "Editor"); + buffer.y += font->get_height(font_size); + buffer.y += get_theme_constant("vseparation", "Tree"); + + const float vector_height = translation_property->get_size().y; + const float transform_height = transform_property->get_size().y; + const float button_height = key_button->get_size().y; + + const float width = get_size().x - get_theme_constant("inspector_margin", "Editor"); + Vector<Rect2> input_rects; + if (keyable && section->get_vbox()->is_visible()) { + input_rects.push_back(Rect2(key_button->get_position() + buffer, Size2(width, button_height))); + } else { + input_rects.push_back(Rect2(0, 0, 0, 0)); + } + + if (section->get_vbox()->is_visible()) { + input_rects.push_back(Rect2(translation_property->get_position() + buffer, Size2(width, vector_height))); + input_rects.push_back(Rect2(rotation_property->get_position() + buffer, Size2(width, vector_height))); + input_rects.push_back(Rect2(scale_property->get_position() + buffer, Size2(width, vector_height))); + input_rects.push_back(Rect2(transform_property->get_position() + buffer, Size2(width, transform_height))); + } else { + const int32_t start = input_rects.size(); + const int32_t empty_input_rect_elements = 4; + const int32_t end = start + empty_input_rect_elements; + for (int i = start; i < end; ++i) { + input_rects.push_back(Rect2(0, 0, 0, 0)); + } + } + + for (int32_t i = 0; i < input_rects.size(); i++) { + background_rects[i] = input_rects[i]; + } + + update(); + break; + } + case NOTIFICATION_DRAW: { + const Color dark_color = get_theme_color("dark_color_2", "Editor"); + + for (int i = 0; i < 5; ++i) { + draw_rect(background_rects[i], dark_color); + } + + break; + } + } +} + +void BoneTransformEditor::_value_changed(const double p_value) { + if (updating) + return; + + Transform tform = compute_transform_from_vector3s(); + _change_transform(tform); +} + +void BoneTransformEditor::_value_changed_vector3(const String p_property_name, const Vector3 p_vector, const StringName p_edited_property_name, const bool p_boolean) { + if (updating) + return; + Transform tform = compute_transform_from_vector3s(); + _change_transform(tform); +} + +Transform BoneTransformEditor::compute_transform_from_vector3s() const { + // Convert rotation from degrees to radians. + Vector3 prop_rotation = rotation_property->get_vector(); + prop_rotation.x = Math::deg2rad(prop_rotation.x); + prop_rotation.y = Math::deg2rad(prop_rotation.y); + prop_rotation.z = Math::deg2rad(prop_rotation.z); + + return Transform( + Basis(prop_rotation, scale_property->get_vector()), + translation_property->get_vector()); +} + +void BoneTransformEditor::_value_changed_transform(const String p_property_name, const Transform p_transform, const StringName p_edited_property_name, const bool p_boolean) { + if (updating) + return; + _change_transform(p_transform); +} + +void BoneTransformEditor::_change_transform(Transform p_new_transform) { + if (property.get_slicec('/', 0) == "bones" && property.get_slicec('/', 2) == "custom_pose") { + undo_redo->create_action(TTR("Set Custom Bone Pose Transform"), UndoRedo::MERGE_ENDS); + undo_redo->add_undo_method(skeleton, "set_bone_custom_pose", property.get_slicec('/', 1).to_int(), skeleton->get_bone_custom_pose(property.get_slicec('/', 1).to_int())); + undo_redo->add_do_method(skeleton, "set_bone_custom_pose", property.get_slicec('/', 1).to_int(), p_new_transform); + undo_redo->commit_action(); + } else if (property.get_slicec('/', 0) == "bones") { + undo_redo->create_action(TTR("Set Bone Transform"), UndoRedo::MERGE_ENDS); + undo_redo->add_undo_property(skeleton, property, skeleton->get(property)); + undo_redo->add_do_property(skeleton, property, p_new_transform); + undo_redo->commit_action(); + } +} + +void BoneTransformEditor::update_enabled_checkbox() { + if (enabled_checkbox) { + const String path = "bones/" + property.get_slicec('/', 1) + "/enabled"; + const bool is_enabled = skeleton->get(path); + enabled_checkbox->set_pressed(is_enabled); + } +} + +void BoneTransformEditor::_update_properties() { + if (updating) + return; + + if (skeleton == nullptr) + return; + + updating = true; + + Transform tform = skeleton->get(property); + _update_transform_properties(tform); +} + +void BoneTransformEditor::_update_custom_pose_properties() { + if (updating) + return; + + if (skeleton == nullptr) + return; + + updating = true; + + Transform tform = skeleton->get_bone_custom_pose(property.to_int()); + _update_transform_properties(tform); +} + +void BoneTransformEditor::_update_transform_properties(Transform tform) { + Basis rotation_basis = tform.get_basis(); + Vector3 rotation_radians = rotation_basis.get_rotation_euler(); + Vector3 rotation_degrees = Vector3(Math::rad2deg(rotation_radians.x), Math::rad2deg(rotation_radians.y), Math::rad2deg(rotation_radians.z)); + Vector3 translation = tform.get_origin(); + Vector3 scale = tform.basis.get_scale(); + + translation_property->update_using_vector(translation); + rotation_property->update_using_vector(rotation_degrees); + scale_property->update_using_vector(scale); + transform_property->update_using_transform(tform); + + update_enabled_checkbox(); + updating = false; +} + +BoneTransformEditor::BoneTransformEditor(Skeleton3D *p_skeleton) : + skeleton(p_skeleton) { + undo_redo = EditorNode::get_undo_redo(); +} + +void BoneTransformEditor::set_target(const String &p_prop) { + property = p_prop; +} + +void BoneTransformEditor::set_keyable(const bool p_keyable) { + keyable = p_keyable; + if (key_button) { + key_button->set_visible(p_keyable); + } +} + +void BoneTransformEditor::set_toggle_enabled(const bool p_enabled) { + toggle_enabled = p_enabled; + if (enabled_checkbox) { + enabled_checkbox->set_visible(p_enabled); + } +} + +void BoneTransformEditor::_key_button_pressed() { + if (skeleton == nullptr) + return; + + const BoneId bone_id = property.get_slicec('/', 1).to_int(); + const String name = skeleton->get_bone_name(bone_id); + + if (name.is_empty()) + return; + + // Need to normalize the basis before you key it + Transform tform = compute_transform_from_vector3s(); + tform.orthonormalize(); + AnimationPlayerEditor::singleton->get_track_editor()->insert_transform_key(skeleton, name, tform); +} + +void BoneTransformEditor::_checkbox_toggled(const bool p_toggled) { + if (enabled_checkbox) { + const String path = "bones/" + property.get_slicec('/', 1) + "/enabled"; + skeleton->set(path, p_toggled); + } +} + void Skeleton3DEditor::_on_click_option(int p_option) { if (!skeleton) { return; @@ -45,12 +317,14 @@ void Skeleton3DEditor::_on_click_option(int p_option) { switch (p_option) { case MENU_OPTION_CREATE_PHYSICAL_SKELETON: { create_physical_skeleton(); - } break; + break; + } } } void Skeleton3DEditor::create_physical_skeleton() { UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo(); + ERR_FAIL_COND(!get_tree()); Node *owner = skeleton == get_tree()->get_edited_scene_root() ? skeleton : skeleton->get_owner(); const int bc = skeleton->get_bone_count(); @@ -109,8 +383,12 @@ PhysicalBone3D *Skeleton3DEditor::create_physical_bone(int bone_id, int bone_chi CollisionShape3D *bone_shape = memnew(CollisionShape3D); bone_shape->set_shape(bone_shape_capsule); + Transform capsule_transform; + capsule_transform.basis = Basis(Vector3(1, 0, 0), Vector3(0, 0, 1), Vector3(0, -1, 0)); + bone_shape->set_transform(capsule_transform); + Transform body_transform; - body_transform.set_look_at(Vector3(0, 0, 0), child_rest.origin, Vector3(0, 1, 0)); + body_transform.set_look_at(Vector3(0, 0, 0), child_rest.origin); body_transform.origin = body_transform.basis.xform(Vector3(0, 0, -half_height)); Transform joint_transform; @@ -124,28 +402,163 @@ PhysicalBone3D *Skeleton3DEditor::create_physical_bone(int bone_id, int bone_chi return physical_bone; } -void Skeleton3DEditor::edit(Skeleton3D *p_node) { - skeleton = p_node; +Variant Skeleton3DEditor::get_drag_data_fw(const Point2 &p_point, Control *p_from) { + TreeItem *selected = joint_tree->get_selected(); + + if (!selected) + return Variant(); + + Ref<Texture> icon = selected->get_icon(0); + + VBoxContainer *vb = memnew(VBoxContainer); + HBoxContainer *hb = memnew(HBoxContainer); + TextureRect *tf = memnew(TextureRect); + tf->set_texture(icon); + tf->set_stretch_mode(TextureRect::STRETCH_KEEP_CENTERED); + hb->add_child(tf); + Label *label = memnew(Label(selected->get_text(0))); + hb->add_child(label); + vb->add_child(hb); + hb->set_modulate(Color(1, 1, 1, 1)); + + set_drag_preview(vb); + Dictionary drag_data; + drag_data["type"] = "nodes"; + drag_data["node"] = selected; + + return drag_data; } -void Skeleton3DEditor::_notification(int p_what) { - if (p_what == NOTIFICATION_ENTER_TREE) { - get_tree()->connect("node_removed", callable_mp(this, &Skeleton3DEditor::_node_removed)); +bool Skeleton3DEditor::can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const { + TreeItem *target = joint_tree->get_item_at_position(p_point); + if (!target) + return false; + + const String path = target->get_metadata(0); + if (!path.begins_with("bones/")) + return false; + + TreeItem *selected = Object::cast_to<TreeItem>(Dictionary(p_data)["node"]); + if (target == selected) + return false; + + const String path2 = target->get_metadata(0); + if (!path2.begins_with("bones/")) + return false; + + return true; +} + +void Skeleton3DEditor::drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) { + if (!can_drop_data_fw(p_point, p_data, p_from)) + return; + + TreeItem *target = joint_tree->get_item_at_position(p_point); + TreeItem *selected = Object::cast_to<TreeItem>(Dictionary(p_data)["node"]); + + const BoneId target_boneidx = String(target->get_metadata(0)).get_slicec('/', 1).to_int(); + const BoneId selected_boneidx = String(selected->get_metadata(0)).get_slicec('/', 1).to_int(); + + move_skeleton_bone(skeleton->get_path(), selected_boneidx, target_boneidx); +} + +void Skeleton3DEditor::move_skeleton_bone(NodePath p_skeleton_path, int32_t p_selected_boneidx, int32_t p_target_boneidx) { + Node *node = get_node_or_null(p_skeleton_path); + Skeleton3D *skeleton = Object::cast_to<Skeleton3D>(node); + ERR_FAIL_NULL(skeleton); + UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo(); + ur->create_action(TTR("Set Bone Parentage")); + // If the target is a child of ourselves, we move only *us* and not our children + if (skeleton->is_bone_parent_of(p_target_boneidx, p_selected_boneidx)) { + const BoneId parent_idx = skeleton->get_bone_parent(p_selected_boneidx); + const int bone_count = skeleton->get_bone_count(); + for (BoneId i = 0; i < bone_count; ++i) { + if (skeleton->get_bone_parent(i) == p_selected_boneidx) { + ur->add_undo_method(skeleton, "set_bone_parent", i, skeleton->get_bone_parent(i)); + ur->add_do_method(skeleton, "set_bone_parent", i, parent_idx); + skeleton->set_bone_parent(i, parent_idx); + } + } } + ur->add_undo_method(skeleton, "set_bone_parent", p_selected_boneidx, skeleton->get_bone_parent(p_selected_boneidx)); + ur->add_do_method(skeleton, "set_bone_parent", p_selected_boneidx, p_target_boneidx); + skeleton->set_bone_parent(p_selected_boneidx, p_target_boneidx); + + update_joint_tree(); + ur->commit_action(); } -void Skeleton3DEditor::_node_removed(Node *p_node) { - if (p_node == skeleton) { - skeleton = nullptr; - options->hide(); +void Skeleton3DEditor::_joint_tree_selection_changed() { + TreeItem *selected = joint_tree->get_selected(); + const String path = selected->get_metadata(0); + + if (path.begins_with("bones/")) { + const int b_idx = path.get_slicec('/', 1).to_int(); + const String bone_path = "bones/" + itos(b_idx) + "/"; + + pose_editor->set_target(bone_path + "pose"); + rest_editor->set_target(bone_path + "rest"); + custom_pose_editor->set_target(bone_path + "custom_pose"); + + pose_editor->set_visible(true); + rest_editor->set_visible(true); + custom_pose_editor->set_visible(true); } } -void Skeleton3DEditor::_bind_methods() { +void Skeleton3DEditor::_joint_tree_rmb_select(const Vector2 &p_pos) { } -Skeleton3DEditor::Skeleton3DEditor() { - skeleton = nullptr; +void Skeleton3DEditor::_update_properties() { + if (rest_editor) + rest_editor->_update_properties(); + if (pose_editor) + pose_editor->_update_properties(); + if (custom_pose_editor) + custom_pose_editor->_update_custom_pose_properties(); +} + +void Skeleton3DEditor::update_joint_tree() { + joint_tree->clear(); + + if (skeleton == nullptr) + return; + + TreeItem *root = joint_tree->create_item(); + + Map<int, TreeItem *> items; + + items.insert(-1, root); + + const Vector<int> &joint_porder = skeleton->get_bone_process_orders(); + Ref<Texture> bone_icon = get_theme_icon("BoneAttachment3D", "EditorIcons"); + + for (int i = 0; i < joint_porder.size(); ++i) { + const int b_idx = joint_porder[i]; + + const int p_idx = skeleton->get_bone_parent(b_idx); + TreeItem *p_item = items.find(p_idx)->get(); + + TreeItem *joint_item = joint_tree->create_item(p_item); + items.insert(b_idx, joint_item); + + joint_item->set_text(0, skeleton->get_bone_name(b_idx)); + joint_item->set_icon(0, bone_icon); + joint_item->set_selectable(0, true); + joint_item->set_metadata(0, "bones/" + itos(b_idx)); + } +} + +void Skeleton3DEditor::update_editors() { +} + +void Skeleton3DEditor::create_editors() { + set_h_size_flags(SIZE_EXPAND_FILL); + add_theme_constant_override("separation", 0); + + set_focus_mode(FOCUS_ALL); + + // Create Top Menu Bar options = memnew(MenuButton); Node3DEditor::get_singleton()->add_control_to_menu_panel(options); @@ -155,32 +568,119 @@ Skeleton3DEditor::Skeleton3DEditor() { options->get_popup()->add_item(TTR("Create physical skeleton"), MENU_OPTION_CREATE_PHYSICAL_SKELETON); options->get_popup()->connect("id_pressed", callable_mp(this, &Skeleton3DEditor::_on_click_option)); - options->hide(); + + const Color section_color = get_theme_color("prop_subsection", "Editor"); + + EditorInspectorSection *bones_section = memnew(EditorInspectorSection); + bones_section->setup("bones", "Bones", skeleton, section_color, true); + add_child(bones_section); + bones_section->unfold(); + + ScrollContainer *s_con = memnew(ScrollContainer); + s_con->set_h_size_flags(SIZE_EXPAND_FILL); + s_con->set_custom_minimum_size(Size2(1, 350) * EDSCALE); + bones_section->get_vbox()->add_child(s_con); + + joint_tree = memnew(Tree); + joint_tree->set_columns(1); + joint_tree->set_focus_mode(Control::FocusMode::FOCUS_NONE); + joint_tree->set_select_mode(Tree::SELECT_SINGLE); + joint_tree->set_hide_root(true); + joint_tree->set_v_size_flags(SIZE_EXPAND_FILL); + joint_tree->set_h_size_flags(SIZE_EXPAND_FILL); + joint_tree->set_allow_rmb_select(true); + joint_tree->set_drag_forwarding(this); + s_con->add_child(joint_tree); + + pose_editor = memnew(BoneTransformEditor(skeleton)); + pose_editor->set_label(TTR("Bone Pose")); + pose_editor->set_keyable(AnimationPlayerEditor::singleton->get_track_editor()->has_keying()); + pose_editor->set_toggle_enabled(true); + pose_editor->set_visible(false); + add_child(pose_editor); + + rest_editor = memnew(BoneTransformEditor(skeleton)); + rest_editor->set_label(TTR("Bone Rest")); + rest_editor->set_visible(false); + add_child(rest_editor); + + custom_pose_editor = memnew(BoneTransformEditor(skeleton)); + custom_pose_editor->set_label(TTR("Bone Custom Pose")); + custom_pose_editor->set_visible(false); + add_child(custom_pose_editor); +} + +void Skeleton3DEditor::_notification(int p_what) { + switch (p_what) { + case NOTIFICATION_ENTER_TREE: { + create_editors(); + update_joint_tree(); + update_editors(); + + get_tree()->connect("node_removed", callable_mp(this, &Skeleton3DEditor::_node_removed), Vector<Variant>(), Object::CONNECT_ONESHOT); + joint_tree->connect("item_selected", callable_mp(this, &Skeleton3DEditor::_joint_tree_selection_changed)); + joint_tree->connect("item_rmb_selected", callable_mp(this, &Skeleton3DEditor::_joint_tree_rmb_select)); +#ifdef TOOLS_ENABLED + skeleton->connect("pose_updated", callable_mp(this, &Skeleton3DEditor::_update_properties)); +#endif // TOOLS_ENABLED + + break; + } + } } -Skeleton3DEditor::~Skeleton3DEditor() {} +void Skeleton3DEditor::_node_removed(Node *p_node) { + if (skeleton && p_node == skeleton) { + skeleton = nullptr; + options->hide(); + } + + _update_properties(); +} -void Skeleton3DEditorPlugin::edit(Object *p_object) { - skeleton_editor->edit(Object::cast_to<Skeleton3D>(p_object)); +void Skeleton3DEditor::_bind_methods() { + ClassDB::bind_method(D_METHOD("_node_removed"), &Skeleton3DEditor::_node_removed); + ClassDB::bind_method(D_METHOD("_joint_tree_selection_changed"), &Skeleton3DEditor::_joint_tree_selection_changed); + ClassDB::bind_method(D_METHOD("_joint_tree_rmb_select"), &Skeleton3DEditor::_joint_tree_rmb_select); + ClassDB::bind_method(D_METHOD("_update_properties"), &Skeleton3DEditor::_update_properties); + ClassDB::bind_method(D_METHOD("_on_click_option"), &Skeleton3DEditor::_on_click_option); + + ClassDB::bind_method(D_METHOD("get_drag_data_fw"), &Skeleton3DEditor::get_drag_data_fw); + ClassDB::bind_method(D_METHOD("can_drop_data_fw"), &Skeleton3DEditor::can_drop_data_fw); + ClassDB::bind_method(D_METHOD("drop_data_fw"), &Skeleton3DEditor::drop_data_fw); + ClassDB::bind_method(D_METHOD("move_skeleton_bone"), &Skeleton3DEditor::move_skeleton_bone); } -bool Skeleton3DEditorPlugin::handles(Object *p_object) const { - return p_object->is_class("Skeleton3D"); +Skeleton3DEditor::Skeleton3DEditor(EditorInspectorPluginSkeleton *e_plugin, EditorNode *p_editor, Skeleton3D *p_skeleton) : + editor(p_editor), + editor_plugin(e_plugin), + skeleton(p_skeleton) { } -void Skeleton3DEditorPlugin::make_visible(bool p_visible) { - if (p_visible) { - skeleton_editor->options->show(); - } else { - skeleton_editor->options->hide(); - skeleton_editor->edit(nullptr); +Skeleton3DEditor::~Skeleton3DEditor() { + if (options) { + Node3DEditor::get_singleton()->remove_control_from_menu_panel(options); } } +bool EditorInspectorPluginSkeleton::can_handle(Object *p_object) { + return Object::cast_to<Skeleton3D>(p_object) != nullptr; +} + +void EditorInspectorPluginSkeleton::parse_begin(Object *p_object) { + Skeleton3D *skeleton = Object::cast_to<Skeleton3D>(p_object); + ERR_FAIL_COND(!skeleton); + + Skeleton3DEditor *skel_editor = memnew(Skeleton3DEditor(this, editor, skeleton)); + add_custom_control(skel_editor); +} + Skeleton3DEditorPlugin::Skeleton3DEditorPlugin(EditorNode *p_node) { editor = p_node; - skeleton_editor = memnew(Skeleton3DEditor); - editor->get_viewport()->add_child(skeleton_editor); -} -Skeleton3DEditorPlugin::~Skeleton3DEditorPlugin() {} + Ref<EditorInspectorPluginSkeleton> skeleton_plugin; + skeleton_plugin.instance(); + skeleton_plugin->editor = editor; + + EditorInspector::add_inspector_plugin(skeleton_plugin); +} diff --git a/editor/plugins/skeleton_3d_editor_plugin.h b/editor/plugins/skeleton_3d_editor_plugin.h index af9ebb6246..14c213f7b2 100644 --- a/editor/plugins/skeleton_3d_editor_plugin.h +++ b/editor/plugins/skeleton_3d_editor_plugin.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -35,11 +35,91 @@ #include "editor/editor_plugin.h" #include "scene/3d/skeleton_3d.h" +class EditorInspectorPluginSkeleton; +class Joint; class PhysicalBone3D; -class Joint3D; +class Skeleton3DEditorPlugin; +class Button; +class CheckBox; +class EditorPropertyTransform; +class EditorPropertyVector3; -class Skeleton3DEditor : public Node { - GDCLASS(Skeleton3DEditor, Node); +class BoneTransformEditor : public VBoxContainer { + GDCLASS(BoneTransformEditor, VBoxContainer); + + EditorInspectorSection *section = nullptr; + + EditorPropertyVector3 *translation_property = nullptr; + EditorPropertyVector3 *rotation_property = nullptr; + EditorPropertyVector3 *scale_property = nullptr; + EditorInspectorSection *transform_section = nullptr; + EditorPropertyTransform *transform_property = nullptr; + + Rect2 background_rects[5]; + + Skeleton3D *skeleton; + String property; + + UndoRedo *undo_redo; + + Button *key_button = nullptr; + CheckBox *enabled_checkbox = nullptr; + + bool keyable = false; + bool toggle_enabled = false; + bool updating = false; + + String label; + + void create_editors(); + + // Called when one of the EditorSpinSliders are changed. + void _value_changed(const double p_value); + // Called when the one of the EditorPropertyVector3 are updated. + void _value_changed_vector3(const String p_property_name, const Vector3 p_vector, const StringName p_edited_property_name, const bool p_boolean); + // Called when the transform_property is updated. + void _value_changed_transform(const String p_property_name, const Transform p_transform, const StringName p_edited_property_name, const bool p_boolean); + // Changes the transform to the given transform and updates the UI accordingly. + void _change_transform(Transform p_new_transform); + // Creates a Transform using the EditorPropertyVector3 properties. + Transform compute_transform_from_vector3s() const; + + void update_enabled_checkbox(); + +protected: + void _notification(int p_what); + +public: + BoneTransformEditor(Skeleton3D *p_skeleton); + + // Which transform target to modify + void set_target(const String &p_prop); + void set_label(const String &p_label) { label = p_label; } + + void _update_properties(); + void _update_custom_pose_properties(); + void _update_transform_properties(Transform p_transform); + + // Can/cannot modify the spinner values for the Transform + void set_read_only(const bool p_read_only); + + // Transform can be keyed, whether or not to show the button + void set_keyable(const bool p_keyable); + + // Bone can be toggled enabled or disabled, whether or not to show the checkbox + void set_toggle_enabled(const bool p_enabled); + + // Key Transform Button pressed + void _key_button_pressed(); + + // Bone Enabled Checkbox toggled + void _checkbox_toggled(const bool p_toggled); +}; + +class Skeleton3DEditor : public VBoxContainer { + GDCLASS(Skeleton3DEditor, VBoxContainer); + + friend class Skeleton3DEditorPlugin; enum Menu { MENU_OPTION_CREATE_PHYSICAL_SKELETON @@ -48,47 +128,80 @@ class Skeleton3DEditor : public Node { struct BoneInfo { PhysicalBone3D *physical_bone = nullptr; Transform relative_rest; // Relative to skeleton node - BoneInfo() {} }; + EditorNode *editor; + EditorInspectorPluginSkeleton *editor_plugin; + Skeleton3D *skeleton; - MenuButton *options; + Tree *joint_tree = nullptr; + BoneTransformEditor *rest_editor = nullptr; + BoneTransformEditor *pose_editor = nullptr; + BoneTransformEditor *custom_pose_editor = nullptr; + + MenuButton *options = nullptr; + EditorFileDialog *file_dialog = nullptr; + + UndoRedo *undo_redo = nullptr; void _on_click_option(int p_option); + void _file_selected(const String &p_file); - friend class Skeleton3DEditorPlugin; + EditorFileDialog *file_export_lib = nullptr; + + void update_joint_tree(); + void update_editors(); + + void create_editors(); + + void create_physical_skeleton(); + PhysicalBone3D *create_physical_bone(int bone_id, int bone_child_id, const Vector<BoneInfo> &bones_infos); + + Variant get_drag_data_fw(const Point2 &p_point, Control *p_from); + bool can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const; + void drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from); protected: void _notification(int p_what); void _node_removed(Node *p_node); static void _bind_methods(); - void create_physical_skeleton(); - PhysicalBone3D *create_physical_bone(int bone_id, int bone_child_id, const Vector<BoneInfo> &bones_infos); - public: - void edit(Skeleton3D *p_node); + void move_skeleton_bone(NodePath p_skeleton_path, int32_t p_selected_boneidx, int32_t p_target_boneidx); - Skeleton3DEditor(); + Skeleton3D *get_skeleton() const { return skeleton; }; + + void _joint_tree_selection_changed(); + void _joint_tree_rmb_select(const Vector2 &p_pos); + + void _update_properties(); + + Skeleton3DEditor(EditorInspectorPluginSkeleton *e_plugin, EditorNode *p_editor, Skeleton3D *skeleton); ~Skeleton3DEditor(); }; +class EditorInspectorPluginSkeleton : public EditorInspectorPlugin { + GDCLASS(EditorInspectorPluginSkeleton, EditorInspectorPlugin); + + friend class Skeleton3DEditorPlugin; + + EditorNode *editor; + +public: + virtual bool can_handle(Object *p_object) override; + virtual void parse_begin(Object *p_object) override; +}; + class Skeleton3DEditorPlugin : public EditorPlugin { GDCLASS(Skeleton3DEditorPlugin, EditorPlugin); EditorNode *editor; - Skeleton3DEditor *skeleton_editor; public: - virtual String get_name() const { return "Skeleton3D"; } - virtual bool has_main_screen() const { return false; } - virtual void edit(Object *p_object); - virtual bool handles(Object *p_object) const; - virtual void make_visible(bool p_visible); - Skeleton3DEditorPlugin(EditorNode *p_node); - ~Skeleton3DEditorPlugin(); + + virtual String get_name() const override { return "Skeleton3D"; } }; #endif // SKELETON_3D_EDITOR_PLUGIN_H diff --git a/editor/plugins/skeleton_ik_3d_editor_plugin.cpp b/editor/plugins/skeleton_ik_3d_editor_plugin.cpp index 8fc789b94a..2da49c1c0b 100644 --- a/editor/plugins/skeleton_ik_3d_editor_plugin.cpp +++ b/editor/plugins/skeleton_ik_3d_editor_plugin.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ diff --git a/editor/plugins/skeleton_ik_3d_editor_plugin.h b/editor/plugins/skeleton_ik_3d_editor_plugin.h index bd4c5ba93e..b0d2138115 100644 --- a/editor/plugins/skeleton_ik_3d_editor_plugin.h +++ b/editor/plugins/skeleton_ik_3d_editor_plugin.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -50,11 +50,11 @@ protected: static void _bind_methods(); public: - virtual String get_name() const { return "SkeletonIK3D"; } - bool has_main_screen() const { return false; } - virtual void edit(Object *p_object); - virtual bool handles(Object *p_object) const; - virtual void make_visible(bool p_visible); + virtual String get_name() const override { return "SkeletonIK3D"; } + bool has_main_screen() const override { return false; } + virtual void edit(Object *p_object) override; + virtual bool handles(Object *p_object) const override; + virtual void make_visible(bool p_visible) override; SkeletonIK3DEditorPlugin(EditorNode *p_node); ~SkeletonIK3DEditorPlugin(); diff --git a/editor/plugins/sprite_2d_editor_plugin.cpp b/editor/plugins/sprite_2d_editor_plugin.cpp index b21586a6b0..4949d2b9b7 100644 --- a/editor/plugins/sprite_2d_editor_plugin.cpp +++ b/editor/plugins/sprite_2d_editor_plugin.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -31,6 +31,7 @@ #include "sprite_2d_editor_plugin.h" #include "canvas_item_editor_plugin.h" +#include "core/math/geometry_2d.h" #include "editor/editor_scale.h" #include "scene/2d/collision_polygon_2d.h" #include "scene/2d/light_occluder_2d.h" @@ -119,7 +120,7 @@ void Sprite2DEditor::_menu_option(int p_option) { switch (p_option) { case MENU_OPTION_CONVERT_TO_MESH_2D: { - debug_uv_dialog->get_ok()->set_text(TTR("Create Mesh2D")); + debug_uv_dialog->get_ok_button()->set_text(TTR("Create Mesh2D")); debug_uv_dialog->set_title(TTR("Mesh2D Preview")); _update_mesh_data(); @@ -128,7 +129,7 @@ void Sprite2DEditor::_menu_option(int p_option) { } break; case MENU_OPTION_CONVERT_TO_POLYGON_2D: { - debug_uv_dialog->get_ok()->set_text(TTR("Create Polygon2D")); + debug_uv_dialog->get_ok_button()->set_text(TTR("Create Polygon2D")); debug_uv_dialog->set_title(TTR("Polygon2D Preview")); _update_mesh_data(); @@ -136,7 +137,7 @@ void Sprite2DEditor::_menu_option(int p_option) { debug_uv->update(); } break; case MENU_OPTION_CREATE_COLLISION_POLY_2D: { - debug_uv_dialog->get_ok()->set_text(TTR("Create CollisionPolygon2D")); + debug_uv_dialog->get_ok_button()->set_text(TTR("Create CollisionPolygon2D")); debug_uv_dialog->set_title(TTR("CollisionPolygon2D Preview")); _update_mesh_data(); @@ -145,7 +146,7 @@ void Sprite2DEditor::_menu_option(int p_option) { } break; case MENU_OPTION_CREATE_LIGHT_OCCLUDER_2D: { - debug_uv_dialog->get_ok()->set_text(TTR("Create LightOccluder2D")); + debug_uv_dialog->get_ok_button()->set_text(TTR("Create LightOccluder2D")); debug_uv_dialog->set_title(TTR("LightOccluder2D Preview")); _update_mesh_data(); @@ -172,6 +173,11 @@ void Sprite2DEditor::_update_mesh_data() { Ref<Image> image = texture->get_data(); ERR_FAIL_COND(image.is_null()); + + if (image->is_compressed()) { + image->decompress(); + } + Rect2 rect; if (node->is_region()) { rect = node->get_region_rect(); @@ -233,7 +239,7 @@ void Sprite2DEditor::_update_mesh_data() { computed_vertices.push_back(vtx); } - Vector<int> poly = Geometry::triangulate_polygon(lines[j]); + Vector<int> poly = Geometry2D::triangulate_polygon(lines[j]); for (int i = 0; i < poly.size(); i += 3) { for (int k = 0; k < 3; k++) { @@ -339,7 +345,7 @@ void Sprite2DEditor::_convert_to_mesh_2d_node() { } void Sprite2DEditor::_convert_to_polygon_2d_node() { - if (computed_outline_lines.empty()) { + if (computed_outline_lines.is_empty()) { err_dialog->set_text(TTR("Invalid geometry, can't create polygon.")); err_dialog->popup_centered(); return; @@ -397,7 +403,7 @@ void Sprite2DEditor::_convert_to_polygon_2d_node() { } void Sprite2DEditor::_create_collision_polygon_2d_node() { - if (computed_outline_lines.empty()) { + if (computed_outline_lines.is_empty()) { err_dialog->set_text(TTR("Invalid geometry, can't create collision polygon.")); err_dialog->popup_centered(); return; @@ -419,7 +425,7 @@ void Sprite2DEditor::_create_collision_polygon_2d_node() { } void Sprite2DEditor::_create_light_occluder_2d_node() { - if (computed_outline_lines.empty()) { + if (computed_outline_lines.is_empty()) { err_dialog->set_text(TTR("Invalid geometry, can't create light occluder.")); err_dialog->popup_centered(); return; @@ -514,7 +520,7 @@ Sprite2DEditor::Sprite2DEditor() { add_child(err_dialog); debug_uv_dialog = memnew(ConfirmationDialog); - debug_uv_dialog->get_ok()->set_text(TTR("Create Mesh2D")); + debug_uv_dialog->get_ok_button()->set_text(TTR("Create Mesh2D")); debug_uv_dialog->set_title("Mesh 2D Preview"); VBoxContainer *vb = memnew(VBoxContainer); debug_uv_dialog->add_child(vb); @@ -582,7 +588,7 @@ void Sprite2DEditorPlugin::make_visible(bool p_visible) { Sprite2DEditorPlugin::Sprite2DEditorPlugin(EditorNode *p_node) { editor = p_node; sprite_editor = memnew(Sprite2DEditor); - editor->get_viewport()->add_child(sprite_editor); + editor->get_main_control()->add_child(sprite_editor); make_visible(false); //sprite_editor->options->hide(); diff --git a/editor/plugins/sprite_2d_editor_plugin.h b/editor/plugins/sprite_2d_editor_plugin.h index c2b942fd82..d4a1ef4312 100644 --- a/editor/plugins/sprite_2d_editor_plugin.h +++ b/editor/plugins/sprite_2d_editor_plugin.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -102,11 +102,11 @@ class Sprite2DEditorPlugin : public EditorPlugin { EditorNode *editor; public: - virtual String get_name() const { return "Sprite2D"; } - bool has_main_screen() const { return false; } - virtual void edit(Object *p_object); - virtual bool handles(Object *p_object) const; - virtual void make_visible(bool p_visible); + virtual String get_name() const override { return "Sprite2D"; } + bool has_main_screen() const override { return false; } + virtual void edit(Object *p_object) override; + virtual bool handles(Object *p_object) const override; + virtual void make_visible(bool p_visible) override; Sprite2DEditorPlugin(EditorNode *p_node); ~Sprite2DEditorPlugin(); diff --git a/editor/plugins/sprite_frames_editor_plugin.cpp b/editor/plugins/sprite_frames_editor_plugin.cpp index 859fec1628..0547f99079 100644 --- a/editor/plugins/sprite_frames_editor_plugin.cpp +++ b/editor/plugins/sprite_frames_editor_plugin.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -30,12 +30,15 @@ #include "sprite_frames_editor_plugin.h" +#include "core/config/project_settings.h" #include "core/io/resource_loader.h" -#include "core/project_settings.h" +#include "core/os/keyboard.h" #include "editor/editor_scale.h" #include "editor/editor_settings.h" #include "scene/3d/sprite_3d.h" #include "scene/gui/center_container.h" +#include "scene/gui/margin_container.h" +#include "scene/gui/panel_container.h" void SpriteFramesEditor::_gui_input(Ref<InputEvent> p_event) { } @@ -48,7 +51,7 @@ void SpriteFramesEditor::_open_sprite_sheet() { file_split_sheet->add_filter("*." + extensions[i]); } - file_split_sheet->popup_centered_ratio(); + file_split_sheet->popup_file_dialog(); } void SpriteFramesEditor::_sheet_preview_draw() { @@ -72,8 +75,8 @@ void SpriteFramesEditor::_sheet_preview_draw() { } if (frames_selected.size() == 0) { - split_sheet_dialog->get_ok()->set_disabled(true); - split_sheet_dialog->get_ok()->set_text(TTR("No Frames Selected")); + split_sheet_dialog->get_ok_button()->set_disabled(true); + split_sheet_dialog->get_ok_button()->set_text(TTR("No Frames Selected")); return; } @@ -95,8 +98,8 @@ void SpriteFramesEditor::_sheet_preview_draw() { split_sheet_preview->draw_rect(Rect2(x + 5, y + 5, width - 10, height - 10), Color(0, 0, 0, 1), false); } - split_sheet_dialog->get_ok()->set_disabled(false); - split_sheet_dialog->get_ok()->set_text(vformat(TTR("Add %d Frame(s)"), frames_selected.size())); + split_sheet_dialog->get_ok_button()->set_disabled(false); + split_sheet_dialog->get_ok_button()->set_text(vformat(TTR("Add %d Frame(s)"), frames_selected.size())); } void SpriteFramesEditor::_sheet_preview_input(const Ref<InputEvent> &p_event) { @@ -140,8 +143,27 @@ void SpriteFramesEditor::_sheet_preview_input(const Ref<InputEvent> &p_event) { } } +void SpriteFramesEditor::_sheet_scroll_input(const Ref<InputEvent> &p_event) { + const Ref<InputEventMouseButton> mb = p_event; + + if (mb.is_valid()) { + // Zoom in/out using Ctrl + mouse wheel. This is done on the ScrollContainer + // to allow performing this action anywhere, even if the cursor isn't + // hovering the texture in the workspace. + if (mb->get_button_index() == BUTTON_WHEEL_UP && mb->is_pressed() && mb->get_control()) { + _sheet_zoom_in(); + // Don't scroll up after zooming in. + accept_event(); + } else if (mb->get_button_index() == BUTTON_WHEEL_DOWN && mb->is_pressed() && mb->get_control()) { + _sheet_zoom_out(); + // Don't scroll down after zooming out. + accept_event(); + } + } +} + void SpriteFramesEditor::_sheet_add_frames() { - Size2i size = split_sheet_preview->get_size(); + Size2i size = split_sheet_preview->get_texture()->get_size(); int h = split_sheet_h->get_value(); int v = split_sheet_v->get_value(); @@ -180,6 +202,28 @@ void SpriteFramesEditor::_sheet_add_frames() { undo_redo->commit_action(); } +void SpriteFramesEditor::_sheet_zoom_in() { + if (sheet_zoom < max_sheet_zoom) { + sheet_zoom *= scale_ratio; + Size2 texture_size = split_sheet_preview->get_texture()->get_size(); + split_sheet_preview->set_custom_minimum_size(texture_size * sheet_zoom); + } +} + +void SpriteFramesEditor::_sheet_zoom_out() { + if (sheet_zoom > min_sheet_zoom) { + sheet_zoom /= scale_ratio; + Size2 texture_size = split_sheet_preview->get_texture()->get_size(); + split_sheet_preview->set_custom_minimum_size(texture_size * sheet_zoom); + } +} + +void SpriteFramesEditor::_sheet_zoom_reset() { + sheet_zoom = 1.f; + Size2 texture_size = split_sheet_preview->get_texture()->get_size(); + split_sheet_preview->set_custom_minimum_size(texture_size * sheet_zoom); +} + void SpriteFramesEditor::_sheet_select_clear_all_frames() { bool should_clear = true; for (int i = 0; i < split_sheet_h->get_value() * split_sheet_v->get_value(); i++) { @@ -207,15 +251,18 @@ void SpriteFramesEditor::_prepare_sprite_sheet(const String &p_file) { EditorNode::get_singleton()->show_warning(TTR("Unable to load images")); ERR_FAIL_COND(!texture.is_valid()); } - if (texture != split_sheet_preview->get_texture()) { - //different texture, reset to 4x4 - split_sheet_h->set_value(4); - split_sheet_v->set_value(4); - } + bool new_texture = texture != split_sheet_preview->get_texture(); frames_selected.clear(); last_frame_selected = -1; split_sheet_preview->set_texture(texture); + if (new_texture) { + //different texture, reset to 4x4 + split_sheet_h->set_value(4); + split_sheet_v->set_value(4); + //reset zoom + _sheet_zoom_reset(); + } split_sheet_dialog->popup_centered_ratio(0.65); } @@ -231,8 +278,14 @@ void SpriteFramesEditor::_notification(int p_what) { move_up->set_icon(get_theme_icon("MoveLeft", "EditorIcons")); move_down->set_icon(get_theme_icon("MoveRight", "EditorIcons")); _delete->set_icon(get_theme_icon("Remove", "EditorIcons")); + zoom_out->set_icon(get_theme_icon("ZoomLess", "EditorIcons")); + zoom_1->set_icon(get_theme_icon("ZoomReset", "EditorIcons")); + zoom_in->set_icon(get_theme_icon("ZoomMore", "EditorIcons")); new_anim->set_icon(get_theme_icon("New", "EditorIcons")); remove_anim->set_icon(get_theme_icon("Remove", "EditorIcons")); + split_sheet_zoom_out->set_icon(get_theme_icon("ZoomLess", "EditorIcons")); + split_sheet_zoom_1->set_icon(get_theme_icon("ZoomReset", "EditorIcons")); + split_sheet_zoom_in->set_icon(get_theme_icon("ZoomMore", "EditorIcons")); [[fallthrough]]; } case NOTIFICATION_THEME_CHANGED: { @@ -258,7 +311,7 @@ void SpriteFramesEditor::_file_load_request(const Vector<String> &p_path, int p_ dialog->set_title(TTR("Error!")); //dialog->get_cancel()->set_text("Close"); - dialog->get_ok()->set_text(TTR("Close")); + dialog->get_ok_button()->set_text(TTR("Close")); dialog->popup_centered(); return; ///beh should show an error i guess } @@ -266,7 +319,7 @@ void SpriteFramesEditor::_file_load_request(const Vector<String> &p_path, int p_ resources.push_back(resource); } - if (resources.empty()) { + if (resources.is_empty()) { return; } @@ -298,8 +351,7 @@ void SpriteFramesEditor::_load_pressed() { } file->set_file_mode(EditorFileDialog::FILE_MODE_OPEN_FILES); - - file->popup_centered_ratio(); + file->popup_file_dialog(); } void SpriteFramesEditor::_paste_pressed() { @@ -310,7 +362,7 @@ void SpriteFramesEditor::_paste_pressed() { dialog->set_text(TTR("Resource clipboard is empty or not a texture!")); dialog->set_title(TTR("Error!")); //dialog->get_cancel()->set_text("Close"); - dialog->get_ok()->set_text(TTR("Close")); + dialog->get_ok_button()->set_text(TTR("Close")); dialog->popup_centered(); return; ///beh should show an error i guess } @@ -459,7 +511,7 @@ void SpriteFramesEditor::_animation_select() { } if (frames->has_animation(edited_anim)) { - double value = anim_speed->get_line_edit()->get_text().to_double(); + double value = anim_speed->get_line_edit()->get_text().to_float(); if (!Math::is_equal_approx(value, frames->get_animation_speed(edited_anim))) { _animation_fps_changed(value); } @@ -637,6 +689,54 @@ void SpriteFramesEditor::_animation_fps_changed(double p_value) { undo_redo->commit_action(); } +void SpriteFramesEditor::_tree_input(const Ref<InputEvent> &p_event) { + const Ref<InputEventMouseButton> mb = p_event; + + if (mb.is_valid()) { + if (mb->get_button_index() == BUTTON_WHEEL_UP && mb->is_pressed() && mb->get_control()) { + _zoom_in(); + // Don't scroll up after zooming in. + accept_event(); + } else if (mb->get_button_index() == BUTTON_WHEEL_DOWN && mb->is_pressed() && mb->get_control()) { + _zoom_out(); + // Don't scroll down after zooming out. + accept_event(); + } + } +} + +void SpriteFramesEditor::_zoom_in() { + // Do not zoom in or out with no visible frames + if (frames->get_frame_count(edited_anim) <= 0) { + return; + } + if (thumbnail_zoom < max_thumbnail_zoom) { + thumbnail_zoom *= scale_ratio; + int thumbnail_size = (int)(thumbnail_default_size * thumbnail_zoom); + tree->set_fixed_column_width(thumbnail_size * 3 / 2); + tree->set_fixed_icon_size(Size2(thumbnail_size, thumbnail_size)); + } +} + +void SpriteFramesEditor::_zoom_out() { + // Do not zoom in or out with no visible frames + if (frames->get_frame_count(edited_anim) <= 0) { + return; + } + if (thumbnail_zoom > min_thumbnail_zoom) { + thumbnail_zoom /= scale_ratio; + int thumbnail_size = (int)(thumbnail_default_size * thumbnail_zoom); + tree->set_fixed_column_width(thumbnail_size * 3 / 2); + tree->set_fixed_icon_size(Size2(thumbnail_size, thumbnail_size)); + } +} + +void SpriteFramesEditor::_zoom_reset() { + thumbnail_zoom = 1.0f; + tree->set_fixed_column_width(thumbnail_default_size * 3 / 2); + tree->set_fixed_icon_size(Size2(thumbnail_default_size, thumbnail_default_size)); +} + void SpriteFramesEditor::_update_library(bool p_skip_selector) { updating = true; @@ -728,6 +828,9 @@ void SpriteFramesEditor::edit(SpriteFrames *p_frames) { } _update_library(); + // Clear zoom and split sheet texture + split_sheet_preview->set_texture(Ref<Texture2D>()); + _zoom_reset(); } else { hide(); } @@ -850,7 +953,11 @@ void SpriteFramesEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da if (String(d["type"]) == "files") { Vector<String> files = d["files"]; - _file_load_request(files, at_pos); + if (Input::get_singleton()->is_key_pressed(KEY_CONTROL)) { + _prepare_sprite_sheet(files[0]); + } else { + _file_load_request(files, at_pos); + } } } @@ -873,12 +980,14 @@ SpriteFramesEditor::SpriteFramesEditor() { HBoxContainer *hbc_animlist = memnew(HBoxContainer); sub_vb->add_child(hbc_animlist); - new_anim = memnew(ToolButton); + new_anim = memnew(Button); + new_anim->set_flat(true); new_anim->set_tooltip(TTR("New Animation")); hbc_animlist->add_child(new_anim); new_anim->connect("pressed", callable_mp(this, &SpriteFramesEditor::_animation_add)); - remove_anim = memnew(ToolButton); + remove_anim = memnew(Button); + remove_anim->set_flat(true); remove_anim->set_tooltip(TTR("Remove Animation")); hbc_animlist->add_child(remove_anim); remove_anim->connect("pressed", callable_mp(this, &SpriteFramesEditor::_animation_remove)); @@ -891,11 +1000,16 @@ SpriteFramesEditor::SpriteFramesEditor() { animations->connect("item_edited", callable_mp(this, &SpriteFramesEditor::_animation_name_edited)); animations->set_allow_reselect(true); + HBoxContainer *hbc_anim_speed = memnew(HBoxContainer); + hbc_anim_speed->add_child(memnew(Label(TTR("Speed:")))); + vbc_animlist->add_child(hbc_anim_speed); anim_speed = memnew(SpinBox); - vbc_animlist->add_margin_child(TTR("Speed (FPS):"), anim_speed); + anim_speed->set_suffix(TTR("FPS")); anim_speed->set_min(0); anim_speed->set_max(100); anim_speed->set_step(0.01); + anim_speed->set_h_size_flags(SIZE_EXPAND_FILL); + hbc_anim_speed->add_child(anim_speed); anim_speed->connect("value_changed", callable_mp(this, &SpriteFramesEditor::_animation_fps_changed)); anim_loop = memnew(CheckButton); @@ -913,48 +1027,75 @@ SpriteFramesEditor::SpriteFramesEditor() { HBoxContainer *hbc = memnew(HBoxContainer); sub_vb->add_child(hbc); - load = memnew(ToolButton); + load = memnew(Button); + load->set_flat(true); load->set_tooltip(TTR("Add a Texture from File")); hbc->add_child(load); - load_sheet = memnew(ToolButton); + load_sheet = memnew(Button); + load_sheet->set_flat(true); load_sheet->set_tooltip(TTR("Add Frames from a Sprite Sheet")); hbc->add_child(load_sheet); hbc->add_child(memnew(VSeparator)); - copy = memnew(ToolButton); + copy = memnew(Button); + copy->set_flat(true); copy->set_tooltip(TTR("Copy")); hbc->add_child(copy); - paste = memnew(ToolButton); + paste = memnew(Button); + paste->set_flat(true); paste->set_tooltip(TTR("Paste")); hbc->add_child(paste); hbc->add_child(memnew(VSeparator)); - empty = memnew(ToolButton); + empty = memnew(Button); + empty->set_flat(true); empty->set_tooltip(TTR("Insert Empty (Before)")); hbc->add_child(empty); - empty2 = memnew(ToolButton); + empty2 = memnew(Button); + empty2->set_flat(true); empty2->set_tooltip(TTR("Insert Empty (After)")); hbc->add_child(empty2); hbc->add_child(memnew(VSeparator)); - move_up = memnew(ToolButton); + move_up = memnew(Button); + move_up->set_flat(true); move_up->set_tooltip(TTR("Move (Before)")); hbc->add_child(move_up); - move_down = memnew(ToolButton); + move_down = memnew(Button); + move_down->set_flat(true); move_down->set_tooltip(TTR("Move (After)")); hbc->add_child(move_down); - _delete = memnew(ToolButton); + _delete = memnew(Button); + _delete->set_flat(true); _delete->set_tooltip(TTR("Delete")); hbc->add_child(_delete); + hbc->add_spacer(); + + zoom_out = memnew(Button); + zoom_out->connect("pressed", callable_mp(this, &SpriteFramesEditor::_zoom_out)); + zoom_out->set_flat(true); + zoom_out->set_tooltip(TTR("Zoom Out")); + hbc->add_child(zoom_out); + zoom_1 = memnew(Button); + zoom_1->connect("pressed", callable_mp(this, &SpriteFramesEditor::_zoom_reset)); + zoom_1->set_flat(true); + zoom_1->set_tooltip(TTR("Zoom Reset")); + hbc->add_child(zoom_1); + zoom_in = memnew(Button); + zoom_in->connect("pressed", callable_mp(this, &SpriteFramesEditor::_zoom_in)); + zoom_in->set_flat(true); + zoom_in->set_tooltip(TTR("Zoom In")); + hbc->add_child(zoom_in); + file = memnew(EditorFileDialog); add_child(file); @@ -962,13 +1103,11 @@ SpriteFramesEditor::SpriteFramesEditor() { tree->set_v_size_flags(SIZE_EXPAND_FILL); tree->set_icon_mode(ItemList::ICON_MODE_TOP); - int thumbnail_size = 96; tree->set_max_columns(0); tree->set_icon_mode(ItemList::ICON_MODE_TOP); - tree->set_fixed_column_width(thumbnail_size * 3 / 2); tree->set_max_text_lines(2); - tree->set_fixed_icon_size(Size2(thumbnail_size, thumbnail_size)); tree->set_drag_forwarding(this); + tree->connect("gui_input", callable_mp(this, &SpriteFramesEditor::_tree_input)); sub_vb->add_child(tree); @@ -1032,8 +1171,13 @@ SpriteFramesEditor::SpriteFramesEditor() { split_sheet_vb->add_child(split_sheet_hb); + PanelContainer *split_sheet_panel = memnew(PanelContainer); + split_sheet_panel->set_h_size_flags(SIZE_EXPAND_FILL); + split_sheet_panel->set_v_size_flags(SIZE_EXPAND_FILL); + split_sheet_vb->add_child(split_sheet_panel); + split_sheet_preview = memnew(TextureRect); - split_sheet_preview->set_expand(false); + split_sheet_preview->set_expand(true); split_sheet_preview->set_mouse_filter(MOUSE_FILTER_PASS); split_sheet_preview->connect("draw", callable_mp(this, &SpriteFramesEditor::_sheet_preview_draw)); split_sheet_preview->connect("gui_input", callable_mp(this, &SpriteFramesEditor::_sheet_preview_input)); @@ -1041,20 +1185,58 @@ SpriteFramesEditor::SpriteFramesEditor() { splite_sheet_scroll = memnew(ScrollContainer); splite_sheet_scroll->set_enable_h_scroll(true); splite_sheet_scroll->set_enable_v_scroll(true); - splite_sheet_scroll->set_v_size_flags(SIZE_EXPAND_FILL); + splite_sheet_scroll->connect("gui_input", callable_mp(this, &SpriteFramesEditor::_sheet_scroll_input)); + split_sheet_panel->add_child(splite_sheet_scroll); CenterContainer *cc = memnew(CenterContainer); cc->add_child(split_sheet_preview); cc->set_h_size_flags(SIZE_EXPAND_FILL); cc->set_v_size_flags(SIZE_EXPAND_FILL); splite_sheet_scroll->add_child(cc); - split_sheet_vb->add_child(splite_sheet_scroll); + MarginContainer *split_sheet_zoom_margin = memnew(MarginContainer); + split_sheet_panel->add_child(split_sheet_zoom_margin); + split_sheet_zoom_margin->set_h_size_flags(0); + split_sheet_zoom_margin->set_v_size_flags(0); + split_sheet_zoom_margin->add_theme_constant_override("margin_top", 5); + split_sheet_zoom_margin->add_theme_constant_override("margin_left", 5); + HBoxContainer *split_sheet_zoom_hb = memnew(HBoxContainer); + split_sheet_zoom_margin->add_child(split_sheet_zoom_hb); + + split_sheet_zoom_out = memnew(Button); + split_sheet_zoom_out->set_flat(true); + split_sheet_zoom_out->set_focus_mode(FOCUS_NONE); + split_sheet_zoom_out->set_tooltip(TTR("Zoom Out")); + split_sheet_zoom_out->connect("pressed", callable_mp(this, &SpriteFramesEditor::_sheet_zoom_out)); + split_sheet_zoom_hb->add_child(split_sheet_zoom_out); + split_sheet_zoom_1 = memnew(Button); + split_sheet_zoom_1->set_flat(true); + split_sheet_zoom_1->set_focus_mode(FOCUS_NONE); + split_sheet_zoom_1->set_tooltip(TTR("Zoom Reset")); + split_sheet_zoom_1->connect("pressed", callable_mp(this, &SpriteFramesEditor::_sheet_zoom_reset)); + split_sheet_zoom_hb->add_child(split_sheet_zoom_1); + split_sheet_zoom_in = memnew(Button); + split_sheet_zoom_in->set_flat(true); + split_sheet_zoom_in->set_focus_mode(FOCUS_NONE); + split_sheet_zoom_in->set_tooltip(TTR("Zoom In")); + split_sheet_zoom_in->connect("pressed", callable_mp(this, &SpriteFramesEditor::_sheet_zoom_in)); + split_sheet_zoom_hb->add_child(split_sheet_zoom_in); file_split_sheet = memnew(EditorFileDialog); file_split_sheet->set_title(TTR("Create Frames from Sprite Sheet")); file_split_sheet->set_file_mode(EditorFileDialog::FILE_MODE_OPEN_FILE); add_child(file_split_sheet); file_split_sheet->connect("file_selected", callable_mp(this, &SpriteFramesEditor::_prepare_sprite_sheet)); + + // Config scale. + scale_ratio = 1.2f; + thumbnail_default_size = 96; + thumbnail_zoom = 1.0f; + max_thumbnail_zoom = 8.0f; + min_thumbnail_zoom = 0.1f; + sheet_zoom = 1.0f; + max_sheet_zoom = 16.0f; + min_sheet_zoom = 0.01f; + _zoom_reset(); } void SpriteFramesEditorPlugin::edit(Object *p_object) { diff --git a/editor/plugins/sprite_frames_editor_plugin.h b/editor/plugins/sprite_frames_editor_plugin.h index 45646eb9e4..bbc26ca726 100644 --- a/editor/plugins/sprite_frames_editor_plugin.h +++ b/editor/plugins/sprite_frames_editor_plugin.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -36,6 +36,7 @@ #include "scene/2d/animated_sprite_2d.h" #include "scene/gui/dialogs.h" #include "scene/gui/file_dialog.h" +#include "scene/gui/scroll_container.h" #include "scene/gui/split_container.h" #include "scene/gui/texture_rect.h" #include "scene/gui/tree.h" @@ -43,22 +44,25 @@ class SpriteFramesEditor : public HSplitContainer { GDCLASS(SpriteFramesEditor, HSplitContainer); - ToolButton *load; - ToolButton *load_sheet; - ToolButton *_delete; - ToolButton *copy; - ToolButton *paste; - ToolButton *empty; - ToolButton *empty2; - ToolButton *move_up; - ToolButton *move_down; + Button *load; + Button *load_sheet; + Button *_delete; + Button *copy; + Button *paste; + Button *empty; + Button *empty2; + Button *move_up; + Button *move_down; + Button *zoom_out; + Button *zoom_1; + Button *zoom_in; ItemList *tree; bool loading_scene; int sel; HSplitContainer *split; - ToolButton *new_anim; - ToolButton *remove_anim; + Button *new_anim; + Button *remove_anim; Tree *animations; SpinBox *anim_speed; @@ -79,10 +83,22 @@ class SpriteFramesEditor : public HSplitContainer { TextureRect *split_sheet_preview; SpinBox *split_sheet_h; SpinBox *split_sheet_v; + Button *split_sheet_zoom_out; + Button *split_sheet_zoom_1; + Button *split_sheet_zoom_in; EditorFileDialog *file_split_sheet; Set<int> frames_selected; int last_frame_selected; + float scale_ratio; + int thumbnail_default_size; + float thumbnail_zoom; + float max_thumbnail_zoom; + float min_thumbnail_zoom; + float sheet_zoom; + float max_sheet_zoom; + float min_sheet_zoom; + void _load_pressed(); void _load_scene_pressed(); void _file_load_request(const Vector<String> &p_path, int p_at_pos = -1); @@ -103,6 +119,11 @@ class SpriteFramesEditor : public HSplitContainer { void _animation_loop_changed(); void _animation_fps_changed(double p_value); + void _tree_input(const Ref<InputEvent> &p_event); + void _zoom_in(); + void _zoom_out(); + void _zoom_reset(); + bool updating; UndoRedo *undo_redo; @@ -117,7 +138,11 @@ class SpriteFramesEditor : public HSplitContainer { void _sheet_preview_draw(); void _sheet_spin_changed(double); void _sheet_preview_input(const Ref<InputEvent> &p_event); + void _sheet_scroll_input(const Ref<InputEvent> &p_event); void _sheet_add_frames(); + void _sheet_zoom_in(); + void _sheet_zoom_out(); + void _sheet_zoom_reset(); void _sheet_select_clear_all_frames(); protected: @@ -140,11 +165,11 @@ class SpriteFramesEditorPlugin : public EditorPlugin { Button *button; public: - virtual String get_name() const { return "SpriteFrames"; } - bool has_main_screen() const { return false; } - virtual void edit(Object *p_object); - virtual bool handles(Object *p_object) const; - virtual void make_visible(bool p_visible); + virtual String get_name() const override { return "SpriteFrames"; } + bool has_main_screen() const override { return false; } + virtual void edit(Object *p_object) override; + virtual bool handles(Object *p_object) const override; + virtual void make_visible(bool p_visible) override; SpriteFramesEditorPlugin(EditorNode *p_node); ~SpriteFramesEditorPlugin(); diff --git a/editor/plugins/style_box_editor_plugin.cpp b/editor/plugins/style_box_editor_plugin.cpp index 3641052a4e..64df982d5d 100644 --- a/editor/plugins/style_box_editor_plugin.cpp +++ b/editor/plugins/style_box_editor_plugin.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ diff --git a/editor/plugins/style_box_editor_plugin.h b/editor/plugins/style_box_editor_plugin.h index d9958d42e6..d4a235cd10 100644 --- a/editor/plugins/style_box_editor_plugin.h +++ b/editor/plugins/style_box_editor_plugin.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -59,17 +59,17 @@ class EditorInspectorPluginStyleBox : public EditorInspectorPlugin { GDCLASS(EditorInspectorPluginStyleBox, EditorInspectorPlugin); public: - virtual bool can_handle(Object *p_object); - virtual void parse_begin(Object *p_object); - virtual bool parse_property(Object *p_object, Variant::Type p_type, const String &p_path, PropertyHint p_hint, const String &p_hint_text, int p_usage, bool p_wide = false); - virtual void parse_end(); + virtual bool can_handle(Object *p_object) override; + virtual void parse_begin(Object *p_object) override; + virtual bool parse_property(Object *p_object, Variant::Type p_type, const String &p_path, PropertyHint p_hint, const String &p_hint_text, int p_usage, bool p_wide = false) override; + virtual void parse_end() override; }; class StyleBoxEditorPlugin : public EditorPlugin { GDCLASS(StyleBoxEditorPlugin, EditorPlugin); public: - virtual String get_name() const { return "StyleBox"; } + virtual String get_name() const override { return "StyleBox"; } StyleBoxEditorPlugin(EditorNode *p_node); }; diff --git a/editor/plugins/text_editor.cpp b/editor/plugins/text_editor.cpp index 3ceb9bfd82..b88f1c91e6 100644 --- a/editor/plugins/text_editor.cpp +++ b/editor/plugins/text_editor.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -33,45 +33,34 @@ #include "core/os/keyboard.h" #include "editor/editor_node.h" -void TextEditor::add_syntax_highlighter(SyntaxHighlighter *p_highlighter) { - highlighters[p_highlighter->get_name()] = p_highlighter; - highlighter_menu->add_radio_check_item(p_highlighter->get_name()); +void TextEditor::add_syntax_highlighter(Ref<EditorSyntaxHighlighter> p_highlighter) { + ERR_FAIL_COND(p_highlighter.is_null()); + + highlighters[p_highlighter->_get_name()] = p_highlighter; + highlighter_menu->add_radio_check_item(p_highlighter->_get_name()); } -void TextEditor::set_syntax_highlighter(SyntaxHighlighter *p_highlighter) { - TextEdit *te = code_editor->get_text_edit(); - te->_set_syntax_highlighting(p_highlighter); - if (p_highlighter != nullptr) { - highlighter_menu->set_item_checked(highlighter_menu->get_item_idx_from_text(p_highlighter->get_name()), true); - } else { - highlighter_menu->set_item_checked(highlighter_menu->get_item_idx_from_text("Standard"), true); - } +void TextEditor::set_syntax_highlighter(Ref<EditorSyntaxHighlighter> p_highlighter) { + ERR_FAIL_COND(p_highlighter.is_null()); - // little work around. GDScript highlighter goes through text_edit for colours, - // so to remove all colours we need to set and unset them here. - if (p_highlighter == nullptr) { // standard - TextEdit *text_edit = code_editor->get_text_edit(); - text_edit->add_theme_color_override("number_color", colors_cache.font_color); - text_edit->add_theme_color_override("function_color", colors_cache.font_color); - text_edit->add_theme_color_override("number_color", colors_cache.font_color); - text_edit->add_theme_color_override("member_variable_color", colors_cache.font_color); - } else { - _load_theme_settings(); + Map<String, Ref<EditorSyntaxHighlighter>>::Element *el = highlighters.front(); + while (el != nullptr) { + int highlighter_index = highlighter_menu->get_item_idx_from_text(el->key()); + highlighter_menu->set_item_checked(highlighter_index, el->value() == p_highlighter); + el = el->next(); } + + CodeEdit *te = code_editor->get_text_editor(); + te->set_syntax_highlighter(p_highlighter); } void TextEditor::_change_syntax_highlighter(int p_idx) { - Map<String, SyntaxHighlighter *>::Element *el = highlighters.front(); - while (el != nullptr) { - highlighter_menu->set_item_checked(highlighter_menu->get_item_idx_from_text(el->key()), false); - el = el->next(); - } set_syntax_highlighter(highlighters[highlighter_menu->get_item_text(p_idx)]); } void TextEditor::_load_theme_settings() { - TextEdit *text_edit = code_editor->get_text_edit(); - text_edit->clear_colors(); + CodeEdit *text_edit = code_editor->get_text_editor(); + text_edit->get_syntax_highlighter()->update_cache(); Color background_color = EDITOR_GET("text_editor/highlighting/background_color"); Color completion_background_color = EDITOR_GET("text_editor/highlighting/completion_background_color"); @@ -89,9 +78,6 @@ void TextEditor::_load_theme_settings() { Color current_line_color = EDITOR_GET("text_editor/highlighting/current_line_color"); Color line_length_guideline_color = EDITOR_GET("text_editor/highlighting/line_length_guideline_color"); Color word_highlighted_color = EDITOR_GET("text_editor/highlighting/word_highlighted_color"); - Color number_color = EDITOR_GET("text_editor/highlighting/number_color"); - Color function_color = EDITOR_GET("text_editor/highlighting/function_color"); - Color member_variable_color = EDITOR_GET("text_editor/highlighting/member_variable_color"); Color mark_color = EDITOR_GET("text_editor/highlighting/mark_color"); Color bookmark_color = EDITOR_GET("text_editor/highlighting/bookmark_color"); Color breakpoint_color = EDITOR_GET("text_editor/highlighting/breakpoint_color"); @@ -99,12 +85,6 @@ void TextEditor::_load_theme_settings() { Color code_folding_color = EDITOR_GET("text_editor/highlighting/code_folding_color"); Color search_result_color = EDITOR_GET("text_editor/highlighting/search_result_color"); Color search_result_border_color = EDITOR_GET("text_editor/highlighting/search_result_border_color"); - Color symbol_color = EDITOR_GET("text_editor/highlighting/symbol_color"); - Color keyword_color = EDITOR_GET("text_editor/highlighting/keyword_color"); - Color basetype_color = EDITOR_GET("text_editor/highlighting/base_type_color"); - Color type_color = EDITOR_GET("text_editor/highlighting/engine_type_color"); - Color comment_color = EDITOR_GET("text_editor/highlighting/comment_color"); - Color string_color = EDITOR_GET("text_editor/highlighting/string_color"); text_edit->add_theme_color_override("background_color", background_color); text_edit->add_theme_color_override("completion_background_color", completion_background_color); @@ -116,15 +96,12 @@ void TextEditor::_load_theme_settings() { text_edit->add_theme_color_override("line_number_color", line_number_color); text_edit->add_theme_color_override("caret_color", caret_color); text_edit->add_theme_color_override("caret_background_color", caret_background_color); - text_edit->add_theme_color_override("font_color_selected", text_selected_color); + text_edit->add_theme_color_override("font_selected_color", text_selected_color); text_edit->add_theme_color_override("selection_color", selection_color); text_edit->add_theme_color_override("brace_mismatch_color", brace_mismatch_color); text_edit->add_theme_color_override("current_line_color", current_line_color); text_edit->add_theme_color_override("line_length_guideline_color", line_length_guideline_color); text_edit->add_theme_color_override("word_highlighted_color", word_highlighted_color); - text_edit->add_theme_color_override("number_color", number_color); - text_edit->add_theme_color_override("function_color", function_color); - text_edit->add_theme_color_override("member_variable_color", member_variable_color); text_edit->add_theme_color_override("breakpoint_color", breakpoint_color); text_edit->add_theme_color_override("executing_line_color", executing_line_color); text_edit->add_theme_color_override("mark_color", mark_color); @@ -132,17 +109,8 @@ void TextEditor::_load_theme_settings() { text_edit->add_theme_color_override("code_folding_color", code_folding_color); text_edit->add_theme_color_override("search_result_color", search_result_color); text_edit->add_theme_color_override("search_result_border_color", search_result_border_color); - text_edit->add_theme_color_override("symbol_color", symbol_color); text_edit->add_theme_constant_override("line_spacing", EDITOR_DEF("text_editor/theme/line_spacing", 6)); - - colors_cache.font_color = text_color; - colors_cache.symbol_color = symbol_color; - colors_cache.keyword_color = keyword_color; - colors_cache.basetype_color = basetype_color; - colors_cache.type_color = type_color; - colors_cache.comment_color = comment_color; - colors_cache.string_color = string_color; } String TextEditor::get_name() { @@ -151,6 +119,9 @@ String TextEditor::get_name() { if (text_file->get_path().find("local://") == -1 && text_file->get_path().find("::") == -1) { name = text_file->get_path().get_file(); if (is_unsaved()) { + if (text_file->get_path().is_empty()) { + name = TTR("[unsaved]"); + } name += "(*)"; } } else if (text_file->get_name() != "") { @@ -163,7 +134,7 @@ String TextEditor::get_name() { } Ref<Texture2D> TextEditor::get_theme_icon() { - return EditorNode::get_singleton()->get_object_icon(text_file.operator->(), ""); + return EditorNode::get_singleton()->get_object_icon(text_file.ptr(), ""); } RES TextEditor::get_edited_resource() const { @@ -171,31 +142,43 @@ RES TextEditor::get_edited_resource() const { } void TextEditor::set_edited_resource(const RES &p_res) { - ERR_FAIL_COND(!text_file.is_null()); + ERR_FAIL_COND(text_file.is_valid()); + ERR_FAIL_COND(p_res.is_null()); text_file = p_res; - code_editor->get_text_edit()->set_text(text_file->get_text()); - code_editor->get_text_edit()->clear_undo_history(); - code_editor->get_text_edit()->tag_saved_version(); + code_editor->get_text_editor()->set_text(text_file->get_text()); + code_editor->get_text_editor()->clear_undo_history(); + code_editor->get_text_editor()->tag_saved_version(); emit_signal("name_changed"); code_editor->update_line_and_column(); } +void TextEditor::enable_editor() { + if (editor_enabled) { + return; + } + + editor_enabled = true; + + _load_theme_settings(); +} + void TextEditor::add_callback(const String &p_function, PackedStringArray p_args) { } void TextEditor::set_debugger_active(bool p_active) { } -void TextEditor::get_breakpoints(List<int> *p_breakpoints) { +Array TextEditor::get_breakpoints() { + return Array(); } void TextEditor::reload_text() { ERR_FAIL_COND(text_file.is_null()); - TextEdit *te = code_editor->get_text_edit(); + CodeEdit *te = code_editor->get_text_editor(); int column = te->cursor_get_column(); int row = te->cursor_get_line(); int h = te->get_h_scroll(); @@ -225,7 +208,7 @@ void TextEditor::_update_bookmark_list() { bookmarks_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/goto_next_bookmark"), BOOKMARK_GOTO_NEXT); bookmarks_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/goto_previous_bookmark"), BOOKMARK_GOTO_PREV); - Array bookmark_list = code_editor->get_text_edit()->get_bookmarks_array(); + Array bookmark_list = code_editor->get_text_editor()->get_bookmarked_lines(); if (bookmark_list.size() == 0) { return; } @@ -233,7 +216,7 @@ void TextEditor::_update_bookmark_list() { bookmarks_menu->add_separator(); for (int i = 0; i < bookmark_list.size(); i++) { - String line = code_editor->get_text_edit()->get_line(bookmark_list[i]).strip_edges(); + String line = code_editor->get_text_editor()->get_line(bookmark_list[i]).strip_edges(); // Limit the size of the line if too big. if (line.length() > 50) { line = line.substr(0, 50); @@ -253,11 +236,14 @@ void TextEditor::_bookmark_item_pressed(int p_idx) { } void TextEditor::apply_code() { - text_file->set_text(code_editor->get_text_edit()->get_text()); + text_file->set_text(code_editor->get_text_editor()->get_text()); } bool TextEditor::is_unsaved() { - return code_editor->get_text_edit()->get_version() != code_editor->get_text_edit()->get_saved_version(); + const bool unsaved = + code_editor->get_text_editor()->get_version() != code_editor->get_text_editor()->get_saved_version() || + text_file->get_path().is_empty(); // In memory. + return unsaved; } Variant TextEditor::get_edit_state() { @@ -274,6 +260,8 @@ void TextEditor::set_edit_state(const Variant &p_state) { _change_syntax_highlighter(idx); } } + + ensure_focus(); } void TextEditor::trim_trailing_whitespace() { @@ -293,7 +281,7 @@ void TextEditor::convert_indent_to_tabs() { } void TextEditor::tag_saved_version() { - code_editor->get_text_edit()->tag_saved_version(); + code_editor->get_text_editor()->tag_saved_version(); } void TextEditor::goto_line(int p_line, bool p_with_error) { @@ -313,7 +301,7 @@ void TextEditor::clear_executing_line() { } void TextEditor::ensure_focus() { - code_editor->get_text_edit()->grab_focus(); + code_editor->get_text_editor()->grab_focus(); } Vector<String> TextEditor::get_functions() { @@ -329,7 +317,7 @@ void TextEditor::update_settings() { } void TextEditor::set_tooltip_request_func(String p_method, Object *p_obj) { - code_editor->get_text_edit()->set_tooltip_request_func(p_obj, p_method, this); + code_editor->get_text_editor()->set_tooltip_request_func(p_obj, p_method, this); } Control *TextEditor::get_edit_menu() { @@ -340,16 +328,8 @@ void TextEditor::clear_edit_menu() { memdelete(edit_hb); } -void TextEditor::_notification(int p_what) { - switch (p_what) { - case NOTIFICATION_READY: - _load_theme_settings(); - break; - } -} - void TextEditor::_edit_option(int p_op) { - TextEdit *tx = code_editor->get_text_edit(); + CodeEdit *tx = code_editor->get_text_editor(); switch (p_op) { case EDIT_UNDO: { @@ -383,10 +363,10 @@ void TextEditor::_edit_option(int p_op) { code_editor->move_lines_down(); } break; case EDIT_INDENT_LEFT: { - tx->indent_left(); + tx->indent_selected_lines_left(); } break; case EDIT_INDENT_RIGHT: { - tx->indent_right(); + tx->indent_selected_lines_right(); } break; case EDIT_DELETE_LINE: { code_editor->delete_lines(); @@ -437,14 +417,14 @@ void TextEditor::_edit_option(int p_op) { code_editor->get_find_replace_bar()->popup_replace(); } break; case SEARCH_IN_FILES: { - String selected_text = code_editor->get_text_edit()->get_selection_text(); + String selected_text = code_editor->get_text_editor()->get_selection_text(); // Yep, because it doesn't make sense to instance this dialog for every single script open... // So this will be delegated to the ScriptEditor. emit_signal("search_in_files_requested", selected_text); } break; case REPLACE_IN_FILES: { - String selected_text = code_editor->get_text_edit()->get_selection_text(); + String selected_text = code_editor->get_text_editor()->get_selection_text(); emit_signal("replace_in_files_requested", selected_text); } break; @@ -471,6 +451,7 @@ void TextEditor::_convert_case(CodeTextEditor::CaseStyle p_case) { } void TextEditor::_bind_methods() { + ClassDB::bind_method(D_METHOD("add_syntax_highlighter", "highlighter"), &TextEditor::add_syntax_highlighter); } static ScriptEditorBase *create_editor(const RES &p_resource) { @@ -490,7 +471,7 @@ void TextEditor::_text_edit_gui_input(const Ref<InputEvent> &ev) { if (mb.is_valid()) { if (mb->get_button_index() == BUTTON_RIGHT) { int col, row; - TextEdit *tx = code_editor->get_text_edit(); + CodeEdit *tx = code_editor->get_text_editor(); tx->_get_mouse_pos(mb->get_global_position() - tx->get_global_position(), row, col); tx->set_right_click_moves_caret(EditorSettings::get_singleton()->get("text_editor/cursor/right_click_moves_caret")); @@ -523,7 +504,7 @@ void TextEditor::_text_edit_gui_input(const Ref<InputEvent> &ev) { Ref<InputEventKey> k = ev; if (k.is_valid() && k->is_pressed() && k->get_keycode() == KEY_MENU) { - TextEdit *tx = code_editor->get_text_edit(); + CodeEdit *tx = code_editor->get_text_editor(); int line = tx->cursor_get_line(); _make_context_menu(tx->is_selection_active(), tx->can_fold(line), tx->is_folded(line), (get_global_transform().inverse() * tx->get_global_transform()).xform(tx->_get_cursor_pixel_pos())); context_menu->grab_focus(); @@ -533,15 +514,15 @@ void TextEditor::_text_edit_gui_input(const Ref<InputEvent> &ev) { void TextEditor::_make_context_menu(bool p_selection, bool p_can_fold, bool p_is_folded, Vector2 p_position) { context_menu->clear(); if (p_selection) { - context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/cut"), EDIT_CUT); - context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/copy"), EDIT_COPY); + context_menu->add_shortcut(ED_GET_SHORTCUT("ui_cut"), EDIT_CUT); + context_menu->add_shortcut(ED_GET_SHORTCUT("ui_copy"), EDIT_COPY); } - context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/paste"), EDIT_PASTE); + context_menu->add_shortcut(ED_GET_SHORTCUT("ui_paste"), EDIT_PASTE); context_menu->add_separator(); - context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/select_all"), EDIT_SELECT_ALL); - context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/undo"), EDIT_UNDO); - context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/redo"), EDIT_REDO); + context_menu->add_shortcut(ED_GET_SHORTCUT("ui_text_select_all"), EDIT_SELECT_ALL); + context_menu->add_shortcut(ED_GET_SHORTCUT("ui_undo"), EDIT_UNDO); + context_menu->add_shortcut(ED_GET_SHORTCUT("ui_redo"), EDIT_REDO); context_menu->add_separator(); context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/indent_left"), EDIT_INDENT_LEFT); context_menu->add_shortcut(ED_GET_SHORTCUT("script_text_editor/indent_right"), EDIT_INDENT_RIGHT); @@ -567,13 +548,13 @@ TextEditor::TextEditor() { code_editor->add_theme_constant_override("separation", 0); code_editor->connect("load_theme_settings", callable_mp(this, &TextEditor::_load_theme_settings)); code_editor->connect("validate_script", callable_mp(this, &TextEditor::_validate_script)); - code_editor->set_anchors_and_margins_preset(Control::PRESET_WIDE); + code_editor->set_anchors_and_offsets_preset(Control::PRESET_WIDE); code_editor->set_v_size_flags(Control::SIZE_EXPAND_FILL); update_settings(); - code_editor->get_text_edit()->set_context_menu_enabled(false); - code_editor->get_text_edit()->connect("gui_input", callable_mp(this, &TextEditor::_text_edit_gui_input)); + code_editor->get_text_editor()->set_context_menu_enabled(false); + code_editor->get_text_editor()->connect("gui_input", callable_mp(this, &TextEditor::_text_edit_gui_input)); context_menu = memnew(PopupMenu); add_child(context_menu); @@ -582,6 +563,7 @@ TextEditor::TextEditor() { edit_hb = memnew(HBoxContainer); search_menu = memnew(MenuButton); + search_menu->set_shortcut_context(this); edit_hb->add_child(search_menu); search_menu->set_text(TTR("Search")); search_menu->set_switch_on_hover(true); @@ -596,19 +578,20 @@ TextEditor::TextEditor() { search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/replace_in_files"), REPLACE_IN_FILES); edit_menu = memnew(MenuButton); + edit_menu->set_shortcut_context(this); edit_hb->add_child(edit_menu); edit_menu->set_text(TTR("Edit")); edit_menu->set_switch_on_hover(true); edit_menu->get_popup()->connect("id_pressed", callable_mp(this, &TextEditor::_edit_option)); - edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/undo"), EDIT_UNDO); - edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/redo"), EDIT_REDO); + edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("ui_undo"), EDIT_UNDO); + edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("un_redo"), EDIT_REDO); edit_menu->get_popup()->add_separator(); - edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/cut"), EDIT_CUT); - edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/copy"), EDIT_COPY); - edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/paste"), EDIT_PASTE); + edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("ui_cut"), EDIT_CUT); + edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("ui_copy"), EDIT_COPY); + edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("ui_paste"), EDIT_PASTE); edit_menu->get_popup()->add_separator(); - edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/select_all"), EDIT_SELECT_ALL); + edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("ui_text_select_all"), EDIT_SELECT_ALL); edit_menu->get_popup()->add_separator(); edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/move_up"), EDIT_MOVE_LINE_UP); edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/move_down"), EDIT_MOVE_LINE_DOWN); @@ -634,15 +617,23 @@ TextEditor::TextEditor() { convert_case->add_shortcut(ED_SHORTCUT("script_text_editor/capitalize", TTR("Capitalize")), EDIT_CAPITALIZE); convert_case->connect("id_pressed", callable_mp(this, &TextEditor::_edit_option)); - highlighters["Standard"] = nullptr; highlighter_menu = memnew(PopupMenu); highlighter_menu->set_name("highlighter_menu"); edit_menu->get_popup()->add_child(highlighter_menu); edit_menu->get_popup()->add_submenu_item(TTR("Syntax Highlighter"), "highlighter_menu"); - highlighter_menu->add_radio_check_item(TTR("Standard")); highlighter_menu->connect("id_pressed", callable_mp(this, &TextEditor::_change_syntax_highlighter)); + Ref<EditorPlainTextSyntaxHighlighter> plain_highlighter; + plain_highlighter.instance(); + add_syntax_highlighter(plain_highlighter); + + Ref<EditorStandardSyntaxHighlighter> highlighter; + highlighter.instance(); + add_syntax_highlighter(highlighter); + set_syntax_highlighter(plain_highlighter); + MenuButton *goto_menu = memnew(MenuButton); + goto_menu->set_shortcut_context(this); edit_hb->add_child(goto_menu); goto_menu->set_text(TTR("Go To")); goto_menu->set_switch_on_hover(true); @@ -662,15 +653,10 @@ TextEditor::TextEditor() { goto_line_dialog = memnew(GotoLineDialog); add_child(goto_line_dialog); - code_editor->get_text_edit()->set_drag_forwarding(this); + code_editor->get_text_editor()->set_drag_forwarding(this); } TextEditor::~TextEditor() { - for (const Map<String, SyntaxHighlighter *>::Element *E = highlighters.front(); E; E = E->next()) { - if (E->get() != nullptr) { - memdelete(E->get()); - } - } highlighters.clear(); } diff --git a/editor/plugins/text_editor.h b/editor/plugins/text_editor.h index 9d9025a2c4..c066d51b18 100644 --- a/editor/plugins/text_editor.h +++ b/editor/plugins/text_editor.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -37,28 +37,19 @@ class TextEditor : public ScriptEditorBase { GDCLASS(TextEditor, ScriptEditorBase); private: - CodeTextEditor *code_editor; + CodeTextEditor *code_editor = nullptr; Ref<TextFile> text_file; + bool editor_enabled = false; - HBoxContainer *edit_hb; - MenuButton *edit_menu; - PopupMenu *highlighter_menu; - MenuButton *search_menu; - PopupMenu *bookmarks_menu; - PopupMenu *context_menu; - - GotoLineDialog *goto_line_dialog; - - struct ColorsCache { - Color font_color; - Color symbol_color; - Color keyword_color; - Color basetype_color; - Color type_color; - Color comment_color; - Color string_color; - } colors_cache; + HBoxContainer *edit_hb = nullptr; + MenuButton *edit_menu = nullptr; + PopupMenu *highlighter_menu = nullptr; + MenuButton *search_menu = nullptr; + PopupMenu *bookmarks_menu = nullptr; + PopupMenu *context_menu = nullptr; + + GotoLineDialog *goto_line_dialog = nullptr; enum { EDIT_UNDO, @@ -98,13 +89,11 @@ private: protected: static void _bind_methods(); - void _notification(int p_what); - void _edit_option(int p_op); void _make_context_menu(bool p_selection, bool p_can_fold, bool p_is_folded, Vector2 p_position); void _text_edit_gui_input(const Ref<InputEvent> &ev); - Map<String, SyntaxHighlighter *> highlighters; + Map<String, Ref<EditorSyntaxHighlighter>> highlighters; void _change_syntax_highlighter(int p_idx); void _load_theme_settings(); @@ -116,42 +105,42 @@ protected: void _bookmark_item_pressed(int p_idx); public: - virtual void add_syntax_highlighter(SyntaxHighlighter *p_highlighter); - virtual void set_syntax_highlighter(SyntaxHighlighter *p_highlighter); - - virtual String get_name(); - virtual Ref<Texture2D> get_theme_icon(); - virtual RES get_edited_resource() const; - virtual void set_edited_resource(const RES &p_res); - void set_edited_file(const Ref<TextFile> &p_file); - virtual void reload_text(); - virtual void apply_code(); - virtual bool is_unsaved(); - virtual Variant get_edit_state(); - virtual void set_edit_state(const Variant &p_state); - virtual Vector<String> get_functions(); - virtual void get_breakpoints(List<int> *p_breakpoints); - virtual void goto_line(int p_line, bool p_with_error = false); + virtual void add_syntax_highlighter(Ref<EditorSyntaxHighlighter> p_highlighter) override; + virtual void set_syntax_highlighter(Ref<EditorSyntaxHighlighter> p_highlighter) override; + + virtual String get_name() override; + virtual Ref<Texture2D> get_theme_icon() override; + virtual RES get_edited_resource() const override; + virtual void set_edited_resource(const RES &p_res) override; + virtual void enable_editor() override; + virtual void reload_text() override; + virtual void apply_code() override; + virtual bool is_unsaved() override; + virtual Variant get_edit_state() override; + virtual void set_edit_state(const Variant &p_state) override; + virtual Vector<String> get_functions() override; + virtual Array get_breakpoints() override; + virtual void goto_line(int p_line, bool p_with_error = false) override; void goto_line_selection(int p_line, int p_begin, int p_end); - virtual void set_executing_line(int p_line); - virtual void clear_executing_line(); - virtual void trim_trailing_whitespace(); - virtual void insert_final_newline(); - virtual void convert_indent_to_spaces(); - virtual void convert_indent_to_tabs(); - virtual void ensure_focus(); - virtual void tag_saved_version(); - virtual void update_settings(); - virtual bool show_members_overview(); - virtual bool can_lose_focus_on_node_selection() { return true; } - virtual void set_debugger_active(bool p_active); - virtual void set_tooltip_request_func(String p_method, Object *p_obj); - virtual void add_callback(const String &p_function, PackedStringArray p_args); - - virtual Control *get_edit_menu(); - virtual void clear_edit_menu(); - - virtual void validate(); + virtual void set_executing_line(int p_line) override; + virtual void clear_executing_line() override; + virtual void trim_trailing_whitespace() override; + virtual void insert_final_newline() override; + virtual void convert_indent_to_spaces() override; + virtual void convert_indent_to_tabs() override; + virtual void ensure_focus() override; + virtual void tag_saved_version() override; + virtual void update_settings() override; + virtual bool show_members_overview() override; + virtual bool can_lose_focus_on_node_selection() override { return true; } + virtual void set_debugger_active(bool p_active) override; + virtual void set_tooltip_request_func(String p_method, Object *p_obj) override; + virtual void add_callback(const String &p_function, PackedStringArray p_args) override; + + virtual Control *get_edit_menu() override; + virtual void clear_edit_menu() override; + + virtual void validate() override; static void register_editor(); diff --git a/editor/plugins/texture_3d_editor_plugin.cpp b/editor/plugins/texture_3d_editor_plugin.cpp new file mode 100644 index 0000000000..36297c8a4a --- /dev/null +++ b/editor/plugins/texture_3d_editor_plugin.cpp @@ -0,0 +1,212 @@ +/*************************************************************************/ +/* texture_3d_editor_plugin.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 "texture_3d_editor_plugin.h" + +#include "core/config/project_settings.h" +#include "core/io/resource_loader.h" +#include "editor/editor_settings.h" + +void Texture3DEditor::_gui_input(Ref<InputEvent> p_event) { +} + +void Texture3DEditor::_texture_rect_draw() { + texture_rect->draw_rect(Rect2(Point2(), texture_rect->get_size()), Color(1, 1, 1, 1)); +} + +void Texture3DEditor::_notification(int p_what) { + if (p_what == NOTIFICATION_READY) { + //get_scene()->connect("node_removed",this,"_node_removed"); + } + if (p_what == NOTIFICATION_RESIZED) { + _texture_rect_update_area(); + } + + if (p_what == NOTIFICATION_DRAW) { + Ref<Texture2D> checkerboard = get_theme_icon("Checkerboard", "EditorIcons"); + Size2 size = get_size(); + + draw_texture_rect(checkerboard, Rect2(Point2(), size), true); + } +} + +void Texture3DEditor::_texture_changed() { + if (!is_visible()) { + return; + } + update(); +} + +void Texture3DEditor::_update_material() { + material->set_shader_param("layer", (layer->get_value() + 0.5) / texture->get_depth()); + material->set_shader_param("tex", texture->get_rid()); + + String format = Image::get_format_name(texture->get_format()); + + String text; + text = itos(texture->get_width()) + "x" + itos(texture->get_height()) + "x" + itos(texture->get_depth()) + " " + format; + + info->set_text(text); +} + +void Texture3DEditor::_make_shaders() { + String shader_3d = "" + "shader_type canvas_item;\n" + "uniform sampler3D tex;\n" + "uniform float layer;\n" + "void fragment() {\n" + " COLOR = textureLod(tex,vec3(UV,layer),0.0);\n" + "}"; + + shader.instance(); + shader->set_code(shader_3d); + material.instance(); + material->set_shader(shader); +} + +void Texture3DEditor::_texture_rect_update_area() { + Size2 size = get_size(); + int tex_width = texture->get_width() * size.height / texture->get_height(); + int tex_height = size.height; + + if (tex_width > size.width) { + tex_width = size.width; + tex_height = texture->get_height() * tex_width / texture->get_width(); + } + + // Prevent the texture from being unpreviewable after the rescale, so that we can still see something + if (tex_height <= 0) { + tex_height = 1; + } + if (tex_width <= 0) { + tex_width = 1; + } + + int ofs_x = (size.width - tex_width) / 2; + int ofs_y = (size.height - tex_height) / 2; + + texture_rect->set_position(Vector2(ofs_x, ofs_y)); + texture_rect->set_size(Vector2(tex_width, tex_height)); +} + +void Texture3DEditor::edit(Ref<Texture3D> p_texture) { + if (!texture.is_null()) { + texture->disconnect("changed", callable_mp(this, &Texture3DEditor::_texture_changed)); + } + + texture = p_texture; + + if (!texture.is_null()) { + if (shader.is_null()) { + _make_shaders(); + } + + texture->connect("changed", callable_mp(this, &Texture3DEditor::_texture_changed)); + update(); + texture_rect->set_material(material); + setting = true; + layer->set_max(texture->get_depth() - 1); + layer->set_value(0); + layer->show(); + _update_material(); + setting = false; + _texture_rect_update_area(); + } else { + hide(); + } +} + +void Texture3DEditor::_bind_methods() { + ClassDB::bind_method(D_METHOD("_gui_input"), &Texture3DEditor::_gui_input); + ClassDB::bind_method(D_METHOD("_layer_changed"), &Texture3DEditor::_layer_changed); +} + +Texture3DEditor::Texture3DEditor() { + set_texture_repeat(TextureRepeat::TEXTURE_REPEAT_ENABLED); + set_custom_minimum_size(Size2(1, 150)); + texture_rect = memnew(Control); + texture_rect->connect("draw", callable_mp(this, &Texture3DEditor::_texture_rect_draw)); + texture_rect->set_mouse_filter(MOUSE_FILTER_IGNORE); + add_child(texture_rect); + + layer = memnew(SpinBox); + layer->set_step(1); + layer->set_max(100); + add_child(layer); + layer->set_anchor(SIDE_RIGHT, 1); + layer->set_anchor(SIDE_LEFT, 1); + layer->set_h_grow_direction(GROW_DIRECTION_BEGIN); + layer->set_modulate(Color(1, 1, 1, 0.8)); + info = memnew(Label); + add_child(info); + info->set_anchor(SIDE_RIGHT, 1); + info->set_anchor(SIDE_LEFT, 1); + info->set_anchor(SIDE_BOTTOM, 1); + info->set_anchor(SIDE_TOP, 1); + info->set_h_grow_direction(GROW_DIRECTION_BEGIN); + info->set_v_grow_direction(GROW_DIRECTION_BEGIN); + info->add_theme_color_override("font_color", Color(1, 1, 1, 1)); + info->add_theme_color_override("font_shadow_color", Color(0, 0, 0, 0.5)); + info->add_theme_constant_override("shadow_as_outline", 1); + info->add_theme_constant_override("shadow_offset_x", 2); + info->add_theme_constant_override("shadow_offset_y", 2); + + setting = false; + layer->connect("value_changed", Callable(this, "_layer_changed")); +} + +Texture3DEditor::~Texture3DEditor() { + if (!texture.is_null()) { + texture->disconnect("changed", callable_mp(this, &Texture3DEditor::_texture_changed)); + } +} + +// +bool EditorInspectorPlugin3DTexture::can_handle(Object *p_object) { + return Object::cast_to<Texture3D>(p_object) != nullptr; +} + +void EditorInspectorPlugin3DTexture::parse_begin(Object *p_object) { + Texture3D *texture = Object::cast_to<Texture3D>(p_object); + if (!texture) { + return; + } + Ref<Texture3D> m(texture); + + Texture3DEditor *editor = memnew(Texture3DEditor); + editor->edit(m); + add_custom_control(editor); +} + +Texture3DEditorPlugin::Texture3DEditorPlugin(EditorNode *p_node) { + Ref<EditorInspectorPlugin3DTexture> plugin; + plugin.instance(); + add_inspector_plugin(plugin); +} diff --git a/editor/plugins/texture_3d_editor_plugin.h b/editor/plugins/texture_3d_editor_plugin.h new file mode 100644 index 0000000000..9d90d3653f --- /dev/null +++ b/editor/plugins/texture_3d_editor_plugin.h @@ -0,0 +1,95 @@ +/*************************************************************************/ +/* texture_3d_editor_plugin.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 TEXTURE_3D_EDITOR_PLUGIN_H +#define TEXTURE_3D_EDITOR_PLUGIN_H + +#include "editor/editor_node.h" +#include "editor/editor_plugin.h" +#include "scene/resources/shader.h" +#include "scene/resources/texture.h" + +class Texture3DEditor : public Control { + GDCLASS(Texture3DEditor, Control); + + SpinBox *layer; + Label *info; + Ref<Texture3D> texture; + + Ref<Shader> shader; + Ref<ShaderMaterial> material; + + Control *texture_rect; + + void _make_shaders(); + + void _update_material(); + bool setting; + void _layer_changed(double) { + if (!setting) { + _update_material(); + } + } + + void _texture_rect_update_area(); + void _texture_rect_draw(); + + void _texture_changed(); + +protected: + void _notification(int p_what); + void _gui_input(Ref<InputEvent> p_event); + + static void _bind_methods(); + +public: + void edit(Ref<Texture3D> p_texture); + Texture3DEditor(); + ~Texture3DEditor(); +}; + +class EditorInspectorPlugin3DTexture : public EditorInspectorPlugin { + GDCLASS(EditorInspectorPlugin3DTexture, EditorInspectorPlugin); + +public: + virtual bool can_handle(Object *p_object) override; + virtual void parse_begin(Object *p_object) override; +}; + +class Texture3DEditorPlugin : public EditorPlugin { + GDCLASS(Texture3DEditorPlugin, EditorPlugin); + +public: + virtual String get_name() const override { return "Texture3D"; } + + Texture3DEditorPlugin(EditorNode *p_node); +}; + +#endif // TEXTURE_EDITOR_PLUGIN_H diff --git a/editor/plugins/texture_editor_plugin.cpp b/editor/plugins/texture_editor_plugin.cpp index b728a6700c..253f8878d2 100644 --- a/editor/plugins/texture_editor_plugin.cpp +++ b/editor/plugins/texture_editor_plugin.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -30,8 +30,8 @@ #include "texture_editor_plugin.h" +#include "core/config/project_settings.h" #include "core/io/resource_loader.h" -#include "core/project_settings.h" #include "editor/editor_settings.h" void TextureEditor::_gui_input(Ref<InputEvent> p_event) { @@ -79,6 +79,7 @@ void TextureEditor::_notification(int p_what) { draw_texture_rect(texture, Rect2(ofs_x, ofs_y, tex_width, tex_height)); Ref<Font> font = get_theme_font("font", "Label"); + int font_size = get_theme_font_size("font_size", "Label"); String format; if (Object::cast_to<ImageTexture>(*texture)) { @@ -90,20 +91,20 @@ void TextureEditor::_notification(int p_what) { } String text = itos(texture->get_width()) + "x" + itos(texture->get_height()) + " " + format; - Size2 rect = font->get_string_size(text); + Size2 rect = font->get_string_size(text, font_size); - Vector2 draw_from = size - rect + Size2(-2, font->get_ascent() - 2); + Vector2 draw_from = size - rect + Size2(-2, font->get_ascent(font_size) - 2); if (draw_from.x < 0) { draw_from.x = 0; } - draw_string(font, draw_from + Vector2(2, 2), text, Color(0, 0, 0, 0.5), size.width); - draw_string(font, draw_from - Vector2(2, 2), text, Color(0, 0, 0, 0.5), size.width); - draw_string(font, draw_from, text, Color(1, 1, 1, 1), size.width); + draw_string(font, draw_from + Vector2(2, 2), text, HALIGN_LEFT, size.width, font_size, Color(0, 0, 0, 0.5)); + draw_string(font, draw_from - Vector2(2, 2), text, HALIGN_LEFT, size.width, font_size, Color(0, 0, 0, 0.5)); + draw_string(font, draw_from, text, HALIGN_LEFT, size.width, font_size, Color(1, 1, 1, 1)); } } -void TextureEditor::_changed_callback(Object *p_changed, const char *p_prop) { +void TextureEditor::_texture_changed() { if (!is_visible()) { return; } @@ -112,13 +113,13 @@ void TextureEditor::_changed_callback(Object *p_changed, const char *p_prop) { void TextureEditor::edit(Ref<Texture2D> p_texture) { if (!texture.is_null()) { - texture->remove_change_receptor(this); + texture->disconnect("changed", callable_mp(this, &TextureEditor::_texture_changed)); } texture = p_texture; if (!texture.is_null()) { - texture->add_change_receptor(this); + texture->connect("changed", callable_mp(this, &TextureEditor::_texture_changed)); update(); } else { hide(); @@ -136,7 +137,7 @@ TextureEditor::TextureEditor() { TextureEditor::~TextureEditor() { if (!texture.is_null()) { - texture->remove_change_receptor(this); + texture->disconnect("changed", callable_mp(this, &TextureEditor::_texture_changed)); } } diff --git a/editor/plugins/texture_editor_plugin.h b/editor/plugins/texture_editor_plugin.h index 63eea2b767..ebe8882194 100644 --- a/editor/plugins/texture_editor_plugin.h +++ b/editor/plugins/texture_editor_plugin.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -43,7 +43,7 @@ class TextureEditor : public Control { protected: void _notification(int p_what); void _gui_input(Ref<InputEvent> p_event); - void _changed_callback(Object *p_changed, const char *p_prop); + void _texture_changed(); static void _bind_methods(); public: @@ -56,15 +56,15 @@ class EditorInspectorPluginTexture : public EditorInspectorPlugin { GDCLASS(EditorInspectorPluginTexture, EditorInspectorPlugin); public: - virtual bool can_handle(Object *p_object); - virtual void parse_begin(Object *p_object); + virtual bool can_handle(Object *p_object) override; + virtual void parse_begin(Object *p_object) override; }; class TextureEditorPlugin : public EditorPlugin { GDCLASS(TextureEditorPlugin, EditorPlugin); public: - virtual String get_name() const { return "Texture2D"; } + virtual String get_name() const override { return "Texture2D"; } TextureEditorPlugin(EditorNode *p_node); }; diff --git a/editor/plugins/texture_layered_editor_plugin.cpp b/editor/plugins/texture_layered_editor_plugin.cpp index 59e87fb273..254ad3d56e 100644 --- a/editor/plugins/texture_layered_editor_plugin.cpp +++ b/editor/plugins/texture_layered_editor_plugin.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -30,8 +30,8 @@ #include "texture_layered_editor_plugin.h" +#include "core/config/project_settings.h" #include "core/io/resource_loader.h" -#include "core/project_settings.h" #include "editor/editor_settings.h" void TextureLayeredEditor::_gui_input(Ref<InputEvent> p_event) { @@ -63,7 +63,7 @@ void TextureLayeredEditor::_notification(int p_what) { } } -void TextureLayeredEditor::_changed_callback(Object *p_changed, const char *p_prop) { +void TextureLayeredEditor::_texture_changed() { if (!is_visible()) { return; } @@ -173,7 +173,7 @@ void TextureLayeredEditor::_texture_rect_update_area() { void TextureLayeredEditor::edit(Ref<TextureLayered> p_texture) { if (!texture.is_null()) { - texture->remove_change_receptor(this); + texture->disconnect("changed", callable_mp(this, &TextureLayeredEditor::_texture_changed)); } texture = p_texture; @@ -183,7 +183,7 @@ void TextureLayeredEditor::edit(Ref<TextureLayered> p_texture) { _make_shaders(); } - texture->add_change_receptor(this); + texture->connect("changed", callable_mp(this, &TextureLayeredEditor::_texture_changed)); update(); texture_rect->set_material(materials[texture->get_layered_type()]); setting = true; @@ -225,21 +225,20 @@ TextureLayeredEditor::TextureLayeredEditor() { layer->set_step(1); layer->set_max(100); add_child(layer); - layer->set_anchor(MARGIN_RIGHT, 1); - layer->set_anchor(MARGIN_LEFT, 1); + layer->set_anchor(SIDE_RIGHT, 1); + layer->set_anchor(SIDE_LEFT, 1); layer->set_h_grow_direction(GROW_DIRECTION_BEGIN); layer->set_modulate(Color(1, 1, 1, 0.8)); info = memnew(Label); add_child(info); - info->set_anchor(MARGIN_RIGHT, 1); - info->set_anchor(MARGIN_LEFT, 1); - info->set_anchor(MARGIN_BOTTOM, 1); - info->set_anchor(MARGIN_TOP, 1); + info->set_anchor(SIDE_RIGHT, 1); + info->set_anchor(SIDE_LEFT, 1); + info->set_anchor(SIDE_BOTTOM, 1); + info->set_anchor(SIDE_TOP, 1); info->set_h_grow_direction(GROW_DIRECTION_BEGIN); info->set_v_grow_direction(GROW_DIRECTION_BEGIN); info->add_theme_color_override("font_color", Color(1, 1, 1, 1)); - info->add_theme_color_override("font_color_shadow", Color(0, 0, 0, 0.5)); - info->add_theme_color_override("font_color_shadow", Color(0, 0, 0, 0.5)); + info->add_theme_color_override("font_shadow_color", Color(0, 0, 0, 0.5)); info->add_theme_constant_override("shadow_as_outline", 1); info->add_theme_constant_override("shadow_offset_x", 2); info->add_theme_constant_override("shadow_offset_y", 2); @@ -249,9 +248,6 @@ TextureLayeredEditor::TextureLayeredEditor() { } TextureLayeredEditor::~TextureLayeredEditor() { - if (!texture.is_null()) { - texture->remove_change_receptor(this); - } } // diff --git a/editor/plugins/texture_layered_editor_plugin.h b/editor/plugins/texture_layered_editor_plugin.h index 4c5e06a5b8..c4ced62fb9 100644 --- a/editor/plugins/texture_layered_editor_plugin.h +++ b/editor/plugins/texture_layered_editor_plugin.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -63,10 +63,11 @@ class TextureLayeredEditor : public Control { void _texture_rect_update_area(); void _texture_rect_draw(); + void _texture_changed(); + protected: void _notification(int p_what); void _gui_input(Ref<InputEvent> p_event); - void _changed_callback(Object *p_changed, const char *p_prop); static void _bind_methods(); public: @@ -79,15 +80,15 @@ class EditorInspectorPluginLayeredTexture : public EditorInspectorPlugin { GDCLASS(EditorInspectorPluginLayeredTexture, EditorInspectorPlugin); public: - virtual bool can_handle(Object *p_object); - virtual void parse_begin(Object *p_object); + virtual bool can_handle(Object *p_object) override; + virtual void parse_begin(Object *p_object) override; }; class TextureLayeredEditorPlugin : public EditorPlugin { GDCLASS(TextureLayeredEditorPlugin, EditorPlugin); public: - virtual String get_name() const { return "TextureLayered"; } + virtual String get_name() const override { return "TextureLayered"; } TextureLayeredEditorPlugin(EditorNode *p_node); }; diff --git a/editor/plugins/texture_region_editor_plugin.cpp b/editor/plugins/texture_region_editor_plugin.cpp index 9b8b111be5..63255e6547 100644 --- a/editor/plugins/texture_region_editor_plugin.cpp +++ b/editor/plugins/texture_region_editor_plugin.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -42,8 +42,21 @@ void draw_margin_line(Control *edit_draw, Vector2 from, Vector2 to) { Vector2 line = (to - from).normalized() * 10; + + // Draw a translucent background line to make the foreground line visible on any background. + edit_draw->draw_line( + from, + to, + EditorNode::get_singleton()->get_theme_base()->get_theme_color("mono_color", "Editor").inverted() * Color(1, 1, 1, 0.5), + Math::round(2 * EDSCALE)); + while ((to - from).length_squared() > 200) { - edit_draw->draw_line(from, from + line, EditorNode::get_singleton()->get_theme_base()->get_theme_color("mono_color", "Editor"), 2); + edit_draw->draw_line( + from, + from + line, + EditorNode::get_singleton()->get_theme_base()->get_theme_color("mono_color", "Editor"), + Math::round(2 * EDSCALE)); + from += line * 2; } } @@ -177,7 +190,7 @@ void TextureRegionEditor::_region_draw() { } ofs = (endpoints[next] - endpoints[i]) / 2; - ofs += (endpoints[next] - endpoints[i]).tangent().normalized() * (select_handle->get_size().width / 2); + ofs += (endpoints[next] - endpoints[i]).orthogonal().normalized() * (select_handle->get_size().width / 2); if (snap_mode != SNAP_AUTOSLICE) { edit_draw->draw_texture(select_handle, (endpoints[i] + ofs - (select_handle->get_size() / 2)).floor() - draw_ofs * draw_zoom); @@ -217,23 +230,23 @@ void TextureRegionEditor::_region_draw() { Size2 vmin = vscroll->get_combined_minimum_size(); // Avoid scrollbar overlapping. - hscroll->set_anchor_and_margin(MARGIN_RIGHT, ANCHOR_END, vscroll->is_visible() ? -vmin.width : 0); - vscroll->set_anchor_and_margin(MARGIN_BOTTOM, ANCHOR_END, hscroll->is_visible() ? -hmin.height : 0); + hscroll->set_anchor_and_offset(SIDE_RIGHT, ANCHOR_END, vscroll->is_visible() ? -vmin.width : 0); + vscroll->set_anchor_and_offset(SIDE_BOTTOM, ANCHOR_END, hscroll->is_visible() ? -hmin.height : 0); updating_scroll = false; if (node_ninepatch || obj_styleBox.is_valid()) { float margins[4] = { 0 }; if (node_ninepatch) { - margins[0] = node_ninepatch->get_patch_margin(MARGIN_TOP); - margins[1] = node_ninepatch->get_patch_margin(MARGIN_BOTTOM); - margins[2] = node_ninepatch->get_patch_margin(MARGIN_LEFT); - margins[3] = node_ninepatch->get_patch_margin(MARGIN_RIGHT); + margins[0] = node_ninepatch->get_patch_margin(SIDE_TOP); + margins[1] = node_ninepatch->get_patch_margin(SIDE_BOTTOM); + margins[2] = node_ninepatch->get_patch_margin(SIDE_LEFT); + margins[3] = node_ninepatch->get_patch_margin(SIDE_RIGHT); } else if (obj_styleBox.is_valid()) { - margins[0] = obj_styleBox->get_margin_size(MARGIN_TOP); - margins[1] = obj_styleBox->get_margin_size(MARGIN_BOTTOM); - margins[2] = obj_styleBox->get_margin_size(MARGIN_LEFT); - margins[3] = obj_styleBox->get_margin_size(MARGIN_RIGHT); + margins[0] = obj_styleBox->get_margin_size(SIDE_TOP); + margins[1] = obj_styleBox->get_margin_size(SIDE_BOTTOM); + margins[2] = obj_styleBox->get_margin_size(SIDE_LEFT); + margins[3] = obj_styleBox->get_margin_size(SIDE_RIGHT); } Vector2 pos[4] = { @@ -278,15 +291,15 @@ void TextureRegionEditor::_region_input(const Ref<InputEvent> &p_input) { edited_margin = -1; float margins[4] = { 0 }; if (node_ninepatch) { - margins[0] = node_ninepatch->get_patch_margin(MARGIN_TOP); - margins[1] = node_ninepatch->get_patch_margin(MARGIN_BOTTOM); - margins[2] = node_ninepatch->get_patch_margin(MARGIN_LEFT); - margins[3] = node_ninepatch->get_patch_margin(MARGIN_RIGHT); + margins[0] = node_ninepatch->get_patch_margin(SIDE_TOP); + margins[1] = node_ninepatch->get_patch_margin(SIDE_BOTTOM); + margins[2] = node_ninepatch->get_patch_margin(SIDE_LEFT); + margins[3] = node_ninepatch->get_patch_margin(SIDE_RIGHT); } else if (obj_styleBox.is_valid()) { - margins[0] = obj_styleBox->get_margin_size(MARGIN_TOP); - margins[1] = obj_styleBox->get_margin_size(MARGIN_BOTTOM); - margins[2] = obj_styleBox->get_margin_size(MARGIN_LEFT); - margins[3] = obj_styleBox->get_margin_size(MARGIN_RIGHT); + margins[0] = obj_styleBox->get_margin_size(SIDE_TOP); + margins[1] = obj_styleBox->get_margin_size(SIDE_BOTTOM); + margins[2] = obj_styleBox->get_margin_size(SIDE_LEFT); + margins[3] = obj_styleBox->get_margin_size(SIDE_RIGHT); } Vector2 pos[4] = { @@ -395,13 +408,13 @@ void TextureRegionEditor::_region_input(const Ref<InputEvent> &p_input) { } else if (drag) { if (edited_margin >= 0) { undo_redo->create_action(TTR("Set Margin")); - static Margin m[4] = { MARGIN_TOP, MARGIN_BOTTOM, MARGIN_LEFT, MARGIN_RIGHT }; + static Side side[4] = { SIDE_TOP, SIDE_BOTTOM, SIDE_LEFT, SIDE_RIGHT }; if (node_ninepatch) { - undo_redo->add_do_method(node_ninepatch, "set_patch_margin", m[edited_margin], node_ninepatch->get_patch_margin(m[edited_margin])); - undo_redo->add_undo_method(node_ninepatch, "set_patch_margin", m[edited_margin], prev_margin); + undo_redo->add_do_method(node_ninepatch, "set_patch_margin", side[edited_margin], node_ninepatch->get_patch_margin(side[edited_margin])); + undo_redo->add_undo_method(node_ninepatch, "set_patch_margin", side[edited_margin], prev_margin); } else if (obj_styleBox.is_valid()) { - undo_redo->add_do_method(obj_styleBox.ptr(), "set_margin_size", m[edited_margin], obj_styleBox->get_margin_size(m[edited_margin])); - undo_redo->add_undo_method(obj_styleBox.ptr(), "set_margin_size", m[edited_margin], prev_margin); + undo_redo->add_do_method(obj_styleBox.ptr(), "set_margin_size", side[edited_margin], obj_styleBox->get_margin_size(side[edited_margin])); + undo_redo->add_undo_method(obj_styleBox.ptr(), "set_margin_size", side[edited_margin], prev_margin); obj_styleBox->emit_signal(CoreStringNames::get_singleton()->changed); } edited_margin = -1; @@ -438,12 +451,12 @@ void TextureRegionEditor::_region_input(const Ref<InputEvent> &p_input) { if (drag) { drag = false; if (edited_margin >= 0) { - static Margin m[4] = { MARGIN_TOP, MARGIN_BOTTOM, MARGIN_LEFT, MARGIN_RIGHT }; + static Side side[4] = { SIDE_TOP, SIDE_BOTTOM, SIDE_LEFT, SIDE_RIGHT }; if (node_ninepatch) { - node_ninepatch->set_patch_margin(m[edited_margin], prev_margin); + node_ninepatch->set_patch_margin(side[edited_margin], prev_margin); } if (obj_styleBox.is_valid()) { - obj_styleBox->set_margin_size(m[edited_margin], prev_margin); + obj_styleBox->set_margin_size(side[edited_margin], prev_margin); } edited_margin = -1; } else { @@ -467,31 +480,52 @@ void TextureRegionEditor::_region_input(const Ref<InputEvent> &p_input) { Vector2 dragged(mm->get_relative().x / draw_zoom, mm->get_relative().y / draw_zoom); hscroll->set_value(hscroll->get_value() - dragged.x); vscroll->set_value(vscroll->get_value() - dragged.y); - } else if (drag) { if (edited_margin >= 0) { float new_margin = 0; - if (edited_margin == 0) { - new_margin = prev_margin + (mm->get_position().y - drag_from.y) / draw_zoom; - } else if (edited_margin == 1) { - new_margin = prev_margin - (mm->get_position().y - drag_from.y) / draw_zoom; - } else if (edited_margin == 2) { - new_margin = prev_margin + (mm->get_position().x - drag_from.x) / draw_zoom; - } else if (edited_margin == 3) { - new_margin = prev_margin - (mm->get_position().x - drag_from.x) / draw_zoom; + + if (snap_mode != SNAP_GRID) { + if (edited_margin == 0) { + new_margin = prev_margin + (mm->get_position().y - drag_from.y) / draw_zoom; + } else if (edited_margin == 1) { + new_margin = prev_margin - (mm->get_position().y - drag_from.y) / draw_zoom; + } else if (edited_margin == 2) { + new_margin = prev_margin + (mm->get_position().x - drag_from.x) / draw_zoom; + } else if (edited_margin == 3) { + new_margin = prev_margin - (mm->get_position().x - drag_from.x) / draw_zoom; + } else { + ERR_PRINT("Unexpected edited_margin"); + } + + if (snap_mode == SNAP_PIXEL) { + new_margin = Math::round(new_margin); + } } else { - ERR_PRINT("Unexpected edited_margin"); + Vector2 pos_snapped = snap_point(mtx.affine_inverse().xform(mm->get_position())); + Rect2 rect_rounded = Rect2(rect.position.round(), rect.size.round()); + + if (edited_margin == 0) { + new_margin = pos_snapped.y - rect_rounded.position.y; + } else if (edited_margin == 1) { + new_margin = rect_rounded.size.y + rect_rounded.position.y - pos_snapped.y; + } else if (edited_margin == 2) { + new_margin = pos_snapped.x - rect_rounded.position.x; + } else if (edited_margin == 3) { + new_margin = rect_rounded.size.x + rect_rounded.position.x - pos_snapped.x; + } else { + ERR_PRINT("Unexpected edited_margin"); + } } if (new_margin < 0) { new_margin = 0; } - static Margin m[4] = { MARGIN_TOP, MARGIN_BOTTOM, MARGIN_LEFT, MARGIN_RIGHT }; + static Side side[4] = { SIDE_TOP, SIDE_BOTTOM, SIDE_LEFT, SIDE_RIGHT }; if (node_ninepatch) { - node_ninepatch->set_patch_margin(m[edited_margin], new_margin); + node_ninepatch->set_patch_margin(side[edited_margin], new_margin); } if (obj_styleBox.is_valid()) { - obj_styleBox->set_margin_size(m[edited_margin], new_margin); + obj_styleBox->set_margin_size(side[edited_margin], new_margin); } } else { Vector2 new_pos = mtx.affine_inverse().xform(mm->get_position()); @@ -772,15 +806,15 @@ void TextureRegionEditor::_notification(int p_what) { zoom_reset->set_icon(get_theme_icon("ZoomReset", "EditorIcons")); zoom_in->set_icon(get_theme_icon("ZoomMore", "EditorIcons")); - vscroll->set_anchors_and_margins_preset(PRESET_RIGHT_WIDE); - hscroll->set_anchors_and_margins_preset(PRESET_BOTTOM_WIDE); + vscroll->set_anchors_and_offsets_preset(PRESET_RIGHT_WIDE); + hscroll->set_anchors_and_offsets_preset(PRESET_BOTTOM_WIDE); } break; case NOTIFICATION_VISIBILITY_CHANGED: { if (snap_mode == SNAP_AUTOSLICE && is_visible() && autoslice_is_dirty) { _update_autoslice(); } } break; - case NOTIFICATION_WM_FOCUS_IN: { + case NOTIFICATION_WM_WINDOW_FOCUS_IN: { // This happens when the user leaves the Editor and returns, // they could have changed the textures, so the cache is cleared. cache_map.clear(); @@ -829,19 +863,19 @@ Sprite2D *TextureRegionEditor::get_sprite() { void TextureRegionEditor::edit(Object *p_obj) { if (node_sprite) { - node_sprite->remove_change_receptor(this); + node_sprite->disconnect("changed", callable_mp(this, &TextureRegionEditor::_texture_changed)); } if (node_sprite_3d) { - node_sprite_3d->remove_change_receptor(this); + node_sprite_3d->disconnect("changed", callable_mp(this, &TextureRegionEditor::_texture_changed)); } if (node_ninepatch) { - node_ninepatch->remove_change_receptor(this); + node_ninepatch->disconnect("changed", callable_mp(this, &TextureRegionEditor::_texture_changed)); } if (obj_styleBox.is_valid()) { - obj_styleBox->remove_change_receptor(this); + obj_styleBox->disconnect("changed", callable_mp(this, &TextureRegionEditor::_texture_changed)); } if (atlas_tex.is_valid()) { - atlas_tex->remove_change_receptor(this); + atlas_tex->disconnect("changed", callable_mp(this, &TextureRegionEditor::_texture_changed)); } if (p_obj) { node_sprite = Object::cast_to<Sprite2D>(p_obj); @@ -853,7 +887,7 @@ void TextureRegionEditor::edit(Object *p_obj) { if (Object::cast_to<AtlasTexture>(p_obj)) { atlas_tex = Ref<AtlasTexture>(Object::cast_to<AtlasTexture>(p_obj)); } - p_obj->add_change_receptor(this); + p_obj->connect("changed", callable_mp(this, &TextureRegionEditor::_texture_changed)); _edit_region(); } else { node_sprite = nullptr; @@ -871,13 +905,11 @@ void TextureRegionEditor::edit(Object *p_obj) { } } -void TextureRegionEditor::_changed_callback(Object *p_changed, const char *p_prop) { +void TextureRegionEditor::_texture_changed() { if (!is_visible()) { return; } - if (p_prop == StringName("atlas") || p_prop == StringName("texture")) { - _edit_region(); - } + _edit_region(); } void TextureRegionEditor::_edit_region() { @@ -1037,17 +1069,20 @@ TextureRegionEditor::TextureRegionEditor(EditorNode *p_editor) { edit_draw->add_child(zoom_hb); zoom_hb->set_begin(Point2(5, 5)); - zoom_out = memnew(ToolButton); + zoom_out = memnew(Button); + zoom_out->set_flat(true); zoom_out->set_tooltip(TTR("Zoom Out")); zoom_out->connect("pressed", callable_mp(this, &TextureRegionEditor::_zoom_out)); zoom_hb->add_child(zoom_out); - zoom_reset = memnew(ToolButton); + zoom_reset = memnew(Button); + zoom_reset->set_flat(true); zoom_reset->set_tooltip(TTR("Zoom Reset")); zoom_reset->connect("pressed", callable_mp(this, &TextureRegionEditor::_zoom_reset)); zoom_hb->add_child(zoom_reset); - zoom_in = memnew(ToolButton); + zoom_in = memnew(Button); + zoom_in->set_flat(true); zoom_in->set_tooltip(TTR("Zoom In")); zoom_in->connect("pressed", callable_mp(this, &TextureRegionEditor::_zoom_in)); zoom_hb->add_child(zoom_in); diff --git a/editor/plugins/texture_region_editor_plugin.h b/editor/plugins/texture_region_editor_plugin.h index 93da23fd50..d3db0a08a9 100644 --- a/editor/plugins/texture_region_editor_plugin.h +++ b/editor/plugins/texture_region_editor_plugin.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -56,9 +56,9 @@ class TextureRegionEditor : public VBoxContainer { friend class TextureRegionEditorPlugin; OptionButton *snap_mode_button; - ToolButton *zoom_in; - ToolButton *zoom_reset; - ToolButton *zoom_out; + Button *zoom_in; + Button *zoom_reset; + Button *zoom_out; HBoxContainer *hb_grid; //For showing/hiding the grid controls when changing the SnapMode SpinBox *sb_step_y; SpinBox *sb_step_x; @@ -117,6 +117,8 @@ class TextureRegionEditor : public VBoxContainer { void _update_rect(); void _update_autoslice(); + void _texture_changed(); + protected: void _notification(int p_what); void _node_removed(Object *p_obj); @@ -124,8 +126,6 @@ protected: Vector2 snap_point(Vector2 p_target) const; - virtual void _changed_callback(Object *p_changed, const char *p_prop); - public: void _edit_region(); void _region_draw(); @@ -155,13 +155,13 @@ protected: void _editor_visiblity_changed(); public: - virtual String get_name() const { return "TextureRegion"; } - bool has_main_screen() const { return false; } - virtual void edit(Object *p_object); - virtual bool handles(Object *p_object) const; - virtual void make_visible(bool p_visible); - void set_state(const Dictionary &p_state); - Dictionary get_state() const; + virtual String get_name() const override { return "TextureRegion"; } + bool has_main_screen() const override { return false; } + virtual void edit(Object *p_object) override; + virtual bool handles(Object *p_object) const override; + virtual void make_visible(bool p_visible) override; + void set_state(const Dictionary &p_state) override; + Dictionary get_state() const override; TextureRegionEditorPlugin(EditorNode *p_node); }; diff --git a/editor/plugins/theme_editor_plugin.cpp b/editor/plugins/theme_editor_plugin.cpp index eb028659fd..dfa8c04145 100644 --- a/editor/plugins/theme_editor_plugin.cpp +++ b/editor/plugins/theme_editor_plugin.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -78,9 +78,12 @@ void ThemeEditor::_name_menu_about_to_show() { Theme::get_default()->get_font_list(fromtype, &names); break; case 3: - Theme::get_default()->get_color_list(fromtype, &names); + Theme::get_default()->get_font_size_list(fromtype, &names); break; case 4: + Theme::get_default()->get_color_list(fromtype, &names); + break; + case 5: Theme::get_default()->get_constant_list(fromtype, &names); break; } @@ -88,6 +91,7 @@ void ThemeEditor::_name_menu_about_to_show() { theme->get_icon_list(fromtype, &names); theme->get_stylebox_list(fromtype, &names); theme->get_font_list(fromtype, &names); + theme->get_font_size_list(fromtype, &names); theme->get_color_list(fromtype, &names); theme->get_constant_list(fromtype, &names); } @@ -120,6 +124,7 @@ struct _TECategory { Set<RefItem<StyleBox>> stylebox_items; Set<RefItem<Font>> font_items; + Set<Item<int>> font_size_items; Set<RefItem<Texture2D>> icon_items; Set<Item<Color>> color_items; @@ -160,6 +165,15 @@ void ThemeEditor::_save_template_cbk(String fname) { tc.font_items.insert(it); } + List<StringName> font_size_list; + Theme::get_default()->get_font_size_list(E->key(), &font_list); + for (List<StringName>::Element *F = font_size_list.front(); F; F = F->next()) { + _TECategory::Item<int> it; + it.name = F->get(); + it.item = Theme::get_default()->get_font_size(F->get(), E->key()); + tc.font_size_items.insert(it); + } + List<StringName> icon_list; Theme::get_default()->get_icon_list(E->key(), &icon_list); for (List<StringName>::Element *F = icon_list.front(); F; F = F->next()) { @@ -206,8 +220,8 @@ void ThemeEditor::_save_template_cbk(String fname) { file->store_line("; [value] examples:"); file->store_line("; "); file->store_line("; Type.item = 6 ; numeric constant. "); - file->store_line("; Type.item = #FF00FF ; HTML color "); - file->store_line("; Type.item = #55FF00FF ; HTML color with alpha 55."); + file->store_line("; Type.item = #FF00FF ; HTML color (magenta)."); + file->store_line("; Type.item = #FF00FF55 ; HTML color (magenta with alpha 0x55)."); file->store_line("; Type.item = icon(image.png) ; icon in a png file (relative to theme file)."); file->store_line("; Type.item = font(font.xres) ; font in a resource (relative to theme file)."); file->store_line("; Type.item = sbox(stylebox.xres) ; stylebox in a resource (relative to theme file)."); @@ -284,6 +298,14 @@ void ThemeEditor::_save_template_cbk(String fname) { file->store_line(E->key() + "." + F->get().name + " = default"); } + if (tc.font_size_items.size()) { + file->store_line("\n; Font Size Items:\n"); + } + + for (Set<_TECategory::Item<int>>::Element *F = tc.font_size_items.front(); F; F = F->next()) { + file->store_line(E->key() + "." + F->get().name + " = default"); + } + if (tc.icon_items.size()) { file->store_line("\n; Icon Items:\n"); } @@ -327,9 +349,12 @@ void ThemeEditor::_dialog_cbk() { theme->set_font(name_edit->get_text(), type_edit->get_text(), Ref<Font>()); break; case 3: - theme->set_color(name_edit->get_text(), type_edit->get_text(), Color()); + theme->set_font_size(name_edit->get_text(), type_edit->get_text(), -1); break; case 4: + theme->set_color(name_edit->get_text(), type_edit->get_text(), Color()); + break; + case 5: theme->set_constant(name_edit->get_text(), type_edit->get_text(), 0); break; } @@ -362,6 +387,13 @@ void ThemeEditor::_dialog_cbk() { } { names.clear(); + Theme::get_default()->get_font_size_list(fromtype, &names); + for (List<StringName>::Element *E = names.front(); E; E = E->next()) { + theme->set_font_size(E->get(), fromtype, Theme::get_default()->get_font_size(E->get(), fromtype)); + } + } + { + names.clear(); Theme::get_default()->get_color_list(fromtype, &names); for (List<StringName>::Element *E = names.front(); E; E = E->next()) { theme->set_color(E->get(), fromtype, Theme::get_default()->get_color(E->get(), fromtype)); @@ -387,9 +419,12 @@ void ThemeEditor::_dialog_cbk() { theme->clear_font(name_edit->get_text(), type_edit->get_text()); break; case 3: - theme->clear_color(name_edit->get_text(), type_edit->get_text()); + theme->clear_font_size(name_edit->get_text(), type_edit->get_text()); break; case 4: + theme->clear_color(name_edit->get_text(), type_edit->get_text()); + break; + case 5: theme->clear_constant(name_edit->get_text(), type_edit->get_text()); break; } @@ -422,6 +457,13 @@ void ThemeEditor::_dialog_cbk() { } { names.clear(); + Theme::get_default()->get_font_size_list(fromtype, &names); + for (List<StringName>::Element *E = names.front(); E; E = E->next()) { + theme->clear_font_size(E->get(), fromtype); + } + } + { + names.clear(); Theme::get_default()->get_color_list(fromtype, &names); for (List<StringName>::Element *E = names.front(); E; E = E->next()) { theme->clear_color(E->get(), fromtype); @@ -465,13 +507,6 @@ void ThemeEditor::_theme_menu_cbk(int p_option) { theme->set_icon(E->get(), type, import ? base_theme->get_icon(E->get(), type) : Ref<Texture2D>()); } - List<StringName> shaders; - base_theme->get_shader_list(type, &shaders); - - for (List<StringName>::Element *E = shaders.front(); E; E = E->next()) { - theme->set_shader(E->get(), type, import ? base_theme->get_shader(E->get(), type) : Ref<Shader>()); - } - List<StringName> styleboxs; base_theme->get_stylebox_list(type, &styleboxs); @@ -486,6 +521,13 @@ void ThemeEditor::_theme_menu_cbk(int p_option) { theme->set_font(E->get(), type, Ref<Font>()); } + List<StringName> font_sizes; + base_theme->get_font_size_list(type, &font_sizes); + + for (List<StringName>::Element *E = font_sizes.front(); E; E = E->next()) { + theme->set_font_size(E->get(), type, base_theme->get_font_size(E->get(), type)); + } + List<StringName> colors; base_theme->get_color_list(type, &colors); @@ -514,7 +556,7 @@ void ThemeEditor::_theme_menu_cbk(int p_option) { if (p_option == POPUP_ADD) { // Add. add_del_dialog->set_title(TTR("Add Item")); - add_del_dialog->get_ok()->set_text(TTR("Add")); + add_del_dialog->get_ok_button()->set_text(TTR("Add")); add_del_dialog->popup_centered(Size2(490, 85) * EDSCALE); base_theme = Theme::get_default(); @@ -522,7 +564,7 @@ void ThemeEditor::_theme_menu_cbk(int p_option) { } else if (p_option == POPUP_CLASS_ADD) { // Add. add_del_dialog->set_title(TTR("Add All Items")); - add_del_dialog->get_ok()->set_text(TTR("Add All")); + add_del_dialog->get_ok_button()->set_text(TTR("Add All")); add_del_dialog->popup_centered(Size2(240, 85) * EDSCALE); base_theme = Theme::get_default(); @@ -534,14 +576,14 @@ void ThemeEditor::_theme_menu_cbk(int p_option) { } else if (p_option == POPUP_REMOVE) { add_del_dialog->set_title(TTR("Remove Item")); - add_del_dialog->get_ok()->set_text(TTR("Remove")); + add_del_dialog->get_ok_button()->set_text(TTR("Remove")); add_del_dialog->popup_centered(Size2(490, 85) * EDSCALE); base_theme = theme; } else if (p_option == POPUP_CLASS_REMOVE) { add_del_dialog->set_title(TTR("Remove All Items")); - add_del_dialog->get_ok()->set_text(TTR("Remove All")); + add_del_dialog->get_ok_button()->set_text(TTR("Remove All")); add_del_dialog->popup_centered(Size2(240, 85) * EDSCALE); base_theme = Theme::get_default(); @@ -629,7 +671,7 @@ ThemeEditor::ThemeEditor() { ScrollContainer *scroll = memnew(ScrollContainer); add_child(scroll); scroll->set_enable_v_scroll(true); - scroll->set_enable_h_scroll(false); + scroll->set_enable_h_scroll(true); scroll->set_v_size_flags(SIZE_EXPAND_FILL); MarginContainer *root_container = memnew(MarginContainer); @@ -672,8 +714,9 @@ ThemeEditor::ThemeEditor() { bt->set_text(TTR("Disabled Button")); bt->set_disabled(true); first_vb->add_child(bt); - ToolButton *tb = memnew(ToolButton); - tb->set_text("ToolButton"); + Button *tb = memnew(Button); + tb->set_flat(true); + tb->set_text("Button"); first_vb->add_child(tb); CheckButton *cb = memnew(CheckButton); @@ -827,7 +870,7 @@ ThemeEditor::ThemeEditor() { type_hbc->add_child(type_edit); type_menu = memnew(MenuButton); type_menu->set_flat(false); - type_menu->set_text(".."); + type_menu->set_text("..."); type_hbc->add_child(type_menu); type_menu->get_popup()->connect("id_pressed", callable_mp(this, &ThemeEditor::_type_menu_cbk)); @@ -845,7 +888,7 @@ ThemeEditor::ThemeEditor() { name_hbc->add_child(name_edit); name_menu = memnew(MenuButton); type_menu->set_flat(false); - name_menu->set_text(".."); + name_menu->set_text("..."); name_hbc->add_child(name_menu); name_menu->get_popup()->connect("about_to_popup", callable_mp(this, &ThemeEditor::_name_menu_about_to_show)); @@ -859,12 +902,13 @@ ThemeEditor::ThemeEditor() { type_select->add_item(TTR("Icon")); type_select->add_item(TTR("Style")); type_select->add_item(TTR("Font")); + type_select->add_item(TTR("Font Size")); type_select->add_item(TTR("Color")); type_select->add_item(TTR("Constant")); dialog_vbc->add_child(type_select); - add_del_dialog->get_ok()->connect("pressed", callable_mp(this, &ThemeEditor::_dialog_cbk)); + add_del_dialog->get_ok_button()->connect("pressed", callable_mp(this, &ThemeEditor::_dialog_cbk)); file_dialog = memnew(EditorFileDialog); file_dialog->add_filter("*.theme ; " + TTR("Theme File")); diff --git a/editor/plugins/theme_editor_plugin.h b/editor/plugins/theme_editor_plugin.h index 983bfb6b50..ab199f8e51 100644 --- a/editor/plugins/theme_editor_plugin.h +++ b/editor/plugins/theme_editor_plugin.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -105,11 +105,11 @@ class ThemeEditorPlugin : public EditorPlugin { Button *button; public: - virtual String get_name() const { return "Theme"; } - bool has_main_screen() const { return false; } - virtual void edit(Object *p_node); - virtual bool handles(Object *p_node) const; - virtual void make_visible(bool p_visible); + virtual String get_name() const override { return "Theme"; } + bool has_main_screen() const override { return false; } + virtual void edit(Object *p_node) override; + virtual bool handles(Object *p_node) const override; + virtual void make_visible(bool p_visible) override; ThemeEditorPlugin(EditorNode *p_node); }; diff --git a/editor/plugins/tile_map_editor_plugin.cpp b/editor/plugins/tile_map_editor_plugin.cpp index 3010d72d81..6a16aa28a9 100644 --- a/editor/plugins/tile_map_editor_plugin.cpp +++ b/editor/plugins/tile_map_editor_plugin.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -39,7 +39,10 @@ #include "scene/gui/split_container.h" void TileMapEditor::_node_removed(Node *p_node) { - if (p_node == node) { + if (p_node == node && node) { + // Fixes #44824, which describes a situation where you can reselect a TileMap node without first de-selecting it when switching scenes. + node->disconnect("settings_changed", callable_mp(this, &TileMapEditor::_tileset_settings_changed)); + node = nullptr; } } @@ -64,6 +67,8 @@ void TileMapEditor::_notification(int p_what) { } paint_button->set_icon(get_theme_icon("Edit", "EditorIcons")); + line_button->set_icon(get_theme_icon("CurveLinear", "EditorIcons")); + rectangle_button->set_icon(get_theme_icon("Rectangle", "EditorIcons")); bucket_fill_button->set_icon(get_theme_icon("Bucket", "EditorIcons")); picker_button->set_icon(get_theme_icon("ColorPick", "EditorIcons")); select_button->set_icon(get_theme_icon("ActionCopy", "EditorIcons")); @@ -87,13 +92,33 @@ void TileMapEditor::_notification(int p_what) { case NOTIFICATION_EXIT_TREE: { get_tree()->disconnect("node_removed", callable_mp(this, &TileMapEditor::_node_removed)); } break; + + case NOTIFICATION_APPLICATION_FOCUS_OUT: { + if (tool == TOOL_PAINTING) { + Vector<int> ids = get_selected_tiles(); + + if (ids.size() > 0 && ids[0] != TileMap::INVALID_CELL) { + _set_cell(over_tile, ids, flip_h, flip_v, transpose); + _finish_undo(); + + paint_undo.clear(); + } + + tool = TOOL_NONE; + _update_button_tool(); + } + + // set flag to ignore over_tile on refocus + refocus_over_tile = true; + } break; } } void TileMapEditor::_update_button_tool() { - ToolButton *tb[4] = { paint_button, bucket_fill_button, picker_button, select_button }; + Button *tb[6] = { paint_button, line_button, rectangle_button, bucket_fill_button, picker_button, select_button }; + // Unpress all buttons - for (int i = 0; i < 4; i++) { + for (int i = 0; i < 6; i++) { tb[i]->set_pressed(false); } @@ -103,6 +128,12 @@ void TileMapEditor::_update_button_tool() { case TOOL_PAINTING: { paint_button->set_pressed(true); } break; + case TOOL_LINE_PAINT: { + line_button->set_pressed(true); + } break; + case TOOL_RECTANGLE_PAINT: { + rectangle_button->set_pressed(true); + } break; case TOOL_BUCKET: { bucket_fill_button->set_pressed(true); } break; @@ -194,6 +225,21 @@ void TileMapEditor::_palette_multi_selected(int index, bool selected) { _update_palette(); } +void TileMapEditor::_palette_input(const Ref<InputEvent> &p_event) { + const Ref<InputEventMouseButton> mb = p_event; + + // Zoom in/out using Ctrl + mouse wheel. + if (mb.is_valid() && mb->is_pressed() && mb->get_command()) { + if (mb->is_pressed() && mb->get_button_index() == BUTTON_WHEEL_UP) { + size_slider->set_value(size_slider->get_value() + 0.2); + } + + if (mb->is_pressed() && mb->get_button_index() == BUTTON_WHEEL_DOWN) { + size_slider->set_value(size_slider->get_value() - 0.2); + } + } +} + void TileMapEditor::_canvas_mouse_enter() { mouse_over = true; CanvasItemEditor::get_singleton()->update_viewport(); @@ -219,7 +265,7 @@ Vector<int> TileMapEditor::get_selected_tiles() const { } void TileMapEditor::set_selected_tiles(Vector<int> p_tiles) { - palette->unselect_all(); + palette->deselect_all(); for (int i = p_tiles.size() - 1; i >= 0; i--) { int idx = palette->find_metadata(p_tiles[i]); @@ -366,11 +412,13 @@ void TileMapEditor::_sbox_input(const Ref<InputEvent> &p_ie) { // In modern C++ this could have been inside its body. namespace { struct _PaletteEntry { - int id; + int id = 0; String name; bool operator<(const _PaletteEntry &p_rhs) const { - return name < p_rhs.name; + // Natural no case comparison will compare strings based on CharType + // order (except digits) and on numbers that start on the same position. + return name.naturalnocasecmp_to(p_rhs.name) < 0; } }; } // namespace @@ -404,7 +452,7 @@ void TileMapEditor::_update_palette() { List<int> tiles; tileset->get_tile_list(&tiles); - if (tiles.empty()) { + if (tiles.is_empty()) { return; } @@ -606,9 +654,15 @@ Vector<Vector2> TileMapEditor::_bucket_fill(const Point2i &p_start, bool erase, return Vector<Vector2>(); } + // Check if the tile variation is the same + Vector2 prev_position = node->get_cell_autotile_coord(p_start.x, p_start.y); if (ids.size() == 1 && ids[0] == prev_id) { - // Same ID, nothing to change - return Vector<Vector2>(); + int current = manual_palette->get_current(); + Vector2 position = manual_palette->get_item_metadata(current); + if (prev_position == position) { + // Same ID and variation, nothing to change + return Vector<Vector2>(); + } } Rect2i r = node->get_used_rect(); @@ -778,7 +832,6 @@ void TileMapEditor::_draw_cell(Control *p_viewport, int p_cell, const Point2i &p r.size = node->get_tileset()->autotile_get_size(p_cell); r.position += (r.size + Vector2(spacing, spacing)) * offset; } - Size2 sc = p_xform.get_scale(); Size2 cell_size = node->get_cell_size(); bool centered_texture = node->is_centered_textures_enabled(); bool compatibility_mode_enabled = node->is_compatibility_mode_enabled(); @@ -814,12 +867,12 @@ void TileMapEditor::_draw_cell(Control *p_viewport, int p_cell, const Point2i &p } if (p_flip_h) { - sc.x *= -1.0; + rect.size.x *= -1.0; tile_ofs.x *= -1.0; } if (p_flip_v) { - sc.y *= -1.0; + rect.size.y *= -1.0; tile_ofs.y *= -1.0; } @@ -862,17 +915,17 @@ void TileMapEditor::_draw_cell(Control *p_viewport, int p_cell, const Point2i &p rect.position += tile_ofs; } - rect.position = p_xform.xform(rect.position); - rect.size *= sc; - Color modulate = node->get_tileset()->tile_get_modulate(p_cell); modulate.a = 0.5; + Transform2D old_transform = p_viewport->get_viewport_transform(); + p_viewport->draw_set_transform_matrix(p_xform); // Take into account TileMap transformation when displaying cell if (r.has_no_area()) { p_viewport->draw_texture_rect(t, rect, false, modulate, p_transpose); } else { p_viewport->draw_texture_rect_region(t, rect, r, modulate, p_transpose); } + p_viewport->draw_set_transform_matrix(old_transform); } void TileMapEditor::_draw_fill_preview(Control *p_viewport, int p_cell, const Point2i &p_point, bool p_flip_h, bool p_flip_v, bool p_transpose, const Point2i &p_autotile_coord, const Transform2D &p_xform) { @@ -978,19 +1031,8 @@ bool TileMapEditor::forward_gui_input(const Ref<InputEvent> &p_event) { } if (tool == TOOL_NONE) { - if (mb->get_shift()) { - if (mb->get_command()) { - tool = TOOL_RECTANGLE_PAINT; - } else { - tool = TOOL_LINE_PAINT; - } - - selection_active = false; - rectangle_begin = over_tile; - - _update_button_tool(); - return true; - } + tool = TOOL_PAINTING; + _update_button_tool(); if (mb->get_command()) { tool = TOOL_PICKING; @@ -999,12 +1041,14 @@ bool TileMapEditor::forward_gui_input(const Ref<InputEvent> &p_event) { return true; } - - tool = TOOL_PAINTING; - _update_button_tool(); } - if (tool == TOOL_PAINTING) { + if (tool == TOOL_LINE_PAINT || tool == TOOL_RECTANGLE_PAINT) { + selection_active = false; + rectangle_begin = over_tile; + + mouse_down = true; + } else if (tool == TOOL_PAINTING) { Vector<int> ids = get_selected_tiles(); if (ids.size() > 0 && ids[0] != TileMap::INVALID_CELL) { @@ -1035,6 +1079,10 @@ bool TileMapEditor::forward_gui_input(const Ref<InputEvent> &p_event) { paint_undo.clear(); } } else if (tool == TOOL_LINE_PAINT) { + if (!mouse_down) { + return true; + } + Vector<int> ids = get_selected_tiles(); if (ids.size() > 0 && ids[0] != TileMap::INVALID_CELL) { @@ -1047,8 +1095,17 @@ bool TileMapEditor::forward_gui_input(const Ref<InputEvent> &p_event) { paint_undo.clear(); CanvasItemEditor::get_singleton()->update_viewport(); + + mouse_down = false; + return true; } + + mouse_down = false; } else if (tool == TOOL_RECTANGLE_PAINT) { + if (!mouse_down) { + return true; + } + Vector<int> ids = get_selected_tiles(); if (ids.size() > 0 && ids[0] != TileMap::INVALID_CELL) { @@ -1061,7 +1118,12 @@ bool TileMapEditor::forward_gui_input(const Ref<InputEvent> &p_event) { _finish_undo(); CanvasItemEditor::get_singleton()->update_viewport(); + + mouse_down = false; + return true; } + + mouse_down = false; } else if (tool == TOOL_PASTING) { Point2 ofs = over_tile - rectangle.position; Vector<int> ids; @@ -1126,6 +1188,28 @@ bool TileMapEditor::forward_gui_input(const Ref<InputEvent> &p_event) { if (tool == TOOL_PASTING) { tool = TOOL_NONE; + + CanvasItemEditor::get_singleton()->update_viewport(); + + _update_button_tool(); + return true; + } + + if (tool == TOOL_LINE_PAINT) { + tool = TOOL_LINE_ERASE; + mouse_down = true; + rectangle_begin = over_tile; + + CanvasItemEditor::get_singleton()->update_viewport(); + + _update_button_tool(); + return true; + } + + if (tool == TOOL_RECTANGLE_PAINT) { + tool = TOOL_RECTANGLE_ERASE; + mouse_down = true; + rectangle_begin = over_tile; copydata.clear(); CanvasItemEditor::get_singleton()->update_viewport(); @@ -1140,39 +1224,74 @@ bool TileMapEditor::forward_gui_input(const Ref<InputEvent> &p_event) { Point2 local = node->world_to_map(xform_inv.xform(mb->get_position())); _start_undo(TTR("Erase TileMap")); + tool = TOOL_ERASING; + _set_cell(local, invalid_cell); - if (mb->get_shift()) { - if (mb->get_command()) { - tool = TOOL_RECTANGLE_ERASE; - } else { - tool = TOOL_LINE_ERASE; + _update_button_tool(); + return true; + } + + } else { + if (tool == TOOL_LINE_ERASE) { + if (!mouse_down) { + return true; + } + + tool = TOOL_LINE_PAINT; + _update_button_tool(); + + Vector<int> ids = get_selected_tiles(); + + if (ids.size() > 0 && ids[0] != TileMap::INVALID_CELL) { + _start_undo(TTR("Line Erase")); + for (Map<Point2i, CellOp>::Element *E = paint_undo.front(); E; E = E->next()) { + _set_cell(E->key(), invalid_cell, flip_h, flip_v, transpose); } + _finish_undo(); + paint_undo.clear(); + + CanvasItemEditor::get_singleton()->update_viewport(); - selection_active = false; - rectangle_begin = local; - } else { - tool = TOOL_ERASING; + mouse_down = false; + return true; + } - _set_cell(local, invalid_cell); + mouse_down = false; + } else if (tool == TOOL_RECTANGLE_ERASE) { + if (!mouse_down) { + return true; } + tool = TOOL_RECTANGLE_PAINT; _update_button_tool(); - return true; - } - } else { - if (tool == TOOL_ERASING || tool == TOOL_RECTANGLE_ERASE || tool == TOOL_LINE_ERASE) { - _finish_undo(); + Vector<int> ids = get_selected_tiles(); + + if (ids.size() > 0 && ids[0] != TileMap::INVALID_CELL) { + _start_undo(TTR("Rectangle Erase")); + for (int i = rectangle.position.y; i <= rectangle.position.y + rectangle.size.y; i++) { + for (int j = rectangle.position.x; j <= rectangle.position.x + rectangle.size.x; j++) { + _set_cell(Point2i(j, i), invalid_cell, flip_h, flip_v, transpose); + } + } + _finish_undo(); + paint_undo.clear(); - if (tool == TOOL_RECTANGLE_ERASE || tool == TOOL_LINE_ERASE) { CanvasItemEditor::get_singleton()->update_viewport(); + + mouse_down = false; + return true; } - tool = TOOL_NONE; + mouse_down = false; + tool = TOOL_RECTANGLE_PAINT; + } + if (tool == TOOL_ERASING) { + tool = TOOL_NONE; _update_button_tool(); - return true; + return true; } else if (tool == TOOL_BUCKET) { Vector<int> ids; ids.push_back(node->get_cell(over_tile.x, over_tile.y)); @@ -1210,6 +1329,12 @@ bool TileMapEditor::forward_gui_input(const Ref<InputEvent> &p_event) { CanvasItemEditor::get_singleton()->update_viewport(); } + if (refocus_over_tile) { + // editor lost focus; forget last tile position + old_over_tile = new_over_tile; + refocus_over_tile = false; + } + int tile_under = node->get_cell(over_tile.x, over_tile.y); String tile_name = "none"; @@ -1263,6 +1388,10 @@ bool TileMapEditor::forward_gui_input(const Ref<InputEvent> &p_event) { Vector<int> tmp_cell; bool erasing = (tool == TOOL_LINE_ERASE); + if (!mouse_down) { + return true; + } + tmp_cell.push_back(0); if (erasing && paint_undo.size()) { for (Map<Point2i, CellOp>::Element *E = paint_undo.front(); E; E = E->next()) { @@ -1293,7 +1422,20 @@ bool TileMapEditor::forward_gui_input(const Ref<InputEvent> &p_event) { Vector<int> tmp_cell; tmp_cell.push_back(0); - _select(rectangle_begin, over_tile); + Point2i end_tile = over_tile; + + if (!mouse_down) { + return true; + } + + if (mm->get_shift()) { + int size = fmax(ABS(end_tile.x - rectangle_begin.x), ABS(end_tile.y - rectangle_begin.y)); + int xDirection = MAX(MIN(end_tile.x - rectangle_begin.x, 1), -1); + int yDirection = MAX(MIN(end_tile.y - rectangle_begin.y, 1), -1); + end_tile = rectangle_begin + Point2i(xDirection * size, yDirection * size); + } + + _select(rectangle_begin, end_tile); if (tool == TOOL_RECTANGLE_ERASE) { if (paint_undo.size()) { @@ -1364,6 +1506,20 @@ bool TileMapEditor::forward_gui_input(const Ref<InputEvent> &p_event) { _update_button_tool(); return true; } + if (ED_IS_SHORTCUT("tile_map_editor/line_fill", p_event)) { + tool = TOOL_LINE_PAINT; + CanvasItemEditor::get_singleton()->update_viewport(); + + _update_button_tool(); + return true; + } + if (ED_IS_SHORTCUT("tile_map_editor/rectangle_fill", p_event)) { + tool = TOOL_RECTANGLE_PAINT; + CanvasItemEditor::get_singleton()->update_viewport(); + + _update_button_tool(); + return true; + } if (ED_IS_SHORTCUT("tile_map_editor/bucket_fill", p_event)) { tool = TOOL_BUCKET; CanvasItemEditor::get_singleton()->update_viewport(); @@ -1622,7 +1778,11 @@ void TileMapEditor::forward_canvas_draw_over_viewport(Control *p_overlay) { } if (tool == TOOL_LINE_PAINT) { - if (paint_undo.empty()) { + if (!mouse_down) { + return; + } + + if (paint_undo.is_empty()) { return; } @@ -1637,6 +1797,10 @@ void TileMapEditor::forward_canvas_draw_over_viewport(Control *p_overlay) { } } else if (tool == TOOL_RECTANGLE_PAINT) { + if (!mouse_down) { + return; + } + Vector<int> ids = get_selected_tiles(); if (ids.size() == 1 && ids[0] == TileMap::INVALID_CELL) { @@ -1649,7 +1813,7 @@ void TileMapEditor::forward_canvas_draw_over_viewport(Control *p_overlay) { } } } else if (tool == TOOL_PASTING) { - if (copydata.empty()) { + if (copydata.is_empty()) { return; } @@ -1850,6 +2014,7 @@ TileMapEditor::TileMapEditor(EditorNode *p_editor) { tool = TOOL_NONE; selection_active = false; mouse_over = false; + mouse_down = false; flip_h = false; flip_v = false; @@ -1913,6 +2078,7 @@ TileMapEditor::TileMapEditor(EditorNode *p_editor) { palette->add_theme_constant_override("vseparation", 8 * EDSCALE); palette->connect("item_selected", callable_mp(this, &TileMapEditor::_palette_selected)); palette->connect("multi_selected", callable_mp(this, &TileMapEditor::_palette_multi_selected)); + palette->connect("gui_input", callable_mp(this, &TileMapEditor::_palette_input)); palette_container->add_child(palette); // Add message for when no texture is selected. @@ -1922,7 +2088,7 @@ TileMapEditor::TileMapEditor(EditorNode *p_editor) { 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); + info_message->set_anchors_and_offsets_preset(PRESET_WIDE, PRESET_MODE_KEEP_SIZE, 8 * EDSCALE); palette->add_child(info_message); // Add autotile override palette. @@ -1943,27 +2109,53 @@ TileMapEditor::TileMapEditor(EditorNode *p_editor) { toolbar->add_child(memnew(VSeparator)); // Tools. - paint_button = memnew(ToolButton); + paint_button = memnew(Button); + paint_button->set_flat(true); paint_button->set_shortcut(ED_SHORTCUT("tile_map_editor/paint_tile", TTR("Paint Tile"), KEY_P)); - paint_button->set_tooltip(TTR("Shift+LMB: Line Draw\nShift+Ctrl+LMB: Rectangle Paint")); + paint_button->set_shortcut_context(this); + paint_button->set_tooltip(TTR("RMB: Erase")); paint_button->connect("pressed", callable_mp(this, &TileMapEditor::_button_tool_select), make_binds(TOOL_NONE)); paint_button->set_toggle_mode(true); toolbar->add_child(paint_button); - bucket_fill_button = memnew(ToolButton); - bucket_fill_button->set_shortcut(ED_SHORTCUT("tile_map_editor/bucket_fill", TTR("Bucket Fill"), KEY_G)); + line_button = memnew(Button); + line_button->set_flat(true); + line_button->set_shortcut(ED_SHORTCUT("tile_map_editor/line_fill", TTR("Line Fill"), KEY_L)); + line_button->set_shortcut_context(this); + line_button->set_tooltip(TTR("RMB: Erase")); + line_button->connect("pressed", callable_mp(this, &TileMapEditor::_button_tool_select), make_binds(TOOL_LINE_PAINT)); + line_button->set_toggle_mode(true); + toolbar->add_child(line_button); + + rectangle_button = memnew(Button); + rectangle_button->set_flat(true); + rectangle_button->set_shortcut(ED_SHORTCUT("tile_map_editor/rectangle_fill", TTR("Rectangle Fill"), KEY_O)); + rectangle_button->set_shortcut_context(this); + rectangle_button->set_tooltip(TTR("Shift+LMB: Keep 1:1 proporsions\nRMB: Erase")); + rectangle_button->connect("pressed", callable_mp(this, &TileMapEditor::_button_tool_select), make_binds(TOOL_RECTANGLE_PAINT)); + rectangle_button->set_toggle_mode(true); + toolbar->add_child(rectangle_button); + + bucket_fill_button = memnew(Button); + bucket_fill_button->set_flat(true); + bucket_fill_button->set_shortcut(ED_SHORTCUT("tile_map_editor/bucket_fill", TTR("Bucket Fill"), KEY_B)); + bucket_fill_button->set_shortcut_context(this); bucket_fill_button->connect("pressed", callable_mp(this, &TileMapEditor::_button_tool_select), make_binds(TOOL_BUCKET)); bucket_fill_button->set_toggle_mode(true); toolbar->add_child(bucket_fill_button); - picker_button = memnew(ToolButton); + picker_button = memnew(Button); + picker_button->set_flat(true); picker_button->set_shortcut(ED_SHORTCUT("tile_map_editor/pick_tile", TTR("Pick Tile"), KEY_I)); + picker_button->set_shortcut_context(this); picker_button->connect("pressed", callable_mp(this, &TileMapEditor::_button_tool_select), make_binds(TOOL_PICKING)); picker_button->set_toggle_mode(true); toolbar->add_child(picker_button); - select_button = memnew(ToolButton); + select_button = memnew(Button); + select_button->set_flat(true); select_button->set_shortcut(ED_SHORTCUT("tile_map_editor/select", TTR("Select"), KEY_M)); + select_button->set_shortcut_context(this); select_button->connect("pressed", callable_mp(this, &TileMapEditor::_button_tool_select), make_binds(TOOL_SELECTING)); select_button->set_toggle_mode(true); toolbar->add_child(select_button); @@ -1982,15 +2174,16 @@ TileMapEditor::TileMapEditor(EditorNode *p_editor) { tile_info->set_modulate(Color(1, 1, 1, 0.8)); tile_info->set_mouse_filter(MOUSE_FILTER_IGNORE); tile_info->add_theme_font_override("font", EditorNode::get_singleton()->get_gui_base()->get_theme_font("main", "EditorFonts")); + tile_info->add_theme_font_size_override("font_size", EditorNode::get_singleton()->get_gui_base()->get_theme_font_size("main_size", "EditorFonts")); // The tile info is only displayed after a tile has been hovered. tile_info->hide(); CanvasItemEditor::get_singleton()->add_control_to_info_overlay(tile_info); // Menu. options = memnew(MenuButton); + options->set_shortcut_context(this); options->set_text("TileMap"); options->set_icon(EditorNode::get_singleton()->get_gui_base()->get_theme_icon("TileMap", "EditorIcons")); - options->set_process_unhandled_key_input(false); toolbar_right->add_child(options); PopupMenu *p = options->get_popup(); @@ -2001,39 +2194,49 @@ TileMapEditor::TileMapEditor(EditorNode *p_editor) { p->add_item(TTR("Fix Invalid Tiles"), OPTION_FIX_INVALID); p->connect("id_pressed", callable_mp(this, &TileMapEditor::_menu_option)); - rotate_left_button = memnew(ToolButton); + rotate_left_button = memnew(Button); + rotate_left_button->set_flat(true); rotate_left_button->set_tooltip(TTR("Rotate Left")); rotate_left_button->set_focus_mode(FOCUS_NONE); rotate_left_button->connect("pressed", callable_mp(this, &TileMapEditor::_rotate), varray(-1)); rotate_left_button->set_shortcut(ED_SHORTCUT("tile_map_editor/rotate_left", TTR("Rotate Left"), KEY_A)); + rotate_left_button->set_shortcut_context(this); tool_hb->add_child(rotate_left_button); - rotate_right_button = memnew(ToolButton); + rotate_right_button = memnew(Button); + rotate_right_button->set_flat(true); rotate_right_button->set_tooltip(TTR("Rotate Right")); rotate_right_button->set_focus_mode(FOCUS_NONE); rotate_right_button->connect("pressed", callable_mp(this, &TileMapEditor::_rotate), varray(1)); rotate_right_button->set_shortcut(ED_SHORTCUT("tile_map_editor/rotate_right", TTR("Rotate Right"), KEY_S)); + rotate_right_button->set_shortcut_context(this); tool_hb->add_child(rotate_right_button); - flip_horizontal_button = memnew(ToolButton); + flip_horizontal_button = memnew(Button); + flip_horizontal_button->set_flat(true); flip_horizontal_button->set_tooltip(TTR("Flip Horizontally")); flip_horizontal_button->set_focus_mode(FOCUS_NONE); flip_horizontal_button->connect("pressed", callable_mp(this, &TileMapEditor::_flip_horizontal)); flip_horizontal_button->set_shortcut(ED_SHORTCUT("tile_map_editor/flip_horizontal", TTR("Flip Horizontally"), KEY_X)); + flip_horizontal_button->set_shortcut_context(this); tool_hb->add_child(flip_horizontal_button); - flip_vertical_button = memnew(ToolButton); + flip_vertical_button = memnew(Button); + flip_vertical_button->set_flat(true); flip_vertical_button->set_tooltip(TTR("Flip Vertically")); flip_vertical_button->set_focus_mode(FOCUS_NONE); flip_vertical_button->connect("pressed", callable_mp(this, &TileMapEditor::_flip_vertical)); flip_vertical_button->set_shortcut(ED_SHORTCUT("tile_map_editor/flip_vertical", TTR("Flip Vertically"), KEY_Z)); + flip_vertical_button->set_shortcut_context(this); tool_hb->add_child(flip_vertical_button); - clear_transform_button = memnew(ToolButton); + clear_transform_button = memnew(Button); + clear_transform_button->set_flat(true); clear_transform_button->set_tooltip(TTR("Clear Transform")); clear_transform_button->set_focus_mode(FOCUS_NONE); clear_transform_button->connect("pressed", callable_mp(this, &TileMapEditor::_clear_transform)); clear_transform_button->set_shortcut(ED_SHORTCUT("tile_map_editor/clear_transform", TTR("Clear Transform"), KEY_W)); + clear_transform_button->set_shortcut_context(this); tool_hb->add_child(clear_transform_button); clear_transform_button->set_disabled(true); diff --git a/editor/plugins/tile_map_editor_plugin.h b/editor/plugins/tile_map_editor_plugin.h index 5f82d7bfb8..421a3b3f68 100644 --- a/editor/plugins/tile_map_editor_plugin.h +++ b/editor/plugins/tile_map_editor_plugin.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -38,13 +38,11 @@ #include "scene/gui/label.h" #include "scene/gui/line_edit.h" #include "scene/gui/menu_button.h" -#include "scene/gui/tool_button.h" class TileMapEditor : public VBoxContainer { GDCLASS(TileMapEditor, VBoxContainer); enum Tool { - TOOL_NONE, TOOL_PAINTING, TOOL_ERASING, @@ -59,7 +57,6 @@ class TileMapEditor : public VBoxContainer { }; enum Options { - OPTION_COPY, OPTION_ERASE_SELECTION, OPTION_FIX_INVALID, @@ -88,16 +85,18 @@ class TileMapEditor : public VBoxContainer { Label *tile_info; MenuButton *options; - ToolButton *paint_button; - ToolButton *bucket_fill_button; - ToolButton *picker_button; - ToolButton *select_button; + Button *paint_button; + Button *line_button; + Button *rectangle_button; + Button *bucket_fill_button; + Button *picker_button; + Button *select_button; - ToolButton *flip_horizontal_button; - ToolButton *flip_vertical_button; - ToolButton *rotate_left_button; - ToolButton *rotate_right_button; - ToolButton *clear_transform_button; + Button *flip_horizontal_button; + Button *flip_vertical_button; + Button *rotate_left_button; + Button *rotate_right_button; + Button *clear_transform_button; CheckBox *manual_button; CheckBox *priority_button; @@ -107,6 +106,7 @@ class TileMapEditor : public VBoxContainer { bool selection_active; bool mouse_over; + bool mouse_down; bool flip_h; bool flip_v; @@ -117,6 +117,7 @@ class TileMapEditor : public VBoxContainer { Rect2i rectangle; Point2i over_tile; + bool refocus_over_tile = false; bool *bucket_cache_visited; Rect2i bucket_cache_rect; @@ -130,8 +131,6 @@ class TileMapEditor : public VBoxContainer { bool yf = false; bool tr = false; Vector2 ac; - - CellOp() {} }; Map<Point2i, CellOp> paint_undo; @@ -143,8 +142,6 @@ class TileMapEditor : public VBoxContainer { bool flip_v = false; bool transpose = false; Point2i autotile_coord; - - TileData() {} }; List<TileData> copydata; @@ -182,6 +179,7 @@ class TileMapEditor : public VBoxContainer { void _menu_option(int p_option); void _palette_selected(int index); void _palette_multi_selected(int index, bool selected); + void _palette_input(const Ref<InputEvent> &p_event); Dictionary _create_cell_dictionary(int tile, bool flip_x, bool flip_y, bool transpose, Vector2 autotile_coord); void _start_undo(const String &p_action); @@ -228,14 +226,14 @@ protected: void _notification(int p_what); public: - virtual bool forward_canvas_gui_input(const Ref<InputEvent> &p_event) { return tile_map_editor->forward_gui_input(p_event); } - virtual void forward_canvas_draw_over_viewport(Control *p_overlay) { tile_map_editor->forward_canvas_draw_over_viewport(p_overlay); } - - virtual String get_name() const { return "TileMap"; } - bool has_main_screen() const { return false; } - virtual void edit(Object *p_object); - virtual bool handles(Object *p_object) const; - virtual void make_visible(bool p_visible); + virtual bool forward_canvas_gui_input(const Ref<InputEvent> &p_event) override { return tile_map_editor->forward_gui_input(p_event); } + virtual void forward_canvas_draw_over_viewport(Control *p_overlay) override { tile_map_editor->forward_canvas_draw_over_viewport(p_overlay); } + + virtual String get_name() const override { return "TileMap"; } + bool has_main_screen() const override { return false; } + virtual void edit(Object *p_object) override; + virtual bool handles(Object *p_object) const override; + virtual void make_visible(bool p_visible) override; TileMapEditorPlugin(EditorNode *p_node); ~TileMapEditorPlugin(); diff --git a/editor/plugins/tile_set_editor_plugin.cpp b/editor/plugins/tile_set_editor_plugin.cpp index 644facd5bd..c628fe8367 100644 --- a/editor/plugins/tile_set_editor_plugin.cpp +++ b/editor/plugins/tile_set_editor_plugin.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -39,7 +39,6 @@ void TileSetEditor::edit(const Ref<TileSet> &p_tileset) { tileset = p_tileset; - tileset->add_change_receptor(this); texture_list->clear(); texture_map.clear(); @@ -60,7 +59,6 @@ void TileSetEditor::_import_node(Node *p_node, Ref<TileSet> p_library) { Sprite2D *mi = Object::cast_to<Sprite2D>(child); Ref<Texture2D> texture = mi->get_texture(); - Ref<Texture2D> normal_map = mi->get_normal_map(); Ref<ShaderMaterial> material = mi->get_material(); if (texture.is_null()) { @@ -75,7 +73,6 @@ void TileSetEditor::_import_node(Node *p_node, Ref<TileSet> p_library) { } p_library->tile_set_texture(id, texture); - p_library->tile_set_normal_map(id, normal_map); p_library->tile_set_material(id, material); p_library->tile_set_modulate(id, mi->get_modulate()); @@ -281,6 +278,8 @@ void TileSetEditor::_notification(int p_what) { case NOTIFICATION_READY: { add_theme_constant_override("autohide", 1); // Fixes the dragger always showing up. } break; + case NOTIFICATION_TRANSLATION_CHANGED: + case NOTIFICATION_LAYOUT_DIRECTION_CHANGED: case NOTIFICATION_ENTER_TREE: case NOTIFICATION_THEME_CHANGED: { tileset_toolbar_buttons[TOOL_TILESET_ADD_TEXTURE]->set_icon(get_theme_icon("ToolAddNode", "EditorIcons")); @@ -298,8 +297,13 @@ void TileSetEditor::_notification(int p_what) { tools[BITMASK_CLEAR]->set_icon(get_theme_icon("Clear", "EditorIcons")); tools[SHAPE_NEW_POLYGON]->set_icon(get_theme_icon("CollisionPolygon2D", "EditorIcons")); tools[SHAPE_NEW_RECTANGLE]->set_icon(get_theme_icon("CollisionShape2D", "EditorIcons")); - tools[SELECT_PREVIOUS]->set_icon(get_theme_icon("ArrowLeft", "EditorIcons")); - tools[SELECT_NEXT]->set_icon(get_theme_icon("ArrowRight", "EditorIcons")); + if (is_layout_rtl()) { + tools[SELECT_PREVIOUS]->set_icon(get_theme_icon("ArrowLeft", "EditorIcons")); + tools[SELECT_NEXT]->set_icon(get_theme_icon("ArrowRight", "EditorIcons")); + } else { + tools[SELECT_PREVIOUS]->set_icon(get_theme_icon("ArrowRight", "EditorIcons")); + tools[SELECT_NEXT]->set_icon(get_theme_icon("ArrowLeft", "EditorIcons")); + } tools[SHAPE_DELETE]->set_icon(get_theme_icon("Remove", "EditorIcons")); tools[SHAPE_KEEP_INSIDE_TILE]->set_icon(get_theme_icon("Snap", "EditorIcons")); tools[TOOL_GRID_SNAP]->set_icon(get_theme_icon("SnapGrid", "EditorIcons")); @@ -341,12 +345,14 @@ TileSetEditor::TileSetEditor(EditorNode *p_editor) { HBoxContainer *tileset_toolbar_container = memnew(HBoxContainer); left_container->add_child(tileset_toolbar_container); - tileset_toolbar_buttons[TOOL_TILESET_ADD_TEXTURE] = memnew(ToolButton); + tileset_toolbar_buttons[TOOL_TILESET_ADD_TEXTURE] = memnew(Button); + tileset_toolbar_buttons[TOOL_TILESET_ADD_TEXTURE]->set_flat(true); tileset_toolbar_buttons[TOOL_TILESET_ADD_TEXTURE]->connect("pressed", callable_mp(this, &TileSetEditor::_on_tileset_toolbar_button_pressed), varray(TOOL_TILESET_ADD_TEXTURE)); tileset_toolbar_container->add_child(tileset_toolbar_buttons[TOOL_TILESET_ADD_TEXTURE]); tileset_toolbar_buttons[TOOL_TILESET_ADD_TEXTURE]->set_tooltip(TTR("Add Texture(s) to TileSet.")); - tileset_toolbar_buttons[TOOL_TILESET_REMOVE_TEXTURE] = memnew(ToolButton); + tileset_toolbar_buttons[TOOL_TILESET_REMOVE_TEXTURE] = memnew(Button); + tileset_toolbar_buttons[TOOL_TILESET_REMOVE_TEXTURE]->set_flat(true); tileset_toolbar_buttons[TOOL_TILESET_REMOVE_TEXTURE]->connect("pressed", callable_mp(this, &TileSetEditor::_on_tileset_toolbar_button_pressed), varray(TOOL_TILESET_REMOVE_TEXTURE)); tileset_toolbar_container->add_child(tileset_toolbar_buttons[TOOL_TILESET_REMOVE_TEXTURE]); tileset_toolbar_buttons[TOOL_TILESET_REMOVE_TEXTURE]->set_tooltip(TTR("Remove selected Texture from TileSet.")); @@ -402,16 +408,20 @@ TileSetEditor::TileSetEditor(EditorNode *p_editor) { tool_hb->add_child(spacer); tool_hb->move_child(spacer, WORKSPACE_CREATE_SINGLE); - tools[SELECT_NEXT] = memnew(ToolButton); + tools[SELECT_NEXT] = memnew(Button); tool_hb->add_child(tools[SELECT_NEXT]); tool_hb->move_child(tools[SELECT_NEXT], WORKSPACE_CREATE_SINGLE); + tools[SELECT_NEXT]->set_flat(true); tools[SELECT_NEXT]->set_shortcut(ED_SHORTCUT("tileset_editor/next_shape", TTR("Next Coordinate"), KEY_PAGEDOWN)); + tools[SELECT_NEXT]->set_shortcut_context(this); tools[SELECT_NEXT]->connect("pressed", callable_mp(this, &TileSetEditor::_on_tool_clicked), varray(SELECT_NEXT)); tools[SELECT_NEXT]->set_tooltip(TTR("Select the next shape, subtile, or Tile.")); - tools[SELECT_PREVIOUS] = memnew(ToolButton); + tools[SELECT_PREVIOUS] = memnew(Button); tool_hb->add_child(tools[SELECT_PREVIOUS]); tool_hb->move_child(tools[SELECT_PREVIOUS], WORKSPACE_CREATE_SINGLE); + tools[SELECT_PREVIOUS]->set_flat(true); tools[SELECT_PREVIOUS]->set_shortcut(ED_SHORTCUT("tileset_editor/previous_shape", TTR("Previous Coordinate"), KEY_PAGEUP)); + tools[SELECT_PREVIOUS]->set_shortcut_context(this); tools[SELECT_PREVIOUS]->set_tooltip(TTR("Select the previous shape, subtile, or Tile.")); tools[SELECT_PREVIOUS]->connect("pressed", callable_mp(this, &TileSetEditor::_on_tool_clicked), varray(SELECT_PREVIOUS)); @@ -458,6 +468,16 @@ TileSetEditor::TileSetEditor(EditorNode *p_editor) { tool_editmode[EDITMODE_ICON]->set_shortcut(ED_SHORTCUT("tileset_editor/editmode_icon", TTR("Icon Mode"), KEY_7)); tool_editmode[EDITMODE_Z_INDEX]->set_shortcut(ED_SHORTCUT("tileset_editor/editmode_z_index", TTR("Z Index Mode"), KEY_8)); + tool_editmode[EDITMODE_REGION]->set_shortcut_context(this); + tool_editmode[EDITMODE_REGION]->set_shortcut_context(this); + tool_editmode[EDITMODE_COLLISION]->set_shortcut_context(this); + tool_editmode[EDITMODE_OCCLUSION]->set_shortcut_context(this); + tool_editmode[EDITMODE_NAVIGATION]->set_shortcut_context(this); + tool_editmode[EDITMODE_BITMASK]->set_shortcut_context(this); + tool_editmode[EDITMODE_PRIORITY]->set_shortcut_context(this); + tool_editmode[EDITMODE_ICON]->set_shortcut_context(this); + tool_editmode[EDITMODE_Z_INDEX]->set_shortcut_context(this); + main_vb->add_child(tool_hb); separator_editmode = memnew(HSeparator); main_vb->add_child(separator_editmode); @@ -465,8 +485,9 @@ TileSetEditor::TileSetEditor(EditorNode *p_editor) { toolbar = memnew(HBoxContainer); Ref<ButtonGroup> tg(memnew(ButtonGroup)); - tools[TOOL_SELECT] = memnew(ToolButton); + tools[TOOL_SELECT] = memnew(Button); toolbar->add_child(tools[TOOL_SELECT]); + tools[TOOL_SELECT]->set_flat(true); tools[TOOL_SELECT]->set_toggle_mode(true); tools[TOOL_SELECT]->set_button_group(tg); tools[TOOL_SELECT]->set_pressed(true); @@ -474,41 +495,53 @@ TileSetEditor::TileSetEditor(EditorNode *p_editor) { separator_bitmask = memnew(VSeparator); toolbar->add_child(separator_bitmask); - tools[BITMASK_COPY] = memnew(ToolButton); + tools[BITMASK_COPY] = memnew(Button); + tools[BITMASK_COPY]->set_flat(true); tools[BITMASK_COPY]->set_tooltip(TTR("Copy bitmask.")); tools[BITMASK_COPY]->connect("pressed", callable_mp(this, &TileSetEditor::_on_tool_clicked), varray(BITMASK_COPY)); toolbar->add_child(tools[BITMASK_COPY]); - tools[BITMASK_PASTE] = memnew(ToolButton); + tools[BITMASK_PASTE] = memnew(Button); + tools[BITMASK_PASTE]->set_flat(true); tools[BITMASK_PASTE]->set_tooltip(TTR("Paste bitmask.")); tools[BITMASK_PASTE]->connect("pressed", callable_mp(this, &TileSetEditor::_on_tool_clicked), varray(BITMASK_PASTE)); toolbar->add_child(tools[BITMASK_PASTE]); - tools[BITMASK_CLEAR] = memnew(ToolButton); + tools[BITMASK_CLEAR] = memnew(Button); + tools[BITMASK_CLEAR]->set_flat(true); tools[BITMASK_CLEAR]->set_tooltip(TTR("Erase bitmask.")); tools[BITMASK_CLEAR]->connect("pressed", callable_mp(this, &TileSetEditor::_on_tool_clicked), varray(BITMASK_CLEAR)); toolbar->add_child(tools[BITMASK_CLEAR]); - tools[SHAPE_NEW_RECTANGLE] = memnew(ToolButton); + tools[SHAPE_NEW_RECTANGLE] = memnew(Button); toolbar->add_child(tools[SHAPE_NEW_RECTANGLE]); + tools[SHAPE_NEW_RECTANGLE]->set_flat(true); tools[SHAPE_NEW_RECTANGLE]->set_toggle_mode(true); tools[SHAPE_NEW_RECTANGLE]->set_button_group(tg); tools[SHAPE_NEW_RECTANGLE]->set_tooltip(TTR("Create a new rectangle.")); + tools[SHAPE_NEW_RECTANGLE]->connect("pressed", callable_mp(this, &TileSetEditor::_on_tool_clicked), varray(SHAPE_NEW_RECTANGLE)); + tools[SHAPE_NEW_RECTANGLE]->set_shortcut(ED_SHORTCUT("tileset_editor/shape_new_rectangle", TTR("New Rectangle"), KEY_MASK_SHIFT | KEY_R)); - tools[SHAPE_NEW_POLYGON] = memnew(ToolButton); + tools[SHAPE_NEW_POLYGON] = memnew(Button); toolbar->add_child(tools[SHAPE_NEW_POLYGON]); + tools[SHAPE_NEW_POLYGON]->set_flat(true); tools[SHAPE_NEW_POLYGON]->set_toggle_mode(true); tools[SHAPE_NEW_POLYGON]->set_button_group(tg); tools[SHAPE_NEW_POLYGON]->set_tooltip(TTR("Create a new polygon.")); + tools[SHAPE_NEW_POLYGON]->connect("pressed", callable_mp(this, &TileSetEditor::_on_tool_clicked), varray(SHAPE_NEW_POLYGON)); + tools[SHAPE_NEW_POLYGON]->set_shortcut(ED_SHORTCUT("tileset_editor/shape_new_polygon", TTR("New Polygon"), KEY_MASK_SHIFT | KEY_P)); separator_shape_toggle = memnew(VSeparator); toolbar->add_child(separator_shape_toggle); - tools[SHAPE_TOGGLE_TYPE] = memnew(ToolButton); + tools[SHAPE_TOGGLE_TYPE] = memnew(Button); + tools[SHAPE_TOGGLE_TYPE]->set_flat(true); tools[SHAPE_TOGGLE_TYPE]->connect("pressed", callable_mp(this, &TileSetEditor::_on_tool_clicked), varray(SHAPE_TOGGLE_TYPE)); toolbar->add_child(tools[SHAPE_TOGGLE_TYPE]); separator_delete = memnew(VSeparator); toolbar->add_child(separator_delete); - tools[SHAPE_DELETE] = memnew(ToolButton); + tools[SHAPE_DELETE] = memnew(Button); + tools[SHAPE_DELETE]->set_flat(true); tools[SHAPE_DELETE]->connect("pressed", callable_mp(this, &TileSetEditor::_on_tool_clicked), varray(SHAPE_DELETE)); + tools[SHAPE_DELETE]->set_shortcut(ED_SHORTCUT("tileset_editor/shape_delete", TTR("Delete Selected Shape"), KEY_MASK_SHIFT | KEY_BACKSPACE)); toolbar->add_child(tools[SHAPE_DELETE]); spin_priority = memnew(SpinBox); @@ -531,12 +564,14 @@ TileSetEditor::TileSetEditor(EditorNode *p_editor) { separator_grid = memnew(VSeparator); toolbar->add_child(separator_grid); - tools[SHAPE_KEEP_INSIDE_TILE] = memnew(ToolButton); + tools[SHAPE_KEEP_INSIDE_TILE] = memnew(Button); + tools[SHAPE_KEEP_INSIDE_TILE]->set_flat(true); tools[SHAPE_KEEP_INSIDE_TILE]->set_toggle_mode(true); tools[SHAPE_KEEP_INSIDE_TILE]->set_pressed(true); tools[SHAPE_KEEP_INSIDE_TILE]->set_tooltip(TTR("Keep polygon inside region Rect.")); toolbar->add_child(tools[SHAPE_KEEP_INSIDE_TILE]); - tools[TOOL_GRID_SNAP] = memnew(ToolButton); + tools[TOOL_GRID_SNAP] = memnew(Button); + tools[TOOL_GRID_SNAP]->set_flat(true); tools[TOOL_GRID_SNAP]->set_toggle_mode(true); tools[TOOL_GRID_SNAP]->set_tooltip(TTR("Enable snap and show grid (configurable via the Inspector).")); tools[TOOL_GRID_SNAP]->connect("toggled", callable_mp(this, &TileSetEditor::_on_grid_snap_toggled)); @@ -546,20 +581,24 @@ TileSetEditor::TileSetEditor(EditorNode *p_editor) { separator->set_h_size_flags(SIZE_EXPAND_FILL); toolbar->add_child(separator); - tools[ZOOM_OUT] = memnew(ToolButton); + tools[ZOOM_OUT] = memnew(Button); + tools[ZOOM_OUT]->set_flat(true); tools[ZOOM_OUT]->connect("pressed", callable_mp(this, &TileSetEditor::_zoom_out)); toolbar->add_child(tools[ZOOM_OUT]); tools[ZOOM_OUT]->set_tooltip(TTR("Zoom Out")); - tools[ZOOM_1] = memnew(ToolButton); + tools[ZOOM_1] = memnew(Button); + tools[ZOOM_1]->set_flat(true); tools[ZOOM_1]->connect("pressed", callable_mp(this, &TileSetEditor::_zoom_reset)); toolbar->add_child(tools[ZOOM_1]); tools[ZOOM_1]->set_tooltip(TTR("Zoom Reset")); - tools[ZOOM_IN] = memnew(ToolButton); + tools[ZOOM_IN] = memnew(Button); + tools[ZOOM_IN]->set_flat(true); tools[ZOOM_IN]->connect("pressed", callable_mp(this, &TileSetEditor::_zoom_in)); toolbar->add_child(tools[ZOOM_IN]); tools[ZOOM_IN]->set_tooltip(TTR("Zoom In")); - tools[VISIBLE_INFO] = memnew(ToolButton); + tools[VISIBLE_INFO] = memnew(Button); + tools[VISIBLE_INFO]->set_flat(true); tools[VISIBLE_INFO]->set_toggle_mode(true); tools[VISIBLE_INFO]->set_tooltip(TTR("Display Tile Names (Hold Alt Key)")); toolbar->add_child(tools[VISIBLE_INFO]); @@ -569,6 +608,7 @@ TileSetEditor::TileSetEditor(EditorNode *p_editor) { scroll = memnew(ScrollContainer); main_vb->add_child(scroll); scroll->set_v_size_flags(SIZE_EXPAND_FILL); + scroll->connect("gui_input", callable_mp(this, &TileSetEditor::_on_scroll_container_input)); scroll->set_clip_contents(true); empty_message = memnew(Label); @@ -643,7 +683,7 @@ void TileSetEditor::_on_tileset_toolbar_button_pressed(int p_index) { option = p_index; switch (option) { case TOOL_TILESET_ADD_TEXTURE: { - texture_dialog->popup_centered_ratio(); + texture_dialog->popup_file_dialog(); } break; case TOOL_TILESET_REMOVE_TEXTURE: { if (get_current_texture().is_valid()) { @@ -695,7 +735,7 @@ void TileSetEditor::_on_tileset_toolbar_confirm() { List<int> ids; tileset->get_tile_list(&ids); - undo_redo->create_action(TTR(option == TOOL_TILESET_MERGE_SCENE ? "Merge Tileset from Scene" : "Create Tileset from Scene")); + undo_redo->create_action(option == TOOL_TILESET_MERGE_SCENE ? TTR("Merge Tileset from Scene") : TTR("Create Tileset from Scene")); undo_redo->add_do_method(this, "_undo_redo_import_scene", scene, option == TOOL_TILESET_MERGE_SCENE); undo_redo->add_undo_method(tileset.ptr(), "clear"); for (List<int>::Element *E = ids.front(); E; E = E->next()) { @@ -1151,11 +1191,12 @@ void TileSetEditor::_on_workspace_overlay_draw() { } String tile_id_name = String::num(t_id, 0) + ": " + tileset->tile_get_name(t_id); Ref<Font> font = get_theme_font("font", "Label"); - region.set_size(font->get_string_size(tile_id_name)); + int font_size = get_theme_font_size("font_size", "Label"); + region.set_size(font->get_string_size(tile_id_name, font_size)); workspace_overlay->draw_rect(region, c); region.position.y += region.size.y - 2; c = Color(0.1, 0.1, 0.1); - workspace_overlay->draw_string(font, region.position, tile_id_name, c); + workspace_overlay->draw_string(font, region.position, tile_id_name, HALIGN_LEFT, -1, font_size, c); } delete tiles; } @@ -1198,6 +1239,27 @@ bool TileSetEditor::is_within_grabbing_distance_of_first_point(const Vector2 &p_ return distance < p_grab_threshold; } +void TileSetEditor::_on_scroll_container_input(const Ref<InputEvent> &p_event) { + const Ref<InputEventMouseButton> mb = p_event; + + if (mb.is_valid()) { + // Zoom in/out using Ctrl + mouse wheel. This is done on the ScrollContainer + // to allow performing this action anywhere, even if the cursor isn't + // hovering the texture in the workspace. + if (mb->get_button_index() == BUTTON_WHEEL_UP && mb->is_pressed() && mb->get_control()) { + print_line("zooming in"); + _zoom_in(); + // Don't scroll up after zooming in. + accept_event(); + } else if (mb->get_button_index() == BUTTON_WHEEL_DOWN && mb->is_pressed() && mb->get_control()) { + print_line("zooming out"); + _zoom_out(); + // Don't scroll down after zooming out. + accept_event(); + } + } +} + void TileSetEditor::_on_workspace_input(const Ref<InputEvent> &p_ie) { if (tileset.is_null() || !get_current_texture().is_valid()) { return; @@ -1214,8 +1276,8 @@ void TileSetEditor::_on_workspace_input(const Ref<InputEvent> &p_ie) { } current_tile_region.position += WORKSPACE_MARGIN; - Ref<InputEventMouseButton> mb = p_ie; - Ref<InputEventMouseMotion> mm = p_ie; + const Ref<InputEventMouseButton> mb = p_ie; + const Ref<InputEventMouseMotion> mm = p_ie; if (mb.is_valid()) { if (mb->is_pressed() && mb->get_button_index() == BUTTON_LEFT && !creating_shape) { @@ -1239,13 +1301,6 @@ void TileSetEditor::_on_workspace_input(const Ref<InputEvent> &p_ie) { delete tiles; } } - - // Mouse Wheel Event - if (mb->get_button_index() == BUTTON_WHEEL_UP && mb->is_pressed() && mb->get_control()) { - _zoom_in(); - } else if (mb->get_button_index() == BUTTON_WHEEL_DOWN && mb->is_pressed() && mb->get_control()) { - _zoom_out(); - } } // Drag Middle Mouse if (mm.is_valid()) { @@ -1803,7 +1858,7 @@ void TileSetEditor::_on_tool_clicked(int p_tool) { _update_toggle_shape_button(); workspace->update(); workspace_container->update(); - helper->_change_notify(""); + helper->notify_property_list_changed(); } } else if (p_tool == SELECT_NEXT) { _select_next_shape(); @@ -1893,7 +1948,7 @@ void TileSetEditor::_on_tool_clicked(int p_tool) { } } } - } else if (p_tool == TOOL_SELECT) { + } else if (p_tool == TOOL_SELECT || p_tool == SHAPE_NEW_POLYGON || p_tool == SHAPE_NEW_RECTANGLE) { if (creating_shape) { // Cancel Creation creating_shape = false; @@ -1960,7 +2015,7 @@ void TileSetEditor::_set_edited_shape_points(const Vector<Vector2> &points) { if (convex.is_valid()) { undo_redo->add_do_method(convex.ptr(), "set_points", points); undo_redo->add_undo_method(convex.ptr(), "set_points", _get_edited_shape_points()); - } else if (concave.is_valid()) { + } else if (concave.is_valid() && points.size() > 1) { PackedVector2Array segments; for (int i = 0; i < points.size() - 1; i++) { segments.push_back(points[i]); @@ -2117,7 +2172,7 @@ Array TileSetEditor::_get_tiles_in_current_texture(bool sorted) { } } if (sorted) { - a.sort_custom(this, "_sort_tiles"); + a.sort_custom(callable_mp(this, &TileSetEditor::_sort_tiles)); } return a; } @@ -2231,7 +2286,7 @@ void TileSetEditor::_select_next_shape() { } workspace->update(); workspace_container->update(); - helper->_change_notify(""); + helper->notify_property_list_changed(); } } @@ -2293,7 +2348,7 @@ void TileSetEditor::_select_previous_shape() { } workspace->update(); workspace_container->update(); - helper->_change_notify(""); + helper->notify_property_list_changed(); } } @@ -2303,8 +2358,8 @@ void TileSetEditor::_set_edited_collision_shape(const Ref<Shape2D> &p_shape) { } void TileSetEditor::_set_snap_step(Vector2 p_val) { - snap_step.x = CLAMP(p_val.x, 0, 256); - snap_step.y = CLAMP(p_val.y, 0, 256); + snap_step.x = CLAMP(p_val.x, 1, 256); + snap_step.y = CLAMP(p_val.y, 1, 256); workspace->update(); } @@ -2333,7 +2388,6 @@ void TileSetEditor::_select_edited_shape_coord() { void TileSetEditor::_undo_tile_removal(int p_id) { undo_redo->add_undo_method(tileset.ptr(), "create_tile", p_id); undo_redo->add_undo_method(tileset.ptr(), "tile_set_name", p_id, tileset->tile_get_name(p_id)); - undo_redo->add_undo_method(tileset.ptr(), "tile_set_normal_map", p_id, tileset->tile_get_normal_map(p_id)); undo_redo->add_undo_method(tileset.ptr(), "tile_set_texture_offset", p_id, tileset->tile_get_texture_offset(p_id)); undo_redo->add_undo_method(tileset.ptr(), "tile_set_material", p_id, tileset->tile_get_material(p_id)); undo_redo->add_undo_method(tileset.ptr(), "tile_set_modulate", p_id, tileset->tile_get_modulate(p_id)); @@ -2652,7 +2706,7 @@ void TileSetEditor::draw_polygon_shapes() { workspace->draw_polygon(polygon, colors); if (coord == edited_shape_coord || tileset->tile_get_tile_mode(get_current_tile()) == TileSet::SINGLE_TILE) { - if (!creating_shape) { + if (!creating_shape && polygon.size() > 1) { for (int j = 0; j < polygon.size() - 1; j++) { workspace->draw_line(polygon[j], polygon[j + 1], c_border, 1); } @@ -2689,13 +2743,11 @@ void TileSetEditor::draw_polygon_shapes() { } workspace->draw_polygon(polygon, colors); - if (!creating_shape) { - if (polygon.size() > 1) { - for (int j = 0; j < polygon.size() - 1; j++) { - workspace->draw_line(polygon[j], polygon[j + 1], c_border, 1); - } - workspace->draw_line(polygon[polygon.size() - 1], polygon[0], c_border, 1); + if (!creating_shape && polygon.size() > 1) { + for (int j = 0; j < polygon.size() - 1; j++) { + workspace->draw_line(polygon[j], polygon[j + 1], c_border, 1); } + workspace->draw_line(polygon[polygon.size() - 1], polygon[0], c_border, 1); } if (shape == edited_occlusion_shape) { draw_handles = true; @@ -2739,7 +2791,7 @@ void TileSetEditor::draw_polygon_shapes() { workspace->draw_polygon(polygon, colors); if (coord == edited_shape_coord) { - if (!creating_shape) { + if (!creating_shape && polygon.size() > 1) { for (int j = 0; j < polygon.size() - 1; j++) { workspace->draw_line(polygon[j], polygon[j + 1], c_border, 1); } @@ -2779,7 +2831,7 @@ void TileSetEditor::draw_polygon_shapes() { } workspace->draw_polygon(polygon, colors); - if (!creating_shape) { + if (!creating_shape && polygon.size() > 1) { for (int j = 0; j < polygon.size() - 1; j++) { workspace->draw_line(polygon[j], polygon[j + 1], c_border, 1); } @@ -2828,7 +2880,7 @@ void TileSetEditor::draw_polygon_shapes() { workspace->draw_polygon(polygon, colors); if (coord == edited_shape_coord) { - if (!creating_shape) { + if (!creating_shape && polygon.size() > 1) { for (int j = 0; j < polygon.size() - 1; j++) { workspace->draw_line(polygon[j], polygon[j + 1], c_border, 1); } @@ -2846,7 +2898,7 @@ void TileSetEditor::draw_polygon_shapes() { } } - if (creating_shape) { + if (creating_shape && current_shape.size() > 1) { for (int j = 0; j < current_shape.size() - 1; j++) { workspace->draw_line(current_shape[j], current_shape[j + 1], Color(0, 1, 1), 1); } @@ -2959,7 +3011,7 @@ void TileSetEditor::close_shape(const Vector2 &shape_anchor) { undo_redo->add_undo_method(this, "_select_edited_shape_coord"); undo_redo->commit_action(); } - tileset->_change_notify(""); + tileset->notify_property_list_changed(); } void TileSetEditor::select_coord(const Vector2 &coord) { @@ -3062,7 +3114,7 @@ void TileSetEditor::select_coord(const Vector2 &coord) { } workspace->update(); workspace_container->update(); - helper->_change_notify(""); + helper->notify_property_list_changed(); } Vector2 TileSetEditor::snap_point(const Vector2 &point) { @@ -3076,6 +3128,7 @@ Vector2 TileSetEditor::snap_point(const Vector2 &point) { anchor += tileset->tile_get_region(get_current_tile()).position; anchor += WORKSPACE_MARGIN; Rect2 region(anchor, tile_size); + Rect2 tile_region(tileset->tile_get_region(get_current_tile()).position + WORKSPACE_MARGIN, tileset->tile_get_region(get_current_tile()).size); if (tileset->tile_get_tile_mode(get_current_tile()) == TileSet::SINGLE_TILE) { region.position = tileset->tile_get_region(get_current_tile()).position + WORKSPACE_MARGIN; region.size = tileset->tile_get_region(get_current_tile()).size; @@ -3085,6 +3138,7 @@ Vector2 TileSetEditor::snap_point(const Vector2 &point) { p.x = Math::snap_scalar_separation(snap_offset.x, snap_step.x, p.x, snap_separation.x); p.y = Math::snap_scalar_separation(snap_offset.y, snap_step.y, p.y, snap_separation.y); } + if (tools[SHAPE_KEEP_INSIDE_TILE]->is_pressed()) { if (p.x < region.position.x) { p.x = region.position.x; @@ -3099,6 +3153,20 @@ Vector2 TileSetEditor::snap_point(const Vector2 &point) { p.y = region.position.y + region.size.y; } } + + if (p.x < tile_region.position.x) { + p.x = tile_region.position.x; + } + if (p.y < tile_region.position.y) { + p.y = tile_region.position.y; + } + if (p.x > (tile_region.position.x + tile_region.size.x)) { + p.x = (tile_region.position.x + tile_region.size.x); + } + if (p.y > (tile_region.position.y + tile_region.size.y)) { + p.y = (tile_region.position.y + tile_region.size.y); + } + return p; } @@ -3156,7 +3224,7 @@ void TileSetEditor::update_texture_list() { workspace_overlay->update(); } update_texture_list_icon(); - helper->_change_notify(""); + helper->notify_property_list_changed(); } void TileSetEditor::update_texture_list_icon() { @@ -3320,7 +3388,7 @@ int TileSetEditor::get_current_tile() const { void TileSetEditor::set_current_tile(int p_id) { if (current_tile != p_id) { current_tile = p_id; - helper->_change_notify(""); + helper->notify_property_list_changed(); select_coord(Vector2(0, 0)); update_workspace_tile_mode(); if (p_id == -1) { @@ -3345,7 +3413,7 @@ void TilesetEditorContext::set_tileset(const Ref<TileSet> &p_tileset) { void TilesetEditorContext::set_snap_options_visible(bool p_visible) { snap_options_visible = p_visible; - _change_notify(""); + notify_property_list_changed(); } bool TilesetEditorContext::_set(const StringName &p_name, const Variant &p_value) { @@ -3381,7 +3449,7 @@ bool TilesetEditorContext::_set(const StringName &p_name, const Variant &p_value tileset->set(String::num(tileset_editor->get_current_tile(), 0) + "/" + name2, p_value, &v); } if (v) { - tileset->_change_notify(""); + tileset->notify_property_list_changed(); tileset_editor->workspace->update(); tileset_editor->workspace_overlay->update(); } @@ -3492,7 +3560,6 @@ void TilesetEditorContext::_get_property_list(List<PropertyInfo> *p_list) const int id = tileset_editor->get_current_tile(); p_list->push_back(PropertyInfo(Variant::NIL, "Selected Tile", PROPERTY_HINT_NONE, "tile_", PROPERTY_USAGE_GROUP)); p_list->push_back(PropertyInfo(Variant::STRING, "tile_name")); - p_list->push_back(PropertyInfo(Variant::OBJECT, "tile_normal_map", PROPERTY_HINT_RESOURCE_TYPE, "Texture2D")); p_list->push_back(PropertyInfo(Variant::VECTOR2, "tile_tex_offset")); p_list->push_back(PropertyInfo(Variant::OBJECT, "tile_material", PROPERTY_HINT_RESOURCE_TYPE, "ShaderMaterial")); p_list->push_back(PropertyInfo(Variant::COLOR, "tile_modulate")); @@ -3552,11 +3619,11 @@ void TileSetEditorPlugin::make_visible(bool p_visible) { if (p_visible) { tileset_editor_button->show(); editor->make_bottom_panel_item_visible(tileset_editor); - get_tree()->connect_compat("idle_frame", tileset_editor, "_on_workspace_process"); + get_tree()->connect("idle_frame", Callable(tileset_editor, "_on_workspace_process")); } else { editor->hide_bottom_panel(); tileset_editor_button->hide(); - get_tree()->disconnect_compat("idle_frame", tileset_editor, "_on_workspace_process"); + get_tree()->disconnect("idle_frame", Callable(tileset_editor, "_on_workspace_process")); } } diff --git a/editor/plugins/tile_set_editor_plugin.h b/editor/plugins/tile_set_editor_plugin.h index 827325cfd7..e778c18f44 100644 --- a/editor/plugins/tile_set_editor_plugin.h +++ b/editor/plugins/tile_set_editor_plugin.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -46,7 +46,7 @@ class TileSetEditor : public HSplitContainer { GDCLASS(TileSetEditor, HSplitContainer); - enum TextureToolButtons { + enum TextureButtons { TOOL_TILESET_ADD_TEXTURE, TOOL_TILESET_REMOVE_TEXTURE, TOOL_TILESET_CREATE_SCENE, @@ -111,7 +111,7 @@ class TileSetEditor : public HSplitContainer { ItemList *texture_list; int option; - ToolButton *tileset_toolbar_buttons[TOOL_TILESET_MAX]; + Button *tileset_toolbar_buttons[TOOL_TILESET_MAX]; MenuButton *tileset_toolbar_tools; Map<RID, Ref<Texture2D>> texture_map; @@ -146,7 +146,7 @@ class TileSetEditor : public HSplitContainer { Button *tool_editmode[EDITMODE_MAX]; HSeparator *separator_editmode; HBoxContainer *toolbar; - ToolButton *tools[TOOL_MAX]; + Button *tools[TOOL_MAX]; VSeparator *separator_shape_toggle; VSeparator *separator_bitmask; VSeparator *separator_delete; @@ -200,6 +200,7 @@ private: void _on_workspace_overlay_draw(); void _on_workspace_draw(); void _on_workspace_process(); + void _on_scroll_container_input(const Ref<InputEvent> &p_event); void _on_workspace_input(const Ref<InputEvent> &p_ie); void _on_tool_clicked(int p_tool); void _on_priority_changed(float val); @@ -283,13 +284,13 @@ class TileSetEditorPlugin : public EditorPlugin { EditorNode *editor; public: - virtual String get_name() const { return "TileSet"; } - bool has_main_screen() const { return false; } - virtual void edit(Object *p_node); - virtual bool handles(Object *p_node) const; - virtual void make_visible(bool p_visible); - void set_state(const Dictionary &p_state); - Dictionary get_state() const; + virtual String get_name() const override { return "TileSet"; } + bool has_main_screen() const override { return false; } + virtual void edit(Object *p_node) override; + virtual bool handles(Object *p_node) const override; + virtual void make_visible(bool p_visible) override; + void set_state(const Dictionary &p_state) override; + Dictionary get_state() const override; TileSetEditorPlugin(EditorNode *p_node); }; diff --git a/editor/plugins/version_control_editor_plugin.cpp b/editor/plugins/version_control_editor_plugin.cpp index a1436e123d..0af3b936cb 100644 --- a/editor/plugins/version_control_editor_plugin.cpp +++ b/editor/plugins/version_control_editor_plugin.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -30,7 +30,7 @@ #include "version_control_editor_plugin.h" -#include "core/script_language.h" +#include "core/object/script_language.h" #include "editor/editor_file_system.h" #include "editor/editor_node.h" #include "editor/editor_scale.h" @@ -119,19 +119,13 @@ void VersionControlEditorPlugin::_initialize_vcs() { } void VersionControlEditorPlugin::_send_commit_msg() { - String msg = commit_message->get_text(); - if (msg == "") { - commit_status->set_text(TTR("No commit message was provided")); - return; - } - if (EditorVCSInterface::get_singleton()) { if (staged_files_count == 0) { commit_status->set_text(TTR("No files added to stage")); return; } - EditorVCSInterface::get_singleton()->commit(msg); + EditorVCSInterface::get_singleton()->commit(commit_message->get_text()); commit_message->set_text(""); version_control_dock_button->set_pressed(false); @@ -294,13 +288,17 @@ void VersionControlEditorPlugin::_update_commit_status() { staged_files_count = 0; } +void VersionControlEditorPlugin::_update_commit_button() { + commit_button->set_disabled(commit_message->get_text().strip_edges() == ""); +} + void VersionControlEditorPlugin::register_editor() { if (!EditorVCSInterface::get_singleton()) { EditorNode::get_singleton()->add_control_to_dock(EditorNode::DOCK_SLOT_RIGHT_UL, version_commit_dock); TabContainer *dock_vbc = (TabContainer *)version_commit_dock->get_parent_control(); dock_vbc->set_tab_title(version_commit_dock->get_index(), TTR("Commit")); - ToolButton *vc = EditorNode::get_singleton()->add_bottom_panel_item(TTR("Version Control"), version_control_dock); + Button *vc = EditorNode::get_singleton()->add_bottom_panel_item(TTR("Version Control"), version_control_dock); set_version_control_tool_button(vc); } } @@ -357,7 +355,7 @@ VersionControlEditorPlugin::VersionControlEditorPlugin() { set_up_dialog->set_min_size(Size2(400, 100)); version_control_actions->add_child(set_up_dialog); - set_up_ok_button = set_up_dialog->get_ok(); + set_up_ok_button = set_up_dialog->get_ok_button(); set_up_ok_button->set_text(TTR("Close")); set_up_vbc = memnew(VBoxContainer); @@ -463,11 +461,12 @@ VersionControlEditorPlugin::VersionControlEditorPlugin() { commit_message->set_v_grow_direction(Control::GrowDirection::GROW_DIRECTION_END); commit_message->set_custom_minimum_size(Size2(200, 100)); commit_message->set_wrap_enabled(true); - commit_message->set_text(TTR("Add a commit message")); + commit_message->connect("text_changed", callable_mp(this, &VersionControlEditorPlugin::_update_commit_button)); commit_box_vbc->add_child(commit_message); commit_button = memnew(Button); commit_button->set_text(TTR("Commit Changes")); + commit_button->set_disabled(true); commit_button->connect("pressed", callable_mp(this, &VersionControlEditorPlugin::_send_commit_msg)); commit_box_vbc->add_child(commit_button); diff --git a/editor/plugins/version_control_editor_plugin.h b/editor/plugins/version_control_editor_plugin.h index 664e38d65f..7d7c66a7ee 100644 --- a/editor/plugins/version_control_editor_plugin.h +++ b/editor/plugins/version_control_editor_plugin.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -43,7 +43,6 @@ class VersionControlEditorPlugin : public EditorPlugin { public: enum ChangeType { - CHANGE_TYPE_NEW = 0, CHANGE_TYPE_MODIFIED = 1, CHANGE_TYPE_RENAMED = 2, @@ -90,7 +89,7 @@ private: Label *commit_status; PanelContainer *version_control_dock; - ToolButton *version_control_dock_button; + Button *version_control_dock_button; VBoxContainer *diff_vbc; HBoxContainer *diff_hbc; Button *diff_refresh_button; @@ -111,6 +110,7 @@ private: void _clear_file_diff(); void _update_stage_status(); void _update_commit_status(); + void _update_commit_button(); friend class EditorVCSInterface; @@ -121,7 +121,7 @@ public: static VersionControlEditorPlugin *get_singleton(); void popup_vcs_set_up_dialog(const Control *p_gui_base); - void set_version_control_tool_button(ToolButton *p_button) { version_control_dock_button = p_button; } + void set_version_control_tool_button(Button *p_button) { version_control_dock_button = p_button; } PopupMenu *get_version_control_actions_panel() const { return version_control_actions; } VBoxContainer *get_version_commit_dock() const { return version_commit_dock; } diff --git a/editor/plugins/visual_shader_editor_plugin.cpp b/editor/plugins/visual_shader_editor_plugin.cpp index 92bdba93e7..a63e641c2b 100644 --- a/editor/plugins/visual_shader_editor_plugin.cpp +++ b/editor/plugins/visual_shader_editor_plugin.cpp @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -30,11 +30,11 @@ #include "visual_shader_editor_plugin.h" +#include "core/config/project_settings.h" #include "core/input/input.h" #include "core/io/resource_loader.h" #include "core/math/math_defs.h" #include "core/os/keyboard.h" -#include "core/project_settings.h" #include "core/version.h" #include "editor/editor_log.h" #include "editor/editor_properties.h" @@ -44,9 +44,31 @@ #include "scene/gui/panel.h" #include "scene/main/window.h" #include "scene/resources/visual_shader_nodes.h" +#include "scene/resources/visual_shader_sdf_nodes.h" #include "servers/display_server.h" #include "servers/rendering/shader_types.h" +struct FloatConstantDef { + String name; + float value = 0; + String desc; +}; + +static FloatConstantDef float_constant_defs[] = { + { "E", Math_E, TTR("E constant (2.718282). Represents the base of the natural logarithm.") }, + { "Epsilon", CMP_EPSILON, TTR("Epsilon constant (0.00001). Smallest possible scalar number.") }, + { "Phi", 1.618034f, TTR("Phi constant (1.618034). Golden ratio.") }, + { "Pi/4", Math_PI / 4, TTR("Pi/4 constant (0.785398) or 45 degrees.") }, + { "Pi/2", Math_PI / 2, TTR("Pi/2 constant (1.570796) or 90 degrees.") }, + { "Pi", Math_PI, TTR("Pi constant (3.141593) or 180 degrees.") }, + { "Tau", Math_TAU, TTR("Tau constant (6.283185) or 360 degrees.") }, + { "Sqrt2", Math_SQRT2, TTR("Sqrt2 constant (1.414214). Square root of 2.") } +}; + +const int MAX_FLOAT_CONST_DEFS = sizeof(float_constant_defs) / sizeof(FloatConstantDef); + +/////////////////// + Control *VisualShaderNodePlugin::create_editor(const Ref<Resource> &p_parent_resource, const Ref<VisualShaderNode> &p_node) { if (get_script_instance()) { return get_script_instance()->call("create_editor", p_parent_resource, p_node); @@ -60,6 +82,712 @@ void VisualShaderNodePlugin::_bind_methods() { /////////////////// +static Ref<StyleBoxEmpty> make_empty_stylebox(float p_margin_left = -1, float p_margin_top = -1, float p_margin_right = -1, float p_margin_bottom = -1) { + Ref<StyleBoxEmpty> style(memnew(StyleBoxEmpty)); + style->set_default_margin(SIDE_LEFT, p_margin_left * EDSCALE); + style->set_default_margin(SIDE_RIGHT, p_margin_right * EDSCALE); + style->set_default_margin(SIDE_BOTTOM, p_margin_bottom * EDSCALE); + style->set_default_margin(SIDE_TOP, p_margin_top * EDSCALE); + return style; +} + +/////////////////// + +VisualShaderGraphPlugin::VisualShaderGraphPlugin() { +} + +void VisualShaderGraphPlugin::_bind_methods() { + ClassDB::bind_method("add_node", &VisualShaderGraphPlugin::add_node); + ClassDB::bind_method("remove_node", &VisualShaderGraphPlugin::remove_node); + ClassDB::bind_method("connect_nodes", &VisualShaderGraphPlugin::connect_nodes); + ClassDB::bind_method("disconnect_nodes", &VisualShaderGraphPlugin::disconnect_nodes); + ClassDB::bind_method("set_node_position", &VisualShaderGraphPlugin::set_node_position); + ClassDB::bind_method("set_node_size", &VisualShaderGraphPlugin::set_node_size); + ClassDB::bind_method("update_node", &VisualShaderGraphPlugin::update_node); + ClassDB::bind_method("update_node_deferred", &VisualShaderGraphPlugin::update_node_deferred); + ClassDB::bind_method("set_input_port_default_value", &VisualShaderGraphPlugin::set_input_port_default_value); + ClassDB::bind_method("set_uniform_name", &VisualShaderGraphPlugin::set_uniform_name); + ClassDB::bind_method("set_expression", &VisualShaderGraphPlugin::set_expression); + ClassDB::bind_method("update_curve", &VisualShaderGraphPlugin::update_curve); + ClassDB::bind_method("update_constant", &VisualShaderGraphPlugin::update_constant); +} + +void VisualShaderGraphPlugin::register_shader(VisualShader *p_shader) { + visual_shader = Ref<VisualShader>(p_shader); +} + +void VisualShaderGraphPlugin::set_connections(List<VisualShader::Connection> &p_connections) { + connections = p_connections; +} + +void VisualShaderGraphPlugin::show_port_preview(VisualShader::Type p_type, int p_node_id, int p_port_id) { + if (visual_shader->get_shader_type() == p_type && links.has(p_node_id) && links[p_node_id].output_ports.has(p_port_id)) { + for (Map<int, Port>::Element *E = links[p_node_id].output_ports.front(); E; E = E->next()) { + if (E->value().preview_button != nullptr) { + E->value().preview_button->set_pressed(false); + } + } + + if (links[p_node_id].preview_visible && !is_dirty() && links[p_node_id].preview_box != nullptr) { + links[p_node_id].graph_node->remove_child(links[p_node_id].preview_box); + memdelete(links[p_node_id].preview_box); + links[p_node_id].graph_node->set_size(Vector2(-1, -1)); + links[p_node_id].preview_visible = false; + } + + if (p_port_id != -1 && links[p_node_id].output_ports[p_port_id].preview_button != nullptr) { + if (is_dirty()) { + links[p_node_id].preview_pos = links[p_node_id].graph_node->get_child_count(); + } + + VBoxContainer *vbox = memnew(VBoxContainer); + links[p_node_id].graph_node->add_child(vbox); + if (links[p_node_id].preview_pos != -1) { + links[p_node_id].graph_node->move_child(vbox, links[p_node_id].preview_pos); + } + + Control *offset = memnew(Control); + offset->set_custom_minimum_size(Size2(0, 5 * EDSCALE)); + vbox->add_child(offset); + + VisualShaderNodePortPreview *port_preview = memnew(VisualShaderNodePortPreview); + port_preview->setup(visual_shader, visual_shader->get_shader_type(), p_node_id, p_port_id); + port_preview->set_h_size_flags(Control::SIZE_SHRINK_CENTER); + vbox->add_child(port_preview); + links[p_node_id].preview_visible = true; + links[p_node_id].preview_box = vbox; + links[p_node_id].output_ports[p_port_id].preview_button->set_pressed(true); + } + } +} + +void VisualShaderGraphPlugin::update_node_deferred(VisualShader::Type p_type, int p_node_id) { + call_deferred("update_node", p_type, p_node_id); +} + +void VisualShaderGraphPlugin::update_node(VisualShader::Type p_type, int p_node_id) { + if (p_type != visual_shader->get_shader_type() || !links.has(p_node_id)) { + return; + } + remove_node(p_type, p_node_id); + add_node(p_type, p_node_id); +} + +void VisualShaderGraphPlugin::set_input_port_default_value(VisualShader::Type p_type, int p_node_id, int p_port_id, Variant p_value) { + if (p_type != visual_shader->get_shader_type() || !links.has(p_node_id)) { + return; + } + + Button *button = links[p_node_id].input_ports[p_port_id].default_input_button; + + switch (p_value.get_type()) { + case Variant::COLOR: { + button->set_custom_minimum_size(Size2(30, 0) * EDSCALE); + if (!button->is_connected("draw", callable_mp(VisualShaderEditor::get_singleton(), &VisualShaderEditor::_draw_color_over_button))) { + button->connect("draw", callable_mp(VisualShaderEditor::get_singleton(), &VisualShaderEditor::_draw_color_over_button), varray(button, p_value)); + } + } break; + case Variant::BOOL: { + button->set_text(((bool)p_value) ? "true" : "false"); + } break; + case Variant::INT: + case Variant::FLOAT: { + button->set_text(String::num(p_value, 4)); + } break; + case Variant::VECTOR3: { + Vector3 v = p_value; + button->set_text(String::num(v.x, 3) + "," + String::num(v.y, 3) + "," + String::num(v.z, 3)); + } break; + default: { + } + } +} + +void VisualShaderGraphPlugin::set_uniform_name(VisualShader::Type p_type, int p_node_id, const String &p_name) { + if (visual_shader->get_shader_type() == p_type && links.has(p_node_id) && links[p_node_id].uniform_name != nullptr) { + links[p_node_id].uniform_name->set_text(p_name); + } +} + +void VisualShaderGraphPlugin::update_curve(int p_node_id) { + if (links.has(p_node_id) && links[p_node_id].curve_editor) { + if (((VisualShaderNodeCurveTexture *)links[p_node_id].visual_node)->get_texture().is_valid()) { + links[p_node_id].curve_editor->set_curve(((VisualShaderNodeCurveTexture *)links[p_node_id].visual_node)->get_texture()->get_curve()); + } + } +} + +int VisualShaderGraphPlugin::get_constant_index(float p_constant) const { + for (int i = 0; i < MAX_FLOAT_CONST_DEFS; i++) { + if (Math::is_equal_approx(p_constant, float_constant_defs[i].value)) { + return i + 1; + } + } + return 0; +} + +void VisualShaderGraphPlugin::update_constant(VisualShader::Type p_type, int p_node_id) { + if (p_type != visual_shader->get_shader_type() || !links.has(p_node_id) || !links[p_node_id].const_op) { + return; + } + VisualShaderNodeFloatConstant *float_const = Object::cast_to<VisualShaderNodeFloatConstant>(links[p_node_id].visual_node); + if (!float_const) { + return; + } + links[p_node_id].const_op->select(get_constant_index(float_const->get_constant())); + links[p_node_id].graph_node->set_size(Size2(-1, -1)); +} + +void VisualShaderGraphPlugin::set_expression(VisualShader::Type p_type, int p_node_id, const String &p_expression) { + if (p_type != visual_shader->get_shader_type() || !links.has(p_node_id) || !links[p_node_id].expression_edit) { + return; + } + links[p_node_id].expression_edit->set_text(p_expression); +} + +void VisualShaderGraphPlugin::update_node_size(int p_node_id) { + if (!links.has(p_node_id)) { + return; + } + links[p_node_id].graph_node->set_size(Size2(-1, -1)); +} + +void VisualShaderGraphPlugin::register_default_input_button(int p_node_id, int p_port_id, Button *p_button) { + links[p_node_id].input_ports.insert(p_port_id, { p_button }); +} + +void VisualShaderGraphPlugin::register_constant_option_btn(int p_node_id, OptionButton *p_button) { + links[p_node_id].const_op = p_button; +} + +void VisualShaderGraphPlugin::register_expression_edit(int p_node_id, CodeEdit *p_expression_edit) { + links[p_node_id].expression_edit = p_expression_edit; +} + +void VisualShaderGraphPlugin::register_curve_editor(int p_node_id, CurveEditor *p_curve_editor) { + links[p_node_id].curve_editor = p_curve_editor; +} + +void VisualShaderGraphPlugin::update_uniform_refs() { + for (Map<int, Link>::Element *E = links.front(); E; E = E->next()) { + VisualShaderNodeUniformRef *ref = Object::cast_to<VisualShaderNodeUniformRef>(E->get().visual_node); + if (ref) { + remove_node(E->get().type, E->key()); + add_node(E->get().type, E->key()); + } + } +} + +VisualShader::Type VisualShaderGraphPlugin::get_shader_type() const { + return visual_shader->get_shader_type(); +} + +void VisualShaderGraphPlugin::set_node_position(VisualShader::Type p_type, int p_id, const Vector2 &p_position) { + if (visual_shader->get_shader_type() == p_type && links.has(p_id)) { + links[p_id].graph_node->set_position_offset(p_position); + } +} + +void VisualShaderGraphPlugin::set_node_size(VisualShader::Type p_type, int p_id, const Vector2 &p_size) { + if (visual_shader->get_shader_type() == p_type && links.has(p_id)) { + links[p_id].graph_node->set_size(p_size); + } +} + +bool VisualShaderGraphPlugin::is_preview_visible(int p_id) const { + return links[p_id].preview_visible; +} + +void VisualShaderGraphPlugin::clear_links() { + links.clear(); +} + +bool VisualShaderGraphPlugin::is_dirty() const { + return dirty; +} + +void VisualShaderGraphPlugin::make_dirty(bool p_enabled) { + dirty = p_enabled; +} + +void VisualShaderGraphPlugin::register_link(VisualShader::Type p_type, int p_id, VisualShaderNode *p_visual_node, GraphNode *p_graph_node) { + links.insert(p_id, { p_type, p_visual_node, p_graph_node, p_visual_node->get_output_port_for_preview() != -1, -1, Map<int, InputPort>(), Map<int, Port>(), nullptr, nullptr, nullptr, nullptr, nullptr }); +} + +void VisualShaderGraphPlugin::register_output_port(int p_node_id, int p_port, TextureButton *p_button) { + links[p_node_id].output_ports.insert(p_port, { p_button }); +} + +void VisualShaderGraphPlugin::register_uniform_name(int p_node_id, LineEdit *p_uniform_name) { + links[p_node_id].uniform_name = p_uniform_name; +} + +void VisualShaderGraphPlugin::add_node(VisualShader::Type p_type, int p_id) { + if (p_type != visual_shader->get_shader_type()) { + return; + } + + Control *offset; + + static Ref<StyleBoxEmpty> label_style = make_empty_stylebox(2, 1, 2, 1); + + static const Color type_color[6] = { + Color(0.38, 0.85, 0.96), // scalar (float) + Color(0.49, 0.78, 0.94), // scalar (int) + Color(0.84, 0.49, 0.93), // vector + Color(0.55, 0.65, 0.94), // boolean + Color(0.96, 0.66, 0.43), // transform + Color(1.0, 1.0, 0.0), // sampler + }; + + Ref<VisualShaderNode> vsnode = visual_shader->get_node(p_type, p_id); + + Ref<VisualShaderNodeResizableBase> resizable_node = Object::cast_to<VisualShaderNodeResizableBase>(vsnode.ptr()); + bool is_resizable = !resizable_node.is_null(); + Size2 size = Size2(0, 0); + + Ref<VisualShaderNodeGroupBase> group_node = Object::cast_to<VisualShaderNodeGroupBase>(vsnode.ptr()); + bool is_group = !group_node.is_null(); + + Ref<VisualShaderNodeExpression> expression_node = Object::cast_to<VisualShaderNodeExpression>(group_node.ptr()); + bool is_expression = !expression_node.is_null(); + String expression = ""; + + GraphNode *node = memnew(GraphNode); + register_link(p_type, p_id, vsnode.ptr(), node); + + if (is_resizable) { + size = resizable_node->get_size(); + + node->set_resizable(true); + node->connect("resize_request", callable_mp(VisualShaderEditor::get_singleton(), &VisualShaderEditor::_node_resized), varray((int)p_type, p_id)); + } + if (is_expression) { + expression = expression_node->get_expression(); + } + + node->set_position_offset(visual_shader->get_node_position(p_type, p_id)); + node->set_title(vsnode->get_caption()); + node->set_name(itos(p_id)); + + if (p_id >= 2) { + node->set_show_close_button(true); + node->connect("close_request", callable_mp(VisualShaderEditor::get_singleton(), &VisualShaderEditor::_delete_node_request), varray(p_type, p_id), CONNECT_DEFERRED); + } + + node->connect("dragged", callable_mp(VisualShaderEditor::get_singleton(), &VisualShaderEditor::_node_dragged), varray(p_id)); + + Control *custom_editor = nullptr; + int port_offset = 0; + + if (is_group) { + port_offset += 2; + } + + Ref<VisualShaderNodeUniform> uniform = vsnode; + if (uniform.is_valid()) { + VisualShaderEditor::get_singleton()->graph->add_child(node); + VisualShaderEditor::get_singleton()->_update_created_node(node); + + LineEdit *uniform_name = memnew(LineEdit); + register_uniform_name(p_id, uniform_name); + uniform_name->set_text(uniform->get_uniform_name()); + node->add_child(uniform_name); + uniform_name->connect("text_entered", callable_mp(VisualShaderEditor::get_singleton(), &VisualShaderEditor::_uniform_line_edit_changed), varray(p_id)); + uniform_name->connect("focus_exited", callable_mp(VisualShaderEditor::get_singleton(), &VisualShaderEditor::_uniform_line_edit_focus_out), varray(uniform_name, p_id)); + + if (vsnode->get_input_port_count() == 0 && vsnode->get_output_port_count() == 1 && vsnode->get_output_port_name(0) == "") { + //shortcut + VisualShaderNode::PortType port_right = vsnode->get_output_port_type(0); + node->set_slot(0, false, VisualShaderNode::PORT_TYPE_SCALAR, Color(), true, port_right, type_color[port_right]); + if (!vsnode->is_use_prop_slots()) { + return; + } + } + port_offset++; + } + + for (int i = 0; i < VisualShaderEditor::get_singleton()->plugins.size(); i++) { + vsnode->set_meta("id", p_id); + vsnode->set_meta("shader_type", (int)p_type); + custom_editor = VisualShaderEditor::get_singleton()->plugins.write[i]->create_editor(visual_shader, vsnode); + vsnode->remove_meta("id"); + vsnode->remove_meta("shader_type"); + if (custom_editor) { + if (vsnode->is_show_prop_names()) { + custom_editor->call_deferred("_show_prop_names", true); + } + break; + } + } + + Ref<VisualShaderNodeCurveTexture> curve = vsnode; + if (curve.is_valid()) { + if (curve->get_texture().is_valid() && !curve->get_texture()->is_connected("changed", callable_mp(VisualShaderEditor::get_singleton()->get_graph_plugin(), &VisualShaderGraphPlugin::update_curve))) { + curve->get_texture()->connect("changed", callable_mp(VisualShaderEditor::get_singleton()->get_graph_plugin(), &VisualShaderGraphPlugin::update_curve), varray(p_id)); + } + + HBoxContainer *hbox = memnew(HBoxContainer); + custom_editor->set_h_size_flags(Control::SIZE_EXPAND_FILL); + hbox->add_child(custom_editor); + custom_editor = hbox; + } + + Ref<VisualShaderNodeFloatConstant> float_const = vsnode; + if (float_const.is_valid()) { + HBoxContainer *hbox = memnew(HBoxContainer); + + hbox->add_child(custom_editor); + OptionButton *btn = memnew(OptionButton); + hbox->add_child(btn); + register_constant_option_btn(p_id, btn); + btn->add_item(""); + for (int i = 0; i < MAX_FLOAT_CONST_DEFS; i++) { + btn->add_item(float_constant_defs[i].name); + } + btn->select(get_constant_index(float_const->get_constant())); + btn->connect("item_selected", callable_mp(VisualShaderEditor::get_singleton(), &VisualShaderEditor::_float_constant_selected), varray(p_id)); + custom_editor = hbox; + } + + if (custom_editor && !vsnode->is_use_prop_slots() && vsnode->get_output_port_count() > 0 && vsnode->get_output_port_name(0) == "" && (vsnode->get_input_port_count() == 0 || vsnode->get_input_port_name(0) == "")) { + //will be embedded in first port + } else if (custom_editor) { + port_offset++; + node->add_child(custom_editor); + + if (curve.is_valid()) { + VisualShaderEditor::get_singleton()->graph->add_child(node); + VisualShaderEditor::get_singleton()->_update_created_node(node); + + CurveEditor *curve_editor = memnew(CurveEditor); + node->add_child(curve_editor); + register_curve_editor(p_id, curve_editor); + curve_editor->set_custom_minimum_size(Size2(300, 0)); + curve_editor->set_h_size_flags(Control::SIZE_EXPAND_FILL); + if (curve->get_texture().is_valid()) { + curve_editor->set_curve(curve->get_texture()->get_curve()); + } + + TextureButton *preview = memnew(TextureButton); + preview->set_toggle_mode(true); + preview->set_normal_texture(VisualShaderEditor::get_singleton()->get_theme_icon("GuiVisibilityHidden", "EditorIcons")); + preview->set_pressed_texture(VisualShaderEditor::get_singleton()->get_theme_icon("GuiVisibilityVisible", "EditorIcons")); + preview->set_v_size_flags(Control::SIZE_SHRINK_CENTER); + + register_output_port(p_id, 0, preview); + + preview->connect("pressed", callable_mp(VisualShaderEditor::get_singleton(), &VisualShaderEditor::_preview_select_port), varray(p_id, 0), CONNECT_DEFERRED); + custom_editor->add_child(preview); + + VisualShaderNode::PortType port_left = vsnode->get_input_port_type(0); + VisualShaderNode::PortType port_right = vsnode->get_output_port_type(0); + node->set_slot(0, true, port_left, type_color[port_left], true, port_right, type_color[port_right]); + + VisualShaderEditor::get_singleton()->call_deferred("_set_node_size", (int)p_type, p_id, size); + } + if (vsnode->is_use_prop_slots()) { + return; + } + custom_editor = nullptr; + } + + if (is_group) { + offset = memnew(Control); + offset->set_custom_minimum_size(Size2(0, 6 * EDSCALE)); + node->add_child(offset); + + if (group_node->is_editable()) { + HBoxContainer *hb2 = memnew(HBoxContainer); + + String input_port_name = "input" + itos(group_node->get_free_input_port_id()); + String output_port_name = "output" + itos(group_node->get_free_output_port_id()); + + for (int i = 0; i < MAX(vsnode->get_input_port_count(), vsnode->get_output_port_count()); i++) { + if (i < vsnode->get_input_port_count()) { + if (input_port_name == vsnode->get_input_port_name(i)) { + input_port_name = "_" + input_port_name; + } + } + if (i < vsnode->get_output_port_count()) { + if (output_port_name == vsnode->get_output_port_name(i)) { + output_port_name = "_" + output_port_name; + } + } + } + + Button *add_input_btn = memnew(Button); + add_input_btn->set_text(TTR("Add Input")); + add_input_btn->connect("pressed", callable_mp(VisualShaderEditor::get_singleton(), &VisualShaderEditor::_add_input_port), varray(p_id, group_node->get_free_input_port_id(), VisualShaderNode::PORT_TYPE_VECTOR, input_port_name), CONNECT_DEFERRED); + hb2->add_child(add_input_btn); + + hb2->add_spacer(); + + Button *add_output_btn = memnew(Button); + add_output_btn->set_text(TTR("Add Output")); + add_output_btn->connect("pressed", callable_mp(VisualShaderEditor::get_singleton(), &VisualShaderEditor::_add_output_port), varray(p_id, group_node->get_free_output_port_id(), VisualShaderNode::PORT_TYPE_VECTOR, output_port_name), CONNECT_DEFERRED); + hb2->add_child(add_output_btn); + + node->add_child(hb2); + } + } + + for (int i = 0; i < MAX(vsnode->get_input_port_count(), vsnode->get_output_port_count()); i++) { + if (vsnode->is_port_separator(i)) { + node->add_child(memnew(HSeparator)); + port_offset++; + } + + bool valid_left = i < vsnode->get_input_port_count(); + VisualShaderNode::PortType port_left = VisualShaderNode::PORT_TYPE_SCALAR; + bool port_left_used = false; + String name_left; + if (valid_left) { + name_left = vsnode->get_input_port_name(i); + port_left = vsnode->get_input_port_type(i); + for (List<VisualShader::Connection>::Element *E = connections.front(); E; E = E->next()) { + if (E->get().to_node == p_id && E->get().to_port == i) { + port_left_used = true; + } + } + } + + bool valid_right = i < vsnode->get_output_port_count(); + VisualShaderNode::PortType port_right = VisualShaderNode::PORT_TYPE_SCALAR; + String name_right; + if (valid_right) { + name_right = vsnode->get_output_port_name(i); + port_right = vsnode->get_output_port_type(i); + } + + HBoxContainer *hb = memnew(HBoxContainer); + hb->add_theme_constant_override("separation", 7 * EDSCALE); + + Variant default_value; + + if (valid_left && !port_left_used) { + default_value = vsnode->get_input_port_default_value(i); + } + + Button *button = memnew(Button); + hb->add_child(button); + register_default_input_button(p_id, i, button); + button->connect("pressed", callable_mp(VisualShaderEditor::get_singleton(), &VisualShaderEditor::_edit_port_default_input), varray(button, p_id, i)); + if (default_value.get_type() != Variant::NIL) { // only a label + set_input_port_default_value(p_type, p_id, i, default_value); + } else { + button->hide(); + } + + if (i == 0 && custom_editor) { + hb->add_child(custom_editor); + custom_editor->set_h_size_flags(Control::SIZE_EXPAND_FILL); + } else { + if (valid_left) { + if (is_group) { + OptionButton *type_box = memnew(OptionButton); + hb->add_child(type_box); + type_box->add_item(TTR("Float")); + type_box->add_item(TTR("Int")); + type_box->add_item(TTR("Vector")); + type_box->add_item(TTR("Boolean")); + type_box->add_item(TTR("Transform")); + type_box->add_item(TTR("Sampler")); + type_box->select(group_node->get_input_port_type(i)); + type_box->set_custom_minimum_size(Size2(100 * EDSCALE, 0)); + type_box->connect("item_selected", callable_mp(VisualShaderEditor::get_singleton(), &VisualShaderEditor::_change_input_port_type), varray(p_id, i), CONNECT_DEFERRED); + + LineEdit *name_box = memnew(LineEdit); + hb->add_child(name_box); + name_box->set_custom_minimum_size(Size2(65 * EDSCALE, 0)); + name_box->set_h_size_flags(Control::SIZE_EXPAND_FILL); + name_box->set_text(name_left); + name_box->connect("text_entered", callable_mp(VisualShaderEditor::get_singleton(), &VisualShaderEditor::_change_input_port_name), varray(name_box, p_id, i), CONNECT_DEFERRED); + name_box->connect("focus_exited", callable_mp(VisualShaderEditor::get_singleton(), &VisualShaderEditor::_port_name_focus_out), varray(name_box, p_id, i, false), CONNECT_DEFERRED); + + Button *remove_btn = memnew(Button); + remove_btn->set_icon(EditorNode::get_singleton()->get_gui_base()->get_theme_icon("Remove", "EditorIcons")); + remove_btn->set_tooltip(TTR("Remove") + " " + name_left); + remove_btn->connect("pressed", callable_mp(VisualShaderEditor::get_singleton(), &VisualShaderEditor::_remove_input_port), varray(p_id, i), CONNECT_DEFERRED); + hb->add_child(remove_btn); + } else { + Label *label = memnew(Label); + label->set_text(name_left); + label->add_theme_style_override("normal", label_style); //more compact + hb->add_child(label); + + if (vsnode->get_input_port_default_hint(i) != "" && !port_left_used) { + Label *hint_label = memnew(Label); + hint_label->set_text("[" + vsnode->get_input_port_default_hint(i) + "]"); + hint_label->add_theme_color_override("font_color", VisualShaderEditor::get_singleton()->get_theme_color("font_readonly_color", "TextEdit")); + hint_label->add_theme_style_override("normal", label_style); + hb->add_child(hint_label); + } + } + } + + if (!is_group) { + hb->add_spacer(); + } + + if (valid_right) { + if (is_group) { + Button *remove_btn = memnew(Button); + remove_btn->set_icon(EditorNode::get_singleton()->get_gui_base()->get_theme_icon("Remove", "EditorIcons")); + remove_btn->set_tooltip(TTR("Remove") + " " + name_left); + remove_btn->connect("pressed", callable_mp(VisualShaderEditor::get_singleton(), &VisualShaderEditor::_remove_output_port), varray(p_id, i), CONNECT_DEFERRED); + hb->add_child(remove_btn); + + LineEdit *name_box = memnew(LineEdit); + hb->add_child(name_box); + name_box->set_custom_minimum_size(Size2(65 * EDSCALE, 0)); + name_box->set_h_size_flags(Control::SIZE_EXPAND_FILL); + name_box->set_text(name_right); + name_box->connect("text_entered", callable_mp(VisualShaderEditor::get_singleton(), &VisualShaderEditor::_change_output_port_name), varray(name_box, p_id, i), CONNECT_DEFERRED); + name_box->connect("focus_exited", callable_mp(VisualShaderEditor::get_singleton(), &VisualShaderEditor::_port_name_focus_out), varray(name_box, p_id, i, true), CONNECT_DEFERRED); + + OptionButton *type_box = memnew(OptionButton); + hb->add_child(type_box); + type_box->add_item(TTR("Float")); + type_box->add_item(TTR("Int")); + type_box->add_item(TTR("Vector")); + type_box->add_item(TTR("Boolean")); + type_box->add_item(TTR("Transform")); + type_box->select(group_node->get_output_port_type(i)); + type_box->set_custom_minimum_size(Size2(100 * EDSCALE, 0)); + type_box->connect("item_selected", callable_mp(VisualShaderEditor::get_singleton(), &VisualShaderEditor::_change_output_port_type), varray(p_id, i), CONNECT_DEFERRED); + } else { + Label *label = memnew(Label); + label->set_text(name_right); + label->add_theme_style_override("normal", label_style); //more compact + hb->add_child(label); + } + } + } + + if (valid_right && visual_shader->get_shader_type() == VisualShader::TYPE_FRAGMENT && port_right != VisualShaderNode::PORT_TYPE_TRANSFORM && port_right != VisualShaderNode::PORT_TYPE_SAMPLER) { + TextureButton *preview = memnew(TextureButton); + preview->set_toggle_mode(true); + preview->set_normal_texture(VisualShaderEditor::get_singleton()->get_theme_icon("GuiVisibilityHidden", "EditorIcons")); + preview->set_pressed_texture(VisualShaderEditor::get_singleton()->get_theme_icon("GuiVisibilityVisible", "EditorIcons")); + preview->set_v_size_flags(Control::SIZE_SHRINK_CENTER); + + register_output_port(p_id, i, preview); + + preview->connect("pressed", callable_mp(VisualShaderEditor::get_singleton(), &VisualShaderEditor::_preview_select_port), varray(p_id, i), CONNECT_DEFERRED); + hb->add_child(preview); + } + + if (is_group) { + offset = memnew(Control); + offset->set_custom_minimum_size(Size2(0, 5 * EDSCALE)); + node->add_child(offset); + port_offset++; + } + + node->add_child(hb); + + node->set_slot(i + port_offset, valid_left, port_left, type_color[port_left], valid_right, port_right, type_color[port_right]); + } + + if (vsnode->get_output_port_for_preview() >= 0) { + show_port_preview(p_type, p_id, vsnode->get_output_port_for_preview()); + } + + offset = memnew(Control); + offset->set_custom_minimum_size(Size2(0, 4 * EDSCALE)); + node->add_child(offset); + + String error = vsnode->get_warning(visual_shader->get_mode(), p_type); + if (error != String()) { + Label *error_label = memnew(Label); + error_label->add_theme_color_override("font_color", VisualShaderEditor::get_singleton()->get_theme_color("error_color", "Editor")); + error_label->set_text(error); + node->add_child(error_label); + } + + if (is_expression) { + CodeEdit *expression_box = memnew(CodeEdit); + Ref<CodeHighlighter> expression_syntax_highlighter; + expression_syntax_highlighter.instance(); + expression_node->set_control(expression_box, 0); + node->add_child(expression_box); + register_expression_edit(p_id, expression_box); + + Color background_color = EDITOR_GET("text_editor/highlighting/background_color"); + Color text_color = EDITOR_GET("text_editor/highlighting/text_color"); + Color keyword_color = EDITOR_GET("text_editor/highlighting/keyword_color"); + Color comment_color = EDITOR_GET("text_editor/highlighting/comment_color"); + Color symbol_color = EDITOR_GET("text_editor/highlighting/symbol_color"); + Color function_color = EDITOR_GET("text_editor/highlighting/function_color"); + Color number_color = EDITOR_GET("text_editor/highlighting/number_color"); + Color members_color = EDITOR_GET("text_editor/highlighting/member_variable_color"); + + expression_box->set_syntax_highlighter(expression_syntax_highlighter); + expression_box->add_theme_color_override("background_color", background_color); + + for (List<String>::Element *E = VisualShaderEditor::get_singleton()->keyword_list.front(); E; E = E->next()) { + expression_syntax_highlighter->add_keyword_color(E->get(), keyword_color); + } + + expression_box->add_theme_font_override("font", VisualShaderEditor::get_singleton()->get_theme_font("expression", "EditorFonts")); + expression_box->add_theme_font_size_override("font_size", VisualShaderEditor::get_singleton()->get_theme_font_size("expression_size", "EditorFonts")); + expression_box->add_theme_color_override("font_color", text_color); + expression_syntax_highlighter->set_number_color(number_color); + expression_syntax_highlighter->set_symbol_color(symbol_color); + expression_syntax_highlighter->set_function_color(function_color); + expression_syntax_highlighter->set_member_variable_color(members_color); + expression_syntax_highlighter->add_color_region("/*", "*/", comment_color, false); + expression_syntax_highlighter->add_color_region("//", "", comment_color, true); + + expression_box->set_text(expression); + expression_box->set_context_menu_enabled(false); + expression_box->set_draw_line_numbers(true); + + expression_box->connect("focus_exited", callable_mp(VisualShaderEditor::get_singleton(), &VisualShaderEditor::_expression_focus_out), varray(expression_box, p_id)); + } + + if (!uniform.is_valid()) { + VisualShaderEditor::get_singleton()->graph->add_child(node); + VisualShaderEditor::get_singleton()->_update_created_node(node); + if (is_resizable) { + VisualShaderEditor::get_singleton()->call_deferred("_set_node_size", (int)p_type, p_id, size); + } + } +} + +void VisualShaderGraphPlugin::remove_node(VisualShader::Type p_type, int p_id) { + if (visual_shader->get_shader_type() == p_type && links.has(p_id)) { + links[p_id].graph_node->get_parent()->remove_child(links[p_id].graph_node); + memdelete(links[p_id].graph_node); + links.erase(p_id); + } +} + +void VisualShaderGraphPlugin::connect_nodes(VisualShader::Type p_type, int p_from_node, int p_from_port, int p_to_node, int p_to_port) { + if (visual_shader->get_shader_type() == p_type) { + VisualShaderEditor::get_singleton()->graph->connect_node(itos(p_from_node), p_from_port, itos(p_to_node), p_to_port); + if (links[p_to_node].input_ports.has(p_to_port) && links[p_to_node].input_ports[p_to_port].default_input_button != nullptr) { + links[p_to_node].input_ports[p_to_port].default_input_button->hide(); + } + } +} + +void VisualShaderGraphPlugin::disconnect_nodes(VisualShader::Type p_type, int p_from_node, int p_from_port, int p_to_node, int p_to_port) { + if (visual_shader->get_shader_type() == p_type) { + VisualShaderEditor::get_singleton()->graph->disconnect_node(itos(p_from_node), p_from_port, itos(p_to_node), p_to_port); + if (links[p_to_node].input_ports.has(p_to_port) && links[p_to_node].input_ports[p_to_port].default_input_button != nullptr && links[p_to_node].visual_node->get_input_port_default_value(p_to_port).get_type() != Variant::NIL) { + links[p_to_node].input_ports[p_to_port].default_input_button->show(); + set_input_port_default_value(p_type, p_to_node, p_to_port, links[p_to_node].visual_node->get_input_port_default_value(p_to_port)); + } + } +} + +VisualShaderGraphPlugin::~VisualShaderGraphPlugin() { +} + +///////////////// + void VisualShaderEditor::edit(VisualShader *p_visual_shader) { bool changed = false; if (p_visual_shader) { @@ -71,6 +799,7 @@ void VisualShaderEditor::edit(VisualShader *p_visual_shader) { } } visual_shader = Ref<VisualShader>(p_visual_shader); + graph_plugin->register_shader(visual_shader.ptr()); if (!visual_shader->is_connected("changed", callable_mp(this, &VisualShaderEditor::_update_preview))) { visual_shader->connect("changed", callable_mp(this, &VisualShaderEditor::_update_preview)); } @@ -81,6 +810,7 @@ void VisualShaderEditor::edit(VisualShader *p_visual_shader) { } #endif visual_shader->set_graph_offset(graph->get_scroll_ofs() / EDSCALE); + _set_mode(visual_shader->get_mode()); } else { if (visual_shader.is_valid()) { if (visual_shader->is_connected("changed", callable_mp(this, &VisualShaderEditor::_update_preview))) { @@ -97,8 +827,8 @@ void VisualShaderEditor::edit(VisualShader *p_visual_shader) { _clear_buffer(); _update_options_menu(); _update_preview(); + _update_graph(); } - _update_graph(); } } @@ -168,34 +898,18 @@ bool VisualShaderEditor::_is_available(int p_mode) { if (p_mode != -1) { switch (current_mode) { - case VisualShader::TYPE_VERTEX: + case 0: // Vertex or Emit current_mode = 1; break; - case VisualShader::TYPE_FRAGMENT: + case 1: // Fragment or Process current_mode = 2; break; - case VisualShader::TYPE_LIGHT: + case 2: // Light or End current_mode = 4; break; default: break; } - - int temp_mode = 0; - - if (p_mode & VisualShader::TYPE_FRAGMENT) { - temp_mode |= 2; - } - - if (p_mode & VisualShader::TYPE_LIGHT) { - temp_mode |= 4; - } - - if (temp_mode == 0) { - temp_mode |= 1; - } - - p_mode = temp_mode; } return (p_mode == -1 || (p_mode & current_mode) != 0); @@ -296,20 +1010,20 @@ String VisualShaderEditor::_get_description(int p_idx) { void VisualShaderEditor::_update_options_menu() { node_desc->set_text(""); - members_dialog->get_ok()->set_disabled(true); + members_dialog->get_ok_button()->set_disabled(true); members->clear(); TreeItem *root = members->create_item(); String filter = node_filter->get_text().strip_edges(); - bool use_filter = !filter.empty(); + bool use_filter = !filter.is_empty(); bool is_first_item = true; Color unsupported_color = get_theme_color("error_color", "Editor"); Color supported_color = get_theme_color("warning_color", "Editor"); - static bool low_driver = ProjectSettings::get_singleton()->get("rendering/quality/driver/driver_name") == "GLES2"; + static bool low_driver = ProjectSettings::get_singleton()->get("rendering/driver/driver_name") == "GLES2"; Map<String, TreeItem *> folders; @@ -404,6 +1118,21 @@ void VisualShaderEditor::_update_options_menu() { } } +void VisualShaderEditor::_set_mode(int p_which) { + if (p_which == VisualShader::MODE_PARTICLES) { + edit_type_standart->set_visible(false); + edit_type_particles->set_visible(true); + edit_type = edit_type_particles; + particles_mode = true; + } else { + edit_type_particles->set_visible(false); + edit_type_standart->set_visible(true); + edit_type = edit_type_standart; + particles_mode = false; + } + visual_shader->set_shader_type(get_current_shader_type()); +} + Size2 VisualShaderEditor::get_minimum_size() const { return Size2(10, 200); } @@ -418,15 +1147,6 @@ void VisualShaderEditor::_draw_color_over_button(Object *obj, Color p_color) { button->draw_rect(Rect2(normal->get_offset(), button->get_size() - normal->get_minimum_size()), p_color); } -static Ref<StyleBoxEmpty> make_empty_stylebox(float p_margin_left = -1, float p_margin_top = -1, float p_margin_right = -1, float p_margin_bottom = -1) { - Ref<StyleBoxEmpty> style(memnew(StyleBoxEmpty)); - style->set_default_margin(MARGIN_LEFT, p_margin_left * EDSCALE); - style->set_default_margin(MARGIN_RIGHT, p_margin_right * EDSCALE); - style->set_default_margin(MARGIN_BOTTOM, p_margin_bottom * EDSCALE); - style->set_default_margin(MARGIN_TOP, p_margin_top * EDSCALE); - return style; -} - void VisualShaderEditor::_update_created_node(GraphNode *node) { if (EditorSettings::get_singleton()->get("interface/theme/use_graph_node_headers")) { Ref<StyleBoxFlat> sb = node->get_theme_stylebox("frame", "GraphNode"); @@ -450,6 +1170,69 @@ void VisualShaderEditor::_update_created_node(GraphNode *node) { } } +void VisualShaderEditor::_update_uniforms(bool p_update_refs) { + VisualShaderNodeUniformRef::clear_uniforms(); + + for (int t = 0; t < VisualShader::TYPE_MAX; t++) { + Vector<int> tnodes = visual_shader->get_node_list((VisualShader::Type)t); + for (int i = 0; i < tnodes.size(); i++) { + Ref<VisualShaderNode> vsnode = visual_shader->get_node((VisualShader::Type)t, tnodes[i]); + Ref<VisualShaderNodeUniform> uniform = vsnode; + + if (uniform.is_valid()) { + Ref<VisualShaderNodeFloatUniform> float_uniform = vsnode; + Ref<VisualShaderNodeIntUniform> int_uniform = vsnode; + Ref<VisualShaderNodeVec3Uniform> vec3_uniform = vsnode; + Ref<VisualShaderNodeColorUniform> color_uniform = vsnode; + Ref<VisualShaderNodeBooleanUniform> bool_uniform = vsnode; + Ref<VisualShaderNodeTransformUniform> transform_uniform = vsnode; + + VisualShaderNodeUniformRef::UniformType uniform_type; + if (float_uniform.is_valid()) { + uniform_type = VisualShaderNodeUniformRef::UniformType::UNIFORM_TYPE_FLOAT; + } else if (int_uniform.is_valid()) { + uniform_type = VisualShaderNodeUniformRef::UniformType::UNIFORM_TYPE_INT; + } else if (bool_uniform.is_valid()) { + uniform_type = VisualShaderNodeUniformRef::UniformType::UNIFORM_TYPE_BOOLEAN; + } else if (vec3_uniform.is_valid()) { + uniform_type = VisualShaderNodeUniformRef::UniformType::UNIFORM_TYPE_VECTOR; + } else if (transform_uniform.is_valid()) { + uniform_type = VisualShaderNodeUniformRef::UniformType::UNIFORM_TYPE_TRANSFORM; + } else if (color_uniform.is_valid()) { + uniform_type = VisualShaderNodeUniformRef::UniformType::UNIFORM_TYPE_COLOR; + } else { + uniform_type = VisualShaderNodeUniformRef::UniformType::UNIFORM_TYPE_SAMPLER; + } + VisualShaderNodeUniformRef::add_uniform(uniform->get_uniform_name(), uniform_type); + } + } + } + if (p_update_refs) { + graph_plugin->update_uniform_refs(); + } +} + +void VisualShaderEditor::_update_uniform_refs(Set<String> &p_deleted_names) { + for (int i = 0; i < VisualShader::TYPE_MAX; i++) { + VisualShader::Type type = VisualShader::Type(i); + + Vector<int> nodes = visual_shader->get_node_list(type); + for (int j = 0; j < nodes.size(); j++) { + if (j > 0) { + Ref<VisualShaderNodeUniformRef> ref = visual_shader->get_node(type, nodes[j]); + if (ref.is_valid()) { + if (p_deleted_names.has(ref->get_uniform_name())) { + undo_redo->add_do_method(ref.ptr(), "set_uniform_name", "[None]"); + undo_redo->add_undo_method(ref.ptr(), "set_uniform_name", ref->get_uniform_name()); + undo_redo->add_do_method(graph_plugin.ptr(), "update_node", VisualShader::Type(i), nodes[j]); + undo_redo->add_undo_method(graph_plugin.ptr(), "update_node", VisualShader::Type(i), nodes[j]); + } + } + } + } + } +} + void VisualShaderEditor::_update_graph() { if (updating) { return; @@ -461,7 +1244,8 @@ void VisualShaderEditor::_update_graph() { graph->set_scroll_ofs(visual_shader->get_graph_offset() * EDSCALE); - VisualShader::Type type = VisualShader::Type(edit_type->get_selected()); + VisualShader::Type type = get_current_shader_type(); + graph->clear_connections(); //erase all nodes for (int i = 0; i < graph->get_child_count(); i++) { @@ -473,395 +1257,23 @@ void VisualShaderEditor::_update_graph() { } } - static const Color type_color[6] = { - Color(0.38, 0.85, 0.96), // scalar (float) - Color(0.49, 0.78, 0.94), // scalar (int) - Color(0.84, 0.49, 0.93), // vector - Color(0.55, 0.65, 0.94), // boolean - Color(0.96, 0.66, 0.43), // transform - Color(1.0, 1.0, 0.0), // sampler - }; - List<VisualShader::Connection> connections; visual_shader->get_node_connections(type, &connections); - - Ref<StyleBoxEmpty> label_style = make_empty_stylebox(2, 1, 2, 1); + graph_plugin->set_connections(connections); Vector<int> nodes = visual_shader->get_node_list(type); - Control *offset; - - for (int n_i = 0; n_i < nodes.size(); n_i++) { - Vector2 position = visual_shader->get_node_position(type, nodes[n_i]); - Ref<VisualShaderNode> vsnode = visual_shader->get_node(type, nodes[n_i]); - - Ref<VisualShaderNodeGroupBase> group_node = Object::cast_to<VisualShaderNodeGroupBase>(vsnode.ptr()); - bool is_group = !group_node.is_null(); - Size2 size = Size2(0, 0); - - Ref<VisualShaderNodeExpression> expression_node = Object::cast_to<VisualShaderNodeExpression>(group_node.ptr()); - bool is_expression = !expression_node.is_null(); - String expression = ""; - - GraphNode *node = memnew(GraphNode); - - if (is_group) { - size = group_node->get_size(); - - node->set_resizable(true); - node->connect("resize_request", callable_mp(this, &VisualShaderEditor::_node_resized), varray((int)type, nodes[n_i])); - } - if (is_expression) { - expression = expression_node->get_expression(); - } - - node->set_offset(position); - - node->set_title(vsnode->get_caption()); - node->set_name(itos(nodes[n_i])); - - if (nodes[n_i] >= 2) { - node->set_show_close_button(true); - node->connect("close_request", callable_mp(this, &VisualShaderEditor::_delete_request), varray(nodes[n_i]), CONNECT_DEFERRED); - } - - node->connect("dragged", callable_mp(this, &VisualShaderEditor::_node_dragged), varray(nodes[n_i])); - - Control *custom_editor = nullptr; - int port_offset = 0; - - if (is_group) { - port_offset += 2; - } - - Ref<VisualShaderNodeUniform> uniform = vsnode; - Ref<VisualShaderNodeFloatUniform> float_uniform = vsnode; - Ref<VisualShaderNodeIntUniform> int_uniform = vsnode; - Ref<VisualShaderNodeVec3Uniform> vec3_uniform = vsnode; - Ref<VisualShaderNodeColorUniform> color_uniform = vsnode; - Ref<VisualShaderNodeBooleanUniform> bool_uniform = vsnode; - Ref<VisualShaderNodeTransformUniform> transform_uniform = vsnode; - if (uniform.is_valid()) { - graph->add_child(node); - _update_created_node(node); - - LineEdit *uniform_name = memnew(LineEdit); - uniform_name->set_text(uniform->get_uniform_name()); - node->add_child(uniform_name); - uniform_name->connect("text_entered", callable_mp(this, &VisualShaderEditor::_line_edit_changed), varray(uniform_name, nodes[n_i])); - uniform_name->connect("focus_exited", callable_mp(this, &VisualShaderEditor::_line_edit_focus_out), varray(uniform_name, nodes[n_i])); - - String error = vsnode->get_warning(visual_shader->get_mode(), type); - if (error != String()) { - offset = memnew(Control); - offset->set_custom_minimum_size(Size2(0, 4 * EDSCALE)); - node->add_child(offset); - Label *error_label = memnew(Label); - error_label->add_theme_color_override("font_color", get_theme_color("error_color", "Editor")); - error_label->set_text(error); - node->add_child(error_label); - } - - if (vsnode->get_input_port_count() == 0 && vsnode->get_output_port_count() == 1 && vsnode->get_output_port_name(0) == "") { - //shortcut - VisualShaderNode::PortType port_right = vsnode->get_output_port_type(0); - node->set_slot(0, false, VisualShaderNode::PORT_TYPE_SCALAR, Color(), true, port_right, type_color[port_right]); - if (!float_uniform.is_valid() && !int_uniform.is_valid() && !vec3_uniform.is_valid() && !color_uniform.is_valid() && !bool_uniform.is_valid() && !transform_uniform.is_valid()) { - continue; - } - } - port_offset++; - } - - for (int i = 0; i < plugins.size(); i++) { - custom_editor = plugins.write[i]->create_editor(visual_shader, vsnode); - if (custom_editor) { - break; - } - } - - if (custom_editor && !float_uniform.is_valid() && !int_uniform.is_valid() && !vec3_uniform.is_valid() && !bool_uniform.is_valid() && !transform_uniform.is_valid() && vsnode->get_output_port_count() > 0 && vsnode->get_output_port_name(0) == "" && (vsnode->get_input_port_count() == 0 || vsnode->get_input_port_name(0) == "")) { - //will be embedded in first port - } else if (custom_editor) { - port_offset++; - node->add_child(custom_editor); - if (color_uniform.is_valid()) { - custom_editor->call_deferred("_show_prop_names", true); - } - if (float_uniform.is_valid() || int_uniform.is_valid() || vec3_uniform.is_valid() || bool_uniform.is_valid() || transform_uniform.is_valid()) { - custom_editor->call_deferred("_show_prop_names", true); - continue; - } - custom_editor = nullptr; - } - - if (is_group) { - offset = memnew(Control); - offset->set_custom_minimum_size(Size2(0, 6 * EDSCALE)); - node->add_child(offset); - - if (group_node->is_editable()) { - HBoxContainer *hb2 = memnew(HBoxContainer); - - Button *add_input_btn = memnew(Button); - add_input_btn->set_text(TTR("Add Input")); - add_input_btn->connect("pressed", callable_mp(this, &VisualShaderEditor::_add_input_port), varray(nodes[n_i], group_node->get_free_input_port_id(), VisualShaderNode::PORT_TYPE_VECTOR, "input" + itos(group_node->get_free_input_port_id())), CONNECT_DEFERRED); - hb2->add_child(add_input_btn); + _update_uniforms(false); - hb2->add_spacer(); + graph_plugin->clear_links(); + graph_plugin->make_dirty(true); - Button *add_output_btn = memnew(Button); - add_output_btn->set_text(TTR("Add Output")); - add_output_btn->connect("pressed", callable_mp(this, &VisualShaderEditor::_add_output_port), varray(nodes[n_i], group_node->get_free_output_port_id(), VisualShaderNode::PORT_TYPE_VECTOR, "output" + itos(group_node->get_free_output_port_id())), CONNECT_DEFERRED); - hb2->add_child(add_output_btn); - - node->add_child(hb2); - } - } - - for (int i = 0; i < MAX(vsnode->get_input_port_count(), vsnode->get_output_port_count()); i++) { - if (vsnode->is_port_separator(i)) { - node->add_child(memnew(HSeparator)); - port_offset++; - } - - bool valid_left = i < vsnode->get_input_port_count(); - VisualShaderNode::PortType port_left = VisualShaderNode::PORT_TYPE_SCALAR; - bool port_left_used = false; - String name_left; - if (valid_left) { - name_left = vsnode->get_input_port_name(i); - port_left = vsnode->get_input_port_type(i); - for (List<VisualShader::Connection>::Element *E = connections.front(); E; E = E->next()) { - if (E->get().to_node == nodes[n_i] && E->get().to_port == i) { - port_left_used = true; - } - } - } - - bool valid_right = i < vsnode->get_output_port_count(); - VisualShaderNode::PortType port_right = VisualShaderNode::PORT_TYPE_SCALAR; - String name_right; - if (valid_right) { - name_right = vsnode->get_output_port_name(i); - port_right = vsnode->get_output_port_type(i); - } - - HBoxContainer *hb = memnew(HBoxContainer); - hb->add_theme_constant_override("separation", 7 * EDSCALE); - - Variant default_value; - - if (valid_left && !port_left_used) { - default_value = vsnode->get_input_port_default_value(i); - } - - if (default_value.get_type() != Variant::NIL) { // only a label - Button *button = memnew(Button); - hb->add_child(button); - button->connect("pressed", callable_mp(this, &VisualShaderEditor::_edit_port_default_input), varray(button, nodes[n_i], i)); - - switch (default_value.get_type()) { - case Variant::COLOR: { - button->set_custom_minimum_size(Size2(30, 0) * EDSCALE); - button->connect("draw", callable_mp(this, &VisualShaderEditor::_draw_color_over_button), varray(button, default_value)); - } break; - case Variant::BOOL: { - button->set_text(((bool)default_value) ? "true" : "false"); - } break; - case Variant::INT: - case Variant::FLOAT: { - button->set_text(String::num(default_value, 4)); - } break; - case Variant::VECTOR3: { - Vector3 v = default_value; - button->set_text(String::num(v.x, 3) + "," + String::num(v.y, 3) + "," + String::num(v.z, 3)); - } break; - default: { - } - } - } - - if (i == 0 && custom_editor) { - hb->add_child(custom_editor); - custom_editor->set_h_size_flags(SIZE_EXPAND_FILL); - } else { - if (valid_left) { - if (is_group) { - OptionButton *type_box = memnew(OptionButton); - hb->add_child(type_box); - type_box->add_item(TTR("Float")); - type_box->add_item(TTR("Int")); - type_box->add_item(TTR("Vector")); - type_box->add_item(TTR("Boolean")); - type_box->add_item(TTR("Transform")); - type_box->add_item(TTR("Sampler")); - type_box->select(group_node->get_input_port_type(i)); - type_box->set_custom_minimum_size(Size2(100 * EDSCALE, 0)); - type_box->connect("item_selected", callable_mp(this, &VisualShaderEditor::_change_input_port_type), varray(nodes[n_i], i), CONNECT_DEFERRED); - - LineEdit *name_box = memnew(LineEdit); - hb->add_child(name_box); - name_box->set_custom_minimum_size(Size2(65 * EDSCALE, 0)); - name_box->set_h_size_flags(SIZE_EXPAND_FILL); - name_box->set_text(name_left); - name_box->connect("text_entered", callable_mp(this, &VisualShaderEditor::_change_input_port_name), varray(name_box, nodes[n_i], i)); - name_box->connect("focus_exited", callable_mp(this, &VisualShaderEditor::_port_name_focus_out), varray(name_box, nodes[n_i], i, false)); - - Button *remove_btn = memnew(Button); - remove_btn->set_icon(EditorNode::get_singleton()->get_gui_base()->get_theme_icon("Remove", "EditorIcons")); - remove_btn->set_tooltip(TTR("Remove") + " " + name_left); - remove_btn->connect("pressed", callable_mp(this, &VisualShaderEditor::_remove_input_port), varray(nodes[n_i], i), CONNECT_DEFERRED); - hb->add_child(remove_btn); - } else { - Label *label = memnew(Label); - label->set_text(name_left); - label->add_theme_style_override("normal", label_style); //more compact - hb->add_child(label); - - if (vsnode->get_input_port_default_hint(i) != "" && !port_left_used) { - Label *hint_label = memnew(Label); - hint_label->set_text("[" + vsnode->get_input_port_default_hint(i) + "]"); - hint_label->add_theme_color_override("font_color", get_theme_color("font_color_readonly", "TextEdit")); - hint_label->add_theme_style_override("normal", label_style); - hb->add_child(hint_label); - } - } - } - - if (!is_group) { - hb->add_spacer(); - } - - if (valid_right) { - if (is_group) { - Button *remove_btn = memnew(Button); - remove_btn->set_icon(EditorNode::get_singleton()->get_gui_base()->get_theme_icon("Remove", "EditorIcons")); - remove_btn->set_tooltip(TTR("Remove") + " " + name_left); - remove_btn->connect("pressed", callable_mp(this, &VisualShaderEditor::_remove_output_port), varray(nodes[n_i], i), CONNECT_DEFERRED); - hb->add_child(remove_btn); - - LineEdit *name_box = memnew(LineEdit); - hb->add_child(name_box); - name_box->set_custom_minimum_size(Size2(65 * EDSCALE, 0)); - name_box->set_h_size_flags(SIZE_EXPAND_FILL); - name_box->set_text(name_right); - name_box->connect("text_entered", callable_mp(this, &VisualShaderEditor::_change_output_port_name), varray(name_box, nodes[n_i], i)); - name_box->connect("focus_exited", callable_mp(this, &VisualShaderEditor::_port_name_focus_out), varray(name_box, nodes[n_i], i, true)); - - OptionButton *type_box = memnew(OptionButton); - hb->add_child(type_box); - type_box->add_item(TTR("Float")); - type_box->add_item(TTR("Int")); - type_box->add_item(TTR("Vector")); - type_box->add_item(TTR("Boolean")); - type_box->add_item(TTR("Transform")); - type_box->select(group_node->get_output_port_type(i)); - type_box->set_custom_minimum_size(Size2(100 * EDSCALE, 0)); - type_box->connect("item_selected", callable_mp(this, &VisualShaderEditor::_change_output_port_type), varray(nodes[n_i], i), CONNECT_DEFERRED); - } else { - Label *label = memnew(Label); - label->set_text(name_right); - label->add_theme_style_override("normal", label_style); //more compact - hb->add_child(label); - } - } - } - - if (valid_right && edit_type->get_selected() == VisualShader::TYPE_FRAGMENT && port_right != VisualShaderNode::PORT_TYPE_TRANSFORM && port_right != VisualShaderNode::PORT_TYPE_SAMPLER) { - TextureButton *preview = memnew(TextureButton); - preview->set_toggle_mode(true); - preview->set_normal_texture(get_theme_icon("GuiVisibilityHidden", "EditorIcons")); - preview->set_pressed_texture(get_theme_icon("GuiVisibilityVisible", "EditorIcons")); - preview->set_v_size_flags(SIZE_SHRINK_CENTER); - - if (vsnode->get_output_port_for_preview() == i) { - preview->set_pressed(true); - } - - preview->connect("pressed", callable_mp(this, &VisualShaderEditor::_preview_select_port), varray(nodes[n_i], i), CONNECT_DEFERRED); - hb->add_child(preview); - } - - if (is_group) { - offset = memnew(Control); - offset->set_custom_minimum_size(Size2(0, 5 * EDSCALE)); - node->add_child(offset); - port_offset++; - } - - node->add_child(hb); - - node->set_slot(i + port_offset, valid_left, port_left, type_color[port_left], valid_right, port_right, type_color[port_right]); - } - - if (vsnode->get_output_port_for_preview() >= 0) { - int port_type = vsnode->get_output_port_type(vsnode->get_output_port_for_preview()); - - if (port_type != VisualShaderNode::PORT_TYPE_TRANSFORM && port_type != VisualShaderNode::PORT_TYPE_SAMPLER) { - offset = memnew(Control); - offset->set_custom_minimum_size(Size2(0, 5 * EDSCALE)); - node->add_child(offset); - - VisualShaderNodePortPreview *port_preview = memnew(VisualShaderNodePortPreview); - port_preview->setup(visual_shader, type, nodes[n_i], vsnode->get_output_port_for_preview()); - port_preview->set_h_size_flags(SIZE_SHRINK_CENTER); - node->add_child(port_preview); - } - } - - offset = memnew(Control); - offset->set_custom_minimum_size(Size2(0, 4 * EDSCALE)); - node->add_child(offset); - - String error = vsnode->get_warning(visual_shader->get_mode(), type); - if (error != String()) { - Label *error_label = memnew(Label); - error_label->add_theme_color_override("font_color", get_theme_color("error_color", "Editor")); - error_label->set_text(error); - node->add_child(error_label); - } - - if (is_expression) { - TextEdit *expression_box = memnew(TextEdit); - expression_node->set_control(expression_box, 0); - node->add_child(expression_box); - - Color background_color = EDITOR_GET("text_editor/highlighting/background_color"); - Color text_color = EDITOR_GET("text_editor/highlighting/text_color"); - Color keyword_color = EDITOR_GET("text_editor/highlighting/keyword_color"); - Color comment_color = EDITOR_GET("text_editor/highlighting/comment_color"); - Color symbol_color = EDITOR_GET("text_editor/highlighting/symbol_color"); - - expression_box->set_syntax_coloring(true); - expression_box->add_theme_color_override("background_color", background_color); - - for (List<String>::Element *E = keyword_list.front(); E; E = E->next()) { - expression_box->add_keyword_color(E->get(), keyword_color); - } - - expression_box->add_theme_font_override("font", get_theme_font("expression", "EditorFonts")); - expression_box->add_theme_color_override("font_color", text_color); - expression_box->add_theme_color_override("symbol_color", symbol_color); - expression_box->add_color_region("/*", "*/", comment_color, false); - expression_box->add_color_region("//", "", comment_color, false); - - expression_box->set_text(expression); - expression_box->set_context_menu_enabled(false); - expression_box->set_show_line_numbers(true); - - expression_box->connect("focus_exited", callable_mp(this, &VisualShaderEditor::_expression_focus_out), varray(expression_box, nodes[n_i])); - } - - if (!uniform.is_valid()) { - graph->add_child(node); - _update_created_node(node); - if (is_group) { - call_deferred("_set_node_size", (int)type, nodes[n_i], size); - } - } + for (int n_i = 0; n_i < nodes.size(); n_i++) { + graph_plugin->add_node(type, nodes[n_i]); } + graph_plugin->make_dirty(false); + for (List<VisualShader::Connection>::Element *E = connections.front(); E; E = E->next()) { int from = E->get().from_node; int from_idx = E->get().from_port; @@ -870,112 +1282,145 @@ void VisualShaderEditor::_update_graph() { graph->connect_node(itos(from), from_idx, itos(to), to_idx); } + + float graph_minimap_opacity = EditorSettings::get_singleton()->get("editors/visual_editors/minimap_opacity"); + graph->set_minimap_opacity(graph_minimap_opacity); +} + +VisualShader::Type VisualShaderEditor::get_current_shader_type() const { + VisualShader::Type type; + if (particles_mode) { + type = VisualShader::Type(edit_type->get_selected() + 3); + } else { + type = VisualShader::Type(edit_type->get_selected()); + } + return type; } void VisualShaderEditor::_add_input_port(int p_node, int p_port, int p_port_type, const String &p_name) { - VisualShader::Type type = VisualShader::Type(edit_type->get_selected()); + VisualShader::Type type = get_current_shader_type(); Ref<VisualShaderNodeExpression> node = visual_shader->get_node(type, p_node); if (node.is_null()) { return; } - undo_redo->create_action(TTR("Add input port")); + undo_redo->create_action(TTR("Add Input Port")); undo_redo->add_do_method(node.ptr(), "add_input_port", p_port, p_port_type, p_name); undo_redo->add_undo_method(node.ptr(), "remove_input_port", p_port); - undo_redo->add_do_method(this, "_update_graph"); - undo_redo->add_undo_method(this, "_update_graph"); - undo_redo->add_do_method(this, "_rebuild"); - undo_redo->add_undo_method(this, "_rebuild"); + undo_redo->add_do_method(graph_plugin.ptr(), "update_node", type, p_node); + undo_redo->add_undo_method(graph_plugin.ptr(), "update_node", type, p_node); undo_redo->commit_action(); } void VisualShaderEditor::_add_output_port(int p_node, int p_port, int p_port_type, const String &p_name) { - VisualShader::Type type = VisualShader::Type(edit_type->get_selected()); + VisualShader::Type type = get_current_shader_type(); Ref<VisualShaderNodeGroupBase> node = visual_shader->get_node(type, p_node); if (node.is_null()) { return; } - undo_redo->create_action(TTR("Add output port")); + undo_redo->create_action(TTR("Add Output Port")); undo_redo->add_do_method(node.ptr(), "add_output_port", p_port, p_port_type, p_name); undo_redo->add_undo_method(node.ptr(), "remove_output_port", p_port); - undo_redo->add_do_method(this, "_update_graph"); - undo_redo->add_undo_method(this, "_update_graph"); - undo_redo->add_do_method(this, "_rebuild"); - undo_redo->add_undo_method(this, "_rebuild"); + undo_redo->add_do_method(graph_plugin.ptr(), "update_node", type, p_node); + undo_redo->add_undo_method(graph_plugin.ptr(), "update_node", type, p_node); undo_redo->commit_action(); } void VisualShaderEditor::_change_input_port_type(int p_type, int p_node, int p_port) { - VisualShader::Type type = VisualShader::Type(edit_type->get_selected()); + VisualShader::Type type = get_current_shader_type(); Ref<VisualShaderNodeGroupBase> node = visual_shader->get_node(type, p_node); if (node.is_null()) { return; } - undo_redo->create_action(TTR("Change input port type")); + undo_redo->create_action(TTR("Change Input Port Type")); undo_redo->add_do_method(node.ptr(), "set_input_port_type", p_port, p_type); undo_redo->add_undo_method(node.ptr(), "set_input_port_type", p_port, node->get_input_port_type(p_port)); - undo_redo->add_do_method(this, "_update_graph"); - undo_redo->add_undo_method(this, "_update_graph"); - undo_redo->add_do_method(this, "_rebuild"); - undo_redo->add_undo_method(this, "_rebuild"); + undo_redo->add_do_method(graph_plugin.ptr(), "update_node", type, p_node); + undo_redo->add_undo_method(graph_plugin.ptr(), "update_node", type, p_node); undo_redo->commit_action(); } void VisualShaderEditor::_change_output_port_type(int p_type, int p_node, int p_port) { - VisualShader::Type type = VisualShader::Type(edit_type->get_selected()); + VisualShader::Type type = get_current_shader_type(); Ref<VisualShaderNodeGroupBase> node = visual_shader->get_node(type, p_node); if (node.is_null()) { return; } - undo_redo->create_action(TTR("Change output port type")); + undo_redo->create_action(TTR("Change Output Port Type")); undo_redo->add_do_method(node.ptr(), "set_output_port_type", p_port, p_type); undo_redo->add_undo_method(node.ptr(), "set_output_port_type", p_port, node->get_output_port_type(p_port)); - undo_redo->add_do_method(this, "_update_graph"); - undo_redo->add_undo_method(this, "_update_graph"); - undo_redo->add_do_method(this, "_rebuild"); - undo_redo->add_undo_method(this, "_rebuild"); + undo_redo->add_do_method(graph_plugin.ptr(), "update_node", type, p_node); + undo_redo->add_undo_method(graph_plugin.ptr(), "update_node", type, p_node); undo_redo->commit_action(); } -void VisualShaderEditor::_change_input_port_name(const String &p_text, Object *line_edit, int p_node_id, int p_port_id) { - VisualShader::Type type = VisualShader::Type(edit_type->get_selected()); +void VisualShaderEditor::_change_input_port_name(const String &p_text, Object *p_line_edit, int p_node_id, int p_port_id) { + VisualShader::Type type = get_current_shader_type(); Ref<VisualShaderNodeGroupBase> node = visual_shader->get_node(type, p_node_id); ERR_FAIL_COND(!node.is_valid()); - undo_redo->create_action(TTR("Change input port name")); - undo_redo->add_do_method(node.ptr(), "set_input_port_name", p_port_id, p_text); + String prev_name = node->get_input_port_name(p_port_id); + if (prev_name == p_text) { + return; + } + + LineEdit *line_edit = Object::cast_to<LineEdit>(p_line_edit); + ERR_FAIL_COND(!line_edit); + + String validated_name = visual_shader->validate_port_name(p_text, node.ptr(), p_port_id, false); + if (validated_name == String() || prev_name == validated_name) { + line_edit->set_text(node->get_input_port_name(p_port_id)); + return; + } + + undo_redo->create_action(TTR("Change Input Port Name")); + undo_redo->add_do_method(node.ptr(), "set_input_port_name", p_port_id, validated_name); undo_redo->add_undo_method(node.ptr(), "set_input_port_name", p_port_id, node->get_input_port_name(p_port_id)); - undo_redo->add_do_method(this, "_rebuild"); - undo_redo->add_undo_method(this, "_rebuild"); + undo_redo->add_do_method(graph_plugin.ptr(), "update_node", type, p_node_id); + undo_redo->add_undo_method(graph_plugin.ptr(), "update_node", type, p_node_id); undo_redo->commit_action(); } -void VisualShaderEditor::_change_output_port_name(const String &p_text, Object *line_edit, int p_node_id, int p_port_id) { - VisualShader::Type type = VisualShader::Type(edit_type->get_selected()); +void VisualShaderEditor::_change_output_port_name(const String &p_text, Object *p_line_edit, int p_node_id, int p_port_id) { + VisualShader::Type type = get_current_shader_type(); Ref<VisualShaderNodeGroupBase> node = visual_shader->get_node(type, p_node_id); ERR_FAIL_COND(!node.is_valid()); - undo_redo->create_action(TTR("Change output port name")); - undo_redo->add_do_method(node.ptr(), "set_output_port_name", p_port_id, p_text); - undo_redo->add_undo_method(node.ptr(), "set_output_port_name", p_port_id, node->get_output_port_name(p_port_id)); - undo_redo->add_do_method(this, "_rebuild"); - undo_redo->add_undo_method(this, "_rebuild"); + String prev_name = node->get_output_port_name(p_port_id); + if (prev_name == p_text) { + return; + } + + LineEdit *line_edit = Object::cast_to<LineEdit>(p_line_edit); + ERR_FAIL_COND(!line_edit); + + String validated_name = visual_shader->validate_port_name(p_text, node.ptr(), p_port_id, true); + if (validated_name == String() || prev_name == validated_name) { + line_edit->set_text(node->get_output_port_name(p_port_id)); + return; + } + + undo_redo->create_action(TTR("Change Output Port Name")); + undo_redo->add_do_method(node.ptr(), "set_output_port_name", p_port_id, validated_name); + undo_redo->add_undo_method(node.ptr(), "set_output_port_name", p_port_id, prev_name); + undo_redo->add_do_method(graph_plugin.ptr(), "update_node", type, p_node_id); + undo_redo->add_undo_method(graph_plugin.ptr(), "update_node", type, p_node_id); undo_redo->commit_action(); } void VisualShaderEditor::_remove_input_port(int p_node, int p_port) { - VisualShader::Type type = VisualShader::Type(edit_type->get_selected()); + VisualShader::Type type = get_current_shader_type(); Ref<VisualShaderNodeGroupBase> node = visual_shader->get_node(type, p_node); if (node.is_null()) { return; } - undo_redo->create_action(TTR("Remove input port")); + undo_redo->create_action(TTR("Remove Input Port")); List<VisualShader::Connection> conns; visual_shader->get_node_connections(type, &conns); @@ -989,12 +1434,21 @@ void VisualShaderEditor::_remove_input_port(int p_node, int p_port) { if (to_port == p_port) { undo_redo->add_do_method(visual_shader.ptr(), "disconnect_nodes", type, from_node, from_port, to_node, to_port); undo_redo->add_undo_method(visual_shader.ptr(), "connect_nodes_forced", type, from_node, from_port, to_node, to_port); + + undo_redo->add_do_method(graph_plugin.ptr(), "disconnect_nodes", type, from_node, from_port, to_node, to_port); + undo_redo->add_undo_method(graph_plugin.ptr(), "connect_nodes", type, from_node, from_port, to_node, to_port); } else if (to_port > p_port) { undo_redo->add_do_method(visual_shader.ptr(), "disconnect_nodes", type, from_node, from_port, to_node, to_port); undo_redo->add_undo_method(visual_shader.ptr(), "connect_nodes_forced", type, from_node, from_port, to_node, to_port); + undo_redo->add_do_method(graph_plugin.ptr(), "disconnect_nodes", type, from_node, from_port, to_node, to_port); + undo_redo->add_undo_method(graph_plugin.ptr(), "connect_nodes", type, from_node, from_port, to_node, to_port); + undo_redo->add_do_method(visual_shader.ptr(), "connect_nodes_forced", type, from_node, from_port, to_node, to_port - 1); undo_redo->add_undo_method(visual_shader.ptr(), "disconnect_nodes", type, from_node, from_port, to_node, to_port - 1); + + undo_redo->add_do_method(graph_plugin.ptr(), "connect_nodes", type, from_node, from_port, to_node, to_port - 1); + undo_redo->add_undo_method(graph_plugin.ptr(), "disconnect_nodes", type, from_node, from_port, to_node, to_port - 1); } } } @@ -1002,23 +1456,20 @@ void VisualShaderEditor::_remove_input_port(int p_node, int p_port) { undo_redo->add_do_method(node.ptr(), "remove_input_port", p_port); undo_redo->add_undo_method(node.ptr(), "add_input_port", p_port, (int)node->get_input_port_type(p_port), node->get_input_port_name(p_port)); - undo_redo->add_do_method(this, "_update_graph"); - undo_redo->add_undo_method(this, "_update_graph"); - - undo_redo->add_do_method(this, "_rebuild"); - undo_redo->add_undo_method(this, "_rebuild"); + undo_redo->add_do_method(graph_plugin.ptr(), "update_node", type, p_node); + undo_redo->add_undo_method(graph_plugin.ptr(), "update_node", type, p_node); undo_redo->commit_action(); } void VisualShaderEditor::_remove_output_port(int p_node, int p_port) { - VisualShader::Type type = VisualShader::Type(edit_type->get_selected()); + VisualShader::Type type = get_current_shader_type(); Ref<VisualShaderNodeGroupBase> node = visual_shader->get_node(type, p_node); if (node.is_null()) { return; } - undo_redo->create_action(TTR("Remove output port")); + undo_redo->create_action(TTR("Remove Output Port")); List<VisualShader::Connection> conns; visual_shader->get_node_connections(type, &conns); @@ -1032,75 +1483,91 @@ void VisualShaderEditor::_remove_output_port(int p_node, int p_port) { if (from_port == p_port) { undo_redo->add_do_method(visual_shader.ptr(), "disconnect_nodes", type, from_node, from_port, to_node, to_port); undo_redo->add_undo_method(visual_shader.ptr(), "connect_nodes_forced", type, from_node, from_port, to_node, to_port); + + undo_redo->add_do_method(graph_plugin.ptr(), "disconnect_nodes", type, from_node, from_port, to_node, to_port); + undo_redo->add_undo_method(graph_plugin.ptr(), "connect_nodes", type, from_node, from_port, to_node, to_port); } else if (from_port > p_port) { undo_redo->add_do_method(visual_shader.ptr(), "disconnect_nodes", type, from_node, from_port, to_node, to_port); undo_redo->add_undo_method(visual_shader.ptr(), "connect_nodes_forced", type, from_node, from_port, to_node, to_port); + undo_redo->add_do_method(graph_plugin.ptr(), "disconnect_nodes", type, from_node, from_port, to_node, to_port); + undo_redo->add_undo_method(graph_plugin.ptr(), "connect_nodes", type, from_node, from_port, to_node, to_port); + undo_redo->add_do_method(visual_shader.ptr(), "connect_nodes_forced", type, from_node, from_port - 1, to_node, to_port); undo_redo->add_undo_method(visual_shader.ptr(), "disconnect_nodes", type, from_node, from_port - 1, to_node, to_port); + + undo_redo->add_do_method(graph_plugin.ptr(), "connect_nodes", type, from_node, from_port - 1, to_node, to_port); + undo_redo->add_undo_method(graph_plugin.ptr(), "disconnect_nodes", type, from_node, from_port - 1, to_node, to_port); } } } + int preview_port = node->get_output_port_for_preview(); + if (preview_port != -1) { + if (preview_port == p_port) { + undo_redo->add_do_method(node.ptr(), "set_output_port_for_preview", -1); + undo_redo->add_undo_method(node.ptr(), "set_output_port_for_preview", preview_port); + } else if (preview_port > p_port) { + undo_redo->add_do_method(node.ptr(), "set_output_port_for_preview", preview_port - 1); + undo_redo->add_undo_method(node.ptr(), "set_output_port_for_preview", preview_port); + } + } + undo_redo->add_do_method(node.ptr(), "remove_output_port", p_port); undo_redo->add_undo_method(node.ptr(), "add_output_port", p_port, (int)node->get_output_port_type(p_port), node->get_output_port_name(p_port)); - undo_redo->add_do_method(this, "_update_graph"); - undo_redo->add_undo_method(this, "_update_graph"); - - undo_redo->add_do_method(this, "_rebuild"); - undo_redo->add_undo_method(this, "_rebuild"); + undo_redo->add_do_method(graph_plugin.ptr(), "update_node", type, p_node); + undo_redo->add_undo_method(graph_plugin.ptr(), "update_node", type, p_node); undo_redo->commit_action(); } -void VisualShaderEditor::_expression_focus_out(Object *text_edit, int p_node) { - VisualShader::Type type = VisualShader::Type(edit_type->get_selected()); +void VisualShaderEditor::_expression_focus_out(Object *code_edit, int p_node) { + VisualShader::Type type = get_current_shader_type(); Ref<VisualShaderNodeExpression> node = visual_shader->get_node(type, p_node); if (node.is_null()) { return; } - TextEdit *expression_box = Object::cast_to<TextEdit>(text_edit); + CodeEdit *expression_box = Object::cast_to<CodeEdit>(code_edit); if (node->get_expression() == expression_box->get_text()) { return; } - undo_redo->create_action(TTR("Set expression")); + undo_redo->create_action(TTR("Set VisualShader Expression")); undo_redo->add_do_method(node.ptr(), "set_expression", expression_box->get_text()); undo_redo->add_undo_method(node.ptr(), "set_expression", node->get_expression()); - undo_redo->add_do_method(this, "_rebuild"); - undo_redo->add_undo_method(this, "_rebuild"); + undo_redo->add_do_method(graph_plugin.ptr(), "set_expression", type, p_node, expression_box->get_text()); + undo_redo->add_undo_method(graph_plugin.ptr(), "set_expression", type, p_node, node->get_expression()); undo_redo->commit_action(); } -void VisualShaderEditor::_rebuild() { - if (visual_shader != nullptr) { - EditorNode::get_singleton()->get_log()->clear(); - visual_shader->rebuild(); - } -} - void VisualShaderEditor::_set_node_size(int p_type, int p_node, const Vector2 &p_size) { VisualShader::Type type = VisualShader::Type(p_type); - Ref<VisualShaderNode> node = visual_shader->get_node(type, p_node); + Ref<VisualShaderNodeResizableBase> node = visual_shader->get_node(type, p_node); if (node.is_null()) { return; } - Ref<VisualShaderNodeGroupBase> group_node = Object::cast_to<VisualShaderNodeGroupBase>(node.ptr()); - - if (group_node.is_null()) { - return; + Size2 size = p_size; + if (!node->is_allow_v_resize()) { + size.y = 0; } - Vector2 size = p_size; + node->set_size(size); - group_node->set_size(size); + if (get_current_shader_type() == type) { + Ref<VisualShaderNodeExpression> expression_node = Object::cast_to<VisualShaderNodeExpression>(node.ptr()); + Control *text_box = nullptr; + if (!expression_node.is_null()) { + text_box = expression_node->get_control(0); + if (text_box) { + text_box->set_custom_minimum_size(Size2(0, 0)); + } + } - GraphNode *gn = nullptr; - if (edit_type->get_selected() == p_type) { // check - otherwise the error will be emitted + GraphNode *gn = nullptr; Node *node2 = graph->get_node(itos(p_node)); gn = Object::cast_to<GraphNode>(node2); if (!gn) { @@ -1109,135 +1576,96 @@ void VisualShaderEditor::_set_node_size(int p_type, int p_node, const Vector2 &p gn->set_custom_minimum_size(size); gn->set_size(Size2(1, 1)); - } - Ref<VisualShaderNodeExpression> expression_node = Object::cast_to<VisualShaderNodeExpression>(node.ptr()); - if (!expression_node.is_null()) { - Control *text_box = expression_node->get_control(0); - Size2 box_size = size; - if (gn != nullptr) { - if (box_size.x < 150 * EDSCALE || box_size.y < 0) { - box_size.x = gn->get_size().x; + if (!expression_node.is_null() && text_box) { + Size2 box_size = size; + if (gn != nullptr) { + if (box_size.x < 150 * EDSCALE || box_size.y < 0) { + box_size.x = gn->get_size().x; + } } + box_size.x -= text_box->get_offset(SIDE_LEFT); + box_size.x -= 28 * EDSCALE; + box_size.y -= text_box->get_offset(SIDE_TOP); + box_size.y -= 28 * EDSCALE; + text_box->set_custom_minimum_size(Size2(box_size.x, box_size.y)); + text_box->set_size(Size2(1, 1)); } - box_size.x -= text_box->get_margin(MARGIN_LEFT); - box_size.x -= 28 * EDSCALE; - box_size.y -= text_box->get_margin(MARGIN_TOP); - box_size.y -= 28 * EDSCALE; - text_box->set_custom_minimum_size(Size2(box_size.x, box_size.y)); - text_box->set_size(Size2(1, 1)); } } void VisualShaderEditor::_node_resized(const Vector2 &p_new_size, int p_type, int p_node) { - VisualShader::Type type = VisualShader::Type(p_type); - Ref<VisualShaderNodeGroupBase> node = visual_shader->get_node(type, p_node); + Ref<VisualShaderNodeResizableBase> node = visual_shader->get_node(VisualShader::Type(p_type), p_node); if (node.is_null()) { return; } - undo_redo->create_action(TTR("Resize VisualShader node"), UndoRedo::MERGE_ENDS); + undo_redo->create_action(TTR("Resize VisualShader Node"), UndoRedo::MERGE_ENDS); undo_redo->add_do_method(this, "_set_node_size", p_type, p_node, p_new_size); undo_redo->add_undo_method(this, "_set_node_size", p_type, p_node, node->get_size()); undo_redo->commit_action(); } void VisualShaderEditor::_preview_select_port(int p_node, int p_port) { - VisualShader::Type type = VisualShader::Type(edit_type->get_selected()); + VisualShader::Type type = get_current_shader_type(); Ref<VisualShaderNode> node = visual_shader->get_node(type, p_node); if (node.is_null()) { return; } - + int prev_port = node->get_output_port_for_preview(); if (node->get_output_port_for_preview() == p_port) { p_port = -1; //toggle it } - undo_redo->create_action(TTR("Set Uniform Name")); + undo_redo->create_action(p_port == -1 ? TTR("Hide Port Preview") : TTR("Show Port Preview")); undo_redo->add_do_method(node.ptr(), "set_output_port_for_preview", p_port); - undo_redo->add_undo_method(node.ptr(), "set_output_port_for_preview", node->get_output_port_for_preview()); - undo_redo->add_do_method(this, "_update_graph"); - undo_redo->add_undo_method(this, "_update_graph"); + undo_redo->add_undo_method(node.ptr(), "set_output_port_for_preview", prev_port); + undo_redo->add_do_method(graph_plugin.ptr(), "update_node", (int)type, p_node); + undo_redo->add_undo_method(graph_plugin.ptr(), "update_node", (int)type, p_node); undo_redo->commit_action(); } -void VisualShaderEditor::_line_edit_changed(const String &p_text, Object *line_edit, int p_node_id) { - VisualShader::Type type = VisualShader::Type(edit_type->get_selected()); +void VisualShaderEditor::_uniform_line_edit_changed(const String &p_text, int p_node_id) { + VisualShader::Type type = get_current_shader_type(); Ref<VisualShaderNodeUniform> node = visual_shader->get_node(type, p_node_id); ERR_FAIL_COND(!node.is_valid()); String validated_name = visual_shader->validate_uniform_name(p_text, node); - updating = true; + if (validated_name == node->get_uniform_name()) { + return; + } + undo_redo->create_action(TTR("Set Uniform Name")); undo_redo->add_do_method(node.ptr(), "set_uniform_name", validated_name); undo_redo->add_undo_method(node.ptr(), "set_uniform_name", node->get_uniform_name()); - undo_redo->add_do_method(this, "_update_graph"); - undo_redo->add_undo_method(this, "_update_graph"); - undo_redo->commit_action(); - updating = false; + undo_redo->add_do_method(graph_plugin.ptr(), "set_uniform_name", type, p_node_id, validated_name); + undo_redo->add_undo_method(graph_plugin.ptr(), "set_uniform_name", type, p_node_id, node->get_uniform_name()); + + undo_redo->add_do_method(this, "_update_uniforms", true); + undo_redo->add_undo_method(this, "_update_uniforms", true); - Object::cast_to<LineEdit>(line_edit)->set_text(validated_name); + Set<String> changed_names; + changed_names.insert(node->get_uniform_name()); + _update_uniform_refs(changed_names); + + undo_redo->commit_action(); } -void VisualShaderEditor::_line_edit_focus_out(Object *line_edit, int p_node_id) { - String text = Object::cast_to<LineEdit>(line_edit)->get_text(); - _line_edit_changed(text, line_edit, p_node_id); +void VisualShaderEditor::_uniform_line_edit_focus_out(Object *line_edit, int p_node_id) { + _uniform_line_edit_changed(Object::cast_to<LineEdit>(line_edit)->get_text(), p_node_id); } void VisualShaderEditor::_port_name_focus_out(Object *line_edit, int p_node_id, int p_port_id, bool p_output) { - VisualShader::Type type = VisualShader::Type(edit_type->get_selected()); - - Ref<VisualShaderNodeGroupBase> node = visual_shader->get_node(type, p_node_id); - ERR_FAIL_COND(!node.is_valid()); - - String text = Object::cast_to<LineEdit>(line_edit)->get_text(); - - if (!p_output) { - if (node->get_input_port_name(p_port_id) == text) { - return; - } - } else { - if (node->get_output_port_name(p_port_id) == text) { - return; - } - } - - List<String> input_names; - List<String> output_names; - - for (int i = 0; i < node->get_input_port_count(); i++) { - if (!p_output && i == p_port_id) { - continue; - } - input_names.push_back(node->get_input_port_name(i)); - } - for (int i = 0; i < node->get_output_port_count(); i++) { - if (p_output && i == p_port_id) { - continue; - } - output_names.push_back(node->get_output_port_name(i)); - } - - String validated_name = visual_shader->validate_port_name(text, input_names, output_names); - if (validated_name == "") { - if (!p_output) { - Object::cast_to<LineEdit>(line_edit)->set_text(node->get_input_port_name(p_port_id)); - } else { - Object::cast_to<LineEdit>(line_edit)->set_text(node->get_output_port_name(p_port_id)); - } - return; - } - if (!p_output) { - _change_input_port_name(validated_name, line_edit, p_node_id, p_port_id); + _change_input_port_name(Object::cast_to<LineEdit>(line_edit)->get_text(), line_edit, p_node_id, p_port_id); } else { - _change_output_port_name(validated_name, line_edit, p_node_id, p_port_id); + _change_output_port_name(Object::cast_to<LineEdit>(line_edit)->get_text(), line_edit, p_node_id, p_port_id); } } void VisualShaderEditor::_port_edited() { - VisualShader::Type type = VisualShader::Type(edit_type->get_selected()); + VisualShader::Type type = get_current_shader_type(); Variant value = property_editor->get_variant(); Ref<VisualShaderNode> vsn = visual_shader->get_node(type, editing_node); @@ -1246,15 +1674,15 @@ void VisualShaderEditor::_port_edited() { undo_redo->create_action(TTR("Set Input Default Port")); undo_redo->add_do_method(vsn.ptr(), "set_input_port_default_value", editing_port, value); undo_redo->add_undo_method(vsn.ptr(), "set_input_port_default_value", editing_port, vsn->get_input_port_default_value(editing_port)); - undo_redo->add_do_method(this, "_update_graph"); - undo_redo->add_undo_method(this, "_update_graph"); + undo_redo->add_do_method(graph_plugin.ptr(), "set_input_port_default_value", type, editing_node, editing_port, value); + undo_redo->add_undo_method(graph_plugin.ptr(), "set_input_port_default_value", type, editing_node, editing_port, vsn->get_input_port_default_value(editing_port)); undo_redo->commit_action(); property_editor->hide(); } void VisualShaderEditor::_edit_port_default_input(Object *p_button, int p_node, int p_port) { - VisualShader::Type type = VisualShader::Type(edit_type->get_selected()); + VisualShader::Type type = get_current_shader_type(); Ref<VisualShaderNode> vsn = visual_shader->get_node(type, p_node); @@ -1284,113 +1712,245 @@ void VisualShaderEditor::_add_custom_node(const String &p_path) { } } -void VisualShaderEditor::_add_texture_node(const String &p_path) { - VisualShaderNodeTexture *texture = (VisualShaderNodeTexture *)_add_node(texture_node_option_idx, -1); - texture->set_texture(ResourceLoader::load(p_path)); +void VisualShaderEditor::_add_cubemap_node(const String &p_path) { + VisualShaderNodeCubemap *cubemap = (VisualShaderNodeCubemap *)_add_node(cubemap_node_option_idx, -1); + cubemap->set_cube_map(ResourceLoader::load(p_path)); } -VisualShaderNode *VisualShaderEditor::_add_node(int p_idx, int p_op_idx) { - ERR_FAIL_INDEX_V(p_idx, add_options.size(), nullptr); +void VisualShaderEditor::_add_texture2d_node(const String &p_path) { + VisualShaderNodeTexture *texture2d = (VisualShaderNodeTexture *)_add_node(texture2d_node_option_idx, -1); + texture2d->set_texture(ResourceLoader::load(p_path)); +} - Ref<VisualShaderNode> vsnode; +void VisualShaderEditor::_add_texture2d_array_node(const String &p_path) { + VisualShaderNodeTexture2DArray *texture2d_array = (VisualShaderNodeTexture2DArray *)_add_node(texture2d_array_node_option_idx, -1); + texture2d_array->set_texture_array(ResourceLoader::load(p_path)); +} - bool is_custom = add_options[p_idx].is_custom; +void VisualShaderEditor::_add_texture3d_node(const String &p_path) { + VisualShaderNodeTexture3D *texture3d = (VisualShaderNodeTexture3D *)_add_node(texture3d_node_option_idx, -1); + texture3d->set_texture(ResourceLoader::load(p_path)); +} - if (!is_custom && add_options[p_idx].type != String()) { - VisualShaderNode *vsn = Object::cast_to<VisualShaderNode>(ClassDB::instance(add_options[p_idx].type)); - ERR_FAIL_COND_V(!vsn, nullptr); +void VisualShaderEditor::_add_curve_node(const String &p_path) { + VisualShaderNodeCurveTexture *curve = (VisualShaderNodeCurveTexture *)_add_node(curve_node_option_idx, -1); + curve->set_texture(ResourceLoader::load(p_path)); +} - VisualShaderNodeFloatConstant *constant = Object::cast_to<VisualShaderNodeFloatConstant>(vsn); +void VisualShaderEditor::_setup_node(VisualShaderNode *p_node, int p_op_idx) { + // FLOAT_OP + { + VisualShaderNodeFloatOp *floatOp = Object::cast_to<VisualShaderNodeFloatOp>(p_node); - if (constant) { - if ((int)add_options[p_idx].value != -1) { - constant->set_constant(add_options[p_idx].value); - } + if (floatOp) { + floatOp->set_operator((VisualShaderNodeFloatOp::Operator)p_op_idx); + return; } + } - if (p_op_idx != -1) { - VisualShaderNodeInput *input = Object::cast_to<VisualShaderNodeInput>(vsn); + // FLOAT_FUNC + { + VisualShaderNodeFloatFunc *floatFunc = Object::cast_to<VisualShaderNodeFloatFunc>(p_node); - if (input) { - input->set_input_name(add_options[p_idx].sub_func_str); - } + if (floatFunc) { + floatFunc->set_function((VisualShaderNodeFloatFunc::Function)p_op_idx); + return; + } + } - VisualShaderNodeIs *is = Object::cast_to<VisualShaderNodeIs>(vsn); + // VECTOR_OP + { + VisualShaderNodeVectorOp *vecOp = Object::cast_to<VisualShaderNodeVectorOp>(p_node); - if (is) { - is->set_function((VisualShaderNodeIs::Function)p_op_idx); - } + if (vecOp) { + vecOp->set_operator((VisualShaderNodeVectorOp::Operator)p_op_idx); + return; + } + } - VisualShaderNodeCompare *cmp = Object::cast_to<VisualShaderNodeCompare>(vsn); + // VECTOR_FUNC + { + VisualShaderNodeVectorFunc *vecFunc = Object::cast_to<VisualShaderNodeVectorFunc>(p_node); - if (cmp) { - cmp->set_function((VisualShaderNodeCompare::Function)p_op_idx); - } + if (vecFunc) { + vecFunc->set_function((VisualShaderNodeVectorFunc::Function)p_op_idx); + return; + } + } - VisualShaderNodeColorOp *colorOp = Object::cast_to<VisualShaderNodeColorOp>(vsn); + // COLOR_OP + { + VisualShaderNodeColorOp *colorOp = Object::cast_to<VisualShaderNodeColorOp>(p_node); - if (colorOp) { - colorOp->set_operator((VisualShaderNodeColorOp::Operator)p_op_idx); - } + if (colorOp) { + colorOp->set_operator((VisualShaderNodeColorOp::Operator)p_op_idx); + return; + } + } - VisualShaderNodeColorFunc *colorFunc = Object::cast_to<VisualShaderNodeColorFunc>(vsn); + // COLOR_FUNC + { + VisualShaderNodeColorFunc *colorFunc = Object::cast_to<VisualShaderNodeColorFunc>(p_node); - if (colorFunc) { - colorFunc->set_function((VisualShaderNodeColorFunc::Function)p_op_idx); - } + if (colorFunc) { + colorFunc->set_function((VisualShaderNodeColorFunc::Function)p_op_idx); + return; + } + } - VisualShaderNodeFloatOp *floatOp = Object::cast_to<VisualShaderNodeFloatOp>(vsn); + // INT_OP + { + VisualShaderNodeIntOp *intOp = Object::cast_to<VisualShaderNodeIntOp>(p_node); - if (floatOp) { - floatOp->set_operator((VisualShaderNodeFloatOp::Operator)p_op_idx); - } + if (intOp) { + intOp->set_operator((VisualShaderNodeIntOp::Operator)p_op_idx); + return; + } + } - VisualShaderNodeIntOp *intOp = Object::cast_to<VisualShaderNodeIntOp>(vsn); + // INT_FUNC + { + VisualShaderNodeIntFunc *intFunc = Object::cast_to<VisualShaderNodeIntFunc>(p_node); - if (intOp) { - intOp->set_operator((VisualShaderNodeIntOp::Operator)p_op_idx); - } + if (intFunc) { + intFunc->set_function((VisualShaderNodeIntFunc::Function)p_op_idx); + return; + } + } - VisualShaderNodeFloatFunc *floatFunc = Object::cast_to<VisualShaderNodeFloatFunc>(vsn); + // TRANSFORM_FUNC + { + VisualShaderNodeTransformFunc *matFunc = Object::cast_to<VisualShaderNodeTransformFunc>(p_node); - if (floatFunc) { - floatFunc->set_function((VisualShaderNodeFloatFunc::Function)p_op_idx); - } + if (matFunc) { + matFunc->set_function((VisualShaderNodeTransformFunc::Function)p_op_idx); + return; + } + } - VisualShaderNodeIntFunc *intFunc = Object::cast_to<VisualShaderNodeIntFunc>(vsn); + // IS + { + VisualShaderNodeIs *is = Object::cast_to<VisualShaderNodeIs>(p_node); - if (intFunc) { - intFunc->set_function((VisualShaderNodeIntFunc::Function)p_op_idx); - } + if (is) { + is->set_function((VisualShaderNodeIs::Function)p_op_idx); + return; + } + } - VisualShaderNodeVectorOp *vecOp = Object::cast_to<VisualShaderNodeVectorOp>(vsn); + // COMPARE + { + VisualShaderNodeCompare *cmp = Object::cast_to<VisualShaderNodeCompare>(p_node); - if (vecOp) { - vecOp->set_operator((VisualShaderNodeVectorOp::Operator)p_op_idx); - } + if (cmp) { + cmp->set_function((VisualShaderNodeCompare::Function)p_op_idx); + return; + } + } - VisualShaderNodeVectorFunc *vecFunc = Object::cast_to<VisualShaderNodeVectorFunc>(vsn); + // DERIVATIVE + { + VisualShaderNodeScalarDerivativeFunc *sderFunc = Object::cast_to<VisualShaderNodeScalarDerivativeFunc>(p_node); - if (vecFunc) { - vecFunc->set_function((VisualShaderNodeVectorFunc::Function)p_op_idx); - } + if (sderFunc) { + sderFunc->set_function((VisualShaderNodeScalarDerivativeFunc::Function)p_op_idx); + return; + } - VisualShaderNodeTransformFunc *matFunc = Object::cast_to<VisualShaderNodeTransformFunc>(vsn); + VisualShaderNodeVectorDerivativeFunc *vderFunc = Object::cast_to<VisualShaderNodeVectorDerivativeFunc>(p_node); - if (matFunc) { - matFunc->set_function((VisualShaderNodeTransformFunc::Function)p_op_idx); - } + if (vderFunc) { + vderFunc->set_function((VisualShaderNodeVectorDerivativeFunc::Function)p_op_idx); + return; + } + } - VisualShaderNodeScalarDerivativeFunc *sderFunc = Object::cast_to<VisualShaderNodeScalarDerivativeFunc>(vsn); + // MIX + { + VisualShaderNodeMix *mix = Object::cast_to<VisualShaderNodeMix>(p_node); - if (sderFunc) { - sderFunc->set_function((VisualShaderNodeScalarDerivativeFunc::Function)p_op_idx); - } + if (mix) { + mix->set_op_type((VisualShaderNodeMix::OpType)p_op_idx); + return; + } + } + + // CLAMP + { + VisualShaderNodeClamp *clampFunc = Object::cast_to<VisualShaderNodeClamp>(p_node); + + if (clampFunc) { + clampFunc->set_op_type((VisualShaderNodeClamp::OpType)p_op_idx); + return; + } + } + + // SWITCH + { + VisualShaderNodeSwitch *switchFunc = Object::cast_to<VisualShaderNodeSwitch>(p_node); + + if (switchFunc) { + switchFunc->set_op_type((VisualShaderNodeSwitch::OpType)p_op_idx); + return; + } + } + + // SMOOTHSTEP + { + VisualShaderNodeSmoothStep *smoothStepFunc = Object::cast_to<VisualShaderNodeSmoothStep>(p_node); + + if (smoothStepFunc) { + smoothStepFunc->set_op_type((VisualShaderNodeSmoothStep::OpType)p_op_idx); + return; + } + } + + // STEP + { + VisualShaderNodeStep *stepFunc = Object::cast_to<VisualShaderNodeStep>(p_node); + + if (stepFunc) { + stepFunc->set_op_type((VisualShaderNodeStep::OpType)p_op_idx); + return; + } + } + + // MULTIPLY_ADD + { + VisualShaderNodeMultiplyAdd *fmaFunc = Object::cast_to<VisualShaderNodeMultiplyAdd>(p_node); + + if (fmaFunc) { + fmaFunc->set_op_type((VisualShaderNodeMultiplyAdd::OpType)p_op_idx); + } + } +} + +VisualShaderNode *VisualShaderEditor::_add_node(int p_idx, int p_op_idx) { + ERR_FAIL_INDEX_V(p_idx, add_options.size(), nullptr); + + Ref<VisualShaderNode> vsnode; + + bool is_custom = add_options[p_idx].is_custom; - VisualShaderNodeVectorDerivativeFunc *vderFunc = Object::cast_to<VisualShaderNodeVectorDerivativeFunc>(vsn); + if (!is_custom && add_options[p_idx].type != String()) { + VisualShaderNode *vsn = Object::cast_to<VisualShaderNode>(ClassDB::instance(add_options[p_idx].type)); + ERR_FAIL_COND_V(!vsn, nullptr); + + VisualShaderNodeFloatConstant *constant = Object::cast_to<VisualShaderNodeFloatConstant>(vsn); + + if (constant) { + if ((int)add_options[p_idx].value != -1) { + constant->set_constant(add_options[p_idx].value); + } + } else { + if (p_op_idx != -1) { + VisualShaderNodeInput *input = Object::cast_to<VisualShaderNodeInput>(vsn); - if (vderFunc) { - vderFunc->set_function((VisualShaderNodeVectorDerivativeFunc::Function)p_op_idx); + if (input) { + input->set_input_name(add_options[p_idx].sub_func_str); + } else { + _setup_node(vsn, p_op_idx); + } } } @@ -1414,62 +1974,156 @@ VisualShaderNode *VisualShaderEditor::_add_node(int p_idx, int p_op_idx) { } saved_node_pos_dirty = false; - VisualShader::Type type = VisualShader::Type(edit_type->get_selected()); + VisualShader::Type type = get_current_shader_type(); int id_to_use = visual_shader->get_valid_node_id(type); undo_redo->create_action(TTR("Add Node to Visual Shader")); undo_redo->add_do_method(visual_shader.ptr(), "add_node", type, vsnode, position, id_to_use); undo_redo->add_undo_method(visual_shader.ptr(), "remove_node", type, id_to_use); + undo_redo->add_do_method(graph_plugin.ptr(), "add_node", type, id_to_use); + undo_redo->add_undo_method(graph_plugin.ptr(), "remove_node", type, id_to_use); VisualShaderNodeExpression *expr = Object::cast_to<VisualShaderNodeExpression>(vsnode.ptr()); if (expr) { undo_redo->add_do_method(expr, "set_size", Size2(250 * EDSCALE, 150 * EDSCALE)); } + bool created_expression_port = false; + if (to_node != -1 && to_slot != -1) { - if (vsnode->get_output_port_count() > 0) { + VisualShaderNode::PortType input_port_type = visual_shader->get_node(type, to_node)->get_input_port_type(to_slot); + + if (expr && expr->is_editable() && input_port_type != VisualShaderNode::PORT_TYPE_SAMPLER) { + undo_redo->add_do_method(expr, "add_output_port", 0, input_port_type, "output0"); + undo_redo->add_undo_method(expr, "remove_output_port", 0); + + String initial_expression_code; + + switch (input_port_type) { + case VisualShaderNode::PORT_TYPE_SCALAR: + initial_expression_code = "output0 = 1.0;"; + break; + case VisualShaderNode::PORT_TYPE_SCALAR_INT: + initial_expression_code = "output0 = 1;"; + break; + case VisualShaderNode::PORT_TYPE_VECTOR: + initial_expression_code = "output0 = vec3(1.0, 1.0, 1.0);"; + break; + case VisualShaderNode::PORT_TYPE_BOOLEAN: + initial_expression_code = "output0 = true;"; + break; + case VisualShaderNode::PORT_TYPE_TRANSFORM: + initial_expression_code = "output0 = mat4(1.0);"; + break; + default: + break; + } + + undo_redo->add_do_method(expr, "set_expression", initial_expression_code); + undo_redo->add_do_method(graph_plugin.ptr(), "update_node", type, id_to_use); + + created_expression_port = true; + } + if (vsnode->get_output_port_count() > 0 || created_expression_port) { int _from_node = id_to_use; int _from_slot = 0; - if (visual_shader->is_port_types_compatible(vsnode->get_output_port_type(_from_slot), visual_shader->get_node(type, to_node)->get_input_port_type(to_slot))) { + if (created_expression_port) { undo_redo->add_do_method(visual_shader.ptr(), "connect_nodes", type, _from_node, _from_slot, to_node, to_slot); undo_redo->add_undo_method(visual_shader.ptr(), "disconnect_nodes", type, _from_node, _from_slot, to_node, to_slot); + undo_redo->add_do_method(graph_plugin.ptr(), "connect_nodes", type, _from_node, _from_slot, to_node, to_slot); + undo_redo->add_undo_method(graph_plugin.ptr(), "disconnect_nodes", type, _from_node, _from_slot, to_node, to_slot); + } else { + // Attempting to connect to the first correct port. + for (int i = 0; i < vsnode->get_output_port_count(); i++) { + if (visual_shader->is_port_types_compatible(vsnode->get_output_port_type(i), input_port_type)) { + undo_redo->add_do_method(visual_shader.ptr(), "connect_nodes", type, _from_node, i, to_node, to_slot); + undo_redo->add_undo_method(visual_shader.ptr(), "disconnect_nodes", type, _from_node, i, to_node, to_slot); + undo_redo->add_do_method(graph_plugin.ptr(), "connect_nodes", type, _from_node, i, to_node, to_slot); + undo_redo->add_undo_method(graph_plugin.ptr(), "disconnect_nodes", type, _from_node, i, to_node, to_slot); + break; + } + } } } } else if (from_node != -1 && from_slot != -1) { - if (vsnode->get_input_port_count() > 0) { + VisualShaderNode::PortType output_port_type = visual_shader->get_node(type, from_node)->get_output_port_type(from_slot); + + if (expr && expr->is_editable()) { + undo_redo->add_do_method(expr, "add_input_port", 0, output_port_type, "input0"); + undo_redo->add_undo_method(expr, "remove_input_port", 0); + undo_redo->add_do_method(graph_plugin.ptr(), "update_node", type, id_to_use); + + created_expression_port = true; + } + + if (vsnode->get_input_port_count() > 0 || created_expression_port) { int _to_node = id_to_use; int _to_slot = 0; - if (visual_shader->is_port_types_compatible(visual_shader->get_node(type, from_node)->get_output_port_type(from_slot), vsnode->get_input_port_type(_to_slot))) { - undo_redo->add_do_method(visual_shader.ptr(), "connect_nodes", type, from_node, from_slot, _to_node, _to_slot); + if (created_expression_port) { undo_redo->add_undo_method(visual_shader.ptr(), "disconnect_nodes", type, from_node, from_slot, _to_node, _to_slot); + undo_redo->add_do_method(visual_shader.ptr(), "connect_nodes", type, from_node, from_slot, _to_node, _to_slot); + undo_redo->add_undo_method(graph_plugin.ptr(), "disconnect_nodes", type, from_node, from_slot, _to_node, _to_slot); + undo_redo->add_do_method(graph_plugin.ptr(), "connect_nodes", type, from_node, from_slot, _to_node, _to_slot); + } else { + // Attempting to connect to the first correct port. + for (int i = 0; i < vsnode->get_input_port_count(); i++) { + if (visual_shader->is_port_types_compatible(output_port_type, vsnode->get_input_port_type(i))) { + undo_redo->add_undo_method(visual_shader.ptr(), "disconnect_nodes", type, from_node, from_slot, _to_node, i); + undo_redo->add_do_method(visual_shader.ptr(), "connect_nodes", type, from_node, from_slot, _to_node, i); + undo_redo->add_undo_method(graph_plugin.ptr(), "disconnect_nodes", type, from_node, from_slot, _to_node, i); + undo_redo->add_do_method(graph_plugin.ptr(), "connect_nodes", type, from_node, from_slot, _to_node, i); + break; + } + } } } } - undo_redo->add_do_method(this, "_update_graph"); - undo_redo->add_undo_method(this, "_update_graph"); + VisualShaderNodeUniform *uniform = Object::cast_to<VisualShaderNodeUniform>(vsnode.ptr()); + if (uniform) { + undo_redo->add_do_method(this, "_update_uniforms", true); + undo_redo->add_undo_method(this, "_update_uniforms", true); + } + + VisualShaderNodeCurveTexture *curve = Object::cast_to<VisualShaderNodeCurveTexture>(vsnode.ptr()); + if (curve) { + graph_plugin->call_deferred("update_curve", id_to_use); + } + undo_redo->commit_action(); return vsnode.ptr(); } void VisualShaderEditor::_node_dragged(const Vector2 &p_from, const Vector2 &p_to, int p_node) { - VisualShader::Type type = VisualShader::Type(edit_type->get_selected()); + VisualShader::Type type = get_current_shader_type(); + drag_buffer.push_back({ type, p_node, p_from, p_to }); + if (!drag_dirty) { + call_deferred("_nodes_dragged"); + } + drag_dirty = true; +} - updating = true; - undo_redo->create_action(TTR("Node Moved")); - undo_redo->add_do_method(visual_shader.ptr(), "set_node_position", type, p_node, p_to); - undo_redo->add_undo_method(visual_shader.ptr(), "set_node_position", type, p_node, p_from); - undo_redo->add_do_method(this, "_update_graph"); - undo_redo->add_undo_method(this, "_update_graph"); +void VisualShaderEditor::_nodes_dragged() { + drag_dirty = false; + + undo_redo->create_action(TTR("Node(s) Moved")); + + for (List<DragOp>::Element *E = drag_buffer.front(); E; E = E->next()) { + undo_redo->add_do_method(visual_shader.ptr(), "set_node_position", E->get().type, E->get().node, E->get().to); + undo_redo->add_undo_method(visual_shader.ptr(), "set_node_position", E->get().type, E->get().node, E->get().from); + undo_redo->add_do_method(graph_plugin.ptr(), "set_node_position", E->get().type, E->get().node, E->get().to); + undo_redo->add_undo_method(graph_plugin.ptr(), "set_node_position", E->get().type, E->get().node, E->get().from); + } + + drag_buffer.clear(); undo_redo->commit_action(); - updating = false; } void VisualShaderEditor::_connection_request(const String &p_from, int p_from_index, const String &p_to, int p_to_index) { - VisualShader::Type type = VisualShader::Type(edit_type->get_selected()); + VisualShader::Type type = get_current_shader_type(); int from = p_from.to_int(); int to = p_to.to_int(); @@ -1487,32 +2141,36 @@ void VisualShaderEditor::_connection_request(const String &p_from, int p_from_in if (E->get().to_node == to && E->get().to_port == p_to_index) { undo_redo->add_do_method(visual_shader.ptr(), "disconnect_nodes", type, E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port); undo_redo->add_undo_method(visual_shader.ptr(), "connect_nodes", type, E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port); + undo_redo->add_do_method(graph_plugin.ptr(), "disconnect_nodes", type, E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port); + undo_redo->add_undo_method(graph_plugin.ptr(), "connect_nodes", type, E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port); } } undo_redo->add_do_method(visual_shader.ptr(), "connect_nodes", type, from, p_from_index, to, p_to_index); undo_redo->add_undo_method(visual_shader.ptr(), "disconnect_nodes", type, from, p_from_index, to, p_to_index); - undo_redo->add_do_method(this, "_update_graph"); - undo_redo->add_undo_method(this, "_update_graph"); + undo_redo->add_do_method(graph_plugin.ptr(), "connect_nodes", type, from, p_from_index, to, p_to_index); + undo_redo->add_undo_method(graph_plugin.ptr(), "disconnect_nodes", type, from, p_from_index, to, p_to_index); + undo_redo->add_do_method(graph_plugin.ptr(), "update_node", (int)type, to); + undo_redo->add_undo_method(graph_plugin.ptr(), "update_node", (int)type, to); undo_redo->commit_action(); } void VisualShaderEditor::_disconnection_request(const String &p_from, int p_from_index, const String &p_to, int p_to_index) { graph->disconnect_node(p_from, p_from_index, p_to, p_to_index); - VisualShader::Type type = VisualShader::Type(edit_type->get_selected()); + VisualShader::Type type = get_current_shader_type(); int from = p_from.to_int(); int to = p_to.to_int(); - //updating = true; seems graph edit can handle this, no need to protect undo_redo->create_action(TTR("Nodes Disconnected")); undo_redo->add_do_method(visual_shader.ptr(), "disconnect_nodes", type, from, p_from_index, to, p_to_index); undo_redo->add_undo_method(visual_shader.ptr(), "connect_nodes", type, from, p_from_index, to, p_to_index); - undo_redo->add_do_method(this, "_update_graph"); - undo_redo->add_undo_method(this, "_update_graph"); + undo_redo->add_do_method(graph_plugin.ptr(), "disconnect_nodes", type, from, p_from_index, to, p_to_index); + undo_redo->add_undo_method(graph_plugin.ptr(), "connect_nodes", type, from, p_from_index, to, p_to_index); + undo_redo->add_do_method(graph_plugin.ptr(), "update_node", (int)type, to); + undo_redo->add_undo_method(graph_plugin.ptr(), "update_node", (int)type, to); undo_redo->commit_action(); - //updating = false; } void VisualShaderEditor::_connection_to_empty(const String &p_from, int p_from_slot, const Vector2 &p_release_position) { @@ -1527,47 +2185,308 @@ void VisualShaderEditor::_connection_from_empty(const String &p_to, int p_to_slo _show_members_dialog(true); } -void VisualShaderEditor::_delete_request(int which) { - VisualShader::Type type = VisualShader::Type(edit_type->get_selected()); - Ref<VisualShaderNode> node = Ref<VisualShaderNode>(visual_shader->get_node(type, which)); +void VisualShaderEditor::_delete_nodes(int p_type, const List<int> &p_nodes) { + VisualShader::Type type = VisualShader::Type(p_type); + List<VisualShader::Connection> conns; + visual_shader->get_node_connections(type, &conns); + + for (const List<int>::Element *F = p_nodes.front(); F; F = F->next()) { + for (List<VisualShader::Connection>::Element *E = conns.front(); E; E = E->next()) { + if (E->get().from_node == F->get() || E->get().to_node == F->get()) { + undo_redo->add_do_method(graph_plugin.ptr(), "disconnect_nodes", type, E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port); + } + } + } + + Set<String> uniform_names; + + for (const List<int>::Element *F = p_nodes.front(); F; F = F->next()) { + Ref<VisualShaderNode> node = visual_shader->get_node(type, F->get()); + + undo_redo->add_do_method(visual_shader.ptr(), "remove_node", type, F->get()); + undo_redo->add_undo_method(visual_shader.ptr(), "add_node", type, node, visual_shader->get_node_position(type, F->get()), F->get()); + undo_redo->add_undo_method(graph_plugin.ptr(), "add_node", type, F->get()); - undo_redo->create_action(TTR("Delete Node")); - undo_redo->add_do_method(visual_shader.ptr(), "remove_node", type, which); - undo_redo->add_undo_method(visual_shader.ptr(), "add_node", type, node, visual_shader->get_node_position(type, which), which); + undo_redo->add_do_method(this, "_clear_buffer"); + undo_redo->add_undo_method(this, "_clear_buffer"); - undo_redo->add_do_method(this, "_clear_buffer"); - undo_redo->add_undo_method(this, "_clear_buffer"); + // restore size, inputs and outputs if node is group + VisualShaderNodeGroupBase *group = Object::cast_to<VisualShaderNodeGroupBase>(node.ptr()); + if (group) { + undo_redo->add_undo_method(group, "set_size", group->get_size()); + undo_redo->add_undo_method(group, "set_inputs", group->get_inputs()); + undo_redo->add_undo_method(group, "set_outputs", group->get_outputs()); + } - // restore size, inputs and outputs if node is group - VisualShaderNodeGroupBase *group = Object::cast_to<VisualShaderNodeGroupBase>(node.ptr()); - if (group) { - undo_redo->add_undo_method(group, "set_size", group->get_size()); - undo_redo->add_undo_method(group, "set_inputs", group->get_inputs()); - undo_redo->add_undo_method(group, "set_outputs", group->get_outputs()); + // restore expression text if node is expression + VisualShaderNodeExpression *expression = Object::cast_to<VisualShaderNodeExpression>(node.ptr()); + if (expression) { + undo_redo->add_undo_method(expression, "set_expression", expression->get_expression()); + } + + VisualShaderNodeUniform *uniform = Object::cast_to<VisualShaderNodeUniform>(node.ptr()); + if (uniform) { + uniform_names.insert(uniform->get_uniform_name()); + } + } + + List<VisualShader::Connection> used_conns; + for (const List<int>::Element *F = p_nodes.front(); F; F = F->next()) { + for (List<VisualShader::Connection>::Element *E = conns.front(); E; E = E->next()) { + if (E->get().from_node == F->get() || E->get().to_node == F->get()) { + bool cancel = false; + for (List<VisualShader::Connection>::Element *R = used_conns.front(); R; R = R->next()) { + if (R->get().from_node == E->get().from_node && R->get().from_port == E->get().from_port && R->get().to_node == E->get().to_node && R->get().to_port == E->get().to_port) { + cancel = true; // to avoid ERR_ALREADY_EXISTS warning + break; + } + } + if (!cancel) { + undo_redo->add_undo_method(visual_shader.ptr(), "connect_nodes", type, E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port); + undo_redo->add_undo_method(graph_plugin.ptr(), "connect_nodes", type, E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port); + used_conns.push_back(E->get()); + } + } + } } - // restore expression text if node is expression - VisualShaderNodeExpression *expression = Object::cast_to<VisualShaderNodeExpression>(node.ptr()); - if (expression) { - undo_redo->add_undo_method(expression, "set_expression", expression->get_expression()); + // delete nodes from the graph + for (const List<int>::Element *F = p_nodes.front(); F; F = F->next()) { + undo_redo->add_do_method(graph_plugin.ptr(), "remove_node", type, F->get()); } - List<VisualShader::Connection> conns; - visual_shader->get_node_connections(type, &conns); + // update uniform refs if any uniform has been deleted + if (uniform_names.size() > 0) { + undo_redo->add_do_method(this, "_update_uniforms", true); + undo_redo->add_undo_method(this, "_update_uniforms", true); - for (List<VisualShader::Connection>::Element *E = conns.front(); E; E = E->next()) { - if (E->get().from_node == which || E->get().to_node == which) { - undo_redo->add_undo_method(visual_shader.ptr(), "connect_nodes", type, E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port); + _update_uniform_refs(uniform_names); + } +} + +void VisualShaderEditor::_replace_node(VisualShader::Type p_type_id, int p_node_id, const StringName &p_from, const StringName &p_to) { + undo_redo->add_do_method(visual_shader.ptr(), "replace_node", p_type_id, p_node_id, p_to); + undo_redo->add_undo_method(visual_shader.ptr(), "replace_node", p_type_id, p_node_id, p_from); +} + +void VisualShaderEditor::_update_constant(VisualShader::Type p_type_id, int p_node_id, Variant p_var, int p_preview_port) { + Ref<VisualShaderNode> node = visual_shader->get_node(p_type_id, p_node_id); + ERR_FAIL_COND(!node.is_valid()); + ERR_FAIL_COND(!node->has_method("set_constant")); + node->call("set_constant", p_var); + if (p_preview_port != -1) { + node->set_output_port_for_preview(p_preview_port); + } +} + +void VisualShaderEditor::_update_uniform(VisualShader::Type p_type_id, int p_node_id, Variant p_var, int p_preview_port) { + Ref<VisualShaderNodeUniform> uniform = visual_shader->get_node(p_type_id, p_node_id); + ERR_FAIL_COND(!uniform.is_valid()); + + String valid_name = visual_shader->validate_uniform_name(uniform->get_uniform_name(), uniform); + uniform->set_uniform_name(valid_name); + graph_plugin->set_uniform_name(p_type_id, p_node_id, valid_name); + + if (uniform->has_method("set_default_value_enabled")) { + uniform->call("set_default_value_enabled", true); + uniform->call("set_default_value", p_var); + } + if (p_preview_port != -1) { + uniform->set_output_port_for_preview(p_preview_port); + } +} + +void VisualShaderEditor::_convert_constants_to_uniforms(bool p_vice_versa) { + VisualShader::Type type_id = get_current_shader_type(); + + if (!p_vice_versa) { + undo_redo->create_action(TTR("Convert Constant Node(s) To Uniform(s)")); + } else { + undo_redo->create_action(TTR("Convert Uniform Node(s) To Constant(s)")); + } + + const Set<int> ¤t_set = p_vice_versa ? selected_uniforms : selected_constants; + Set<String> deleted_names; + + for (Set<int>::Element *E = current_set.front(); E; E = E->next()) { + int node_id = E->get(); + Ref<VisualShaderNode> node = visual_shader->get_node(type_id, node_id); + bool catched = false; + Variant var; + + // float + if (!p_vice_versa) { + Ref<VisualShaderNodeFloatConstant> float_const = Object::cast_to<VisualShaderNodeFloatConstant>(node.ptr()); + if (float_const.is_valid()) { + _replace_node(type_id, node_id, "VisualShaderNodeFloatConstant", "VisualShaderNodeFloatUniform"); + var = float_const->get_constant(); + catched = true; + } + } else { + Ref<VisualShaderNodeFloatUniform> float_uniform = Object::cast_to<VisualShaderNodeFloatUniform>(node.ptr()); + if (float_uniform.is_valid()) { + _replace_node(type_id, node_id, "VisualShaderNodeFloatUniform", "VisualShaderNodeFloatConstant"); + var = float_uniform->get_default_value(); + catched = true; + } + } + + // int + if (!catched) { + if (!p_vice_versa) { + Ref<VisualShaderNodeIntConstant> int_const = Object::cast_to<VisualShaderNodeIntConstant>(node.ptr()); + if (int_const.is_valid()) { + _replace_node(type_id, node_id, "VisualShaderNodeIntConstant", "VisualShaderNodeIntUniform"); + var = int_const->get_constant(); + catched = true; + } + } else { + Ref<VisualShaderNodeIntUniform> int_uniform = Object::cast_to<VisualShaderNodeIntUniform>(node.ptr()); + if (int_uniform.is_valid()) { + _replace_node(type_id, node_id, "VisualShaderNodeIntUniform", "VisualShaderNodeIntConstant"); + var = int_uniform->get_default_value(); + catched = true; + } + } + } + + // boolean + if (!catched) { + if (!p_vice_versa) { + Ref<VisualShaderNodeBooleanConstant> boolean_const = Object::cast_to<VisualShaderNodeBooleanConstant>(node.ptr()); + if (boolean_const.is_valid()) { + _replace_node(type_id, node_id, "VisualShaderNodeBooleanConstant", "VisualShaderNodeBooleanUniform"); + var = boolean_const->get_constant(); + catched = true; + } + } else { + Ref<VisualShaderNodeBooleanUniform> boolean_uniform = Object::cast_to<VisualShaderNodeBooleanUniform>(node.ptr()); + if (boolean_uniform.is_valid()) { + _replace_node(type_id, node_id, "VisualShaderNodeBooleanUniform", "VisualShaderNodeBooleanConstant"); + var = boolean_uniform->get_default_value(); + catched = true; + } + } } + + // vec3 + if (!catched) { + if (!p_vice_versa) { + Ref<VisualShaderNodeVec3Constant> vec3_const = Object::cast_to<VisualShaderNodeVec3Constant>(node.ptr()); + if (vec3_const.is_valid()) { + _replace_node(type_id, node_id, "VisualShaderNodeVec3Constant", "VisualShaderNodeVec3Uniform"); + var = vec3_const->get_constant(); + catched = true; + } + } else { + Ref<VisualShaderNodeVec3Uniform> vec3_uniform = Object::cast_to<VisualShaderNodeVec3Uniform>(node.ptr()); + if (vec3_uniform.is_valid()) { + _replace_node(type_id, node_id, "VisualShaderNodeVec3Uniform", "VisualShaderNodeVec3Constant"); + var = vec3_uniform->get_default_value(); + catched = true; + } + } + } + + // color + if (!catched) { + if (!p_vice_versa) { + Ref<VisualShaderNodeColorConstant> color_const = Object::cast_to<VisualShaderNodeColorConstant>(node.ptr()); + if (color_const.is_valid()) { + _replace_node(type_id, node_id, "VisualShaderNodeColorConstant", "VisualShaderNodeColorUniform"); + var = color_const->get_constant(); + catched = true; + } + } else { + Ref<VisualShaderNodeColorUniform> color_uniform = Object::cast_to<VisualShaderNodeColorUniform>(node.ptr()); + if (color_uniform.is_valid()) { + _replace_node(type_id, node_id, "VisualShaderNodeColorUniform", "VisualShaderNodeColorConstant"); + var = color_uniform->get_default_value(); + catched = true; + } + } + } + + // transform + if (!catched) { + if (!p_vice_versa) { + Ref<VisualShaderNodeTransformConstant> transform_const = Object::cast_to<VisualShaderNodeTransformConstant>(node.ptr()); + if (transform_const.is_valid()) { + _replace_node(type_id, node_id, "VisualShaderNodeTransformConstant", "VisualShaderNodeTransformUniform"); + var = transform_const->get_constant(); + catched = true; + } + } else { + Ref<VisualShaderNodeTransformUniform> transform_uniform = Object::cast_to<VisualShaderNodeTransformUniform>(node.ptr()); + if (transform_uniform.is_valid()) { + _replace_node(type_id, node_id, "VisualShaderNodeTransformUniform", "VisualShaderNodeTransformConstant"); + var = transform_uniform->get_default_value(); + catched = true; + } + } + } + ERR_CONTINUE(!catched); + int preview_port = node->get_output_port_for_preview(); + + if (!p_vice_versa) { + undo_redo->add_do_method(this, "_update_uniform", type_id, node_id, var, preview_port); + undo_redo->add_undo_method(this, "_update_constant", type_id, node_id, var, preview_port); + } else { + undo_redo->add_do_method(this, "_update_constant", type_id, node_id, var, preview_port); + undo_redo->add_undo_method(this, "_update_uniform", type_id, node_id, var, preview_port); + + Ref<VisualShaderNodeUniform> uniform = Object::cast_to<VisualShaderNodeUniform>(node.ptr()); + ERR_CONTINUE(!uniform.is_valid()); + + deleted_names.insert(uniform->get_uniform_name()); + } + + undo_redo->add_do_method(graph_plugin.ptr(), "update_node", type_id, node_id); + undo_redo->add_undo_method(graph_plugin.ptr(), "update_node", type_id, node_id); + } + + undo_redo->add_do_method(this, "_update_uniforms", true); + undo_redo->add_undo_method(this, "_update_uniforms", true); + + if (deleted_names.size() > 0) { + _update_uniform_refs(deleted_names); } - undo_redo->add_do_method(this, "_update_graph"); - undo_redo->add_undo_method(this, "_update_graph"); + undo_redo->commit_action(); +} + +void VisualShaderEditor::_delete_node_request(int p_type, int p_node) { + List<int> to_erase; + to_erase.push_back(p_node); + + undo_redo->create_action(TTR("Delete VisualShader Node")); + _delete_nodes(p_type, to_erase); + undo_redo->commit_action(); +} + +void VisualShaderEditor::_delete_nodes_request() { + List<int> to_erase; + + for (int i = 0; i < graph->get_child_count(); i++) { + GraphNode *gn = Object::cast_to<GraphNode>(graph->get_child(i)); + if (gn) { + if (gn->is_selected() && gn->is_close_button_visible()) { + to_erase.push_back(gn->get_name().operator String().to_int()); + } + } + } + + if (to_erase.is_empty()) { + return; + } + + undo_redo->create_action(TTR("Delete VisualShader Node(s)")); + _delete_nodes(get_current_shader_type(), to_erase); undo_redo->commit_action(); } void VisualShaderEditor::_node_selected(Object *p_node) { - VisualShader::Type type = VisualShader::Type(edit_type->get_selected()); + VisualShader::Type type = get_current_shader_type(); GraphNode *gn = Object::cast_to<GraphNode>(p_node); ERR_FAIL_COND(!gn); @@ -1583,27 +2502,69 @@ void VisualShaderEditor::_node_selected(Object *p_node) { void VisualShaderEditor::_graph_gui_input(const Ref<InputEvent> &p_event) { Ref<InputEventMouseButton> mb = p_event; + VisualShader::Type type = get_current_shader_type(); if (mb.is_valid() && mb->is_pressed() && mb->get_button_index() == BUTTON_RIGHT) { + selected_constants.clear(); + selected_uniforms.clear(); + List<int> to_change; for (int i = 0; i < graph->get_child_count(); i++) { GraphNode *gn = Object::cast_to<GraphNode>(graph->get_child(i)); if (gn) { if (gn->is_selected() && gn->is_close_button_visible()) { - to_change.push_back(gn->get_name().operator String().to_int()); + int id = gn->get_name().operator String().to_int(); + to_change.push_back(id); + + Ref<VisualShaderNode> node = visual_shader->get_node(type, id); + VisualShaderNodeConstant *cnode = Object::cast_to<VisualShaderNodeConstant>(node.ptr()); + if (cnode != nullptr) { + selected_constants.insert(id); + } + VisualShaderNodeUniform *unode = Object::cast_to<VisualShaderNodeUniform>(node.ptr()); + if (unode != nullptr) { + selected_uniforms.insert(id); + } } } } - if (to_change.empty() && copy_nodes_buffer.empty()) { + if (to_change.is_empty() && copy_nodes_buffer.is_empty()) { _show_members_dialog(true); } else { - popup_menu->set_item_disabled(NodeMenuOptions::COPY, to_change.empty()); - popup_menu->set_item_disabled(NodeMenuOptions::PASTE, copy_nodes_buffer.empty()); - popup_menu->set_item_disabled(NodeMenuOptions::DELETE, to_change.empty()); - popup_menu->set_item_disabled(NodeMenuOptions::DUPLICATE, to_change.empty()); + popup_menu->set_item_disabled(NodeMenuOptions::COPY, to_change.is_empty()); + popup_menu->set_item_disabled(NodeMenuOptions::PASTE, copy_nodes_buffer.is_empty()); + popup_menu->set_item_disabled(NodeMenuOptions::DELETE, to_change.is_empty()); + popup_menu->set_item_disabled(NodeMenuOptions::DUPLICATE, to_change.is_empty()); + + int temp = popup_menu->get_item_index(NodeMenuOptions::SEPARATOR2); + if (temp != -1) { + popup_menu->remove_item(temp); + } + temp = popup_menu->get_item_index(NodeMenuOptions::CONVERT_CONSTANTS_TO_UNIFORMS); + if (temp != -1) { + popup_menu->remove_item(temp); + } + temp = popup_menu->get_item_index(NodeMenuOptions::CONVERT_UNIFORMS_TO_CONSTANTS); + if (temp != -1) { + popup_menu->remove_item(temp); + } + + if (selected_constants.size() > 0 || selected_uniforms.size() > 0) { + popup_menu->add_separator("", NodeMenuOptions::SEPARATOR2); + + if (selected_constants.size() > 0) { + popup_menu->add_item(TTR("Convert Constant(s) to Uniform(s)"), NodeMenuOptions::CONVERT_CONSTANTS_TO_UNIFORMS); + } + + if (selected_uniforms.size() > 0) { + popup_menu->add_item(TTR("Convert Uniforms(s) to Constant(s)"), NodeMenuOptions::CONVERT_UNIFORMS_TO_CONSTANTS); + } + } + menu_point = graph->get_local_mouse_position(); Point2 gpos = Input::get_singleton()->get_mouse_position(); popup_menu->set_position(gpos); + popup_menu->set_size(Size2(-1, -1)); popup_menu->popup(); } } @@ -1693,20 +2654,29 @@ void VisualShaderEditor::_notification(int p_what) { Color keyword_color = EDITOR_GET("text_editor/highlighting/keyword_color"); Color comment_color = EDITOR_GET("text_editor/highlighting/comment_color"); Color symbol_color = EDITOR_GET("text_editor/highlighting/symbol_color"); + Color function_color = EDITOR_GET("text_editor/highlighting/function_color"); + Color number_color = EDITOR_GET("text_editor/highlighting/number_color"); + Color members_color = EDITOR_GET("text_editor/highlighting/member_variable_color"); preview_text->add_theme_color_override("background_color", background_color); for (List<String>::Element *E = keyword_list.front(); E; E = E->next()) { - preview_text->add_keyword_color(E->get(), keyword_color); + syntax_highlighter->add_keyword_color(E->get(), keyword_color); } preview_text->add_theme_font_override("font", get_theme_font("expression", "EditorFonts")); + preview_text->add_theme_font_size_override("font_size", get_theme_font_size("expression_size", "EditorFonts")); preview_text->add_theme_color_override("font_color", text_color); - preview_text->add_theme_color_override("symbol_color", symbol_color); - preview_text->add_color_region("/*", "*/", comment_color, false); - preview_text->add_color_region("//", "", comment_color, false); + syntax_highlighter->set_number_color(number_color); + syntax_highlighter->set_symbol_color(symbol_color); + syntax_highlighter->set_function_color(function_color); + syntax_highlighter->set_member_variable_color(members_color); + syntax_highlighter->clear_color_regions(); + syntax_highlighter->add_color_region("/*", "*/", comment_color, false); + syntax_highlighter->add_color_region("//", "", comment_color, true); error_text->add_theme_font_override("font", get_theme_font("status_source", "EditorFonts")); + error_text->add_theme_font_size_override("font_size", get_theme_font_size("status_source_size", "EditorFonts")); error_text->add_theme_color_override("font_color", get_theme_color("error_color", "Editor")); } @@ -1814,12 +2784,13 @@ void VisualShaderEditor::_dup_paste_nodes(int p_type, int p_pasted_type, List<in Ref<VisualShaderNode> dupli = node->duplicate(); undo_redo->add_do_method(visual_shader.ptr(), "add_node", type, dupli, visual_shader->get_node_position(pasted_type, E->get()) + p_offset, id_from); - undo_redo->add_undo_method(visual_shader.ptr(), "remove_node", type, id_from); + undo_redo->add_do_method(graph_plugin.ptr(), "add_node", type, id_from); // duplicate size, inputs and outputs if node is group Ref<VisualShaderNodeGroupBase> group = Object::cast_to<VisualShaderNodeGroupBase>(node.ptr()); if (!group.is_null()) { undo_redo->add_do_method(dupli.ptr(), "set_size", group->get_size()); + undo_redo->add_do_method(graph_plugin.ptr(), "set_node_size", type, id_from, group->get_size()); undo_redo->add_do_method(dupli.ptr(), "set_inputs", group->get_inputs()); undo_redo->add_do_method(dupli.ptr(), "set_outputs", group->get_outputs()); } @@ -1840,12 +2811,19 @@ void VisualShaderEditor::_dup_paste_nodes(int p_type, int p_pasted_type, List<in continue; } if (connection_remap.has(E->get().from_node) && connection_remap.has(E->get().to_node)) { - undo_redo->add_do_method(visual_shader.ptr(), "connect_nodes_forced", type, connection_remap[E->get().from_node], E->get().from_port, connection_remap[E->get().to_node], E->get().to_port); + undo_redo->add_do_method(visual_shader.ptr(), "connect_nodes", type, connection_remap[E->get().from_node], E->get().from_port, connection_remap[E->get().to_node], E->get().to_port); + undo_redo->add_do_method(graph_plugin.ptr(), "connect_nodes", type, connection_remap[E->get().from_node], E->get().from_port, connection_remap[E->get().to_node], E->get().to_port); + undo_redo->add_undo_method(graph_plugin.ptr(), "disconnect_nodes", type, connection_remap[E->get().from_node], E->get().from_port, connection_remap[E->get().to_node], E->get().to_port); } } - undo_redo->add_do_method(this, "_update_graph"); - undo_redo->add_undo_method(this, "_update_graph"); + id_from = base_id; + for (List<int>::Element *E = r_nodes.front(); E; E = E->next()) { + undo_redo->add_undo_method(visual_shader.ptr(), "remove_node", type, id_from); + undo_redo->add_undo_method(graph_plugin.ptr(), "remove_node", type, id_from); + id_from++; + } + undo_redo->commit_action(); if (p_select) { @@ -1870,24 +2848,24 @@ void VisualShaderEditor::_clear_buffer() { } void VisualShaderEditor::_duplicate_nodes() { - int type = edit_type->get_selected(); + int type = get_current_shader_type(); List<int> nodes; Set<int> excluded; _dup_copy_nodes(type, nodes, excluded); - if (nodes.empty()) { + if (nodes.is_empty()) { return; } - undo_redo->create_action(TTR("Duplicate Nodes")); + undo_redo->create_action(TTR("Duplicate VisualShader Node(s)")); _dup_paste_nodes(type, type, nodes, excluded, Vector2(10, 10) * EDSCALE, true); } void VisualShaderEditor::_copy_nodes() { - copy_type = edit_type->get_selected(); + copy_type = get_current_shader_type(); _clear_buffer(); @@ -1895,13 +2873,11 @@ void VisualShaderEditor::_copy_nodes() { } void VisualShaderEditor::_paste_nodes(bool p_use_custom_position, const Vector2 &p_custom_position) { - if (copy_nodes_buffer.empty()) { + if (copy_nodes_buffer.is_empty()) { return; } - int type = edit_type->get_selected(); - - undo_redo->create_action(TTR("Paste Nodes")); + int type = get_current_shader_type(); float scale = graph->get_zoom(); @@ -1912,117 +2888,130 @@ void VisualShaderEditor::_paste_nodes(bool p_use_custom_position, const Vector2 mpos = graph->get_local_mouse_position(); } + undo_redo->create_action(TTR("Paste VisualShader Node(s)")); + _dup_paste_nodes(type, copy_type, copy_nodes_buffer, copy_nodes_excluded_buffer, (graph->get_scroll_ofs() / scale + mpos / scale - selection_center), false); _dup_update_excluded(type, copy_nodes_excluded_buffer); // to prevent selection of previous copies at new paste } -void VisualShaderEditor::_delete_nodes() { - VisualShader::Type type = VisualShader::Type(edit_type->get_selected()); - List<int> to_erase; +void VisualShaderEditor::_mode_selected(int p_id) { + visual_shader->set_shader_type(particles_mode ? VisualShader::Type(p_id + 3) : VisualShader::Type(p_id)); + _update_options_menu(); + _update_graph(); +} - for (int i = 0; i < graph->get_child_count(); i++) { - GraphNode *gn = Object::cast_to<GraphNode>(graph->get_child(i)); - if (gn) { - if (gn->is_selected() && gn->is_close_button_visible()) { - to_erase.push_back(gn->get_name().operator String().to_int()); - } - } - } +void VisualShaderEditor::_input_select_item(Ref<VisualShaderNodeInput> p_input, String p_name) { + String prev_name = p_input->get_input_name(); - if (to_erase.empty()) { + if (p_name == prev_name) { return; } - undo_redo->create_action(TTR("Delete Nodes")); + bool type_changed = p_input->get_input_type_by_name(p_name) != p_input->get_input_type_by_name(prev_name); - for (List<int>::Element *F = to_erase.front(); F; F = F->next()) { - Ref<VisualShaderNode> node = visual_shader->get_node(type, F->get()); + UndoRedo *undo_redo = EditorNode::get_singleton()->get_undo_redo(); + undo_redo->create_action(TTR("Visual Shader Input Type Changed")); - undo_redo->add_do_method(visual_shader.ptr(), "remove_node", type, F->get()); - undo_redo->add_undo_method(visual_shader.ptr(), "add_node", type, node, visual_shader->get_node_position(type, F->get()), F->get()); + undo_redo->add_do_method(p_input.ptr(), "set_input_name", p_name); + undo_redo->add_undo_method(p_input.ptr(), "set_input_name", prev_name); + + // update output port + for (int type_id = 0; type_id < VisualShader::TYPE_MAX; type_id++) { + VisualShader::Type type = VisualShader::Type(type_id); + int id = visual_shader->find_node_id(type, p_input); + if (id != VisualShader::NODE_ID_INVALID) { + if (type_changed) { + List<VisualShader::Connection> conns; + visual_shader->get_node_connections(type, &conns); + for (List<VisualShader::Connection>::Element *E = conns.front(); E; E = E->next()) { + if (E->get().from_node == id) { + if (visual_shader->is_port_types_compatible(p_input->get_input_type_by_name(p_name), visual_shader->get_node(type, E->get().to_node)->get_input_port_type(E->get().to_port))) { + undo_redo->add_do_method(visual_shader.ptr(), "connect_nodes", type, E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port); + undo_redo->add_undo_method(visual_shader.ptr(), "connect_nodes", type, E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port); + continue; + } + undo_redo->add_do_method(visual_shader.ptr(), "disconnect_nodes", type, E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port); + undo_redo->add_undo_method(visual_shader.ptr(), "connect_nodes", type, E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port); + undo_redo->add_do_method(graph_plugin.ptr(), "disconnect_nodes", type, E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port); + undo_redo->add_undo_method(graph_plugin.ptr(), "connect_nodes", type, E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port); + } + } + } + undo_redo->add_do_method(graph_plugin.ptr(), "update_node", type_id, id); + undo_redo->add_undo_method(graph_plugin.ptr(), "update_node", type_id, id); + break; + } + } - undo_redo->add_do_method(this, "_clear_buffer"); - undo_redo->add_undo_method(this, "_clear_buffer"); + undo_redo->commit_action(); +} - // restore size, inputs and outputs if node is group - VisualShaderNodeGroupBase *group = Object::cast_to<VisualShaderNodeGroupBase>(node.ptr()); - if (group) { - undo_redo->add_undo_method(group, "set_size", group->get_size()); - undo_redo->add_undo_method(group, "set_inputs", group->get_inputs()); - undo_redo->add_undo_method(group, "set_outputs", group->get_outputs()); - } +void VisualShaderEditor::_uniform_select_item(Ref<VisualShaderNodeUniformRef> p_uniform_ref, String p_name) { + String prev_name = p_uniform_ref->get_uniform_name(); - // restore expression text if node is expression - VisualShaderNodeExpression *expression = Object::cast_to<VisualShaderNodeExpression>(node.ptr()); - if (expression) { - undo_redo->add_undo_method(expression, "set_expression", expression->get_expression()); - } + if (p_name == prev_name) { + return; } - List<VisualShader::Connection> conns; - visual_shader->get_node_connections(type, &conns); + bool type_changed = p_uniform_ref->get_uniform_type_by_name(p_name) != p_uniform_ref->get_uniform_type_by_name(prev_name); - List<VisualShader::Connection> used_conns; - for (List<int>::Element *F = to_erase.front(); F; F = F->next()) { - for (List<VisualShader::Connection>::Element *E = conns.front(); E; E = E->next()) { - if (E->get().from_node == F->get() || E->get().to_node == F->get()) { - bool cancel = false; - for (List<VisualShader::Connection>::Element *R = used_conns.front(); R; R = R->next()) { - if (R->get().from_node == E->get().from_node && R->get().from_port == E->get().from_port && R->get().to_node == E->get().to_node && R->get().to_port == E->get().to_port) { - cancel = true; // to avoid ERR_ALREADY_EXISTS warning - break; + UndoRedo *undo_redo = EditorNode::get_singleton()->get_undo_redo(); + undo_redo->create_action(TTR("UniformRef Name Changed")); + + undo_redo->add_do_method(p_uniform_ref.ptr(), "set_uniform_name", p_name); + undo_redo->add_undo_method(p_uniform_ref.ptr(), "set_uniform_name", prev_name); + + // update output port + for (int type_id = 0; type_id < VisualShader::TYPE_MAX; type_id++) { + VisualShader::Type type = VisualShader::Type(type_id); + int id = visual_shader->find_node_id(type, p_uniform_ref); + if (id != VisualShader::NODE_ID_INVALID) { + if (type_changed) { + List<VisualShader::Connection> conns; + visual_shader->get_node_connections(type, &conns); + for (List<VisualShader::Connection>::Element *E = conns.front(); E; E = E->next()) { + if (E->get().from_node == id) { + if (visual_shader->is_port_types_compatible(p_uniform_ref->get_uniform_type_by_name(p_name), visual_shader->get_node(type, E->get().to_node)->get_input_port_type(E->get().to_port))) { + continue; + } + undo_redo->add_do_method(visual_shader.ptr(), "disconnect_nodes", type, E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port); + undo_redo->add_undo_method(visual_shader.ptr(), "connect_nodes", type, E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port); + undo_redo->add_do_method(graph_plugin.ptr(), "disconnect_nodes", type, E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port); + undo_redo->add_undo_method(graph_plugin.ptr(), "connect_nodes", type, E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port); } } - if (!cancel) { - undo_redo->add_undo_method(visual_shader.ptr(), "connect_nodes", type, E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port); - used_conns.push_back(E->get()); - } } + undo_redo->add_do_method(graph_plugin.ptr(), "update_node", type_id, id); + undo_redo->add_undo_method(graph_plugin.ptr(), "update_node", type_id, id); + break; } } - undo_redo->add_do_method(this, "_update_graph"); - undo_redo->add_undo_method(this, "_update_graph"); undo_redo->commit_action(); } -void VisualShaderEditor::_mode_selected(int p_id) { - _update_options_menu(); - _update_graph(); -} - -void VisualShaderEditor::_input_select_item(Ref<VisualShaderNodeInput> input, String name) { - String prev_name = input->get_input_name(); - - if (name == prev_name) { +void VisualShaderEditor::_float_constant_selected(int p_index, int p_node) { + if (p_index == 0) { + graph_plugin->update_node_size(p_node); return; } - bool type_changed = input->get_input_type_by_name(name) != input->get_input_type_by_name(prev_name); + --p_index; - UndoRedo *undo_redo = EditorNode::get_singleton()->get_undo_redo(); - undo_redo->create_action(TTR("Visual Shader Input Type Changed")); + ERR_FAIL_INDEX(p_index, MAX_FLOAT_CONST_DEFS); - undo_redo->add_do_method(input.ptr(), "set_input_name", name); - undo_redo->add_undo_method(input.ptr(), "set_input_name", prev_name); - - if (type_changed) { - //restore connections if type changed - VisualShader::Type type = VisualShader::Type(edit_type->get_selected()); - int id = visual_shader->find_node_id(type, input); - List<VisualShader::Connection> conns; - visual_shader->get_node_connections(type, &conns); - for (List<VisualShader::Connection>::Element *E = conns.front(); E; E = E->next()) { - if (E->get().from_node == id) { - undo_redo->add_undo_method(visual_shader.ptr(), "connect_nodes", type, E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port); - } - } + VisualShader::Type type = get_current_shader_type(); + Ref<VisualShaderNodeFloatConstant> node = visual_shader->get_node(type, p_node); + if (!node.is_valid()) { + return; } - undo_redo->add_do_method(VisualShaderEditor::get_singleton(), "_update_graph"); - undo_redo->add_undo_method(VisualShaderEditor::get_singleton(), "_update_graph"); - + undo_redo->create_action(TTR("Set constant")); + undo_redo->add_do_method(node.ptr(), "set_constant", float_constant_defs[p_index].value); + undo_redo->add_undo_method(node.ptr(), "set_constant", node->get_constant()); + undo_redo->add_do_method(graph_plugin.ptr(), "update_constant", type, p_node); + undo_redo->add_undo_method(graph_plugin.ptr(), "update_constant", type, p_node); undo_redo->commit_action(); } @@ -2034,12 +3023,12 @@ void VisualShaderEditor::_member_selected() { TreeItem *item = members->get_selected(); if (item != nullptr && item->has_meta("id")) { - members_dialog->get_ok()->set_disabled(false); + members_dialog->get_ok_button()->set_disabled(false); highend_label->set_visible(add_options[item->get_meta("id")].highend); node_desc->set_text(_get_description(item->get_meta("id"))); } else { highend_label->set_visible(false); - members_dialog->get_ok()->set_disabled(true); + members_dialog->get_ok_button()->set_disabled(true); node_desc->set_text(""); } } @@ -2111,11 +3100,19 @@ void VisualShaderEditor::_node_menu_id_pressed(int p_idx) { _paste_nodes(true, menu_point); break; case NodeMenuOptions::DELETE: - _delete_nodes(); + _delete_nodes_request(); break; case NodeMenuOptions::DUPLICATE: _duplicate_nodes(); break; + case NodeMenuOptions::CONVERT_CONSTANTS_TO_UNIFORMS: + _convert_constants_to_uniforms(false); + break; + case NodeMenuOptions::CONVERT_UNIFORMS_TO_CONSTANTS: + _convert_constants_to_uniforms(true); + break; + default: + break; } } @@ -2186,10 +3183,30 @@ void VisualShaderEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da _add_custom_node(arr[i]); j++; } + } else if (type == "CurveTexture") { + saved_node_pos = p_point + Vector2(0, j * 210 * EDSCALE); + saved_node_pos_dirty = true; + _add_curve_node(arr[i]); + j++; } else if (ClassDB::get_parent_class(type) == "Texture2D") { saved_node_pos = p_point + Vector2(0, j * 210 * EDSCALE); saved_node_pos_dirty = true; - _add_texture_node(arr[i]); + _add_texture2d_node(arr[i]); + j++; + } else if (type == "Texture2DArray") { + saved_node_pos = p_point + Vector2(0, j * 210 * EDSCALE); + saved_node_pos_dirty = true; + _add_texture2d_array_node(arr[i]); + j++; + } else if (ClassDB::get_parent_class(type) == "Texture3D") { + saved_node_pos = p_point + Vector2(0, j * 210 * EDSCALE); + saved_node_pos_dirty = true; + _add_texture3d_node(arr[i]); + j++; + } else if (type == "Cubemap") { + saved_node_pos = p_point + Vector2(0, j * 210 * EDSCALE); + saved_node_pos_dirty = true; + _add_cubemap_node(arr[i]); j++; } } @@ -2200,15 +3217,35 @@ void VisualShaderEditor::drop_data_fw(const Point2 &p_point, const Variant &p_da void VisualShaderEditor::_show_preview_text() { preview_showed = !preview_showed; - preview_vbox->set_visible(preview_showed); if (preview_showed) { + if (preview_first) { + preview_window->set_size(Size2(400 * EDSCALE, 600 * EDSCALE)); + preview_window->popup_centered(); + preview_first = false; + } else { + preview_window->popup(); + } + _preview_size_changed(); + if (pending_update_preview) { _update_preview(); pending_update_preview = false; } + } else { + preview_window->hide(); } } +void VisualShaderEditor::_preview_close_requested() { + preview_showed = false; + preview_window->hide(); + preview_shader->set_pressed(false); +} + +void VisualShaderEditor::_preview_size_changed() { + preview_vbox->set_custom_minimum_size(preview_window->get_size()); +} + static ShaderLanguage::DataType _get_global_variable_type(const StringName &p_variable) { RS::GlobalVariableType gvt = RS::get_singleton()->global_variable_get_type(p_variable); return RS::global_variable_type_get_shader_datatype(gvt); @@ -2244,15 +3281,31 @@ void VisualShaderEditor::_update_preview() { } } +void VisualShaderEditor::_visibility_changed() { + if (!is_visible()) { + if (preview_window->is_visible()) { + preview_shader->set_pressed(false); + preview_window->hide(); + preview_showed = false; + } + } +} + void VisualShaderEditor::_bind_methods() { - ClassDB::bind_method("_rebuild", &VisualShaderEditor::_rebuild); ClassDB::bind_method("_update_graph", &VisualShaderEditor::_update_graph); ClassDB::bind_method("_update_options_menu", &VisualShaderEditor::_update_options_menu); ClassDB::bind_method("_add_node", &VisualShaderEditor::_add_node); ClassDB::bind_method("_node_changed", &VisualShaderEditor::_node_changed); ClassDB::bind_method("_input_select_item", &VisualShaderEditor::_input_select_item); + ClassDB::bind_method("_uniform_select_item", &VisualShaderEditor::_uniform_select_item); ClassDB::bind_method("_set_node_size", &VisualShaderEditor::_set_node_size); ClassDB::bind_method("_clear_buffer", &VisualShaderEditor::_clear_buffer); + ClassDB::bind_method("_update_uniforms", &VisualShaderEditor::_update_uniforms); + ClassDB::bind_method("_set_mode", &VisualShaderEditor::_set_mode); + ClassDB::bind_method("_nodes_dragged", &VisualShaderEditor::_nodes_dragged); + ClassDB::bind_method("_float_constant_selected", &VisualShaderEditor::_float_constant_selected); + ClassDB::bind_method("_update_constant", &VisualShaderEditor::_update_constant); + ClassDB::bind_method("_update_uniform", &VisualShaderEditor::_update_uniform); ClassDB::bind_method(D_METHOD("get_drag_data_fw"), &VisualShaderEditor::get_drag_data_fw); ClassDB::bind_method(D_METHOD("can_drop_data_fw"), &VisualShaderEditor::can_drop_data_fw); @@ -2270,7 +3323,6 @@ VisualShaderEditor::VisualShaderEditor() { saved_node_pos = Point2(0, 0); ShaderLanguage::get_keyword_list(&keyword_list); - preview_showed = false; pending_update_preview = false; shader_error = false; @@ -2279,17 +3331,14 @@ VisualShaderEditor::VisualShaderEditor() { from_node = -1; from_slot = -1; - main_box = memnew(HSplitContainer); - main_box->set_v_size_flags(SIZE_EXPAND_FILL); - main_box->set_h_size_flags(SIZE_EXPAND_FILL); - add_child(main_box); - graph = memnew(GraphEdit); graph->get_zoom_hbox()->set_h_size_flags(SIZE_EXPAND_FILL); graph->set_v_size_flags(SIZE_EXPAND_FILL); graph->set_h_size_flags(SIZE_EXPAND_FILL); - main_box->add_child(graph); + add_child(graph); graph->set_drag_forwarding(this); + float graph_minimap_opacity = EditorSettings::get_singleton()->get("editors/visual_editors/minimap_opacity"); + graph->set_minimap_opacity(graph_minimap_opacity); graph->add_valid_right_disconnect_type(VisualShaderNode::PORT_TYPE_SCALAR); graph->add_valid_right_disconnect_type(VisualShaderNode::PORT_TYPE_SCALAR_INT); graph->add_valid_right_disconnect_type(VisualShaderNode::PORT_TYPE_BOOLEAN); @@ -2304,11 +3353,12 @@ VisualShaderEditor::VisualShaderEditor() { graph->connect("scroll_offset_changed", callable_mp(this, &VisualShaderEditor::_scroll_changed)); graph->connect("duplicate_nodes_request", callable_mp(this, &VisualShaderEditor::_duplicate_nodes)); graph->connect("copy_nodes_request", callable_mp(this, &VisualShaderEditor::_copy_nodes)); - graph->connect("paste_nodes_request", callable_mp(this, &VisualShaderEditor::_paste_nodes)); - graph->connect("delete_nodes_request", callable_mp(this, &VisualShaderEditor::_delete_nodes)); + graph->connect("paste_nodes_request", callable_mp(this, &VisualShaderEditor::_paste_nodes), varray(false, Point2())); + graph->connect("delete_nodes_request", callable_mp(this, &VisualShaderEditor::_delete_nodes_request)); graph->connect("gui_input", callable_mp(this, &VisualShaderEditor::_graph_gui_input)); graph->connect("connection_to_empty", callable_mp(this, &VisualShaderEditor::_connection_to_empty)); graph->connect("connection_from_empty", callable_mp(this, &VisualShaderEditor::_connection_from_empty)); + graph->connect("visibility_changed", callable_mp(this, &VisualShaderEditor::_visibility_changed)); graph->add_valid_connection_type(VisualShaderNode::PORT_TYPE_SCALAR, VisualShaderNode::PORT_TYPE_SCALAR); graph->add_valid_connection_type(VisualShaderNode::PORT_TYPE_SCALAR, VisualShaderNode::PORT_TYPE_SCALAR_INT); graph->add_valid_connection_type(VisualShaderNode::PORT_TYPE_SCALAR, VisualShaderNode::PORT_TYPE_VECTOR); @@ -2332,45 +3382,66 @@ VisualShaderEditor::VisualShaderEditor() { graph->get_zoom_hbox()->add_child(vs); graph->get_zoom_hbox()->move_child(vs, 0); - edit_type = memnew(OptionButton); - edit_type->add_item(TTR("Vertex")); - edit_type->add_item(TTR("Fragment")); - edit_type->add_item(TTR("Light")); - edit_type->select(1); - edit_type->connect("item_selected", callable_mp(this, &VisualShaderEditor::_mode_selected)); - graph->get_zoom_hbox()->add_child(edit_type); - graph->get_zoom_hbox()->move_child(edit_type, 0); - - add_node = memnew(ToolButton); + edit_type_standart = memnew(OptionButton); + edit_type_standart->add_item(TTR("Vertex")); + edit_type_standart->add_item(TTR("Fragment")); + edit_type_standart->add_item(TTR("Light")); + edit_type_standart->select(1); + edit_type_standart->connect("item_selected", callable_mp(this, &VisualShaderEditor::_mode_selected)); + + edit_type_particles = memnew(OptionButton); + edit_type_particles->add_item(TTR("Emit")); + edit_type_particles->add_item(TTR("Process")); + edit_type_particles->add_item(TTR("End")); + edit_type_particles->select(0); + edit_type_particles->connect("item_selected", callable_mp(this, &VisualShaderEditor::_mode_selected)); + + edit_type = edit_type_standart; + + graph->get_zoom_hbox()->add_child(edit_type_particles); + graph->get_zoom_hbox()->move_child(edit_type_particles, 0); + graph->get_zoom_hbox()->add_child(edit_type_standart); + graph->get_zoom_hbox()->move_child(edit_type_standart, 0); + + add_node = memnew(Button); + add_node->set_flat(true); graph->get_zoom_hbox()->add_child(add_node); add_node->set_text(TTR("Add Node...")); graph->get_zoom_hbox()->move_child(add_node, 0); add_node->connect("pressed", callable_mp(this, &VisualShaderEditor::_show_members_dialog), varray(false)); - preview_shader = memnew(ToolButton); + preview_shader = memnew(Button); + preview_shader->set_flat(true); preview_shader->set_toggle_mode(true); - preview_shader->set_tooltip(TTR("Show resulted shader code.")); + preview_shader->set_tooltip(TTR("Show generated shader code.")); graph->get_zoom_hbox()->add_child(preview_shader); preview_shader->connect("pressed", callable_mp(this, &VisualShaderEditor::_show_preview_text)); /////////////////////////////////////// - // PREVIEW PANEL + // PREVIEW WINDOW /////////////////////////////////////// + preview_window = memnew(Window); + preview_window->set_title(TTR("Generated shader code")); + preview_window->set_visible(preview_showed); + preview_window->connect("close_requested", callable_mp(this, &VisualShaderEditor::_preview_close_requested)); + preview_window->connect("size_changed", callable_mp(this, &VisualShaderEditor::_preview_size_changed)); + add_child(preview_window); + preview_vbox = memnew(VBoxContainer); - preview_vbox->set_visible(preview_showed); - main_box->add_child(preview_vbox); - preview_text = memnew(TextEdit); + preview_window->add_child(preview_vbox); + + preview_text = memnew(CodeEdit); + syntax_highlighter.instance(); preview_vbox->add_child(preview_text); - preview_text->set_h_size_flags(SIZE_EXPAND_FILL); - preview_text->set_v_size_flags(SIZE_EXPAND_FILL); - preview_text->set_custom_minimum_size(Size2(400 * EDSCALE, 0)); - preview_text->set_syntax_coloring(true); - preview_text->set_show_line_numbers(true); + preview_text->set_v_size_flags(Control::SIZE_EXPAND_FILL); + preview_text->set_syntax_highlighter(syntax_highlighter); + preview_text->set_draw_line_numbers(true); preview_text->set_readonly(true); error_text = memnew(Label); preview_vbox->add_child(error_text); + error_text->set_autowrap(true); error_text->set_visible(false); /////////////////////////////////////// @@ -2379,12 +3450,12 @@ VisualShaderEditor::VisualShaderEditor() { popup_menu = memnew(PopupMenu); add_child(popup_menu); - popup_menu->add_item("Add Node", NodeMenuOptions::ADD); + popup_menu->add_item(TTR("Add Node"), NodeMenuOptions::ADD); popup_menu->add_separator(); - popup_menu->add_item("Copy", NodeMenuOptions::COPY); - popup_menu->add_item("Paste", NodeMenuOptions::PASTE); - popup_menu->add_item("Delete", NodeMenuOptions::DELETE); - popup_menu->add_item("Duplicate", NodeMenuOptions::DUPLICATE); + popup_menu->add_item(TTR("Copy"), NodeMenuOptions::COPY); + popup_menu->add_item(TTR("Paste"), NodeMenuOptions::PASTE); + popup_menu->add_item(TTR("Delete"), NodeMenuOptions::DELETE); + popup_menu->add_item(TTR("Duplicate"), NodeMenuOptions::DUPLICATE); popup_menu->connect("id_pressed", callable_mp(this, &VisualShaderEditor::_node_menu_id_pressed)); /////////////////////////////////////// @@ -2448,10 +3519,11 @@ VisualShaderEditor::VisualShaderEditor() { members_dialog = memnew(ConfirmationDialog); members_dialog->set_title(TTR("Create Shader Node")); + members_dialog->set_exclusive(false); members_dialog->add_child(members_vb); - members_dialog->get_ok()->set_text(TTR("Create")); - members_dialog->get_ok()->connect("pressed", callable_mp(this, &VisualShaderEditor::_member_create)); - members_dialog->get_ok()->set_disabled(true); + members_dialog->get_ok_button()->set_text(TTR("Create")); + members_dialog->get_ok_button()->connect("pressed", callable_mp(this, &VisualShaderEditor::_member_create)); + members_dialog->get_ok_button()->set_disabled(true); members_dialog->connect("cancelled", callable_mp(this, &VisualShaderEditor::_member_cancel)); add_child(members_dialog); @@ -2502,8 +3574,11 @@ VisualShaderEditor::VisualShaderEditor() { add_options.push_back(AddOption("LessThan", "Conditional", "Functions", "VisualShaderNodeCompare", vformat(compare_func_desc, TTR("Less Than (<)")), VisualShaderNodeCompare::FUNC_LESS_THAN, VisualShaderNode::PORT_TYPE_BOOLEAN)); add_options.push_back(AddOption("LessThanEqual", "Conditional", "Functions", "VisualShaderNodeCompare", vformat(compare_func_desc, TTR("Less Than or Equal (<=)")), VisualShaderNodeCompare::FUNC_LESS_THAN_EQUAL, VisualShaderNode::PORT_TYPE_BOOLEAN)); add_options.push_back(AddOption("NotEqual", "Conditional", "Functions", "VisualShaderNodeCompare", vformat(compare_func_desc, TTR("Not Equal (!=)")), VisualShaderNodeCompare::FUNC_NOT_EQUAL, VisualShaderNode::PORT_TYPE_BOOLEAN)); - add_options.push_back(AddOption("Switch", "Conditional", "Functions", "VisualShaderNodeSwitch", TTR("Returns an associated vector if the provided boolean value is true or false."), -1, VisualShaderNode::PORT_TYPE_VECTOR)); - add_options.push_back(AddOption("SwitchS", "Conditional", "Functions", "VisualShaderNodeScalarSwitch", TTR("Returns an associated scalar if the provided boolean value is true or false."), -1, VisualShaderNode::PORT_TYPE_SCALAR)); + add_options.push_back(AddOption("Switch", "Conditional", "Functions", "VisualShaderNodeSwitch", TTR("Returns an associated vector if the provided boolean value is true or false."), VisualShaderNodeSwitch::OP_TYPE_VECTOR, VisualShaderNode::PORT_TYPE_VECTOR)); + add_options.push_back(AddOption("SwitchBool", "Conditional", "Functions", "VisualShaderNodeSwitch", TTR("Returns an associated boolean if the provided boolean value is true or false."), VisualShaderNodeSwitch::OP_TYPE_BOOLEAN, VisualShaderNode::PORT_TYPE_BOOLEAN)); + add_options.push_back(AddOption("SwitchFloat", "Conditional", "Functions", "VisualShaderNodeSwitch", TTR("Returns an associated floating-point scalar if the provided boolean value is true or false."), VisualShaderNodeSwitch::OP_TYPE_FLOAT, VisualShaderNode::PORT_TYPE_SCALAR)); + add_options.push_back(AddOption("SwitchInt", "Conditional", "Functions", "VisualShaderNodeSwitch", TTR("Returns an associated integer scalar if the provided boolean value is true or false."), VisualShaderNodeSwitch::OP_TYPE_INT, VisualShaderNode::PORT_TYPE_SCALAR_INT)); + add_options.push_back(AddOption("SwitchTransform", "Conditional", "Functions", "VisualShaderNodeSwitch", TTR("Returns an associated transform if the provided boolean value is true or false."), VisualShaderNodeSwitch::OP_TYPE_TRANSFORM, VisualShaderNode::PORT_TYPE_TRANSFORM)); add_options.push_back(AddOption("Compare", "Conditional", "Common", "VisualShaderNodeCompare", TTR("Returns the boolean result of the comparison between two parameters."), -1, VisualShaderNode::PORT_TYPE_BOOLEAN)); add_options.push_back(AddOption("Is", "Conditional", "Common", "VisualShaderNodeIs", TTR("Returns the boolean result of the comparison between INF (or NaN) and a scalar parameter."), -1, VisualShaderNode::PORT_TYPE_BOOLEAN)); @@ -2514,13 +3589,14 @@ VisualShaderEditor::VisualShaderEditor() { // INPUT // SPATIAL-FOR-ALL + const String input_param_shader_modes = TTR("'%s' input parameter for all shader modes."); add_options.push_back(AddOption("Camera", "Input", "All", "VisualShaderNodeInput", vformat(input_param_shader_modes, "camera"), "camera", VisualShaderNode::PORT_TYPE_TRANSFORM, -1, Shader::MODE_SPATIAL)); add_options.push_back(AddOption("InvCamera", "Input", "All", "VisualShaderNodeInput", vformat(input_param_shader_modes, "inv_camera"), "inv_camera", VisualShaderNode::PORT_TYPE_TRANSFORM, -1, Shader::MODE_SPATIAL)); add_options.push_back(AddOption("InvProjection", "Input", "All", "VisualShaderNodeInput", vformat(input_param_shader_modes, "inv_projection"), "inv_projection", VisualShaderNode::PORT_TYPE_TRANSFORM, -1, Shader::MODE_SPATIAL)); add_options.push_back(AddOption("Normal", "Input", "All", "VisualShaderNodeInput", vformat(input_param_shader_modes, "normal"), "normal", VisualShaderNode::PORT_TYPE_VECTOR, -1, Shader::MODE_SPATIAL)); add_options.push_back(AddOption("OutputIsSRGB", "Input", "All", "VisualShaderNodeInput", vformat(input_param_shader_modes, "output_is_srgb"), "output_is_srgb", VisualShaderNode::PORT_TYPE_BOOLEAN, -1, Shader::MODE_SPATIAL)); - add_options.push_back(AddOption("Projection", "Input", "All", "VisualShaderNodeInput", vformat(input_param_shader_modes, "camera"), "projection", VisualShaderNode::PORT_TYPE_TRANSFORM, -1, Shader::MODE_SPATIAL)); + add_options.push_back(AddOption("Projection", "Input", "All", "VisualShaderNodeInput", vformat(input_param_shader_modes, "projection"), "projection", VisualShaderNode::PORT_TYPE_TRANSFORM, -1, Shader::MODE_SPATIAL)); add_options.push_back(AddOption("Time", "Input", "All", "VisualShaderNodeInput", vformat(input_param_shader_modes, "time"), "time", VisualShaderNode::PORT_TYPE_SCALAR, -1, Shader::MODE_SPATIAL)); add_options.push_back(AddOption("ViewportSize", "Input", "All", "VisualShaderNodeInput", vformat(input_param_shader_modes, "viewport_size"), "viewport_size", VisualShaderNode::PORT_TYPE_VECTOR, -1, Shader::MODE_SPATIAL)); add_options.push_back(AddOption("World", "Input", "All", "VisualShaderNodeInput", vformat(input_param_shader_modes, "world"), "world", VisualShaderNode::PORT_TYPE_TRANSFORM, -1, Shader::MODE_SPATIAL)); @@ -2544,124 +3620,162 @@ VisualShaderEditor::VisualShaderEditor() { const String input_param_for_fragment_shader_mode = TTR("'%s' input parameter for fragment shader mode."); const String input_param_for_light_shader_mode = TTR("'%s' input parameter for light shader mode."); const String input_param_for_vertex_shader_mode = TTR("'%s' input parameter for vertex shader mode."); + const String input_param_for_emit_shader_mode = TTR("'%s' input parameter for emit shader mode."); + const String input_param_for_process_shader_mode = TTR("'%s' input parameter for process shader mode."); + const String input_param_for_end_shader_mode = TTR("'%s' input parameter for end shader mode."); + const String input_param_for_emit_and_process_shader_mode = TTR("'%s' input parameter for emit and process shader mode."); const String input_param_for_vertex_and_fragment_shader_mode = TTR("'%s' input parameter for vertex and fragment shader mode."); - add_options.push_back(AddOption("Alpha", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_vertex_and_fragment_shader_modes, "alpha"), "alpha", VisualShaderNode::PORT_TYPE_SCALAR, VisualShader::TYPE_FRAGMENT, Shader::MODE_SPATIAL)); - add_options.push_back(AddOption("Binormal", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_vertex_and_fragment_shader_modes, "binormal"), "binormal", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_FRAGMENT, Shader::MODE_SPATIAL)); - add_options.push_back(AddOption("Color", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_vertex_and_fragment_shader_modes, "color"), "color", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_FRAGMENT, Shader::MODE_SPATIAL)); - add_options.push_back(AddOption("DepthTexture", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "depth_texture"), "depth_texture", VisualShaderNode::PORT_TYPE_SAMPLER, VisualShader::TYPE_FRAGMENT, Shader::MODE_SPATIAL)); - add_options.push_back(AddOption("FragCoord", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_and_light_shader_modes, "fragcoord"), "fragcoord", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_FRAGMENT, Shader::MODE_SPATIAL)); - add_options.push_back(AddOption("FrontFacing", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "front_facing"), "front_facing", VisualShaderNode::PORT_TYPE_BOOLEAN, VisualShader::TYPE_FRAGMENT, Shader::MODE_SPATIAL)); - add_options.push_back(AddOption("PointCoord", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "point_coord"), "point_coord", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_FRAGMENT, Shader::MODE_SPATIAL)); - add_options.push_back(AddOption("ScreenTexture", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "screen_texture"), "screen_texture", VisualShaderNode::PORT_TYPE_SAMPLER, VisualShader::TYPE_FRAGMENT, Shader::MODE_SPATIAL)); - add_options.push_back(AddOption("ScreenUV", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "screen_uv"), "screen_uv", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_FRAGMENT, Shader::MODE_SPATIAL)); - add_options.push_back(AddOption("Side", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "side"), "side", VisualShaderNode::PORT_TYPE_SCALAR, VisualShader::TYPE_FRAGMENT, Shader::MODE_SPATIAL)); - add_options.push_back(AddOption("Tangent", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_vertex_and_fragment_shader_modes, "tangent"), "tangent", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_FRAGMENT, Shader::MODE_SPATIAL)); - add_options.push_back(AddOption("UV", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_vertex_and_fragment_shader_modes, "uv"), "uv", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_FRAGMENT, Shader::MODE_SPATIAL)); - add_options.push_back(AddOption("UV2", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_vertex_and_fragment_shader_modes, "uv2"), "uv2", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_FRAGMENT, Shader::MODE_SPATIAL)); - add_options.push_back(AddOption("Vertex", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_vertex_and_fragment_shader_modes, "vertex"), "vertex", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_FRAGMENT, Shader::MODE_SPATIAL)); - add_options.push_back(AddOption("View", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_and_light_shader_modes, "view"), "view", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_FRAGMENT, Shader::MODE_SPATIAL)); - - add_options.push_back(AddOption("Albedo", "Input", "Light", "VisualShaderNodeInput", vformat(input_param_for_light_shader_mode, "albedo"), "albedo", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_LIGHT, Shader::MODE_SPATIAL)); - add_options.push_back(AddOption("Attenuation", "Input", "Light", "VisualShaderNodeInput", vformat(input_param_for_light_shader_mode, "attenuation"), "attenuation", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_LIGHT, Shader::MODE_SPATIAL)); - add_options.push_back(AddOption("Diffuse", "Input", "Light", "VisualShaderNodeInput", vformat(input_param_for_light_shader_mode, "diffuse"), "diffuse", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_LIGHT, Shader::MODE_SPATIAL)); - add_options.push_back(AddOption("FragCoord", "Input", "Light", "VisualShaderNodeInput", vformat(input_param_for_fragment_and_light_shader_modes, "fragcoord"), "fragcoord", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_LIGHT, Shader::MODE_SPATIAL)); - add_options.push_back(AddOption("Light", "Input", "Light", "VisualShaderNodeInput", vformat(input_param_for_light_shader_mode, "light"), "light", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_LIGHT, Shader::MODE_SPATIAL)); - add_options.push_back(AddOption("LightColor", "Input", "Light", "VisualShaderNodeInput", vformat(input_param_for_light_shader_mode, "light_color"), "light_color", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_LIGHT, Shader::MODE_SPATIAL)); - add_options.push_back(AddOption("Roughness", "Input", "Light", "VisualShaderNodeInput", vformat(input_param_for_light_shader_mode, "roughness"), "roughness", VisualShaderNode::PORT_TYPE_SCALAR, VisualShader::TYPE_LIGHT, Shader::MODE_SPATIAL)); - add_options.push_back(AddOption("Specular", "Input", "Light", "VisualShaderNodeInput", vformat(input_param_for_light_shader_mode, "specular"), "specular", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_LIGHT, Shader::MODE_SPATIAL)); - add_options.push_back(AddOption("Transmission", "Input", "Light", "VisualShaderNodeInput", vformat(input_param_for_light_shader_mode, "transmission"), "transmission", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_LIGHT, Shader::MODE_SPATIAL)); - add_options.push_back(AddOption("View", "Input", "Light", "VisualShaderNodeInput", vformat(input_param_for_fragment_and_light_shader_modes, "view"), "view", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_LIGHT, Shader::MODE_SPATIAL)); - - add_options.push_back(AddOption("Alpha", "Input", "Vertex", "VisualShaderNodeInput", vformat(input_param_for_vertex_and_fragment_shader_modes, "alpha"), "alpha", VisualShaderNode::PORT_TYPE_SCALAR, VisualShader::TYPE_VERTEX, Shader::MODE_SPATIAL)); - add_options.push_back(AddOption("Binormal", "Input", "Vertex", "VisualShaderNodeInput", vformat(input_param_for_vertex_and_fragment_shader_modes, "binormal"), "binormal", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_VERTEX, Shader::MODE_SPATIAL)); - add_options.push_back(AddOption("Color", "Input", "Vertex", "VisualShaderNodeInput", vformat(input_param_for_vertex_and_fragment_shader_modes, "color"), "color", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_VERTEX, Shader::MODE_SPATIAL)); - add_options.push_back(AddOption("ModelView", "Input", "Vertex", "VisualShaderNodeInput", vformat(input_param_for_vertex_shader_mode, "modelview"), "modelview", VisualShaderNode::PORT_TYPE_TRANSFORM, VisualShader::TYPE_VERTEX, Shader::MODE_SPATIAL)); - add_options.push_back(AddOption("PointSize", "Input", "Vertex", "VisualShaderNodeInput", vformat(input_param_for_vertex_shader_mode, "point_size"), "point_size", VisualShaderNode::PORT_TYPE_SCALAR, VisualShader::TYPE_VERTEX, Shader::MODE_SPATIAL)); - add_options.push_back(AddOption("Tangent", "Input", "Vertex", "VisualShaderNodeInput", vformat(input_param_for_vertex_and_fragment_shader_mode, "tangent"), "tangent", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_VERTEX, Shader::MODE_SPATIAL)); - add_options.push_back(AddOption("UV", "Input", "Vertex", "VisualShaderNodeInput", vformat(input_param_for_vertex_and_fragment_shader_modes, "uv"), "uv", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_VERTEX, Shader::MODE_SPATIAL)); - add_options.push_back(AddOption("UV2", "Input", "Vertex", "VisualShaderNodeInput", vformat(input_param_for_vertex_and_fragment_shader_modes, "uv2"), "uv2", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_VERTEX, Shader::MODE_SPATIAL)); - add_options.push_back(AddOption("Vertex", "Input", "Vertex", "VisualShaderNodeInput", vformat(input_param_for_vertex_and_fragment_shader_modes, "vertex"), "vertex", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_VERTEX, Shader::MODE_SPATIAL)); + add_options.push_back(AddOption("Alpha", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_vertex_and_fragment_shader_modes, "alpha"), "alpha", VisualShaderNode::PORT_TYPE_SCALAR, TYPE_FLAGS_FRAGMENT, Shader::MODE_SPATIAL)); + add_options.push_back(AddOption("Binormal", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_vertex_and_fragment_shader_modes, "binormal"), "binormal", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_FRAGMENT, Shader::MODE_SPATIAL)); + add_options.push_back(AddOption("Color", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_vertex_and_fragment_shader_modes, "color"), "color", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_FRAGMENT, Shader::MODE_SPATIAL)); + add_options.push_back(AddOption("DepthTexture", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "depth_texture"), "depth_texture", VisualShaderNode::PORT_TYPE_SAMPLER, TYPE_FLAGS_FRAGMENT, Shader::MODE_SPATIAL)); + add_options.push_back(AddOption("FragCoord", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_and_light_shader_modes, "fragcoord"), "fragcoord", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_FRAGMENT, Shader::MODE_SPATIAL)); + add_options.push_back(AddOption("FrontFacing", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "front_facing"), "front_facing", VisualShaderNode::PORT_TYPE_BOOLEAN, TYPE_FLAGS_FRAGMENT, Shader::MODE_SPATIAL)); + add_options.push_back(AddOption("PointCoord", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "point_coord"), "point_coord", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_FRAGMENT, Shader::MODE_SPATIAL)); + add_options.push_back(AddOption("ScreenTexture", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "screen_texture"), "screen_texture", VisualShaderNode::PORT_TYPE_SAMPLER, TYPE_FLAGS_FRAGMENT, Shader::MODE_SPATIAL)); + add_options.push_back(AddOption("ScreenUV", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "screen_uv"), "screen_uv", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_FRAGMENT, Shader::MODE_SPATIAL)); + add_options.push_back(AddOption("Side", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "side"), "side", VisualShaderNode::PORT_TYPE_SCALAR, TYPE_FLAGS_FRAGMENT, Shader::MODE_SPATIAL)); + add_options.push_back(AddOption("Tangent", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_vertex_and_fragment_shader_modes, "tangent"), "tangent", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_FRAGMENT, Shader::MODE_SPATIAL)); + add_options.push_back(AddOption("UV", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_vertex_and_fragment_shader_modes, "uv"), "uv", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_FRAGMENT, Shader::MODE_SPATIAL)); + add_options.push_back(AddOption("UV2", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_vertex_and_fragment_shader_modes, "uv2"), "uv2", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_FRAGMENT, Shader::MODE_SPATIAL)); + add_options.push_back(AddOption("Vertex", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_vertex_and_fragment_shader_modes, "vertex"), "vertex", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_FRAGMENT, Shader::MODE_SPATIAL)); + add_options.push_back(AddOption("View", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_and_light_shader_modes, "view"), "view", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_FRAGMENT, Shader::MODE_SPATIAL)); + + add_options.push_back(AddOption("Albedo", "Input", "Light", "VisualShaderNodeInput", vformat(input_param_for_light_shader_mode, "albedo"), "albedo", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_LIGHT, Shader::MODE_SPATIAL)); + add_options.push_back(AddOption("Attenuation", "Input", "Light", "VisualShaderNodeInput", vformat(input_param_for_light_shader_mode, "attenuation"), "attenuation", VisualShaderNode::PORT_TYPE_SCALAR, TYPE_FLAGS_LIGHT, Shader::MODE_SPATIAL)); + add_options.push_back(AddOption("Diffuse", "Input", "Light", "VisualShaderNodeInput", vformat(input_param_for_light_shader_mode, "diffuse"), "diffuse", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_LIGHT, Shader::MODE_SPATIAL)); + add_options.push_back(AddOption("FragCoord", "Input", "Light", "VisualShaderNodeInput", vformat(input_param_for_fragment_and_light_shader_modes, "fragcoord"), "fragcoord", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_LIGHT, Shader::MODE_SPATIAL)); + add_options.push_back(AddOption("Light", "Input", "Light", "VisualShaderNodeInput", vformat(input_param_for_light_shader_mode, "light"), "light", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_LIGHT, Shader::MODE_SPATIAL)); + add_options.push_back(AddOption("LightColor", "Input", "Light", "VisualShaderNodeInput", vformat(input_param_for_light_shader_mode, "light_color"), "light_color", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_LIGHT, Shader::MODE_SPATIAL)); + add_options.push_back(AddOption("Metallic", "Input", "Light", "VisualShaderNodeInput", vformat(input_param_for_light_shader_mode, "metallic"), "metallic", VisualShaderNode::PORT_TYPE_SCALAR, TYPE_FLAGS_LIGHT, Shader::MODE_SPATIAL)); + add_options.push_back(AddOption("Roughness", "Input", "Light", "VisualShaderNodeInput", vformat(input_param_for_light_shader_mode, "roughness"), "roughness", VisualShaderNode::PORT_TYPE_SCALAR, TYPE_FLAGS_LIGHT, Shader::MODE_SPATIAL)); + add_options.push_back(AddOption("Specular", "Input", "Light", "VisualShaderNodeInput", vformat(input_param_for_light_shader_mode, "specular"), "specular", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_LIGHT, Shader::MODE_SPATIAL)); + add_options.push_back(AddOption("Backlight", "Input", "Light", "VisualShaderNodeInput", vformat(input_param_for_light_shader_mode, "backlight"), "backlight", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_LIGHT, Shader::MODE_SPATIAL)); + add_options.push_back(AddOption("View", "Input", "Light", "VisualShaderNodeInput", vformat(input_param_for_fragment_and_light_shader_modes, "view"), "view", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_LIGHT, Shader::MODE_SPATIAL)); + + add_options.push_back(AddOption("Alpha", "Input", "Vertex", "VisualShaderNodeInput", vformat(input_param_for_vertex_and_fragment_shader_modes, "alpha"), "alpha", VisualShaderNode::PORT_TYPE_SCALAR, TYPE_FLAGS_VERTEX, Shader::MODE_SPATIAL)); + add_options.push_back(AddOption("Binormal", "Input", "Vertex", "VisualShaderNodeInput", vformat(input_param_for_vertex_and_fragment_shader_modes, "binormal"), "binormal", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_VERTEX, Shader::MODE_SPATIAL)); + add_options.push_back(AddOption("Color", "Input", "Vertex", "VisualShaderNodeInput", vformat(input_param_for_vertex_and_fragment_shader_modes, "color"), "color", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_VERTEX, Shader::MODE_SPATIAL)); + add_options.push_back(AddOption("ModelView", "Input", "Vertex", "VisualShaderNodeInput", vformat(input_param_for_vertex_shader_mode, "modelview"), "modelview", VisualShaderNode::PORT_TYPE_TRANSFORM, TYPE_FLAGS_VERTEX, Shader::MODE_SPATIAL)); + add_options.push_back(AddOption("PointSize", "Input", "Vertex", "VisualShaderNodeInput", vformat(input_param_for_vertex_shader_mode, "point_size"), "point_size", VisualShaderNode::PORT_TYPE_SCALAR, TYPE_FLAGS_VERTEX, Shader::MODE_SPATIAL)); + add_options.push_back(AddOption("Tangent", "Input", "Vertex", "VisualShaderNodeInput", vformat(input_param_for_vertex_and_fragment_shader_mode, "tangent"), "tangent", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_VERTEX, Shader::MODE_SPATIAL)); + add_options.push_back(AddOption("UV", "Input", "Vertex", "VisualShaderNodeInput", vformat(input_param_for_vertex_and_fragment_shader_modes, "uv"), "uv", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_VERTEX, Shader::MODE_SPATIAL)); + add_options.push_back(AddOption("UV2", "Input", "Vertex", "VisualShaderNodeInput", vformat(input_param_for_vertex_and_fragment_shader_modes, "uv2"), "uv2", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_VERTEX, Shader::MODE_SPATIAL)); + add_options.push_back(AddOption("Vertex", "Input", "Vertex", "VisualShaderNodeInput", vformat(input_param_for_vertex_and_fragment_shader_modes, "vertex"), "vertex", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_VERTEX, Shader::MODE_SPATIAL)); // CANVASITEM INPUTS - add_options.push_back(AddOption("FragCoord", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_and_light_shader_modes, "fragcoord"), "fragcoord", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_FRAGMENT, Shader::MODE_CANVAS_ITEM)); - add_options.push_back(AddOption("LightPass", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_vertex_and_fragment_shader_modes, "light_pass"), "light_pass", VisualShaderNode::PORT_TYPE_SCALAR, VisualShader::TYPE_FRAGMENT, Shader::MODE_CANVAS_ITEM)); - add_options.push_back(AddOption("NormalTexture", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "normal_texture"), "normal_texture", VisualShaderNode::PORT_TYPE_SAMPLER, VisualShader::TYPE_FRAGMENT, Shader::MODE_CANVAS_ITEM)); - add_options.push_back(AddOption("PointCoord", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_and_light_shader_modes, "point_coord"), "point_coord", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_FRAGMENT, Shader::MODE_CANVAS_ITEM)); - add_options.push_back(AddOption("ScreenPixelSize", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "screen_pixel_size"), "screen_pixel_size", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_FRAGMENT, Shader::MODE_CANVAS_ITEM)); - add_options.push_back(AddOption("ScreenTexture", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "screen_texture"), "screen_texture", VisualShaderNode::PORT_TYPE_SAMPLER, VisualShader::TYPE_FRAGMENT, Shader::MODE_CANVAS_ITEM)); - add_options.push_back(AddOption("ScreenUV", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_and_light_shader_modes, "screen_uv"), "screen_uv", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_FRAGMENT, Shader::MODE_CANVAS_ITEM)); - add_options.push_back(AddOption("Texture", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_and_light_shader_modes, "texture"), "texture", VisualShaderNode::PORT_TYPE_SAMPLER, VisualShader::TYPE_FRAGMENT, Shader::MODE_CANVAS_ITEM)); - - add_options.push_back(AddOption("FragCoord", "Input", "Light", "VisualShaderNodeInput", vformat(input_param_for_fragment_and_light_shader_modes, "fragcoord"), "fragcoord", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_LIGHT, Shader::MODE_CANVAS_ITEM)); - add_options.push_back(AddOption("LightAlpha", "Input", "Light", "VisualShaderNodeInput", vformat(input_param_for_light_shader_mode, "light_alpha"), "light_alpha", VisualShaderNode::PORT_TYPE_SCALAR, VisualShader::TYPE_LIGHT, Shader::MODE_CANVAS_ITEM)); - add_options.push_back(AddOption("LightColor", "Input", "Light", "VisualShaderNodeInput", vformat(input_param_for_light_shader_mode, "light_color"), "light_color", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_LIGHT, Shader::MODE_CANVAS_ITEM)); - add_options.push_back(AddOption("LightHeight", "Input", "Light", "VisualShaderNodeInput", vformat(input_param_for_light_shader_mode, "light_height"), "light_height", VisualShaderNode::PORT_TYPE_SCALAR, VisualShader::TYPE_LIGHT, Shader::MODE_CANVAS_ITEM)); - add_options.push_back(AddOption("LightUV", "Input", "Light", "VisualShaderNodeInput", vformat(input_param_for_light_shader_mode, "light_uv"), "light_uv", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_LIGHT, Shader::MODE_CANVAS_ITEM)); - add_options.push_back(AddOption("LightVector", "Input", "Light", "VisualShaderNodeInput", vformat(input_param_for_light_shader_mode, "light_vec"), "light_vec", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_LIGHT, Shader::MODE_CANVAS_ITEM)); - add_options.push_back(AddOption("Normal", "Input", "Light", "VisualShaderNodeInput", vformat(input_param_for_light_shader_mode, "normal"), "normal", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_LIGHT, Shader::MODE_CANVAS_ITEM)); - add_options.push_back(AddOption("PointCoord", "Input", "Light", "VisualShaderNodeInput", vformat(input_param_for_fragment_and_light_shader_modes, "point_coord"), "point_coord", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_LIGHT, Shader::MODE_CANVAS_ITEM)); - add_options.push_back(AddOption("ScreenUV", "Input", "Light", "VisualShaderNodeInput", vformat(input_param_for_fragment_and_light_shader_modes, "screen_uv"), "screen_uv", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_LIGHT, Shader::MODE_CANVAS_ITEM)); - add_options.push_back(AddOption("ShadowAlpha", "Input", "Light", "VisualShaderNodeInput", vformat(input_param_for_light_shader_mode, "shadow_alpha"), "shadow_alpha", VisualShaderNode::PORT_TYPE_SCALAR, VisualShader::TYPE_LIGHT, Shader::MODE_CANVAS_ITEM)); - add_options.push_back(AddOption("ShadowColor", "Input", "Light", "VisualShaderNodeInput", vformat(input_param_for_light_shader_mode, "shadow_color"), "shadow_color", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_LIGHT, Shader::MODE_CANVAS_ITEM)); - add_options.push_back(AddOption("ShadowVec", "Input", "Light", "VisualShaderNodeInput", vformat(input_param_for_light_shader_mode, "shadow_vec"), "shadow_vec", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_LIGHT, Shader::MODE_CANVAS_ITEM)); - add_options.push_back(AddOption("Texture", "Input", "Light", "VisualShaderNodeInput", vformat(input_param_for_fragment_and_light_shader_modes, "texture"), "texture", VisualShaderNode::PORT_TYPE_SAMPLER, VisualShader::TYPE_LIGHT, Shader::MODE_CANVAS_ITEM)); - - add_options.push_back(AddOption("Extra", "Input", "Vertex", "VisualShaderNodeInput", vformat(input_param_for_vertex_shader_mode, "extra"), "extra", VisualShaderNode::PORT_TYPE_TRANSFORM, VisualShader::TYPE_VERTEX, Shader::MODE_CANVAS_ITEM)); - add_options.push_back(AddOption("LightPass", "Input", "Vertex", "VisualShaderNodeInput", vformat(input_param_for_vertex_and_fragment_shader_modes, "light_pass"), "light_pass", VisualShaderNode::PORT_TYPE_SCALAR, VisualShader::TYPE_VERTEX, Shader::MODE_CANVAS_ITEM)); - add_options.push_back(AddOption("PointSize", "Input", "Vertex", "VisualShaderNodeInput", vformat(input_param_for_vertex_shader_mode, "point_size"), "point_size", VisualShaderNode::PORT_TYPE_SCALAR, VisualShader::TYPE_VERTEX, Shader::MODE_CANVAS_ITEM)); - add_options.push_back(AddOption("Projection", "Input", "Vertex", "VisualShaderNodeInput", vformat(input_param_for_vertex_shader_mode, "projection"), "projection", VisualShaderNode::PORT_TYPE_TRANSFORM, VisualShader::TYPE_VERTEX, Shader::MODE_CANVAS_ITEM)); - add_options.push_back(AddOption("Vertex", "Input", "Vertex", "VisualShaderNodeInput", vformat(input_param_for_vertex_shader_mode, "vertex"), "vertex", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_VERTEX, Shader::MODE_CANVAS_ITEM)); - add_options.push_back(AddOption("World", "Input", "Vertex", "VisualShaderNodeInput", vformat(input_param_for_vertex_shader_mode, "world"), "world", VisualShaderNode::PORT_TYPE_TRANSFORM, VisualShader::TYPE_VERTEX, Shader::MODE_CANVAS_ITEM)); + add_options.push_back(AddOption("AtLightPass", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_vertex_and_fragment_shader_modes, "at_light_pass"), "at_light_pass", VisualShaderNode::PORT_TYPE_BOOLEAN, TYPE_FLAGS_FRAGMENT, Shader::MODE_CANVAS_ITEM)); + add_options.push_back(AddOption("FragCoord", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_and_light_shader_modes, "fragcoord"), "fragcoord", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_FRAGMENT, Shader::MODE_CANVAS_ITEM)); + add_options.push_back(AddOption("NormalTexture", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "normal_texture"), "normal_texture", VisualShaderNode::PORT_TYPE_SAMPLER, TYPE_FLAGS_FRAGMENT, Shader::MODE_CANVAS_ITEM)); + add_options.push_back(AddOption("PointCoord", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_and_light_shader_modes, "point_coord"), "point_coord", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_FRAGMENT, Shader::MODE_CANVAS_ITEM)); + add_options.push_back(AddOption("ScreenPixelSize", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "screen_pixel_size"), "screen_pixel_size", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_FRAGMENT, Shader::MODE_CANVAS_ITEM)); + add_options.push_back(AddOption("ScreenTexture", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "screen_texture"), "screen_texture", VisualShaderNode::PORT_TYPE_SAMPLER, TYPE_FLAGS_FRAGMENT, Shader::MODE_CANVAS_ITEM)); + add_options.push_back(AddOption("ScreenUV", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_and_light_shader_modes, "screen_uv"), "screen_uv", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_FRAGMENT, Shader::MODE_CANVAS_ITEM)); + add_options.push_back(AddOption("SpecularShininess", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_and_light_shader_modes, "specular_shininess"), "specular_shininess", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_FRAGMENT, Shader::MODE_CANVAS_ITEM)); + add_options.push_back(AddOption("SpecularShininessAlpha", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_and_light_shader_modes, "specular_shininess_alpha"), "specular_shininess_alpha", VisualShaderNode::PORT_TYPE_SCALAR, TYPE_FLAGS_FRAGMENT, Shader::MODE_CANVAS_ITEM)); + add_options.push_back(AddOption("SpecularShininessTexture", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "specular_shininess_texture"), "specular_shininess_texture", VisualShaderNode::PORT_TYPE_SAMPLER, TYPE_FLAGS_FRAGMENT, Shader::MODE_CANVAS_ITEM)); + add_options.push_back(AddOption("Texture", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_and_light_shader_modes, "texture"), "texture", VisualShaderNode::PORT_TYPE_SAMPLER, TYPE_FLAGS_FRAGMENT, Shader::MODE_CANVAS_ITEM)); + + add_options.push_back(AddOption("FragCoord", "Input", "Light", "VisualShaderNodeInput", vformat(input_param_for_fragment_and_light_shader_modes, "fragcoord"), "fragcoord", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_LIGHT, Shader::MODE_CANVAS_ITEM)); + add_options.push_back(AddOption("Light", "Input", "Light", "VisualShaderNodeInput", vformat(input_param_for_light_shader_mode, "light"), "light", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_LIGHT, Shader::MODE_CANVAS_ITEM)); + add_options.push_back(AddOption("LightAlpha", "Input", "Light", "VisualShaderNodeInput", vformat(input_param_for_light_shader_mode, "light_alpha"), "light_alpha", VisualShaderNode::PORT_TYPE_SCALAR, TYPE_FLAGS_LIGHT, Shader::MODE_CANVAS_ITEM)); + add_options.push_back(AddOption("LightColor", "Input", "Light", "VisualShaderNodeInput", vformat(input_param_for_light_shader_mode, "light_color"), "light_color", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_LIGHT, Shader::MODE_CANVAS_ITEM)); + add_options.push_back(AddOption("LightColorAlpha", "Input", "Light", "VisualShaderNodeInput", vformat(input_param_for_light_shader_mode, "light_color_alpha"), "light_color_alpha", VisualShaderNode::PORT_TYPE_SCALAR, TYPE_FLAGS_LIGHT, Shader::MODE_CANVAS_ITEM)); + add_options.push_back(AddOption("LightPosition", "Input", "Light", "VisualShaderNodeInput", vformat(input_param_for_light_shader_mode, "light_position"), "light_position", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_LIGHT, Shader::MODE_CANVAS_ITEM)); + add_options.push_back(AddOption("LightVertex", "Input", "Light", "VisualShaderNodeInput", vformat(input_param_for_light_shader_mode, "light_vertex"), "light_vertex", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_LIGHT, Shader::MODE_CANVAS_ITEM)); + add_options.push_back(AddOption("Normal", "Input", "Light", "VisualShaderNodeInput", vformat(input_param_for_light_shader_mode, "normal"), "normal", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_LIGHT, Shader::MODE_CANVAS_ITEM)); + add_options.push_back(AddOption("PointCoord", "Input", "Light", "VisualShaderNodeInput", vformat(input_param_for_fragment_and_light_shader_modes, "point_coord"), "point_coord", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_LIGHT, Shader::MODE_CANVAS_ITEM)); + add_options.push_back(AddOption("ScreenUV", "Input", "Light", "VisualShaderNodeInput", vformat(input_param_for_fragment_and_light_shader_modes, "screen_uv"), "screen_uv", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_LIGHT, Shader::MODE_CANVAS_ITEM)); + add_options.push_back(AddOption("ShadowAlpha", "Input", "Light", "VisualShaderNodeInput", vformat(input_param_for_light_shader_mode, "shadow_alpha"), "shadow_alpha", VisualShaderNode::PORT_TYPE_SCALAR, TYPE_FLAGS_LIGHT, Shader::MODE_CANVAS_ITEM)); + add_options.push_back(AddOption("ShadowColor", "Input", "Light", "VisualShaderNodeInput", vformat(input_param_for_light_shader_mode, "shadow_color"), "shadow_color", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_LIGHT, Shader::MODE_CANVAS_ITEM)); + add_options.push_back(AddOption("SpecularShininess", "Input", "Light", "VisualShaderNodeInput", vformat(input_param_for_fragment_and_light_shader_modes, "specular_shininess"), "specular_shininess", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_LIGHT, Shader::MODE_CANVAS_ITEM)); + add_options.push_back(AddOption("SpecularShininessAlpha", "Input", "Light", "VisualShaderNodeInput", vformat(input_param_for_fragment_and_light_shader_modes, "specular_shininess_alpha"), "specular_shininess_alpha", VisualShaderNode::PORT_TYPE_SCALAR, TYPE_FLAGS_LIGHT, Shader::MODE_CANVAS_ITEM)); + add_options.push_back(AddOption("Texture", "Input", "Light", "VisualShaderNodeInput", vformat(input_param_for_fragment_and_light_shader_modes, "texture"), "texture", VisualShaderNode::PORT_TYPE_SAMPLER, TYPE_FLAGS_LIGHT, Shader::MODE_CANVAS_ITEM)); + + add_options.push_back(AddOption("AtLightPass", "Input", "Vertex", "VisualShaderNodeInput", vformat(input_param_for_vertex_and_fragment_shader_modes, "at_light_pass"), "at_light_pass", VisualShaderNode::PORT_TYPE_BOOLEAN, TYPE_FLAGS_VERTEX, Shader::MODE_CANVAS_ITEM)); + add_options.push_back(AddOption("Canvas", "Input", "Vertex", "VisualShaderNodeInput", vformat(input_param_for_vertex_shader_mode, "canvas"), "canvas", VisualShaderNode::PORT_TYPE_TRANSFORM, TYPE_FLAGS_VERTEX, Shader::MODE_CANVAS_ITEM)); + add_options.push_back(AddOption("PointSize", "Input", "Vertex", "VisualShaderNodeInput", vformat(input_param_for_vertex_shader_mode, "point_size"), "point_size", VisualShaderNode::PORT_TYPE_SCALAR, TYPE_FLAGS_VERTEX, Shader::MODE_CANVAS_ITEM)); + add_options.push_back(AddOption("Screen", "Input", "Vertex", "VisualShaderNodeInput", vformat(input_param_for_vertex_shader_mode, "screen"), "screen", VisualShaderNode::PORT_TYPE_TRANSFORM, TYPE_FLAGS_VERTEX, Shader::MODE_CANVAS_ITEM)); + add_options.push_back(AddOption("Vertex", "Input", "Vertex", "VisualShaderNodeInput", vformat(input_param_for_vertex_shader_mode, "vertex"), "vertex", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_VERTEX, Shader::MODE_CANVAS_ITEM)); + add_options.push_back(AddOption("World", "Input", "Vertex", "VisualShaderNodeInput", vformat(input_param_for_vertex_shader_mode, "world"), "world", VisualShaderNode::PORT_TYPE_TRANSFORM, TYPE_FLAGS_VERTEX, Shader::MODE_CANVAS_ITEM)); // PARTICLES INPUTS - add_options.push_back(AddOption("Active", "Input", "Vertex", "VisualShaderNodeInput", vformat(input_param_for_vertex_shader_mode, "active"), "active", VisualShaderNode::PORT_TYPE_SCALAR, VisualShader::TYPE_VERTEX, Shader::MODE_PARTICLES)); - add_options.push_back(AddOption("Alpha", "Input", "Vertex", "VisualShaderNodeInput", vformat(input_param_for_vertex_shader_mode, "alpha"), "alpha", VisualShaderNode::PORT_TYPE_SCALAR, VisualShader::TYPE_VERTEX, Shader::MODE_PARTICLES)); - add_options.push_back(AddOption("Color", "Input", "Vertex", "VisualShaderNodeInput", vformat(input_param_for_vertex_shader_mode, "color"), "color", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_VERTEX, Shader::MODE_PARTICLES)); - add_options.push_back(AddOption("Custom", "Input", "Vertex", "VisualShaderNodeInput", vformat(input_param_for_vertex_shader_mode, "custom"), "custom", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_VERTEX, Shader::MODE_PARTICLES)); - add_options.push_back(AddOption("CustomAlpha", "Input", "Vertex", "VisualShaderNodeInput", vformat(input_param_for_vertex_shader_mode, "custom_alpha"), "custom_alpha", VisualShaderNode::PORT_TYPE_SCALAR, VisualShader::TYPE_VERTEX, Shader::MODE_PARTICLES)); - add_options.push_back(AddOption("Delta", "Input", "Vertex", "VisualShaderNodeInput", vformat(input_param_for_vertex_shader_mode, "delta"), "delta", VisualShaderNode::PORT_TYPE_SCALAR, VisualShader::TYPE_VERTEX, Shader::MODE_PARTICLES)); - add_options.push_back(AddOption("EmissionTransform", "Input", "Vertex", "VisualShaderNodeInput", vformat(input_param_for_vertex_shader_mode, "emission_transform"), "emission_transform", VisualShaderNode::PORT_TYPE_TRANSFORM, VisualShader::TYPE_VERTEX, Shader::MODE_PARTICLES)); - add_options.push_back(AddOption("Index", "Input", "Vertex", "VisualShaderNodeInput", vformat(input_param_for_vertex_shader_mode, "index"), "index", VisualShaderNode::PORT_TYPE_SCALAR_INT, VisualShader::TYPE_VERTEX, Shader::MODE_PARTICLES)); - add_options.push_back(AddOption("LifeTime", "Input", "Vertex", "VisualShaderNodeInput", vformat(input_param_for_vertex_shader_mode, "lifetime"), "lifetime", VisualShaderNode::PORT_TYPE_SCALAR, VisualShader::TYPE_VERTEX, Shader::MODE_PARTICLES)); - add_options.push_back(AddOption("Restart", "Input", "Vertex", "VisualShaderNodeInput", vformat(input_param_for_vertex_shader_mode, "restart"), "restart", VisualShaderNode::PORT_TYPE_SCALAR, VisualShader::TYPE_VERTEX, Shader::MODE_PARTICLES)); - add_options.push_back(AddOption("Time", "Input", "Vertex", "VisualShaderNodeInput", vformat(input_param_for_vertex_shader_mode, "time"), "time", VisualShaderNode::PORT_TYPE_SCALAR, VisualShader::TYPE_VERTEX, Shader::MODE_PARTICLES)); - add_options.push_back(AddOption("Transform", "Input", "Vertex", "VisualShaderNodeInput", vformat(input_param_for_vertex_shader_mode, "transform"), "transform", VisualShaderNode::PORT_TYPE_TRANSFORM, VisualShader::TYPE_VERTEX, Shader::MODE_PARTICLES)); - add_options.push_back(AddOption("Velocity", "Input", "Vertex", "VisualShaderNodeInput", vformat(input_param_for_vertex_shader_mode, "velocity"), "velocity", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_VERTEX, Shader::MODE_PARTICLES)); + add_options.push_back(AddOption("Active", "Input", "Emit", "VisualShaderNodeInput", vformat(input_param_shader_modes, "active"), "active", VisualShaderNode::PORT_TYPE_SCALAR, TYPE_FLAGS_EMIT, Shader::MODE_PARTICLES)); + add_options.push_back(AddOption("Alpha", "Input", "Emit", "VisualShaderNodeInput", vformat(input_param_shader_modes, "alpha"), "alpha", VisualShaderNode::PORT_TYPE_SCALAR, TYPE_FLAGS_EMIT, Shader::MODE_PARTICLES)); + add_options.push_back(AddOption("Color", "Input", "Emit", "VisualShaderNodeInput", vformat(input_param_shader_modes, "color"), "color", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_EMIT, Shader::MODE_PARTICLES)); + add_options.push_back(AddOption("Custom", "Input", "Emit", "VisualShaderNodeInput", vformat(input_param_shader_modes, "custom"), "custom", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_EMIT, Shader::MODE_PARTICLES)); + add_options.push_back(AddOption("CustomAlpha", "Input", "Emit", "VisualShaderNodeInput", vformat(input_param_shader_modes, "custom_alpha"), "custom_alpha", VisualShaderNode::PORT_TYPE_SCALAR, TYPE_FLAGS_EMIT, Shader::MODE_PARTICLES)); + add_options.push_back(AddOption("Delta", "Input", "Emit", "VisualShaderNodeInput", vformat(input_param_shader_modes, "delta"), "delta", VisualShaderNode::PORT_TYPE_SCALAR, TYPE_FLAGS_EMIT, Shader::MODE_PARTICLES)); + add_options.push_back(AddOption("EmissionTransform", "Input", "Emit", "VisualShaderNodeInput", vformat(input_param_shader_modes, "emission_transform"), "emission_transform", VisualShaderNode::PORT_TYPE_TRANSFORM, TYPE_FLAGS_EMIT, Shader::MODE_PARTICLES)); + add_options.push_back(AddOption("Index", "Input", "Emit", "VisualShaderNodeInput", vformat(input_param_shader_modes, "index"), "index", VisualShaderNode::PORT_TYPE_SCALAR_INT, TYPE_FLAGS_EMIT, Shader::MODE_PARTICLES)); + add_options.push_back(AddOption("LifeTime", "Input", "Emit", "VisualShaderNodeInput", vformat(input_param_shader_modes, "lifetime"), "lifetime", VisualShaderNode::PORT_TYPE_SCALAR, TYPE_FLAGS_EMIT, Shader::MODE_PARTICLES)); + add_options.push_back(AddOption("Restart", "Input", "Emit", "VisualShaderNodeInput", vformat(input_param_shader_modes, "restart"), "restart", VisualShaderNode::PORT_TYPE_SCALAR, TYPE_FLAGS_EMIT, Shader::MODE_PARTICLES)); + add_options.push_back(AddOption("Time", "Input", "Emit", "VisualShaderNodeInput", vformat(input_param_shader_modes, "time"), "time", VisualShaderNode::PORT_TYPE_SCALAR, TYPE_FLAGS_EMIT, Shader::MODE_PARTICLES)); + add_options.push_back(AddOption("Transform", "Input", "Emit", "VisualShaderNodeInput", vformat(input_param_shader_modes, "transform"), "transform", VisualShaderNode::PORT_TYPE_TRANSFORM, TYPE_FLAGS_EMIT, Shader::MODE_PARTICLES)); + add_options.push_back(AddOption("Velocity", "Input", "Emit", "VisualShaderNodeInput", vformat(input_param_shader_modes, "velocity"), "velocity", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_EMIT, Shader::MODE_PARTICLES)); + + add_options.push_back(AddOption("Active", "Input", "Process", "VisualShaderNodeInput", vformat(input_param_shader_modes, "active"), "active", VisualShaderNode::PORT_TYPE_SCALAR, TYPE_FLAGS_PROCESS, Shader::MODE_PARTICLES)); + add_options.push_back(AddOption("Alpha", "Input", "Process", "VisualShaderNodeInput", vformat(input_param_shader_modes, "alpha"), "alpha", VisualShaderNode::PORT_TYPE_SCALAR, TYPE_FLAGS_PROCESS, Shader::MODE_PARTICLES)); + add_options.push_back(AddOption("Color", "Input", "Process", "VisualShaderNodeInput", vformat(input_param_shader_modes, "color"), "color", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_PROCESS, Shader::MODE_PARTICLES)); + add_options.push_back(AddOption("Custom", "Input", "Process", "VisualShaderNodeInput", vformat(input_param_shader_modes, "custom"), "custom", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_PROCESS, Shader::MODE_PARTICLES)); + add_options.push_back(AddOption("CustomAlpha", "Input", "Process", "VisualShaderNodeInput", vformat(input_param_shader_modes, "custom_alpha"), "custom_alpha", VisualShaderNode::PORT_TYPE_SCALAR, TYPE_FLAGS_PROCESS, Shader::MODE_PARTICLES)); + add_options.push_back(AddOption("Delta", "Input", "Process", "VisualShaderNodeInput", vformat(input_param_shader_modes, "delta"), "delta", VisualShaderNode::PORT_TYPE_SCALAR, TYPE_FLAGS_PROCESS, Shader::MODE_PARTICLES)); + add_options.push_back(AddOption("EmissionTransform", "Input", "Process", "VisualShaderNodeInput", vformat(input_param_shader_modes, "emission_transform"), "emission_transform", VisualShaderNode::PORT_TYPE_TRANSFORM, TYPE_FLAGS_PROCESS, Shader::MODE_PARTICLES)); + add_options.push_back(AddOption("Index", "Input", "Process", "VisualShaderNodeInput", vformat(input_param_shader_modes, "index"), "index", VisualShaderNode::PORT_TYPE_SCALAR_INT, TYPE_FLAGS_PROCESS, Shader::MODE_PARTICLES)); + add_options.push_back(AddOption("LifeTime", "Input", "Process", "VisualShaderNodeInput", vformat(input_param_shader_modes, "lifetime"), "lifetime", VisualShaderNode::PORT_TYPE_SCALAR, TYPE_FLAGS_PROCESS, Shader::MODE_PARTICLES)); + add_options.push_back(AddOption("Restart", "Input", "Process", "VisualShaderNodeInput", vformat(input_param_shader_modes, "restart"), "restart", VisualShaderNode::PORT_TYPE_SCALAR, TYPE_FLAGS_PROCESS, Shader::MODE_PARTICLES)); + add_options.push_back(AddOption("Time", "Input", "Process", "VisualShaderNodeInput", vformat(input_param_shader_modes, "time"), "time", VisualShaderNode::PORT_TYPE_SCALAR, TYPE_FLAGS_PROCESS, Shader::MODE_PARTICLES)); + add_options.push_back(AddOption("Transform", "Input", "Process", "VisualShaderNodeInput", vformat(input_param_shader_modes, "transform"), "transform", VisualShaderNode::PORT_TYPE_TRANSFORM, TYPE_FLAGS_PROCESS, Shader::MODE_PARTICLES)); + add_options.push_back(AddOption("Velocity", "Input", "Process", "VisualShaderNodeInput", vformat(input_param_shader_modes, "velocity"), "velocity", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_PROCESS, Shader::MODE_PARTICLES)); + + add_options.push_back(AddOption("Active", "Input", "End", "VisualShaderNodeInput", vformat(input_param_shader_modes, "active"), "active", VisualShaderNode::PORT_TYPE_SCALAR, TYPE_FLAGS_END, Shader::MODE_PARTICLES)); + add_options.push_back(AddOption("Alpha", "Input", "End", "VisualShaderNodeInput", vformat(input_param_shader_modes, "alpha"), "alpha", VisualShaderNode::PORT_TYPE_SCALAR, TYPE_FLAGS_END, Shader::MODE_PARTICLES)); + add_options.push_back(AddOption("Color", "Input", "End", "VisualShaderNodeInput", vformat(input_param_shader_modes, "color"), "color", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_END, Shader::MODE_PARTICLES)); + add_options.push_back(AddOption("Custom", "Input", "End", "VisualShaderNodeInput", vformat(input_param_shader_modes, "custom"), "custom", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_END, Shader::MODE_PARTICLES)); + add_options.push_back(AddOption("CustomAlpha", "Input", "End", "VisualShaderNodeInput", vformat(input_param_shader_modes, "custom_alpha"), "custom_alpha", VisualShaderNode::PORT_TYPE_SCALAR, TYPE_FLAGS_END, Shader::MODE_PARTICLES)); + add_options.push_back(AddOption("Delta", "Input", "End", "VisualShaderNodeInput", vformat(input_param_shader_modes, "delta"), "delta", VisualShaderNode::PORT_TYPE_SCALAR, TYPE_FLAGS_END, Shader::MODE_PARTICLES)); + add_options.push_back(AddOption("EmissionTransform", "Input", "End", "VisualShaderNodeInput", vformat(input_param_shader_modes, "emission_transform"), "emission_transform", VisualShaderNode::PORT_TYPE_TRANSFORM, TYPE_FLAGS_END, Shader::MODE_PARTICLES)); + add_options.push_back(AddOption("Index", "Input", "End", "VisualShaderNodeInput", vformat(input_param_shader_modes, "index"), "index", VisualShaderNode::PORT_TYPE_SCALAR_INT, TYPE_FLAGS_END, Shader::MODE_PARTICLES)); + add_options.push_back(AddOption("LifeTime", "Input", "End", "VisualShaderNodeInput", vformat(input_param_shader_modes, "lifetime"), "lifetime", VisualShaderNode::PORT_TYPE_SCALAR, TYPE_FLAGS_END, Shader::MODE_PARTICLES)); + add_options.push_back(AddOption("Restart", "Input", "End", "VisualShaderNodeInput", vformat(input_param_shader_modes, "restart"), "restart", VisualShaderNode::PORT_TYPE_SCALAR, TYPE_FLAGS_END, Shader::MODE_PARTICLES)); + add_options.push_back(AddOption("Time", "Input", "End", "VisualShaderNodeInput", vformat(input_param_shader_modes, "time"), "time", VisualShaderNode::PORT_TYPE_SCALAR, TYPE_FLAGS_END, Shader::MODE_PARTICLES)); + add_options.push_back(AddOption("Transform", "Input", "End", "VisualShaderNodeInput", vformat(input_param_shader_modes, "transform"), "transform", VisualShaderNode::PORT_TYPE_TRANSFORM, TYPE_FLAGS_END, Shader::MODE_PARTICLES)); + add_options.push_back(AddOption("Velocity", "Input", "End", "VisualShaderNodeInput", vformat(input_param_shader_modes, "velocity"), "velocity", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_END, Shader::MODE_PARTICLES)); // SKY INPUTS - add_options.push_back(AddOption("AtCubeMapPass", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "at_cubemap_pass"), "at_cubemap_pass", VisualShaderNode::PORT_TYPE_BOOLEAN, VisualShader::TYPE_FRAGMENT, Shader::MODE_SKY)); - add_options.push_back(AddOption("AtHalfResPass", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "at_half_res_pass"), "at_half_res_pass", VisualShaderNode::PORT_TYPE_BOOLEAN, VisualShader::TYPE_FRAGMENT, Shader::MODE_SKY)); - add_options.push_back(AddOption("AtQuarterResPass", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "at_quarter_res_pass"), "at_quarter_res_pass", VisualShaderNode::PORT_TYPE_BOOLEAN, VisualShader::TYPE_FRAGMENT, Shader::MODE_SKY)); - add_options.push_back(AddOption("EyeDir", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "eyedir"), "eyedir", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_FRAGMENT, Shader::MODE_SKY)); - add_options.push_back(AddOption("HalfResColor", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "half_res_color"), "half_res_color", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_FRAGMENT, Shader::MODE_SKY)); - add_options.push_back(AddOption("HalfResAlpha", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "half_res_alpha"), "half_res_alpha", VisualShaderNode::PORT_TYPE_SCALAR, VisualShader::TYPE_FRAGMENT, Shader::MODE_SKY)); - add_options.push_back(AddOption("Light0Color", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "light0_color"), "light0_color", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_FRAGMENT, Shader::MODE_SKY)); - add_options.push_back(AddOption("Light0Direction", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "light0_direction"), "light0_direction", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_FRAGMENT, Shader::MODE_SKY)); - add_options.push_back(AddOption("Light0Enabled", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "light0_enabled"), "light0_enabled", VisualShaderNode::PORT_TYPE_BOOLEAN, VisualShader::TYPE_FRAGMENT, Shader::MODE_SKY)); - add_options.push_back(AddOption("Light0Energy", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "light0_energy"), "light0_energy", VisualShaderNode::PORT_TYPE_SCALAR, VisualShader::TYPE_FRAGMENT, Shader::MODE_SKY)); - add_options.push_back(AddOption("Light1Color", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "light1_color"), "light1_color", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_FRAGMENT, Shader::MODE_SKY)); - add_options.push_back(AddOption("Light1Direction", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "light1_direction"), "light1_direction", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_FRAGMENT, Shader::MODE_SKY)); - add_options.push_back(AddOption("Light1Enabled", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "light1_enabled"), "light1_enabled", VisualShaderNode::PORT_TYPE_BOOLEAN, VisualShader::TYPE_FRAGMENT, Shader::MODE_SKY)); - add_options.push_back(AddOption("Light1Energy", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "light1_energy"), "light1_energy", VisualShaderNode::PORT_TYPE_SCALAR, VisualShader::TYPE_FRAGMENT, Shader::MODE_SKY)); - add_options.push_back(AddOption("Light2Color", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "light2_color"), "light2_color", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_FRAGMENT, Shader::MODE_SKY)); - add_options.push_back(AddOption("Light2Direction", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "light2_direction"), "light2_direction", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_FRAGMENT, Shader::MODE_SKY)); - add_options.push_back(AddOption("Light2Enabled", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "light2_enabled"), "light2_enabled", VisualShaderNode::PORT_TYPE_BOOLEAN, VisualShader::TYPE_FRAGMENT, Shader::MODE_SKY)); - add_options.push_back(AddOption("Light2Energy", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "light2_energy"), "light2_energy", VisualShaderNode::PORT_TYPE_SCALAR, VisualShader::TYPE_FRAGMENT, Shader::MODE_SKY)); - add_options.push_back(AddOption("Light3Color", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "light3_color"), "light3_color", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_FRAGMENT, Shader::MODE_SKY)); - add_options.push_back(AddOption("Light3Direction", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "light3_direction"), "light3_direction", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_FRAGMENT, Shader::MODE_SKY)); - add_options.push_back(AddOption("Light3Enabled", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "light3_enabled"), "light3_enabled", VisualShaderNode::PORT_TYPE_BOOLEAN, VisualShader::TYPE_FRAGMENT, Shader::MODE_SKY)); - add_options.push_back(AddOption("Light3Energy", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "light3_energy"), "light3_energy", VisualShaderNode::PORT_TYPE_SCALAR, VisualShader::TYPE_FRAGMENT, Shader::MODE_SKY)); - add_options.push_back(AddOption("Position", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "position"), "position", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_FRAGMENT, Shader::MODE_SKY)); - add_options.push_back(AddOption("QuarterResColor", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "quarter_res_color"), "quarter_res_color", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_FRAGMENT, Shader::MODE_SKY)); - add_options.push_back(AddOption("QuarterResAlpha", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "quarter_res_alpha"), "quarter_res_alpha", VisualShaderNode::PORT_TYPE_SCALAR, VisualShader::TYPE_FRAGMENT, Shader::MODE_SKY)); - add_options.push_back(AddOption("Radiance", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "radiance"), "radiance", VisualShaderNode::PORT_TYPE_SAMPLER, VisualShader::TYPE_FRAGMENT, Shader::MODE_SKY)); - add_options.push_back(AddOption("ScreenUV", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "screen_uv"), "screen_uv", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_FRAGMENT, Shader::MODE_SKY)); - add_options.push_back(AddOption("SkyCoords", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "sky_coords"), "sky_coords", VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_FRAGMENT, Shader::MODE_SKY)); - add_options.push_back(AddOption("Time", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "time"), "time", VisualShaderNode::PORT_TYPE_SCALAR, VisualShader::TYPE_FRAGMENT, Shader::MODE_SKY)); + add_options.push_back(AddOption("AtCubeMapPass", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "at_cubemap_pass"), "at_cubemap_pass", VisualShaderNode::PORT_TYPE_BOOLEAN, TYPE_FLAGS_FRAGMENT, Shader::MODE_SKY)); + add_options.push_back(AddOption("AtHalfResPass", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "at_half_res_pass"), "at_half_res_pass", VisualShaderNode::PORT_TYPE_BOOLEAN, TYPE_FLAGS_FRAGMENT, Shader::MODE_SKY)); + add_options.push_back(AddOption("AtQuarterResPass", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "at_quarter_res_pass"), "at_quarter_res_pass", VisualShaderNode::PORT_TYPE_BOOLEAN, TYPE_FLAGS_FRAGMENT, Shader::MODE_SKY)); + add_options.push_back(AddOption("EyeDir", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "eyedir"), "eyedir", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_FRAGMENT, Shader::MODE_SKY)); + add_options.push_back(AddOption("HalfResColor", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "half_res_color"), "half_res_color", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_FRAGMENT, Shader::MODE_SKY)); + add_options.push_back(AddOption("HalfResAlpha", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "half_res_alpha"), "half_res_alpha", VisualShaderNode::PORT_TYPE_SCALAR, TYPE_FLAGS_FRAGMENT, Shader::MODE_SKY)); + add_options.push_back(AddOption("Light0Color", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "light0_color"), "light0_color", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_FRAGMENT, Shader::MODE_SKY)); + add_options.push_back(AddOption("Light0Direction", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "light0_direction"), "light0_direction", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_FRAGMENT, Shader::MODE_SKY)); + add_options.push_back(AddOption("Light0Enabled", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "light0_enabled"), "light0_enabled", VisualShaderNode::PORT_TYPE_BOOLEAN, TYPE_FLAGS_FRAGMENT, Shader::MODE_SKY)); + add_options.push_back(AddOption("Light0Energy", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "light0_energy"), "light0_energy", VisualShaderNode::PORT_TYPE_SCALAR, TYPE_FLAGS_FRAGMENT, Shader::MODE_SKY)); + add_options.push_back(AddOption("Light1Color", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "light1_color"), "light1_color", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_FRAGMENT, Shader::MODE_SKY)); + add_options.push_back(AddOption("Light1Direction", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "light1_direction"), "light1_direction", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_FRAGMENT, Shader::MODE_SKY)); + add_options.push_back(AddOption("Light1Enabled", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "light1_enabled"), "light1_enabled", VisualShaderNode::PORT_TYPE_BOOLEAN, TYPE_FLAGS_FRAGMENT, Shader::MODE_SKY)); + add_options.push_back(AddOption("Light1Energy", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "light1_energy"), "light1_energy", VisualShaderNode::PORT_TYPE_SCALAR, TYPE_FLAGS_FRAGMENT, Shader::MODE_SKY)); + add_options.push_back(AddOption("Light2Color", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "light2_color"), "light2_color", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_FRAGMENT, Shader::MODE_SKY)); + add_options.push_back(AddOption("Light2Direction", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "light2_direction"), "light2_direction", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_FRAGMENT, Shader::MODE_SKY)); + add_options.push_back(AddOption("Light2Enabled", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "light2_enabled"), "light2_enabled", VisualShaderNode::PORT_TYPE_BOOLEAN, TYPE_FLAGS_FRAGMENT, Shader::MODE_SKY)); + add_options.push_back(AddOption("Light2Energy", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "light2_energy"), "light2_energy", VisualShaderNode::PORT_TYPE_SCALAR, TYPE_FLAGS_FRAGMENT, Shader::MODE_SKY)); + add_options.push_back(AddOption("Light3Color", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "light3_color"), "light3_color", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_FRAGMENT, Shader::MODE_SKY)); + add_options.push_back(AddOption("Light3Direction", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "light3_direction"), "light3_direction", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_FRAGMENT, Shader::MODE_SKY)); + add_options.push_back(AddOption("Light3Enabled", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "light3_enabled"), "light3_enabled", VisualShaderNode::PORT_TYPE_BOOLEAN, TYPE_FLAGS_FRAGMENT, Shader::MODE_SKY)); + add_options.push_back(AddOption("Light3Energy", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "light3_energy"), "light3_energy", VisualShaderNode::PORT_TYPE_SCALAR, TYPE_FLAGS_FRAGMENT, Shader::MODE_SKY)); + add_options.push_back(AddOption("Position", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "position"), "position", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_FRAGMENT, Shader::MODE_SKY)); + add_options.push_back(AddOption("QuarterResColor", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "quarter_res_color"), "quarter_res_color", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_FRAGMENT, Shader::MODE_SKY)); + add_options.push_back(AddOption("QuarterResAlpha", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "quarter_res_alpha"), "quarter_res_alpha", VisualShaderNode::PORT_TYPE_SCALAR, TYPE_FLAGS_FRAGMENT, Shader::MODE_SKY)); + add_options.push_back(AddOption("Radiance", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "radiance"), "radiance", VisualShaderNode::PORT_TYPE_SAMPLER, TYPE_FLAGS_FRAGMENT, Shader::MODE_SKY)); + add_options.push_back(AddOption("ScreenUV", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "screen_uv"), "screen_uv", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_FRAGMENT, Shader::MODE_SKY)); + add_options.push_back(AddOption("SkyCoords", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "sky_coords"), "sky_coords", VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_FRAGMENT, Shader::MODE_SKY)); + add_options.push_back(AddOption("Time", "Input", "Fragment", "VisualShaderNodeInput", vformat(input_param_for_fragment_shader_mode, "time"), "time", VisualShaderNode::PORT_TYPE_SCALAR, TYPE_FLAGS_FRAGMENT, Shader::MODE_SKY)); // SCALAR @@ -2672,15 +3786,9 @@ VisualShaderEditor::VisualShaderEditor() { //CONSTANTS - add_options.push_back(AddOption("E", "Scalar", "Constants", "VisualShaderNodeFloatConstant", TTR("E constant (2.718282). Represents the base of the natural logarithm."), -1, VisualShaderNode::PORT_TYPE_SCALAR, -1, -1, Math_E)); - add_options.push_back(AddOption("Epsilon", "Scalar", "Constants", "VisualShaderNodeFloatConstant", TTR("Epsilon constant (0.00001). Smallest possible scalar number."), -1, VisualShaderNode::PORT_TYPE_SCALAR, -1, -1, CMP_EPSILON)); - add_options.push_back(AddOption("Phi", "Scalar", "Constants", "VisualShaderNodeFloatConstant", TTR("Phi constant (1.618034). Golden ratio."), -1, VisualShaderNode::PORT_TYPE_SCALAR, -1, -1, 1.618034f)); - add_options.push_back(AddOption("Pi/4", "Scalar", "Constants", "VisualShaderNodeFloatConstant", TTR("Pi/4 constant (0.785398) or 45 degrees."), -1, VisualShaderNode::PORT_TYPE_SCALAR, -1, -1, Math_PI / 4)); - add_options.push_back(AddOption("Pi/2", "Scalar", "Constants", "VisualShaderNodeFloatConstant", TTR("Pi/2 constant (1.570796) or 90 degrees."), -1, VisualShaderNode::PORT_TYPE_SCALAR, -1, -1, Math_PI / 2)); - add_options.push_back(AddOption("Pi", "Scalar", "Constants", "VisualShaderNodeFloatConstant", TTR("Pi constant (3.141593) or 180 degrees."), -1, VisualShaderNode::PORT_TYPE_SCALAR, -1, -1, Math_PI)); - add_options.push_back(AddOption("Tau", "Scalar", "Constants", "VisualShaderNodeFloatConstant", TTR("Tau constant (6.283185) or 360 degrees."), -1, VisualShaderNode::PORT_TYPE_SCALAR, -1, -1, Math_TAU)); - add_options.push_back(AddOption("Sqrt2", "Scalar", "Constants", "VisualShaderNodeFloatConstant", TTR("Sqrt2 constant (1.414214). Square root of 2."), -1, VisualShaderNode::PORT_TYPE_SCALAR, -1, -1, Math_SQRT2)); - + for (int i = 0; i < MAX_FLOAT_CONST_DEFS; i++) { + add_options.push_back(AddOption(float_constant_defs[i].name, "Scalar", "Constants", "VisualShaderNodeFloatConstant", float_constant_defs[i].desc, -1, VisualShaderNode::PORT_TYPE_SCALAR, -1, -1, float_constant_defs[i].value)); + } // FUNCTIONS add_options.push_back(AddOption("Abs", "Scalar", "Functions", "VisualShaderNodeFloatFunc", TTR("Returns the absolute value of the parameter."), VisualShaderNodeFloatFunc::FUNC_ABS, VisualShaderNode::PORT_TYPE_SCALAR)); @@ -2693,8 +3801,8 @@ VisualShaderEditor::VisualShaderEditor() { add_options.push_back(AddOption("ATan2", "Scalar", "Functions", "VisualShaderNodeFloatOp", TTR("Returns the arc-tangent of the parameters."), VisualShaderNodeFloatOp::OP_ATAN2, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("ATanH", "Scalar", "Functions", "VisualShaderNodeFloatFunc", TTR("Returns the inverse hyperbolic tangent of the parameter."), VisualShaderNodeFloatFunc::FUNC_ATANH, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("Ceil", "Scalar", "Functions", "VisualShaderNodeFloatFunc", TTR("Finds the nearest integer that is greater than or equal to the parameter."), VisualShaderNodeFloatFunc::FUNC_CEIL, VisualShaderNode::PORT_TYPE_SCALAR)); - add_options.push_back(AddOption("Clamp", "Scalar", "Functions", "VisualShaderNodeScalarClamp", TTR("Constrains a value to lie between two further values."), -1, VisualShaderNode::PORT_TYPE_SCALAR)); - add_options.push_back(AddOption("Clamp", "Scalar", "Functions", "VisualShaderNodeIntFunc", TTR("Constrains a value to lie between two further values."), VisualShaderNodeIntFunc::FUNC_CLAMP, VisualShaderNode::PORT_TYPE_SCALAR_INT)); + add_options.push_back(AddOption("Clamp", "Scalar", "Functions", "VisualShaderNodeClamp", TTR("Constrains a value to lie between two further values."), VisualShaderNodeClamp::OP_TYPE_FLOAT, VisualShaderNode::PORT_TYPE_SCALAR)); + add_options.push_back(AddOption("Clamp", "Scalar", "Functions", "VisualShaderNodeClamp", TTR("Constrains a value to lie between two further values."), VisualShaderNodeClamp::OP_TYPE_INT, VisualShaderNode::PORT_TYPE_SCALAR_INT)); add_options.push_back(AddOption("Cos", "Scalar", "Functions", "VisualShaderNodeFloatFunc", TTR("Returns the cosine of the parameter."), VisualShaderNodeFloatFunc::FUNC_COS, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("CosH", "Scalar", "Functions", "VisualShaderNodeFloatFunc", TTR("Returns the hyperbolic cosine of the parameter."), VisualShaderNodeFloatFunc::FUNC_COSH, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("Degrees", "Scalar", "Functions", "VisualShaderNodeFloatFunc", TTR("Converts a quantity in radians to degrees."), VisualShaderNodeFloatFunc::FUNC_DEGREES, VisualShaderNode::PORT_TYPE_SCALAR)); @@ -2707,7 +3815,8 @@ VisualShaderEditor::VisualShaderEditor() { add_options.push_back(AddOption("Log2", "Scalar", "Functions", "VisualShaderNodeFloatFunc", TTR("Base-2 logarithm."), VisualShaderNodeFloatFunc::FUNC_LOG2, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("Max", "Scalar", "Functions", "VisualShaderNodeFloatOp", TTR("Returns the greater of two values."), VisualShaderNodeFloatOp::OP_MAX, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("Min", "Scalar", "Functions", "VisualShaderNodeFloatOp", TTR("Returns the lesser of two values."), VisualShaderNodeFloatOp::OP_MIN, VisualShaderNode::PORT_TYPE_SCALAR)); - add_options.push_back(AddOption("Mix", "Scalar", "Functions", "VisualShaderNodeScalarInterp", TTR("Linear interpolation between two scalars."), -1, VisualShaderNode::PORT_TYPE_SCALAR)); + add_options.push_back(AddOption("Mix", "Scalar", "Functions", "VisualShaderNodeMix", TTR("Linear interpolation between two scalars."), VisualShaderNodeMix::OP_TYPE_SCALAR, VisualShaderNode::PORT_TYPE_SCALAR)); + add_options.push_back(AddOption("MultiplyAdd", "Scalar", "Functions", "VisualShaderNodeMultiplyAdd", TTR("Performs a fused multiply-add operation (a * b + c) on scalars."), VisualShaderNodeMultiplyAdd::OP_TYPE_SCALAR, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("Negate", "Scalar", "Functions", "VisualShaderNodeFloatFunc", TTR("Returns the opposite value of the parameter."), VisualShaderNodeFloatFunc::FUNC_NEGATE, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("Negate", "Scalar", "Functions", "VisualShaderNodeIntFunc", TTR("Returns the opposite value of the parameter."), VisualShaderNodeIntFunc::FUNC_NEGATE, VisualShaderNode::PORT_TYPE_SCALAR_INT)); add_options.push_back(AddOption("OneMinus", "Scalar", "Functions", "VisualShaderNodeFloatFunc", TTR("1.0 - scalar"), VisualShaderNodeFloatFunc::FUNC_ONEMINUS, VisualShaderNode::PORT_TYPE_SCALAR)); @@ -2722,8 +3831,8 @@ VisualShaderEditor::VisualShaderEditor() { add_options.push_back(AddOption("Sin", "Scalar", "Functions", "VisualShaderNodeFloatFunc", TTR("Returns the sine of the parameter."), VisualShaderNodeFloatFunc::FUNC_SIN, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("SinH", "Scalar", "Functions", "VisualShaderNodeFloatFunc", TTR("Returns the hyperbolic sine of the parameter."), VisualShaderNodeFloatFunc::FUNC_SINH, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("Sqrt", "Scalar", "Functions", "VisualShaderNodeFloatFunc", TTR("Returns the square root of the parameter."), VisualShaderNodeFloatFunc::FUNC_SQRT, VisualShaderNode::PORT_TYPE_SCALAR)); - add_options.push_back(AddOption("SmoothStep", "Scalar", "Functions", "VisualShaderNodeScalarSmoothStep", TTR("SmoothStep function( scalar(edge0), scalar(edge1), scalar(x) ).\n\nReturns 0.0 if 'x' is smaller than 'edge0' and 1.0 if x is larger than 'edge1'. Otherwise the return value is interpolated between 0.0 and 1.0 using Hermite polynomials."), -1, VisualShaderNode::PORT_TYPE_SCALAR)); - add_options.push_back(AddOption("Step", "Scalar", "Functions", "VisualShaderNodeFloatOp", TTR("Step function( scalar(edge), scalar(x) ).\n\nReturns 0.0 if 'x' is smaller than 'edge' and otherwise 1.0."), VisualShaderNodeFloatOp::OP_STEP, VisualShaderNode::PORT_TYPE_SCALAR)); + add_options.push_back(AddOption("SmoothStep", "Scalar", "Functions", "VisualShaderNodeSmoothStep", TTR("SmoothStep function( scalar(edge0), scalar(edge1), scalar(x) ).\n\nReturns 0.0 if 'x' is smaller than 'edge0' and 1.0 if x is larger than 'edge1'. Otherwise the return value is interpolated between 0.0 and 1.0 using Hermite polynomials."), VisualShaderNodeSmoothStep::OP_TYPE_SCALAR, VisualShaderNode::PORT_TYPE_SCALAR)); + add_options.push_back(AddOption("Step", "Scalar", "Functions", "VisualShaderNodeStep", TTR("Step function( scalar(edge), scalar(x) ).\n\nReturns 0.0 if 'x' is smaller than 'edge' and otherwise 1.0."), VisualShaderNodeStep::OP_TYPE_SCALAR, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("Tan", "Scalar", "Functions", "VisualShaderNodeFloatFunc", TTR("Returns the tangent of the parameter."), VisualShaderNodeFloatFunc::FUNC_TAN, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("TanH", "Scalar", "Functions", "VisualShaderNodeFloatFunc", TTR("Returns the hyperbolic tangent of the parameter."), VisualShaderNodeFloatFunc::FUNC_TANH, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("Trunc", "Scalar", "Functions", "VisualShaderNodeFloatFunc", TTR("Finds the truncated value of the parameter."), VisualShaderNodeFloatFunc::FUNC_TRUNC, VisualShaderNode::PORT_TYPE_SCALAR)); @@ -2744,14 +3853,33 @@ VisualShaderEditor::VisualShaderEditor() { add_options.push_back(AddOption("FloatUniform", "Scalar", "Variables", "VisualShaderNodeFloatUniform", TTR("Scalar floating-point uniform."), -1, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("IntUniform", "Scalar", "Variables", "VisualShaderNodeIntUniform", TTR("Scalar integer uniform."), -1, VisualShaderNode::PORT_TYPE_SCALAR_INT)); + // SDF + { + add_options.push_back(AddOption("ScreenUVToSDF", "SDF", "", "VisualShaderNodeScreenUVToSDF", TTR("Converts screen UV to a SDF."), -1, VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_FRAGMENT | TYPE_FLAGS_LIGHT, Shader::MODE_CANVAS_ITEM)); + add_options.push_back(AddOption("SDFRaymarch", "SDF", "", "VisualShaderNodeSDFRaymarch", TTR("Casts a ray against the screen SDF and returns the distance travelled."), -1, -1, TYPE_FLAGS_FRAGMENT | TYPE_FLAGS_LIGHT, Shader::MODE_CANVAS_ITEM)); + add_options.push_back(AddOption("SDFToScreenUV", "SDF", "", "VisualShaderNodeSDFToScreenUV", TTR("Converts a SDF to screen UV."), -1, VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_FRAGMENT | TYPE_FLAGS_LIGHT, Shader::MODE_CANVAS_ITEM)); + add_options.push_back(AddOption("TextureSDF", "SDF", "", "VisualShaderNodeTextureSDF", TTR("Performs a SDF texture lookup."), -1, VisualShaderNode::PORT_TYPE_SCALAR, TYPE_FLAGS_FRAGMENT | TYPE_FLAGS_LIGHT, Shader::MODE_CANVAS_ITEM)); + add_options.push_back(AddOption("TextureSDFNormal", "SDF", "", "VisualShaderNodeTextureSDFNormal", TTR("Performs a SDF normal texture lookup."), -1, VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_FRAGMENT | TYPE_FLAGS_LIGHT, Shader::MODE_CANVAS_ITEM)); + } + // TEXTURES + cubemap_node_option_idx = add_options.size(); add_options.push_back(AddOption("CubeMap", "Textures", "Functions", "VisualShaderNodeCubemap", TTR("Perform the cubic texture lookup."), -1, -1)); - texture_node_option_idx = add_options.size(); - add_options.push_back(AddOption("Texture2D", "Textures", "Functions", "VisualShaderNodeTexture", TTR("Perform the texture lookup."), -1, -1)); + curve_node_option_idx = add_options.size(); + add_options.push_back(AddOption("CurveTexture", "Textures", "Functions", "VisualShaderNodeCurveTexture", TTR("Perform the curve texture lookup."), -1, -1)); + texture2d_node_option_idx = add_options.size(); + add_options.push_back(AddOption("Texture2D", "Textures", "Functions", "VisualShaderNodeTexture", TTR("Perform the 2D texture lookup."), -1, -1)); + texture2d_array_node_option_idx = add_options.size(); + add_options.push_back(AddOption("Texture2DArray", "Textures", "Functions", "VisualShaderNodeTexture2DArray", TTR("Perform the 2D-array texture lookup."), -1, -1, -1, -1, -1)); + texture3d_node_option_idx = add_options.size(); + add_options.push_back(AddOption("Texture3D", "Textures", "Functions", "VisualShaderNodeTexture3D", TTR("Perform the 3D texture lookup."), -1, -1)); + add_options.push_back(AddOption("CubeMapUniform", "Textures", "Variables", "VisualShaderNodeCubemapUniform", TTR("Cubic texture uniform lookup."), -1, -1)); add_options.push_back(AddOption("TextureUniform", "Textures", "Variables", "VisualShaderNodeTextureUniform", TTR("2D texture uniform lookup."), -1, -1)); - add_options.push_back(AddOption("TextureUniformTriplanar", "Textures", "Variables", "VisualShaderNodeTextureUniformTriplanar", TTR("2D texture uniform lookup with triplanar."), -1, -1, VisualShader::TYPE_FRAGMENT | VisualShader::TYPE_LIGHT, Shader::MODE_SPATIAL)); + add_options.push_back(AddOption("TextureUniformTriplanar", "Textures", "Variables", "VisualShaderNodeTextureUniformTriplanar", TTR("2D texture uniform lookup with triplanar."), -1, -1, TYPE_FLAGS_FRAGMENT | TYPE_FLAGS_LIGHT, Shader::MODE_SPATIAL)); + add_options.push_back(AddOption("Texture2DArrayUniform", "Textures", "Variables", "VisualShaderNodeTexture2DArrayUniform", TTR("2D array of textures uniform lookup."), -1, -1, -1, -1, -1)); + add_options.push_back(AddOption("Texture3DUniform", "Textures", "Variables", "VisualShaderNodeTexture3DUniform", TTR("3D texture uniform lookup."), -1, -1, -1, -1, -1)); // TRANSFORM @@ -2788,7 +3916,7 @@ VisualShaderEditor::VisualShaderEditor() { add_options.push_back(AddOption("ATan2", "Vector", "Functions", "VisualShaderNodeVectorOp", TTR("Returns the arc-tangent of the parameters."), VisualShaderNodeVectorOp::OP_ATAN2, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("ATanH", "Vector", "Functions", "VisualShaderNodeVectorFunc", TTR("Returns the inverse hyperbolic tangent of the parameter."), VisualShaderNodeVectorFunc::FUNC_ATANH, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Ceil", "Vector", "Functions", "VisualShaderNodeVectorFunc", TTR("Finds the nearest integer that is greater than or equal to the parameter."), VisualShaderNodeVectorFunc::FUNC_CEIL, VisualShaderNode::PORT_TYPE_VECTOR)); - add_options.push_back(AddOption("Clamp", "Vector", "Functions", "VisualShaderNodeVectorClamp", TTR("Constrains a value to lie between two further values."), -1, VisualShaderNode::PORT_TYPE_VECTOR)); + add_options.push_back(AddOption("Clamp", "Vector", "Functions", "VisualShaderNodeClamp", TTR("Constrains a value to lie between two further values."), VisualShaderNodeClamp::OP_TYPE_VECTOR, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Cos", "Vector", "Functions", "VisualShaderNodeVectorFunc", TTR("Returns the cosine of the parameter."), VisualShaderNodeVectorFunc::FUNC_COS, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("CosH", "Vector", "Functions", "VisualShaderNodeVectorFunc", TTR("Returns the hyperbolic cosine of the parameter."), VisualShaderNodeVectorFunc::FUNC_COSH, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Cross", "Vector", "Functions", "VisualShaderNodeVectorOp", TTR("Calculates the cross product of two vectors."), VisualShaderNodeVectorOp::OP_CROSS, VisualShaderNode::PORT_TYPE_VECTOR)); @@ -2806,8 +3934,9 @@ VisualShaderEditor::VisualShaderEditor() { add_options.push_back(AddOption("Log2", "Vector", "Functions", "VisualShaderNodeVectorFunc", TTR("Base-2 logarithm."), VisualShaderNodeVectorFunc::FUNC_LOG2, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Max", "Vector", "Functions", "VisualShaderNodeVectorOp", TTR("Returns the greater of two values."), VisualShaderNodeVectorOp::OP_MAX, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Min", "Vector", "Functions", "VisualShaderNodeVectorOp", TTR("Returns the lesser of two values."), VisualShaderNodeVectorOp::OP_MIN, VisualShaderNode::PORT_TYPE_VECTOR)); - add_options.push_back(AddOption("Mix", "Vector", "Functions", "VisualShaderNodeVectorInterp", TTR("Linear interpolation between two vectors."), -1, VisualShaderNode::PORT_TYPE_VECTOR)); - add_options.push_back(AddOption("MixS", "Vector", "Functions", "VisualShaderNodeVectorScalarMix", TTR("Linear interpolation between two vectors using scalar."), -1, VisualShaderNode::PORT_TYPE_VECTOR)); + add_options.push_back(AddOption("Mix", "Vector", "Functions", "VisualShaderNodeMix", TTR("Linear interpolation between two vectors."), VisualShaderNodeMix::OP_TYPE_VECTOR, VisualShaderNode::PORT_TYPE_VECTOR)); + add_options.push_back(AddOption("MixS", "Vector", "Functions", "VisualShaderNodeMix", TTR("Linear interpolation between two vectors using scalar."), VisualShaderNodeMix::OP_TYPE_VECTOR_SCALAR, VisualShaderNode::PORT_TYPE_VECTOR)); + add_options.push_back(AddOption("MultiplyAdd", "Vector", "Functions", "VisualShaderNodeMultiplyAdd", TTR("Performs a fused multiply-add operation (a * b + c) on vectors."), VisualShaderNodeMultiplyAdd::OP_TYPE_VECTOR, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Negate", "Vector", "Functions", "VisualShaderNodeVectorFunc", TTR("Returns the opposite value of the parameter."), VisualShaderNodeVectorFunc::FUNC_NEGATE, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Normalize", "Vector", "Functions", "VisualShaderNodeVectorFunc", TTR("Calculates the normalize product of vector."), VisualShaderNodeVectorFunc::FUNC_NORMALIZE, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("OneMinus", "Vector", "Functions", "VisualShaderNodeVectorFunc", TTR("1.0 - vector"), VisualShaderNodeVectorFunc::FUNC_ONEMINUS, VisualShaderNode::PORT_TYPE_VECTOR)); @@ -2823,10 +3952,10 @@ VisualShaderEditor::VisualShaderEditor() { add_options.push_back(AddOption("Sin", "Vector", "Functions", "VisualShaderNodeVectorFunc", TTR("Returns the sine of the parameter."), VisualShaderNodeVectorFunc::FUNC_SIN, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("SinH", "Vector", "Functions", "VisualShaderNodeVectorFunc", TTR("Returns the hyperbolic sine of the parameter."), VisualShaderNodeVectorFunc::FUNC_SINH, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Sqrt", "Vector", "Functions", "VisualShaderNodeVectorFunc", TTR("Returns the square root of the parameter."), VisualShaderNodeVectorFunc::FUNC_SQRT, VisualShaderNode::PORT_TYPE_VECTOR)); - add_options.push_back(AddOption("SmoothStep", "Vector", "Functions", "VisualShaderNodeVectorSmoothStep", TTR("SmoothStep function( vector(edge0), vector(edge1), vector(x) ).\n\nReturns 0.0 if 'x' is smaller than 'edge0' and 1.0 if 'x' is larger than 'edge1'. Otherwise the return value is interpolated between 0.0 and 1.0 using Hermite polynomials."), -1, VisualShaderNode::PORT_TYPE_VECTOR)); - add_options.push_back(AddOption("SmoothStepS", "Vector", "Functions", "VisualShaderNodeVectorScalarSmoothStep", TTR("SmoothStep function( scalar(edge0), scalar(edge1), vector(x) ).\n\nReturns 0.0 if 'x' is smaller than 'edge0' and 1.0 if 'x' is larger than 'edge1'. Otherwise the return value is interpolated between 0.0 and 1.0 using Hermite polynomials."), -1, VisualShaderNode::PORT_TYPE_VECTOR)); - add_options.push_back(AddOption("Step", "Vector", "Functions", "VisualShaderNodeVectorOp", TTR("Step function( vector(edge), vector(x) ).\n\nReturns 0.0 if 'x' is smaller than 'edge' and otherwise 1.0."), VisualShaderNodeVectorOp::OP_STEP, VisualShaderNode::PORT_TYPE_VECTOR)); - add_options.push_back(AddOption("StepS", "Vector", "Functions", "VisualShaderNodeVectorScalarStep", TTR("Step function( scalar(edge), vector(x) ).\n\nReturns 0.0 if 'x' is smaller than 'edge' and otherwise 1.0."), -1, VisualShaderNode::PORT_TYPE_VECTOR)); + add_options.push_back(AddOption("SmoothStep", "Vector", "Functions", "VisualShaderNodeSmoothStep", TTR("SmoothStep function( vector(edge0), vector(edge1), vector(x) ).\n\nReturns 0.0 if 'x' is smaller than 'edge0' and 1.0 if 'x' is larger than 'edge1'. Otherwise the return value is interpolated between 0.0 and 1.0 using Hermite polynomials."), VisualShaderNodeSmoothStep::OP_TYPE_VECTOR, VisualShaderNode::PORT_TYPE_VECTOR)); + add_options.push_back(AddOption("SmoothStepS", "Vector", "Functions", "VisualShaderNodeSmoothStep", TTR("SmoothStep function( scalar(edge0), scalar(edge1), vector(x) ).\n\nReturns 0.0 if 'x' is smaller than 'edge0' and 1.0 if 'x' is larger than 'edge1'. Otherwise the return value is interpolated between 0.0 and 1.0 using Hermite polynomials."), VisualShaderNodeSmoothStep::OP_TYPE_VECTOR_SCALAR, VisualShaderNode::PORT_TYPE_VECTOR)); + add_options.push_back(AddOption("Step", "Vector", "Functions", "VisualShaderNodeStep", TTR("Step function( vector(edge), vector(x) ).\n\nReturns 0.0 if 'x' is smaller than 'edge' and otherwise 1.0."), VisualShaderNodeStep::OP_TYPE_VECTOR, VisualShaderNode::PORT_TYPE_VECTOR)); + add_options.push_back(AddOption("StepS", "Vector", "Functions", "VisualShaderNodeStep", TTR("Step function( scalar(edge), vector(x) ).\n\nReturns 0.0 if 'x' is smaller than 'edge' and otherwise 1.0."), VisualShaderNodeStep::OP_TYPE_VECTOR_SCALAR, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Tan", "Vector", "Functions", "VisualShaderNodeVectorFunc", TTR("Returns the tangent of the parameter."), VisualShaderNodeVectorFunc::FUNC_TAN, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("TanH", "Vector", "Functions", "VisualShaderNodeVectorFunc", TTR("Returns the hyperbolic tangent of the parameter."), VisualShaderNodeVectorFunc::FUNC_TANH, VisualShaderNode::PORT_TYPE_VECTOR)); add_options.push_back(AddOption("Trunc", "Vector", "Functions", "VisualShaderNodeVectorFunc", TTR("Finds the truncated value of the parameter."), VisualShaderNodeVectorFunc::FUNC_TRUNC, VisualShaderNode::PORT_TYPE_VECTOR)); @@ -2845,16 +3974,17 @@ VisualShaderEditor::VisualShaderEditor() { add_options.push_back(AddOption("Expression", "Special", "", "VisualShaderNodeExpression", TTR("Custom Godot Shader Language expression, with custom amount of input and output ports. This is a direct injection of code into the vertex/fragment/light function, do not use it to write the function declarations inside."))); add_options.push_back(AddOption("Fresnel", "Special", "", "VisualShaderNodeFresnel", TTR("Returns falloff based on the dot product of surface normal and view direction of camera (pass associated inputs to it)."), -1, VisualShaderNode::PORT_TYPE_SCALAR)); add_options.push_back(AddOption("GlobalExpression", "Special", "", "VisualShaderNodeGlobalExpression", TTR("Custom Godot Shader Language expression, which is placed on top of the resulted shader. You can place various function definitions inside and call it later in the Expressions. You can also declare varyings, uniforms and constants."))); + add_options.push_back(AddOption("UniformRef", "Special", "", "VisualShaderNodeUniformRef", TTR("A reference to an existing uniform."))); - add_options.push_back(AddOption("ScalarDerivativeFunc", "Special", "Common", "VisualShaderNodeScalarDerivativeFunc", TTR("(Fragment/Light mode only) Scalar derivative function."), -1, VisualShaderNode::PORT_TYPE_SCALAR, VisualShader::TYPE_FRAGMENT | VisualShader::TYPE_LIGHT, -1, -1, true)); - add_options.push_back(AddOption("VectorDerivativeFunc", "Special", "Common", "VisualShaderNodeVectorDerivativeFunc", TTR("(Fragment/Light mode only) Vector derivative function."), -1, VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_FRAGMENT | VisualShader::TYPE_LIGHT, -1, -1, true)); + add_options.push_back(AddOption("ScalarDerivativeFunc", "Special", "Common", "VisualShaderNodeScalarDerivativeFunc", TTR("(Fragment/Light mode only) Scalar derivative function."), -1, VisualShaderNode::PORT_TYPE_SCALAR, TYPE_FLAGS_FRAGMENT | TYPE_FLAGS_LIGHT, -1, -1, true)); + add_options.push_back(AddOption("VectorDerivativeFunc", "Special", "Common", "VisualShaderNodeVectorDerivativeFunc", TTR("(Fragment/Light mode only) Vector derivative function."), -1, VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_FRAGMENT | TYPE_FLAGS_LIGHT, -1, -1, true)); - add_options.push_back(AddOption("DdX", "Special", "Derivative", "VisualShaderNodeVectorDerivativeFunc", TTR("(Fragment/Light mode only) (Vector) Derivative in 'x' using local differencing."), VisualShaderNodeVectorDerivativeFunc::FUNC_X, VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_FRAGMENT | VisualShader::TYPE_LIGHT, -1, -1, true)); - add_options.push_back(AddOption("DdXS", "Special", "Derivative", "VisualShaderNodeScalarDerivativeFunc", TTR("(Fragment/Light mode only) (Scalar) Derivative in 'x' using local differencing."), VisualShaderNodeScalarDerivativeFunc::FUNC_X, VisualShaderNode::PORT_TYPE_SCALAR, VisualShader::TYPE_FRAGMENT | VisualShader::TYPE_LIGHT, -1, -1, true)); - add_options.push_back(AddOption("DdY", "Special", "Derivative", "VisualShaderNodeVectorDerivativeFunc", TTR("(Fragment/Light mode only) (Vector) Derivative in 'y' using local differencing."), VisualShaderNodeVectorDerivativeFunc::FUNC_Y, VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_FRAGMENT | VisualShader::TYPE_LIGHT, -1, -1, true)); - add_options.push_back(AddOption("DdYS", "Special", "Derivative", "VisualShaderNodeScalarDerivativeFunc", TTR("(Fragment/Light mode only) (Scalar) Derivative in 'y' using local differencing."), VisualShaderNodeScalarDerivativeFunc::FUNC_Y, VisualShaderNode::PORT_TYPE_SCALAR, VisualShader::TYPE_FRAGMENT | VisualShader::TYPE_LIGHT, -1, -1, true)); - add_options.push_back(AddOption("Sum", "Special", "Derivative", "VisualShaderNodeVectorDerivativeFunc", TTR("(Fragment/Light mode only) (Vector) Sum of absolute derivative in 'x' and 'y'."), VisualShaderNodeVectorDerivativeFunc::FUNC_SUM, VisualShaderNode::PORT_TYPE_VECTOR, VisualShader::TYPE_FRAGMENT | VisualShader::TYPE_LIGHT, -1, -1, true)); - add_options.push_back(AddOption("SumS", "Special", "Derivative", "VisualShaderNodeScalarDerivativeFunc", TTR("(Fragment/Light mode only) (Scalar) Sum of absolute derivative in 'x' and 'y'."), VisualShaderNodeScalarDerivativeFunc::FUNC_SUM, VisualShaderNode::PORT_TYPE_SCALAR, VisualShader::TYPE_FRAGMENT | VisualShader::TYPE_LIGHT, -1, -1, true)); + add_options.push_back(AddOption("DdX", "Special", "Derivative", "VisualShaderNodeVectorDerivativeFunc", TTR("(Fragment/Light mode only) (Vector) Derivative in 'x' using local differencing."), VisualShaderNodeVectorDerivativeFunc::FUNC_X, VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_FRAGMENT | TYPE_FLAGS_LIGHT, -1, -1, true)); + add_options.push_back(AddOption("DdXS", "Special", "Derivative", "VisualShaderNodeScalarDerivativeFunc", TTR("(Fragment/Light mode only) (Scalar) Derivative in 'x' using local differencing."), VisualShaderNodeScalarDerivativeFunc::FUNC_X, VisualShaderNode::PORT_TYPE_SCALAR, TYPE_FLAGS_FRAGMENT | TYPE_FLAGS_LIGHT, -1, -1, true)); + add_options.push_back(AddOption("DdY", "Special", "Derivative", "VisualShaderNodeVectorDerivativeFunc", TTR("(Fragment/Light mode only) (Vector) Derivative in 'y' using local differencing."), VisualShaderNodeVectorDerivativeFunc::FUNC_Y, VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_FRAGMENT | TYPE_FLAGS_LIGHT, -1, -1, true)); + add_options.push_back(AddOption("DdYS", "Special", "Derivative", "VisualShaderNodeScalarDerivativeFunc", TTR("(Fragment/Light mode only) (Scalar) Derivative in 'y' using local differencing."), VisualShaderNodeScalarDerivativeFunc::FUNC_Y, VisualShaderNode::PORT_TYPE_SCALAR, TYPE_FLAGS_FRAGMENT | TYPE_FLAGS_LIGHT, -1, -1, true)); + add_options.push_back(AddOption("Sum", "Special", "Derivative", "VisualShaderNodeVectorDerivativeFunc", TTR("(Fragment/Light mode only) (Vector) Sum of absolute derivative in 'x' and 'y'."), VisualShaderNodeVectorDerivativeFunc::FUNC_SUM, VisualShaderNode::PORT_TYPE_VECTOR, TYPE_FLAGS_FRAGMENT | TYPE_FLAGS_LIGHT, -1, -1, true)); + add_options.push_back(AddOption("SumS", "Special", "Derivative", "VisualShaderNodeScalarDerivativeFunc", TTR("(Fragment/Light mode only) (Scalar) Sum of absolute derivative in 'x' and 'y'."), VisualShaderNodeScalarDerivativeFunc::FUNC_SUM, VisualShaderNode::PORT_TYPE_SCALAR, TYPE_FLAGS_FRAGMENT | TYPE_FLAGS_LIGHT, -1, -1, true)); custom_node_option_idx = add_options.size(); ///////////////////////////////////////////////////////////////////// @@ -2874,12 +4004,16 @@ VisualShaderEditor::VisualShaderEditor() { default_plugin.instance(); add_plugin(default_plugin); + graph_plugin.instance(); + property_editor = memnew(CustomPropertyEditor); add_child(property_editor); property_editor->connect("variant_changed", callable_mp(this, &VisualShaderEditor::_port_edited)); } +///////////////// + void VisualShaderEditorPlugin::edit(Object *p_object) { visual_shader_editor->edit(Object::cast_to<VisualShader>(p_object)); } @@ -2963,9 +4097,59 @@ public: } }; +//////////////// + +class VisualShaderNodePluginUniformRefEditor : public OptionButton { + GDCLASS(VisualShaderNodePluginUniformRefEditor, OptionButton); + + Ref<VisualShaderNodeUniformRef> uniform_ref; + +public: + void _notification(int p_what) { + if (p_what == NOTIFICATION_READY) { + connect("item_selected", callable_mp(this, &VisualShaderNodePluginUniformRefEditor::_item_selected)); + } + } + + void _item_selected(int p_item) { + VisualShaderEditor::get_singleton()->call_deferred("_uniform_select_item", uniform_ref, get_item_text(p_item)); + } + + void setup(const Ref<VisualShaderNodeUniformRef> &p_uniform_ref) { + uniform_ref = p_uniform_ref; + + Ref<Texture2D> type_icon[7] = { + EditorNode::get_singleton()->get_gui_base()->get_theme_icon("float", "EditorIcons"), + EditorNode::get_singleton()->get_gui_base()->get_theme_icon("int", "EditorIcons"), + EditorNode::get_singleton()->get_gui_base()->get_theme_icon("bool", "EditorIcons"), + EditorNode::get_singleton()->get_gui_base()->get_theme_icon("Vector3", "EditorIcons"), + EditorNode::get_singleton()->get_gui_base()->get_theme_icon("Transform", "EditorIcons"), + EditorNode::get_singleton()->get_gui_base()->get_theme_icon("Color", "EditorIcons"), + EditorNode::get_singleton()->get_gui_base()->get_theme_icon("ImageTexture", "EditorIcons"), + }; + + add_item("[None]"); + int to_select = -1; + for (int i = 0; i < p_uniform_ref->get_uniforms_count(); i++) { + if (p_uniform_ref->get_uniform_name() == p_uniform_ref->get_uniform_name_by_index(i)) { + to_select = i + 1; + } + add_icon_item(type_icon[p_uniform_ref->get_uniform_type_by_index(i)], p_uniform_ref->get_uniform_name_by_index(i)); + } + + if (to_select >= 0) { + select(to_select); + } + } +}; + +//////////////// + class VisualShaderNodePluginDefaultEditor : public VBoxContainer { GDCLASS(VisualShaderNodePluginDefaultEditor, VBoxContainer); Ref<Resource> parent_resource; + int node_id; + VisualShader::Type shader_type; public: void _property_changed(const String &p_property, const Variant &p_value, const String &p_field = "", bool p_changing = false) { @@ -2994,8 +4178,13 @@ public: } else { undo_redo->add_undo_method(this, "_open_inspector", (RES)parent_resource.ptr()); } - undo_redo->add_do_method(this, "_refresh_request"); - undo_redo->add_undo_method(this, "_refresh_request"); + } + if (p_property != "constant") { + undo_redo->add_do_method(VisualShaderEditor::get_singleton()->get_graph_plugin(), "update_node_deferred", shader_type, node_id); + undo_redo->add_undo_method(VisualShaderEditor::get_singleton()->get_graph_plugin(), "update_node_deferred", shader_type, node_id); + } else { + undo_redo->add_do_method(VisualShaderEditor::get_singleton()->get_graph_plugin(), "update_constant", shader_type, node_id); + undo_redo->add_undo_method(VisualShaderEditor::get_singleton()->get_graph_plugin(), "update_constant", shader_type, node_id); } undo_redo->commit_action(); @@ -3011,10 +4200,6 @@ public: } } - void _refresh_request() { - VisualShaderEditor::get_singleton()->call_deferred("_update_graph"); - } - void _resource_selected(const String &p_path, RES p_resource) { _open_inspector(p_resource); } @@ -3040,6 +4225,9 @@ public: node = p_node; properties = p_properties; + node_id = (int)p_node->get_meta("id"); + shader_type = VisualShader::Type((int)p_node->get_meta("shader_type")); + for (int i = 0; i < p_properties.size(); i++) { HBoxContainer *hbox = memnew(HBoxContainer); hbox->set_h_size_flags(SIZE_EXPAND_FILL); @@ -3067,17 +4255,22 @@ public: properties[i]->set_name_split_ratio(0); } node->connect("changed", callable_mp(this, &VisualShaderNodePluginDefaultEditor::_node_changed)); - node->connect("editor_refresh_request", callable_mp(this, &VisualShaderNodePluginDefaultEditor::_refresh_request), varray(), CONNECT_DEFERRED); } static void _bind_methods() { - ClassDB::bind_method("_refresh_request", &VisualShaderNodePluginDefaultEditor::_refresh_request); // Used by UndoRedo. ClassDB::bind_method("_open_inspector", &VisualShaderNodePluginDefaultEditor::_open_inspector); // Used by UndoRedo. ClassDB::bind_method("_show_prop_names", &VisualShaderNodePluginDefaultEditor::_show_prop_names); // Used with call_deferred. } }; Control *VisualShaderNodePluginDefault::create_editor(const Ref<Resource> &p_parent_resource, const Ref<VisualShaderNode> &p_node) { + if (p_node->is_class("VisualShaderNodeUniformRef")) { + //create input + VisualShaderNodePluginUniformRefEditor *uniform_editor = memnew(VisualShaderNodePluginUniformRefEditor); + uniform_editor->setup(p_node); + return uniform_editor; + } + if (p_node->is_class("VisualShaderNodeInput")) { //create input VisualShaderNodePluginInputEditor *input_editor = memnew(VisualShaderNodePluginInputEditor); @@ -3153,6 +4346,10 @@ void EditorPropertyShaderMode::_option_selected(int p_which) { //do is easy undo_redo->add_do_method(visual_shader.ptr(), "set_mode", p_which); undo_redo->add_undo_method(visual_shader.ptr(), "set_mode", visual_shader->get_mode()); + + undo_redo->add_do_method(VisualShaderEditor::get_singleton(), "_set_mode", p_which); + undo_redo->add_undo_method(VisualShaderEditor::get_singleton(), "_set_mode", visual_shader->get_mode()); + //now undo is hell //1. restore connections to output @@ -3276,10 +4473,17 @@ void VisualShaderNodePortPreview::_shader_changed() { for (int i = EditorNode::get_singleton()->get_editor_history()->get_path_size() - 1; i >= 0; i--) { Object *object = ObjectDB::get_instance(EditorNode::get_singleton()->get_editor_history()->get_path_object(i)); + ShaderMaterial *src_mat; if (!object) { continue; } - ShaderMaterial *src_mat = Object::cast_to<ShaderMaterial>(object); + if (object->has_method("get_material_override")) { // trying getting material from MeshInstance + src_mat = Object::cast_to<ShaderMaterial>(object->call("get_material_override")); + } else if (object->has_method("get_material")) { // from CanvasItem/Node2D + src_mat = Object::cast_to<ShaderMaterial>(object->call("get_material")); + } else { + src_mat = Object::cast_to<ShaderMaterial>(object); + } if (src_mat && src_mat->get_shader().is_valid()) { List<PropertyInfo> params; src_mat->get_shader()->get_param_list(¶ms); @@ -3331,9 +4535,6 @@ void VisualShaderNodePortPreview::_notification(int p_what) { void VisualShaderNodePortPreview::_bind_methods() { } -VisualShaderNodePortPreview::VisualShaderNodePortPreview() { -} - ////////////////////////////////// String VisualShaderConversionPlugin::converts_to() const { diff --git a/editor/plugins/visual_shader_editor_plugin.h b/editor/plugins/visual_shader_editor_plugin.h index d2f10d9407..182bed6ba6 100644 --- a/editor/plugins/visual_shader_editor_plugin.h +++ b/editor/plugins/visual_shader_editor_plugin.h @@ -5,8 +5,8 @@ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ -/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ -/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 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 */ @@ -33,6 +33,7 @@ #include "editor/editor_node.h" #include "editor/editor_plugin.h" +#include "editor/plugins/curve_editor_plugin.h" #include "editor/property_editor.h" #include "scene/gui/button.h" #include "scene/gui/graph_edit.h" @@ -50,28 +51,106 @@ public: virtual Control *create_editor(const Ref<Resource> &p_parent_resource, const Ref<VisualShaderNode> &p_node); }; +class VisualShaderGraphPlugin : public Reference { + GDCLASS(VisualShaderGraphPlugin, Reference); + +private: + struct InputPort { + Button *default_input_button = nullptr; + }; + + struct Port { + TextureButton *preview_button = nullptr; + }; + + struct Link { + VisualShader::Type type = VisualShader::Type::TYPE_MAX; + VisualShaderNode *visual_node = nullptr; + GraphNode *graph_node = nullptr; + bool preview_visible = 0; + int preview_pos = 0; + Map<int, InputPort> input_ports; + Map<int, Port> output_ports; + VBoxContainer *preview_box = nullptr; + LineEdit *uniform_name = nullptr; + OptionButton *const_op = nullptr; + CodeEdit *expression_edit = nullptr; + CurveEditor *curve_editor = nullptr; + }; + + Ref<VisualShader> visual_shader; + Map<int, Link> links; + List<VisualShader::Connection> connections; + bool dirty = false; + +protected: + static void _bind_methods(); + +public: + void register_shader(VisualShader *p_visual_shader); + void set_connections(List<VisualShader::Connection> &p_connections); + void register_link(VisualShader::Type p_type, int p_id, VisualShaderNode *p_visual_node, GraphNode *p_graph_node); + void register_output_port(int p_id, int p_port, TextureButton *p_button); + void register_uniform_name(int p_id, LineEdit *p_uniform_name); + void register_default_input_button(int p_node_id, int p_port_id, Button *p_button); + void register_constant_option_btn(int p_node_id, OptionButton *p_button); + void register_expression_edit(int p_node_id, CodeEdit *p_expression_edit); + void register_curve_editor(int p_node_id, CurveEditor *p_curve_editor); + void clear_links(); + void set_shader_type(VisualShader::Type p_type); + bool is_preview_visible(int p_id) const; + bool is_dirty() const; + void make_dirty(bool p_enabled); + void update_node(VisualShader::Type p_type, int p_id); + void update_node_deferred(VisualShader::Type p_type, int p_node_id); + void add_node(VisualShader::Type p_type, int p_id); + void remove_node(VisualShader::Type p_type, int p_id); + void connect_nodes(VisualShader::Type p_type, int p_from_node, int p_from_port, int p_to_node, int p_to_port); + void disconnect_nodes(VisualShader::Type p_type, int p_from_node, int p_from_port, int p_to_node, int p_to_port); + void show_port_preview(VisualShader::Type p_type, int p_node_id, int p_port_id); + void set_node_position(VisualShader::Type p_type, int p_id, const Vector2 &p_position); + void set_node_size(VisualShader::Type p_type, int p_id, const Vector2 &p_size); + void refresh_node_ports(VisualShader::Type p_type, int p_node); + void set_input_port_default_value(VisualShader::Type p_type, int p_node_id, int p_port_id, Variant p_value); + void update_uniform_refs(); + void set_uniform_name(VisualShader::Type p_type, int p_node_id, const String &p_name); + void update_curve(int p_node_id); + void update_constant(VisualShader::Type p_type, int p_node_id); + void set_expression(VisualShader::Type p_type, int p_node_id, const String &p_expression); + int get_constant_index(float p_constant) const; + void update_node_size(int p_node_id); + VisualShader::Type get_shader_type() const; + + VisualShaderGraphPlugin(); + ~VisualShaderGraphPlugin(); +}; + class VisualShaderEditor : public VBoxContainer { GDCLASS(VisualShaderEditor, VBoxContainer); + friend class VisualShaderGraphPlugin; CustomPropertyEditor *property_editor; int editing_node; int editing_port; Ref<VisualShader> visual_shader; - HSplitContainer *main_box; GraphEdit *graph; - ToolButton *add_node; - ToolButton *preview_shader; + Button *add_node; + Button *preview_shader; - OptionButton *edit_type; + OptionButton *edit_type = nullptr; + OptionButton *edit_type_standart; + OptionButton *edit_type_particles; PanelContainer *error_panel; Label *error_label; bool pending_update_preview; bool shader_error; + Window *preview_window; VBoxContainer *preview_vbox; - TextEdit *preview_text; + CodeEdit *preview_text; + Ref<CodeHighlighter> syntax_highlighter; Label *error_text; UndoRedo *undo_redo; @@ -82,7 +161,21 @@ class VisualShaderEditor : public VBoxContainer { PopupMenu *popup_menu; MenuButton *tools; - bool preview_showed; + bool preview_first = true; + bool preview_showed = false; + bool particles_mode; + + enum TypeFlags { + TYPE_FLAGS_VERTEX = 1, + TYPE_FLAGS_FRAGMENT = 2, + TYPE_FLAGS_LIGHT = 4, + }; + + enum ParticlesTypeFlags { + TYPE_FLAGS_EMIT = 1, + TYPE_FLAGS_PROCESS = 2, + TYPE_FLAGS_END = 4 + }; enum ToolsMenuOptions { EXPAND_ALL, @@ -96,6 +189,9 @@ class VisualShaderEditor : public VBoxContainer { PASTE, DELETE, DUPLICATE, + SEPARATOR2, // ignore + CONVERT_CONSTANTS_TO_UNIFORMS, + CONVERT_UNIFORMS_TO_CONSTANTS, }; Tree *members; @@ -114,16 +210,16 @@ class VisualShaderEditor : public VBoxContainer { String category; String type; String description; - int sub_func; + int sub_func = 0; String sub_func_str; Ref<Script> script; - int mode; - int return_type; - int func; - float value; - bool highend; - bool is_custom; - int temp_idx; + int mode = 0; + int return_type = 0; + int func = 0; + float value = 0; + bool highend = false; + bool is_custom = false; + int temp_idx = 0; AddOption(const String &p_name = String(), const String &p_category = String(), const String &p_sub_category = String(), const String &p_type = String(), const String &p_description = String(), int p_sub_func = -1, int p_return_type = -1, int p_mode = -1, int p_func = -1, float p_value = -1, bool p_highend = false) { name = p_name; @@ -161,24 +257,48 @@ class VisualShaderEditor : public VBoxContainer { }; Vector<AddOption> add_options; - int texture_node_option_idx; + int cubemap_node_option_idx; + int texture2d_node_option_idx; + int texture2d_array_node_option_idx; + int texture3d_node_option_idx; int custom_node_option_idx; + int curve_node_option_idx; List<String> keyword_list; + List<VisualShaderNodeUniformRef> uniform_refs; + void _draw_color_over_button(Object *obj, Color p_color); void _add_custom_node(const String &p_path); - void _add_texture_node(const String &p_path); + void _add_cubemap_node(const String &p_path); + void _add_texture2d_node(const String &p_path); + void _add_texture2d_array_node(const String &p_path); + void _add_texture3d_node(const String &p_path); + void _add_curve_node(const String &p_path); + + void _setup_node(VisualShaderNode *p_node, int p_op_idx); VisualShaderNode *_add_node(int p_idx, int p_op_idx = -1); void _update_options_menu(); + void _set_mode(int p_which); void _show_preview_text(); + void _preview_close_requested(); + void _preview_size_changed(); void _update_preview(); String _get_description(int p_idx); static VisualShaderEditor *singleton; + struct DragOp { + VisualShader::Type type = VisualShader::Type::TYPE_MAX; + int node = 0; + Vector2 from; + Vector2 to; + }; + List<DragOp> drag_buffer; + bool drag_dirty = false; void _node_dragged(const Vector2 &p_from, const Vector2 &p_to, int p_node); + void _nodes_dragged(); bool updating; void _connection_request(const String &p_from, int p_from_index, const String &p_to, int p_to_index); @@ -187,8 +307,9 @@ class VisualShaderEditor : public VBoxContainer { void _scroll_changed(const Vector2 &p_scroll); void _node_selected(Object *p_node); - void _delete_request(int); - void _delete_nodes(); + void _delete_nodes(int p_type, const List<int> &p_nodes); + void _delete_node_request(int p_type, int p_node); + void _delete_nodes_request(); void _removed_from_graph(); @@ -202,11 +323,19 @@ class VisualShaderEditor : public VBoxContainer { int from_node; int from_slot; + Set<int> selected_constants; + Set<int> selected_uniforms; + + void _convert_constants_to_uniforms(bool p_vice_versa); + void _replace_node(VisualShader::Type p_type_id, int p_node_id, const StringName &p_from, const StringName &p_to); + void _update_constant(VisualShader::Type p_type_id, int p_node_id, Variant p_var, int p_preview_port); + void _update_uniform(VisualShader::Type p_type_id, int p_node_id, Variant p_var, int p_preview_port); + void _connection_to_empty(const String &p_from, int p_from_slot, const Vector2 &p_release_position); void _connection_from_empty(const String &p_to, int p_to_slot, const Vector2 &p_release_position); - void _line_edit_changed(const String &p_text, Object *line_edit, int p_node_id); - void _line_edit_focus_out(Object *line_edit, int p_node_id); + void _uniform_line_edit_changed(const String &p_text, int p_node_id); + void _uniform_line_edit_focus_out(Object *line_edit, int p_node_id); void _port_name_focus_out(Object *line_edit, int p_node_id, int p_port_id, bool p_output); @@ -226,23 +355,28 @@ class VisualShaderEditor : public VBoxContainer { void _paste_nodes(bool p_use_custom_position = false, const Vector2 &p_custom_position = Vector2()); Vector<Ref<VisualShaderNodePlugin>> plugins; + Ref<VisualShaderGraphPlugin> graph_plugin; void _mode_selected(int p_id); - void _rebuild(); void _input_select_item(Ref<VisualShaderNodeInput> input, String name); + void _uniform_select_item(Ref<VisualShaderNodeUniformRef> p_uniform, String p_name); + + void _float_constant_selected(int p_index, int p_node); + + VisualShader::Type get_current_shader_type() const; void _add_input_port(int p_node, int p_port, int p_port_type, const String &p_name); void _remove_input_port(int p_node, int p_port); void _change_input_port_type(int p_type, int p_node, int p_port); - void _change_input_port_name(const String &p_text, Object *line_edit, int p_node, int p_port); + void _change_input_port_name(const String &p_text, Object *p_line_edit, int p_node, int p_port); void _add_output_port(int p_node, int p_port, int p_port_type, const String &p_name); void _remove_output_port(int p_node, int p_port); void _change_output_port_type(int p_type, int p_node, int p_port); - void _change_output_port_name(const String &p_text, Object *line_edit, int p_node, int p_port); + void _change_output_port_name(const String &p_text, Object *p_line_edit, int p_node, int p_port); - void _expression_focus_out(Object *text_edit, int p_node); + void _expression_focus_out(Object *code_edit, int p_node); void _set_node_size(int p_type, int p_node, const Size2 &p_size); void _node_resized(const Vector2 &p_new_size, int p_type, int p_node); @@ -266,6 +400,10 @@ class VisualShaderEditor : public VBoxContainer { bool _is_available(int p_mode); void _update_created_node(GraphNode *node); + void _update_uniforms(bool p_update_refs); + void _update_uniform_refs(Set<String> &p_names); + + void _visibility_changed(); protected: void _notification(int p_what); @@ -277,11 +415,12 @@ public: void remove_plugin(const Ref<VisualShaderNodePlugin> &p_plugin); static VisualShaderEditor *get_singleton() { return singleton; } + VisualShaderGraphPlugin *get_graph_plugin() { return graph_plugin.ptr(); } void clear_custom_types(); void add_custom_type(const String &p_name, const Ref<Script> &p_script, const String &p_description, int p_return_icon_type, const String &p_category, bool p_highend); - virtual Size2 get_minimum_size() const; + virtual Size2 get_minimum_size() const override; void edit(VisualShader *p_visual_shader); VisualShaderEditor(); }; @@ -294,11 +433,11 @@ class VisualShaderEditorPlugin : public EditorPlugin { Button *button; public: - virtual String get_name() const { return "VisualShader"; } - bool has_main_screen() const { return false; } - virtual void edit(Object *p_object); - virtual bool handles(Object *p_object) const; - virtual void make_visible(bool p_visible); + virtual String get_name() const override { return "VisualShader"; } + bool has_main_screen() const override { return false; } + virtual void edit(Object *p_object) override; + virtual bool handles(Object *p_object) const override; + virtual void make_visible(bool p_visible) override; VisualShaderEditorPlugin(EditorNode *p_node); ~VisualShaderEditorPlugin(); @@ -308,7 +447,7 @@ class VisualShaderNodePluginDefault : public VisualShaderNodePlugin { GDCLASS(VisualShaderNodePluginDefault, VisualShaderNodePlugin); public: - virtual Control *create_editor(const Ref<Resource> &p_parent_resource, const Ref<VisualShaderNode> &p_node); + virtual Control *create_editor(const Ref<Resource> &p_parent_resource, const Ref<VisualShaderNode> &p_node) override; }; class EditorPropertyShaderMode : public EditorProperty { @@ -322,7 +461,7 @@ protected: public: void setup(const Vector<String> &p_options); - virtual void update_property(); + virtual void update_property() override; void set_option_button_clip(bool p_enable); EditorPropertyShaderMode(); }; @@ -331,36 +470,35 @@ class EditorInspectorShaderModePlugin : public EditorInspectorPlugin { GDCLASS(EditorInspectorShaderModePlugin, EditorInspectorPlugin); public: - virtual bool can_handle(Object *p_object); - virtual void parse_begin(Object *p_object); - virtual bool parse_property(Object *p_object, Variant::Type p_type, const String &p_path, PropertyHint p_hint, const String &p_hint_text, int p_usage, bool p_wide = false); - virtual void parse_end(); + virtual bool can_handle(Object *p_object) override; + virtual void parse_begin(Object *p_object) override; + virtual bool parse_property(Object *p_object, Variant::Type p_type, const String &p_path, PropertyHint p_hint, const String &p_hint_text, int p_usage, bool p_wide = false) override; + virtual void parse_end() override; }; class VisualShaderNodePortPreview : public Control { GDCLASS(VisualShaderNodePortPreview, Control); Ref<VisualShader> shader; - VisualShader::Type type; - int node; - int port; + VisualShader::Type type = VisualShader::Type::TYPE_MAX; + int node = 0; + int port = 0; void _shader_changed(); //must regen protected: void _notification(int p_what); static void _bind_methods(); public: - virtual Size2 get_minimum_size() const; + virtual Size2 get_minimum_size() const override; void setup(const Ref<VisualShader> &p_shader, VisualShader::Type p_type, int p_node, int p_port); - VisualShaderNodePortPreview(); }; class VisualShaderConversionPlugin : public EditorResourceConversionPlugin { GDCLASS(VisualShaderConversionPlugin, EditorResourceConversionPlugin); public: - virtual String converts_to() const; - virtual bool handles(const Ref<Resource> &p_resource) const; - virtual Ref<Resource> convert(const Ref<Resource> &p_resource) const; + virtual String converts_to() const override; + virtual bool handles(const Ref<Resource> &p_resource) const override; + virtual Ref<Resource> convert(const Ref<Resource> &p_resource) const override; }; #endif // VISUAL_SHADER_EDITOR_PLUGIN_H |