summaryrefslogtreecommitdiff
path: root/scene
diff options
context:
space:
mode:
Diffstat (limited to 'scene')
-rw-r--r--scene/2d/audio_stream_player_2d.cpp3
-rw-r--r--scene/2d/audio_stream_player_2d.h2
-rw-r--r--scene/2d/back_buffer_copy.cpp7
-rw-r--r--scene/2d/back_buffer_copy.h1
-rw-r--r--scene/2d/camera_2d.cpp7
-rw-r--r--scene/2d/canvas_group.cpp2
-rw-r--r--scene/2d/gpu_particles_2d.cpp10
-rw-r--r--scene/2d/gpu_particles_2d.h2
-rw-r--r--scene/2d/joint_2d.cpp18
-rw-r--r--scene/2d/multimesh_instance_2d.cpp10
-rw-r--r--scene/2d/navigation_agent_2d.cpp99
-rw-r--r--scene/2d/navigation_agent_2d.h25
-rw-r--r--scene/2d/navigation_link_2d.cpp2
-rw-r--r--scene/2d/navigation_link_2d.h6
-rw-r--r--scene/2d/navigation_region_2d.cpp388
-rw-r--r--scene/2d/navigation_region_2d.h71
-rw-r--r--scene/2d/node_2d.cpp76
-rw-r--r--scene/2d/node_2d.h17
-rw-r--r--scene/2d/path_2d.cpp61
-rw-r--r--scene/2d/path_2d.h1
-rw-r--r--scene/2d/physics_body_2d.cpp18
-rw-r--r--scene/2d/physics_body_2d.h4
-rw-r--r--scene/2d/polygon_2d.cpp4
-rw-r--r--scene/2d/skeleton_2d.cpp2
-rw-r--r--scene/2d/tile_map.cpp141
-rw-r--r--scene/2d/tile_map.h24
-rw-r--r--scene/2d/touch_screen_button.cpp4
-rw-r--r--scene/3d/audio_stream_player_3d.cpp3
-rw-r--r--scene/3d/audio_stream_player_3d.h2
-rw-r--r--scene/3d/bone_attachment_3d.cpp4
-rw-r--r--scene/3d/bone_attachment_3d.h2
-rw-r--r--scene/3d/camera_3d.cpp11
-rw-r--r--scene/3d/collision_object_3d.cpp1
-rw-r--r--scene/3d/collision_shape_3d.cpp11
-rw-r--r--scene/3d/cpu_particles_3d.cpp2
-rw-r--r--scene/3d/gpu_particles_3d.cpp4
-rw-r--r--scene/3d/gpu_particles_3d.h2
-rw-r--r--scene/3d/gpu_particles_collision_3d.cpp4
-rw-r--r--scene/3d/light_3d.cpp14
-rw-r--r--scene/3d/light_3d.h3
-rw-r--r--scene/3d/mesh_instance_3d.cpp12
-rw-r--r--scene/3d/mesh_instance_3d.h1
-rw-r--r--scene/3d/navigation_agent_3d.cpp99
-rw-r--r--scene/3d/navigation_agent_3d.h25
-rw-r--r--scene/3d/navigation_link_3d.cpp2
-rw-r--r--scene/3d/navigation_link_3d.h6
-rw-r--r--scene/3d/navigation_region_3d.cpp65
-rw-r--r--scene/3d/navigation_region_3d.h11
-rw-r--r--scene/3d/node_3d.cpp34
-rw-r--r--scene/3d/node_3d.h4
-rw-r--r--scene/3d/path_3d.cpp177
-rw-r--r--scene/3d/path_3d.h7
-rw-r--r--scene/3d/physics_body_3d.cpp16
-rw-r--r--scene/3d/physics_body_3d.h4
-rw-r--r--scene/3d/skeleton_3d.cpp2
-rw-r--r--scene/3d/soft_body_3d.cpp4
-rw-r--r--scene/3d/spring_arm_3d.cpp1
-rw-r--r--scene/3d/sprite_3d.cpp4
-rw-r--r--scene/3d/visual_instance_3d.cpp77
-rw-r--r--scene/3d/visual_instance_3d.h18
-rw-r--r--scene/3d/xr_nodes.cpp40
-rw-r--r--scene/3d/xr_nodes.h2
-rw-r--r--scene/animation/animation_blend_space_1d.cpp10
-rw-r--r--scene/animation/animation_blend_space_1d.h2
-rw-r--r--scene/animation/animation_blend_space_2d.cpp22
-rw-r--r--scene/animation/animation_blend_space_2d.h2
-rw-r--r--scene/animation/animation_blend_tree.cpp159
-rw-r--r--scene/animation/animation_blend_tree.h24
-rw-r--r--scene/animation/animation_node_state_machine.cpp99
-rw-r--r--scene/animation/animation_node_state_machine.h25
-rw-r--r--scene/animation/animation_player.cpp241
-rw-r--r--scene/animation/animation_player.h6
-rw-r--r--scene/animation/animation_tree.cpp267
-rw-r--r--scene/animation/animation_tree.h26
-rw-r--r--scene/animation/root_motion_view.cpp8
-rw-r--r--scene/debugger/scene_debugger.cpp107
-rw-r--r--scene/debugger/scene_debugger.h20
-rw-r--r--scene/gui/base_button.cpp12
-rw-r--r--scene/gui/base_button.h2
-rw-r--r--scene/gui/button.cpp2
-rw-r--r--scene/gui/code_edit.cpp34
-rw-r--r--scene/gui/code_edit.h1
-rw-r--r--scene/gui/color_picker.cpp9
-rw-r--r--scene/gui/color_picker.h4
-rw-r--r--scene/gui/control.cpp209
-rw-r--r--scene/gui/control.h18
-rw-r--r--scene/gui/dialogs.cpp2
-rw-r--r--scene/gui/file_dialog.cpp7
-rw-r--r--scene/gui/graph_edit.cpp91
-rw-r--r--scene/gui/graph_edit.h4
-rw-r--r--scene/gui/graph_node.cpp66
-rw-r--r--scene/gui/item_list.cpp1
-rw-r--r--scene/gui/line_edit.cpp102
-rw-r--r--scene/gui/line_edit.h3
-rw-r--r--scene/gui/link_button.cpp19
-rw-r--r--scene/gui/link_button.h4
-rw-r--r--scene/gui/option_button.cpp6
-rw-r--r--scene/gui/popup_menu.cpp4
-rw-r--r--scene/gui/progress_bar.cpp7
-rw-r--r--scene/gui/range.cpp23
-rw-r--r--scene/gui/range.h1
-rw-r--r--scene/gui/rich_text_effect.cpp4
-rw-r--r--scene/gui/rich_text_effect.h6
-rw-r--r--scene/gui/rich_text_label.cpp152
-rw-r--r--scene/gui/rich_text_label.h8
-rw-r--r--scene/gui/scroll_bar.cpp2
-rw-r--r--scene/gui/scroll_bar.h2
-rw-r--r--scene/gui/scroll_container.cpp4
-rw-r--r--scene/gui/spin_box.cpp5
-rw-r--r--scene/gui/split_container.cpp3
-rw-r--r--scene/gui/subviewport_container.cpp12
-rw-r--r--scene/gui/subviewport_container.h3
-rw-r--r--scene/gui/tab_bar.cpp3
-rw-r--r--scene/gui/text_edit.cpp27
-rw-r--r--scene/gui/texture_button.cpp52
-rw-r--r--scene/gui/texture_button.h20
-rw-r--r--scene/gui/tree.cpp132
-rw-r--r--scene/gui/tree.h5
-rw-r--r--scene/main/canvas_item.cpp60
-rw-r--r--scene/main/canvas_item.h17
-rw-r--r--scene/main/canvas_layer.cpp15
-rw-r--r--scene/main/canvas_layer.h1
-rw-r--r--scene/main/http_request.cpp49
-rw-r--r--scene/main/multiplayer_api.cpp2
-rw-r--r--scene/main/multiplayer_peer.h4
-rw-r--r--scene/main/node.cpp98
-rw-r--r--scene/main/node.h5
-rw-r--r--scene/main/scene_tree.cpp13
-rw-r--r--scene/main/viewport.cpp116
-rw-r--r--scene/main/viewport.h6
-rw-r--r--scene/main/window.cpp538
-rw-r--r--scene/main/window.h64
-rw-r--r--scene/property_utils.h2
-rw-r--r--scene/register_scene_types.cpp21
-rw-r--r--scene/resources/animation.cpp834
-rw-r--r--scene/resources/animation.h48
-rw-r--r--scene/resources/animation_library.cpp13
-rw-r--r--scene/resources/animation_library.h2
-rw-r--r--scene/resources/bit_map.cpp105
-rw-r--r--scene/resources/bit_map.h2
-rw-r--r--scene/resources/bone_map.cpp2
-rw-r--r--scene/resources/camera_attributes.cpp4
-rw-r--r--scene/resources/curve.cpp865
-rw-r--r--scene/resources/curve.h41
-rw-r--r--scene/resources/default_theme/default_theme.cpp8
-rw-r--r--scene/resources/font.cpp183
-rw-r--r--scene/resources/font.h27
-rw-r--r--scene/resources/importer_mesh.cpp6
-rw-r--r--scene/resources/importer_mesh.h2
-rw-r--r--scene/resources/label_settings.cpp6
-rw-r--r--scene/resources/material.cpp24
-rw-r--r--scene/resources/mesh.cpp140
-rw-r--r--scene/resources/mesh.h10
-rw-r--r--scene/resources/mesh_library.cpp77
-rw-r--r--scene/resources/mesh_library.h17
-rw-r--r--scene/resources/multimesh.cpp1
-rw-r--r--scene/resources/navigation_mesh.cpp51
-rw-r--r--scene/resources/navigation_mesh.h12
-rw-r--r--scene/resources/navigation_polygon.cpp354
-rw-r--r--scene/resources/navigation_polygon.h94
-rw-r--r--scene/resources/packed_scene.cpp73
-rw-r--r--scene/resources/packed_scene.h5
-rw-r--r--scene/resources/primitive_meshes.cpp782
-rw-r--r--scene/resources/primitive_meshes.h43
-rw-r--r--scene/resources/resource_format_text.cpp51
-rw-r--r--scene/resources/shader.cpp4
-rw-r--r--scene/resources/shader_include.cpp2
-rw-r--r--scene/resources/shape_2d.cpp1
-rw-r--r--scene/resources/shape_3d.cpp1
-rw-r--r--scene/resources/skeleton_modification_2d_fabrik.h4
-rw-r--r--scene/resources/skeleton_modification_3d_fabrik.h6
-rw-r--r--scene/resources/style_box.cpp12
-rw-r--r--scene/resources/syntax_highlighter.cpp2
-rw-r--r--scene/resources/text_line.cpp12
-rw-r--r--scene/resources/text_line.h4
-rw-r--r--scene/resources/text_paragraph.cpp12
-rw-r--r--scene/resources/text_paragraph.h4
-rw-r--r--scene/resources/texture.cpp152
-rw-r--r--scene/resources/tile_set.cpp59
-rw-r--r--scene/resources/tile_set.h4
-rw-r--r--scene/resources/visual_shader.cpp90
-rw-r--r--scene/resources/visual_shader_nodes.cpp4
-rw-r--r--scene/resources/visual_shader_particle_nodes.cpp59
-rw-r--r--scene/scene_string_names.cpp2
-rw-r--r--scene/scene_string_names.h2
-rw-r--r--scene/theme/theme_db.cpp9
-rw-r--r--scene/theme/theme_owner.cpp69
-rw-r--r--scene/theme/theme_owner.h1
188 files changed, 5614 insertions, 3562 deletions
diff --git a/scene/2d/audio_stream_player_2d.cpp b/scene/2d/audio_stream_player_2d.cpp
index 9ac3083718..2ded209180 100644
--- a/scene/2d/audio_stream_player_2d.cpp
+++ b/scene/2d/audio_stream_player_2d.cpp
@@ -284,6 +284,9 @@ bool AudioStreamPlayer2D::is_playing() const {
return true;
}
}
+ if (setplay.get() >= 0) {
+ return true; // play() has been called this frame, but no playback exists just yet.
+ }
return false;
}
diff --git a/scene/2d/audio_stream_player_2d.h b/scene/2d/audio_stream_player_2d.h
index 616d7fdb60..5bc9083488 100644
--- a/scene/2d/audio_stream_player_2d.h
+++ b/scene/2d/audio_stream_player_2d.h
@@ -82,7 +82,7 @@ private:
float attenuation = 1.0;
float panning_strength = 1.0f;
- float cached_global_panning_strength = 1.0f;
+ float cached_global_panning_strength = 0.5f;
protected:
void _validate_property(PropertyInfo &p_property) const;
diff --git a/scene/2d/back_buffer_copy.cpp b/scene/2d/back_buffer_copy.cpp
index aa4ae01fd9..9c332123e3 100644
--- a/scene/2d/back_buffer_copy.cpp
+++ b/scene/2d/back_buffer_copy.cpp
@@ -71,12 +71,19 @@ Rect2 BackBufferCopy::get_rect() const {
void BackBufferCopy::set_copy_mode(CopyMode p_mode) {
copy_mode = p_mode;
_update_copy_mode();
+ notify_property_list_changed();
}
BackBufferCopy::CopyMode BackBufferCopy::get_copy_mode() const {
return copy_mode;
}
+void BackBufferCopy::_validate_property(PropertyInfo &p_property) const {
+ if (copy_mode != COPY_MODE_RECT && p_property.name == "rect") {
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
+ }
+}
+
void BackBufferCopy::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_rect", "rect"), &BackBufferCopy::set_rect);
ClassDB::bind_method(D_METHOD("get_rect"), &BackBufferCopy::get_rect);
diff --git a/scene/2d/back_buffer_copy.h b/scene/2d/back_buffer_copy.h
index 1f2d5810b0..caacbc83c6 100644
--- a/scene/2d/back_buffer_copy.h
+++ b/scene/2d/back_buffer_copy.h
@@ -51,6 +51,7 @@ private:
protected:
static void _bind_methods();
+ void _validate_property(PropertyInfo &p_property) const;
public:
#ifdef TOOLS_ENABLED
diff --git a/scene/2d/camera_2d.cpp b/scene/2d/camera_2d.cpp
index 4b31bbddac..229625ad6d 100644
--- a/scene/2d/camera_2d.cpp
+++ b/scene/2d/camera_2d.cpp
@@ -39,8 +39,11 @@ void Camera2D::_update_scroll() {
}
if (Engine::get_singleton()->is_editor_hint()) {
- queue_redraw(); //will just be drawn
- return;
+ queue_redraw();
+ // Only set viewport transform when not bound to the main viewport.
+ if (get_viewport() == get_tree()->get_edited_scene_root()->get_viewport()) {
+ return;
+ }
}
if (!viewport) {
diff --git a/scene/2d/canvas_group.cpp b/scene/2d/canvas_group.cpp
index d4182f85a7..0ada703837 100644
--- a/scene/2d/canvas_group.cpp
+++ b/scene/2d/canvas_group.cpp
@@ -47,7 +47,7 @@ void CanvasGroup::set_clear_margin(real_t p_clear_margin) {
ERR_FAIL_COND(p_clear_margin < 0.0);
clear_margin = p_clear_margin;
- RS::get_singleton()->canvas_item_set_canvas_group_mode(get_canvas_item(), RS::CANVAS_GROUP_MODE_TRANSPARENT, clear_margin, true, clear_margin, use_mipmaps);
+ RS::get_singleton()->canvas_item_set_canvas_group_mode(get_canvas_item(), RS::CANVAS_GROUP_MODE_TRANSPARENT, clear_margin, true, fit_margin, use_mipmaps);
queue_redraw();
}
diff --git a/scene/2d/gpu_particles_2d.cpp b/scene/2d/gpu_particles_2d.cpp
index e18f2bd1a1..ccbc080768 100644
--- a/scene/2d/gpu_particles_2d.cpp
+++ b/scene/2d/gpu_particles_2d.cpp
@@ -299,10 +299,6 @@ bool GPUParticles2D::get_interpolate() const {
PackedStringArray GPUParticles2D::get_configuration_warnings() const {
PackedStringArray warnings = Node2D::get_configuration_warnings();
- if (RenderingServer::get_singleton()->is_low_end()) {
- warnings.push_back(RTR("GPU-based particles are not supported by the OpenGL video driver.\nUse the CPUParticles2D node instead. You can use the \"Convert to CPUParticles2D\" option for this purpose."));
- }
-
if (process_material.is_null()) {
warnings.push_back(RTR("A material to process the particles is not assigned, so no behavior is imprinted."));
} else {
@@ -629,6 +625,8 @@ void GPUParticles2D::_bind_methods() {
ADD_PROPERTY_DEFAULT("emitting", true); // Workaround for doctool in headless mode, as dummy rasterizer always returns false.
ADD_PROPERTY(PropertyInfo(Variant::INT, "amount", PROPERTY_HINT_RANGE, "1,1000000,1,exp"), "set_amount", "get_amount");
ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "sub_emitter", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "GPUParticles2D"), "set_sub_emitter", "get_sub_emitter");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "process_material", PROPERTY_HINT_RESOURCE_TYPE, "ShaderMaterial,ParticleProcessMaterial"), "set_process_material", "get_process_material");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture2D"), "set_texture", "get_texture");
ADD_GROUP("Time", "");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "lifetime", PROPERTY_HINT_RANGE, "0.01,600.0,0.01,or_greater,suffix:s"), "set_lifetime", "get_lifetime");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "one_shot"), "set_one_shot", "get_one_shot");
@@ -650,10 +648,6 @@ void GPUParticles2D::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "trail_lifetime", PROPERTY_HINT_RANGE, "0.01,10,0.01,or_greater,suffix:s"), "set_trail_lifetime", "get_trail_lifetime");
ADD_PROPERTY(PropertyInfo(Variant::INT, "trail_sections", PROPERTY_HINT_RANGE, "2,128,1"), "set_trail_sections", "get_trail_sections");
ADD_PROPERTY(PropertyInfo(Variant::INT, "trail_section_subdivisions", PROPERTY_HINT_RANGE, "1,1024,1"), "set_trail_section_subdivisions", "get_trail_section_subdivisions");
- ADD_GROUP("Process Material", "process_");
- ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "process_material", PROPERTY_HINT_RESOURCE_TYPE, "ShaderMaterial,ParticleProcessMaterial"), "set_process_material", "get_process_material");
- ADD_GROUP("Textures", "");
- ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture2D"), "set_texture", "get_texture");
BIND_ENUM_CONSTANT(DRAW_ORDER_INDEX);
BIND_ENUM_CONSTANT(DRAW_ORDER_LIFETIME);
diff --git a/scene/2d/gpu_particles_2d.h b/scene/2d/gpu_particles_2d.h
index 7fba174357..94555e0bb0 100644
--- a/scene/2d/gpu_particles_2d.h
+++ b/scene/2d/gpu_particles_2d.h
@@ -64,7 +64,7 @@ private:
#endif
Ref<Material> process_material;
- DrawOrder draw_order;
+ DrawOrder draw_order = DRAW_ORDER_LIFETIME;
Ref<Texture2D> texture;
diff --git a/scene/2d/joint_2d.cpp b/scene/2d/joint_2d.cpp
index 6000508f36..3ec744ff8e 100644
--- a/scene/2d/joint_2d.cpp
+++ b/scene/2d/joint_2d.cpp
@@ -112,7 +112,7 @@ void Joint2D::_update_joint(bool p_only_free) {
ERR_FAIL_COND_MSG(!joint.is_valid(), "Failed to configure the joint.");
- PhysicsServer2D::get_singleton()->get_singleton()->joint_set_param(joint, PhysicsServer2D::JOINT_PARAM_BIAS, bias);
+ PhysicsServer2D::get_singleton()->joint_set_param(joint, PhysicsServer2D::JOINT_PARAM_BIAS, bias);
ba = body_a->get_rid();
bb = body_b->get_rid();
@@ -133,7 +133,13 @@ void Joint2D::set_node_a(const NodePath &p_node_a) {
}
a = p_node_a;
- _update_joint();
+ if (Engine::get_singleton()->is_editor_hint()) {
+ // When in editor, the setter may be called as a result of node rename.
+ // It happens before the node actually changes its name, which triggers false warning.
+ callable_mp(this, &Joint2D::_update_joint).call_deferred();
+ } else {
+ _update_joint();
+ }
}
NodePath Joint2D::get_node_a() const {
@@ -150,7 +156,11 @@ void Joint2D::set_node_b(const NodePath &p_node_b) {
}
b = p_node_b;
- _update_joint();
+ if (Engine::get_singleton()->is_editor_hint()) {
+ callable_mp(this, &Joint2D::_update_joint).call_deferred();
+ } else {
+ _update_joint();
+ }
}
NodePath Joint2D::get_node_b() const {
@@ -178,7 +188,7 @@ void Joint2D::_notification(int p_what) {
void Joint2D::set_bias(real_t p_bias) {
bias = p_bias;
if (joint.is_valid()) {
- PhysicsServer2D::get_singleton()->get_singleton()->joint_set_param(joint, PhysicsServer2D::JOINT_PARAM_BIAS, bias);
+ PhysicsServer2D::get_singleton()->joint_set_param(joint, PhysicsServer2D::JOINT_PARAM_BIAS, bias);
}
}
diff --git a/scene/2d/multimesh_instance_2d.cpp b/scene/2d/multimesh_instance_2d.cpp
index 68d529fd32..fa72fc5b8b 100644
--- a/scene/2d/multimesh_instance_2d.cpp
+++ b/scene/2d/multimesh_instance_2d.cpp
@@ -30,6 +30,7 @@
#include "multimesh_instance_2d.h"
+#include "core/core_string_names.h"
#include "scene/scene_string_names.h"
void MultiMeshInstance2D::_notification(int p_what) {
@@ -60,7 +61,16 @@ void MultiMeshInstance2D::_bind_methods() {
}
void MultiMeshInstance2D::set_multimesh(const Ref<MultiMesh> &p_multimesh) {
+ // Cleanup previous connection if any.
+ if (multimesh.is_valid()) {
+ multimesh->disconnect(CoreStringNames::get_singleton()->changed, callable_mp((CanvasItem *)this, &CanvasItem::queue_redraw));
+ }
multimesh = p_multimesh;
+
+ // Connect to the multimesh so the AABB can update when instance transforms are changed.
+ if (multimesh.is_valid()) {
+ multimesh->connect(CoreStringNames::get_singleton()->changed, callable_mp((CanvasItem *)this, &CanvasItem::queue_redraw));
+ }
queue_redraw();
}
diff --git a/scene/2d/navigation_agent_2d.cpp b/scene/2d/navigation_agent_2d.cpp
index 1a62c9bb6c..62afe0d89b 100644
--- a/scene/2d/navigation_agent_2d.cpp
+++ b/scene/2d/navigation_agent_2d.cpp
@@ -70,6 +70,9 @@ void NavigationAgent2D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_navigation_layer_value", "layer_number", "value"), &NavigationAgent2D::set_navigation_layer_value);
ClassDB::bind_method(D_METHOD("get_navigation_layer_value", "layer_number"), &NavigationAgent2D::get_navigation_layer_value);
+ ClassDB::bind_method(D_METHOD("set_path_metadata_flags", "flags"), &NavigationAgent2D::set_path_metadata_flags);
+ ClassDB::bind_method(D_METHOD("get_path_metadata_flags"), &NavigationAgent2D::get_path_metadata_flags);
+
ClassDB::bind_method(D_METHOD("set_navigation_map", "navigation_map"), &NavigationAgent2D::set_navigation_map);
ClassDB::bind_method(D_METHOD("get_navigation_map"), &NavigationAgent2D::get_navigation_map);
@@ -79,8 +82,9 @@ void NavigationAgent2D::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_next_location"), &NavigationAgent2D::get_next_location);
ClassDB::bind_method(D_METHOD("distance_to_target"), &NavigationAgent2D::distance_to_target);
ClassDB::bind_method(D_METHOD("set_velocity", "velocity"), &NavigationAgent2D::set_velocity);
- ClassDB::bind_method(D_METHOD("get_nav_path"), &NavigationAgent2D::get_nav_path);
- ClassDB::bind_method(D_METHOD("get_nav_path_index"), &NavigationAgent2D::get_nav_path_index);
+ ClassDB::bind_method(D_METHOD("get_current_navigation_result"), &NavigationAgent2D::get_current_navigation_result);
+ ClassDB::bind_method(D_METHOD("get_current_navigation_path"), &NavigationAgent2D::get_current_navigation_path);
+ ClassDB::bind_method(D_METHOD("get_current_navigation_path_index"), &NavigationAgent2D::get_current_navigation_path_index);
ClassDB::bind_method(D_METHOD("is_target_reached"), &NavigationAgent2D::is_target_reached);
ClassDB::bind_method(D_METHOD("is_target_reachable"), &NavigationAgent2D::is_target_reachable);
ClassDB::bind_method(D_METHOD("is_navigation_finished"), &NavigationAgent2D::is_navigation_finished);
@@ -94,6 +98,7 @@ void NavigationAgent2D::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "target_desired_distance", PROPERTY_HINT_RANGE, "0.1,100,0.01,suffix:px"), "set_target_desired_distance", "get_target_desired_distance");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "path_max_distance", PROPERTY_HINT_RANGE, "10,100,1,suffix:px"), "set_path_max_distance", "get_path_max_distance");
ADD_PROPERTY(PropertyInfo(Variant::INT, "navigation_layers", PROPERTY_HINT_LAYERS_2D_NAVIGATION), "set_navigation_layers", "get_navigation_layers");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "path_metadata_flags", PROPERTY_HINT_FLAGS, "Include Types,Include RIDs,Include Owners"), "set_path_metadata_flags", "get_path_metadata_flags");
ADD_GROUP("Avoidance", "");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "avoidance_enabled"), "set_avoidance_enabled", "get_avoidance_enabled");
@@ -105,6 +110,8 @@ void NavigationAgent2D::_bind_methods() {
ADD_SIGNAL(MethodInfo("path_changed"));
ADD_SIGNAL(MethodInfo("target_reached"));
+ ADD_SIGNAL(MethodInfo("waypoint_reached", PropertyInfo(Variant::DICTIONARY, "details")));
+ ADD_SIGNAL(MethodInfo("link_reached", PropertyInfo(Variant::DICTIONARY, "details")));
ADD_SIGNAL(MethodInfo("navigation_finished"));
ADD_SIGNAL(MethodInfo("velocity_computed", PropertyInfo(Variant::VECTOR2, "safe_velocity")));
}
@@ -161,7 +168,7 @@ void NavigationAgent2D::_notification(int p_what) {
} break;
case NOTIFICATION_INTERNAL_PHYSICS_PROCESS: {
- if (agent_parent) {
+ if (agent_parent && target_position_submitted) {
if (avoidance_enabled) {
// agent_position on NavigationServer is avoidance only and has nothing to do with pathfinding
// no point in flooding NavigationServer queue with agent position updates that get send to the void if avoidance is not used
@@ -197,9 +204,9 @@ NavigationAgent2D::~NavigationAgent2D() {
void NavigationAgent2D::set_avoidance_enabled(bool p_enabled) {
avoidance_enabled = p_enabled;
if (avoidance_enabled) {
- NavigationServer2D::get_singleton()->agent_set_callback(agent, this, "_avoidance_done");
+ NavigationServer2D::get_singleton()->agent_set_callback(agent, get_instance_id(), "_avoidance_done");
} else {
- NavigationServer2D::get_singleton()->agent_set_callback(agent, nullptr, "_avoidance_done");
+ NavigationServer2D::get_singleton()->agent_set_callback(agent, ObjectID(), "_avoidance_done");
}
}
@@ -209,7 +216,7 @@ bool NavigationAgent2D::get_avoidance_enabled() const {
void NavigationAgent2D::set_agent_parent(Node *p_agent_parent) {
// remove agent from any avoidance map before changing parent or there will be leftovers on the RVO map
- NavigationServer2D::get_singleton()->agent_set_callback(agent, nullptr, "_avoidance_done");
+ NavigationServer2D::get_singleton()->agent_set_callback(agent, ObjectID(), "_avoidance_done");
if (Object::cast_to<Node2D>(p_agent_parent) != nullptr) {
// place agent on navigation map first or else the RVO agent callback creation fails silently later
agent_parent = Object::cast_to<Node2D>(p_agent_parent);
@@ -256,6 +263,14 @@ bool NavigationAgent2D::get_navigation_layer_value(int p_layer_number) const {
return get_navigation_layers() & (1 << (p_layer_number - 1));
}
+void NavigationAgent2D::set_path_metadata_flags(BitField<NavigationPathQueryParameters2D::PathMetadataFlags> p_path_metadata_flags) {
+ if (path_metadata_flags == p_path_metadata_flags) {
+ return;
+ }
+
+ path_metadata_flags = p_path_metadata_flags;
+}
+
void NavigationAgent2D::set_navigation_map(RID p_navigation_map) {
map_override = p_navigation_map;
NavigationServer2D::get_singleton()->agent_set_map(agent, map_override);
@@ -314,6 +329,7 @@ real_t NavigationAgent2D::get_path_max_distance() {
void NavigationAgent2D::set_target_location(Vector2 p_location) {
target_location = p_location;
+ target_position_submitted = true;
_request_repath();
}
@@ -329,14 +345,10 @@ Vector2 NavigationAgent2D::get_next_location() {
ERR_FAIL_COND_V_MSG(agent_parent == nullptr, Vector2(), "The agent has no parent.");
return agent_parent->get_global_position();
} else {
- return navigation_path[nav_path_index];
+ return navigation_path[navigation_path_index];
}
}
-const Vector<Vector2> &NavigationAgent2D::get_nav_path() const {
- return navigation_result->get_path();
-}
-
real_t NavigationAgent2D::distance_to_target() const {
ERR_FAIL_COND_V_MSG(agent_parent == nullptr, 0.0, "The agent has no parent.");
return agent_parent->get_global_position().distance_to(target_location);
@@ -402,6 +414,9 @@ void NavigationAgent2D::update_navigation() {
if (!agent_parent->is_inside_tree()) {
return;
}
+ if (!target_position_submitted) {
+ return;
+ }
if (update_frame_id == Engine::get_singleton()->get_physics_frames()) {
return;
}
@@ -418,12 +433,12 @@ void NavigationAgent2D::update_navigation() {
reload_path = true;
} else {
// Check if too far from the navigation path
- if (nav_path_index > 0) {
+ if (navigation_path_index > 0) {
const Vector<Vector2> &navigation_path = navigation_result->get_path();
Vector2 segment[2];
- segment[0] = navigation_path[nav_path_index - 1];
- segment[1] = navigation_path[nav_path_index];
+ segment[0] = navigation_path[navigation_path_index - 1];
+ segment[1] = navigation_path[navigation_path_index];
Vector2 p = Geometry2D::get_closest_point_to_segment(origin, segment);
if (origin.distance_to(p) >= path_max_distance) {
// To faraway, reload path
@@ -436,6 +451,7 @@ void NavigationAgent2D::update_navigation() {
navigation_query->set_start_position(origin);
navigation_query->set_target_position(target_location);
navigation_query->set_navigation_layers(navigation_layers);
+ navigation_query->set_metadata_flags(path_metadata_flags);
if (map_override.is_valid()) {
navigation_query->set_map(map_override);
@@ -445,7 +461,7 @@ void NavigationAgent2D::update_navigation() {
NavigationServer2D::get_singleton()->query_path(navigation_query, navigation_result);
navigation_finished = false;
- nav_path_index = 0;
+ navigation_path_index = 0;
emit_signal(SNAME("path_changed"));
}
@@ -457,12 +473,57 @@ void NavigationAgent2D::update_navigation() {
if (navigation_finished == false) {
// Advances to the next far away location.
const Vector<Vector2> &navigation_path = navigation_result->get_path();
- while (origin.distance_to(navigation_path[nav_path_index]) < path_desired_distance) {
- nav_path_index += 1;
- if (nav_path_index == navigation_path.size()) {
+ const Vector<int32_t> &navigation_path_types = navigation_result->get_path_types();
+ const TypedArray<RID> &navigation_path_rids = navigation_result->get_path_rids();
+ const Vector<int64_t> &navigation_path_owners = navigation_result->get_path_owner_ids();
+
+ while (origin.distance_to(navigation_path[navigation_path_index]) < path_desired_distance) {
+ Dictionary details;
+
+ const Vector2 waypoint = navigation_path[navigation_path_index];
+ details[SNAME("location")] = waypoint;
+
+ int waypoint_type = -1;
+ if (path_metadata_flags.has_flag(NavigationPathQueryParameters2D::PathMetadataFlags::PATH_METADATA_INCLUDE_TYPES)) {
+ const NavigationPathQueryResult2D::PathSegmentType type = NavigationPathQueryResult2D::PathSegmentType(navigation_path_types[navigation_path_index]);
+
+ details[SNAME("type")] = type;
+ waypoint_type = type;
+ }
+
+ if (path_metadata_flags.has_flag(NavigationPathQueryParameters2D::PathMetadataFlags::PATH_METADATA_INCLUDE_RIDS)) {
+ details[SNAME("rid")] = navigation_path_rids[navigation_path_index];
+ }
+
+ if (path_metadata_flags.has_flag(NavigationPathQueryParameters2D::PathMetadataFlags::PATH_METADATA_INCLUDE_OWNERS)) {
+ const ObjectID waypoint_owner_id = ObjectID(navigation_path_owners[navigation_path_index]);
+
+ // Get a reference to the owning object.
+ Object *owner = nullptr;
+ if (waypoint_owner_id.is_valid()) {
+ owner = ObjectDB::get_instance(waypoint_owner_id);
+ }
+
+ details[SNAME("owner")] = owner;
+ }
+
+ // Emit a signal for the waypoint
+ emit_signal(SNAME("waypoint_reached"), details);
+
+ // Emit a signal if we've reached a navigation link
+ if (waypoint_type == NavigationPathQueryResult2D::PATH_SEGMENT_TYPE_LINK) {
+ emit_signal(SNAME("link_reached"), details);
+ }
+
+ // Move to the next waypoint on the list
+ navigation_path_index += 1;
+
+ // Check to see if we've finished our route
+ if (navigation_path_index == navigation_path.size()) {
_check_distance_to_target();
- nav_path_index -= 1;
+ navigation_path_index -= 1;
navigation_finished = true;
+ target_position_submitted = false;
emit_signal(SNAME("navigation_finished"));
break;
}
diff --git a/scene/2d/navigation_agent_2d.h b/scene/2d/navigation_agent_2d.h
index 5abd3c0317..439192cce7 100644
--- a/scene/2d/navigation_agent_2d.h
+++ b/scene/2d/navigation_agent_2d.h
@@ -32,10 +32,10 @@
#define NAVIGATION_AGENT_2D_H
#include "scene/main/node.h"
+#include "servers/navigation/navigation_path_query_parameters_2d.h"
+#include "servers/navigation/navigation_path_query_result_2d.h"
class Node2D;
-class NavigationPathQueryParameters2D;
-class NavigationPathQueryResult2D;
class NavigationAgent2D : public Node {
GDCLASS(NavigationAgent2D, Node);
@@ -48,6 +48,7 @@ class NavigationAgent2D : public Node {
bool avoidance_enabled = false;
uint32_t navigation_layers = 1;
+ BitField<NavigationPathQueryParameters2D::PathMetadataFlags> path_metadata_flags = NavigationPathQueryParameters2D::PathMetadataFlags::PATH_METADATA_INCLUDE_ALL;
real_t path_desired_distance = 1.0;
real_t target_desired_distance = 1.0;
@@ -60,9 +61,10 @@ class NavigationAgent2D : public Node {
real_t path_max_distance = 3.0;
Vector2 target_location;
+ bool target_position_submitted = false;
Ref<NavigationPathQueryParameters2D> navigation_query;
Ref<NavigationPathQueryResult2D> navigation_result;
- int nav_path_index = 0;
+ int navigation_path_index = 0;
bool velocity_submitted = false;
Vector2 prev_safe_velocity;
/// The submitted target velocity
@@ -95,6 +97,11 @@ public:
void set_navigation_layer_value(int p_layer_number, bool p_value);
bool get_navigation_layer_value(int p_layer_number) const;
+ void set_path_metadata_flags(BitField<NavigationPathQueryParameters2D::PathMetadataFlags> p_flags);
+ BitField<NavigationPathQueryParameters2D::PathMetadataFlags> get_path_metadata_flags() const {
+ return path_metadata_flags;
+ }
+
void set_navigation_map(RID p_navigation_map);
RID get_navigation_map() const;
@@ -141,10 +148,14 @@ public:
Vector2 get_next_location();
- const Vector<Vector2> &get_nav_path() const;
-
- int get_nav_path_index() const {
- return nav_path_index;
+ Ref<NavigationPathQueryResult2D> get_current_navigation_result() const {
+ return navigation_result;
+ }
+ const Vector<Vector2> &get_current_navigation_path() const {
+ return navigation_result->get_path();
+ }
+ int get_current_navigation_path_index() const {
+ return navigation_path_index;
}
real_t distance_to_target() const;
diff --git a/scene/2d/navigation_link_2d.cpp b/scene/2d/navigation_link_2d.cpp
index 3f7e10eaea..d639e1cc89 100644
--- a/scene/2d/navigation_link_2d.cpp
+++ b/scene/2d/navigation_link_2d.cpp
@@ -279,6 +279,8 @@ PackedStringArray NavigationLink2D::get_configuration_warnings() const {
NavigationLink2D::NavigationLink2D() {
link = NavigationServer2D::get_singleton()->link_create();
+ NavigationServer2D::get_singleton()->link_set_owner_id(link, get_instance_id());
+
set_notify_transform(true);
}
diff --git a/scene/2d/navigation_link_2d.h b/scene/2d/navigation_link_2d.h
index 2a5092216d..9d36f80dd6 100644
--- a/scene/2d/navigation_link_2d.h
+++ b/scene/2d/navigation_link_2d.h
@@ -37,11 +37,11 @@ class NavigationLink2D : public Node2D {
GDCLASS(NavigationLink2D, Node2D);
bool enabled = true;
- RID link = RID();
+ RID link;
bool bidirectional = true;
uint32_t navigation_layers = 1;
- Vector2 end_location = Vector2();
- Vector2 start_location = Vector2();
+ Vector2 end_location;
+ Vector2 start_location;
real_t enter_cost = 0.0;
real_t travel_cost = 1.0;
diff --git a/scene/2d/navigation_region_2d.cpp b/scene/2d/navigation_region_2d.cpp
index 6e8ecb13b1..675ef7c780 100644
--- a/scene/2d/navigation_region_2d.cpp
+++ b/scene/2d/navigation_region_2d.cpp
@@ -31,331 +31,10 @@
#include "navigation_region_2d.h"
#include "core/core_string_names.h"
-#include "core/math/geometry_2d.h"
-#include "core/os/mutex.h"
#include "scene/resources/world_2d.h"
#include "servers/navigation_server_2d.h"
#include "servers/navigation_server_3d.h"
-#include "thirdparty/misc/polypartition.h"
-
-#ifdef TOOLS_ENABLED
-Rect2 NavigationPolygon::_edit_get_rect() const {
- if (rect_cache_dirty) {
- item_rect = Rect2();
- bool first = true;
-
- for (int i = 0; i < outlines.size(); i++) {
- const Vector<Vector2> &outline = outlines[i];
- const int outline_size = outline.size();
- if (outline_size < 3) {
- continue;
- }
- const Vector2 *p = outline.ptr();
- for (int j = 0; j < outline_size; j++) {
- if (first) {
- item_rect = Rect2(p[j], Vector2(0, 0));
- first = false;
- } else {
- item_rect.expand_to(p[j]);
- }
- }
- }
-
- rect_cache_dirty = false;
- }
- return item_rect;
-}
-
-bool NavigationPolygon::_edit_is_selected_on_click(const Point2 &p_point, double p_tolerance) const {
- for (int i = 0; i < outlines.size(); i++) {
- const Vector<Vector2> &outline = outlines[i];
- const int outline_size = outline.size();
- if (outline_size < 3) {
- continue;
- }
- if (Geometry2D::is_point_in_polygon(p_point, Variant(outline))) {
- return true;
- }
- }
- return false;
-}
-#endif
-
-void NavigationPolygon::set_vertices(const Vector<Vector2> &p_vertices) {
- {
- MutexLock lock(navmesh_generation);
- navmesh.unref();
- }
- vertices = p_vertices;
- rect_cache_dirty = true;
-}
-
-Vector<Vector2> NavigationPolygon::get_vertices() const {
- return vertices;
-}
-
-void NavigationPolygon::_set_polygons(const TypedArray<Vector<int32_t>> &p_array) {
- {
- MutexLock lock(navmesh_generation);
- navmesh.unref();
- }
- polygons.resize(p_array.size());
- for (int i = 0; i < p_array.size(); i++) {
- polygons.write[i].indices = p_array[i];
- }
-}
-
-TypedArray<Vector<int32_t>> NavigationPolygon::_get_polygons() const {
- TypedArray<Vector<int32_t>> ret;
- ret.resize(polygons.size());
- for (int i = 0; i < ret.size(); i++) {
- ret[i] = polygons[i].indices;
- }
-
- return ret;
-}
-
-void NavigationPolygon::_set_outlines(const TypedArray<Vector<Vector2>> &p_array) {
- outlines.resize(p_array.size());
- for (int i = 0; i < p_array.size(); i++) {
- outlines.write[i] = p_array[i];
- }
- rect_cache_dirty = true;
-}
-
-TypedArray<Vector<Vector2>> NavigationPolygon::_get_outlines() const {
- TypedArray<Vector<Vector2>> ret;
- ret.resize(outlines.size());
- for (int i = 0; i < ret.size(); i++) {
- ret[i] = outlines[i];
- }
-
- return ret;
-}
-
-void NavigationPolygon::add_polygon(const Vector<int> &p_polygon) {
- Polygon polygon;
- polygon.indices = p_polygon;
- polygons.push_back(polygon);
- {
- MutexLock lock(navmesh_generation);
- navmesh.unref();
- }
-}
-
-void NavigationPolygon::add_outline_at_index(const Vector<Vector2> &p_outline, int p_index) {
- outlines.insert(p_index, p_outline);
- rect_cache_dirty = true;
-}
-
-int NavigationPolygon::get_polygon_count() const {
- return polygons.size();
-}
-
-Vector<int> NavigationPolygon::get_polygon(int p_idx) {
- ERR_FAIL_INDEX_V(p_idx, polygons.size(), Vector<int>());
- return polygons[p_idx].indices;
-}
-
-void NavigationPolygon::clear_polygons() {
- polygons.clear();
- {
- MutexLock lock(navmesh_generation);
- navmesh.unref();
- }
-}
-
-Ref<NavigationMesh> NavigationPolygon::get_mesh() {
- MutexLock lock(navmesh_generation);
-
- if (navmesh.is_null()) {
- navmesh.instantiate();
- Vector<Vector3> verts;
- {
- verts.resize(get_vertices().size());
- Vector3 *w = verts.ptrw();
-
- const Vector2 *r = get_vertices().ptr();
-
- for (int i(0); i < get_vertices().size(); i++) {
- w[i] = Vector3(r[i].x, 0.0, r[i].y);
- }
- }
- navmesh->set_vertices(verts);
-
- for (int i(0); i < get_polygon_count(); i++) {
- navmesh->add_polygon(get_polygon(i));
- }
- }
-
- return navmesh;
-}
-
-void NavigationPolygon::add_outline(const Vector<Vector2> &p_outline) {
- outlines.push_back(p_outline);
- rect_cache_dirty = true;
-}
-
-int NavigationPolygon::get_outline_count() const {
- return outlines.size();
-}
-
-void NavigationPolygon::set_outline(int p_idx, const Vector<Vector2> &p_outline) {
- ERR_FAIL_INDEX(p_idx, outlines.size());
- outlines.write[p_idx] = p_outline;
- rect_cache_dirty = true;
-}
-
-void NavigationPolygon::remove_outline(int p_idx) {
- ERR_FAIL_INDEX(p_idx, outlines.size());
- outlines.remove_at(p_idx);
- rect_cache_dirty = true;
-}
-
-Vector<Vector2> NavigationPolygon::get_outline(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx, outlines.size(), Vector<Vector2>());
- return outlines[p_idx];
-}
-
-void NavigationPolygon::clear_outlines() {
- outlines.clear();
- rect_cache_dirty = true;
-}
-
-void NavigationPolygon::make_polygons_from_outlines() {
- {
- MutexLock lock(navmesh_generation);
- navmesh.unref();
- }
- List<TPPLPoly> in_poly, out_poly;
-
- Vector2 outside_point(-1e10, -1e10);
-
- for (int i = 0; i < outlines.size(); i++) {
- Vector<Vector2> ol = outlines[i];
- int olsize = ol.size();
- if (olsize < 3) {
- continue;
- }
- const Vector2 *r = ol.ptr();
- for (int j = 0; j < olsize; j++) {
- outside_point.x = MAX(r[j].x, outside_point.x);
- outside_point.y = MAX(r[j].y, outside_point.y);
- }
- }
-
- outside_point += Vector2(0.7239784, 0.819238); //avoid precision issues
-
- for (int i = 0; i < outlines.size(); i++) {
- Vector<Vector2> ol = outlines[i];
- int olsize = ol.size();
- if (olsize < 3) {
- continue;
- }
- const Vector2 *r = ol.ptr();
-
- int interscount = 0;
- //test if this is an outer outline
- for (int k = 0; k < outlines.size(); k++) {
- if (i == k) {
- continue; //no self intersect
- }
-
- Vector<Vector2> ol2 = outlines[k];
- int olsize2 = ol2.size();
- if (olsize2 < 3) {
- continue;
- }
- const Vector2 *r2 = ol2.ptr();
-
- for (int l = 0; l < olsize2; l++) {
- if (Geometry2D::segment_intersects_segment(r[0], outside_point, r2[l], r2[(l + 1) % olsize2], nullptr)) {
- interscount++;
- }
- }
- }
-
- bool outer = (interscount % 2) == 0;
-
- TPPLPoly tp;
- tp.Init(olsize);
- for (int j = 0; j < olsize; j++) {
- tp[j] = r[j];
- }
-
- if (outer) {
- tp.SetOrientation(TPPL_ORIENTATION_CCW);
- } else {
- tp.SetOrientation(TPPL_ORIENTATION_CW);
- tp.SetHole(true);
- }
-
- in_poly.push_back(tp);
- }
-
- TPPLPartition tpart;
- if (tpart.ConvexPartition_HM(&in_poly, &out_poly) == 0) { //failed!
- ERR_PRINT("NavigationPolygon: Convex partition failed!");
- return;
- }
-
- polygons.clear();
- vertices.clear();
-
- HashMap<Vector2, int> points;
- for (List<TPPLPoly>::Element *I = out_poly.front(); I; I = I->next()) {
- TPPLPoly &tp = I->get();
-
- struct Polygon p;
-
- for (int64_t i = 0; i < tp.GetNumPoints(); i++) {
- HashMap<Vector2, int>::Iterator E = points.find(tp[i]);
- if (!E) {
- E = points.insert(tp[i], vertices.size());
- vertices.push_back(tp[i]);
- }
- p.indices.push_back(E->value);
- }
-
- polygons.push_back(p);
- }
-
- emit_signal(CoreStringNames::get_singleton()->changed);
-}
-
-void NavigationPolygon::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_vertices", "vertices"), &NavigationPolygon::set_vertices);
- ClassDB::bind_method(D_METHOD("get_vertices"), &NavigationPolygon::get_vertices);
-
- ClassDB::bind_method(D_METHOD("add_polygon", "polygon"), &NavigationPolygon::add_polygon);
- ClassDB::bind_method(D_METHOD("get_polygon_count"), &NavigationPolygon::get_polygon_count);
- ClassDB::bind_method(D_METHOD("get_polygon", "idx"), &NavigationPolygon::get_polygon);
- ClassDB::bind_method(D_METHOD("clear_polygons"), &NavigationPolygon::clear_polygons);
- ClassDB::bind_method(D_METHOD("get_mesh"), &NavigationPolygon::get_mesh);
-
- ClassDB::bind_method(D_METHOD("add_outline", "outline"), &NavigationPolygon::add_outline);
- ClassDB::bind_method(D_METHOD("add_outline_at_index", "outline", "index"), &NavigationPolygon::add_outline_at_index);
- ClassDB::bind_method(D_METHOD("get_outline_count"), &NavigationPolygon::get_outline_count);
- ClassDB::bind_method(D_METHOD("set_outline", "idx", "outline"), &NavigationPolygon::set_outline);
- ClassDB::bind_method(D_METHOD("get_outline", "idx"), &NavigationPolygon::get_outline);
- ClassDB::bind_method(D_METHOD("remove_outline", "idx"), &NavigationPolygon::remove_outline);
- ClassDB::bind_method(D_METHOD("clear_outlines"), &NavigationPolygon::clear_outlines);
- ClassDB::bind_method(D_METHOD("make_polygons_from_outlines"), &NavigationPolygon::make_polygons_from_outlines);
-
- ClassDB::bind_method(D_METHOD("_set_polygons", "polygons"), &NavigationPolygon::_set_polygons);
- ClassDB::bind_method(D_METHOD("_get_polygons"), &NavigationPolygon::_get_polygons);
-
- ClassDB::bind_method(D_METHOD("_set_outlines", "outlines"), &NavigationPolygon::_set_outlines);
- ClassDB::bind_method(D_METHOD("_get_outlines"), &NavigationPolygon::_get_outlines);
-
- ADD_PROPERTY(PropertyInfo(Variant::PACKED_VECTOR2_ARRAY, "vertices", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL), "set_vertices", "get_vertices");
- ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "polygons", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL), "_set_polygons", "_get_polygons");
- ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "outlines", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL), "_set_outlines", "_get_outlines");
-}
-
-/////////////////////////////
-
void NavigationRegion2D::set_enabled(bool p_enabled) {
if (enabled == p_enabled) {
return;
@@ -458,11 +137,11 @@ RID NavigationRegion2D::get_region_rid() const {
#ifdef TOOLS_ENABLED
Rect2 NavigationRegion2D::_edit_get_rect() const {
- return navpoly.is_valid() ? navpoly->_edit_get_rect() : Rect2();
+ return navigation_polygon.is_valid() ? navigation_polygon->_edit_get_rect() : Rect2();
}
bool NavigationRegion2D::_edit_is_selected_on_click(const Point2 &p_point, double p_tolerance) const {
- return navpoly.is_valid() ? navpoly->_edit_is_selected_on_click(p_point, p_tolerance) : false;
+ return navigation_polygon.is_valid() ? navigation_polygon->_edit_is_selected_on_click(p_point, p_tolerance) : false;
}
#endif
@@ -488,8 +167,8 @@ void NavigationRegion2D::_notification(int p_what) {
case NOTIFICATION_DRAW: {
#ifdef DEBUG_ENABLED
- if (is_inside_tree() && (Engine::get_singleton()->is_editor_hint() || NavigationServer3D::get_singleton()->get_debug_enabled()) && navpoly.is_valid()) {
- Vector<Vector2> verts = navpoly->get_vertices();
+ if (is_inside_tree() && (Engine::get_singleton()->is_editor_hint() || NavigationServer3D::get_singleton()->get_debug_enabled()) && navigation_polygon.is_valid()) {
+ Vector<Vector2> verts = navigation_polygon->get_vertices();
if (verts.size() < 3) {
return;
}
@@ -504,9 +183,9 @@ void NavigationRegion2D::_notification(int p_what) {
RandomPCG rand;
- for (int i = 0; i < navpoly->get_polygon_count(); i++) {
+ for (int i = 0; i < navigation_polygon->get_polygon_count(); i++) {
// An array of vertices for this polygon.
- Vector<int> polygon = navpoly->get_polygon(i);
+ Vector<int> polygon = navigation_polygon->get_polygon(i);
Vector<Vector2> vertices;
vertices.resize(polygon.size());
for (int j = 0; j < polygon.size(); j++) {
@@ -547,36 +226,36 @@ void NavigationRegion2D::_notification(int p_what) {
}
}
-void NavigationRegion2D::set_navigation_polygon(const Ref<NavigationPolygon> &p_navpoly) {
- if (p_navpoly == navpoly) {
+void NavigationRegion2D::set_navigation_polygon(const Ref<NavigationPolygon> &p_navigation_polygon) {
+ if (p_navigation_polygon == navigation_polygon) {
return;
}
- if (navpoly.is_valid()) {
- navpoly->disconnect(CoreStringNames::get_singleton()->changed, callable_mp(this, &NavigationRegion2D::_navpoly_changed));
+ if (navigation_polygon.is_valid()) {
+ navigation_polygon->disconnect(CoreStringNames::get_singleton()->changed, callable_mp(this, &NavigationRegion2D::_navigation_polygon_changed));
}
- navpoly = p_navpoly;
- NavigationServer2D::get_singleton()->region_set_navpoly(region, p_navpoly);
+ navigation_polygon = p_navigation_polygon;
+ NavigationServer2D::get_singleton()->region_set_navigation_polygon(region, p_navigation_polygon);
- if (navpoly.is_valid()) {
- navpoly->connect(CoreStringNames::get_singleton()->changed, callable_mp(this, &NavigationRegion2D::_navpoly_changed));
+ if (navigation_polygon.is_valid()) {
+ navigation_polygon->connect(CoreStringNames::get_singleton()->changed, callable_mp(this, &NavigationRegion2D::_navigation_polygon_changed));
}
- _navpoly_changed();
+ _navigation_polygon_changed();
update_configuration_warnings();
}
Ref<NavigationPolygon> NavigationRegion2D::get_navigation_polygon() const {
- return navpoly;
+ return navigation_polygon;
}
-void NavigationRegion2D::_navpoly_changed() {
+void NavigationRegion2D::_navigation_polygon_changed() {
if (is_inside_tree() && (Engine::get_singleton()->is_editor_hint() || get_tree()->is_debugging_navigation_hint())) {
queue_redraw();
}
- if (navpoly.is_valid()) {
- NavigationServer2D::get_singleton()->region_set_navpoly(region, navpoly);
+ if (navigation_polygon.is_valid()) {
+ NavigationServer2D::get_singleton()->region_set_navigation_polygon(region, navigation_polygon);
}
}
@@ -592,7 +271,7 @@ PackedStringArray NavigationRegion2D::get_configuration_warnings() const {
PackedStringArray warnings = Node2D::get_configuration_warnings();
if (is_visible_in_tree() && is_inside_tree()) {
- if (!navpoly.is_valid()) {
+ if (!navigation_polygon.is_valid()) {
warnings.push_back(RTR("A NavigationMesh resource must be set or created for this node to work. Please set a property or draw a polygon."));
}
}
@@ -601,7 +280,7 @@ PackedStringArray NavigationRegion2D::get_configuration_warnings() const {
}
void NavigationRegion2D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_navigation_polygon", "navpoly"), &NavigationRegion2D::set_navigation_polygon);
+ ClassDB::bind_method(D_METHOD("set_navigation_polygon", "navigation_polygon"), &NavigationRegion2D::set_navigation_polygon);
ClassDB::bind_method(D_METHOD("get_navigation_polygon"), &NavigationRegion2D::get_navigation_polygon);
ClassDB::bind_method(D_METHOD("set_enabled", "enabled"), &NavigationRegion2D::set_enabled);
@@ -621,18 +300,39 @@ void NavigationRegion2D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_travel_cost", "travel_cost"), &NavigationRegion2D::set_travel_cost);
ClassDB::bind_method(D_METHOD("get_travel_cost"), &NavigationRegion2D::get_travel_cost);
- ClassDB::bind_method(D_METHOD("_navpoly_changed"), &NavigationRegion2D::_navpoly_changed);
+ ClassDB::bind_method(D_METHOD("_navigation_polygon_changed"), &NavigationRegion2D::_navigation_polygon_changed);
- ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "navpoly", PROPERTY_HINT_RESOURCE_TYPE, "NavigationPolygon"), "set_navigation_polygon", "get_navigation_polygon");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "navigation_polygon", PROPERTY_HINT_RESOURCE_TYPE, "NavigationPolygon"), "set_navigation_polygon", "get_navigation_polygon");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "enabled"), "set_enabled", "is_enabled");
ADD_PROPERTY(PropertyInfo(Variant::INT, "navigation_layers", PROPERTY_HINT_LAYERS_2D_NAVIGATION), "set_navigation_layers", "get_navigation_layers");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "enter_cost"), "set_enter_cost", "get_enter_cost");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "travel_cost"), "set_travel_cost", "get_travel_cost");
}
+#ifndef DISABLE_DEPRECATED
+// Compatibility with earlier 4.0 betas.
+bool NavigationRegion2D::_set(const StringName &p_name, const Variant &p_value) {
+ if (p_name == "navpoly") {
+ set_navigation_polygon(p_value);
+ return true;
+ }
+ return false;
+}
+
+bool NavigationRegion2D::_get(const StringName &p_name, Variant &r_ret) const {
+ if (p_name == "navpoly") {
+ r_ret = get_navigation_polygon();
+ return true;
+ }
+ return false;
+}
+#endif // DISABLE_DEPRECATED
+
NavigationRegion2D::NavigationRegion2D() {
set_notify_transform(true);
+
region = NavigationServer2D::get_singleton()->region_create();
+ NavigationServer2D::get_singleton()->region_set_owner_id(region, get_instance_id());
NavigationServer2D::get_singleton()->region_set_enter_cost(region, get_enter_cost());
NavigationServer2D::get_singleton()->region_set_travel_cost(region, get_travel_cost());
diff --git a/scene/2d/navigation_region_2d.h b/scene/2d/navigation_region_2d.h
index c630e20780..45029fd95f 100644
--- a/scene/2d/navigation_region_2d.h
+++ b/scene/2d/navigation_region_2d.h
@@ -31,65 +31,7 @@
#ifndef NAVIGATION_REGION_2D_H
#define NAVIGATION_REGION_2D_H
-#include "scene/2d/node_2d.h"
-#include "scene/resources/navigation_mesh.h"
-
-class NavigationPolygon : public Resource {
- GDCLASS(NavigationPolygon, Resource);
-
- Vector<Vector2> vertices;
- struct Polygon {
- Vector<int> indices;
- };
- Vector<Polygon> polygons;
- Vector<Vector<Vector2>> outlines;
-
- mutable Rect2 item_rect;
- mutable bool rect_cache_dirty = true;
-
- Mutex navmesh_generation;
- // Navigation mesh
- Ref<NavigationMesh> navmesh;
-
-protected:
- static void _bind_methods();
-
- void _set_polygons(const TypedArray<Vector<int32_t>> &p_array);
- TypedArray<Vector<int32_t>> _get_polygons() const;
-
- void _set_outlines(const TypedArray<Vector<Vector2>> &p_array);
- TypedArray<Vector<Vector2>> _get_outlines() const;
-
-public:
-#ifdef TOOLS_ENABLED
- Rect2 _edit_get_rect() const;
- bool _edit_is_selected_on_click(const Point2 &p_point, double p_tolerance) const;
-#endif
-
- void set_vertices(const Vector<Vector2> &p_vertices);
- Vector<Vector2> get_vertices() const;
-
- void add_polygon(const Vector<int> &p_polygon);
- int get_polygon_count() const;
-
- void add_outline(const Vector<Vector2> &p_outline);
- void add_outline_at_index(const Vector<Vector2> &p_outline, int p_index);
- void set_outline(int p_idx, const Vector<Vector2> &p_outline);
- Vector<Vector2> get_outline(int p_idx) const;
- void remove_outline(int p_idx);
- int get_outline_count() const;
-
- void clear_outlines();
- void make_polygons_from_outlines();
-
- Vector<int> get_polygon(int p_idx);
- void clear_polygons();
-
- Ref<NavigationMesh> get_mesh();
-
- NavigationPolygon() {}
- ~NavigationPolygon() {}
-};
+#include "scene/resources/navigation_polygon.h"
class NavigationRegion2D : public Node2D {
GDCLASS(NavigationRegion2D, Node2D);
@@ -99,15 +41,20 @@ class NavigationRegion2D : public Node2D {
uint32_t navigation_layers = 1;
real_t enter_cost = 0.0;
real_t travel_cost = 1.0;
- Ref<NavigationPolygon> navpoly;
+ Ref<NavigationPolygon> navigation_polygon;
- void _navpoly_changed();
+ void _navigation_polygon_changed();
void _map_changed(RID p_RID);
protected:
void _notification(int p_what);
static void _bind_methods();
+#ifndef DISABLE_DEPRECATED
+ bool _set(const StringName &p_name, const Variant &p_value);
+ bool _get(const StringName &p_name, Variant &r_ret) const;
+#endif // DISABLE_DEPRECATED
+
public:
#ifdef TOOLS_ENABLED
virtual Rect2 _edit_get_rect() const override;
@@ -131,7 +78,7 @@ public:
void set_travel_cost(real_t p_travel_cost);
real_t get_travel_cost() const;
- void set_navigation_polygon(const Ref<NavigationPolygon> &p_navpoly);
+ void set_navigation_polygon(const Ref<NavigationPolygon> &p_navigation_polygon);
Ref<NavigationPolygon> get_navigation_polygon() const;
PackedStringArray get_configuration_warnings() const override;
diff --git a/scene/2d/node_2d.cpp b/scene/2d/node_2d.cpp
index 2518069b78..166bc26848 100644
--- a/scene/2d/node_2d.cpp
+++ b/scene/2d/node_2d.cpp
@@ -30,6 +30,8 @@
#include "node_2d.h"
+#include "scene/main/viewport.h"
+
#ifdef TOOLS_ENABLED
Dictionary Node2D::_edit_get_state() const {
Dictionary state;
@@ -147,6 +149,10 @@ void Node2D::set_rotation(real_t p_radians) {
_update_transform();
}
+void Node2D::set_rotation_degrees(real_t p_degrees) {
+ set_rotation(Math::deg_to_rad(p_degrees));
+}
+
void Node2D::set_skew(real_t p_radians) {
if (_xform_dirty) {
const_cast<Node2D *>(this)->_update_xform_values();
@@ -185,6 +191,10 @@ real_t Node2D::get_rotation() const {
return rotation;
}
+real_t Node2D::get_rotation_degrees() const {
+ return Math::rad_to_deg(get_rotation());
+}
+
real_t Node2D::get_skew() const {
if (_xform_dirty) {
const_cast<Node2D *>(this)->_update_xform_values();
@@ -257,6 +267,10 @@ real_t Node2D::get_global_rotation() const {
return get_global_transform().get_rotation();
}
+real_t Node2D::get_global_rotation_degrees() const {
+ return Math::rad_to_deg(get_global_rotation());
+}
+
real_t Node2D::get_global_skew() const {
return get_global_transform().get_skew();
}
@@ -274,6 +288,10 @@ void Node2D::set_global_rotation(const real_t p_radians) {
}
}
+void Node2D::set_global_rotation_degrees(const real_t p_degrees) {
+ set_global_rotation(Math::deg_to_rad(p_degrees));
+}
+
void Node2D::set_global_skew(const real_t p_radians) {
CanvasItem *parent = get_parent_item();
if (parent) {
@@ -326,29 +344,6 @@ void Node2D::set_global_transform(const Transform2D &p_transform) {
}
}
-void Node2D::set_z_index(int p_z) {
- ERR_FAIL_COND(p_z < RS::CANVAS_ITEM_Z_MIN);
- ERR_FAIL_COND(p_z > RS::CANVAS_ITEM_Z_MAX);
- z_index = p_z;
- RS::get_singleton()->canvas_item_set_z_index(get_canvas_item(), z_index);
-}
-
-void Node2D::set_z_as_relative(bool p_enabled) {
- if (z_relative == p_enabled) {
- return;
- }
- z_relative = p_enabled;
- RS::get_singleton()->canvas_item_set_z_as_relative_to_parent(get_canvas_item(), p_enabled);
-}
-
-bool Node2D::is_z_relative() const {
- return z_relative;
-}
-
-int Node2D::get_z_index() const {
- return z_index;
-}
-
Transform2D Node2D::get_relative_transform_to_parent(const Node *p_parent) const {
if (p_parent == this) {
return Transform2D();
@@ -380,23 +375,26 @@ Point2 Node2D::to_global(Point2 p_local) const {
return get_global_transform().xform(p_local);
}
-void Node2D::set_y_sort_enabled(bool p_enabled) {
- y_sort_enabled = p_enabled;
- RS::get_singleton()->canvas_item_set_sort_children_by_y(get_canvas_item(), y_sort_enabled);
-}
-
-bool Node2D::is_y_sort_enabled() const {
- return y_sort_enabled;
+void Node2D::_notification(int p_notification) {
+ switch (p_notification) {
+ case NOTIFICATION_MOVED_IN_PARENT: {
+ if (get_viewport()) {
+ get_viewport()->gui_set_root_order_dirty();
+ }
+ } break;
+ }
}
void Node2D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_position", "position"), &Node2D::set_position);
ClassDB::bind_method(D_METHOD("set_rotation", "radians"), &Node2D::set_rotation);
+ ClassDB::bind_method(D_METHOD("set_rotation_degrees", "degrees"), &Node2D::set_rotation_degrees);
ClassDB::bind_method(D_METHOD("set_skew", "radians"), &Node2D::set_skew);
ClassDB::bind_method(D_METHOD("set_scale", "scale"), &Node2D::set_scale);
ClassDB::bind_method(D_METHOD("get_position"), &Node2D::get_position);
ClassDB::bind_method(D_METHOD("get_rotation"), &Node2D::get_rotation);
+ ClassDB::bind_method(D_METHOD("get_rotation_degrees"), &Node2D::get_rotation_degrees);
ClassDB::bind_method(D_METHOD("get_skew"), &Node2D::get_skew);
ClassDB::bind_method(D_METHOD("get_scale"), &Node2D::get_scale);
@@ -410,7 +408,9 @@ void Node2D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_global_position", "position"), &Node2D::set_global_position);
ClassDB::bind_method(D_METHOD("get_global_position"), &Node2D::get_global_position);
ClassDB::bind_method(D_METHOD("set_global_rotation", "radians"), &Node2D::set_global_rotation);
+ ClassDB::bind_method(D_METHOD("set_global_rotation_degrees", "degrees"), &Node2D::set_global_rotation_degrees);
ClassDB::bind_method(D_METHOD("get_global_rotation"), &Node2D::get_global_rotation);
+ ClassDB::bind_method(D_METHOD("get_global_rotation_degrees"), &Node2D::get_global_rotation_degrees);
ClassDB::bind_method(D_METHOD("set_global_skew", "radians"), &Node2D::set_global_skew);
ClassDB::bind_method(D_METHOD("get_global_skew"), &Node2D::get_global_skew);
ClassDB::bind_method(D_METHOD("set_global_scale", "scale"), &Node2D::set_global_scale);
@@ -425,32 +425,20 @@ void Node2D::_bind_methods() {
ClassDB::bind_method(D_METHOD("to_local", "global_point"), &Node2D::to_local);
ClassDB::bind_method(D_METHOD("to_global", "local_point"), &Node2D::to_global);
- ClassDB::bind_method(D_METHOD("set_z_index", "z_index"), &Node2D::set_z_index);
- ClassDB::bind_method(D_METHOD("get_z_index"), &Node2D::get_z_index);
-
- ClassDB::bind_method(D_METHOD("set_z_as_relative", "enable"), &Node2D::set_z_as_relative);
- ClassDB::bind_method(D_METHOD("is_z_relative"), &Node2D::is_z_relative);
-
- ClassDB::bind_method(D_METHOD("set_y_sort_enabled", "enabled"), &Node2D::set_y_sort_enabled);
- ClassDB::bind_method(D_METHOD("is_y_sort_enabled"), &Node2D::is_y_sort_enabled);
-
ClassDB::bind_method(D_METHOD("get_relative_transform_to_parent", "parent"), &Node2D::get_relative_transform_to_parent);
ADD_GROUP("Transform", "");
ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "position", PROPERTY_HINT_RANGE, "-99999,99999,0.001,or_less,or_greater,hide_slider,suffix:px"), "set_position", "get_position");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "rotation", PROPERTY_HINT_RANGE, "-360,360,0.1,or_less,or_greater,radians"), "set_rotation", "get_rotation");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "rotation_degrees", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NONE), "set_rotation_degrees", "get_rotation_degrees");
ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "scale", PROPERTY_HINT_LINK), "set_scale", "get_scale");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "skew", PROPERTY_HINT_RANGE, "-89.9,89.9,0.1,radians"), "set_skew", "get_skew");
ADD_PROPERTY(PropertyInfo(Variant::TRANSFORM2D, "transform", PROPERTY_HINT_NONE, "suffix:px", PROPERTY_USAGE_NONE), "set_transform", "get_transform");
ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "global_position", PROPERTY_HINT_NONE, "suffix:px", PROPERTY_USAGE_NONE), "set_global_position", "get_global_position");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "global_rotation", PROPERTY_HINT_NONE, "radians", PROPERTY_USAGE_NONE), "set_global_rotation", "get_global_rotation");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "global_rotation_degrees", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NONE), "set_global_rotation_degrees", "get_global_rotation_degrees");
ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "global_scale", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NONE), "set_global_scale", "get_global_scale");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "global_skew", PROPERTY_HINT_NONE, "radians", PROPERTY_USAGE_NONE), "set_global_skew", "get_global_skew");
ADD_PROPERTY(PropertyInfo(Variant::TRANSFORM2D, "global_transform", PROPERTY_HINT_NONE, "suffix:px", PROPERTY_USAGE_NONE), "set_global_transform", "get_global_transform");
-
- ADD_GROUP("Ordering", "");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "z_index", PROPERTY_HINT_RANGE, itos(RS::CANVAS_ITEM_Z_MIN) + "," + itos(RS::CANVAS_ITEM_Z_MAX) + ",1"), "set_z_index", "get_z_index");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL, "z_as_relative"), "set_z_as_relative", "is_z_relative");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL, "y_sort_enabled"), "set_y_sort_enabled", "is_y_sort_enabled");
}
diff --git a/scene/2d/node_2d.h b/scene/2d/node_2d.h
index 0d8a31e6bb..b066332dcb 100644
--- a/scene/2d/node_2d.h
+++ b/scene/2d/node_2d.h
@@ -40,9 +40,6 @@ class Node2D : public CanvasItem {
real_t rotation = 0.0;
Size2 scale = Vector2(1, 1);
real_t skew = 0.0;
- int z_index = 0;
- bool z_relative = true;
- bool y_sort_enabled = false;
Transform2D transform;
@@ -53,6 +50,7 @@ class Node2D : public CanvasItem {
void _update_xform_values();
protected:
+ void _notification(int p_notification);
static void _bind_methods();
public:
@@ -75,6 +73,7 @@ public:
void set_position(const Point2 &p_pos);
void set_rotation(real_t p_radians);
+ void set_rotation_degrees(real_t p_degrees);
void set_skew(real_t p_radians);
void set_scale(const Size2 &p_scale);
@@ -87,11 +86,13 @@ public:
Point2 get_position() const;
real_t get_rotation() const;
+ real_t get_rotation_degrees() const;
real_t get_skew() const;
Size2 get_scale() const;
Point2 get_global_position() const;
real_t get_global_rotation() const;
+ real_t get_global_rotation_degrees() const;
real_t get_global_skew() const;
Size2 get_global_scale() const;
@@ -99,24 +100,16 @@ public:
void set_global_transform(const Transform2D &p_transform);
void set_global_position(const Point2 &p_pos);
void set_global_rotation(const real_t p_radians);
+ void set_global_rotation_degrees(const real_t p_degrees);
void set_global_skew(const real_t p_radians);
void set_global_scale(const Size2 &p_scale);
- void set_z_index(int p_z);
- int get_z_index() const;
-
void look_at(const Vector2 &p_pos);
real_t get_angle_to(const Vector2 &p_pos) const;
Point2 to_local(Point2 p_global) const;
Point2 to_global(Point2 p_local) const;
- void set_z_as_relative(bool p_enabled);
- bool is_z_relative() const;
-
- virtual void set_y_sort_enabled(bool p_enabled);
- virtual bool is_y_sort_enabled() const;
-
Transform2D get_relative_transform_to_parent(const Node *p_parent) const;
Transform2D get_transform() const override;
diff --git a/scene/2d/path_2d.cpp b/scene/2d/path_2d.cpp
index b5945a4562..823b8d56e3 100644
--- a/scene/2d/path_2d.cpp
+++ b/scene/2d/path_2d.cpp
@@ -106,18 +106,57 @@ void Path2D::_notification(int p_what) {
#else
const real_t line_width = get_tree()->get_debug_paths_width();
#endif
- _cached_draw_pts.resize(curve->get_point_count() * 8);
- int count = 0;
-
- for (int i = 0; i < curve->get_point_count(); i++) {
- for (int j = 0; j < 8; j++) {
- real_t frac = j * (1.0 / 8.0);
- Vector2 p = curve->sample(i, frac);
- _cached_draw_pts.set(count++, p);
+ real_t interval = 10;
+ const real_t length = curve->get_baked_length();
+
+ if (length > CMP_EPSILON) {
+ const int sample_count = int(length / interval) + 2;
+ interval = length / (sample_count - 1); // Recalculate real interval length.
+
+ Vector<Transform2D> frames;
+ frames.resize(sample_count);
+
+ {
+ Transform2D *w = frames.ptrw();
+
+ for (int i = 0; i < sample_count; i++) {
+ w[i] = curve->sample_baked_with_rotation(i * interval, false);
+ }
}
- }
- draw_polyline(_cached_draw_pts, get_tree()->get_debug_paths_color(), line_width, true);
+ const Transform2D *r = frames.ptr();
+ // Draw curve segments
+ {
+ PackedVector2Array v2p;
+ v2p.resize(sample_count);
+ Vector2 *w = v2p.ptrw();
+
+ for (int i = 0; i < sample_count; i++) {
+ w[i] = r[i].get_origin();
+ }
+ draw_polyline(v2p, get_tree()->get_debug_paths_color(), line_width, false);
+ }
+
+ // Draw fish bones
+ {
+ PackedVector2Array v2p;
+ v2p.resize(3);
+ Vector2 *w = v2p.ptrw();
+
+ for (int i = 0; i < sample_count; i++) {
+ const Vector2 p = r[i].get_origin();
+ const Vector2 side = r[i].columns[0];
+ const Vector2 forward = r[i].columns[1];
+
+ // Fish Bone.
+ w[0] = p + (side - forward) * 5;
+ w[1] = p;
+ w[2] = p + (-side - forward) * 5;
+
+ draw_polyline(v2p, get_tree()->get_debug_paths_color(), line_width * 0.5, false);
+ }
+ }
+ }
} break;
}
}
@@ -177,7 +216,7 @@ void PathFollow2D::_update_transform() {
}
if (rotates) {
- Transform2D xform = c->sample_baked_with_rotation(progress, cubic, loop, lookahead);
+ Transform2D xform = c->sample_baked_with_rotation(progress, cubic);
xform.translate_local(v_offset, h_offset);
set_rotation(xform[1].angle());
set_position(xform[2]);
diff --git a/scene/2d/path_2d.h b/scene/2d/path_2d.h
index 5e436fb9f6..935717605a 100644
--- a/scene/2d/path_2d.h
+++ b/scene/2d/path_2d.h
@@ -38,7 +38,6 @@ class Path2D : public Node2D {
GDCLASS(Path2D, Node2D);
Ref<Curve2D> curve;
- Vector<Vector2> _cached_draw_pts;
void _curve_changed();
diff --git a/scene/2d/physics_body_2d.cpp b/scene/2d/physics_body_2d.cpp
index 0f3e6c7529..7f5b5d1ea4 100644
--- a/scene/2d/physics_body_2d.cpp
+++ b/scene/2d/physics_body_2d.cpp
@@ -34,8 +34,8 @@
#include "scene/scene_string_names.h"
void PhysicsBody2D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("move_and_collide", "distance", "test_only", "safe_margin", "recovery_as_collision"), &PhysicsBody2D::_move, DEFVAL(false), DEFVAL(0.08), DEFVAL(false));
- ClassDB::bind_method(D_METHOD("test_move", "from", "distance", "collision", "safe_margin", "recovery_as_collision"), &PhysicsBody2D::test_move, DEFVAL(Variant()), DEFVAL(0.08), DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("move_and_collide", "motion", "test_only", "safe_margin", "recovery_as_collision"), &PhysicsBody2D::_move, DEFVAL(false), DEFVAL(0.08), DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("test_move", "from", "motion", "collision", "safe_margin", "recovery_as_collision"), &PhysicsBody2D::test_move, DEFVAL(Variant()), DEFVAL(0.08), DEFVAL(false));
ClassDB::bind_method(D_METHOD("get_collision_exceptions"), &PhysicsBody2D::get_collision_exceptions);
ClassDB::bind_method(D_METHOD("add_collision_exception_with", "body"), &PhysicsBody2D::add_collision_exception_with);
@@ -54,8 +54,8 @@ PhysicsBody2D::~PhysicsBody2D() {
}
}
-Ref<KinematicCollision2D> PhysicsBody2D::_move(const Vector2 &p_distance, bool p_test_only, real_t p_margin, bool p_recovery_as_collision) {
- PhysicsServer2D::MotionParameters parameters(get_global_transform(), p_distance, p_margin);
+Ref<KinematicCollision2D> PhysicsBody2D::_move(const Vector2 &p_motion, bool p_test_only, real_t p_margin, bool p_recovery_as_collision) {
+ PhysicsServer2D::MotionParameters parameters(get_global_transform(), p_motion, p_margin);
parameters.recovery_as_collision = p_recovery_as_collision;
PhysicsServer2D::MotionResult result;
@@ -128,7 +128,7 @@ bool PhysicsBody2D::move_and_collide(const PhysicsServer2D::MotionParameters &p_
return colliding;
}
-bool PhysicsBody2D::test_move(const Transform2D &p_from, const Vector2 &p_distance, const Ref<KinematicCollision2D> &r_collision, real_t p_margin, bool p_recovery_as_collision) {
+bool PhysicsBody2D::test_move(const Transform2D &p_from, const Vector2 &p_motion, const Ref<KinematicCollision2D> &r_collision, real_t p_margin, bool p_recovery_as_collision) {
ERR_FAIL_COND_V(!is_inside_tree(), false);
PhysicsServer2D::MotionResult *r = nullptr;
@@ -140,7 +140,7 @@ bool PhysicsBody2D::test_move(const Transform2D &p_from, const Vector2 &p_distan
r = &temp_result;
}
- PhysicsServer2D::MotionParameters parameters(p_from, p_distance, p_margin);
+ PhysicsServer2D::MotionParameters parameters(p_from, p_motion, p_margin);
parameters.recovery_as_collision = p_recovery_as_collision;
return PhysicsServer2D::get_singleton()->body_test_motion(get_rid(), parameters, r);
@@ -162,14 +162,14 @@ TypedArray<PhysicsBody2D> PhysicsBody2D::get_collision_exceptions() {
void PhysicsBody2D::add_collision_exception_with(Node *p_node) {
ERR_FAIL_NULL(p_node);
PhysicsBody2D *physics_body = Object::cast_to<PhysicsBody2D>(p_node);
- ERR_FAIL_COND_MSG(!physics_body, "Collision exception only works between two objects of PhysicsBody2D type.");
+ ERR_FAIL_COND_MSG(!physics_body, "Collision exception only works between two nodes that inherit from PhysicsBody2D.");
PhysicsServer2D::get_singleton()->body_add_collision_exception(get_rid(), physics_body->get_rid());
}
void PhysicsBody2D::remove_collision_exception_with(Node *p_node) {
ERR_FAIL_NULL(p_node);
PhysicsBody2D *physics_body = Object::cast_to<PhysicsBody2D>(p_node);
- ERR_FAIL_COND_MSG(!physics_body, "Collision exception only works between two objects of PhysicsBody2D type.");
+ ERR_FAIL_COND_MSG(!physics_body, "Collision exception only works between two nodes that inherit from PhysicsBody2D.");
PhysicsServer2D::get_singleton()->body_remove_collision_exception(get_rid(), physics_body->get_rid());
}
@@ -1761,7 +1761,7 @@ void CharacterBody2D::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "floor_max_angle", PROPERTY_HINT_RANGE, "0,180,0.1,radians"), "set_floor_max_angle", "get_floor_max_angle");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "floor_snap_length", PROPERTY_HINT_RANGE, "0,32,0.1,or_greater,suffix:px"), "set_floor_snap_length", "get_floor_snap_length");
- ADD_GROUP("Moving Platform", "platform");
+ ADD_GROUP("Moving Platform", "platform_");
ADD_PROPERTY(PropertyInfo(Variant::INT, "platform_on_leave", PROPERTY_HINT_ENUM, "Add Velocity,Add Upward Velocity,Do Nothing", PROPERTY_USAGE_DEFAULT), "set_platform_on_leave", "get_platform_on_leave");
ADD_PROPERTY(PropertyInfo(Variant::INT, "platform_floor_layers", PROPERTY_HINT_LAYERS_2D_PHYSICS), "set_platform_floor_layers", "get_platform_floor_layers");
ADD_PROPERTY(PropertyInfo(Variant::INT, "platform_wall_layers", PROPERTY_HINT_LAYERS_2D_PHYSICS), "set_platform_wall_layers", "get_platform_wall_layers");
diff --git a/scene/2d/physics_body_2d.h b/scene/2d/physics_body_2d.h
index 932ec1de16..504e1dc333 100644
--- a/scene/2d/physics_body_2d.h
+++ b/scene/2d/physics_body_2d.h
@@ -47,11 +47,11 @@ protected:
Ref<KinematicCollision2D> motion_cache;
- Ref<KinematicCollision2D> _move(const Vector2 &p_distance, bool p_test_only = false, real_t p_margin = 0.08, bool p_recovery_as_collision = false);
+ Ref<KinematicCollision2D> _move(const Vector2 &p_motion, bool p_test_only = false, real_t p_margin = 0.08, bool p_recovery_as_collision = false);
public:
bool move_and_collide(const PhysicsServer2D::MotionParameters &p_parameters, PhysicsServer2D::MotionResult &r_result, bool p_test_only = false, bool p_cancel_sliding = true);
- bool test_move(const Transform2D &p_from, const Vector2 &p_distance, const Ref<KinematicCollision2D> &r_collision = Ref<KinematicCollision2D>(), real_t p_margin = 0.08, bool p_recovery_as_collision = false);
+ bool test_move(const Transform2D &p_from, const Vector2 &p_motion, const Ref<KinematicCollision2D> &r_collision = Ref<KinematicCollision2D>(), real_t p_margin = 0.08, bool p_recovery_as_collision = false);
TypedArray<PhysicsBody2D> get_collision_exceptions();
void add_collision_exception_with(Node *p_node); //must be physicsbody
diff --git a/scene/2d/polygon_2d.cpp b/scene/2d/polygon_2d.cpp
index 5e77902977..e41664b006 100644
--- a/scene/2d/polygon_2d.cpp
+++ b/scene/2d/polygon_2d.cpp
@@ -114,7 +114,7 @@ void Polygon2D::_notification(int p_what) {
ObjectID new_skeleton_id;
- if (skeleton_node) {
+ if (skeleton_node && !invert && bone_weights.size()) {
RS::get_singleton()->canvas_item_attach_skeleton(get_canvas_item(), skeleton_node->get_skeleton());
new_skeleton_id = skeleton_node->get_instance_id();
} else {
@@ -663,5 +663,7 @@ Polygon2D::Polygon2D() {
}
Polygon2D::~Polygon2D() {
+ // This will free the internally-allocated mesh instance, if allocated.
+ RS::get_singleton()->canvas_item_attach_skeleton(get_canvas_item(), RID());
RS::get_singleton()->free(mesh);
}
diff --git a/scene/2d/skeleton_2d.cpp b/scene/2d/skeleton_2d.cpp
index 02d8e20ce8..62787d4488 100644
--- a/scene/2d/skeleton_2d.cpp
+++ b/scene/2d/skeleton_2d.cpp
@@ -213,7 +213,7 @@ void Bone2D::_notification(int p_what) {
}
// Undo scaling
- Transform2D editor_gizmo_trans = Transform2D();
+ Transform2D editor_gizmo_trans;
editor_gizmo_trans.set_scale(Vector2(1, 1) / get_global_scale());
RenderingServer::get_singleton()->canvas_item_set_transform(editor_gizmo_rid, editor_gizmo_trans);
diff --git a/scene/2d/tile_map.cpp b/scene/2d/tile_map.cpp
index 40e8818262..3136752a2e 100644
--- a/scene/2d/tile_map.cpp
+++ b/scene/2d/tile_map.cpp
@@ -358,7 +358,7 @@ TileMap::TerrainConstraint::TerrainConstraint(const TileMap *p_tile_map, const V
terrain = p_terrain;
}
-Vector2i TileMap::transform_coords_layout(Vector2i p_coords, TileSet::TileOffsetAxis p_offset_axis, TileSet::TileLayout p_from_layout, TileSet::TileLayout p_to_layout) {
+Vector2i TileMap::transform_coords_layout(const Vector2i &p_coords, TileSet::TileOffsetAxis p_offset_axis, TileSet::TileLayout p_from_layout, TileSet::TileLayout p_to_layout) {
// Transform to stacked layout.
Vector2i output = p_coords;
if (p_offset_axis == TileSet::TILE_OFFSET_AXIS_VERTICAL) {
@@ -755,6 +755,7 @@ void TileMap::set_y_sort_enabled(bool p_enable) {
_clear_internals();
_recreate_internals();
emit_signal(SNAME("changed"));
+ update_configuration_warnings();
}
Vector2i TileMap::_coords_to_quadrant_coords(int p_layer, const Vector2i &p_coords) const {
@@ -995,9 +996,11 @@ void TileMap::_recompute_rect_cache() {
}
}
+ bool changed = rect_cache != r_total;
+
rect_cache = r_total;
- item_rect_changed();
+ item_rect_changed(changed);
rect_cache_dirty = false;
#endif
@@ -1089,7 +1092,7 @@ void TileMap::_rendering_update_layer(int p_layer) {
/*Transform2D xform;
xform.set_origin(Vector2(0, p_layer));
rs->canvas_item_set_transform(ci, xform);*/
- rs->canvas_item_set_draw_index(ci, p_layer);
+ rs->canvas_item_set_draw_index(ci, p_layer - (int64_t)0x80000000);
layers[p_layer].canvas_item = ci;
}
@@ -1340,7 +1343,7 @@ void TileMap::_rendering_draw_quadrant_debug(TileMapQuadrant *p_quadrant) {
}
}
-void TileMap::draw_tile(RID p_canvas_item, Vector2i p_position, const Ref<TileSet> p_tile_set, int p_atlas_source_id, Vector2i p_atlas_coords, int p_alternative_tile, int p_frame, Color p_modulation, const TileData *p_tile_data_override) {
+void TileMap::draw_tile(RID p_canvas_item, const Vector2i &p_position, const Ref<TileSet> p_tile_set, int p_atlas_source_id, const Vector2i &p_atlas_coords, int p_alternative_tile, int p_frame, Color p_modulation, const TileData *p_tile_data_override) {
ERR_FAIL_COND(!p_tile_set.is_valid());
ERR_FAIL_COND(!p_tile_set->has_source(p_atlas_source_id));
ERR_FAIL_COND(!p_tile_set->get_source(p_atlas_source_id)->has_tile(p_atlas_coords));
@@ -1725,17 +1728,19 @@ void TileMap::_navigation_update_dirty_quadrants(SelfList<TileMapQuadrant>::List
q.navigation_regions[E_cell].resize(tile_set->get_navigation_layers_count());
for (int layer_index = 0; layer_index < tile_set->get_navigation_layers_count(); layer_index++) {
- Ref<NavigationPolygon> navpoly;
- navpoly = tile_data->get_navigation_polygon(layer_index);
+ Ref<NavigationPolygon> navigation_polygon;
+ navigation_polygon = tile_data->get_navigation_polygon(layer_index);
- if (navpoly.is_valid()) {
+ if (navigation_polygon.is_valid()) {
Transform2D tile_transform;
tile_transform.set_origin(map_to_local(E_cell));
RID region = NavigationServer2D::get_singleton()->region_create();
+ NavigationServer2D::get_singleton()->region_set_owner_id(region, get_instance_id());
NavigationServer2D::get_singleton()->region_set_map(region, get_world_2d()->get_navigation_map());
NavigationServer2D::get_singleton()->region_set_transform(region, tilemap_xform * tile_transform);
- NavigationServer2D::get_singleton()->region_set_navpoly(region, navpoly);
+ NavigationServer2D::get_singleton()->region_set_navigation_layers(region, tile_set->get_navigation_layer_layers(layer_index));
+ NavigationServer2D::get_singleton()->region_set_navigation_polygon(region, navigation_polygon);
q.navigation_regions[E_cell].write[layer_index] = region;
}
}
@@ -1859,11 +1864,13 @@ void TileMap::_scenes_update_dirty_quadrants(SelfList<TileMapQuadrant>::List &r_
while (q_list_element) {
TileMapQuadrant &q = *q_list_element->self();
- // Clear the scenes.
- for (const KeyValue<Vector2i, String> &E : q.scenes) {
- Node *node = get_node_or_null(E.value);
- if (node) {
- node->queue_free();
+ // Clear the scenes if instance cache was cleared.
+ if (instantiated_scenes.is_empty()) {
+ for (const KeyValue<Vector2i, String> &E : q.scenes) {
+ Node *node = get_node_or_null(E.value);
+ if (node) {
+ node->queue_free();
+ }
}
}
@@ -1871,6 +1878,15 @@ void TileMap::_scenes_update_dirty_quadrants(SelfList<TileMapQuadrant>::List &r_
// Recreate the scenes.
for (const Vector2i &E_cell : q.cells) {
+ Vector3i cell_coords = Vector3i(q.layer, E_cell.x, E_cell.y);
+ if (instantiated_scenes.has(cell_coords)) {
+ // Skip scene if the instance was cached (to avoid recreating scenes unnecessarily).
+ continue;
+ }
+ if (!Engine::get_singleton()->is_editor_hint()) {
+ instantiated_scenes.insert(cell_coords);
+ }
+
const TileMapCell &c = get_cell(q.layer, E_cell, true);
TileSetSource *source;
@@ -1907,15 +1923,16 @@ void TileMap::_scenes_update_dirty_quadrants(SelfList<TileMapQuadrant>::List &r_
}
void TileMap::_scenes_cleanup_quadrant(TileMapQuadrant *p_quadrant) {
- // Clear the scenes.
- for (const KeyValue<Vector2i, String> &E : p_quadrant->scenes) {
- Node *node = get_node_or_null(E.value);
- if (node) {
- node->queue_free();
+ // Clear the scenes if instance cache was cleared.
+ if (instantiated_scenes.is_empty()) {
+ for (const KeyValue<Vector2i, String> &E : p_quadrant->scenes) {
+ Node *node = get_node_or_null(E.value);
+ if (node) {
+ node->queue_free();
+ }
}
+ p_quadrant->scenes.clear();
}
-
- p_quadrant->scenes.clear();
}
void TileMap::_scenes_draw_quadrant_debug(TileMapQuadrant *p_quadrant) {
@@ -1980,7 +1997,6 @@ void TileMap::set_cell(int p_layer, const Vector2i &p_coords, int p_source_id, c
if ((source_id == TileSet::INVALID_SOURCE || atlas_coords == TileSetSource::INVALID_ATLAS_COORDS || alternative_tile == TileSetSource::INVALID_TILE_ALTERNATIVE) &&
(source_id != TileSet::INVALID_SOURCE || atlas_coords != TileSetSource::INVALID_ATLAS_COORDS || alternative_tile != TileSetSource::INVALID_TILE_ALTERNATIVE)) {
- WARN_PRINT("Setting a cell as empty requires both source_id, atlas_coord and alternative_tile to be set to their respective \"invalid\" values. Values were thus changes accordingly.");
source_id = TileSet::INVALID_SOURCE;
atlas_coords = TileSetSource::INVALID_ATLAS_COORDS;
alternative_tile = TileSetSource::INVALID_TILE_ALTERNATIVE;
@@ -2171,7 +2187,7 @@ Ref<TileMapPattern> TileMap::get_pattern(int p_layer, TypedArray<Vector2i> p_coo
return output;
}
-Vector2i TileMap::map_pattern(Vector2i p_position_in_tilemap, Vector2i p_coords_in_pattern, Ref<TileMapPattern> p_pattern) {
+Vector2i TileMap::map_pattern(const Vector2i &p_position_in_tilemap, const Vector2i &p_coords_in_pattern, Ref<TileMapPattern> p_pattern) {
ERR_FAIL_COND_V(p_pattern.is_null(), Vector2i());
ERR_FAIL_COND_V(!p_pattern->has_cell(p_coords_in_pattern), Vector2i());
@@ -2195,7 +2211,7 @@ Vector2i TileMap::map_pattern(Vector2i p_position_in_tilemap, Vector2i p_coords_
return output;
}
-void TileMap::set_pattern(int p_layer, Vector2i p_position, const Ref<TileMapPattern> p_pattern) {
+void TileMap::set_pattern(int p_layer, const Vector2i &p_position, const Ref<TileMapPattern> p_pattern) {
ERR_FAIL_INDEX(p_layer, (int)layers.size());
ERR_FAIL_COND(!tile_set.is_valid());
@@ -2206,7 +2222,7 @@ void TileMap::set_pattern(int p_layer, Vector2i p_position, const Ref<TileMapPat
}
}
-TileSet::TerrainsPattern TileMap::_get_best_terrain_pattern_for_constraints(int p_terrain_set, const Vector2i &p_position, RBSet<TerrainConstraint> p_constraints, TileSet::TerrainsPattern p_current_pattern) {
+TileSet::TerrainsPattern TileMap::_get_best_terrain_pattern_for_constraints(int p_terrain_set, const Vector2i &p_position, const RBSet<TerrainConstraint> &p_constraints, TileSet::TerrainsPattern p_current_pattern) {
if (!tile_set.is_valid()) {
return TileSet::TerrainsPattern();
}
@@ -2219,7 +2235,7 @@ TileSet::TerrainsPattern TileMap::_get_best_terrain_pattern_for_constraints(int
// Check the center bit constraint
TerrainConstraint terrain_constraint = TerrainConstraint(this, p_position, terrain_pattern.get_terrain());
- RBSet<TerrainConstraint>::Element *in_set_constraint_element = p_constraints.find(terrain_constraint);
+ const RBSet<TerrainConstraint>::Element *in_set_constraint_element = p_constraints.find(terrain_constraint);
if (in_set_constraint_element) {
if (in_set_constraint_element->get().get_terrain() != terrain_constraint.get_terrain()) {
score += in_set_constraint_element->get().get_priority();
@@ -2266,7 +2282,7 @@ TileSet::TerrainsPattern TileMap::_get_best_terrain_pattern_for_constraints(int
return min_score_pattern;
}
-RBSet<TileMap::TerrainConstraint> TileMap::_get_terrain_constraints_from_added_pattern(Vector2i p_position, int p_terrain_set, TileSet::TerrainsPattern p_terrains_pattern) const {
+RBSet<TileMap::TerrainConstraint> TileMap::_get_terrain_constraints_from_added_pattern(const Vector2i &p_position, int p_terrain_set, TileSet::TerrainsPattern p_terrains_pattern) const {
if (!tile_set.is_valid()) {
return RBSet<TerrainConstraint>();
}
@@ -2374,7 +2390,7 @@ RBSet<TileMap::TerrainConstraint> TileMap::_get_terrain_constraints_from_painted
return constraints;
}
-HashMap<Vector2i, TileSet::TerrainsPattern> TileMap::terrain_fill_constraints(int p_layer, const Vector<Vector2i> &p_to_replace, int p_terrain_set, const RBSet<TerrainConstraint> p_constraints) {
+HashMap<Vector2i, TileSet::TerrainsPattern> TileMap::terrain_fill_constraints(int p_layer, const Vector<Vector2i> &p_to_replace, int p_terrain_set, const RBSet<TerrainConstraint> &p_constraints) {
if (!tile_set.is_valid()) {
return HashMap<Vector2i, TileSet::TerrainsPattern>();
}
@@ -3826,7 +3842,7 @@ void TileMap::set_texture_repeat(CanvasItem::TextureRepeat p_texture_repeat) {
}
}
-TypedArray<Vector2i> TileMap::get_surrounding_tiles(Vector2i coords) {
+TypedArray<Vector2i> TileMap::get_surrounding_cells(const Vector2i &coords) {
if (!tile_set.is_valid()) {
return TypedArray<Vector2i>();
}
@@ -3864,7 +3880,7 @@ TypedArray<Vector2i> TileMap::get_surrounding_tiles(Vector2i coords) {
return around;
}
-void TileMap::draw_cells_outline(Control *p_control, RBSet<Vector2i> p_cells, Color p_color, Transform2D p_transform) {
+void TileMap::draw_cells_outline(Control *p_control, const RBSet<Vector2i> &p_cells, Color p_color, Transform2D p_transform) {
if (!tile_set.is_valid()) {
return;
}
@@ -3889,35 +3905,26 @@ void TileMap::draw_cells_outline(Control *p_control, RBSet<Vector2i> p_cells, Co
DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_BOTTOM_SIDE, 2, 3);
DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_LEFT_SIDE, 3, 0);
DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_TOP_SIDE, 0, 1);
+ } else if (shape == TileSet::TILE_SHAPE_ISOMETRIC) {
+ DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE, 2, 3);
+ DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_SIDE, 1, 2);
+ DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_TOP_LEFT_SIDE, 0, 1);
+ DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_TOP_RIGHT_SIDE, 3, 0);
} else {
if (tile_set->get_tile_offset_axis() == TileSet::TILE_OFFSET_AXIS_HORIZONTAL) {
- if (shape == TileSet::TILE_SHAPE_ISOMETRIC) {
- DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE, 3, 4);
- DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_SIDE, 2, 3);
- DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_TOP_LEFT_SIDE, 0, 1);
- DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_TOP_RIGHT_SIDE, 5, 0);
- } else {
- DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE, 3, 4);
- DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_SIDE, 2, 3);
- DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_LEFT_SIDE, 1, 2);
- DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_TOP_LEFT_SIDE, 0, 1);
- DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_TOP_RIGHT_SIDE, 5, 0);
- DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_RIGHT_SIDE, 4, 5);
- }
+ DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE, 3, 4);
+ DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_SIDE, 2, 3);
+ DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_LEFT_SIDE, 1, 2);
+ DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_TOP_LEFT_SIDE, 0, 1);
+ DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_TOP_RIGHT_SIDE, 5, 0);
+ DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_RIGHT_SIDE, 4, 5);
} else {
- if (shape == TileSet::TILE_SHAPE_ISOMETRIC) {
- DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE, 3, 4);
- DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_SIDE, 5, 0);
- DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_TOP_LEFT_SIDE, 0, 1);
- DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_TOP_RIGHT_SIDE, 2, 3);
- } else {
- DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE, 3, 4);
- DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_BOTTOM_SIDE, 4, 5);
- DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_SIDE, 5, 0);
- DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_TOP_LEFT_SIDE, 0, 1);
- DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_TOP_SIDE, 1, 2);
- DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_TOP_RIGHT_SIDE, 2, 3);
- }
+ DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE, 3, 4);
+ DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_BOTTOM_SIDE, 4, 5);
+ DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_SIDE, 5, 0);
+ DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_TOP_LEFT_SIDE, 0, 1);
+ DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_TOP_SIDE, 1, 2);
+ DRAW_SIDE_IF_NEEDED(TileSet::CELL_NEIGHBOR_TOP_RIGHT_SIDE, 2, 3);
}
}
}
@@ -3943,6 +3950,22 @@ PackedStringArray TileMap::get_configuration_warnings() const {
}
}
+ if (tile_set.is_valid() && tile_set->get_tile_shape() == TileSet::TILE_SHAPE_ISOMETRIC) {
+ bool warn = !is_y_sort_enabled();
+ if (!warn) {
+ for (int layer = 0; layer < (int)layers.size(); layer++) {
+ if (!layers[layer].y_sort_enabled) {
+ warn = true;
+ break;
+ }
+ }
+ }
+
+ if (warn) {
+ warnings.push_back(RTR("Isometric TileSet will likely not look as intended without Y-sort enabled for the TileMap and all of its layers."));
+ }
+ }
+
return warnings;
}
@@ -4000,7 +4023,7 @@ void TileMap::_bind_methods() {
ClassDB::bind_method(D_METHOD("force_update", "layer"), &TileMap::force_update, DEFVAL(-1));
- ClassDB::bind_method(D_METHOD("get_surrounding_tiles", "coords"), &TileMap::get_surrounding_tiles);
+ ClassDB::bind_method(D_METHOD("get_surrounding_cells", "coords"), &TileMap::get_surrounding_cells);
ClassDB::bind_method(D_METHOD("get_used_cells", "layer"), &TileMap::get_used_cells);
ClassDB::bind_method(D_METHOD("get_used_rect"), &TileMap::get_used_rect);
@@ -4037,7 +4060,9 @@ void TileMap::_bind_methods() {
void TileMap::_tile_set_changed() {
emit_signal(SNAME("changed"));
_tile_set_changed_deferred_update_needed = true;
+ instantiated_scenes.clear();
call_deferred(SNAME("_tile_set_changed_deferred_update"));
+ update_configuration_warnings();
}
void TileMap::_tile_set_changed_deferred_update() {
@@ -4056,5 +4081,9 @@ TileMap::TileMap() {
}
TileMap::~TileMap() {
+ if (tile_set.is_valid()) {
+ tile_set->disconnect("changed", callable_mp(this, &TileMap::_tile_set_changed));
+ }
+
_clear_internals();
}
diff --git a/scene/2d/tile_map.h b/scene/2d/tile_map.h
index 7f3e241871..6f71636e47 100644
--- a/scene/2d/tile_map.h
+++ b/scene/2d/tile_map.h
@@ -115,7 +115,7 @@ public:
class TerrainConstraint {
private:
const TileMap *tile_map;
- Vector2i base_cell_coords = Vector2i();
+ Vector2i base_cell_coords;
int bit = -1;
int terrain = -1;
@@ -155,7 +155,7 @@ public:
priority = p_priority;
}
- int get_priority() {
+ int get_priority() const {
return priority;
}
@@ -236,6 +236,8 @@ private:
void _clear_layer_internals(int p_layer);
void _clear_internals();
+ HashSet<Vector3i> instantiated_scenes;
+
// Rect caching.
void _recompute_rect_cache();
@@ -266,8 +268,8 @@ private:
void _scenes_draw_quadrant_debug(TileMapQuadrant *p_quadrant);
// Terrains.
- TileSet::TerrainsPattern _get_best_terrain_pattern_for_constraints(int p_terrain_set, const Vector2i &p_position, RBSet<TerrainConstraint> p_constraints, TileSet::TerrainsPattern p_current_pattern);
- RBSet<TerrainConstraint> _get_terrain_constraints_from_added_pattern(Vector2i p_position, int p_terrain_set, TileSet::TerrainsPattern p_terrains_pattern) const;
+ TileSet::TerrainsPattern _get_best_terrain_pattern_for_constraints(int p_terrain_set, const Vector2i &p_position, const RBSet<TerrainConstraint> &p_constraints, TileSet::TerrainsPattern p_current_pattern);
+ RBSet<TerrainConstraint> _get_terrain_constraints_from_added_pattern(const Vector2i &p_position, int p_terrain_set, TileSet::TerrainsPattern p_terrains_pattern) const;
RBSet<TerrainConstraint> _get_terrain_constraints_from_painted_cells_list(int p_layer, const RBSet<Vector2i> &p_painted, int p_terrain_set, bool p_ignore_empty_terrains) const;
// Set and get tiles from data arrays.
@@ -289,7 +291,7 @@ protected:
static void _bind_methods();
public:
- static Vector2i transform_coords_layout(Vector2i p_coords, TileSet::TileOffsetAxis p_offset_axis, TileSet::TileLayout p_from_layout, TileSet::TileLayout p_to_layout);
+ static Vector2i transform_coords_layout(const Vector2i &p_coords, TileSet::TileOffsetAxis p_offset_axis, TileSet::TileLayout p_from_layout, TileSet::TileLayout p_to_layout);
enum {
INVALID_CELL = -1
@@ -305,7 +307,7 @@ public:
void set_quadrant_size(int p_size);
int get_quadrant_size() const;
- static void draw_tile(RID p_canvas_item, Vector2i p_position, const Ref<TileSet> p_tile_set, int p_atlas_source_id, Vector2i p_atlas_coords, int p_alternative_tile, int p_frame = -1, Color p_modulation = Color(1.0, 1.0, 1.0, 1.0), const TileData *p_tile_data_override = nullptr);
+ static void draw_tile(RID p_canvas_item, const Vector2i &p_position, const Ref<TileSet> p_tile_set, int p_atlas_source_id, const Vector2i &p_atlas_coords, int p_alternative_tile, int p_frame = -1, Color p_modulation = Color(1.0, 1.0, 1.0, 1.0), const TileData *p_tile_data_override = nullptr);
// Layers management.
int get_layers_count() const;
@@ -348,11 +350,11 @@ public:
// Patterns.
Ref<TileMapPattern> get_pattern(int p_layer, TypedArray<Vector2i> p_coords_array);
- Vector2i map_pattern(Vector2i p_position_in_tilemap, Vector2i p_coords_in_pattern, Ref<TileMapPattern> p_pattern);
- void set_pattern(int p_layer, Vector2i p_position, const Ref<TileMapPattern> p_pattern);
+ Vector2i map_pattern(const Vector2i &p_position_in_tilemap, const Vector2i &p_coords_in_pattern, Ref<TileMapPattern> p_pattern);
+ void set_pattern(int p_layer, const Vector2i &p_position, const Ref<TileMapPattern> p_pattern);
// Terrains.
- HashMap<Vector2i, TileSet::TerrainsPattern> terrain_fill_constraints(int p_layer, const Vector<Vector2i> &p_to_replace, int p_terrain_set, const RBSet<TerrainConstraint> p_constraints); // Not exposed.
+ HashMap<Vector2i, TileSet::TerrainsPattern> terrain_fill_constraints(int p_layer, const Vector<Vector2i> &p_to_replace, int p_terrain_set, const RBSet<TerrainConstraint> &p_constraints); // Not exposed.
HashMap<Vector2i, TileSet::TerrainsPattern> terrain_fill_connect(int p_layer, const Vector<Vector2i> &p_coords_array, int p_terrain_set, int p_terrain, bool p_ignore_empty_terrains = true); // Not exposed.
HashMap<Vector2i, TileSet::TerrainsPattern> terrain_fill_path(int p_layer, const Vector<Vector2i> &p_coords_array, int p_terrain_set, int p_terrain, bool p_ignore_empty_terrains = true); // Not exposed.
HashMap<Vector2i, TileSet::TerrainsPattern> terrain_fill_pattern(int p_layer, const Vector<Vector2i> &p_coords_array, int p_terrain_set, TileSet::TerrainsPattern p_terrains_pattern, bool p_ignore_empty_terrains = true); // Not exposed.
@@ -398,8 +400,8 @@ public:
void force_update(int p_layer = -1);
// Helpers?
- TypedArray<Vector2i> get_surrounding_tiles(Vector2i coords);
- void draw_cells_outline(Control *p_control, RBSet<Vector2i> p_cells, Color p_color, Transform2D p_transform = Transform2D());
+ TypedArray<Vector2i> get_surrounding_cells(const Vector2i &coords);
+ void draw_cells_outline(Control *p_control, const RBSet<Vector2i> &p_cells, Color p_color, Transform2D p_transform = Transform2D());
// Virtual function to modify the TileData at runtime
GDVIRTUAL2R(bool, _use_tile_data_runtime_update, int, Vector2i);
diff --git a/scene/2d/touch_screen_button.cpp b/scene/2d/touch_screen_button.cpp
index a02f322ef1..11b4718802 100644
--- a/scene/2d/touch_screen_button.cpp
+++ b/scene/2d/touch_screen_button.cpp
@@ -100,7 +100,7 @@ void TouchScreenButton::_notification(int p_what) {
if (!is_inside_tree()) {
return;
}
- if (!Engine::get_singleton()->is_editor_hint() && !!DisplayServer::get_singleton()->screen_is_touchscreen(DisplayServer::get_singleton()->window_get_current_screen(get_viewport()->get_window_id())) && visibility == VISIBILITY_TOUCHSCREEN_ONLY) {
+ if (!Engine::get_singleton()->is_editor_hint() && !DisplayServer::get_singleton()->is_touchscreen_available() && visibility == VISIBILITY_TOUCHSCREEN_ONLY) {
return;
}
@@ -137,7 +137,7 @@ void TouchScreenButton::_notification(int p_what) {
} break;
case NOTIFICATION_ENTER_TREE: {
- if (!Engine::get_singleton()->is_editor_hint() && !!DisplayServer::get_singleton()->screen_is_touchscreen(DisplayServer::get_singleton()->window_get_current_screen(get_viewport()->get_window_id())) && visibility == VISIBILITY_TOUCHSCREEN_ONLY) {
+ if (!Engine::get_singleton()->is_editor_hint() && !DisplayServer::get_singleton()->is_touchscreen_available() && visibility == VISIBILITY_TOUCHSCREEN_ONLY) {
return;
}
queue_redraw();
diff --git a/scene/3d/audio_stream_player_3d.cpp b/scene/3d/audio_stream_player_3d.cpp
index b9d95672fe..75e840c24b 100644
--- a/scene/3d/audio_stream_player_3d.cpp
+++ b/scene/3d/audio_stream_player_3d.cpp
@@ -606,6 +606,9 @@ bool AudioStreamPlayer3D::is_playing() const {
return true;
}
}
+ if (setplay.get() >= 0) {
+ return true; // play() has been called this frame, but no playback exists just yet.
+ }
return false;
}
diff --git a/scene/3d/audio_stream_player_3d.h b/scene/3d/audio_stream_player_3d.h
index 913cc9fc00..806b250ba7 100644
--- a/scene/3d/audio_stream_player_3d.h
+++ b/scene/3d/audio_stream_player_3d.h
@@ -117,7 +117,7 @@ private:
float _get_attenuation_db(float p_distance) const;
float panning_strength = 1.0f;
- float cached_global_panning_strength = 1.0f;
+ float cached_global_panning_strength = 0.5f;
protected:
void _validate_property(PropertyInfo &p_property) const;
diff --git a/scene/3d/bone_attachment_3d.cpp b/scene/3d/bone_attachment_3d.cpp
index d8524a7392..9cf10dbef1 100644
--- a/scene/3d/bone_attachment_3d.cpp
+++ b/scene/3d/bone_attachment_3d.cpp
@@ -375,7 +375,7 @@ void BoneAttachment3D::on_bone_pose_update(int p_bone_index) {
}
}
#ifdef TOOLS_ENABLED
-void BoneAttachment3D::_notify_skeleton_bones_renamed(Node *p_base_scene, Skeleton3D *p_skeleton, Ref<BoneMap> p_bone_map) {
+void BoneAttachment3D::_notify_skeleton_bones_renamed(Node *p_base_scene, Skeleton3D *p_skeleton, Dictionary p_rename_map) {
const Skeleton3D *parent = nullptr;
if (use_external_skeleton) {
if (external_skeleton_node_cache.is_valid()) {
@@ -385,7 +385,7 @@ void BoneAttachment3D::_notify_skeleton_bones_renamed(Node *p_base_scene, Skelet
parent = Object::cast_to<Skeleton3D>(get_parent());
}
if (parent && parent == p_skeleton) {
- StringName bn = p_bone_map->find_profile_bone_name(bone_name);
+ StringName bn = p_rename_map[bone_name];
if (bn) {
set_bone_name(bn);
}
diff --git a/scene/3d/bone_attachment_3d.h b/scene/3d/bone_attachment_3d.h
index 2db6ba6268..81338b30e9 100644
--- a/scene/3d/bone_attachment_3d.h
+++ b/scene/3d/bone_attachment_3d.h
@@ -72,7 +72,7 @@ protected:
static void _bind_methods();
#ifdef TOOLS_ENABLED
- virtual void _notify_skeleton_bones_renamed(Node *p_base_scene, Skeleton3D *p_skeleton, Ref<BoneMap> p_bone_map);
+ virtual void _notify_skeleton_bones_renamed(Node *p_base_scene, Skeleton3D *p_skeleton, Dictionary p_rename_map);
#endif // TOOLS_ENABLED
public:
diff --git a/scene/3d/camera_3d.cpp b/scene/3d/camera_3d.cpp
index 304e56326d..2a50575749 100644
--- a/scene/3d/camera_3d.cpp
+++ b/scene/3d/camera_3d.cpp
@@ -112,6 +112,12 @@ void Camera3D::_notification(int p_what) {
if (current || first_camera) {
viewport->_camera_3d_set(this);
}
+
+#ifdef TOOLS_ENABLED
+ if (Engine::get_singleton()->is_editor_hint()) {
+ viewport->connect(SNAME("size_changed"), callable_mp((Node3D *)this, &Camera3D::update_gizmos));
+ }
+#endif
} break;
case NOTIFICATION_TRANSFORM_CHANGED: {
@@ -133,6 +139,11 @@ void Camera3D::_notification(int p_what) {
}
if (viewport) {
+#ifdef TOOLS_ENABLED
+ if (Engine::get_singleton()->is_editor_hint()) {
+ viewport->disconnect(SNAME("size_changed"), callable_mp((Node3D *)this, &Camera3D::update_gizmos));
+ }
+#endif
viewport->_camera_3d_remove(this);
viewport = nullptr;
}
diff --git a/scene/3d/collision_object_3d.cpp b/scene/3d/collision_object_3d.cpp
index ca23fe03a2..66546092f2 100644
--- a/scene/3d/collision_object_3d.cpp
+++ b/scene/3d/collision_object_3d.cpp
@@ -30,6 +30,7 @@
#include "collision_object_3d.h"
+#include "scene/resources/shape_3d.h"
#include "scene/scene_string_names.h"
void CollisionObject3D::_notification(int p_what) {
diff --git a/scene/3d/collision_shape_3d.cpp b/scene/3d/collision_shape_3d.cpp
index ef381641ab..2729dfc369 100644
--- a/scene/3d/collision_shape_3d.cpp
+++ b/scene/3d/collision_shape_3d.cpp
@@ -34,6 +34,7 @@
#include "physics_body_3d.h"
#include "scene/resources/concave_polygon_shape_3d.h"
#include "scene/resources/convex_polygon_shape_3d.h"
+#include "scene/resources/world_boundary_shape_3d.h"
void CollisionShape3D::make_convex_from_siblings() {
Node *p = get_parent();
@@ -125,10 +126,12 @@ PackedStringArray CollisionShape3D::get_configuration_warnings() const {
warnings.push_back(RTR("A shape must be provided for CollisionShape3D to function. Please create a shape resource for it."));
}
- if (shape.is_valid() &&
- Object::cast_to<RigidBody3D>(get_parent()) &&
- Object::cast_to<ConcavePolygonShape3D>(*shape)) {
- warnings.push_back(RTR("ConcavePolygonShape3D doesn't support RigidBody3D in another mode than static."));
+ if (shape.is_valid() && Object::cast_to<RigidBody3D>(get_parent())) {
+ if (Object::cast_to<ConcavePolygonShape3D>(*shape)) {
+ warnings.push_back(RTR("ConcavePolygonShape3D doesn't support RigidBody3D in another mode than static."));
+ } else if (Object::cast_to<WorldBoundaryShape3D>(*shape)) {
+ warnings.push_back(RTR("WorldBoundaryShape3D doesn't support RigidBody3D in another mode than static."));
+ }
}
return warnings;
diff --git a/scene/3d/cpu_particles_3d.cpp b/scene/3d/cpu_particles_3d.cpp
index 7de685b469..5ac8535bb6 100644
--- a/scene/3d/cpu_particles_3d.cpp
+++ b/scene/3d/cpu_particles_3d.cpp
@@ -867,7 +867,7 @@ void CPUParticles3D::_particles_process(double p_delta) {
real_t ring_random_angle = Math::randf() * Math_TAU;
real_t ring_random_radius = Math::randf() * (emission_ring_radius - emission_ring_inner_radius) + emission_ring_inner_radius;
Vector3 axis = emission_ring_axis.normalized();
- Vector3 ortho_axis = Vector3();
+ Vector3 ortho_axis;
if (axis == Vector3(1.0, 0.0, 0.0)) {
ortho_axis = Vector3(0.0, 1.0, 0.0).cross(axis);
} else {
diff --git a/scene/3d/gpu_particles_3d.cpp b/scene/3d/gpu_particles_3d.cpp
index 9d04202c2d..17dfe2610e 100644
--- a/scene/3d/gpu_particles_3d.cpp
+++ b/scene/3d/gpu_particles_3d.cpp
@@ -272,10 +272,6 @@ bool GPUParticles3D::get_interpolate() const {
PackedStringArray GPUParticles3D::get_configuration_warnings() const {
PackedStringArray warnings = GeometryInstance3D::get_configuration_warnings();
- if (RenderingServer::get_singleton()->is_low_end()) {
- warnings.push_back(RTR("GPU-based particles are not supported by the OpenGL video driver.\nUse the CPUParticles3D node instead. You can use the \"Convert to CPUParticles3D\" option for this purpose."));
- }
-
bool meshes_found = false;
bool anim_material_found = false;
diff --git a/scene/3d/gpu_particles_3d.h b/scene/3d/gpu_particles_3d.h
index 835d71862a..d1768436e5 100644
--- a/scene/3d/gpu_particles_3d.h
+++ b/scene/3d/gpu_particles_3d.h
@@ -82,7 +82,7 @@ private:
Ref<Material> process_material;
- DrawOrder draw_order;
+ DrawOrder draw_order = DRAW_ORDER_INDEX;
Vector<Ref<Mesh>> draw_passes;
Ref<Skin> skin;
diff --git a/scene/3d/gpu_particles_collision_3d.cpp b/scene/3d/gpu_particles_collision_3d.cpp
index 2c5df48b75..476820b1c4 100644
--- a/scene/3d/gpu_particles_collision_3d.cpp
+++ b/scene/3d/gpu_particles_collision_3d.cpp
@@ -347,7 +347,9 @@ void GPUParticlesCollisionSDF3D::_compute_sdf(ComputeSDFParams *params) {
WorkerThreadPool::GroupID group_task = WorkerThreadPool::get_singleton()->add_template_group_task(this, &GPUParticlesCollisionSDF3D::_compute_sdf_z, params, params->size.z);
while (!WorkerThreadPool::get_singleton()->is_group_task_completed(group_task)) {
OS::get_singleton()->delay_usec(10000);
- bake_step_function(WorkerThreadPool::get_singleton()->get_group_processed_element_count(group_task) * 100 / params->size.z, "Baking SDF");
+ if (bake_step_function) {
+ bake_step_function(WorkerThreadPool::get_singleton()->get_group_processed_element_count(group_task) * 100 / params->size.z, "Baking SDF");
+ }
}
WorkerThreadPool::get_singleton()->wait_for_group_task_completion(group_task);
}
diff --git a/scene/3d/light_3d.cpp b/scene/3d/light_3d.cpp
index 198dba7811..3f43e718b8 100644
--- a/scene/3d/light_3d.cpp
+++ b/scene/3d/light_3d.cpp
@@ -461,7 +461,7 @@ Light3D::Light3D(RenderingServer::LightType p_type) {
set_param(PARAM_SHADOW_PANCAKE_SIZE, 20.0);
set_param(PARAM_SHADOW_OPACITY, 1.0);
set_param(PARAM_SHADOW_BLUR, 1.0);
- set_param(PARAM_SHADOW_BIAS, 0.03);
+ set_param(PARAM_SHADOW_BIAS, 0.1);
set_param(PARAM_SHADOW_NORMAL_BIAS, 1.0);
set_param(PARAM_TRANSMITTANCE_BIAS, 0.05);
set_param(PARAM_SHADOW_FADE_START, 1);
@@ -571,8 +571,8 @@ DirectionalLight3D::DirectionalLight3D() :
Light3D(RenderingServer::LIGHT_DIRECTIONAL) {
set_param(PARAM_SHADOW_MAX_DISTANCE, 100);
set_param(PARAM_SHADOW_FADE_START, 0.8);
- // Increase the default shadow bias to better suit most scenes.
- set_param(PARAM_SHADOW_BIAS, 0.1);
+ // Increase the default shadow normal bias to better suit most scenes.
+ set_param(PARAM_SHADOW_NORMAL_BIAS, 2.0);
set_param(PARAM_INTENSITY, 100000.0); // Specified in Lux, approximate mid-day sun.
set_shadow_mode(SHADOW_PARALLEL_4_SPLITS);
blend_splits = false;
@@ -614,8 +614,6 @@ void OmniLight3D::_bind_methods() {
OmniLight3D::OmniLight3D() :
Light3D(RenderingServer::LIGHT_OMNI) {
set_shadow_mode(SHADOW_CUBE);
- // Increase the default shadow biases to better suit most scenes.
- set_param(PARAM_SHADOW_BIAS, 0.2);
}
PackedStringArray SpotLight3D::get_configuration_warnings() const {
@@ -639,3 +637,9 @@ void SpotLight3D::_bind_methods() {
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "spot_angle", PROPERTY_HINT_RANGE, "0,180,0.01,degrees"), "set_param", "get_param", PARAM_SPOT_ANGLE);
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "spot_angle_attenuation", PROPERTY_HINT_EXP_EASING, "attenuation"), "set_param", "get_param", PARAM_SPOT_ATTENUATION);
}
+
+SpotLight3D::SpotLight3D() :
+ Light3D(RenderingServer::LIGHT_SPOT) {
+ // Decrease the default shadow bias to better suit most scenes.
+ set_param(PARAM_SHADOW_BIAS, 0.03);
+}
diff --git a/scene/3d/light_3d.h b/scene/3d/light_3d.h
index 84d214030b..d2dfa32aac 100644
--- a/scene/3d/light_3d.h
+++ b/scene/3d/light_3d.h
@@ -233,8 +233,7 @@ protected:
public:
PackedStringArray get_configuration_warnings() const override;
- SpotLight3D() :
- Light3D(RenderingServer::LIGHT_SPOT) {}
+ SpotLight3D();
};
#endif // LIGHT_3D_H
diff --git a/scene/3d/mesh_instance_3d.cpp b/scene/3d/mesh_instance_3d.cpp
index d4f60503c2..c4ec54fa8f 100644
--- a/scene/3d/mesh_instance_3d.cpp
+++ b/scene/3d/mesh_instance_3d.cpp
@@ -33,6 +33,8 @@
#include "collision_shape_3d.h"
#include "core/core_string_names.h"
#include "physics_body_3d.h"
+#include "scene/resources/concave_polygon_shape_3d.h"
+#include "scene/resources/convex_polygon_shape_3d.h"
bool MeshInstance3D::_set(const StringName &p_name, const Variant &p_value) {
//this is not _too_ bad performance wise, really. it only arrives here if the property was not set anywhere else.
@@ -50,6 +52,7 @@ bool MeshInstance3D::_set(const StringName &p_name, const Variant &p_value) {
if (p_name.operator String().begins_with("surface_material_override/")) {
int idx = p_name.operator String().get_slicec('/', 1).to_int();
+
if (idx >= surface_override_materials.size() || idx < 0) {
return false;
}
@@ -224,7 +227,7 @@ Node *MeshInstance3D::create_trimesh_collision_node() {
return nullptr;
}
- Ref<Shape3D> shape = mesh->create_trimesh_shape();
+ Ref<ConcavePolygonShape3D> shape = mesh->create_trimesh_shape();
if (shape.is_null()) {
return nullptr;
}
@@ -254,7 +257,7 @@ Node *MeshInstance3D::create_convex_collision_node(bool p_clean, bool p_simplify
return nullptr;
}
- Ref<Shape3D> shape = mesh->create_convex_shape(p_clean, p_simplify);
+ Ref<ConvexPolygonShape3D> shape = mesh->create_convex_shape(p_clean, p_simplify);
if (shape.is_null()) {
return nullptr;
}
@@ -320,6 +323,11 @@ void MeshInstance3D::_notification(int p_what) {
case NOTIFICATION_ENTER_TREE: {
_resolve_skeleton_path();
} break;
+ case NOTIFICATION_TRANSLATION_CHANGED: {
+ if (mesh.is_valid()) {
+ mesh->notification(NOTIFICATION_TRANSLATION_CHANGED);
+ }
+ } break;
}
}
diff --git a/scene/3d/mesh_instance_3d.h b/scene/3d/mesh_instance_3d.h
index caf7d25616..e1cc5272ea 100644
--- a/scene/3d/mesh_instance_3d.h
+++ b/scene/3d/mesh_instance_3d.h
@@ -57,6 +57,7 @@ protected:
bool _set(const StringName &p_name, const Variant &p_value);
bool _get(const StringName &p_name, Variant &r_ret) const;
void _get_property_list(List<PropertyInfo> *p_list) const;
+ bool surface_index_0 = false;
void _notification(int p_what);
static void _bind_methods();
diff --git a/scene/3d/navigation_agent_3d.cpp b/scene/3d/navigation_agent_3d.cpp
index 36350d251e..741f7397ad 100644
--- a/scene/3d/navigation_agent_3d.cpp
+++ b/scene/3d/navigation_agent_3d.cpp
@@ -74,6 +74,9 @@ void NavigationAgent3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_navigation_layer_value", "layer_number", "value"), &NavigationAgent3D::set_navigation_layer_value);
ClassDB::bind_method(D_METHOD("get_navigation_layer_value", "layer_number"), &NavigationAgent3D::get_navigation_layer_value);
+ ClassDB::bind_method(D_METHOD("set_path_metadata_flags", "flags"), &NavigationAgent3D::set_path_metadata_flags);
+ ClassDB::bind_method(D_METHOD("get_path_metadata_flags"), &NavigationAgent3D::get_path_metadata_flags);
+
ClassDB::bind_method(D_METHOD("set_navigation_map", "navigation_map"), &NavigationAgent3D::set_navigation_map);
ClassDB::bind_method(D_METHOD("get_navigation_map"), &NavigationAgent3D::get_navigation_map);
@@ -83,8 +86,9 @@ void NavigationAgent3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_next_location"), &NavigationAgent3D::get_next_location);
ClassDB::bind_method(D_METHOD("distance_to_target"), &NavigationAgent3D::distance_to_target);
ClassDB::bind_method(D_METHOD("set_velocity", "velocity"), &NavigationAgent3D::set_velocity);
- ClassDB::bind_method(D_METHOD("get_nav_path"), &NavigationAgent3D::get_nav_path);
- ClassDB::bind_method(D_METHOD("get_nav_path_index"), &NavigationAgent3D::get_nav_path_index);
+ ClassDB::bind_method(D_METHOD("get_current_navigation_result"), &NavigationAgent3D::get_current_navigation_result);
+ ClassDB::bind_method(D_METHOD("get_current_navigation_path"), &NavigationAgent3D::get_current_navigation_path);
+ ClassDB::bind_method(D_METHOD("get_current_navigation_path_index"), &NavigationAgent3D::get_current_navigation_path_index);
ClassDB::bind_method(D_METHOD("is_target_reached"), &NavigationAgent3D::is_target_reached);
ClassDB::bind_method(D_METHOD("is_target_reachable"), &NavigationAgent3D::is_target_reachable);
ClassDB::bind_method(D_METHOD("is_navigation_finished"), &NavigationAgent3D::is_navigation_finished);
@@ -99,6 +103,7 @@ void NavigationAgent3D::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "agent_height_offset", PROPERTY_HINT_RANGE, "-100.0,100,0.01,suffix:m"), "set_agent_height_offset", "get_agent_height_offset");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "path_max_distance", PROPERTY_HINT_RANGE, "0.01,100,0.1,suffix:m"), "set_path_max_distance", "get_path_max_distance");
ADD_PROPERTY(PropertyInfo(Variant::INT, "navigation_layers", PROPERTY_HINT_LAYERS_3D_NAVIGATION), "set_navigation_layers", "get_navigation_layers");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "path_metadata_flags", PROPERTY_HINT_FLAGS, "Include Types,Include RIDs,Include Owners"), "set_path_metadata_flags", "get_path_metadata_flags");
ADD_GROUP("Avoidance", "");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "avoidance_enabled"), "set_avoidance_enabled", "get_avoidance_enabled");
@@ -111,6 +116,8 @@ void NavigationAgent3D::_bind_methods() {
ADD_SIGNAL(MethodInfo("path_changed"));
ADD_SIGNAL(MethodInfo("target_reached"));
+ ADD_SIGNAL(MethodInfo("waypoint_reached", PropertyInfo(Variant::DICTIONARY, "details")));
+ ADD_SIGNAL(MethodInfo("link_reached", PropertyInfo(Variant::DICTIONARY, "details")));
ADD_SIGNAL(MethodInfo("navigation_finished"));
ADD_SIGNAL(MethodInfo("velocity_computed", PropertyInfo(Variant::VECTOR3, "safe_velocity")));
}
@@ -167,7 +174,7 @@ void NavigationAgent3D::_notification(int p_what) {
} break;
case NOTIFICATION_INTERNAL_PHYSICS_PROCESS: {
- if (agent_parent) {
+ if (agent_parent && target_position_submitted) {
if (avoidance_enabled) {
// agent_position on NavigationServer is avoidance only and has nothing to do with pathfinding
// no point in flooding NavigationServer queue with agent position updates that get send to the void if avoidance is not used
@@ -204,9 +211,9 @@ NavigationAgent3D::~NavigationAgent3D() {
void NavigationAgent3D::set_avoidance_enabled(bool p_enabled) {
avoidance_enabled = p_enabled;
if (avoidance_enabled) {
- NavigationServer3D::get_singleton()->agent_set_callback(agent, this, "_avoidance_done");
+ NavigationServer3D::get_singleton()->agent_set_callback(agent, get_instance_id(), "_avoidance_done");
} else {
- NavigationServer3D::get_singleton()->agent_set_callback(agent, nullptr, "_avoidance_done");
+ NavigationServer3D::get_singleton()->agent_set_callback(agent, ObjectID(), "_avoidance_done");
}
}
@@ -216,7 +223,7 @@ bool NavigationAgent3D::get_avoidance_enabled() const {
void NavigationAgent3D::set_agent_parent(Node *p_agent_parent) {
// remove agent from any avoidance map before changing parent or there will be leftovers on the RVO map
- NavigationServer3D::get_singleton()->agent_set_callback(agent, nullptr, "_avoidance_done");
+ NavigationServer3D::get_singleton()->agent_set_callback(agent, ObjectID(), "_avoidance_done");
if (Object::cast_to<Node3D>(p_agent_parent) != nullptr) {
// place agent on navigation map first or else the RVO agent callback creation fails silently later
agent_parent = Object::cast_to<Node3D>(p_agent_parent);
@@ -263,6 +270,14 @@ bool NavigationAgent3D::get_navigation_layer_value(int p_layer_number) const {
return get_navigation_layers() & (1 << (p_layer_number - 1));
}
+void NavigationAgent3D::set_path_metadata_flags(BitField<NavigationPathQueryParameters3D::PathMetadataFlags> p_path_metadata_flags) {
+ if (path_metadata_flags == p_path_metadata_flags) {
+ return;
+ }
+
+ path_metadata_flags = p_path_metadata_flags;
+}
+
void NavigationAgent3D::set_navigation_map(RID p_navigation_map) {
map_override = p_navigation_map;
NavigationServer3D::get_singleton()->agent_set_map(agent, map_override);
@@ -330,6 +345,7 @@ real_t NavigationAgent3D::get_path_max_distance() {
void NavigationAgent3D::set_target_location(Vector3 p_location) {
target_location = p_location;
+ target_position_submitted = true;
_request_repath();
}
@@ -345,14 +361,10 @@ Vector3 NavigationAgent3D::get_next_location() {
ERR_FAIL_COND_V_MSG(agent_parent == nullptr, Vector3(), "The agent has no parent.");
return agent_parent->get_global_transform().origin;
} else {
- return navigation_path[nav_path_index] - Vector3(0, navigation_height_offset, 0);
+ return navigation_path[navigation_path_index] - Vector3(0, navigation_height_offset, 0);
}
}
-const Vector<Vector3> &NavigationAgent3D::get_nav_path() const {
- return navigation_result->get_path();
-}
-
real_t NavigationAgent3D::distance_to_target() const {
ERR_FAIL_COND_V_MSG(agent_parent == nullptr, 0.0, "The agent has no parent.");
return agent_parent->get_global_transform().origin.distance_to(target_location);
@@ -417,6 +429,9 @@ void NavigationAgent3D::update_navigation() {
if (!agent_parent->is_inside_tree()) {
return;
}
+ if (!target_position_submitted) {
+ return;
+ }
if (update_frame_id == Engine::get_singleton()->get_physics_frames()) {
return;
}
@@ -433,12 +448,12 @@ void NavigationAgent3D::update_navigation() {
reload_path = true;
} else {
// Check if too far from the navigation path
- if (nav_path_index > 0) {
+ if (navigation_path_index > 0) {
const Vector<Vector3> &navigation_path = navigation_result->get_path();
Vector3 segment[2];
- segment[0] = navigation_path[nav_path_index - 1];
- segment[1] = navigation_path[nav_path_index];
+ segment[0] = navigation_path[navigation_path_index - 1];
+ segment[1] = navigation_path[navigation_path_index];
segment[0].y -= navigation_height_offset;
segment[1].y -= navigation_height_offset;
Vector3 p = Geometry3D::get_closest_point_to_segment(origin, segment);
@@ -453,6 +468,7 @@ void NavigationAgent3D::update_navigation() {
navigation_query->set_start_position(origin);
navigation_query->set_target_position(target_location);
navigation_query->set_navigation_layers(navigation_layers);
+ navigation_query->set_metadata_flags(path_metadata_flags);
if (map_override.is_valid()) {
navigation_query->set_map(map_override);
@@ -462,7 +478,7 @@ void NavigationAgent3D::update_navigation() {
NavigationServer3D::get_singleton()->query_path(navigation_query, navigation_result);
navigation_finished = false;
- nav_path_index = 0;
+ navigation_path_index = 0;
emit_signal(SNAME("path_changed"));
}
@@ -474,12 +490,57 @@ void NavigationAgent3D::update_navigation() {
if (navigation_finished == false) {
// Advances to the next far away location.
const Vector<Vector3> &navigation_path = navigation_result->get_path();
- while (origin.distance_to(navigation_path[nav_path_index] - Vector3(0, navigation_height_offset, 0)) < path_desired_distance) {
- nav_path_index += 1;
- if (nav_path_index == navigation_path.size()) {
+ const Vector<int32_t> &navigation_path_types = navigation_result->get_path_types();
+ const TypedArray<RID> &navigation_path_rids = navigation_result->get_path_rids();
+ const Vector<int64_t> &navigation_path_owners = navigation_result->get_path_owner_ids();
+
+ while (origin.distance_to(navigation_path[navigation_path_index] - Vector3(0, navigation_height_offset, 0)) < path_desired_distance) {
+ Dictionary details;
+
+ const Vector3 waypoint = navigation_path[navigation_path_index];
+ details[SNAME("location")] = waypoint;
+
+ int waypoint_type = -1;
+ if (path_metadata_flags.has_flag(NavigationPathQueryParameters3D::PathMetadataFlags::PATH_METADATA_INCLUDE_TYPES)) {
+ const NavigationPathQueryResult3D::PathSegmentType type = NavigationPathQueryResult3D::PathSegmentType(navigation_path_types[navigation_path_index]);
+
+ details[SNAME("type")] = type;
+ waypoint_type = type;
+ }
+
+ if (path_metadata_flags.has_flag(NavigationPathQueryParameters3D::PathMetadataFlags::PATH_METADATA_INCLUDE_RIDS)) {
+ details[SNAME("rid")] = navigation_path_rids[navigation_path_index];
+ }
+
+ if (path_metadata_flags.has_flag(NavigationPathQueryParameters3D::PathMetadataFlags::PATH_METADATA_INCLUDE_OWNERS)) {
+ const ObjectID waypoint_owner_id = ObjectID(navigation_path_owners[navigation_path_index]);
+
+ // Get a reference to the owning object.
+ Object *owner = nullptr;
+ if (waypoint_owner_id.is_valid()) {
+ owner = ObjectDB::get_instance(waypoint_owner_id);
+ }
+
+ details[SNAME("owner")] = owner;
+ }
+
+ // Emit a signal for the waypoint
+ emit_signal(SNAME("waypoint_reached"), details);
+
+ // Emit a signal if we've reached a navigation link
+ if (waypoint_type == NavigationPathQueryResult3D::PATH_SEGMENT_TYPE_LINK) {
+ emit_signal(SNAME("link_reached"), details);
+ }
+
+ // Move to the next waypoint on the list
+ navigation_path_index += 1;
+
+ // Check to see if we've finished our route
+ if (navigation_path_index == navigation_path.size()) {
_check_distance_to_target();
- nav_path_index -= 1;
+ navigation_path_index -= 1;
navigation_finished = true;
+ target_position_submitted = false;
emit_signal(SNAME("navigation_finished"));
break;
}
diff --git a/scene/3d/navigation_agent_3d.h b/scene/3d/navigation_agent_3d.h
index 90ceab0242..cda218b538 100644
--- a/scene/3d/navigation_agent_3d.h
+++ b/scene/3d/navigation_agent_3d.h
@@ -32,10 +32,10 @@
#define NAVIGATION_AGENT_3D_H
#include "scene/main/node.h"
+#include "servers/navigation/navigation_path_query_parameters_3d.h"
+#include "servers/navigation/navigation_path_query_result_3d.h"
class Node3D;
-class NavigationPathQueryParameters3D;
-class NavigationPathQueryResult3D;
class NavigationAgent3D : public Node {
GDCLASS(NavigationAgent3D, Node);
@@ -48,6 +48,7 @@ class NavigationAgent3D : public Node {
bool avoidance_enabled = false;
uint32_t navigation_layers = 1;
+ BitField<NavigationPathQueryParameters3D::PathMetadataFlags> path_metadata_flags = NavigationPathQueryParameters3D::PathMetadataFlags::PATH_METADATA_INCLUDE_ALL;
real_t path_desired_distance = 1.0;
real_t target_desired_distance = 1.0;
@@ -62,9 +63,10 @@ class NavigationAgent3D : public Node {
real_t path_max_distance = 3.0;
Vector3 target_location;
+ bool target_position_submitted = false;
Ref<NavigationPathQueryParameters3D> navigation_query;
Ref<NavigationPathQueryResult3D> navigation_result;
- int nav_path_index = 0;
+ int navigation_path_index = 0;
bool velocity_submitted = false;
Vector3 prev_safe_velocity;
/// The submitted target velocity
@@ -97,6 +99,11 @@ public:
void set_navigation_layer_value(int p_layer_number, bool p_value);
bool get_navigation_layer_value(int p_layer_number) const;
+ void set_path_metadata_flags(BitField<NavigationPathQueryParameters3D::PathMetadataFlags> p_flags);
+ BitField<NavigationPathQueryParameters3D::PathMetadataFlags> get_path_metadata_flags() const {
+ return path_metadata_flags;
+ }
+
void set_navigation_map(RID p_navigation_map);
RID get_navigation_map() const;
@@ -153,10 +160,14 @@ public:
Vector3 get_next_location();
- const Vector<Vector3> &get_nav_path() const;
-
- int get_nav_path_index() const {
- return nav_path_index;
+ Ref<NavigationPathQueryResult3D> get_current_navigation_result() const {
+ return navigation_result;
+ }
+ const Vector<Vector3> &get_current_navigation_path() const {
+ return navigation_result->get_path();
+ }
+ int get_current_navigation_path_index() const {
+ return navigation_path_index;
}
real_t distance_to_target() const;
diff --git a/scene/3d/navigation_link_3d.cpp b/scene/3d/navigation_link_3d.cpp
index 78fe4754ea..bee7c7f39b 100644
--- a/scene/3d/navigation_link_3d.cpp
+++ b/scene/3d/navigation_link_3d.cpp
@@ -221,6 +221,8 @@ void NavigationLink3D::_notification(int p_what) {
NavigationLink3D::NavigationLink3D() {
link = NavigationServer3D::get_singleton()->link_create();
+ NavigationServer3D::get_singleton()->link_set_owner_id(link, get_instance_id());
+
set_notify_transform(true);
}
diff --git a/scene/3d/navigation_link_3d.h b/scene/3d/navigation_link_3d.h
index 1fc03546fa..46bc6318b8 100644
--- a/scene/3d/navigation_link_3d.h
+++ b/scene/3d/navigation_link_3d.h
@@ -37,11 +37,11 @@ class NavigationLink3D : public Node3D {
GDCLASS(NavigationLink3D, Node3D);
bool enabled = true;
- RID link = RID();
+ RID link;
bool bidirectional = true;
uint32_t navigation_layers = 1;
- Vector3 end_location = Vector3();
- Vector3 start_location = Vector3();
+ Vector3 end_location;
+ Vector3 start_location;
real_t enter_cost = 0.0;
real_t travel_cost = 1.0;
diff --git a/scene/3d/navigation_region_3d.cpp b/scene/3d/navigation_region_3d.cpp
index 06182d921c..86b78f847e 100644
--- a/scene/3d/navigation_region_3d.cpp
+++ b/scene/3d/navigation_region_3d.cpp
@@ -192,26 +192,26 @@ void NavigationRegion3D::_notification(int p_what) {
}
}
-void NavigationRegion3D::set_navigation_mesh(const Ref<NavigationMesh> &p_navmesh) {
- if (p_navmesh == navmesh) {
+void NavigationRegion3D::set_navigation_mesh(const Ref<NavigationMesh> &p_navigation_mesh) {
+ if (p_navigation_mesh == navigation_mesh) {
return;
}
- if (navmesh.is_valid()) {
- navmesh->disconnect("changed", callable_mp(this, &NavigationRegion3D::_navigation_changed));
+ if (navigation_mesh.is_valid()) {
+ navigation_mesh->disconnect("changed", callable_mp(this, &NavigationRegion3D::_navigation_changed));
}
- navmesh = p_navmesh;
+ navigation_mesh = p_navigation_mesh;
- if (navmesh.is_valid()) {
- navmesh->connect("changed", callable_mp(this, &NavigationRegion3D::_navigation_changed));
+ if (navigation_mesh.is_valid()) {
+ navigation_mesh->connect("changed", callable_mp(this, &NavigationRegion3D::_navigation_changed));
}
- NavigationServer3D::get_singleton()->region_set_navmesh(region, p_navmesh);
+ NavigationServer3D::get_singleton()->region_set_navigation_mesh(region, p_navigation_mesh);
#ifdef DEBUG_ENABLED
if (is_inside_tree() && NavigationServer3D::get_singleton()->get_debug_enabled()) {
- if (navmesh.is_valid()) {
+ if (navigation_mesh.is_valid()) {
_update_debug_mesh();
_update_debug_edge_connections_mesh();
} else {
@@ -232,7 +232,7 @@ void NavigationRegion3D::set_navigation_mesh(const Ref<NavigationMesh> &p_navmes
}
Ref<NavigationMesh> NavigationRegion3D::get_navigation_mesh() const {
- return navmesh;
+ return navigation_mesh;
}
struct BakeThreadsArgs {
@@ -245,7 +245,7 @@ void _bake_navigation_mesh(void *p_user_data) {
if (args->nav_region->get_navigation_mesh().is_valid()) {
Ref<NavigationMesh> nav_mesh = args->nav_region->get_navigation_mesh()->duplicate();
- NavigationServer3D::get_singleton()->region_bake_navmesh(nav_mesh, args->nav_region);
+ NavigationServer3D::get_singleton()->region_bake_navigation_mesh(nav_mesh, args->nav_region);
args->nav_region->call_deferred(SNAME("_bake_finished"), nav_mesh);
memdelete(args);
} else {
@@ -278,7 +278,7 @@ PackedStringArray NavigationRegion3D::get_configuration_warnings() const {
PackedStringArray warnings = Node::get_configuration_warnings();
if (is_visible_in_tree() && is_inside_tree()) {
- if (!navmesh.is_valid()) {
+ if (!navigation_mesh.is_valid()) {
warnings.push_back(RTR("A NavigationMesh resource must be set or created for this node to work."));
}
}
@@ -287,7 +287,7 @@ PackedStringArray NavigationRegion3D::get_configuration_warnings() const {
}
void NavigationRegion3D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_navigation_mesh", "navmesh"), &NavigationRegion3D::set_navigation_mesh);
+ ClassDB::bind_method(D_METHOD("set_navigation_mesh", "navigation_mesh"), &NavigationRegion3D::set_navigation_mesh);
ClassDB::bind_method(D_METHOD("get_navigation_mesh"), &NavigationRegion3D::get_navigation_mesh);
ClassDB::bind_method(D_METHOD("set_enabled", "enabled"), &NavigationRegion3D::set_enabled);
@@ -308,9 +308,9 @@ void NavigationRegion3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_travel_cost"), &NavigationRegion3D::get_travel_cost);
ClassDB::bind_method(D_METHOD("bake_navigation_mesh", "on_thread"), &NavigationRegion3D::bake_navigation_mesh, DEFVAL(true));
- ClassDB::bind_method(D_METHOD("_bake_finished", "nav_mesh"), &NavigationRegion3D::_bake_finished);
+ ClassDB::bind_method(D_METHOD("_bake_finished", "navigation_mesh"), &NavigationRegion3D::_bake_finished);
- ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "navmesh", PROPERTY_HINT_RESOURCE_TYPE, "NavigationMesh"), "set_navigation_mesh", "get_navigation_mesh");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "navigation_mesh", PROPERTY_HINT_RESOURCE_TYPE, "NavigationMesh"), "set_navigation_mesh", "get_navigation_mesh");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "enabled"), "set_enabled", "is_enabled");
ADD_PROPERTY(PropertyInfo(Variant::INT, "navigation_layers", PROPERTY_HINT_LAYERS_3D_NAVIGATION), "set_navigation_layers", "get_navigation_layers");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "enter_cost"), "set_enter_cost", "get_enter_cost");
@@ -320,6 +320,25 @@ void NavigationRegion3D::_bind_methods() {
ADD_SIGNAL(MethodInfo("bake_finished"));
}
+#ifndef DISABLE_DEPRECATED
+// Compatibility with earlier 4.0 betas.
+bool NavigationRegion3D::_set(const StringName &p_name, const Variant &p_value) {
+ if (p_name == "navmesh") {
+ set_navigation_mesh(p_value);
+ return true;
+ }
+ return false;
+}
+
+bool NavigationRegion3D::_get(const StringName &p_name, Variant &r_ret) const {
+ if (p_name == "navmesh") {
+ r_ret = get_navigation_mesh();
+ return true;
+ }
+ return false;
+}
+#endif // DISABLE_DEPRECATED
+
void NavigationRegion3D::_navigation_changed() {
update_gizmos();
update_configuration_warnings();
@@ -339,7 +358,9 @@ void NavigationRegion3D::_navigation_map_changed(RID p_map) {
NavigationRegion3D::NavigationRegion3D() {
set_notify_transform(true);
+
region = NavigationServer3D::get_singleton()->region_create();
+ NavigationServer3D::get_singleton()->region_set_owner_id(region, get_instance_id());
NavigationServer3D::get_singleton()->region_set_enter_cost(region, get_enter_cost());
NavigationServer3D::get_singleton()->region_set_travel_cost(region, get_travel_cost());
@@ -351,8 +372,8 @@ NavigationRegion3D::NavigationRegion3D() {
}
NavigationRegion3D::~NavigationRegion3D() {
- if (navmesh.is_valid()) {
- navmesh->disconnect("changed", callable_mp(this, &NavigationRegion3D::_navigation_changed));
+ if (navigation_mesh.is_valid()) {
+ navigation_mesh->disconnect("changed", callable_mp(this, &NavigationRegion3D::_navigation_changed));
}
NavigationServer3D::get_singleton()->free(region);
@@ -390,7 +411,7 @@ void NavigationRegion3D::_update_debug_mesh() {
return;
}
- if (!navmesh.is_valid()) {
+ if (!navigation_mesh.is_valid()) {
if (debug_instance.is_valid()) {
RS::get_singleton()->instance_set_visible(debug_instance, false);
}
@@ -410,12 +431,12 @@ void NavigationRegion3D::_update_debug_mesh() {
bool enabled_geometry_face_random_color = NavigationServer3D::get_singleton()->get_debug_navigation_enable_geometry_face_random_color();
bool enabled_edge_lines = NavigationServer3D::get_singleton()->get_debug_navigation_enable_edge_lines();
- Vector<Vector3> vertices = navmesh->get_vertices();
+ Vector<Vector3> vertices = navigation_mesh->get_vertices();
if (vertices.size() == 0) {
return;
}
- int polygon_count = navmesh->get_polygon_count();
+ int polygon_count = navigation_mesh->get_polygon_count();
if (polygon_count == 0) {
return;
}
@@ -448,7 +469,7 @@ void NavigationRegion3D::_update_debug_mesh() {
polygon_color.a = debug_navigation_geometry_face_color.a;
}
- Vector<int> polygon = navmesh->get_polygon(i);
+ Vector<int> polygon = navigation_mesh->get_polygon(i);
face_vertex_array.push_back(vertices[polygon[0]]);
face_vertex_array.push_back(vertices[polygon[1]]);
@@ -526,7 +547,7 @@ void NavigationRegion3D::_update_debug_edge_connections_mesh() {
return;
}
- if (!navmesh.is_valid()) {
+ if (!navigation_mesh.is_valid()) {
if (debug_edge_connections_instance.is_valid()) {
RS::get_singleton()->instance_set_visible(debug_edge_connections_instance, false);
}
diff --git a/scene/3d/navigation_region_3d.h b/scene/3d/navigation_region_3d.h
index 660538d314..811c0885a1 100644
--- a/scene/3d/navigation_region_3d.h
+++ b/scene/3d/navigation_region_3d.h
@@ -42,7 +42,7 @@ class NavigationRegion3D : public Node3D {
uint32_t navigation_layers = 1;
real_t enter_cost = 0.0;
real_t travel_cost = 1.0;
- Ref<NavigationMesh> navmesh;
+ Ref<NavigationMesh> navigation_mesh;
Thread bake_thread;
@@ -64,6 +64,11 @@ protected:
void _notification(int p_what);
static void _bind_methods();
+#ifndef DISABLE_DEPRECATED
+ bool _set(const StringName &p_name, const Variant &p_value);
+ bool _get(const StringName &p_name, Variant &r_ret) const;
+#endif // DISABLE_DEPRECATED
+
public:
void set_enabled(bool p_enabled);
bool is_enabled() const;
@@ -82,13 +87,13 @@ public:
void set_travel_cost(real_t p_travel_cost);
real_t get_travel_cost() const;
- void set_navigation_mesh(const Ref<NavigationMesh> &p_navmesh);
+ void set_navigation_mesh(const Ref<NavigationMesh> &p_navigation_mesh);
Ref<NavigationMesh> get_navigation_mesh() const;
/// Bakes the navigation mesh; once done, automatically
/// sets the new navigation mesh and emits a signal
void bake_navigation_mesh(bool p_on_thread);
- void _bake_finished(Ref<NavigationMesh> p_nav_mesh);
+ void _bake_finished(Ref<NavigationMesh> p_navigation_mesh);
PackedStringArray get_configuration_warnings() const override;
diff --git a/scene/3d/node_3d.cpp b/scene/3d/node_3d.cpp
index 1327bdd6e9..32bbea8ff3 100644
--- a/scene/3d/node_3d.cpp
+++ b/scene/3d/node_3d.cpp
@@ -188,7 +188,7 @@ void Node3D::_notification(int p_what) {
#ifdef TOOLS_ENABLED
if (Engine::get_singleton()->is_editor_hint() && get_tree()->is_node_being_edited(this)) {
- get_tree()->call_group_flags(SceneTree::GROUP_CALL_DEFERRED, SceneStringNames::get_singleton()->_spatial_editor_group, SceneStringNames::get_singleton()->_request_gizmo, this);
+ get_tree()->call_group_flags(SceneTree::GROUP_CALL_DEFERRED, SceneStringNames::get_singleton()->_spatial_editor_group, SNAME("_request_gizmo_for_id"), get_instance_id());
}
#endif
} break;
@@ -251,12 +251,22 @@ Vector3 Node3D::get_global_rotation() const {
return get_global_transform().get_basis().get_euler();
}
+Vector3 Node3D::get_global_rotation_degrees() const {
+ Vector3 radians = get_global_rotation();
+ return Vector3(Math::rad_to_deg(radians.x), Math::rad_to_deg(radians.y), Math::rad_to_deg(radians.z));
+}
+
void Node3D::set_global_rotation(const Vector3 &p_euler_rad) {
Transform3D transform = get_global_transform();
transform.basis = Basis::from_euler(p_euler_rad);
set_global_transform(transform);
}
+void Node3D::set_global_rotation_degrees(const Vector3 &p_euler_degrees) {
+ Vector3 radians(Math::deg_to_rad(p_euler_degrees.x), Math::deg_to_rad(p_euler_degrees.y), Math::deg_to_rad(p_euler_degrees.z));
+ set_global_rotation(radians);
+}
+
void Node3D::set_transform(const Transform3D &p_transform) {
data.local_transform = p_transform;
data.dirty = DIRTY_EULER_ROTATION_AND_SCALE; // Make rot/scale dirty.
@@ -440,6 +450,11 @@ void Node3D::set_rotation(const Vector3 &p_euler_rad) {
}
}
+void Node3D::set_rotation_degrees(const Vector3 &p_euler_degrees) {
+ Vector3 radians(Math::deg_to_rad(p_euler_degrees.x), Math::deg_to_rad(p_euler_degrees.y), Math::deg_to_rad(p_euler_degrees.z));
+ set_rotation(radians);
+}
+
void Node3D::set_scale(const Vector3 &p_scale) {
if (data.dirty & DIRTY_EULER_ROTATION_AND_SCALE) {
// Update rotation only if rotation and scale are dirty, as scale will be overridden.
@@ -467,6 +482,11 @@ Vector3 Node3D::get_rotation() const {
return data.euler_rotation;
}
+Vector3 Node3D::get_rotation_degrees() const {
+ Vector3 radians = get_rotation();
+ return Vector3(Math::rad_to_deg(radians.x), Math::rad_to_deg(radians.y), Math::rad_to_deg(radians.z));
+}
+
Vector3 Node3D::get_scale() const {
if (data.dirty & DIRTY_EULER_ROTATION_AND_SCALE) {
_update_rotation_and_scale();
@@ -482,7 +502,7 @@ void Node3D::update_gizmos() {
}
if (data.gizmos.is_empty()) {
- get_tree()->call_group_flags(SceneTree::GROUP_CALL_DEFERRED, SceneStringNames::get_singleton()->_spatial_editor_group, SceneStringNames::get_singleton()->_request_gizmo, this);
+ get_tree()->call_group_flags(SceneTree::GROUP_CALL_DEFERRED, SceneStringNames::get_singleton()->_spatial_editor_group, SNAME("_request_gizmo_for_id"), get_instance_id());
return;
}
if (data.gizmos_dirty) {
@@ -958,8 +978,10 @@ void Node3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_transform"), &Node3D::get_transform);
ClassDB::bind_method(D_METHOD("set_position", "position"), &Node3D::set_position);
ClassDB::bind_method(D_METHOD("get_position"), &Node3D::get_position);
- ClassDB::bind_method(D_METHOD("set_rotation", "euler"), &Node3D::set_rotation);
+ ClassDB::bind_method(D_METHOD("set_rotation", "euler_radians"), &Node3D::set_rotation);
ClassDB::bind_method(D_METHOD("get_rotation"), &Node3D::get_rotation);
+ ClassDB::bind_method(D_METHOD("set_rotation_degrees", "euler_degrees"), &Node3D::set_rotation_degrees);
+ ClassDB::bind_method(D_METHOD("get_rotation_degrees"), &Node3D::get_rotation_degrees);
ClassDB::bind_method(D_METHOD("set_rotation_order", "order"), &Node3D::set_rotation_order);
ClassDB::bind_method(D_METHOD("get_rotation_order"), &Node3D::get_rotation_order);
ClassDB::bind_method(D_METHOD("set_rotation_edit_mode", "edit_mode"), &Node3D::set_rotation_edit_mode);
@@ -975,8 +997,10 @@ void Node3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_global_transform"), &Node3D::get_global_transform);
ClassDB::bind_method(D_METHOD("set_global_position", "position"), &Node3D::set_global_position);
ClassDB::bind_method(D_METHOD("get_global_position"), &Node3D::get_global_position);
- ClassDB::bind_method(D_METHOD("set_global_rotation", "radians"), &Node3D::set_global_rotation);
+ ClassDB::bind_method(D_METHOD("set_global_rotation", "euler_radians"), &Node3D::set_global_rotation);
ClassDB::bind_method(D_METHOD("get_global_rotation"), &Node3D::get_global_rotation);
+ ClassDB::bind_method(D_METHOD("set_global_rotation_degrees", "euler_degrees"), &Node3D::set_global_rotation_degrees);
+ ClassDB::bind_method(D_METHOD("get_global_rotation_degrees"), &Node3D::get_global_rotation_degrees);
ClassDB::bind_method(D_METHOD("get_parent_node_3d"), &Node3D::get_parent_node_3d);
ClassDB::bind_method(D_METHOD("set_ignore_transform_notification", "enabled"), &Node3D::set_ignore_transform_notification);
@@ -1045,6 +1069,7 @@ void Node3D::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::TRANSFORM3D, "global_transform", PROPERTY_HINT_NONE, "suffix:m", PROPERTY_USAGE_NONE), "set_global_transform", "get_global_transform");
ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "position", PROPERTY_HINT_RANGE, "-99999,99999,0.001,or_greater,or_less,hide_slider,suffix:m", PROPERTY_USAGE_EDITOR), "set_position", "get_position");
ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "rotation", PROPERTY_HINT_RANGE, "-360,360,0.1,or_less,or_greater,radians", PROPERTY_USAGE_EDITOR), "set_rotation", "get_rotation");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "rotation_degrees", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NONE), "set_rotation_degrees", "get_rotation_degrees");
ADD_PROPERTY(PropertyInfo(Variant::QUATERNION, "quaternion", PROPERTY_HINT_HIDE_QUATERNION_EDIT, "", PROPERTY_USAGE_EDITOR), "set_quaternion", "get_quaternion");
ADD_PROPERTY(PropertyInfo(Variant::BASIS, "basis", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR), "set_basis", "get_basis");
ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "scale", PROPERTY_HINT_LINK, "", PROPERTY_USAGE_EDITOR), "set_scale", "get_scale");
@@ -1054,6 +1079,7 @@ void Node3D::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "global_position", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NONE), "set_global_position", "get_global_position");
ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "global_rotation", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NONE), "set_global_rotation", "get_global_rotation");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "global_rotation_degrees", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NONE), "set_global_rotation_degrees", "get_global_rotation_degrees");
ADD_GROUP("Visibility", "");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "visible"), "set_visible", "is_visible");
ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "visibility_parent", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "GeometryInstance3D"), "set_visibility_parent", "get_visibility_parent");
diff --git a/scene/3d/node_3d.h b/scene/3d/node_3d.h
index 76c1e3e22c..9558a978fd 100644
--- a/scene/3d/node_3d.h
+++ b/scene/3d/node_3d.h
@@ -172,19 +172,23 @@ public:
void set_rotation_order(EulerOrder p_order);
void set_rotation(const Vector3 &p_euler_rad);
+ void set_rotation_degrees(const Vector3 &p_euler_degrees);
void set_scale(const Vector3 &p_scale);
void set_global_position(const Vector3 &p_position);
void set_global_rotation(const Vector3 &p_euler_rad);
+ void set_global_rotation_degrees(const Vector3 &p_euler_degrees);
Vector3 get_position() const;
EulerOrder get_rotation_order() const;
Vector3 get_rotation() const;
+ Vector3 get_rotation_degrees() const;
Vector3 get_scale() const;
Vector3 get_global_position() const;
Vector3 get_global_rotation() const;
+ Vector3 get_global_rotation_degrees() const;
void set_transform(const Transform3D &p_transform);
void set_basis(const Basis &p_basis);
diff --git a/scene/3d/path_3d.cpp b/scene/3d/path_3d.cpp
index ab4cba86fb..02ab297d8e 100644
--- a/scene/3d/path_3d.cpp
+++ b/scene/3d/path_3d.cpp
@@ -182,125 +182,31 @@ void PathFollow3D::_update_transform(bool p_update_xyz_rot) {
if (bl == 0.0) {
return;
}
- real_t bi = c->get_bake_interval();
- real_t o_next = progress + bi;
- real_t o_prev = progress - bi;
-
- if (loop) {
- o_next = Math::fposmod(o_next, bl);
- o_prev = Math::fposmod(o_prev, bl);
- } else if (rotation_mode == ROTATION_ORIENTED) {
- if (o_next >= bl) {
- o_next = bl;
- }
- if (o_prev <= 0) {
- o_prev = 0;
- }
- }
-
- Vector3 pos = c->sample_baked(progress, cubic);
- Transform3D t = get_transform();
- // Vector3 pos_offset = Vector3(h_offset, v_offset, 0); not used in all cases
- // will be replaced by "Vector3(h_offset, v_offset, 0)" where it was formerly used
-
- if (rotation_mode == ROTATION_ORIENTED) {
- Vector3 forward = c->sample_baked(o_next, cubic) - pos;
-
- // Try with the previous position
- if (forward.length_squared() < CMP_EPSILON2) {
- forward = pos - c->sample_baked(o_prev, cubic);
- }
-
- if (forward.length_squared() < CMP_EPSILON2) {
- forward = Vector3(0, 0, 1);
- } else {
- forward.normalize();
- }
-
- Vector3 up = c->sample_baked_up_vector(progress, true);
- if (o_next < progress) {
- Vector3 up1 = c->sample_baked_up_vector(o_next, true);
- Vector3 axis = up.cross(up1);
-
- if (axis.length_squared() < CMP_EPSILON2) {
- axis = forward;
- } else {
- axis.normalize();
- }
-
- up.rotate(axis, up.angle_to(up1) * 0.5f);
- }
-
- Vector3 scale = t.basis.get_scale();
- Vector3 sideways = up.cross(forward).normalized();
- up = forward.cross(sideways).normalized();
-
- t.basis.set_columns(sideways, up, forward);
- t.basis.scale_local(scale);
-
- t.origin = pos + sideways * h_offset + up * v_offset;
- } else if (rotation_mode != ROTATION_NONE) {
- // perform parallel transport
- //
- // see C. Dougan, The Parallel Transport Frame, Game Programming Gems 2 for example
- // for a discussion about why not Frenet frame.
+ Transform3D t;
+ if (rotation_mode == ROTATION_NONE) {
+ Vector3 pos = c->sample_baked(progress, cubic);
t.origin = pos;
- if (p_update_xyz_rot && prev_offset != progress) { // Only update rotation if some parameter has changed - i.e. not on addition to scene tree.
- real_t sample_distance = bi * 0.01;
- Vector3 t_prev_pos_a = c->sample_baked(prev_offset - sample_distance, cubic);
- Vector3 t_prev_pos_b = c->sample_baked(prev_offset + sample_distance, cubic);
- Vector3 t_cur_pos_a = c->sample_baked(progress - sample_distance, cubic);
- Vector3 t_cur_pos_b = c->sample_baked(progress + sample_distance, cubic);
- Vector3 t_prev = (t_prev_pos_a - t_prev_pos_b).normalized();
- Vector3 t_cur = (t_cur_pos_a - t_cur_pos_b).normalized();
-
- Vector3 axis = t_prev.cross(t_cur);
- real_t dot = t_prev.dot(t_cur);
- real_t angle = Math::acos(CLAMP(dot, -1, 1));
-
- if (likely(!Math::is_zero_approx(angle))) {
- if (rotation_mode == ROTATION_Y) {
- // assuming we're referring to global Y-axis. is this correct?
- axis.x = 0;
- axis.z = 0;
- } else if (rotation_mode == ROTATION_XY) {
- axis.z = 0;
- } else if (rotation_mode == ROTATION_XYZ) {
- // all components are allowed
- }
+ } else {
+ t = c->sample_baked_with_rotation(progress, cubic, false);
+ Vector3 forward = t.basis.get_column(2); // Retain tangent for applying tilt
+ t = PathFollow3D::correct_posture(t, rotation_mode);
- if (likely(!Math::is_zero_approx(axis.length()))) {
- t.rotate_basis(axis.normalized(), angle);
- }
- }
+ // Apply tilt *after* correct_posture
+ if (tilt_enabled) {
+ const real_t tilt = c->sample_baked_tilt(progress);
- // do the additional tilting
- real_t tilt_angle = c->sample_baked_tilt(progress);
- Vector3 tilt_axis = t_cur; // not sure what tilt is supposed to do, is this correct??
-
- if (likely(!Math::is_zero_approx(Math::abs(tilt_angle)))) {
- if (rotation_mode == ROTATION_Y) {
- tilt_axis.x = 0;
- tilt_axis.z = 0;
- } else if (rotation_mode == ROTATION_XY) {
- tilt_axis.z = 0;
- } else if (rotation_mode == ROTATION_XYZ) {
- // all components are allowed
- }
-
- if (likely(!Math::is_zero_approx(tilt_axis.length()))) {
- t.rotate_basis(tilt_axis.normalized(), tilt_angle);
- }
- }
+ const Basis twist(forward, tilt);
+ t.basis = twist * t.basis;
}
-
- t.translate_local(Vector3(h_offset, v_offset, 0));
- } else {
- t.origin = pos + Vector3(h_offset, v_offset, 0);
}
+ Vector3 scale = get_transform().basis.get_scale();
+
+ t.translate_local(Vector3(h_offset, v_offset, 0));
+ t.basis.scale_local(scale);
+
set_transform(t);
}
@@ -358,6 +264,38 @@ PackedStringArray PathFollow3D::get_configuration_warnings() const {
return warnings;
}
+Transform3D PathFollow3D::correct_posture(Transform3D p_transform, PathFollow3D::RotationMode p_rotation_mode) {
+ Transform3D t = p_transform;
+
+ // Modify frame according to rotation mode.
+ if (p_rotation_mode == PathFollow3D::ROTATION_NONE) {
+ // Clear rotation.
+ t.basis = Basis();
+ } else if (p_rotation_mode == PathFollow3D::ROTATION_ORIENTED) {
+ // Y-axis always straight up.
+ Vector3 up(0.0, 1.0, 0.0);
+ Vector3 forward = t.basis.get_column(2);
+
+ t.basis = Basis::looking_at(-forward, up);
+ } else {
+ // Lock some euler axes.
+ Vector3 euler = t.basis.get_euler_normalized(EulerOrder::YXZ);
+ if (p_rotation_mode == PathFollow3D::ROTATION_Y) {
+ // Only Y-axis allowed.
+ euler[0] = 0;
+ euler[2] = 0;
+ } else if (p_rotation_mode == PathFollow3D::ROTATION_XY) {
+ // XY allowed.
+ euler[2] = 0;
+ }
+
+ Basis locked = Basis::from_euler(euler, EulerOrder::YXZ);
+ t.basis = locked;
+ }
+
+ return t;
+}
+
void PathFollow3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_progress", "progress"), &PathFollow3D::set_progress);
ClassDB::bind_method(D_METHOD("get_progress"), &PathFollow3D::get_progress);
@@ -380,6 +318,11 @@ void PathFollow3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_loop", "loop"), &PathFollow3D::set_loop);
ClassDB::bind_method(D_METHOD("has_loop"), &PathFollow3D::has_loop);
+ ClassDB::bind_method(D_METHOD("set_tilt_enabled", "enabled"), &PathFollow3D::set_tilt_enabled);
+ ClassDB::bind_method(D_METHOD("is_tilt_enabled"), &PathFollow3D::is_tilt_enabled);
+
+ ClassDB::bind_static_method("PathFollow3D", D_METHOD("correct_posture", "transform", "rotation_mode"), &PathFollow3D::correct_posture);
+
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "progress", PROPERTY_HINT_RANGE, "0,10000,0.01,or_less,or_greater,suffix:m"), "set_progress", "get_progress");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "progress_ratio", PROPERTY_HINT_RANGE, "0,1,0.0001,or_less,or_greater", PROPERTY_USAGE_EDITOR), "set_progress_ratio", "get_progress_ratio");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "h_offset", PROPERTY_HINT_NONE, "suffix:m"), "set_h_offset", "get_h_offset");
@@ -387,6 +330,7 @@ void PathFollow3D::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::INT, "rotation_mode", PROPERTY_HINT_ENUM, "None,Y,XY,XYZ,Oriented"), "set_rotation_mode", "get_rotation_mode");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "cubic_interp"), "set_cubic_interpolation", "get_cubic_interpolation");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "loop"), "set_loop", "has_loop");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "tilt_enabled"), "set_tilt_enabled", "is_tilt_enabled");
BIND_ENUM_CONSTANT(ROTATION_NONE);
BIND_ENUM_CONSTANT(ROTATION_Y);
@@ -397,7 +341,6 @@ void PathFollow3D::_bind_methods() {
void PathFollow3D::set_progress(real_t p_progress) {
ERR_FAIL_COND(!isfinite(p_progress));
- prev_offset = progress;
progress = p_progress;
if (path) {
@@ -409,8 +352,6 @@ void PathFollow3D::set_progress(real_t p_progress) {
if (!Math::is_zero_approx(p_progress) && Math::is_zero_approx(progress)) {
progress = path_length;
}
- } else {
- progress = CLAMP(progress, 0, path_length);
}
}
@@ -476,3 +417,11 @@ void PathFollow3D::set_loop(bool p_loop) {
bool PathFollow3D::has_loop() const {
return loop;
}
+
+void PathFollow3D::set_tilt_enabled(bool p_enable) {
+ tilt_enabled = p_enable;
+}
+
+bool PathFollow3D::is_tilt_enabled() const {
+ return tilt_enabled;
+}
diff --git a/scene/3d/path_3d.h b/scene/3d/path_3d.h
index b161b12185..9d5f694247 100644
--- a/scene/3d/path_3d.h
+++ b/scene/3d/path_3d.h
@@ -72,14 +72,16 @@ public:
ROTATION_ORIENTED
};
+ static Transform3D correct_posture(Transform3D p_transform, PathFollow3D::RotationMode p_rotation_mode);
+
private:
Path3D *path = nullptr;
- real_t prev_offset = 0.0; // Offset during the last _update_transform.
real_t progress = 0.0;
real_t h_offset = 0.0;
real_t v_offset = 0.0;
bool cubic = true;
bool loop = true;
+ bool tilt_enabled = true;
RotationMode rotation_mode = ROTATION_XYZ;
void _update_transform(bool p_update_xyz_rot = true);
@@ -106,6 +108,9 @@ public:
void set_loop(bool p_loop);
bool has_loop() const;
+ void set_tilt_enabled(bool p_enable);
+ bool is_tilt_enabled() const;
+
void set_rotation_mode(RotationMode p_rotation_mode);
RotationMode get_rotation_mode() const;
diff --git a/scene/3d/physics_body_3d.cpp b/scene/3d/physics_body_3d.cpp
index d9fa37ce74..d29f337fc8 100644
--- a/scene/3d/physics_body_3d.cpp
+++ b/scene/3d/physics_body_3d.cpp
@@ -34,8 +34,8 @@
#include "scene/scene_string_names.h"
void PhysicsBody3D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("move_and_collide", "distance", "test_only", "safe_margin", "recovery_as_collision", "max_collisions"), &PhysicsBody3D::_move, DEFVAL(false), DEFVAL(0.001), DEFVAL(false), DEFVAL(1));
- ClassDB::bind_method(D_METHOD("test_move", "from", "distance", "collision", "safe_margin", "recovery_as_collision", "max_collisions"), &PhysicsBody3D::test_move, DEFVAL(Variant()), DEFVAL(0.001), DEFVAL(false), DEFVAL(1));
+ ClassDB::bind_method(D_METHOD("move_and_collide", "motion", "test_only", "safe_margin", "recovery_as_collision", "max_collisions"), &PhysicsBody3D::_move, DEFVAL(false), DEFVAL(0.001), DEFVAL(false), DEFVAL(1));
+ ClassDB::bind_method(D_METHOD("test_move", "from", "motion", "collision", "safe_margin", "recovery_as_collision", "max_collisions"), &PhysicsBody3D::test_move, DEFVAL(Variant()), DEFVAL(0.001), DEFVAL(false), DEFVAL(1));
ClassDB::bind_method(D_METHOD("set_axis_lock", "axis", "lock"), &PhysicsBody3D::set_axis_lock);
ClassDB::bind_method(D_METHOD("get_axis_lock", "axis"), &PhysicsBody3D::get_axis_lock);
@@ -80,19 +80,19 @@ TypedArray<PhysicsBody3D> PhysicsBody3D::get_collision_exceptions() {
void PhysicsBody3D::add_collision_exception_with(Node *p_node) {
ERR_FAIL_NULL(p_node);
CollisionObject3D *collision_object = Object::cast_to<CollisionObject3D>(p_node);
- ERR_FAIL_COND_MSG(!collision_object, "Collision exception only works between two CollisionObject3Ds.");
+ ERR_FAIL_COND_MSG(!collision_object, "Collision exception only works between two nodes that inherit from CollisionObject3D (such as Area3D or PhysicsBody3D).");
PhysicsServer3D::get_singleton()->body_add_collision_exception(get_rid(), collision_object->get_rid());
}
void PhysicsBody3D::remove_collision_exception_with(Node *p_node) {
ERR_FAIL_NULL(p_node);
CollisionObject3D *collision_object = Object::cast_to<CollisionObject3D>(p_node);
- ERR_FAIL_COND_MSG(!collision_object, "Collision exception only works between two CollisionObject3Ds.");
+ ERR_FAIL_COND_MSG(!collision_object, "Collision exception only works between two nodes that inherit from CollisionObject3D (such as Area3D or PhysicsBody3D).");
PhysicsServer3D::get_singleton()->body_remove_collision_exception(get_rid(), collision_object->get_rid());
}
-Ref<KinematicCollision3D> PhysicsBody3D::_move(const Vector3 &p_distance, bool p_test_only, real_t p_margin, bool p_recovery_as_collision, int p_max_collisions) {
- PhysicsServer3D::MotionParameters parameters(get_global_transform(), p_distance, p_margin);
+Ref<KinematicCollision3D> PhysicsBody3D::_move(const Vector3 &p_motion, bool p_test_only, real_t p_margin, bool p_recovery_as_collision, int p_max_collisions) {
+ PhysicsServer3D::MotionParameters parameters(get_global_transform(), p_motion, p_margin);
parameters.max_collisions = p_max_collisions;
parameters.recovery_as_collision = p_recovery_as_collision;
@@ -169,7 +169,7 @@ bool PhysicsBody3D::move_and_collide(const PhysicsServer3D::MotionParameters &p_
return colliding;
}
-bool PhysicsBody3D::test_move(const Transform3D &p_from, const Vector3 &p_distance, const Ref<KinematicCollision3D> &r_collision, real_t p_margin, bool p_recovery_as_collision, int p_max_collisions) {
+bool PhysicsBody3D::test_move(const Transform3D &p_from, const Vector3 &p_motion, const Ref<KinematicCollision3D> &r_collision, real_t p_margin, bool p_recovery_as_collision, int p_max_collisions) {
ERR_FAIL_COND_V(!is_inside_tree(), false);
PhysicsServer3D::MotionResult *r = nullptr;
@@ -181,7 +181,7 @@ bool PhysicsBody3D::test_move(const Transform3D &p_from, const Vector3 &p_distan
r = &temp_result;
}
- PhysicsServer3D::MotionParameters parameters(p_from, p_distance, p_margin);
+ PhysicsServer3D::MotionParameters parameters(p_from, p_motion, p_margin);
parameters.recovery_as_collision = p_recovery_as_collision;
return PhysicsServer3D::get_singleton()->body_test_motion(get_rid(), parameters, r);
diff --git a/scene/3d/physics_body_3d.h b/scene/3d/physics_body_3d.h
index 4b874b91d9..36b7ce774c 100644
--- a/scene/3d/physics_body_3d.h
+++ b/scene/3d/physics_body_3d.h
@@ -50,11 +50,11 @@ protected:
uint16_t locked_axis = 0;
- Ref<KinematicCollision3D> _move(const Vector3 &p_distance, bool p_test_only = false, real_t p_margin = 0.001, bool p_recovery_as_collision = false, int p_max_collisions = 1);
+ Ref<KinematicCollision3D> _move(const Vector3 &p_motion, bool p_test_only = false, real_t p_margin = 0.001, bool p_recovery_as_collision = false, int p_max_collisions = 1);
public:
bool move_and_collide(const PhysicsServer3D::MotionParameters &p_parameters, PhysicsServer3D::MotionResult &r_result, bool p_test_only = false, bool p_cancel_sliding = true);
- bool test_move(const Transform3D &p_from, const Vector3 &p_distance, const Ref<KinematicCollision3D> &r_collision = Ref<KinematicCollision3D>(), real_t p_margin = 0.001, bool p_recovery_as_collision = false, int p_max_collisions = 1);
+ bool test_move(const Transform3D &p_from, const Vector3 &p_motion, const Ref<KinematicCollision3D> &r_collision = Ref<KinematicCollision3D>(), real_t p_margin = 0.001, bool p_recovery_as_collision = false, int p_max_collisions = 1);
void set_axis_lock(PhysicsServer3D::BodyAxis p_axis, bool p_lock);
bool get_axis_lock(PhysicsServer3D::BodyAxis p_axis) const;
diff --git a/scene/3d/skeleton_3d.cpp b/scene/3d/skeleton_3d.cpp
index a1f962c690..b205c2cde0 100644
--- a/scene/3d/skeleton_3d.cpp
+++ b/scene/3d/skeleton_3d.cpp
@@ -541,7 +541,7 @@ void Skeleton3D::set_bone_name(int p_bone, const String &p_name) {
for (int i = 0; i < bone_size; i++) {
if (i != p_bone) {
- ERR_FAIL_COND(bones[i].name == p_name);
+ ERR_FAIL_COND_MSG(bones[i].name == p_name, "Skeleton3D: '" + get_name() + "', bone name: '" + p_name + "' is already exist.");
}
}
diff --git a/scene/3d/soft_body_3d.cpp b/scene/3d/soft_body_3d.cpp
index 83e3369423..1814baa9e9 100644
--- a/scene/3d/soft_body_3d.cpp
+++ b/scene/3d/soft_body_3d.cpp
@@ -607,14 +607,14 @@ TypedArray<PhysicsBody3D> SoftBody3D::get_collision_exceptions() {
void SoftBody3D::add_collision_exception_with(Node *p_node) {
ERR_FAIL_NULL(p_node);
CollisionObject3D *collision_object = Object::cast_to<CollisionObject3D>(p_node);
- ERR_FAIL_COND_MSG(!collision_object, "Collision exception only works between two CollisionObject3Ds.");
+ ERR_FAIL_COND_MSG(!collision_object, "Collision exception only works between two nodes that inherit from CollisionObject3D (such as Area3D or PhysicsBody3D).");
PhysicsServer3D::get_singleton()->soft_body_add_collision_exception(physics_rid, collision_object->get_rid());
}
void SoftBody3D::remove_collision_exception_with(Node *p_node) {
ERR_FAIL_NULL(p_node);
CollisionObject3D *collision_object = Object::cast_to<CollisionObject3D>(p_node);
- ERR_FAIL_COND_MSG(!collision_object, "Collision exception only works between two CollisionObject3Ds.");
+ ERR_FAIL_COND_MSG(!collision_object, "Collision exception only works between two nodes that inherit from CollisionObject3D (such as Area3D or PhysicsBody3D).");
PhysicsServer3D::get_singleton()->soft_body_remove_collision_exception(physics_rid, collision_object->get_rid());
}
diff --git a/scene/3d/spring_arm_3d.cpp b/scene/3d/spring_arm_3d.cpp
index f855fce318..6d8ce06524 100644
--- a/scene/3d/spring_arm_3d.cpp
+++ b/scene/3d/spring_arm_3d.cpp
@@ -31,6 +31,7 @@
#include "spring_arm_3d.h"
#include "scene/3d/camera_3d.h"
+#include "scene/resources/shape_3d.h"
void SpringArm3D::_notification(int p_what) {
switch (p_what) {
diff --git a/scene/3d/sprite_3d.cpp b/scene/3d/sprite_3d.cpp
index d69953fee5..e488ff3059 100644
--- a/scene/3d/sprite_3d.cpp
+++ b/scene/3d/sprite_3d.cpp
@@ -191,9 +191,7 @@ void SpriteBase3D::draw_texture_rect(Ref<Texture2D> p_texture, Rect2 p_dst_rect,
uint32_t v_normal;
{
- Vector3 n = normal * Vector3(0.5, 0.5, 0.5) + Vector3(0.5, 0.5, 0.5);
-
- Vector2 res = n.octahedron_encode();
+ Vector2 res = normal.octahedron_encode();
uint32_t value = 0;
value |= (uint16_t)CLAMP(res.x * 65535, 0, 65535);
value |= (uint16_t)CLAMP(res.y * 65535, 0, 65535) << 16;
diff --git a/scene/3d/visual_instance_3d.cpp b/scene/3d/visual_instance_3d.cpp
index 09d31b1ca0..3b21f5c03a 100644
--- a/scene/3d/visual_instance_3d.cpp
+++ b/scene/3d/visual_instance_3d.cpp
@@ -30,6 +30,7 @@
#include "visual_instance_3d.h"
+#include "core/core_string_names.h"
#include "scene/scene_string_names.h"
AABB VisualInstance3D::get_aabb() const {
@@ -74,10 +75,6 @@ RID VisualInstance3D::get_instance() const {
return instance;
}
-RID VisualInstance3D::_get_visual_instance_rid() const {
- return instance;
-}
-
void VisualInstance3D::set_layer_mask(uint32_t p_mask) {
layers = p_mask;
RenderingServer::get_singleton()->instance_set_layer_mask(instance, p_mask);
@@ -105,8 +102,25 @@ bool VisualInstance3D::get_layer_mask_value(int p_layer_number) const {
return layers & (1 << (p_layer_number - 1));
}
+void VisualInstance3D::set_sorting_offset(float p_offset) {
+ sorting_offset = p_offset;
+ RenderingServer::get_singleton()->instance_set_pivot_data(instance, sorting_offset, sorting_use_aabb_center);
+}
+
+float VisualInstance3D::get_sorting_offset() const {
+ return sorting_offset;
+}
+
+void VisualInstance3D::set_sorting_use_aabb_center(bool p_enabled) {
+ sorting_use_aabb_center = p_enabled;
+ RenderingServer::get_singleton()->instance_set_pivot_data(instance, sorting_offset, sorting_use_aabb_center);
+}
+
+bool VisualInstance3D::is_sorting_use_aabb_center() const {
+ return sorting_use_aabb_center;
+}
+
void VisualInstance3D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_get_visual_instance_rid"), &VisualInstance3D::_get_visual_instance_rid);
ClassDB::bind_method(D_METHOD("set_base", "base"), &VisualInstance3D::set_base);
ClassDB::bind_method(D_METHOD("get_base"), &VisualInstance3D::get_base);
ClassDB::bind_method(D_METHOD("get_instance"), &VisualInstance3D::get_instance);
@@ -114,9 +128,17 @@ void VisualInstance3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_layer_mask"), &VisualInstance3D::get_layer_mask);
ClassDB::bind_method(D_METHOD("set_layer_mask_value", "layer_number", "value"), &VisualInstance3D::set_layer_mask_value);
ClassDB::bind_method(D_METHOD("get_layer_mask_value", "layer_number"), &VisualInstance3D::get_layer_mask_value);
+ ClassDB::bind_method(D_METHOD("set_sorting_offset", "offset"), &VisualInstance3D::set_sorting_offset);
+ ClassDB::bind_method(D_METHOD("get_sorting_offset"), &VisualInstance3D::get_sorting_offset);
+ ClassDB::bind_method(D_METHOD("set_sorting_use_aabb_center", "enabled"), &VisualInstance3D::set_sorting_use_aabb_center);
+ ClassDB::bind_method(D_METHOD("is_sorting_use_aabb_center"), &VisualInstance3D::is_sorting_use_aabb_center);
GDVIRTUAL_BIND(_get_aabb);
ADD_PROPERTY(PropertyInfo(Variant::INT, "layers", PROPERTY_HINT_LAYERS_3D_RENDER), "set_layer_mask", "get_layer_mask");
+
+ ADD_GROUP("Sorting", "sorting_");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "sorting_offset"), "set_sorting_offset", "get_sorting_offset");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "sorting_use_aabb_center"), "set_sorting_use_aabb_center", "is_sorting_use_aabb_center");
}
void VisualInstance3D::set_base(const RID &p_base) {
@@ -139,7 +161,13 @@ VisualInstance3D::~VisualInstance3D() {
}
void GeometryInstance3D::set_material_override(const Ref<Material> &p_material) {
+ if (material_override.is_valid()) {
+ material_override->disconnect(CoreStringNames::get_singleton()->property_list_changed, callable_mp((Object *)this, &Object::notify_property_list_changed));
+ }
material_override = p_material;
+ if (material_override.is_valid()) {
+ material_override->connect(CoreStringNames::get_singleton()->property_list_changed, callable_mp((Object *)this, &Object::notify_property_list_changed));
+ }
RS::get_singleton()->instance_geometry_set_material_override(get_instance(), p_material.is_valid() ? p_material->get_rid() : RID());
}
@@ -216,15 +244,20 @@ GeometryInstance3D::VisibilityRangeFadeMode GeometryInstance3D::get_visibility_r
}
const StringName *GeometryInstance3D::_instance_uniform_get_remap(const StringName p_name) const {
- StringName *r = instance_uniform_property_remap.getptr(p_name);
+ StringName *r = instance_shader_parameter_property_remap.getptr(p_name);
if (!r) {
String s = p_name;
+#ifndef DISABLE_DEPRECATED
if (s.begins_with("shader_uniforms/")) {
- StringName name = s.replace("shader_uniforms/", "");
- instance_uniform_property_remap[p_name] = name;
- return instance_uniform_property_remap.getptr(p_name);
+ s = s.replace("shader_uniforms/", "instance_shader_parameters/");
+ }
+#endif // DISABLE_DEPRECATED
+ if (s.begins_with("instance_shader_parameters/")) {
+ StringName pname = StringName(s);
+ StringName name = s.replace("instance_shader_parameters/", "");
+ instance_shader_parameter_property_remap[pname] = name;
+ return instance_shader_parameter_property_remap.getptr(pname);
}
-
return nullptr;
}
@@ -247,7 +280,7 @@ bool GeometryInstance3D::_set(const StringName &p_name, const Variant &p_value)
set_gi_mode(GI_MODE_DYNAMIC);
return true;
}
-#endif
+#endif // DISABLE_DEPRECATED
return false;
}
@@ -270,13 +303,13 @@ void GeometryInstance3D::_get_property_list(List<PropertyInfo> *p_list) const {
if (def_value.get_type() != Variant::NIL) {
has_def_value = true;
}
- if (instance_uniforms.has(pi.name)) {
+ if (instance_shader_parameters.has(pi.name)) {
pi.usage = PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_STORAGE | (has_def_value ? (PROPERTY_USAGE_CHECKABLE | PROPERTY_USAGE_CHECKED) : PROPERTY_USAGE_NONE);
} else {
pi.usage = PROPERTY_USAGE_EDITOR | (has_def_value ? PROPERTY_USAGE_CHECKABLE : PROPERTY_USAGE_NONE); //do not save if not changed
}
- pi.name = "shader_uniforms/" + pi.name;
+ pi.name = "instance_shader_parameters/" + pi.name;
p_list->push_back(pi);
}
}
@@ -315,9 +348,9 @@ void GeometryInstance3D::set_instance_shader_parameter(const StringName &p_name,
if (p_value.get_type() == Variant::NIL) {
Variant def_value = RS::get_singleton()->instance_geometry_get_shader_parameter_default_value(get_instance(), p_name);
RS::get_singleton()->instance_geometry_set_shader_parameter(get_instance(), p_name, def_value);
- instance_uniforms.erase(p_value);
+ instance_shader_parameters.erase(p_value);
} else {
- instance_uniforms[p_name] = p_value;
+ instance_shader_parameters[p_name] = p_value;
if (p_value.get_type() == Variant::OBJECT) {
RID tex_id = p_value;
RS::get_singleton()->instance_geometry_set_shader_parameter(get_instance(), p_name, tex_id);
@@ -331,8 +364,16 @@ Variant GeometryInstance3D::get_instance_shader_parameter(const StringName &p_na
return RS::get_singleton()->instance_geometry_get_shader_parameter(get_instance(), p_name);
}
-void GeometryInstance3D::set_custom_aabb(AABB aabb) {
- RS::get_singleton()->instance_set_custom_aabb(get_instance(), aabb);
+void GeometryInstance3D::set_custom_aabb(AABB p_aabb) {
+ if (p_aabb == custom_aabb) {
+ return;
+ }
+ custom_aabb = p_aabb;
+ RS::get_singleton()->instance_set_custom_aabb(get_instance(), custom_aabb);
+}
+
+AABB GeometryInstance3D::get_custom_aabb() const {
+ return custom_aabb;
}
void GeometryInstance3D::set_lightmap_scale(LightmapScale p_scale) {
@@ -442,6 +483,7 @@ void GeometryInstance3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("is_ignoring_occlusion_culling"), &GeometryInstance3D::is_ignoring_occlusion_culling);
ClassDB::bind_method(D_METHOD("set_custom_aabb", "aabb"), &GeometryInstance3D::set_custom_aabb);
+ ClassDB::bind_method(D_METHOD("get_custom_aabb"), &GeometryInstance3D::get_custom_aabb);
ClassDB::bind_method(D_METHOD("get_aabb"), &GeometryInstance3D::get_aabb);
@@ -451,6 +493,7 @@ void GeometryInstance3D::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "transparency", PROPERTY_HINT_RANGE, "0.0,1.0,0.01"), "set_transparency", "get_transparency");
ADD_PROPERTY(PropertyInfo(Variant::INT, "cast_shadow", PROPERTY_HINT_ENUM, "Off,On,Double-Sided,Shadows Only"), "set_cast_shadows_setting", "get_cast_shadows_setting");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "extra_cull_margin", PROPERTY_HINT_RANGE, "0,16384,0.01,suffix:m"), "set_extra_cull_margin", "get_extra_cull_margin");
+ ADD_PROPERTY(PropertyInfo(Variant::AABB, "custom_aabb", PROPERTY_HINT_NONE, "suffix:m"), "set_custom_aabb", "get_custom_aabb");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "lod_bias", PROPERTY_HINT_RANGE, "0.001,128,0.001"), "set_lod_bias", "get_lod_bias");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "ignore_occlusion_culling"), "set_ignore_occlusion_culling", "is_ignoring_occlusion_culling");
diff --git a/scene/3d/visual_instance_3d.h b/scene/3d/visual_instance_3d.h
index c9a25d9705..2d107f61d2 100644
--- a/scene/3d/visual_instance_3d.h
+++ b/scene/3d/visual_instance_3d.h
@@ -39,8 +39,8 @@ class VisualInstance3D : public Node3D {
RID base;
RID instance;
uint32_t layers = 1;
-
- RID _get_visual_instance_rid() const;
+ float sorting_offset = 0.0;
+ bool sorting_use_aabb_center = true;
protected:
void _update_visibility();
@@ -69,6 +69,12 @@ public:
void set_layer_mask_value(int p_layer_number, bool p_enable);
bool get_layer_mask_value(int p_layer_number) const;
+ void set_sorting_offset(float p_offset);
+ float get_sorting_offset() const;
+
+ void set_sorting_use_aabb_center(bool p_enabled);
+ bool is_sorting_use_aabb_center() const;
+
VisualInstance3D();
~VisualInstance3D();
};
@@ -119,10 +125,11 @@ private:
float lod_bias = 1.0;
- mutable HashMap<StringName, Variant> instance_uniforms;
- mutable HashMap<StringName, StringName> instance_uniform_property_remap;
+ mutable HashMap<StringName, Variant> instance_shader_parameters;
+ mutable HashMap<StringName, StringName> instance_shader_parameter_property_remap;
float extra_cull_margin = 0.0;
+ AABB custom_aabb;
LightmapScale lightmap_scale = LIGHTMAP_SCALE_1X;
GIMode gi_mode = GI_MODE_STATIC;
bool ignore_occlusion_culling = false;
@@ -179,7 +186,8 @@ public:
void set_instance_shader_parameter(const StringName &p_name, const Variant &p_value);
Variant get_instance_shader_parameter(const StringName &p_name) const;
- void set_custom_aabb(AABB aabb);
+ void set_custom_aabb(AABB p_aabb);
+ AABB get_custom_aabb() const;
void set_ignore_occlusion_culling(bool p_enabled);
bool is_ignoring_occlusion_culling();
diff --git a/scene/3d/xr_nodes.cpp b/scene/3d/xr_nodes.cpp
index ca7d1dfc1d..05fc73306c 100644
--- a/scene/3d/xr_nodes.cpp
+++ b/scene/3d/xr_nodes.cpp
@@ -627,7 +627,9 @@ void XROrigin3D::set_world_scale(real_t p_world_scale) {
xr_server->set_world_scale(p_world_scale);
}
-void XROrigin3D::set_current(bool p_enabled) {
+void XROrigin3D::_set_current(bool p_enabled, bool p_update_others) {
+ // We run this logic even if current already equals p_enabled as we may have set this previously before we entered our tree.
+ // This is then called a second time on NOTIFICATION_ENTER_TREE where we actually process activating this origin node.
current = p_enabled;
if (!is_inside_tree() || Engine::get_singleton()->is_editor_hint()) {
@@ -638,30 +640,38 @@ void XROrigin3D::set_current(bool p_enabled) {
set_notify_local_transform(current);
set_notify_transform(current);
+ // update XRServer with our current position
if (current) {
- for (int i = 0; i < origin_nodes.size(); i++) {
- if (origin_nodes[i] != this) {
- origin_nodes[i]->set_current(false);
- }
- }
-
- // update XRServer with our current position
XRServer *xr_server = XRServer::get_singleton();
ERR_FAIL_NULL(xr_server);
xr_server->set_world_origin(get_global_transform());
- } else {
- bool found = false;
- // We no longer have a current origin so find the first one we can make current
- for (int i = 0; !found && i < origin_nodes.size(); i++) {
- if (origin_nodes[i] != this) {
- origin_nodes[i]->set_current(true);
- found = true;
+ }
+
+ // Check if we need to update our other origin nodes accordingly
+ if (p_update_others) {
+ if (current) {
+ for (int i = 0; i < origin_nodes.size(); i++) {
+ if (origin_nodes[i] != this && origin_nodes[i]->current) {
+ origin_nodes[i]->_set_current(false, false);
+ }
+ }
+ } else {
+ // We no longer have a current origin so find the first one we can make current
+ for (int i = 0; i < origin_nodes.size(); i++) {
+ if (origin_nodes[i] != this) {
+ origin_nodes[i]->_set_current(true, false);
+ return; // we are done.
+ }
}
}
}
}
+void XROrigin3D::set_current(bool p_enabled) {
+ _set_current(p_enabled, true);
+}
+
bool XROrigin3D::is_current() const {
if (Engine::get_singleton()->is_editor_hint()) {
// return as is
diff --git a/scene/3d/xr_nodes.h b/scene/3d/xr_nodes.h
index 990fb61983..ec8e151a08 100644
--- a/scene/3d/xr_nodes.h
+++ b/scene/3d/xr_nodes.h
@@ -183,6 +183,8 @@ private:
bool current = false;
static Vector<XROrigin3D *> origin_nodes; // all origin nodes in tree
+ void _set_current(bool p_enabled, bool p_update_others);
+
protected:
void _notification(int p_what);
static void _bind_methods();
diff --git a/scene/animation/animation_blend_space_1d.cpp b/scene/animation/animation_blend_space_1d.cpp
index f30aea3bdd..4b325ee464 100644
--- a/scene/animation/animation_blend_space_1d.cpp
+++ b/scene/animation/animation_blend_space_1d.cpp
@@ -230,14 +230,14 @@ void AnimationNodeBlendSpace1D::_add_blend_point(int p_index, const Ref<Animatio
}
}
-double AnimationNodeBlendSpace1D::process(double p_time, bool p_seek, bool p_seek_root) {
+double AnimationNodeBlendSpace1D::process(double p_time, bool p_seek, bool p_is_external_seeking) {
if (blend_points_used == 0) {
return 0.0;
}
if (blend_points_used == 1) {
// only one point available, just play that animation
- return blend_node(blend_points[0].name, blend_points[0].node, p_time, p_seek, p_seek_root, 1.0, FILTER_IGNORE, true);
+ return blend_node(blend_points[0].name, blend_points[0].node, p_time, p_seek, p_is_external_seeking, 1.0, FILTER_IGNORE, true);
}
double blend_pos = get_parameter(blend_position);
@@ -307,10 +307,10 @@ double AnimationNodeBlendSpace1D::process(double p_time, bool p_seek, bool p_see
for (int i = 0; i < blend_points_used; i++) {
if (i == point_lower || i == point_higher) {
- double remaining = blend_node(blend_points[i].name, blend_points[i].node, p_time, p_seek, p_seek_root, weights[i], FILTER_IGNORE, true);
+ double remaining = blend_node(blend_points[i].name, blend_points[i].node, p_time, p_seek, p_is_external_seeking, weights[i], FILTER_IGNORE, true);
max_time_remaining = MAX(max_time_remaining, remaining);
- } else {
- blend_node(blend_points[i].name, blend_points[i].node, p_time, p_seek, p_seek_root, 0, FILTER_IGNORE, sync);
+ } else if (sync) {
+ blend_node(blend_points[i].name, blend_points[i].node, p_time, p_seek, p_is_external_seeking, 0, FILTER_IGNORE, true);
}
}
diff --git a/scene/animation/animation_blend_space_1d.h b/scene/animation/animation_blend_space_1d.h
index 1876ccebc7..30cfe52c8e 100644
--- a/scene/animation/animation_blend_space_1d.h
+++ b/scene/animation/animation_blend_space_1d.h
@@ -98,7 +98,7 @@ public:
void set_use_sync(bool p_sync);
bool is_using_sync() const;
- double process(double p_time, bool p_seek, bool p_seek_root) override;
+ double process(double p_time, bool p_seek, bool p_is_external_seeking) override;
String get_caption() const override;
Ref<AnimationNode> get_child_by_name(const StringName &p_name) override;
diff --git a/scene/animation/animation_blend_space_2d.cpp b/scene/animation/animation_blend_space_2d.cpp
index 0d8b7ba8f7..4e20429ac9 100644
--- a/scene/animation/animation_blend_space_2d.cpp
+++ b/scene/animation/animation_blend_space_2d.cpp
@@ -432,7 +432,7 @@ void AnimationNodeBlendSpace2D::_blend_triangle(const Vector2 &p_pos, const Vect
r_weights[2] = w;
}
-double AnimationNodeBlendSpace2D::process(double p_time, bool p_seek, bool p_seek_root) {
+double AnimationNodeBlendSpace2D::process(double p_time, bool p_seek, bool p_is_external_seeking) {
_update_triangles();
Vector2 blend_pos = get_parameter(blend_position);
@@ -502,7 +502,7 @@ double AnimationNodeBlendSpace2D::process(double p_time, bool p_seek, bool p_see
for (int j = 0; j < 3; j++) {
if (i == triangle_points[j]) {
//blend with the given weight
- double t = blend_node(blend_points[i].name, blend_points[i].node, p_time, p_seek, p_seek_root, blend_weights[j], FILTER_IGNORE, true);
+ double t = blend_node(blend_points[i].name, blend_points[i].node, p_time, p_seek, p_is_external_seeking, blend_weights[j], FILTER_IGNORE, true);
if (first || t < mind) {
mind = t;
first = false;
@@ -512,8 +512,8 @@ double AnimationNodeBlendSpace2D::process(double p_time, bool p_seek, bool p_see
}
}
- if (!found) {
- blend_node(blend_points[i].name, blend_points[i].node, p_time, p_seek, p_seek_root, 0, FILTER_IGNORE, sync);
+ if (sync && !found) {
+ blend_node(blend_points[i].name, blend_points[i].node, p_time, p_seek, p_is_external_seeking, 0, FILTER_IGNORE, true);
}
}
} else {
@@ -538,21 +538,23 @@ double AnimationNodeBlendSpace2D::process(double p_time, bool p_seek, bool p_see
na_n->set_backward(na_c->is_backward());
}
//see how much animation remains
- from = cur_length_internal - blend_node(blend_points[cur_closest].name, blend_points[cur_closest].node, p_time, false, p_seek_root, 0.0, FILTER_IGNORE, true);
+ from = cur_length_internal - blend_node(blend_points[cur_closest].name, blend_points[cur_closest].node, p_time, false, p_is_external_seeking, 0.0, FILTER_IGNORE, true);
}
- mind = blend_node(blend_points[new_closest].name, blend_points[new_closest].node, from, true, p_seek_root, 1.0, FILTER_IGNORE, true);
+ mind = blend_node(blend_points[new_closest].name, blend_points[new_closest].node, from, true, p_is_external_seeking, 1.0, FILTER_IGNORE, true);
cur_length_internal = from + mind;
cur_closest = new_closest;
} else {
- mind = blend_node(blend_points[cur_closest].name, blend_points[cur_closest].node, p_time, p_seek, p_seek_root, 1.0, FILTER_IGNORE, true);
+ mind = blend_node(blend_points[cur_closest].name, blend_points[cur_closest].node, p_time, p_seek, p_is_external_seeking, 1.0, FILTER_IGNORE, true);
}
- for (int i = 0; i < blend_points_used; i++) {
- if (i != cur_closest) {
- blend_node(blend_points[i].name, blend_points[i].node, p_time, p_seek, p_seek_root, 0, FILTER_IGNORE, sync);
+ if (sync) {
+ for (int i = 0; i < blend_points_used; i++) {
+ if (i != cur_closest) {
+ blend_node(blend_points[i].name, blend_points[i].node, p_time, p_seek, p_is_external_seeking, 0, FILTER_IGNORE, true);
+ }
}
}
}
diff --git a/scene/animation/animation_blend_space_2d.h b/scene/animation/animation_blend_space_2d.h
index 250189f202..41854f73a4 100644
--- a/scene/animation/animation_blend_space_2d.h
+++ b/scene/animation/animation_blend_space_2d.h
@@ -128,7 +128,7 @@ public:
void set_y_label(const String &p_label);
String get_y_label() const;
- virtual double process(double p_time, bool p_seek, bool p_seek_root) override;
+ virtual double process(double p_time, bool p_seek, bool p_is_external_seeking) override;
virtual String get_caption() const override;
Vector2 get_closest_point(const Vector2 &p_point);
diff --git a/scene/animation/animation_blend_tree.cpp b/scene/animation/animation_blend_tree.cpp
index 0c91729a6f..26261d6da5 100644
--- a/scene/animation/animation_blend_tree.cpp
+++ b/scene/animation/animation_blend_tree.cpp
@@ -64,7 +64,7 @@ void AnimationNodeAnimation::_validate_property(PropertyInfo &p_property) const
}
}
-double AnimationNodeAnimation::process(double p_time, bool p_seek, bool p_seek_root) {
+double AnimationNodeAnimation::process(double p_time, bool p_seek, bool p_is_external_seeking) {
AnimationPlayer *ap = state->player;
ERR_FAIL_COND_V(!ap, 0);
@@ -87,40 +87,43 @@ double AnimationNodeAnimation::process(double p_time, bool p_seek, bool p_seek_r
double anim_size = (double)anim->get_length();
double step = 0.0;
double prev_time = cur_time;
- int pingponged = 0;
- bool current_backward = signbit(p_time);
+ Animation::LoopedFlag looped_flag = Animation::LOOPED_FLAG_NONE;
+ bool node_backward = play_mode == PLAY_MODE_BACKWARD;
if (p_seek) {
step = p_time - cur_time;
cur_time = p_time;
} else {
p_time *= backward ? -1.0 : 1.0;
- if (!(cur_time == anim_size && !current_backward) && !(cur_time == 0 && current_backward)) {
- cur_time = cur_time + p_time;
- step = p_time;
- }
+ cur_time = cur_time + p_time;
+ step = p_time;
}
if (anim->get_loop_mode() == Animation::LOOP_PINGPONG) {
if (!Math::is_zero_approx(anim_size)) {
- if ((int)Math::floor(abs(cur_time - prev_time) / anim_size) % 2 == 0) {
- if (prev_time >= 0 && cur_time < 0) {
- backward = !backward;
- pingponged = -1;
- }
- if (prev_time <= anim_size && cur_time > anim_size) {
- backward = !backward;
- pingponged = 1;
- }
+ if (prev_time >= 0 && cur_time < 0) {
+ backward = !backward;
+ looped_flag = node_backward ? Animation::LOOPED_FLAG_END : Animation::LOOPED_FLAG_START;
+ }
+ if (prev_time <= anim_size && cur_time > anim_size) {
+ backward = !backward;
+ looped_flag = node_backward ? Animation::LOOPED_FLAG_START : Animation::LOOPED_FLAG_END;
}
cur_time = Math::pingpong(cur_time, anim_size);
}
- } else {
- if (anim->get_loop_mode() == Animation::LOOP_LINEAR) {
- if (!Math::is_zero_approx(anim_size)) {
- cur_time = Math::fposmod(cur_time, anim_size);
+ } else if (anim->get_loop_mode() == Animation::LOOP_LINEAR) {
+ if (!Math::is_zero_approx(anim_size)) {
+ if (prev_time >= 0 && cur_time < 0) {
+ looped_flag = node_backward ? Animation::LOOPED_FLAG_END : Animation::LOOPED_FLAG_START;
}
- } else if (cur_time < 0) {
+ if (prev_time <= anim_size && cur_time > anim_size) {
+ looped_flag = node_backward ? Animation::LOOPED_FLAG_START : Animation::LOOPED_FLAG_END;
+ }
+ cur_time = Math::fposmod(cur_time, anim_size);
+ }
+ backward = false;
+ } else {
+ if (cur_time < 0) {
step += cur_time;
cur_time = 0;
} else if (cur_time > anim_size) {
@@ -128,12 +131,38 @@ double AnimationNodeAnimation::process(double p_time, bool p_seek, bool p_seek_r
cur_time = anim_size;
}
backward = false;
+
+ // If ended, don't progress animation. So set delta to 0.
+ if (p_time > 0) {
+ if (play_mode == PLAY_MODE_FORWARD) {
+ if (prev_time >= anim_size) {
+ step = 0;
+ }
+ } else {
+ if (prev_time <= 0) {
+ step = 0;
+ }
+ }
+ }
+
+ // Emit start & finish signal. Internally, the detections are the same for backward.
+ // We should use call_deferred since the track keys are still being prosessed.
+ if (state->tree) {
+ // AnimationTree uses seek to 0 "internally" to process the first key of the animation, which is used as the start detection.
+ if (p_seek && !p_is_external_seeking && cur_time == 0) {
+ state->tree->call_deferred(SNAME("emit_signal"), "animation_started", animation);
+ }
+ // Finished.
+ if (prev_time < anim_size && cur_time >= anim_size) {
+ state->tree->call_deferred(SNAME("emit_signal"), "animation_finished", animation);
+ }
+ }
}
if (play_mode == PLAY_MODE_FORWARD) {
- blend_animation(animation, cur_time, step, p_seek, p_seek_root, 1.0, pingponged);
+ blend_animation(animation, cur_time, step, p_seek, p_is_external_seeking, 1.0, looped_flag);
} else {
- blend_animation(animation, anim_size - cur_time, -step, p_seek, p_seek_root, 1.0, pingponged);
+ blend_animation(animation, anim_size - cur_time, -step, p_seek, p_is_external_seeking, 1.0, looped_flag);
}
set_parameter(time, cur_time);
@@ -273,7 +302,7 @@ bool AnimationNodeOneShot::has_filter() const {
return true;
}
-double AnimationNodeOneShot::process(double p_time, bool p_seek, bool p_seek_root) {
+double AnimationNodeOneShot::process(double p_time, bool p_seek, bool p_is_external_seeking) {
bool cur_active = get_parameter(active);
bool cur_prev_active = get_parameter(prev_active);
double cur_time = get_parameter(time);
@@ -295,9 +324,7 @@ double AnimationNodeOneShot::process(double p_time, bool p_seek, bool p_seek_roo
set_parameter(time_to_restart, cur_time_to_restart);
}
- if (!cur_active) {
- return blend_input(0, p_time, p_seek, p_seek_root, 1.0, FILTER_IGNORE, sync);
- }
+ return blend_input(0, p_time, p_seek, p_is_external_seeking, 1.0, FILTER_IGNORE, sync);
}
bool os_seek = p_seek;
@@ -333,12 +360,11 @@ double AnimationNodeOneShot::process(double p_time, bool p_seek, bool p_seek_roo
double main_rem;
if (mix == MIX_MODE_ADD) {
- main_rem = blend_input(0, p_time, p_seek, p_seek_root, 1.0, FILTER_IGNORE, sync);
+ main_rem = blend_input(0, p_time, p_seek, p_is_external_seeking, 1.0, FILTER_IGNORE, sync);
} else {
- main_rem = blend_input(0, p_time, p_seek, p_seek_root, 1.0 - blend, FILTER_BLEND, sync);
+ main_rem = blend_input(0, p_time, p_seek, p_is_external_seeking, 1.0 - blend, FILTER_BLEND, sync); // Unlike below, processing this edge is a corner case.
}
-
- double os_rem = blend_input(1, os_seek ? cur_time : p_time, os_seek, p_seek_root, blend, FILTER_PASS, true);
+ double os_rem = blend_input(1, os_seek ? cur_time : p_time, os_seek, p_is_external_seeking, Math::is_zero_approx(blend) ? CMP_EPSILON : blend, FILTER_PASS, true); // Blend values must be more than CMP_EPSILON to process discrete keys in edge.
if (do_start) {
cur_remaining = os_rem;
@@ -420,10 +446,10 @@ bool AnimationNodeAdd2::has_filter() const {
return true;
}
-double AnimationNodeAdd2::process(double p_time, bool p_seek, bool p_seek_root) {
+double AnimationNodeAdd2::process(double p_time, bool p_seek, bool p_is_external_seeking) {
double amount = get_parameter(add_amount);
- double rem0 = blend_input(0, p_time, p_seek, p_seek_root, 1.0, FILTER_IGNORE, sync);
- blend_input(1, p_time, p_seek, p_seek_root, amount, FILTER_PASS, sync);
+ double rem0 = blend_input(0, p_time, p_seek, p_is_external_seeking, 1.0, FILTER_IGNORE, sync);
+ blend_input(1, p_time, p_seek, p_is_external_seeking, amount, FILTER_PASS, sync);
return rem0;
}
@@ -454,11 +480,11 @@ bool AnimationNodeAdd3::has_filter() const {
return true;
}
-double AnimationNodeAdd3::process(double p_time, bool p_seek, bool p_seek_root) {
+double AnimationNodeAdd3::process(double p_time, bool p_seek, bool p_is_external_seeking) {
double amount = get_parameter(add_amount);
- blend_input(0, p_time, p_seek, p_seek_root, MAX(0, -amount), FILTER_PASS, sync);
- double rem0 = blend_input(1, p_time, p_seek, p_seek_root, 1.0, FILTER_IGNORE, sync);
- blend_input(2, p_time, p_seek, p_seek_root, MAX(0, amount), FILTER_PASS, sync);
+ blend_input(0, p_time, p_seek, p_is_external_seeking, MAX(0, -amount), FILTER_PASS, sync);
+ double rem0 = blend_input(1, p_time, p_seek, p_is_external_seeking, 1.0, FILTER_IGNORE, sync);
+ blend_input(2, p_time, p_seek, p_is_external_seeking, MAX(0, amount), FILTER_PASS, sync);
return rem0;
}
@@ -486,11 +512,11 @@ String AnimationNodeBlend2::get_caption() const {
return "Blend2";
}
-double AnimationNodeBlend2::process(double p_time, bool p_seek, bool p_seek_root) {
+double AnimationNodeBlend2::process(double p_time, bool p_seek, bool p_is_external_seeking) {
double amount = get_parameter(blend_amount);
- double rem0 = blend_input(0, p_time, p_seek, p_seek_root, 1.0 - amount, FILTER_BLEND, sync);
- double rem1 = blend_input(1, p_time, p_seek, p_seek_root, amount, FILTER_PASS, sync);
+ double rem0 = blend_input(0, p_time, p_seek, p_is_external_seeking, 1.0 - amount, FILTER_BLEND, sync);
+ double rem1 = blend_input(1, p_time, p_seek, p_is_external_seeking, amount, FILTER_PASS, sync);
return amount > 0.5 ? rem1 : rem0; //hacky but good enough
}
@@ -521,11 +547,11 @@ String AnimationNodeBlend3::get_caption() const {
return "Blend3";
}
-double AnimationNodeBlend3::process(double p_time, bool p_seek, bool p_seek_root) {
+double AnimationNodeBlend3::process(double p_time, bool p_seek, bool p_is_external_seeking) {
double amount = get_parameter(blend_amount);
- double rem0 = blend_input(0, p_time, p_seek, p_seek_root, MAX(0, -amount), FILTER_IGNORE, sync);
- double rem1 = blend_input(1, p_time, p_seek, p_seek_root, 1.0 - ABS(amount), FILTER_IGNORE, sync);
- double rem2 = blend_input(2, p_time, p_seek, p_seek_root, MAX(0, amount), FILTER_IGNORE, sync);
+ double rem0 = blend_input(0, p_time, p_seek, p_is_external_seeking, MAX(0, -amount), FILTER_IGNORE, sync);
+ double rem1 = blend_input(1, p_time, p_seek, p_is_external_seeking, 1.0 - ABS(amount), FILTER_IGNORE, sync);
+ double rem2 = blend_input(2, p_time, p_seek, p_is_external_seeking, MAX(0, amount), FILTER_IGNORE, sync);
return amount > 0.5 ? rem2 : (amount < -0.5 ? rem0 : rem1); //hacky but good enough
}
@@ -553,12 +579,12 @@ String AnimationNodeTimeScale::get_caption() const {
return "TimeScale";
}
-double AnimationNodeTimeScale::process(double p_time, bool p_seek, bool p_seek_root) {
+double AnimationNodeTimeScale::process(double p_time, bool p_seek, bool p_is_external_seeking) {
double cur_scale = get_parameter(scale);
if (p_seek) {
- return blend_input(0, p_time, true, p_seek_root, 1.0, FILTER_IGNORE, true);
+ return blend_input(0, p_time, true, p_is_external_seeking, 1.0, FILTER_IGNORE, true);
} else {
- return blend_input(0, p_time * cur_scale, false, p_seek_root, 1.0, FILTER_IGNORE, true);
+ return blend_input(0, p_time * cur_scale, false, p_is_external_seeking, 1.0, FILTER_IGNORE, true);
}
}
@@ -583,16 +609,16 @@ String AnimationNodeTimeSeek::get_caption() const {
return "Seek";
}
-double AnimationNodeTimeSeek::process(double p_time, bool p_seek, bool p_seek_root) {
+double AnimationNodeTimeSeek::process(double p_time, bool p_seek, bool p_is_external_seeking) {
double cur_seek_pos = get_parameter(seek_pos);
if (p_seek) {
- return blend_input(0, p_time, true, p_seek_root, 1.0, FILTER_IGNORE, true);
+ return blend_input(0, p_time, true, p_is_external_seeking, 1.0, FILTER_IGNORE, true);
} else if (cur_seek_pos >= 0) {
double ret = blend_input(0, cur_seek_pos, true, true, 1.0, FILTER_IGNORE, true);
set_parameter(seek_pos, -1.0); //reset
return ret;
} else {
- return blend_input(0, p_time, false, p_seek_root, 1.0, FILTER_IGNORE, true);
+ return blend_input(0, p_time, false, p_is_external_seeking, 1.0, FILTER_IGNORE, true);
}
}
@@ -700,7 +726,7 @@ bool AnimationNodeTransition::is_from_start() const {
return from_start;
}
-double AnimationNodeTransition::process(double p_time, bool p_seek, bool p_seek_root) {
+double AnimationNodeTransition::process(double p_time, bool p_seek, bool p_is_external_seeking) {
int cur_current = get_parameter(current);
int cur_prev = get_parameter(prev);
int cur_prev_current = get_parameter(prev_current);
@@ -726,15 +752,17 @@ double AnimationNodeTransition::process(double p_time, bool p_seek, bool p_seek_
double rem = 0.0;
- for (int i = 0; i < enabled_inputs; i++) {
- if (i != cur_current && i != cur_prev) {
- blend_input(i, p_time, p_seek, p_seek_root, 0, FILTER_IGNORE, sync);
+ if (sync) {
+ for (int i = 0; i < enabled_inputs; i++) {
+ if (i != cur_current && i != cur_prev) {
+ blend_input(i, p_time, p_seek, p_is_external_seeking, 0, FILTER_IGNORE, true);
+ }
}
}
if (cur_prev < 0) { // process current animation, check for transition
- rem = blend_input(cur_current, p_time, p_seek, p_seek_root, 1.0, FILTER_IGNORE, true);
+ rem = blend_input(cur_current, p_time, p_seek, p_is_external_seeking, 1.0, FILTER_IGNORE, true);
if (p_seek) {
cur_time = p_time;
@@ -753,18 +781,19 @@ double AnimationNodeTransition::process(double p_time, bool p_seek, bool p_seek_
blend = xfade_curve->sample(blend);
}
+ // Blend values must be more than CMP_EPSILON to process discrete keys in edge.
+ real_t blend_inv = 1.0 - blend;
if (from_start && !p_seek && switched) { //just switched, seek to start of current
-
- rem = blend_input(cur_current, 0, true, p_seek_root, 1.0 - blend, FILTER_IGNORE, true);
+ rem = blend_input(cur_current, 0, true, p_is_external_seeking, Math::is_zero_approx(blend_inv) ? CMP_EPSILON : blend_inv, FILTER_IGNORE, true);
} else {
- rem = blend_input(cur_current, p_time, p_seek, p_seek_root, 1.0 - blend, FILTER_IGNORE, true);
+ rem = blend_input(cur_current, p_time, p_seek, p_is_external_seeking, Math::is_zero_approx(blend_inv) ? CMP_EPSILON : blend_inv, FILTER_IGNORE, true);
}
if (p_seek) {
- blend_input(cur_prev, p_time, true, p_seek_root, blend, FILTER_IGNORE, true);
+ blend_input(cur_prev, p_time, true, p_is_external_seeking, Math::is_zero_approx(blend) ? CMP_EPSILON : blend, FILTER_IGNORE, true);
cur_time = p_time;
} else {
- blend_input(cur_prev, p_time, false, p_seek_root, blend, FILTER_IGNORE, true);
+ blend_input(cur_prev, p_time, false, p_is_external_seeking, Math::is_zero_approx(blend) ? CMP_EPSILON : blend, FILTER_IGNORE, true);
cur_time += p_time;
cur_prev_xfading -= p_time;
if (cur_prev_xfading < 0) {
@@ -833,8 +862,8 @@ String AnimationNodeOutput::get_caption() const {
return "Output";
}
-double AnimationNodeOutput::process(double p_time, bool p_seek, bool p_seek_root) {
- return blend_input(0, p_time, p_seek, p_seek_root, 1.0, FILTER_IGNORE, true);
+double AnimationNodeOutput::process(double p_time, bool p_seek, bool p_is_external_seeking) {
+ return blend_input(0, p_time, p_seek, p_is_external_seeking, 1.0, FILTER_IGNORE, true);
}
AnimationNodeOutput::AnimationNodeOutput() {
@@ -1046,9 +1075,9 @@ String AnimationNodeBlendTree::get_caption() const {
return "BlendTree";
}
-double AnimationNodeBlendTree::process(double p_time, bool p_seek, bool p_seek_root) {
+double AnimationNodeBlendTree::process(double p_time, bool p_seek, bool p_is_external_seeking) {
Ref<AnimationNodeOutput> output = nodes[SceneStringNames::get_singleton()->output].node;
- return _blend_node("output", nodes[SceneStringNames::get_singleton()->output].connections, this, output, p_time, p_seek, p_seek_root, 1.0, FILTER_IGNORE, true);
+ return _blend_node("output", nodes[SceneStringNames::get_singleton()->output].connections, this, output, p_time, p_seek, p_is_external_seeking, 1.0, FILTER_IGNORE, true);
}
void AnimationNodeBlendTree::get_node_list(List<StringName> *r_list) {
diff --git a/scene/animation/animation_blend_tree.h b/scene/animation/animation_blend_tree.h
index 1c31718259..52bf67b8f5 100644
--- a/scene/animation/animation_blend_tree.h
+++ b/scene/animation/animation_blend_tree.h
@@ -53,7 +53,7 @@ public:
static Vector<String> (*get_editable_animation_list)();
virtual String get_caption() const override;
- virtual double process(double p_time, bool p_seek, bool p_seek_root) override;
+ virtual double process(double p_time, bool p_seek, bool p_is_external_seeking) override;
void set_animation(const StringName &p_name);
StringName get_animation() const;
@@ -72,7 +72,7 @@ protected:
private:
PlayMode play_mode = PLAY_MODE_FORWARD;
- bool backward = false;
+ bool backward = false; // Only used by pingpong animation.
};
VARIANT_ENUM_CAST(AnimationNodeAnimation::PlayMode)
@@ -148,7 +148,7 @@ public:
MixMode get_mix_mode() const;
virtual bool has_filter() const override;
- virtual double process(double p_time, bool p_seek, bool p_seek_root) override;
+ virtual double process(double p_time, bool p_seek, bool p_is_external_seeking) override;
AnimationNodeOneShot();
};
@@ -170,7 +170,7 @@ public:
virtual String get_caption() const override;
virtual bool has_filter() const override;
- virtual double process(double p_time, bool p_seek, bool p_seek_root) override;
+ virtual double process(double p_time, bool p_seek, bool p_is_external_seeking) override;
AnimationNodeAdd2();
};
@@ -190,7 +190,7 @@ public:
virtual String get_caption() const override;
virtual bool has_filter() const override;
- virtual double process(double p_time, bool p_seek, bool p_seek_root) override;
+ virtual double process(double p_time, bool p_seek, bool p_is_external_seeking) override;
AnimationNodeAdd3();
};
@@ -208,7 +208,7 @@ public:
virtual Variant get_parameter_default_value(const StringName &p_parameter) const override;
virtual String get_caption() const override;
- virtual double process(double p_time, bool p_seek, bool p_seek_root) override;
+ virtual double process(double p_time, bool p_seek, bool p_is_external_seeking) override;
virtual bool has_filter() const override;
AnimationNodeBlend2();
@@ -228,7 +228,7 @@ public:
virtual String get_caption() const override;
- double process(double p_time, bool p_seek, bool p_seek_root) override;
+ double process(double p_time, bool p_seek, bool p_is_external_seeking) override;
AnimationNodeBlend3();
};
@@ -246,7 +246,7 @@ public:
virtual String get_caption() const override;
- double process(double p_time, bool p_seek, bool p_seek_root) override;
+ double process(double p_time, bool p_seek, bool p_is_external_seeking) override;
AnimationNodeTimeScale();
};
@@ -265,7 +265,7 @@ public:
virtual String get_caption() const override;
- double process(double p_time, bool p_seek, bool p_seek_root) override;
+ double process(double p_time, bool p_seek, bool p_is_external_seeking) override;
AnimationNodeTimeSeek();
};
@@ -331,7 +331,7 @@ public:
void set_from_start(bool p_from_start);
bool is_from_start() const;
- double process(double p_time, bool p_seek, bool p_seek_root) override;
+ double process(double p_time, bool p_seek, bool p_is_external_seeking) override;
AnimationNodeTransition();
};
@@ -341,7 +341,7 @@ class AnimationNodeOutput : public AnimationNode {
public:
virtual String get_caption() const override;
- virtual double process(double p_time, bool p_seek, bool p_seek_root) override;
+ virtual double process(double p_time, bool p_seek, bool p_is_external_seeking) override;
AnimationNodeOutput();
};
@@ -410,7 +410,7 @@ public:
void get_node_connections(List<NodeConnection> *r_connections) const;
virtual String get_caption() const override;
- virtual double process(double p_time, bool p_seek, bool p_seek_root) override;
+ virtual double process(double p_time, bool p_seek, bool p_is_external_seeking) override;
void get_node_list(List<StringName> *r_list);
diff --git a/scene/animation/animation_node_state_machine.cpp b/scene/animation/animation_node_state_machine.cpp
index 8291df8036..d54740e9b0 100644
--- a/scene/animation/animation_node_state_machine.cpp
+++ b/scene/animation/animation_node_state_machine.cpp
@@ -41,12 +41,12 @@ AnimationNodeStateMachineTransition::SwitchMode AnimationNodeStateMachineTransit
return switch_mode;
}
-void AnimationNodeStateMachineTransition::set_auto_advance(bool p_enable) {
- auto_advance = p_enable;
+void AnimationNodeStateMachineTransition::set_advance_mode(AdvanceMode p_mode) {
+ advance_mode = p_mode;
}
-bool AnimationNodeStateMachineTransition::has_auto_advance() const {
- return auto_advance;
+AnimationNodeStateMachineTransition::AdvanceMode AnimationNodeStateMachineTransition::get_advance_mode() const {
+ return advance_mode;
}
void AnimationNodeStateMachineTransition::set_advance_condition(const StringName &p_condition) {
@@ -107,15 +107,6 @@ Ref<Curve> AnimationNodeStateMachineTransition::get_xfade_curve() const {
return xfade_curve;
}
-void AnimationNodeStateMachineTransition::set_disabled(bool p_disabled) {
- disabled = p_disabled;
- emit_changed();
-}
-
-bool AnimationNodeStateMachineTransition::is_disabled() const {
- return disabled;
-}
-
void AnimationNodeStateMachineTransition::set_priority(int p_priority) {
priority = p_priority;
emit_changed();
@@ -129,8 +120,8 @@ void AnimationNodeStateMachineTransition::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_switch_mode", "mode"), &AnimationNodeStateMachineTransition::set_switch_mode);
ClassDB::bind_method(D_METHOD("get_switch_mode"), &AnimationNodeStateMachineTransition::get_switch_mode);
- ClassDB::bind_method(D_METHOD("set_auto_advance", "auto_advance"), &AnimationNodeStateMachineTransition::set_auto_advance);
- ClassDB::bind_method(D_METHOD("has_auto_advance"), &AnimationNodeStateMachineTransition::has_auto_advance);
+ ClassDB::bind_method(D_METHOD("set_advance_mode", "mode"), &AnimationNodeStateMachineTransition::set_advance_mode);
+ ClassDB::bind_method(D_METHOD("get_advance_mode"), &AnimationNodeStateMachineTransition::get_advance_mode);
ClassDB::bind_method(D_METHOD("set_advance_condition", "name"), &AnimationNodeStateMachineTransition::set_advance_condition);
ClassDB::bind_method(D_METHOD("get_advance_condition"), &AnimationNodeStateMachineTransition::get_advance_condition);
@@ -141,9 +132,6 @@ void AnimationNodeStateMachineTransition::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_xfade_curve", "curve"), &AnimationNodeStateMachineTransition::set_xfade_curve);
ClassDB::bind_method(D_METHOD("get_xfade_curve"), &AnimationNodeStateMachineTransition::get_xfade_curve);
- ClassDB::bind_method(D_METHOD("set_disabled", "disabled"), &AnimationNodeStateMachineTransition::set_disabled);
- ClassDB::bind_method(D_METHOD("is_disabled"), &AnimationNodeStateMachineTransition::is_disabled);
-
ClassDB::bind_method(D_METHOD("set_priority", "priority"), &AnimationNodeStateMachineTransition::set_priority);
ClassDB::bind_method(D_METHOD("get_priority"), &AnimationNodeStateMachineTransition::get_priority);
@@ -155,17 +143,19 @@ void AnimationNodeStateMachineTransition::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::INT, "priority", PROPERTY_HINT_RANGE, "0,32,1"), "set_priority", "get_priority");
ADD_GROUP("Switch", "");
ADD_PROPERTY(PropertyInfo(Variant::INT, "switch_mode", PROPERTY_HINT_ENUM, "Immediate,Sync,At End"), "set_switch_mode", "get_switch_mode");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL, "auto_advance"), "set_auto_advance", "has_auto_advance");
ADD_GROUP("Advance", "advance_");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "advance_mode", PROPERTY_HINT_ENUM, "Disabled,Enabled,Auto"), "set_advance_mode", "get_advance_mode");
ADD_PROPERTY(PropertyInfo(Variant::STRING_NAME, "advance_condition"), "set_advance_condition", "get_advance_condition");
ADD_PROPERTY(PropertyInfo(Variant::STRING, "advance_expression", PROPERTY_HINT_EXPRESSION, ""), "set_advance_expression", "get_advance_expression");
- ADD_GROUP("Disabling", "");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL, "disabled"), "set_disabled", "is_disabled");
BIND_ENUM_CONSTANT(SWITCH_MODE_IMMEDIATE);
BIND_ENUM_CONSTANT(SWITCH_MODE_SYNC);
BIND_ENUM_CONSTANT(SWITCH_MODE_AT_END);
+ BIND_ENUM_CONSTANT(ADVANCE_MODE_DISABLED);
+ BIND_ENUM_CONSTANT(ADVANCE_MODE_ENABLED);
+ BIND_ENUM_CONSTANT(ADVANCE_MODE_AUTO);
+
ADD_SIGNAL(MethodInfo("advance_condition_changed"));
}
@@ -234,7 +224,7 @@ bool AnimationNodeStateMachinePlayback::_travel(AnimationNodeStateMachine *p_sta
//build open list
for (int i = 0; i < p_state_machine->transitions.size(); i++) {
- if (p_state_machine->transitions[i].transition->is_disabled()) {
+ if (p_state_machine->transitions[i].transition->get_advance_mode() == AnimationNodeStateMachineTransition::ADVANCE_MODE_DISABLED) {
continue;
}
@@ -279,7 +269,7 @@ bool AnimationNodeStateMachinePlayback::_travel(AnimationNodeStateMachine *p_sta
StringName transition = p_state_machine->transitions[least_cost_transition->get()].local_to;
for (int i = 0; i < p_state_machine->transitions.size(); i++) {
- if (p_state_machine->transitions[i].transition->is_disabled()) {
+ if (p_state_machine->transitions[i].transition->get_advance_mode() == AnimationNodeStateMachineTransition::ADVANCE_MODE_DISABLED) {
continue;
}
@@ -332,11 +322,11 @@ bool AnimationNodeStateMachinePlayback::_travel(AnimationNodeStateMachine *p_sta
return true;
}
-double AnimationNodeStateMachinePlayback::process(AnimationNodeStateMachine *p_state_machine, double p_time, bool p_seek, bool p_seek_root) {
+double AnimationNodeStateMachinePlayback::process(AnimationNodeStateMachine *p_state_machine, double p_time, bool p_seek, bool p_is_external_seeking) {
if (p_time == -1) {
Ref<AnimationNodeStateMachine> anodesm = p_state_machine->states[current].node;
if (anodesm.is_valid()) {
- p_state_machine->blend_node(current, p_state_machine->states[current].node, -1, p_seek, p_seek_root, 0, AnimationNode::FILTER_IGNORE, true);
+ p_state_machine->blend_node(current, p_state_machine->states[current].node, -1, p_seek, p_is_external_seeking, 0, AnimationNode::FILTER_IGNORE, true);
}
playing = false;
return 0;
@@ -379,6 +369,7 @@ double AnimationNodeStateMachinePlayback::process(AnimationNodeStateMachine *p_s
// can't travel, then teleport
path.clear();
current = start_request;
+ play_start = true;
}
start_request = StringName(); //clear start request
}
@@ -405,7 +396,7 @@ double AnimationNodeStateMachinePlayback::process(AnimationNodeStateMachine *p_s
current = p_state_machine->start_node;
}
- len_current = p_state_machine->blend_node(current, p_state_machine->states[current].node, 0, true, p_seek_root, 1.0, AnimationNode::FILTER_IGNORE, true);
+ len_current = p_state_machine->blend_node(current, p_state_machine->states[current].node, 0, true, p_is_external_seeking, 1.0, AnimationNode::FILTER_IGNORE, true);
pos_current = 0;
}
@@ -424,7 +415,7 @@ double AnimationNodeStateMachinePlayback::process(AnimationNodeStateMachine *p_s
fading_pos += p_time;
}
fade_blend = MIN(1.0, fading_pos / fading_time);
- if (fade_blend >= 1.0) {
+ if (fade_blend > 1.0) {
fading_from = StringName();
}
}
@@ -433,10 +424,11 @@ double AnimationNodeStateMachinePlayback::process(AnimationNodeStateMachine *p_s
if (current_curve.is_valid()) {
fade_blend = current_curve->sample(fade_blend);
}
- float rem = p_state_machine->blend_node(current, p_state_machine->states[current].node, p_time, p_seek, p_seek_root, fade_blend, AnimationNode::FILTER_IGNORE, true);
+ double rem = p_state_machine->blend_node(current, p_state_machine->states[current].node, p_time, p_seek, p_is_external_seeking, Math::is_zero_approx(fade_blend) ? CMP_EPSILON : fade_blend, AnimationNode::FILTER_IGNORE, true); // Blend values must be more than CMP_EPSILON to process discrete keys in edge.
+ double fade_blend_inv = 1.0 - fade_blend;
if (fading_from != StringName()) {
- p_state_machine->blend_node(fading_from, p_state_machine->states[fading_from].node, p_time, p_seek, p_seek_root, 1.0 - fade_blend, AnimationNode::FILTER_IGNORE, true);
+ p_state_machine->blend_node(fading_from, p_state_machine->states[fading_from].node, p_time, p_seek, p_is_external_seeking, Math::is_zero_approx(fade_blend_inv) ? CMP_EPSILON : fade_blend_inv, AnimationNode::FILTER_IGNORE, true); // Blend values must be more than CMP_EPSILON to process discrete keys in edge.
}
//guess playback position
@@ -445,19 +437,19 @@ double AnimationNodeStateMachinePlayback::process(AnimationNodeStateMachine *p_s
}
{ //advance and loop check
- float next_pos = len_current - rem;
+ double next_pos = len_current - rem;
end_loop = next_pos < pos_current;
pos_current = next_pos; //looped
}
//find next
StringName next;
- float next_xfade = 0.0;
+ double next_xfade = 0.0;
AnimationNodeStateMachineTransition::SwitchMode switch_mode = AnimationNodeStateMachineTransition::SWITCH_MODE_IMMEDIATE;
if (path.size()) {
for (int i = 0; i < p_state_machine->transitions.size(); i++) {
- if (p_state_machine->transitions[i].transition->is_disabled()) {
+ if (p_state_machine->transitions[i].transition->get_advance_mode() == AnimationNodeStateMachineTransition::ADVANCE_MODE_DISABLED) {
continue;
}
@@ -473,7 +465,7 @@ double AnimationNodeStateMachinePlayback::process(AnimationNodeStateMachine *p_s
int auto_advance_to = -1;
for (int i = 0; i < p_state_machine->transitions.size(); i++) {
- if (p_state_machine->transitions[i].transition->is_disabled()) {
+ if (p_state_machine->transitions[i].transition->get_advance_mode() == AnimationNodeStateMachineTransition::ADVANCE_MODE_DISABLED) {
continue;
}
@@ -541,7 +533,7 @@ double AnimationNodeStateMachinePlayback::process(AnimationNodeStateMachine *p_s
int auto_advance_to = -1;
for (int i = 0; i < prev_state_machine->transitions.size(); i++) {
- if (prev_state_machine->transitions[i].transition->is_disabled()) {
+ if (prev_state_machine->transitions[i].transition->get_advance_mode() == AnimationNodeStateMachineTransition::ADVANCE_MODE_DISABLED) {
continue;
}
@@ -593,19 +585,17 @@ double AnimationNodeStateMachinePlayback::process(AnimationNodeStateMachine *p_s
{ // if the current node is a state machine, update the "playing" variable to false by passing -1 in p_time
Ref<AnimationNodeStateMachine> anodesm = p_state_machine->states[current].node;
if (anodesm.is_valid()) {
- p_state_machine->blend_node(current, p_state_machine->states[current].node, -1, p_seek, p_seek_root, 0, AnimationNode::FILTER_IGNORE, true);
+ p_state_machine->blend_node(current, p_state_machine->states[current].node, -1, p_seek, p_is_external_seeking, 0, AnimationNode::FILTER_IGNORE, true);
}
}
current = next;
+ len_current = p_state_machine->blend_node(current, p_state_machine->states[current].node, 0, true, p_is_external_seeking, CMP_EPSILON, AnimationNode::FILTER_IGNORE, true); // Process next node's first key in here.
if (switch_mode == AnimationNodeStateMachineTransition::SWITCH_MODE_SYNC) {
- len_current = p_state_machine->blend_node(current, p_state_machine->states[current].node, 0, true, p_seek_root, 0, AnimationNode::FILTER_IGNORE, true);
pos_current = MIN(pos_current, len_current);
- p_state_machine->blend_node(current, p_state_machine->states[current].node, pos_current, true, p_seek_root, 0, AnimationNode::FILTER_IGNORE, true);
-
+ p_state_machine->blend_node(current, p_state_machine->states[current].node, pos_current, true, p_is_external_seeking, 0, AnimationNode::FILTER_IGNORE, true);
} else {
- len_current = p_state_machine->blend_node(current, p_state_machine->states[current].node, 0, true, p_seek_root, 0, AnimationNode::FILTER_IGNORE, true);
pos_current = 0;
}
@@ -630,14 +620,14 @@ double AnimationNodeStateMachinePlayback::process(AnimationNodeStateMachine *p_s
}
bool AnimationNodeStateMachinePlayback::_check_advance_condition(const Ref<AnimationNodeStateMachine> state_machine, const Ref<AnimationNodeStateMachineTransition> transition) const {
- if (transition->has_auto_advance()) {
- return true;
+ if (transition->get_advance_mode() != AnimationNodeStateMachineTransition::ADVANCE_MODE_AUTO) {
+ return false;
}
StringName advance_condition_name = transition->get_advance_condition_name();
- if (advance_condition_name != StringName() && bool(state_machine->get_parameter(advance_condition_name))) {
- return true;
+ if (advance_condition_name != StringName() && !bool(state_machine->get_parameter(advance_condition_name))) {
+ return false;
}
if (transition->expression.is_valid()) {
@@ -647,20 +637,18 @@ bool AnimationNodeStateMachinePlayback::_check_advance_condition(const Ref<Anima
NodePath advance_expression_base_node_path = tree_base->get_advance_expression_base_node();
Node *expression_base = tree_base->get_node_or_null(advance_expression_base_node_path);
- WARN_PRINT_ONCE("Animation transition has a valid expression, but no expression base node was set on its AnimationTree.");
-
if (expression_base) {
Ref<Expression> exp = transition->expression;
bool ret = exp->execute(Array(), expression_base, false, Engine::get_singleton()->is_editor_hint()); // Avoids allowing the user to crash the system with an expression by only allowing const calls.
- if (!exp->has_execute_failed()) {
- if (ret) {
- return true;
- }
+ if (exp->has_execute_failed() || !ret) {
+ return false;
}
+ } else {
+ WARN_PRINT_ONCE("Animation transition has a valid expression, but no expression base node was set on its AnimationTree.");
}
}
- return false;
+ return true;
}
void AnimationNodeStateMachinePlayback::_bind_methods() {
@@ -836,7 +824,8 @@ void AnimationNodeStateMachine::rename_node(const StringName &p_name, const Stri
_rename_transitions(p_name, p_new_name);
- emit_signal("tree_changed");
+ emit_changed();
+ emit_signal(SNAME("tree_changed"));
}
void AnimationNodeStateMachine::_rename_transitions(const StringName &p_name, const StringName &p_new_name) {
@@ -879,9 +868,8 @@ void AnimationNodeStateMachine::_rename_transitions(const StringName &p_name, co
transitions.write[i].to = p_new_name;
}
-
- updating_transitions = false;
}
+ updating_transitions = false;
}
void AnimationNodeStateMachine::get_node_list(List<StringName> *r_nodes) const {
@@ -1133,11 +1121,11 @@ Vector2 AnimationNodeStateMachine::get_graph_offset() const {
return graph_offset;
}
-double AnimationNodeStateMachine::process(double p_time, bool p_seek, bool p_seek_root) {
+double AnimationNodeStateMachine::process(double p_time, bool p_seek, bool p_is_external_seeking) {
Ref<AnimationNodeStateMachinePlayback> playback_new = get_parameter(playback);
ERR_FAIL_COND_V(playback_new.is_null(), 0.0);
- return playback_new->process(this, p_time, p_seek, p_seek_root);
+ return playback_new->process(this, p_time, p_seek, p_is_external_seeking);
}
String AnimationNodeStateMachine::get_caption() const {
@@ -1293,6 +1281,7 @@ Vector2 AnimationNodeStateMachine::get_node_position(const StringName &p_name) c
}
void AnimationNodeStateMachine::_tree_changed() {
+ emit_changed();
emit_signal(SNAME("tree_changed"));
}
diff --git a/scene/animation/animation_node_state_machine.h b/scene/animation/animation_node_state_machine.h
index cdb4c7528a..83b5e66491 100644
--- a/scene/animation/animation_node_state_machine.h
+++ b/scene/animation/animation_node_state_machine.h
@@ -44,14 +44,19 @@ public:
SWITCH_MODE_AT_END,
};
+ enum AdvanceMode {
+ ADVANCE_MODE_DISABLED,
+ ADVANCE_MODE_ENABLED,
+ ADVANCE_MODE_AUTO,
+ };
+
private:
SwitchMode switch_mode = SWITCH_MODE_IMMEDIATE;
- bool auto_advance = false;
+ AdvanceMode advance_mode = ADVANCE_MODE_ENABLED;
StringName advance_condition;
StringName advance_condition_name;
float xfade_time = 0.0;
Ref<Curve> xfade_curve;
- bool disabled = false;
int priority = 1;
String advance_expression;
@@ -65,8 +70,8 @@ public:
void set_switch_mode(SwitchMode p_mode);
SwitchMode get_switch_mode() const;
- void set_auto_advance(bool p_enable);
- bool has_auto_advance() const;
+ void set_advance_mode(AdvanceMode p_mode);
+ AdvanceMode get_advance_mode() const;
void set_advance_condition(const StringName &p_condition);
StringName get_advance_condition() const;
@@ -82,9 +87,6 @@ public:
void set_xfade_curve(const Ref<Curve> &p_curve);
Ref<Curve> get_xfade_curve() const;
- void set_disabled(bool p_disabled);
- bool is_disabled() const;
-
void set_priority(int p_priority);
int get_priority() const;
@@ -92,6 +94,7 @@ public:
};
VARIANT_ENUM_CAST(AnimationNodeStateMachineTransition::SwitchMode)
+VARIANT_ENUM_CAST(AnimationNodeStateMachineTransition::AdvanceMode)
class AnimationNodeStateMachine;
@@ -111,8 +114,8 @@ class AnimationNodeStateMachinePlayback : public Resource {
StringName next;
};
- float len_current = 0.0;
- float pos_current = 0.0;
+ double len_current = 0.0;
+ double pos_current = 0.0;
bool end_loop = false;
StringName current;
@@ -133,7 +136,7 @@ class AnimationNodeStateMachinePlayback : public Resource {
bool _travel(AnimationNodeStateMachine *p_state_machine, const StringName &p_travel);
- double process(AnimationNodeStateMachine *p_state_machine, double p_time, bool p_seek, bool p_seek_root);
+ double process(AnimationNodeStateMachine *p_state_machine, double p_time, bool p_seek, bool p_is_external_seeking);
bool _check_advance_condition(const Ref<AnimationNodeStateMachine> p_state_machine, const Ref<AnimationNodeStateMachineTransition> p_transition) const;
@@ -239,7 +242,7 @@ public:
void set_graph_offset(const Vector2 &p_offset);
Vector2 get_graph_offset() const;
- virtual double process(double p_time, bool p_seek, bool p_seek_root) override;
+ virtual double process(double p_time, bool p_seek, bool p_is_external_seeking) override;
virtual String get_caption() const override;
virtual Ref<AnimationNode> get_child_by_name(const StringName &p_name) override;
diff --git a/scene/animation/animation_player.cpp b/scene/animation/animation_player.cpp
index 59930a3fbb..ff20724f89 100644
--- a/scene/animation/animation_player.cpp
+++ b/scene/animation/animation_player.cpp
@@ -468,7 +468,7 @@ Variant AnimationPlayer::_post_process_key_value(const Ref<Animation> &p_anim, i
return p_value;
}
-void AnimationPlayer::_animation_process_animation(AnimationData *p_anim, double p_time, double p_delta, float p_interp, bool p_is_current, bool p_seeked, bool p_started, int p_pingponged) {
+void AnimationPlayer::_animation_process_animation(AnimationData *p_anim, double p_prev_time, double p_time, double p_delta, float p_interp, bool p_is_current, bool p_seeked, bool p_started, Animation::LoopedFlag p_looped_flag) {
_ensure_node_caches(p_anim);
ERR_FAIL_COND(p_anim->node_cache.size() != p_anim->animation->get_track_count());
@@ -664,7 +664,7 @@ void AnimationPlayer::_animation_process_animation(AnimationData *p_anim, double
}
}
- if (update_mode == Animation::UPDATE_CONTINUOUS || update_mode == Animation::UPDATE_CAPTURE || (p_delta == 0 && update_mode == Animation::UPDATE_DISCRETE)) { //delta == 0 means seek
+ if (update_mode == Animation::UPDATE_CONTINUOUS || update_mode == Animation::UPDATE_CAPTURE) {
Variant value = a->value_track_interpolate(i, p_time);
if (value == Variant()) {
@@ -681,9 +681,23 @@ void AnimationPlayer::_animation_process_animation(AnimationData *p_anim, double
pa->value_accum = Animation::interpolate_variant(pa->value_accum, value, p_interp);
}
- } else if (p_is_current && p_delta != 0) {
+ } else {
List<int> indices;
- a->value_track_get_key_indices(i, p_time, p_delta, &indices, p_pingponged);
+
+ if (p_seeked) {
+ int found_key = a->track_find_key(i, p_time);
+ if (found_key >= 0) {
+ indices.push_back(found_key);
+ }
+ } else {
+ if (p_started) {
+ int first_key = a->track_find_key(i, p_prev_time, Animation::FIND_MODE_EXACT);
+ if (first_key >= 0) {
+ indices.push_back(first_key);
+ }
+ }
+ a->track_get_key_indices_in_range(i, p_time, p_delta, &indices, p_looped_flag);
+ }
for (int &F : indices) {
Variant value = a->track_get_key_value(i, F);
@@ -734,16 +748,26 @@ void AnimationPlayer::_animation_process_animation(AnimationData *p_anim, double
if (!nc->node) {
continue;
}
- if (p_delta == 0) {
- continue;
- }
if (!p_is_current) {
break;
}
List<int> indices;
- a->method_track_get_key_indices(i, p_time, p_delta, &indices, p_pingponged);
+ if (p_seeked) {
+ int found_key = a->track_find_key(i, p_time);
+ if (found_key >= 0) {
+ indices.push_back(found_key);
+ }
+ } else {
+ if (p_started) {
+ int first_key = a->track_find_key(i, p_prev_time, Animation::FIND_MODE_EXACT);
+ if (first_key >= 0) {
+ indices.push_back(first_key);
+ }
+ }
+ a->track_get_key_indices_in_range(i, p_time, p_delta, &indices, p_looped_flag);
+ }
for (int &E : indices) {
StringName method = a->method_track_get_name(i, E);
@@ -787,9 +811,6 @@ void AnimationPlayer::_animation_process_animation(AnimationData *p_anim, double
if (!nc->node) {
continue;
}
- if (p_delta == 0) {
- continue;
- }
if (p_seeked) {
//find whatever should be playing
@@ -833,7 +854,13 @@ void AnimationPlayer::_animation_process_animation(AnimationData *p_anim, double
} else {
//find stuff to play
List<int> to_play;
- a->track_get_key_indices_in_range(i, p_time, p_delta, &to_play, p_pingponged);
+ if (p_started) {
+ int first_key = a->track_find_key(i, p_prev_time, Animation::FIND_MODE_EXACT);
+ if (first_key >= 0) {
+ to_play.push_back(first_key);
+ }
+ }
+ a->track_get_key_indices_in_range(i, p_time, p_delta, &to_play, p_looped_flag);
if (to_play.size()) {
int idx = to_play.back()->get();
@@ -893,7 +920,7 @@ void AnimationPlayer::_animation_process_animation(AnimationData *p_anim, double
continue;
}
- if (p_delta == 0 || p_seeked) {
+ if (p_seeked) {
//seek
int idx = a->track_find_key(i, p_time);
if (idx < 0) {
@@ -928,9 +955,9 @@ void AnimationPlayer::_animation_process_animation(AnimationData *p_anim, double
break;
}
- if (player->is_playing() || p_seeked) {
- player->play(anim_name);
+ if (player->is_playing()) {
player->seek(at_anim_pos);
+ player->play(anim_name);
nc->animation_playing = true;
playing_caches.insert(nc);
} else {
@@ -940,7 +967,13 @@ void AnimationPlayer::_animation_process_animation(AnimationData *p_anim, double
} else {
//find stuff to play
List<int> to_play;
- a->track_get_key_indices_in_range(i, p_time, p_delta, &to_play, p_pingponged);
+ if (p_started) {
+ int first_key = a->track_find_key(i, p_prev_time, Animation::FIND_MODE_EXACT);
+ if (first_key >= 0) {
+ to_play.push_back(first_key);
+ }
+ }
+ a->track_get_key_indices_in_range(i, p_time, p_delta, &to_play, p_looped_flag);
if (to_play.size()) {
int idx = to_play.back()->get();
@@ -952,8 +985,8 @@ void AnimationPlayer::_animation_process_animation(AnimationData *p_anim, double
nc->animation_playing = false;
}
} else {
+ player->seek(0.0);
player->play(anim_name);
- player->seek(0.0, true);
nc->animation_playing = true;
playing_caches.insert(nc);
}
@@ -968,9 +1001,10 @@ void AnimationPlayer::_animation_process_animation(AnimationData *p_anim, double
void AnimationPlayer::_animation_process_data(PlaybackData &cd, double p_delta, float p_blend, bool p_seeked, bool p_started) {
double delta = p_delta * speed_scale * cd.speed_scale;
double next_pos = cd.pos + delta;
+ bool backwards = signbit(delta); // Negative zero means playing backwards too.
real_t len = cd.from->animation->get_length();
- int pingponged = 0;
+ Animation::LoopedFlag looped_flag = Animation::LOOPED_FLAG_NONE;
switch (cd.from->animation->get_loop_mode()) {
case Animation::LOOP_NONE: {
@@ -979,64 +1013,57 @@ void AnimationPlayer::_animation_process_data(PlaybackData &cd, double p_delta,
} else if (next_pos > len) {
next_pos = len;
}
-
- bool backwards = signbit(delta); // Negative zero means playing backwards too
- delta = next_pos - cd.pos; // Fix delta (after determination of backwards because negative zero is lost here)
-
- if (&cd == &playback.current) {
- if (!backwards && cd.pos <= len && next_pos == len) {
- //playback finished
- end_reached = true;
- end_notify = cd.pos < len; // Notify only if not already at the end
- }
-
- if (backwards && cd.pos >= 0 && next_pos == 0) {
- //playback finished
- end_reached = true;
- end_notify = cd.pos > 0; // Notify only if not already at the beginning
- }
- }
+ delta = next_pos - cd.pos; // Fix delta (after determination of backwards because negative zero is lost here).
} break;
case Animation::LOOP_LINEAR: {
- double looped_next_pos = Math::fposmod(next_pos, (double)len);
- if (looped_next_pos == 0 && next_pos != 0) {
- // Loop multiples of the length to it, rather than 0
- // so state at time=length is previewable in the editor
- next_pos = len;
- } else {
- next_pos = looped_next_pos;
+ if (next_pos < 0 && cd.pos >= 0) {
+ looped_flag = Animation::LOOPED_FLAG_START;
+ }
+ if (next_pos > len && cd.pos <= len) {
+ looped_flag = Animation::LOOPED_FLAG_END;
}
+ next_pos = Math::fposmod(next_pos, (double)len);
} break;
case Animation::LOOP_PINGPONG: {
- if ((int)Math::floor(abs(next_pos - cd.pos) / len) % 2 == 0) {
- if (next_pos < 0 && cd.pos >= 0) {
- cd.speed_scale *= -1.0;
- pingponged = -1;
- }
- if (next_pos > len && cd.pos <= len) {
- cd.speed_scale *= -1.0;
- pingponged = 1;
- }
+ if (next_pos < 0 && cd.pos >= 0) {
+ cd.speed_scale *= -1.0;
+ looped_flag = Animation::LOOPED_FLAG_START;
}
- double looped_next_pos = Math::pingpong(next_pos, (double)len);
- if (looped_next_pos == 0 && next_pos != 0) {
- // Loop multiples of the length to it, rather than 0
- // so state at time=length is previewable in the editor
- next_pos = len;
- } else {
- next_pos = looped_next_pos;
+ if (next_pos > len && cd.pos <= len) {
+ cd.speed_scale *= -1.0;
+ looped_flag = Animation::LOOPED_FLAG_END;
}
+ next_pos = Math::pingpong(next_pos, (double)len);
} break;
default:
break;
}
+ double prev_pos = cd.pos; // The animation may be changed during process, so it is safer that the state is changed before process.
cd.pos = next_pos;
- _animation_process_animation(cd.from, cd.pos, delta, p_blend, &cd == &playback.current, p_seeked, p_started, pingponged);
+ AnimationData *prev_from = cd.from;
+ _animation_process_animation(cd.from, prev_pos, cd.pos, delta, p_blend, &cd == &playback.current, p_seeked, p_started, looped_flag);
+
+ // End detection.
+ if (cd.from->animation->get_loop_mode() == Animation::LOOP_NONE) {
+ if (prev_from != playback.current.from) {
+ return; // Animation has been changed in the process (may be caused by method track), abort process.
+ }
+ if (!backwards && prev_pos <= len && next_pos == len) {
+ // Playback finished.
+ end_reached = true;
+ end_notify = prev_pos < len; // Notify only if not already at the end.
+ }
+ if (backwards && prev_pos >= 0 && next_pos == 0) {
+ // Playback finished.
+ end_reached = true;
+ end_notify = prev_pos > 0; // Notify only if not already at the beginning.
+ }
+ }
}
void AnimationPlayer::_animation_process2(double p_delta, bool p_started) {
@@ -1044,24 +1071,35 @@ void AnimationPlayer::_animation_process2(double p_delta, bool p_started) {
accum_pass++;
- _animation_process_data(c.current, p_delta, 1.0f, c.seeked && p_delta != 0, p_started);
+ bool seeked = c.seeked; // The animation may be changed during process, so it is safer that the state is changed before process.
+
if (p_delta != 0) {
c.seeked = false;
}
- List<Blend>::Element *prev = nullptr;
- for (List<Blend>::Element *E = c.blend.back(); E; E = prev) {
+ float blend = 1.0; // First animation we play at 100% blend
+
+ List<Blend>::Element *next = NULL;
+ for (List<Blend>::Element *E = c.blend.front(); E; E = next) {
Blend &b = E->get();
- float blend = b.blend_left / b.blend_time;
+ // Note: There may be issues if an animation event triggers an animation change while this blend is active,
+ // so it is best to use "deferred" calls instead of "immediate" for animation events that can trigger new animations.
_animation_process_data(b.data, p_delta, blend, false, false);
-
+ blend = 1.0 - b.blend_left / b.blend_time; // This is how much to blend the NEXT animation
b.blend_left -= Math::absf(speed_scale * p_delta);
-
- prev = E->prev();
+ next = E->next();
if (b.blend_left < 0) {
- c.blend.erase(E);
+ // If the blend of this has finished, we need to remove ALL the previous blends
+ List<Blend>::Element *prev;
+ while (E) {
+ prev = E->prev();
+ c.blend.erase(E);
+ E = prev;
+ }
}
}
+
+ _animation_process_data(c.current, p_delta, blend, seeked, p_started);
}
void AnimationPlayer::_animation_update_transforms() {
@@ -1101,8 +1139,6 @@ void AnimationPlayer::_animation_update_transforms() {
}
}
- cache_update_size = 0;
-
for (int i = 0; i < cache_update_prop_size; i++) {
TrackNodeCache::PropertyAnim *pa = cache_update_prop[i];
@@ -1164,29 +1200,35 @@ void AnimationPlayer::_animation_update_transforms() {
}
}
- cache_update_prop_size = 0;
-
for (int i = 0; i < cache_update_bezier_size; i++) {
TrackNodeCache::BezierAnim *ba = cache_update_bezier[i];
ERR_CONTINUE(ba->accum_pass != accum_pass);
ba->object->set_indexed(ba->bezier_property, ba->bezier_accum);
}
-
- cache_update_bezier_size = 0;
}
void AnimationPlayer::_animation_process(double p_delta) {
if (playback.current.from) {
end_reached = false;
end_notify = false;
- _animation_process2(p_delta, playback.started);
+ bool started = playback.started; // The animation may be changed during process, so it is safer that the state is changed before process.
if (playback.started) {
playback.started = false;
}
+ cache_update_size = 0;
+ cache_update_prop_size = 0;
+ cache_update_bezier_size = 0;
+
+ AnimationData *prev_from = playback.current.from;
+ _animation_process2(p_delta, started);
+ if (prev_from != playback.current.from) {
+ return; // Animation has been changed in the process (may be caused by method track), abort process.
+ }
_animation_update_transforms();
+
if (end_reached) {
if (queued.size()) {
String old = playback.assigned;
@@ -1274,23 +1316,6 @@ void AnimationPlayer::_animation_set_cache_update() {
}
void AnimationPlayer::_animation_added(const StringName &p_name, const StringName &p_library) {
- {
- int at_pos = -1;
-
- for (uint32_t i = 0; i < animation_libraries.size(); i++) {
- if (animation_libraries[i].name == p_library) {
- at_pos = i;
- break;
- }
- }
-
- ERR_FAIL_COND(at_pos == -1);
-
- ERR_FAIL_COND(!animation_libraries[at_pos].library->animations.has(p_name));
-
- _ref_anim(animation_libraries[at_pos].library->animations[p_name]);
- }
-
_animation_set_cache_update();
}
@@ -1301,11 +1326,6 @@ void AnimationPlayer::_animation_removed(const StringName &p_name, const StringN
return; // No need to update because not the one from the library being used.
}
- AnimationData animation_data = animation_set[name];
- if (animation_data.animation_library == p_library) {
- _unref_anim(animation_data.animation);
- }
-
_animation_set_cache_update();
// Erase blends if needed
@@ -1401,10 +1421,7 @@ Error AnimationPlayer::add_animation_library(const StringName &p_name, const Ref
ald.library->connect(SNAME("animation_added"), callable_mp(this, &AnimationPlayer::_animation_added).bind(p_name));
ald.library->connect(SNAME("animation_removed"), callable_mp(this, &AnimationPlayer::_animation_removed).bind(p_name));
ald.library->connect(SNAME("animation_renamed"), callable_mp(this, &AnimationPlayer::_animation_renamed).bind(p_name));
-
- for (const KeyValue<StringName, Ref<Animation>> &K : ald.library->animations) {
- _ref_anim(K.value);
- }
+ ald.library->connect(SNAME("animation_changed"), callable_mp(this, &AnimationPlayer::_animation_changed));
_animation_set_cache_update();
@@ -1428,27 +1445,16 @@ void AnimationPlayer::remove_animation_library(const StringName &p_name) {
animation_libraries[at_pos].library->disconnect(SNAME("animation_added"), callable_mp(this, &AnimationPlayer::_animation_added));
animation_libraries[at_pos].library->disconnect(SNAME("animation_removed"), callable_mp(this, &AnimationPlayer::_animation_removed));
animation_libraries[at_pos].library->disconnect(SNAME("animation_renamed"), callable_mp(this, &AnimationPlayer::_animation_renamed));
+ animation_libraries[at_pos].library->disconnect(SNAME("animation_changed"), callable_mp(this, &AnimationPlayer::_animation_changed));
stop();
- for (const KeyValue<StringName, Ref<Animation>> &K : animation_libraries[at_pos].library->animations) {
- _unref_anim(K.value);
- }
-
animation_libraries.remove_at(at_pos);
_animation_set_cache_update();
notify_property_list_changed();
}
-void AnimationPlayer::_ref_anim(const Ref<Animation> &p_anim) {
- Ref<Animation>(p_anim)->connect(SceneStringNames::get_singleton()->tracks_changed, callable_mp(this, &AnimationPlayer::_animation_changed), CONNECT_REFERENCE_COUNTED);
-}
-
-void AnimationPlayer::_unref_anim(const Ref<Animation> &p_anim) {
- Ref<Animation>(p_anim)->disconnect(SceneStringNames::get_singleton()->tracks_changed, callable_mp(this, &AnimationPlayer::_animation_changed));
-}
-
void AnimationPlayer::rename_animation_library(const StringName &p_name, const StringName &p_new_name) {
if (p_name == p_new_name) {
return;
@@ -1646,6 +1652,8 @@ void AnimationPlayer::play(const StringName &p_name, double p_custom_blend, floa
b.data = c.current;
b.blend_time = b.blend_left = blend_time;
c.blend.push_back(b);
+ } else {
+ c.blend.clear();
}
}
@@ -1799,9 +1807,8 @@ double AnimationPlayer::get_current_animation_length() const {
return playback.current.from->animation->get_length();
}
-void AnimationPlayer::_animation_changed() {
+void AnimationPlayer::_animation_changed(const StringName &p_name) {
clear_caches();
- emit_signal(SNAME("caches_cleared"));
if (is_playing()) {
playback.seeked = true; //need to restart stuff, like audio
}
@@ -1840,6 +1847,8 @@ void AnimationPlayer::clear_caches() {
cache_update_size = 0;
cache_update_prop_size = 0;
cache_update_bezier_size = 0;
+
+ emit_signal(SNAME("caches_cleared"));
}
void AnimationPlayer::set_active(bool p_active) {
@@ -2073,7 +2082,7 @@ Ref<AnimatedValuesBackup> AnimationPlayer::apply_reset(bool p_user_initiated) {
old_values->restore();
Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
- ur->create_action(TTR("Anim Apply Reset"));
+ ur->create_action(TTR("Animation Apply Reset"));
ur->add_do_method(new_values.ptr(), "restore");
ur->add_undo_method(old_values.ptr(), "restore");
ur->commit_action();
@@ -2158,7 +2167,7 @@ void AnimationPlayer::_bind_methods() {
ClassDB::bind_method(D_METHOD("advance", "delta"), &AnimationPlayer::advance);
ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "root_node"), "set_root", "get_root");
- ADD_PROPERTY(PropertyInfo(Variant::STRING_NAME, "current_animation", PROPERTY_HINT_ENUM, "", PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_ANIMATE_AS_TRIGGER), "set_current_animation", "get_current_animation");
+ ADD_PROPERTY(PropertyInfo(Variant::STRING_NAME, "current_animation", PROPERTY_HINT_ENUM, "", PROPERTY_USAGE_EDITOR), "set_current_animation", "get_current_animation");
ADD_PROPERTY(PropertyInfo(Variant::STRING_NAME, "assigned_animation", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NONE), "set_assigned_animation", "get_assigned_animation");
ADD_PROPERTY(PropertyInfo(Variant::STRING_NAME, "autoplay", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "set_autoplay", "get_autoplay");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "reset_on_save", PROPERTY_HINT_NONE, ""), "set_reset_on_save_enabled", "is_reset_on_save_enabled");
diff --git a/scene/animation/animation_player.h b/scene/animation/animation_player.h
index 4f32927d25..0b95ee4e9e 100644
--- a/scene/animation/animation_player.h
+++ b/scene/animation/animation_player.h
@@ -268,7 +268,7 @@ private:
NodePath root;
- void _animation_process_animation(AnimationData *p_anim, double p_time, double p_delta, float p_interp, bool p_is_current = true, bool p_seeked = false, bool p_started = false, int p_pingponged = 0);
+ void _animation_process_animation(AnimationData *p_anim, double p_prev_time, double p_time, double p_delta, float p_interp, bool p_is_current = true, bool p_seeked = false, bool p_started = false, Animation::LoopedFlag p_looped_flag = Animation::LOOPED_FLAG_NONE);
void _ensure_node_caches(AnimationData *p_anim, Node *p_root_override = nullptr);
void _animation_process_data(PlaybackData &cd, double p_delta, float p_blend, bool p_seeked, bool p_started);
@@ -291,9 +291,7 @@ private:
return ret;
}
- void _animation_changed();
- void _ref_anim(const Ref<Animation> &p_anim);
- void _unref_anim(const Ref<Animation> &p_anim);
+ void _animation_changed(const StringName &p_name);
void _set_process(bool p_process, bool p_force = false);
diff --git a/scene/animation/animation_tree.cpp b/scene/animation/animation_tree.cpp
index 517908077d..b3408c1509 100644
--- a/scene/animation/animation_tree.cpp
+++ b/scene/animation/animation_tree.cpp
@@ -86,7 +86,7 @@ void AnimationNode::get_child_nodes(List<ChildNode> *r_child_nodes) {
}
}
-void AnimationNode::blend_animation(const StringName &p_animation, double p_time, double p_delta, bool p_seeked, bool p_seek_root, real_t p_blend, int p_pingponged) {
+void AnimationNode::blend_animation(const StringName &p_animation, double p_time, double p_delta, bool p_seeked, bool p_is_external_seeking, real_t p_blend, Animation::LoopedFlag p_looped_flag) {
ERR_FAIL_COND(!state);
ERR_FAIL_COND(!state->player->has_animation(p_animation));
@@ -112,19 +112,19 @@ void AnimationNode::blend_animation(const StringName &p_animation, double p_time
anim_state.time = p_time;
anim_state.animation = animation;
anim_state.seeked = p_seeked;
- anim_state.pingponged = p_pingponged;
- anim_state.seek_root = p_seek_root;
+ anim_state.looped_flag = p_looped_flag;
+ anim_state.is_external_seeking = p_is_external_seeking;
state->animation_states.push_back(anim_state);
}
-double AnimationNode::_pre_process(const StringName &p_base_path, AnimationNode *p_parent, State *p_state, double p_time, bool p_seek, bool p_seek_root, const Vector<StringName> &p_connections) {
+double AnimationNode::_pre_process(const StringName &p_base_path, AnimationNode *p_parent, State *p_state, double p_time, bool p_seek, bool p_is_external_seeking, const Vector<StringName> &p_connections) {
base_path = p_base_path;
parent = p_parent;
connections = p_connections;
state = p_state;
- double t = process(p_time, p_seek, p_seek_root);
+ double t = process(p_time, p_seek, p_is_external_seeking);
state = nullptr;
parent = nullptr;
@@ -148,7 +148,7 @@ void AnimationNode::make_invalid(const String &p_reason) {
state->invalid_reasons += String::utf8("• ") + p_reason;
}
-double AnimationNode::blend_input(int p_input, double p_time, bool p_seek, bool p_seek_root, real_t p_blend, FilterAction p_filter, bool p_sync) {
+double AnimationNode::blend_input(int p_input, double p_time, bool p_seek, bool p_is_external_seeking, real_t p_blend, FilterAction p_filter, bool p_sync) {
ERR_FAIL_INDEX_V(p_input, inputs.size(), 0);
ERR_FAIL_COND_V(!state, 0);
@@ -167,7 +167,7 @@ double AnimationNode::blend_input(int p_input, double p_time, bool p_seek, bool
//inputs.write[p_input].last_pass = state->last_pass;
real_t activity = 0.0;
- double ret = _blend_node(node_name, blend_tree->get_node_connection_array(node_name), nullptr, node, p_time, p_seek, p_seek_root, p_blend, p_filter, p_sync, &activity);
+ double ret = _blend_node(node_name, blend_tree->get_node_connection_array(node_name), nullptr, node, p_time, p_seek, p_is_external_seeking, p_blend, p_filter, p_sync, &activity);
Vector<AnimationTree::Activity> *activity_ptr = state->tree->input_activity_map.getptr(base_path);
@@ -178,11 +178,11 @@ double AnimationNode::blend_input(int p_input, double p_time, bool p_seek, bool
return ret;
}
-double AnimationNode::blend_node(const StringName &p_sub_path, Ref<AnimationNode> p_node, double p_time, bool p_seek, bool p_seek_root, real_t p_blend, FilterAction p_filter, bool p_sync) {
- return _blend_node(p_sub_path, Vector<StringName>(), this, p_node, p_time, p_seek, p_seek_root, p_blend, p_filter, p_sync);
+double AnimationNode::blend_node(const StringName &p_sub_path, Ref<AnimationNode> p_node, double p_time, bool p_seek, bool p_is_external_seeking, real_t p_blend, FilterAction p_filter, bool p_sync) {
+ return _blend_node(p_sub_path, Vector<StringName>(), this, p_node, p_time, p_seek, p_is_external_seeking, p_blend, p_filter, p_sync);
}
-double AnimationNode::_blend_node(const StringName &p_subpath, const Vector<StringName> &p_connections, AnimationNode *p_new_parent, Ref<AnimationNode> p_node, double p_time, bool p_seek, bool p_seek_root, real_t p_blend, FilterAction p_filter, bool p_sync, real_t *r_max) {
+double AnimationNode::_blend_node(const StringName &p_subpath, const Vector<StringName> &p_connections, AnimationNode *p_new_parent, Ref<AnimationNode> p_node, double p_time, bool p_seek, bool p_is_external_seeking, real_t p_blend, FilterAction p_filter, bool p_sync, real_t *r_max) {
ERR_FAIL_COND_V(!p_node.is_valid(), 0);
ERR_FAIL_COND_V(!state, 0);
@@ -221,7 +221,7 @@ double AnimationNode::_blend_node(const StringName &p_subpath, const Vector<Stri
}
blendw[i] = blendr[i] * p_blend;
- if (blendw[i] > CMP_EPSILON) {
+ if (!Math::is_zero_approx(blendw[i])) {
any_valid = true;
}
}
@@ -236,7 +236,7 @@ double AnimationNode::_blend_node(const StringName &p_subpath, const Vector<Stri
}
blendw[i] = blendr[i] * p_blend;
- if (blendw[i] > CMP_EPSILON) {
+ if (!Math::is_zero_approx(blendw[i])) {
any_valid = true;
}
}
@@ -252,7 +252,7 @@ double AnimationNode::_blend_node(const StringName &p_subpath, const Vector<Stri
blendw[i] = blendr[i]; //not filtered, do not blend
}
- if (blendw[i] > CMP_EPSILON) {
+ if (!Math::is_zero_approx(blendw[i])) {
any_valid = true;
}
}
@@ -263,7 +263,7 @@ double AnimationNode::_blend_node(const StringName &p_subpath, const Vector<Stri
for (int i = 0; i < blend_count; i++) {
//regular blend
blendw[i] = blendr[i] * p_blend;
- if (blendw[i] > CMP_EPSILON) {
+ if (!Math::is_zero_approx(blendw[i])) {
any_valid = true;
}
}
@@ -289,15 +289,12 @@ double AnimationNode::_blend_node(const StringName &p_subpath, const Vector<Stri
new_path = String(parent->base_path) + String(p_subpath) + "/";
}
- // If tracks for blending don't exist for one of the animations, Rest or RESET animation is blended as init animation instead.
- // Then blend weight is 0 means that the init animation blend weight is 1.
- // In that case, processing only the animation with the lacking track will not process the lacking track, and will not properly apply the Reset value.
- // This means that all tracks which the animations in the branch that may be blended have must be processed.
- // Therefore, the blending process must be executed even if the blend weight is 0.
+ // This process, which depends on p_sync is needed to process sync correctly in the case of
+ // that a synced AnimationNodeSync exists under the un-synced AnimationNodeSync.
if (!p_seek && !p_sync && !any_valid) {
- return p_node->_pre_process(new_path, new_parent, state, 0, p_seek, p_seek_root, p_connections);
+ return p_node->_pre_process(new_path, new_parent, state, 0, p_seek, p_is_external_seeking, p_connections);
}
- return p_node->_pre_process(new_path, new_parent, state, p_time, p_seek, p_seek_root, p_connections);
+ return p_node->_pre_process(new_path, new_parent, state, p_time, p_seek, p_is_external_seeking, p_connections);
}
int AnimationNode::get_input_count() const {
@@ -338,9 +335,9 @@ void AnimationNode::remove_input(int p_index) {
emit_changed();
}
-double AnimationNode::process(double p_time, bool p_seek, bool p_seek_root) {
+double AnimationNode::process(double p_time, bool p_seek, bool p_is_external_seeking) {
double ret = 0;
- GDVIRTUAL_CALL(_process, p_time, p_seek, p_seek_root, ret);
+ GDVIRTUAL_CALL(_process, p_time, p_seek, p_is_external_seeking, ret);
return ret;
}
@@ -416,9 +413,9 @@ void AnimationNode::_bind_methods() {
ClassDB::bind_method(D_METHOD("_set_filters", "filters"), &AnimationNode::_set_filters);
ClassDB::bind_method(D_METHOD("_get_filters"), &AnimationNode::_get_filters);
- ClassDB::bind_method(D_METHOD("blend_animation", "animation", "time", "delta", "seeked", "seek_root", "blend", "pingponged"), &AnimationNode::blend_animation, DEFVAL(0));
- ClassDB::bind_method(D_METHOD("blend_node", "name", "node", "time", "seek", "seek_root", "blend", "filter", "sync"), &AnimationNode::blend_node, DEFVAL(FILTER_IGNORE), DEFVAL(true));
- ClassDB::bind_method(D_METHOD("blend_input", "input_index", "time", "seek", "seek_root", "blend", "filter", "sync"), &AnimationNode::blend_input, DEFVAL(FILTER_IGNORE), DEFVAL(true));
+ ClassDB::bind_method(D_METHOD("blend_animation", "animation", "time", "delta", "seeked", "is_external_seeking", "blend", "looped_flag"), &AnimationNode::blend_animation, DEFVAL(Animation::LOOPED_FLAG_NONE));
+ ClassDB::bind_method(D_METHOD("blend_node", "name", "node", "time", "seek", "is_external_seeking", "blend", "filter", "sync"), &AnimationNode::blend_node, DEFVAL(FILTER_IGNORE), DEFVAL(true));
+ ClassDB::bind_method(D_METHOD("blend_input", "input_index", "time", "seek", "is_external_seeking", "blend", "filter", "sync"), &AnimationNode::blend_input, DEFVAL(FILTER_IGNORE), DEFVAL(true));
ClassDB::bind_method(D_METHOD("set_parameter", "name", "value"), &AnimationNode::set_parameter);
ClassDB::bind_method(D_METHOD("get_parameter", "name"), &AnimationNode::get_parameter);
@@ -430,12 +427,11 @@ void AnimationNode::_bind_methods() {
GDVIRTUAL_BIND(_get_parameter_list);
GDVIRTUAL_BIND(_get_child_by_name, "name");
GDVIRTUAL_BIND(_get_parameter_default_value, "parameter");
- GDVIRTUAL_BIND(_process, "time", "seek", "seek_root");
+ GDVIRTUAL_BIND(_process, "time", "seek", "is_external_seeking");
GDVIRTUAL_BIND(_get_caption);
GDVIRTUAL_BIND(_has_filter);
ADD_SIGNAL(MethodInfo("removed_from_graph"));
-
ADD_SIGNAL(MethodInfo("tree_changed"));
BIND_ENUM_CONSTANT(FILTER_IGNORE);
@@ -589,6 +585,7 @@ bool AnimationTree::_update_caches(AnimationPlayer *player) {
track_value->object = child;
}
+ track_value->is_discrete = anim->value_track_get_update_mode(i) == Animation::UPDATE_DISCRETE;
track_value->is_using_angle = anim->track_get_interpolation_type(i) == Animation::INTERPOLATION_LINEAR_ANGLE || anim->track_get_interpolation_type(i) == Animation::INTERPOLATION_CUBIC_ANGLE;
track_value->subpath = leftover_path;
@@ -596,6 +593,13 @@ bool AnimationTree::_update_caches(AnimationPlayer *player) {
track = track_value;
+ // If a value track without a key is cached first, the initial value cannot be determined.
+ // It is a corner case, but which may cause problems with blending.
+ ERR_CONTINUE_MSG(anim->track_get_key_count(i) == 0, "AnimationTree: '" + String(E) + "', value track: '" + String(path) + "' must have at least one key to cache for blending.");
+ track_value->init_value = anim->track_get_key_value(i, 0);
+ track_value->init_value.zero();
+
+ // If there is a Reset Animation, it takes precedence by overwriting.
if (has_reset_anim) {
int rt = reset_anim->find_track(path, track_type);
if (rt >= 0 && reset_anim->track_get_key_count(rt) > 0) {
@@ -795,8 +799,18 @@ bool AnimationTree::_update_caches(AnimationPlayer *player) {
}
} else if (track_cache_type == Animation::TYPE_VALUE) {
// If it has at least one angle interpolation, it also uses angle interpolation for blending.
- TrackCacheValue *track_value = memnew(TrackCacheValue);
+ TrackCacheValue *track_value = static_cast<TrackCacheValue *>(track);
+ bool was_discrete = track_value->is_discrete;
+ bool was_using_angle = track_value->is_using_angle;
+ track_value->is_discrete |= anim->value_track_get_update_mode(i) == Animation::UPDATE_DISCRETE;
track_value->is_using_angle |= anim->track_get_interpolation_type(i) == Animation::INTERPOLATION_LINEAR_ANGLE || anim->track_get_interpolation_type(i) == Animation::INTERPOLATION_CUBIC_ANGLE;
+
+ if (was_discrete != track_value->is_discrete) {
+ ERR_PRINT_ED("Value track: " + String(path) + " with different update modes are blended. Blending prioritizes Discrete mode, so other update mode tracks will not be blended.");
+ }
+ if (was_using_angle != track_value->is_using_angle) {
+ WARN_PRINT_ED("Value track: " + String(path) + " with different interpolation types for rotation are blended. Blending prioritizes angle interpolation, so the blending result uses the shortest path referenced to the initial (RESET animation) value.");
+ }
}
track->setup_pass = setup_pass;
@@ -844,7 +858,6 @@ void AnimationTree::_clear_caches() {
memdelete(K.value);
}
playing_caches.clear();
-
track_cache.clear();
cache_valid = false;
}
@@ -868,7 +881,9 @@ void AnimationTree::_process_graph(double p_delta) {
_update_properties(); //if properties need updating, update them
//check all tracks, see if they need modification
- root_motion_transform = Transform3D();
+ root_motion_position = Vector3(0, 0, 0);
+ root_motion_rotation = Quaternion(0, 0, 0, 1);
+ root_motion_scale = Vector3(0, 0, 0);
if (!root.is_valid()) {
ERR_PRINT("AnimationTree: root AnimationNode is not set, disabling playback.");
@@ -955,8 +970,44 @@ void AnimationTree::_process_graph(double p_delta) {
if (!state.valid) {
return; //state is not valid. do nothing.
}
- //apply value/transform/bezier blends to track caches and execute method/audio/animation tracks
+ // Init all value/transform/blend/bezier tracks that track_cache has.
+ {
+ for (const KeyValue<NodePath, TrackCache *> &K : track_cache) {
+ TrackCache *track = K.value;
+
+ switch (track->type) {
+ case Animation::TYPE_POSITION_3D: {
+ TrackCacheTransform *t = static_cast<TrackCacheTransform *>(track);
+ if (track->root_motion) {
+ t->loc = Vector3(0, 0, 0);
+ t->rot = Quaternion(0, 0, 0, 1);
+ t->scale = Vector3(1, 1, 1);
+ } else {
+ t->loc = t->init_loc;
+ t->rot = t->init_rot;
+ t->scale = t->init_scale;
+ }
+ } break;
+ case Animation::TYPE_BLEND_SHAPE: {
+ TrackCacheBlendShape *t = static_cast<TrackCacheBlendShape *>(track);
+ t->value = t->init_value;
+ } break;
+ case Animation::TYPE_VALUE: {
+ TrackCacheValue *t = static_cast<TrackCacheValue *>(track);
+ t->value = t->init_value;
+ } break;
+ case Animation::TYPE_BEZIER: {
+ TrackCacheBezier *t = static_cast<TrackCacheBezier *>(track);
+ t->value = t->init_value;
+ } break;
+ default: {
+ } break;
+ }
+ }
+ }
+
+ // Apply value/transform/blend/bezier blends to track caches and execute method/audio/animation tracks.
{
bool can_call = is_inside_tree() && !Engine::get_singleton()->is_editor_hint();
@@ -966,10 +1017,11 @@ void AnimationTree::_process_graph(double p_delta) {
double delta = as.delta;
real_t weight = as.blend;
bool seeked = as.seeked;
- int pingponged = as.pingponged;
+ Animation::LoopedFlag looped_flag = as.looped_flag;
+ bool is_external_seeking = as.is_external_seeking;
#ifndef _3D_DISABLED
- bool backward = signbit(delta);
- bool calc_root = !seeked || as.seek_root;
+ bool backward = signbit(delta); // This flag is required only for the root motion since it calculates the difference between the previous and current frames.
+ bool calc_root = !seeked || is_external_seeking;
#endif // _3D_DISABLED
for (int i = 0; i < a->get_track_count(); i++) {
@@ -978,37 +1030,31 @@ void AnimationTree::_process_graph(double p_delta) {
}
NodePath path = a->track_get_path(i);
-
- ERR_CONTINUE(!track_cache.has(path));
-
+ if (!track_cache.has(path)) {
+ continue; // No path, but avoid error spamming.
+ }
TrackCache *track = track_cache[path];
+ ERR_CONTINUE(!state.track_map.has(path));
+ int blend_idx = state.track_map[path];
+ ERR_CONTINUE(blend_idx < 0 || blend_idx >= state.track_count);
+ real_t blend = (*as.track_blends)[blend_idx] * weight;
+ if (Math::is_zero_approx(blend)) {
+ continue; // Nothing to blend.
+ }
+
Animation::TrackType ttype = a->track_get_type(i);
if (ttype != Animation::TYPE_POSITION_3D && ttype != Animation::TYPE_ROTATION_3D && ttype != Animation::TYPE_SCALE_3D && track->type != ttype) {
//broken animation, but avoid error spamming
continue;
}
-
track->root_motion = root_motion_track == path;
- ERR_CONTINUE(!state.track_map.has(path));
- int blend_idx = state.track_map[path];
-
- ERR_CONTINUE(blend_idx < 0 || blend_idx >= state.track_count);
-
- real_t blend = (*as.track_blends)[blend_idx] * weight;
-
switch (ttype) {
case Animation::TYPE_POSITION_3D: {
#ifndef _3D_DISABLED
TrackCacheTransform *t = static_cast<TrackCacheTransform *>(track);
if (track->root_motion && calc_root) {
- if (t->process_pass != process_pass) {
- t->process_pass = process_pass;
- t->loc = Vector3(0, 0, 0);
- t->rot = Quaternion(0, 0, 0, 1);
- t->scale = Vector3(0, 0, 0);
- }
double prev_time = time - delta;
if (!backward) {
if (prev_time < 0) {
@@ -1084,12 +1130,6 @@ void AnimationTree::_process_graph(double p_delta) {
prev_time = !backward ? 0 : (double)a->get_length();
} else {
- if (t->process_pass != process_pass) {
- t->process_pass = process_pass;
- t->loc = t->init_loc;
- t->rot = t->init_rot;
- t->scale = t->init_scale;
- }
Vector3 loc;
Error err = a->position_track_interpolate(i, time, &loc);
@@ -1106,12 +1146,6 @@ void AnimationTree::_process_graph(double p_delta) {
#ifndef _3D_DISABLED
TrackCacheTransform *t = static_cast<TrackCacheTransform *>(track);
if (track->root_motion && calc_root) {
- if (t->process_pass != process_pass) {
- t->process_pass = process_pass;
- t->loc = Vector3(0, 0, 0);
- t->rot = Quaternion(0, 0, 0, 1);
- t->scale = Vector3(0, 0, 0);
- }
double prev_time = time - delta;
if (!backward) {
if (prev_time < 0) {
@@ -1186,12 +1220,6 @@ void AnimationTree::_process_graph(double p_delta) {
prev_time = !backward ? 0 : (double)a->get_length();
} else {
- if (t->process_pass != process_pass) {
- t->process_pass = process_pass;
- t->loc = t->init_loc;
- t->rot = t->init_rot;
- t->scale = t->init_scale;
- }
Quaternion rot;
Error err = a->rotation_track_interpolate(i, time, &rot);
@@ -1208,12 +1236,6 @@ void AnimationTree::_process_graph(double p_delta) {
#ifndef _3D_DISABLED
TrackCacheTransform *t = static_cast<TrackCacheTransform *>(track);
if (track->root_motion && calc_root) {
- if (t->process_pass != process_pass) {
- t->process_pass = process_pass;
- t->loc = Vector3(0, 0, 0);
- t->rot = Quaternion(0, 0, 0, 1);
- t->scale = Vector3(0, 0, 0);
- }
double prev_time = time - delta;
if (!backward) {
if (prev_time < 0) {
@@ -1289,12 +1311,6 @@ void AnimationTree::_process_graph(double p_delta) {
prev_time = !backward ? 0 : (double)a->get_length();
} else {
- if (t->process_pass != process_pass) {
- t->process_pass = process_pass;
- t->loc = t->init_loc;
- t->rot = t->init_rot;
- t->scale = t->init_scale;
- }
Vector3 scale;
Error err = a->scale_track_interpolate(i, time, &scale);
@@ -1311,11 +1327,6 @@ void AnimationTree::_process_graph(double p_delta) {
#ifndef _3D_DISABLED
TrackCacheBlendShape *t = static_cast<TrackCacheBlendShape *>(track);
- if (t->process_pass != process_pass) {
- t->process_pass = process_pass;
- t->value = t->init_value;
- }
-
float value;
Error err = a->blend_shape_track_interpolate(i, time, &value);
@@ -1342,15 +1353,6 @@ void AnimationTree::_process_graph(double p_delta) {
continue;
}
- if (t->process_pass != process_pass) {
- t->process_pass = process_pass;
- if (!t->init_value) {
- t->init_value = value;
- t->init_value.zero();
- }
- t->value = t->init_value;
- }
-
// Special case for angle interpolation.
if (t->is_using_angle) {
// For blending consistency, it prevents rotation of more than 180 degrees from init_value.
@@ -1379,12 +1381,8 @@ void AnimationTree::_process_graph(double p_delta) {
}
}
} else {
- if (blend < CMP_EPSILON) {
- continue; //nothing to blend
- }
-
if (seeked) {
- int idx = a->track_find_key(i, time);
+ int idx = a->track_find_key(i, time, is_external_seeking ? Animation::FIND_MODE_NEAREST : Animation::FIND_MODE_EXACT);
if (idx < 0) {
continue;
}
@@ -1393,7 +1391,7 @@ void AnimationTree::_process_graph(double p_delta) {
t->object->set_indexed(t->subpath, value);
} else {
List<int> indices;
- a->value_track_get_key_indices(i, time, delta, &indices, pingponged);
+ a->track_get_key_indices_in_range(i, time, delta, &indices, looped_flag);
for (int &F : indices) {
Variant value = a->track_get_key_value(i, F);
value = _post_process_key_value(a, i, value, t->object);
@@ -1404,13 +1402,10 @@ void AnimationTree::_process_graph(double p_delta) {
} break;
case Animation::TYPE_METHOD: {
- if (blend < CMP_EPSILON) {
- continue; //nothing to blend
- }
TrackCacheMethod *t = static_cast<TrackCacheMethod *>(track);
if (seeked) {
- int idx = a->track_find_key(i, time);
+ int idx = a->track_find_key(i, time, is_external_seeking ? Animation::FIND_MODE_NEAREST : Animation::FIND_MODE_EXACT);
if (idx < 0) {
continue;
}
@@ -1421,7 +1416,7 @@ void AnimationTree::_process_graph(double p_delta) {
}
} else {
List<int> indices;
- a->method_track_get_key_indices(i, time, delta, &indices, pingponged);
+ a->track_get_key_indices_in_range(i, time, delta, &indices, looped_flag);
for (int &F : indices) {
StringName method = a->method_track_get_name(i, F);
Vector<Variant> params = a->method_track_get_params(i, F);
@@ -1437,22 +1432,14 @@ void AnimationTree::_process_graph(double p_delta) {
real_t bezier = a->bezier_track_interpolate(i, time);
bezier = _post_process_key_value(a, i, bezier, t->object);
- if (t->process_pass != process_pass) {
- t->process_pass = process_pass;
- t->value = t->init_value;
- }
-
t->value += (bezier - t->init_value) * blend;
} break;
case Animation::TYPE_AUDIO: {
- if (blend < CMP_EPSILON) {
- continue; //nothing to blend
- }
TrackCacheAudio *t = static_cast<TrackCacheAudio *>(track);
if (seeked) {
//find whatever should be playing
- int idx = a->track_find_key(i, time);
+ int idx = a->track_find_key(i, time, is_external_seeking ? Animation::FIND_MODE_NEAREST : Animation::FIND_MODE_EXACT);
if (idx < 0) {
continue;
}
@@ -1492,7 +1479,7 @@ void AnimationTree::_process_graph(double p_delta) {
} else {
//find stuff to play
List<int> to_play;
- a->track_get_key_indices_in_range(i, time, delta, &to_play, pingponged);
+ a->track_get_key_indices_in_range(i, time, delta, &to_play, looped_flag);
if (to_play.size()) {
int idx = to_play.back()->get();
@@ -1555,9 +1542,6 @@ void AnimationTree::_process_graph(double p_delta) {
t->object->call(SNAME("set_volume_db"), db);
} break;
case Animation::TYPE_ANIMATION: {
- if (blend < CMP_EPSILON) {
- continue; //nothing to blend
- }
TrackCacheAnimation *t = static_cast<TrackCacheAnimation *>(track);
AnimationPlayer *player2 = Object::cast_to<AnimationPlayer>(t->object);
@@ -1568,7 +1552,7 @@ void AnimationTree::_process_graph(double p_delta) {
if (seeked) {
//seek
- int idx = a->track_find_key(i, time);
+ int idx = a->track_find_key(i, time, is_external_seeking ? Animation::FIND_MODE_NEAREST : Animation::FIND_MODE_EXACT);
if (idx < 0) {
continue;
}
@@ -1599,8 +1583,8 @@ void AnimationTree::_process_graph(double p_delta) {
}
if (player2->is_playing() || seeked) {
- player2->play(anim_name);
player2->seek(at_anim_pos);
+ player2->play(anim_name);
t->playing = true;
playing_caches.insert(t);
} else {
@@ -1610,7 +1594,7 @@ void AnimationTree::_process_graph(double p_delta) {
} else {
//find stuff to play
List<int> to_play;
- a->track_get_key_indices_in_range(i, time, delta, &to_play, pingponged);
+ a->track_get_key_indices_in_range(i, time, delta, &to_play, looped_flag);
if (to_play.size()) {
int idx = to_play.back()->get();
@@ -1639,9 +1623,6 @@ void AnimationTree::_process_graph(double p_delta) {
// finally, set the tracks
for (const KeyValue<NodePath, TrackCache *> &K : track_cache) {
TrackCache *track = K.value;
- if (track->process_pass != process_pass) {
- continue; //not processed, ignore
- }
switch (track->type) {
case Animation::TYPE_POSITION_3D: {
@@ -1649,11 +1630,9 @@ void AnimationTree::_process_graph(double p_delta) {
TrackCacheTransform *t = static_cast<TrackCacheTransform *>(track);
if (t->root_motion) {
- Transform3D xform;
- xform.origin = t->loc;
- xform.basis.set_quaternion_scale(t->rot, Vector3(1, 1, 1) + t->scale);
-
- root_motion_transform = xform;
+ root_motion_position = t->loc;
+ root_motion_rotation = t->rot;
+ root_motion_scale = t->scale - Vector3(1, 1, 1);
} else if (t->skeleton && t->bone_idx >= 0) {
if (t->loc_used) {
@@ -1691,6 +1670,10 @@ void AnimationTree::_process_graph(double p_delta) {
case Animation::TYPE_VALUE: {
TrackCacheValue *t = static_cast<TrackCacheValue *>(track);
+ if (t->is_discrete) {
+ break; // Don't overwrite the value set by UPDATE_DISCRETE.
+ }
+
if (t->init_value.get_type() == Variant::BOOL) {
t->object->set_indexed(t->subpath, t->value.operator real_t() >= 0.5);
} else {
@@ -1775,7 +1758,7 @@ void AnimationTree::_setup_animation_player() {
AnimationPlayer *new_player = nullptr;
if (!animation_player.is_empty()) {
- new_player = Object::cast_to<AnimationPlayer>(get_node(animation_player));
+ new_player = Object::cast_to<AnimationPlayer>(get_node_or_null(animation_player));
if (new_player && !new_player->is_connected("animation_list_changed", callable_mp(this, &AnimationTree::_animation_player_changed))) {
new_player->connect("animation_list_changed", callable_mp(this, &AnimationTree::_animation_player_changed));
}
@@ -1862,8 +1845,16 @@ NodePath AnimationTree::get_root_motion_track() const {
return root_motion_track;
}
-Transform3D AnimationTree::get_root_motion_transform() const {
- return root_motion_transform;
+Vector3 AnimationTree::get_root_motion_position() const {
+ return root_motion_position;
+}
+
+Quaternion AnimationTree::get_root_motion_rotation() const {
+ return root_motion_rotation;
+}
+
+Vector3 AnimationTree::get_root_motion_scale() const {
+ return root_motion_scale;
}
void AnimationTree::_tree_changed() {
@@ -2021,7 +2012,9 @@ void AnimationTree::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_root_motion_track", "path"), &AnimationTree::set_root_motion_track);
ClassDB::bind_method(D_METHOD("get_root_motion_track"), &AnimationTree::get_root_motion_track);
- ClassDB::bind_method(D_METHOD("get_root_motion_transform"), &AnimationTree::get_root_motion_transform);
+ ClassDB::bind_method(D_METHOD("get_root_motion_position"), &AnimationTree::get_root_motion_position);
+ ClassDB::bind_method(D_METHOD("get_root_motion_rotation"), &AnimationTree::get_root_motion_rotation);
+ ClassDB::bind_method(D_METHOD("get_root_motion_scale"), &AnimationTree::get_root_motion_scale);
ClassDB::bind_method(D_METHOD("_update_properties"), &AnimationTree::_update_properties);
@@ -2043,6 +2036,10 @@ void AnimationTree::_bind_methods() {
BIND_ENUM_CONSTANT(ANIMATION_PROCESS_MANUAL);
ADD_SIGNAL(MethodInfo("animation_player_changed"));
+
+ // Signals from AnimationNodes.
+ ADD_SIGNAL(MethodInfo("animation_started", PropertyInfo(Variant::STRING_NAME, "anim_name")));
+ ADD_SIGNAL(MethodInfo("animation_finished", PropertyInfo(Variant::STRING_NAME, "anim_name")));
}
AnimationTree::AnimationTree() {
diff --git a/scene/animation/animation_tree.h b/scene/animation/animation_tree.h
index 96c1279f82..be0dc1af4e 100644
--- a/scene/animation/animation_tree.h
+++ b/scene/animation/animation_tree.h
@@ -68,8 +68,8 @@ public:
const Vector<real_t> *track_blends = nullptr;
real_t blend = 0.0;
bool seeked = false;
- bool seek_root = false;
- int pingponged = 0;
+ bool is_external_seeking = false;
+ Animation::LoopedFlag looped_flag = Animation::LOOPED_FLAG_NONE;
};
struct State {
@@ -86,7 +86,7 @@ public:
Vector<real_t> blends;
State *state = nullptr;
- double _pre_process(const StringName &p_base_path, AnimationNode *p_parent, State *p_state, double p_time, bool p_seek, bool p_seek_root, const Vector<StringName> &p_connections);
+ double _pre_process(const StringName &p_base_path, AnimationNode *p_parent, State *p_state, double p_time, bool p_seek, bool p_is_external_seeking, const Vector<StringName> &p_connections);
//all this is temporary
StringName base_path;
@@ -99,12 +99,12 @@ public:
Array _get_filters() const;
void _set_filters(const Array &p_filters);
friend class AnimationNodeBlendTree;
- double _blend_node(const StringName &p_subpath, const Vector<StringName> &p_connections, AnimationNode *p_new_parent, Ref<AnimationNode> p_node, double p_time, bool p_seek, bool p_seek_root, real_t p_blend, FilterAction p_filter = FILTER_IGNORE, bool p_sync = true, real_t *r_max = nullptr);
+ double _blend_node(const StringName &p_subpath, const Vector<StringName> &p_connections, AnimationNode *p_new_parent, Ref<AnimationNode> p_node, double p_time, bool p_seek, bool p_is_external_seeking, real_t p_blend, FilterAction p_filter = FILTER_IGNORE, bool p_sync = true, real_t *r_max = nullptr);
protected:
- void blend_animation(const StringName &p_animation, double p_time, double p_delta, bool p_seeked, bool p_seek_root, real_t p_blend, int p_pingponged = 0);
- double blend_node(const StringName &p_sub_path, Ref<AnimationNode> p_node, double p_time, bool p_seek, bool p_seek_root, real_t p_blend, FilterAction p_filter = FILTER_IGNORE, bool p_sync = true);
- double blend_input(int p_input, double p_time, bool p_seek, bool p_seek_root, real_t p_blend, FilterAction p_filter = FILTER_IGNORE, bool p_sync = true);
+ void blend_animation(const StringName &p_animation, double p_time, double p_delta, bool p_seeked, bool p_is_external_seeking, real_t p_blend, Animation::LoopedFlag p_looped_flag = Animation::LOOPED_FLAG_NONE);
+ double blend_node(const StringName &p_sub_path, Ref<AnimationNode> p_node, double p_time, bool p_seek, bool p_is_external_seeking, real_t p_blend, FilterAction p_filter = FILTER_IGNORE, bool p_sync = true);
+ double blend_input(int p_input, double p_time, bool p_seek, bool p_is_external_seeking, real_t p_blend, FilterAction p_filter = FILTER_IGNORE, bool p_sync = true);
void make_invalid(const String &p_reason);
AnimationTree *get_animation_tree() const;
@@ -135,7 +135,7 @@ public:
virtual void get_child_nodes(List<ChildNode> *r_child_nodes);
- virtual double process(double p_time, bool p_seek, bool p_seek_root);
+ virtual double process(double p_time, bool p_seek, bool p_is_external_seeking);
virtual String get_caption() const;
int get_input_count() const;
@@ -190,7 +190,6 @@ private:
struct TrackCache {
bool root_motion = false;
uint64_t setup_pass = 0;
- uint64_t process_pass = 0;
Animation::TrackType type = Animation::TrackType::TYPE_ANIMATION;
Object *object = nullptr;
ObjectID object_id;
@@ -233,6 +232,7 @@ private:
Variant init_value;
Variant value;
Vector<StringName> subpath;
+ bool is_discrete = false;
bool is_using_angle = false;
TrackCacheValue() { type = Animation::TYPE_VALUE; }
};
@@ -294,7 +294,9 @@ private:
bool started = true;
NodePath root_motion_track;
- Transform3D root_motion_transform;
+ Vector3 root_motion_position = Vector3(0, 0, 0);
+ Quaternion root_motion_rotation = Quaternion(0, 0, 0, 1);
+ Vector3 root_motion_scale = Vector3(0, 0, 0);
friend class AnimationNode;
bool properties_dirty = true;
@@ -350,7 +352,9 @@ public:
void set_root_motion_track(const NodePath &p_track);
NodePath get_root_motion_track() const;
- Transform3D get_root_motion_transform() const;
+ Vector3 get_root_motion_position() const;
+ Quaternion get_root_motion_rotation() const;
+ Vector3 get_root_motion_scale() const;
real_t get_connection_activity(const StringName &p_path, int p_connection) const;
void advance(double p_time);
diff --git a/scene/animation/root_motion_view.cpp b/scene/animation/root_motion_view.cpp
index 47f08219a9..a6ccb4a576 100644
--- a/scene/animation/root_motion_view.cpp
+++ b/scene/animation/root_motion_view.cpp
@@ -103,7 +103,8 @@ void RootMotionView::_notification(int p_what) {
set_physics_process_internal(false);
}
- transform = tree->get_root_motion_transform();
+ transform.origin = tree->get_root_motion_position();
+ transform.basis = tree->get_root_motion_rotation(); // Scale is meaningless.
}
}
@@ -113,9 +114,8 @@ void RootMotionView::_notification(int p_what) {
first = false;
- transform.orthonormalize(); //don't want scale, too imprecise
-
- accumulated = accumulated * transform;
+ accumulated.origin += transform.origin;
+ accumulated.basis *= transform.basis;
accumulated.origin.x = Math::fposmod(accumulated.origin.x, cell_size);
if (zero_y) {
accumulated.origin.y = 0;
diff --git a/scene/debugger/scene_debugger.cpp b/scene/debugger/scene_debugger.cpp
index b4bdda9ecb..28eedcbe13 100644
--- a/scene/debugger/scene_debugger.cpp
+++ b/scene/debugger/scene_debugger.cpp
@@ -39,87 +39,10 @@
#include "scene/main/window.h"
#include "scene/resources/packed_scene.h"
-Array SceneDebugger::RPCProfilerFrame::serialize() {
- Array arr;
- arr.push_back(infos.size() * 4);
- for (int i = 0; i < infos.size(); ++i) {
- arr.push_back(uint64_t(infos[i].node));
- arr.push_back(infos[i].node_path);
- arr.push_back(infos[i].incoming_rpc);
- arr.push_back(infos[i].outgoing_rpc);
- }
- return arr;
-}
-
-bool SceneDebugger::RPCProfilerFrame::deserialize(const Array &p_arr) {
- ERR_FAIL_COND_V(p_arr.size() < 1, false);
- uint32_t size = p_arr[0];
- ERR_FAIL_COND_V(size % 4, false);
- ERR_FAIL_COND_V((uint32_t)p_arr.size() != size + 1, false);
- infos.resize(size / 4);
- int idx = 1;
- for (uint32_t i = 0; i < size / 4; ++i) {
- infos.write[i].node = uint64_t(p_arr[idx]);
- infos.write[i].node_path = p_arr[idx + 1];
- infos.write[i].incoming_rpc = p_arr[idx + 2];
- infos.write[i].outgoing_rpc = p_arr[idx + 3];
- }
- return true;
-}
-
-class SceneDebugger::RPCProfiler : public EngineProfiler {
- HashMap<ObjectID, RPCNodeInfo> rpc_node_data;
- uint64_t last_profile_time = 0;
-
- void init_node(const ObjectID p_node) {
- if (rpc_node_data.has(p_node)) {
- return;
- }
- rpc_node_data.insert(p_node, RPCNodeInfo());
- rpc_node_data[p_node].node = p_node;
- rpc_node_data[p_node].node_path = Object::cast_to<Node>(ObjectDB::get_instance(p_node))->get_path();
- rpc_node_data[p_node].incoming_rpc = 0;
- rpc_node_data[p_node].outgoing_rpc = 0;
- }
-
-public:
- void toggle(bool p_enable, const Array &p_opts) {
- rpc_node_data.clear();
- }
-
- void add(const Array &p_data) {
- ERR_FAIL_COND(p_data.size() < 2);
- const ObjectID id = p_data[0];
- const String what = p_data[1];
- init_node(id);
- RPCNodeInfo &info = rpc_node_data[id];
- if (what == "rpc_in") {
- info.incoming_rpc++;
- } else if (what == "rpc_out") {
- info.outgoing_rpc++;
- }
- }
-
- void tick(double p_frame_time, double p_process_time, double p_physics_time, double p_physics_frame_time) {
- uint64_t pt = OS::get_singleton()->get_ticks_msec();
- if (pt - last_profile_time > 100) {
- last_profile_time = pt;
- RPCProfilerFrame frame;
- for (const KeyValue<ObjectID, RPCNodeInfo> &E : rpc_node_data) {
- frame.infos.push_back(E.value);
- }
- rpc_node_data.clear();
- EngineDebugger::get_singleton()->send_message("multiplayer:rpc", frame.serialize());
- }
- }
-};
-
SceneDebugger *SceneDebugger::singleton = nullptr;
SceneDebugger::SceneDebugger() {
singleton = this;
- rpc_profiler.instantiate();
- rpc_profiler->bind("rpc");
#ifdef DEBUG_ENABLED
LiveEditor::singleton = memnew(LiveEditor);
EngineDebugger::register_message_capture("scene", EngineDebugger::Capture(nullptr, SceneDebugger::parse_message));
@@ -264,7 +187,7 @@ Error SceneDebugger::parse_message(void *p_user, const String &p_msg, const Arra
ERR_FAIL_COND_V(p_args.size() < 3, ERR_INVALID_DATA);
live_editor->_create_node_func(p_args[0], p_args[1], p_args[2]);
- } else if (p_msg == "live_instance_node") {
+ } else if (p_msg == "live_instantiate_node") {
ERR_FAIL_COND_V(p_args.size() < 3, ERR_INVALID_DATA);
live_editor->_instance_node_func(p_args[0], p_args[1], p_args[2]);
@@ -297,9 +220,35 @@ void SceneDebugger::_save_node(ObjectID id, const String &p_path) {
Node *node = Object::cast_to<Node>(ObjectDB::get_instance(id));
ERR_FAIL_COND(!node);
+#ifdef TOOLS_ENABLED
+ HashMap<const Node *, Node *> duplimap;
+ Node *copy = node->duplicate_from_editor(duplimap);
+#else
+ Node *copy = node->duplicate();
+#endif
+
+ // Handle Unique Nodes.
+ for (int i = 0; i < copy->get_child_count(false); i++) {
+ _set_node_owner_recursive(copy->get_child(i, false), copy);
+ }
+ // Root node cannot ever be unique name in its own Scene!
+ copy->set_unique_name_in_owner(false);
+
Ref<PackedScene> ps = memnew(PackedScene);
- ps->pack(node);
+ ps->pack(copy);
ResourceSaver::save(ps, p_path);
+
+ memdelete(copy);
+}
+
+void SceneDebugger::_set_node_owner_recursive(Node *p_node, Node *p_owner) {
+ if (!p_node->get_owner()) {
+ p_node->set_owner(p_owner);
+ }
+
+ for (int i = 0; i < p_node->get_child_count(false); i++) {
+ _set_node_owner_recursive(p_node->get_child(i, false), p_owner);
+ }
}
void SceneDebugger::_send_object_id(ObjectID p_id, int p_max_size) {
diff --git a/scene/debugger/scene_debugger.h b/scene/debugger/scene_debugger.h
index fe35446aae..34891ef0fd 100644
--- a/scene/debugger/scene_debugger.h
+++ b/scene/debugger/scene_debugger.h
@@ -42,28 +42,9 @@ class Node;
class SceneDebugger {
public:
- // RPC profiler
- struct RPCNodeInfo {
- ObjectID node;
- String node_path;
- int incoming_rpc = 0;
- int outgoing_rpc = 0;
- };
-
- struct RPCProfilerFrame {
- Vector<RPCNodeInfo> infos;
-
- Array serialize();
- bool deserialize(const Array &p_arr);
- };
-
private:
- class RPCProfiler;
-
static SceneDebugger *singleton;
- Ref<RPCProfiler> rpc_profiler;
-
SceneDebugger();
public:
@@ -75,6 +56,7 @@ public:
#ifdef DEBUG_ENABLED
private:
static void _save_node(ObjectID id, const String &p_path);
+ static void _set_node_owner_recursive(Node *p_node, Node *p_owner);
static void _set_object_property(ObjectID p_id, const String &p_property, const Variant &p_value);
static void _send_object_id(ObjectID p_id, int p_max_size = 1 << 20);
diff --git a/scene/gui/base_button.cpp b/scene/gui/base_button.cpp
index ac9034c6fd..9da1fbda1b 100644
--- a/scene/gui/base_button.cpp
+++ b/scene/gui/base_button.cpp
@@ -300,6 +300,7 @@ void BaseButton::set_toggle_mode(bool p_on) {
}
toggle_mode = p_on;
+ update_configuration_warnings();
}
bool BaseButton::is_toggle_mode() const {
@@ -381,6 +382,7 @@ void BaseButton::set_button_group(const Ref<ButtonGroup> &p_group) {
}
queue_redraw(); //checkbox changes to radio if set a buttongroup
+ update_configuration_warnings();
}
Ref<ButtonGroup> BaseButton::get_button_group() const {
@@ -399,6 +401,16 @@ bool BaseButton::is_shortcut_feedback() const {
return shortcut_feedback;
}
+PackedStringArray BaseButton::get_configuration_warnings() const {
+ PackedStringArray warnings = Control::get_configuration_warnings();
+
+ if (get_button_group().is_valid() && !is_toggle_mode()) {
+ warnings.push_back(RTR("ButtonGroup is intended to be used only with buttons that have toggle_mode set to true."));
+ }
+
+ return warnings;
+}
+
void BaseButton::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_pressed", "pressed"), &BaseButton::set_pressed);
ClassDB::bind_method(D_METHOD("is_pressed"), &BaseButton::is_pressed);
diff --git a/scene/gui/base_button.h b/scene/gui/base_button.h
index 3acf535f54..5018aea120 100644
--- a/scene/gui/base_button.h
+++ b/scene/gui/base_button.h
@@ -136,6 +136,8 @@ public:
void set_shortcut_feedback(bool p_feedback);
bool is_shortcut_feedback() const;
+ PackedStringArray get_configuration_warnings() const override;
+
BaseButton();
~BaseButton();
};
diff --git a/scene/gui/button.cpp b/scene/gui/button.cpp
index c2b82e01d1..0e7bc5c306 100644
--- a/scene/gui/button.cpp
+++ b/scene/gui/button.cpp
@@ -231,7 +231,7 @@ void Button::_notification(int p_what) {
_icon = icon;
}
- Rect2 icon_region = Rect2();
+ Rect2 icon_region;
HorizontalAlignment icon_align_rtl_checked = icon_alignment;
HorizontalAlignment align_rtl_checked = alignment;
// Swap icon and text alignment sides if right-to-left layout is set.
diff --git a/scene/gui/code_edit.cpp b/scene/gui/code_edit.cpp
index ea310f5a12..c84438ed5e 100644
--- a/scene/gui/code_edit.cpp
+++ b/scene/gui/code_edit.cpp
@@ -115,7 +115,9 @@ void CodeEdit::_notification(int p_what) {
const Point2 caret_pos = get_caret_draw_pos();
const int total_height = csb->get_minimum_size().y + code_completion_rect.size.height;
- if (caret_pos.y + row_height + total_height > get_size().height) {
+ const bool can_fit_completion_above = (caret_pos.y - row_height > total_height);
+ const bool can_fit_completion_below = (caret_pos.y + row_height + total_height <= get_size().height);
+ if (!can_fit_completion_below && can_fit_completion_above) {
code_completion_rect.position.y = (caret_pos.y - total_height - row_height) + line_spacing;
} else {
code_completion_rect.position.y = caret_pos.y + (line_spacing / 2.0f);
@@ -378,12 +380,13 @@ void CodeEdit::gui_input(const Ref<InputEvent> &p_gui_input) {
}
if (symbol_lookup_on_click_enabled) {
- if (mm->is_command_or_control_pressed() && mm->get_button_mask() == MouseButton::NONE && !is_dragging_cursor()) {
+ if (mm->is_command_or_control_pressed() && mm->get_button_mask() == MouseButton::NONE) {
+ symbol_lookup_pos = get_line_column_at_pos(mpos);
symbol_lookup_new_word = get_word_at_pos(mpos);
if (symbol_lookup_new_word != symbol_lookup_word) {
emit_signal(SNAME("symbol_validate"), symbol_lookup_new_word);
}
- } else {
+ } else if (!mm->is_command_or_control_pressed() || (mm->get_button_mask() != MouseButton::NONE && symbol_lookup_pos != get_line_column_at_pos(mpos))) {
set_symbol_lookup_word_as_valid(false);
}
}
@@ -1425,7 +1428,10 @@ bool CodeEdit::is_line_numbers_zero_padded() const {
}
void CodeEdit::_line_number_draw_callback(int p_line, int p_gutter, const Rect2 &p_region) {
- String fc = TS->format_number(String::num(p_line + 1).lpad(line_number_digits, line_number_padding));
+ String fc = String::num(p_line + 1).lpad(line_number_digits, line_number_padding);
+ if (is_localizing_numeral_system()) {
+ fc = TS->format_number(fc);
+ }
Ref<TextLine> tl;
tl.instantiate();
tl->add_string(fc, font, font_size);
@@ -2075,20 +2081,22 @@ void CodeEdit::confirm_code_completion(bool p_replace) {
}
char32_t last_completion_char_display = display_text[display_text.length() - 1];
+ bool last_char_matches = (last_completion_char == next_char || last_completion_char_display == next_char);
int pre_brace_pair = get_caret_column(i) > 0 ? _get_auto_brace_pair_open_at_pos(caret_line, get_caret_column(i)) : -1;
int post_brace_pair = get_caret_column(i) < get_line(caret_line).length() ? _get_auto_brace_pair_close_at_pos(caret_line, get_caret_column(i)) : -1;
- if (post_brace_pair != -1 && (last_completion_char == next_char || last_completion_char_display == next_char)) {
- remove_text(caret_line, get_caret_column(i), caret_line, get_caret_column(i) + 1);
- adjust_carets_after_edit(i, caret_line, get_caret_column(i), caret_line, get_caret_column(i) + 1);
- }
-
- if (pre_brace_pair != -1 && pre_brace_pair != post_brace_pair && (last_completion_char == next_char || last_completion_char_display == next_char)) {
+ // Strings do not nest like brackets, so ensure we don't add an additional closing pair.
+ if (has_string_delimiter(String::chr(last_completion_char)) && post_brace_pair != -1 && last_char_matches) {
remove_text(caret_line, get_caret_column(i), caret_line, get_caret_column(i) + 1);
adjust_carets_after_edit(i, caret_line, get_caret_column(i), caret_line, get_caret_column(i) + 1);
- } else if (auto_brace_completion_enabled && pre_brace_pair != -1 && post_brace_pair == -1) {
- insert_text_at_caret(auto_brace_completion_pairs[pre_brace_pair].close_key, i);
- set_caret_column(get_caret_column(i) - auto_brace_completion_pairs[pre_brace_pair].close_key.length(), i == 0, i);
+ } else {
+ if (pre_brace_pair != -1 && pre_brace_pair != post_brace_pair && last_char_matches) {
+ remove_text(caret_line, get_caret_column(i), caret_line, get_caret_column(i) + 1);
+ adjust_carets_after_edit(i, caret_line, get_caret_column(i), caret_line, get_caret_column(i) + 1);
+ } else if (auto_brace_completion_enabled && pre_brace_pair != -1) {
+ insert_text_at_caret(auto_brace_completion_pairs[pre_brace_pair].close_key, i);
+ set_caret_column(get_caret_column(i) - auto_brace_completion_pairs[pre_brace_pair].close_key.length(), i == 0, i);
+ }
}
if (pre_brace_pair == -1 && post_brace_pair == -1 && get_caret_column(i) > 0 && get_caret_column(i) < get_line(caret_line).length()) {
diff --git a/scene/gui/code_edit.h b/scene/gui/code_edit.h
index cbbc13480e..e409c7c82b 100644
--- a/scene/gui/code_edit.h
+++ b/scene/gui/code_edit.h
@@ -236,6 +236,7 @@ private:
String symbol_lookup_new_word = "";
String symbol_lookup_word = "";
+ Point2i symbol_lookup_pos;
/* Visual */
Ref<StyleBox> style_normal;
diff --git a/scene/gui/color_picker.cpp b/scene/gui/color_picker.cpp
index 724e5bcaf6..fa4b57d7a7 100644
--- a/scene/gui/color_picker.cpp
+++ b/scene/gui/color_picker.cpp
@@ -959,7 +959,7 @@ void ColorPicker::_sample_draw() {
// Draw both old and new colors for easier comparison (only if spawned from a ColorPickerButton).
const Rect2 rect_old = Rect2(Point2(), Size2(sample->get_size().width * 0.5, sample->get_size().height * 0.95));
- if (display_old_color && old_color.a < 1.0) {
+ if (old_color.a < 1.0) {
sample->draw_texture_rect(get_theme_icon(SNAME("sample_bg"), SNAME("ColorPicker")), rect_old, true);
}
@@ -1088,7 +1088,9 @@ void ColorPicker::_hsv_draw(int p_which, Control *c) {
} else if (p_which == 1) {
if (actual_shape == SHAPE_HSV_RECTANGLE) {
Ref<Texture2D> hue = get_theme_icon(SNAME("color_hue"), SNAME("ColorPicker"));
- c->draw_texture_rect(hue, Rect2(Point2(), c->get_size()));
+ c->draw_set_transform(Point2(), -Math_PI / 2, Size2(c->get_size().x, -c->get_size().y));
+ c->draw_texture_rect(hue, Rect2(Point2(), Size2(1, 1)));
+ c->draw_set_transform(Point2(), 0, Size2(1, 1));
int y = c->get_size().y - c->get_size().y * (1.0 - h);
Color col;
col.set_hsv(h, 1, 1);
@@ -1575,8 +1577,7 @@ void ColorPicker::_bind_methods() {
BIND_ENUM_CONSTANT(SHAPE_NONE);
}
-ColorPicker::ColorPicker() :
- BoxContainer(true) {
+ColorPicker::ColorPicker() {
HBoxContainer *hb_edit = memnew(HBoxContainer);
add_child(hb_edit, false, INTERNAL_MODE_FRONT);
hb_edit->set_v_size_flags(SIZE_SHRINK_BEGIN);
diff --git a/scene/gui/color_picker.h b/scene/gui/color_picker.h
index 3208676539..799ca2d202 100644
--- a/scene/gui/color_picker.h
+++ b/scene/gui/color_picker.h
@@ -68,8 +68,8 @@ public:
~ColorPresetButton();
};
-class ColorPicker : public BoxContainer {
- GDCLASS(ColorPicker, BoxContainer);
+class ColorPicker : public VBoxContainer {
+ GDCLASS(ColorPicker, VBoxContainer);
public:
enum ColorModeType {
diff --git a/scene/gui/control.cpp b/scene/gui/control.cpp
index c5cb7157e8..21c7c4ddb4 100644
--- a/scene/gui/control.cpp
+++ b/scene/gui/control.cpp
@@ -220,6 +220,10 @@ PackedStringArray Control::get_configuration_warnings() const {
warnings.push_back(RTR("The Hint Tooltip won't be displayed as the control's Mouse Filter is set to \"Ignore\". To solve this, set the Mouse Filter to \"Stop\" or \"Pass\"."));
}
+ if (get_z_index() != 0) {
+ warnings.push_back(RTR("Changing the Z index of a control only affects the drawing order, not the input event handling order."));
+ }
+
return warnings;
}
@@ -253,36 +257,36 @@ bool Control::_set(const StringName &p_name, const Variant &p_value) {
if (p_value.get_type() == Variant::NIL || (p_value.get_type() == Variant::OBJECT && (Object *)p_value == nullptr)) {
if (name.begins_with("theme_override_icons/")) {
String dname = name.get_slicec('/', 1);
- if (data.icon_override.has(dname)) {
- data.icon_override[dname]->disconnect("changed", callable_mp(this, &Control::_notify_theme_override_changed));
+ if (data.theme_icon_override.has(dname)) {
+ data.theme_icon_override[dname]->disconnect("changed", callable_mp(this, &Control::_notify_theme_override_changed));
}
- data.icon_override.erase(dname);
+ data.theme_icon_override.erase(dname);
_notify_theme_override_changed();
} else if (name.begins_with("theme_override_styles/")) {
String dname = name.get_slicec('/', 1);
- if (data.style_override.has(dname)) {
- data.style_override[dname]->disconnect("changed", callable_mp(this, &Control::_notify_theme_override_changed));
+ if (data.theme_style_override.has(dname)) {
+ data.theme_style_override[dname]->disconnect("changed", callable_mp(this, &Control::_notify_theme_override_changed));
}
- data.style_override.erase(dname);
+ data.theme_style_override.erase(dname);
_notify_theme_override_changed();
} else if (name.begins_with("theme_override_fonts/")) {
String dname = name.get_slicec('/', 1);
- if (data.font_override.has(dname)) {
- data.font_override[dname]->disconnect("changed", callable_mp(this, &Control::_notify_theme_override_changed));
+ if (data.theme_font_override.has(dname)) {
+ data.theme_font_override[dname]->disconnect("changed", callable_mp(this, &Control::_notify_theme_override_changed));
}
- data.font_override.erase(dname);
+ data.theme_font_override.erase(dname);
_notify_theme_override_changed();
} else if (name.begins_with("theme_override_font_sizes/")) {
String dname = name.get_slicec('/', 1);
- data.font_size_override.erase(dname);
+ data.theme_font_size_override.erase(dname);
_notify_theme_override_changed();
} else if (name.begins_with("theme_override_colors/")) {
String dname = name.get_slicec('/', 1);
- data.color_override.erase(dname);
+ data.theme_color_override.erase(dname);
_notify_theme_override_changed();
} else if (name.begins_with("theme_override_constants/")) {
String dname = name.get_slicec('/', 1);
- data.constant_override.erase(dname);
+ data.theme_constant_override.erase(dname);
_notify_theme_override_changed();
} else {
return false;
@@ -322,22 +326,22 @@ bool Control::_get(const StringName &p_name, Variant &r_ret) const {
if (sname.begins_with("theme_override_icons/")) {
String name = sname.get_slicec('/', 1);
- r_ret = data.icon_override.has(name) ? Variant(data.icon_override[name]) : Variant();
+ r_ret = data.theme_icon_override.has(name) ? Variant(data.theme_icon_override[name]) : Variant();
} else if (sname.begins_with("theme_override_styles/")) {
String name = sname.get_slicec('/', 1);
- r_ret = data.style_override.has(name) ? Variant(data.style_override[name]) : Variant();
+ r_ret = data.theme_style_override.has(name) ? Variant(data.theme_style_override[name]) : Variant();
} else if (sname.begins_with("theme_override_fonts/")) {
String name = sname.get_slicec('/', 1);
- r_ret = data.font_override.has(name) ? Variant(data.font_override[name]) : Variant();
+ r_ret = data.theme_font_override.has(name) ? Variant(data.theme_font_override[name]) : Variant();
} else if (sname.begins_with("theme_override_font_sizes/")) {
String name = sname.get_slicec('/', 1);
- r_ret = data.font_size_override.has(name) ? Variant(data.font_size_override[name]) : Variant();
+ r_ret = data.theme_font_size_override.has(name) ? Variant(data.theme_font_size_override[name]) : Variant();
} else if (sname.begins_with("theme_override_colors/")) {
String name = sname.get_slicec('/', 1);
- r_ret = data.color_override.has(name) ? Variant(data.color_override[name]) : Variant();
+ r_ret = data.theme_color_override.has(name) ? Variant(data.theme_color_override[name]) : Variant();
} else if (sname.begins_with("theme_override_constants/")) {
String name = sname.get_slicec('/', 1);
- r_ret = data.constant_override.has(name) ? Variant(data.constant_override[name]) : Variant();
+ r_ret = data.theme_constant_override.has(name) ? Variant(data.theme_constant_override[name]) : Variant();
} else {
return false;
}
@@ -346,16 +350,16 @@ bool Control::_get(const StringName &p_name, Variant &r_ret) const {
}
void Control::_get_property_list(List<PropertyInfo> *p_list) const {
- Ref<Theme> theme = ThemeDB::get_singleton()->get_default_theme();
+ Ref<Theme> default_theme = ThemeDB::get_singleton()->get_default_theme();
p_list->push_back(PropertyInfo(Variant::NIL, TTRC("Theme Overrides"), PROPERTY_HINT_NONE, "theme_override_", PROPERTY_USAGE_GROUP));
{
List<StringName> names;
- theme->get_color_list(get_class_name(), &names);
+ default_theme->get_color_list(get_class_name(), &names);
for (const StringName &E : names) {
uint32_t usage = PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_CHECKABLE;
- if (data.color_override.has(E)) {
+ if (data.theme_color_override.has(E)) {
usage |= PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_CHECKED;
}
@@ -364,10 +368,10 @@ void Control::_get_property_list(List<PropertyInfo> *p_list) const {
}
{
List<StringName> names;
- theme->get_constant_list(get_class_name(), &names);
+ default_theme->get_constant_list(get_class_name(), &names);
for (const StringName &E : names) {
uint32_t usage = PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_CHECKABLE;
- if (data.constant_override.has(E)) {
+ if (data.theme_constant_override.has(E)) {
usage |= PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_CHECKED;
}
@@ -376,10 +380,10 @@ void Control::_get_property_list(List<PropertyInfo> *p_list) const {
}
{
List<StringName> names;
- theme->get_font_list(get_class_name(), &names);
+ default_theme->get_font_list(get_class_name(), &names);
for (const StringName &E : names) {
uint32_t usage = PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_CHECKABLE;
- if (data.font_override.has(E)) {
+ if (data.theme_font_override.has(E)) {
usage |= PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_CHECKED;
}
@@ -388,10 +392,10 @@ void Control::_get_property_list(List<PropertyInfo> *p_list) const {
}
{
List<StringName> names;
- theme->get_font_size_list(get_class_name(), &names);
+ default_theme->get_font_size_list(get_class_name(), &names);
for (const StringName &E : names) {
uint32_t usage = PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_CHECKABLE;
- if (data.font_size_override.has(E)) {
+ if (data.theme_font_size_override.has(E)) {
usage |= PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_CHECKED;
}
@@ -400,10 +404,10 @@ void Control::_get_property_list(List<PropertyInfo> *p_list) const {
}
{
List<StringName> names;
- theme->get_icon_list(get_class_name(), &names);
+ default_theme->get_icon_list(get_class_name(), &names);
for (const StringName &E : names) {
uint32_t usage = PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_CHECKABLE;
- if (data.icon_override.has(E)) {
+ if (data.theme_icon_override.has(E)) {
usage |= PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_CHECKED;
}
@@ -412,10 +416,10 @@ void Control::_get_property_list(List<PropertyInfo> *p_list) const {
}
{
List<StringName> names;
- theme->get_stylebox_list(get_class_name(), &names);
+ default_theme->get_stylebox_list(get_class_name(), &names);
for (const StringName &E : names) {
uint32_t usage = PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_CHECKABLE;
- if (data.style_override.has(E)) {
+ if (data.theme_style_override.has(E)) {
usage |= PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_CHECKED;
}
@@ -481,10 +485,10 @@ void Control::_validate_property(PropertyInfo &p_property) const {
}
} else if (Object::cast_to<Container>(parent_node)) {
// If the parent is a container, display only container-related properties.
- if (p_property.name.begins_with("anchor_") || p_property.name.begins_with("offset_") || p_property.name.begins_with("grow_") || p_property.name == "anchors_preset" ||
- p_property.name == "position" || p_property.name == "rotation" || p_property.name == "scale" || p_property.name == "size" || p_property.name == "pivot_offset") {
- p_property.usage ^= PROPERTY_USAGE_EDITOR;
-
+ if (p_property.name.begins_with("anchor_") || p_property.name.begins_with("offset_") || p_property.name.begins_with("grow_") || p_property.name == "anchors_preset") {
+ p_property.usage ^= PROPERTY_USAGE_DEFAULT;
+ } else if (p_property.name == "position" || p_property.name == "rotation" || p_property.name == "scale" || p_property.name == "size" || p_property.name == "pivot_offset") {
+ p_property.usage = PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_READ_ONLY;
} else if (p_property.name == "layout_mode") {
// Set the layout mode to be disabled with the proper value.
p_property.hint_string = "Position,Anchors,Container,Uncontrolled";
@@ -1471,10 +1475,18 @@ void Control::set_rotation(real_t p_radians) {
_notify_transform();
}
+void Control::set_rotation_degrees(real_t p_degrees) {
+ set_rotation(Math::deg_to_rad(p_degrees));
+}
+
real_t Control::get_rotation() const {
return data.rotation;
}
+real_t Control::get_rotation_degrees() const {
+ return Math::rad_to_deg(get_rotation());
+}
+
void Control::set_pivot_offset(const Vector2 &p_pivot) {
if (data.pivot_offset == p_pivot) {
return;
@@ -1559,6 +1571,12 @@ void Control::set_custom_minimum_size(const Size2 &p_custom) {
if (p_custom == data.custom_minimum_size) {
return;
}
+
+ if (isnan(p_custom.x) || isnan(p_custom.y)) {
+ // Prevent infinite loop.
+ return;
+ }
+
data.custom_minimum_size = p_custom;
update_minimum_size();
}
@@ -2377,7 +2395,7 @@ StringName Control::get_theme_type_variation() const {
Ref<Texture2D> Control::get_theme_icon(const StringName &p_name, const StringName &p_theme_type) const {
if (p_theme_type == StringName() || p_theme_type == get_class_name() || p_theme_type == data.theme_type_variation) {
- const Ref<Texture2D> *tex = data.icon_override.getptr(p_name);
+ const Ref<Texture2D> *tex = data.theme_icon_override.getptr(p_name);
if (tex) {
return *tex;
}
@@ -2396,7 +2414,7 @@ Ref<Texture2D> Control::get_theme_icon(const StringName &p_name, const StringNam
Ref<StyleBox> Control::get_theme_stylebox(const StringName &p_name, const StringName &p_theme_type) const {
if (p_theme_type == StringName() || p_theme_type == get_class_name() || p_theme_type == data.theme_type_variation) {
- const Ref<StyleBox> *style = data.style_override.getptr(p_name);
+ const Ref<StyleBox> *style = data.theme_style_override.getptr(p_name);
if (style) {
return *style;
}
@@ -2415,7 +2433,7 @@ Ref<StyleBox> Control::get_theme_stylebox(const StringName &p_name, const String
Ref<Font> Control::get_theme_font(const StringName &p_name, const StringName &p_theme_type) const {
if (p_theme_type == StringName() || p_theme_type == get_class_name() || p_theme_type == data.theme_type_variation) {
- const Ref<Font> *font = data.font_override.getptr(p_name);
+ const Ref<Font> *font = data.theme_font_override.getptr(p_name);
if (font) {
return *font;
}
@@ -2434,7 +2452,7 @@ Ref<Font> Control::get_theme_font(const StringName &p_name, const StringName &p_
int Control::get_theme_font_size(const StringName &p_name, const StringName &p_theme_type) const {
if (p_theme_type == StringName() || p_theme_type == get_class_name() || p_theme_type == data.theme_type_variation) {
- const int *font_size = data.font_size_override.getptr(p_name);
+ const int *font_size = data.theme_font_size_override.getptr(p_name);
if (font_size && (*font_size) > 0) {
return *font_size;
}
@@ -2453,7 +2471,7 @@ int Control::get_theme_font_size(const StringName &p_name, const StringName &p_t
Color Control::get_theme_color(const StringName &p_name, const StringName &p_theme_type) const {
if (p_theme_type == StringName() || p_theme_type == get_class_name() || p_theme_type == data.theme_type_variation) {
- const Color *color = data.color_override.getptr(p_name);
+ const Color *color = data.theme_color_override.getptr(p_name);
if (color) {
return *color;
}
@@ -2472,7 +2490,7 @@ Color Control::get_theme_color(const StringName &p_name, const StringName &p_the
int Control::get_theme_constant(const StringName &p_name, const StringName &p_theme_type) const {
if (p_theme_type == StringName() || p_theme_type == get_class_name() || p_theme_type == data.theme_type_variation) {
- const int *constant = data.constant_override.getptr(p_name);
+ const int *constant = data.theme_constant_override.getptr(p_name);
if (constant) {
return *constant;
}
@@ -2566,123 +2584,123 @@ bool Control::has_theme_constant(const StringName &p_name, const StringName &p_t
void Control::add_theme_icon_override(const StringName &p_name, const Ref<Texture2D> &p_icon) {
ERR_FAIL_COND(!p_icon.is_valid());
- if (data.icon_override.has(p_name)) {
- data.icon_override[p_name]->disconnect("changed", callable_mp(this, &Control::_notify_theme_override_changed));
+ if (data.theme_icon_override.has(p_name)) {
+ data.theme_icon_override[p_name]->disconnect("changed", callable_mp(this, &Control::_notify_theme_override_changed));
}
- data.icon_override[p_name] = p_icon;
- data.icon_override[p_name]->connect("changed", callable_mp(this, &Control::_notify_theme_override_changed), CONNECT_REFERENCE_COUNTED);
+ data.theme_icon_override[p_name] = p_icon;
+ data.theme_icon_override[p_name]->connect("changed", callable_mp(this, &Control::_notify_theme_override_changed), CONNECT_REFERENCE_COUNTED);
_notify_theme_override_changed();
}
void Control::add_theme_style_override(const StringName &p_name, const Ref<StyleBox> &p_style) {
ERR_FAIL_COND(!p_style.is_valid());
- if (data.style_override.has(p_name)) {
- data.style_override[p_name]->disconnect("changed", callable_mp(this, &Control::_notify_theme_override_changed));
+ if (data.theme_style_override.has(p_name)) {
+ data.theme_style_override[p_name]->disconnect("changed", callable_mp(this, &Control::_notify_theme_override_changed));
}
- data.style_override[p_name] = p_style;
- data.style_override[p_name]->connect("changed", callable_mp(this, &Control::_notify_theme_override_changed), CONNECT_REFERENCE_COUNTED);
+ data.theme_style_override[p_name] = p_style;
+ data.theme_style_override[p_name]->connect("changed", callable_mp(this, &Control::_notify_theme_override_changed), CONNECT_REFERENCE_COUNTED);
_notify_theme_override_changed();
}
void Control::add_theme_font_override(const StringName &p_name, const Ref<Font> &p_font) {
ERR_FAIL_COND(!p_font.is_valid());
- if (data.font_override.has(p_name)) {
- data.font_override[p_name]->disconnect("changed", callable_mp(this, &Control::_notify_theme_override_changed));
+ if (data.theme_font_override.has(p_name)) {
+ data.theme_font_override[p_name]->disconnect("changed", callable_mp(this, &Control::_notify_theme_override_changed));
}
- data.font_override[p_name] = p_font;
- data.font_override[p_name]->connect("changed", callable_mp(this, &Control::_notify_theme_override_changed), CONNECT_REFERENCE_COUNTED);
+ data.theme_font_override[p_name] = p_font;
+ data.theme_font_override[p_name]->connect("changed", callable_mp(this, &Control::_notify_theme_override_changed), CONNECT_REFERENCE_COUNTED);
_notify_theme_override_changed();
}
void Control::add_theme_font_size_override(const StringName &p_name, int p_font_size) {
- data.font_size_override[p_name] = p_font_size;
+ data.theme_font_size_override[p_name] = p_font_size;
_notify_theme_override_changed();
}
void Control::add_theme_color_override(const StringName &p_name, const Color &p_color) {
- data.color_override[p_name] = p_color;
+ data.theme_color_override[p_name] = p_color;
_notify_theme_override_changed();
}
void Control::add_theme_constant_override(const StringName &p_name, int p_constant) {
- data.constant_override[p_name] = p_constant;
+ data.theme_constant_override[p_name] = p_constant;
_notify_theme_override_changed();
}
void Control::remove_theme_icon_override(const StringName &p_name) {
- if (data.icon_override.has(p_name)) {
- data.icon_override[p_name]->disconnect("changed", callable_mp(this, &Control::_notify_theme_override_changed));
+ if (data.theme_icon_override.has(p_name)) {
+ data.theme_icon_override[p_name]->disconnect("changed", callable_mp(this, &Control::_notify_theme_override_changed));
}
- data.icon_override.erase(p_name);
+ data.theme_icon_override.erase(p_name);
_notify_theme_override_changed();
}
void Control::remove_theme_style_override(const StringName &p_name) {
- if (data.style_override.has(p_name)) {
- data.style_override[p_name]->disconnect("changed", callable_mp(this, &Control::_notify_theme_override_changed));
+ if (data.theme_style_override.has(p_name)) {
+ data.theme_style_override[p_name]->disconnect("changed", callable_mp(this, &Control::_notify_theme_override_changed));
}
- data.style_override.erase(p_name);
+ data.theme_style_override.erase(p_name);
_notify_theme_override_changed();
}
void Control::remove_theme_font_override(const StringName &p_name) {
- if (data.font_override.has(p_name)) {
- data.font_override[p_name]->disconnect("changed", callable_mp(this, &Control::_notify_theme_override_changed));
+ if (data.theme_font_override.has(p_name)) {
+ data.theme_font_override[p_name]->disconnect("changed", callable_mp(this, &Control::_notify_theme_override_changed));
}
- data.font_override.erase(p_name);
+ data.theme_font_override.erase(p_name);
_notify_theme_override_changed();
}
void Control::remove_theme_font_size_override(const StringName &p_name) {
- data.font_size_override.erase(p_name);
+ data.theme_font_size_override.erase(p_name);
_notify_theme_override_changed();
}
void Control::remove_theme_color_override(const StringName &p_name) {
- data.color_override.erase(p_name);
+ data.theme_color_override.erase(p_name);
_notify_theme_override_changed();
}
void Control::remove_theme_constant_override(const StringName &p_name) {
- data.constant_override.erase(p_name);
+ data.theme_constant_override.erase(p_name);
_notify_theme_override_changed();
}
bool Control::has_theme_icon_override(const StringName &p_name) const {
- const Ref<Texture2D> *tex = data.icon_override.getptr(p_name);
+ const Ref<Texture2D> *tex = data.theme_icon_override.getptr(p_name);
return tex != nullptr;
}
bool Control::has_theme_stylebox_override(const StringName &p_name) const {
- const Ref<StyleBox> *style = data.style_override.getptr(p_name);
+ const Ref<StyleBox> *style = data.theme_style_override.getptr(p_name);
return style != nullptr;
}
bool Control::has_theme_font_override(const StringName &p_name) const {
- const Ref<Font> *font = data.font_override.getptr(p_name);
+ const Ref<Font> *font = data.theme_font_override.getptr(p_name);
return font != nullptr;
}
bool Control::has_theme_font_size_override(const StringName &p_name) const {
- const int *font_size = data.font_size_override.getptr(p_name);
+ const int *font_size = data.theme_font_size_override.getptr(p_name);
return font_size != nullptr;
}
bool Control::has_theme_color_override(const StringName &p_name) const {
- const Color *color = data.color_override.getptr(p_name);
+ const Color *color = data.theme_color_override.getptr(p_name);
return color != nullptr;
}
bool Control::has_theme_constant_override(const StringName &p_name) const {
- const int *constant = data.constant_override.getptr(p_name);
+ const int *constant = data.theme_constant_override.getptr(p_name);
return constant != nullptr;
}
@@ -2773,6 +2791,20 @@ bool Control::is_layout_rtl() const {
return data.is_rtl;
}
+void Control::set_localize_numeral_system(bool p_enable) {
+ if (p_enable == data.localize_numeral_system) {
+ return;
+ }
+
+ data.localize_numeral_system = p_enable;
+
+ notification(MainLoop::NOTIFICATION_TRANSLATION_CHANGED);
+}
+
+bool Control::is_localizing_numeral_system() const {
+ return data.localize_numeral_system;
+}
+
void Control::set_auto_translate(bool p_enable) {
if (p_enable == data.auto_translate) {
return;
@@ -2921,7 +2953,7 @@ void Control::_notification(int p_notification) {
queue_redraw();
if (data.RI) {
- get_viewport()->_gui_set_root_order_dirty();
+ get_viewport()->gui_set_root_order_dirty();
}
} break;
@@ -3018,6 +3050,7 @@ void Control::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_global_position", "position", "keep_offsets"), &Control::set_global_position, DEFVAL(false));
ClassDB::bind_method(D_METHOD("_set_global_position", "position"), &Control::_set_global_position);
ClassDB::bind_method(D_METHOD("set_rotation", "radians"), &Control::set_rotation);
+ ClassDB::bind_method(D_METHOD("set_rotation_degrees", "degrees"), &Control::set_rotation_degrees);
ClassDB::bind_method(D_METHOD("set_scale", "scale"), &Control::set_scale);
ClassDB::bind_method(D_METHOD("set_pivot_offset", "pivot_offset"), &Control::set_pivot_offset);
ClassDB::bind_method(D_METHOD("get_begin"), &Control::get_begin);
@@ -3025,6 +3058,7 @@ void Control::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_position"), &Control::get_position);
ClassDB::bind_method(D_METHOD("get_size"), &Control::get_size);
ClassDB::bind_method(D_METHOD("get_rotation"), &Control::get_rotation);
+ ClassDB::bind_method(D_METHOD("get_rotation_degrees"), &Control::get_rotation_degrees);
ClassDB::bind_method(D_METHOD("get_scale"), &Control::get_scale);
ClassDB::bind_method(D_METHOD("get_pivot_offset"), &Control::get_pivot_offset);
ClassDB::bind_method(D_METHOD("get_custom_minimum_size"), &Control::get_custom_minimum_size);
@@ -3154,6 +3188,9 @@ void Control::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_auto_translate", "enable"), &Control::set_auto_translate);
ClassDB::bind_method(D_METHOD("is_auto_translating"), &Control::is_auto_translating);
+ ClassDB::bind_method(D_METHOD("set_localize_numeral_system", "enable"), &Control::set_localize_numeral_system);
+ ClassDB::bind_method(D_METHOD("is_localizing_numeral_system"), &Control::is_localizing_numeral_system);
+
ADD_GROUP("Layout", "");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "clip_contents"), "set_clip_contents", "is_clipping_contents");
ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "custom_minimum_size", PROPERTY_HINT_NONE, "suffix:px"), "set_custom_minimum_size", "get_custom_minimum_size");
@@ -3190,6 +3227,7 @@ void Control::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "position", PROPERTY_HINT_NONE, "suffix:px", PROPERTY_USAGE_EDITOR), "_set_position", "get_position");
ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "global_position", PROPERTY_HINT_NONE, "suffix:px", PROPERTY_USAGE_NONE), "_set_global_position", "get_global_position");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "rotation", PROPERTY_HINT_RANGE, "-360,360,0.1,or_less,or_greater,radians"), "set_rotation", "get_rotation");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "rotation_degrees", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NONE), "set_rotation_degrees", "get_rotation_degrees");
ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "scale"), "set_scale", "get_scale");
ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "pivot_offset", PROPERTY_HINT_NONE, "suffix:px"), "set_pivot_offset", "get_pivot_offset");
@@ -3198,8 +3236,9 @@ void Control::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::INT, "size_flags_vertical", PROPERTY_HINT_FLAGS, "Fill:1,Expand:2,Shrink Center:4,Shrink End:8"), "set_v_size_flags", "get_v_size_flags");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "size_flags_stretch_ratio", PROPERTY_HINT_RANGE, "0,20,0.01,or_greater"), "set_stretch_ratio", "get_stretch_ratio");
- ADD_GROUP("Auto Translate", "");
+ ADD_GROUP("Localization", "");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "auto_translate"), "set_auto_translate", "is_auto_translating");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "localize_numeral_system"), "set_localize_numeral_system", "is_localizing_numeral_system");
ADD_GROUP("Tooltip", "tooltip_");
ADD_PROPERTY(PropertyInfo(Variant::STRING, "tooltip_text", PROPERTY_HINT_MULTILINE_TEXT), "set_tooltip_text", "get_tooltip_text");
@@ -3337,21 +3376,21 @@ Control::~Control() {
memdelete(data.theme_owner);
// Resources need to be disconnected.
- for (KeyValue<StringName, Ref<Texture2D>> &E : data.icon_override) {
+ for (KeyValue<StringName, Ref<Texture2D>> &E : data.theme_icon_override) {
E.value->disconnect("changed", callable_mp(this, &Control::_notify_theme_override_changed));
}
- for (KeyValue<StringName, Ref<StyleBox>> &E : data.style_override) {
+ for (KeyValue<StringName, Ref<StyleBox>> &E : data.theme_style_override) {
E.value->disconnect("changed", callable_mp(this, &Control::_notify_theme_override_changed));
}
- for (KeyValue<StringName, Ref<Font>> &E : data.font_override) {
+ for (KeyValue<StringName, Ref<Font>> &E : data.theme_font_override) {
E.value->disconnect("changed", callable_mp(this, &Control::_notify_theme_override_changed));
}
// Then override maps can be simply cleared.
- data.icon_override.clear();
- data.style_override.clear();
- data.font_override.clear();
- data.font_size_override.clear();
- data.color_override.clear();
- data.constant_override.clear();
+ data.theme_icon_override.clear();
+ data.theme_style_override.clear();
+ data.theme_font_override.clear();
+ data.theme_font_size_override.clear();
+ data.theme_color_override.clear();
+ data.theme_constant_override.clear();
}
diff --git a/scene/gui/control.h b/scene/gui/control.h
index 72e870930d..f82fba3b1b 100644
--- a/scene/gui/control.h
+++ b/scene/gui/control.h
@@ -228,12 +228,12 @@ private:
StringName theme_type_variation;
bool bulk_theme_override = false;
- Theme::ThemeIconMap icon_override;
- Theme::ThemeStyleMap style_override;
- Theme::ThemeFontMap font_override;
- Theme::ThemeFontSizeMap font_size_override;
- Theme::ThemeColorMap color_override;
- Theme::ThemeConstantMap constant_override;
+ Theme::ThemeIconMap theme_icon_override;
+ Theme::ThemeStyleMap theme_style_override;
+ Theme::ThemeFontMap theme_font_override;
+ Theme::ThemeFontSizeMap theme_font_size_override;
+ Theme::ThemeColorMap theme_color_override;
+ Theme::ThemeConstantMap theme_constant_override;
mutable HashMap<StringName, Theme::ThemeIconMap> theme_icon_cache;
mutable HashMap<StringName, Theme::ThemeStyleMap> theme_style_cache;
@@ -249,6 +249,7 @@ private:
bool is_rtl = false;
bool auto_translate = true;
+ bool localize_numeral_system = true;
// Extra properties.
@@ -450,7 +451,9 @@ public:
void set_scale(const Vector2 &p_scale);
Vector2 get_scale() const;
void set_rotation(real_t p_radians);
+ void set_rotation_degrees(real_t p_degrees);
real_t get_rotation() const;
+ real_t get_rotation_degrees() const;
void set_pivot_offset(const Vector2 &p_pivot);
Vector2 get_pivot_offset() const;
@@ -595,6 +598,9 @@ public:
LayoutDirection get_layout_direction() const;
virtual bool is_layout_rtl() const;
+ void set_localize_numeral_system(bool p_enable);
+ bool is_localizing_numeral_system() const;
+
void set_auto_translate(bool p_enable);
bool is_auto_translating() const;
_FORCE_INLINE_ String atr(const String p_string) const {
diff --git a/scene/gui/dialogs.cpp b/scene/gui/dialogs.cpp
index bf4dd3d245..0d265719ec 100644
--- a/scene/gui/dialogs.cpp
+++ b/scene/gui/dialogs.cpp
@@ -377,7 +377,7 @@ void AcceptDialog::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::STRING, "ok_button_text"), "set_ok_button_text", "get_ok_button_text");
- ADD_GROUP("Dialog", "dialog");
+ ADD_GROUP("Dialog", "dialog_");
ADD_PROPERTY(PropertyInfo(Variant::STRING, "dialog_text", PROPERTY_HINT_MULTILINE_TEXT, "", PROPERTY_USAGE_DEFAULT_INTL), "set_text", "get_text");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "dialog_hide_on_ok"), "set_hide_on_ok", "get_hide_on_ok");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "dialog_close_on_escape"), "set_close_on_escape", "get_close_on_escape");
diff --git a/scene/gui/file_dialog.cpp b/scene/gui/file_dialog.cpp
index cade65108c..11a3803b35 100644
--- a/scene/gui/file_dialog.cpp
+++ b/scene/gui/file_dialog.cpp
@@ -632,8 +632,11 @@ void FileDialog::update_file_list() {
files.pop_front();
}
- if (tree->get_root() && tree->get_root()->get_first_child() && tree->get_selected() == nullptr) {
- tree->get_root()->get_first_child()->select(0);
+ if (mode != FILE_MODE_SAVE_FILE) {
+ // Select the first file from list if nothing is selected.
+ if (tree->get_root() && tree->get_root()->get_first_child() && tree->get_selected() == nullptr) {
+ tree->get_root()->get_first_child()->select(0);
+ }
}
}
diff --git a/scene/gui/graph_edit.cpp b/scene/gui/graph_edit.cpp
index 46b712379d..1c4c8c2574 100644
--- a/scene/gui/graph_edit.cpp
+++ b/scene/gui/graph_edit.cpp
@@ -623,7 +623,7 @@ void GraphEdit::_top_layer_input(const Ref<InputEvent> &p_ev) {
//check disconnect
for (const Connection &E : connections) {
if (E.from == gn->get_name() && E.from_port == j) {
- Node *to = get_node(String(E.to));
+ Node *to = get_node(NodePath(E.to));
if (Object::cast_to<GraphNode>(to)) {
connecting_from = E.to;
connecting_index = E.to_port;
@@ -637,7 +637,7 @@ void GraphEdit::_top_layer_input(const Ref<InputEvent> &p_ev) {
just_disconnected = true;
emit_signal(SNAME("disconnection_request"), E.from, E.from_port, E.to, E.to_port);
- to = get_node(String(connecting_from)); //maybe it was erased
+ to = get_node(NodePath(connecting_from)); // Maybe it was erased.
if (Object::cast_to<GraphNode>(to)) {
connecting = true;
emit_signal(SNAME("connection_drag_started"), connecting_from, connecting_index, false);
@@ -673,10 +673,10 @@ void GraphEdit::_top_layer_input(const Ref<InputEvent> &p_ev) {
if (is_in_input_hotzone(gn, j, click_pos, port_size)) {
if (right_disconnects || valid_right_disconnect_types.has(gn->get_connection_input_type(j))) {
- //check disconnect
+ // Check disconnect.
for (const Connection &E : connections) {
if (E.to == gn->get_name() && E.to_port == j) {
- Node *fr = get_node(String(E.from));
+ Node *fr = get_node(NodePath(E.from));
if (Object::cast_to<GraphNode>(fr)) {
connecting_from = E.from;
connecting_index = E.from_port;
@@ -689,7 +689,7 @@ void GraphEdit::_top_layer_input(const Ref<InputEvent> &p_ev) {
if (connecting_type >= 0) {
emit_signal(SNAME("disconnection_request"), E.from, E.from_port, E.to, E.to_port);
- fr = get_node(String(connecting_from)); //maybe it was erased
+ fr = get_node(NodePath(connecting_from)); // Maybe it was erased.
if (Object::cast_to<GraphNode>(fr)) {
connecting = true;
emit_signal(SNAME("connection_drag_started"), connecting_from, connecting_index, true);
@@ -780,26 +780,16 @@ void GraphEdit::_top_layer_input(const Ref<InputEvent> &p_ev) {
if (mb.is_valid() && mb->get_button_index() == MouseButton::LEFT && !mb->is_pressed()) {
if (connecting_valid) {
if (connecting && connecting_target) {
- String from = connecting_from;
- int from_port = connecting_index;
- String to = connecting_target_to;
- int to_port = connecting_target_index;
-
- if (!connecting_out) {
- SWAP(from, to);
- SWAP(from_port, to_port);
+ if (connecting_out) {
+ emit_signal(SNAME("connection_request"), connecting_from, connecting_index, connecting_target_to, connecting_target_index);
+ } else {
+ emit_signal(SNAME("connection_request"), connecting_target_to, connecting_target_index, connecting_from, connecting_index);
}
- emit_signal(SNAME("connection_request"), from, from_port, to, to_port);
-
} else if (!just_disconnected) {
- String from = connecting_from;
- int from_port = connecting_index;
- Vector2 ofs = mb->get_position();
-
- if (!connecting_out) {
- emit_signal(SNAME("connection_from_empty"), from, from_port, ofs);
+ if (connecting_out) {
+ emit_signal(SNAME("connection_to_empty"), connecting_from, connecting_index, mb->get_position());
} else {
- emit_signal(SNAME("connection_to_empty"), from, from_port, ofs);
+ emit_signal(SNAME("connection_from_empty"), connecting_from, connecting_index, mb->get_position());
}
}
}
@@ -935,17 +925,12 @@ void GraphEdit::_draw_connection_line(CanvasItem *p_where, const Vector2 &p_from
void GraphEdit::_connections_layer_draw() {
Color activity_color = get_theme_color(SNAME("activity"));
- //draw connections
+ // Draw connections.
List<List<Connection>::Element *> to_erase;
for (List<Connection>::Element *E = connections.front(); E; E = E->next()) {
- NodePath fromnp(E->get().from);
-
- Node *from = get_node(fromnp);
- if (!from) {
- to_erase.push_back(E);
- continue;
- }
+ const Connection &c = E->get();
+ Node *from = get_node(NodePath(c.from));
GraphNode *gfrom = Object::cast_to<GraphNode>(from);
if (!gfrom) {
@@ -953,13 +938,7 @@ void GraphEdit::_connections_layer_draw() {
continue;
}
- NodePath tonp(E->get().to);
- Node *to = get_node(tonp);
- if (!to) {
- to_erase.push_back(E);
- continue;
- }
-
+ Node *to = get_node(NodePath(c.to));
GraphNode *gto = Object::cast_to<GraphNode>(to);
if (!gto) {
@@ -967,21 +946,20 @@ void GraphEdit::_connections_layer_draw() {
continue;
}
- Vector2 frompos = gfrom->get_connection_output_position(E->get().from_port) + gfrom->get_position_offset() * zoom;
- Color color = gfrom->get_connection_output_color(E->get().from_port);
- Vector2 topos = gto->get_connection_input_position(E->get().to_port) + gto->get_position_offset() * zoom;
- Color tocolor = gto->get_connection_input_color(E->get().to_port);
+ Vector2 frompos = gfrom->get_connection_output_position(c.from_port) + gfrom->get_position_offset() * zoom;
+ Color color = gfrom->get_connection_output_color(c.from_port);
+ Vector2 topos = gto->get_connection_input_position(c.to_port) + gto->get_position_offset() * zoom;
+ Color tocolor = gto->get_connection_input_color(c.to_port);
- if (E->get().activity > 0) {
- color = color.lerp(activity_color, E->get().activity);
- tocolor = tocolor.lerp(activity_color, E->get().activity);
+ if (c.activity > 0) {
+ color = color.lerp(activity_color, c.activity);
+ tocolor = tocolor.lerp(activity_color, c.activity);
}
_draw_connection_line(connections_layer, frompos, topos, color, tocolor, lines_thickness, zoom);
}
- while (to_erase.size()) {
- connections.erase(to_erase.front()->get());
- to_erase.pop_front();
+ for (List<Connection>::Element *&E : to_erase) {
+ connections.erase(E);
}
}
@@ -989,7 +967,7 @@ void GraphEdit::_top_layer_draw() {
_update_scroll();
if (connecting) {
- Node *fromn = get_node(connecting_from);
+ Node *fromn = get_node(NodePath(connecting_from));
ERR_FAIL_COND(!fromn);
GraphNode *from = Object::cast_to<GraphNode>(fromn);
ERR_FAIL_COND(!from);
@@ -1087,22 +1065,13 @@ void GraphEdit::_minimap_draw() {
// Draw node connections.
Color activity_color = get_theme_color(SNAME("activity"));
for (const Connection &E : connections) {
- NodePath fromnp(E.from);
-
- Node *from = get_node(fromnp);
- if (!from) {
- continue;
- }
+ Node *from = get_node(NodePath(E.from));
GraphNode *gfrom = Object::cast_to<GraphNode>(from);
if (!gfrom) {
continue;
}
- NodePath tonp(E.to);
- Node *to = get_node(tonp);
- if (!to) {
- continue;
- }
+ Node *to = get_node(NodePath(E.to));
GraphNode *gto = Object::cast_to<GraphNode>(to);
if (!gto) {
continue;
@@ -2406,7 +2375,7 @@ void GraphEdit::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "zoom_step"), "set_zoom_step", "get_zoom_step");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "show_zoom_label"), "set_show_zoom_label", "is_showing_zoom_label");
- ADD_GROUP("Minimap", "minimap");
+ ADD_GROUP("Minimap", "minimap_");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "minimap_enabled"), "set_minimap_enabled", "is_minimap_enabled");
ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "minimap_size", PROPERTY_HINT_NONE, "suffix:px"), "set_minimap_size", "get_minimap_size");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "minimap_opacity"), "set_minimap_opacity", "get_minimap_opacity");
@@ -2428,7 +2397,7 @@ void GraphEdit::_bind_methods() {
ADD_SIGNAL(MethodInfo("begin_node_move"));
ADD_SIGNAL(MethodInfo("end_node_move"));
ADD_SIGNAL(MethodInfo("scroll_offset_changed", PropertyInfo(Variant::VECTOR2, "offset")));
- ADD_SIGNAL(MethodInfo("connection_drag_started", PropertyInfo(Variant::STRING, "from_node"), PropertyInfo(Variant::INT, "from_port"), PropertyInfo(Variant::BOOL, "is_output")));
+ ADD_SIGNAL(MethodInfo("connection_drag_started", PropertyInfo(Variant::STRING_NAME, "from_node"), PropertyInfo(Variant::INT, "from_port"), PropertyInfo(Variant::BOOL, "is_output")));
ADD_SIGNAL(MethodInfo("connection_drag_ended"));
BIND_ENUM_CONSTANT(SCROLL_ZOOMS);
diff --git a/scene/gui/graph_edit.h b/scene/gui/graph_edit.h
index 101087bdbd..eda7ddd824 100644
--- a/scene/gui/graph_edit.h
+++ b/scene/gui/graph_edit.h
@@ -136,14 +136,14 @@ private:
bool arrange_nodes_button_hidden = false;
bool connecting = false;
- String connecting_from;
+ StringName connecting_from;
bool connecting_out = false;
int connecting_index = 0;
int connecting_type = 0;
Color connecting_color;
bool connecting_target = false;
Vector2 connecting_to;
- String connecting_target_to;
+ StringName connecting_target_to;
int connecting_target_index = 0;
bool just_disconnected = false;
bool connecting_valid = false;
diff --git a/scene/gui/graph_node.cpp b/scene/gui/graph_node.cpp
index 5df4c066e4..83c789f3d5 100644
--- a/scene/gui/graph_node.cpp
+++ b/scene/gui/graph_node.cpp
@@ -366,38 +366,46 @@ void GraphNode::_notification(int p_what) {
close_rect = Rect2();
}
- for (const KeyValue<int, Slot> &E : slot_info) {
- if (E.key < 0 || E.key >= cache_y.size()) {
- continue;
- }
- if (!slot_info.has(E.key)) {
- continue;
- }
- const Slot &s = slot_info[E.key];
- // Left port.
- if (s.enable_left) {
- Ref<Texture2D> p = port;
- if (s.custom_slot_left.is_valid()) {
- p = s.custom_slot_left;
+ if (get_child_count() > 0) {
+ for (const KeyValue<int, Slot> &E : slot_info) {
+ if (E.key < 0 || E.key >= cache_y.size()) {
+ continue;
}
- p->draw(get_canvas_item(), icofs + Point2(edgeofs, cache_y[E.key]), s.color_left);
- }
- // Right port.
- if (s.enable_right) {
- Ref<Texture2D> p = port;
- if (s.custom_slot_right.is_valid()) {
- p = s.custom_slot_right;
+ if (!slot_info.has(E.key)) {
+ continue;
+ }
+ const Slot &s = slot_info[E.key];
+ // Left port.
+ if (s.enable_left) {
+ Ref<Texture2D> p = port;
+ if (s.custom_slot_left.is_valid()) {
+ p = s.custom_slot_left;
+ }
+ p->draw(get_canvas_item(), icofs + Point2(edgeofs, cache_y[E.key]), s.color_left);
+ }
+ // Right port.
+ if (s.enable_right) {
+ Ref<Texture2D> p = port;
+ if (s.custom_slot_right.is_valid()) {
+ p = s.custom_slot_right;
+ }
+ p->draw(get_canvas_item(), icofs + Point2(get_size().x - edgeofs, cache_y[E.key]), s.color_right);
}
- p->draw(get_canvas_item(), icofs + Point2(get_size().x - edgeofs, cache_y[E.key]), s.color_right);
- }
- // Draw slot stylebox.
- if (s.draw_stylebox) {
- Control *c = Object::cast_to<Control>(get_child(E.key));
- Rect2 c_rect = c->get_rect();
- c_rect.position.x = sb->get_margin(SIDE_LEFT);
- c_rect.size.width = w;
- draw_style_box(sb_slot, c_rect);
+ // Draw slot stylebox.
+ if (s.draw_stylebox) {
+ Control *c = Object::cast_to<Control>(get_child(E.key));
+ if (!c || !c->is_visible_in_tree()) {
+ continue;
+ }
+ if (c->is_set_as_top_level()) {
+ continue;
+ }
+ Rect2 c_rect = c->get_rect();
+ c_rect.position.x = sb->get_margin(SIDE_LEFT);
+ c_rect.size.width = w;
+ draw_style_box(sb_slot, c_rect);
+ }
}
}
diff --git a/scene/gui/item_list.cpp b/scene/gui/item_list.cpp
index 82f089735d..c44feddd38 100644
--- a/scene/gui/item_list.cpp
+++ b/scene/gui/item_list.cpp
@@ -1550,6 +1550,7 @@ bool ItemList::get_allow_reselect() const {
}
void ItemList::set_icon_scale(real_t p_scale) {
+ ERR_FAIL_COND(!Math::is_finite(p_scale));
icon_scale = p_scale;
}
diff --git a/scene/gui/line_edit.cpp b/scene/gui/line_edit.cpp
index fb5ab9f923..b8e2c76413 100644
--- a/scene/gui/line_edit.cpp
+++ b/scene/gui/line_edit.cpp
@@ -768,18 +768,18 @@ void LineEdit::_notification(int p_what) {
case NOTIFICATION_WM_WINDOW_FOCUS_IN: {
window_has_focus = true;
- draw_caret = true;
+ _validate_caret_can_draw();
queue_redraw();
} break;
case NOTIFICATION_WM_WINDOW_FOCUS_OUT: {
window_has_focus = false;
- draw_caret = false;
+ _validate_caret_can_draw();
queue_redraw();
} break;
case NOTIFICATION_INTERNAL_PROCESS: {
- if (caret_blinking) {
+ if (caret_blink_enabled && caret_can_draw) {
caret_blink_timer += get_process_delta_time();
if (caret_blink_timer >= caret_blink_interval) {
@@ -790,10 +790,6 @@ void LineEdit::_notification(int p_what) {
} break;
case NOTIFICATION_DRAW: {
- if ((!has_focus() && !(menu && menu->has_focus()) && !caret_force_displayed) || !window_has_focus) {
- draw_caret = false;
- }
-
int width, height;
bool rtl = is_layout_rtl();
@@ -806,7 +802,6 @@ void LineEdit::_notification(int p_what) {
Ref<StyleBox> style = theme_cache.normal;
if (!is_editable()) {
style = theme_cache.read_only;
- draw_caret = false;
}
Ref<Font> font = theme_cache.font;
@@ -827,7 +822,7 @@ void LineEdit::_notification(int p_what) {
case HORIZONTAL_ALIGNMENT_FILL:
case HORIZONTAL_ALIGNMENT_LEFT: {
if (rtl) {
- x_ofs = MAX(style->get_margin(SIDE_LEFT), int(size.width - style->get_margin(SIDE_RIGHT) - (text_width)));
+ x_ofs = MAX(style->get_margin(SIDE_LEFT), int(size.width - Math::ceil(style->get_margin(SIDE_RIGHT) + (text_width))));
} else {
x_ofs = style->get_offset().x;
}
@@ -843,7 +838,7 @@ void LineEdit::_notification(int p_what) {
if (rtl) {
x_ofs = style->get_offset().x;
} else {
- x_ofs = MAX(style->get_margin(SIDE_LEFT), int(size.width - style->get_margin(SIDE_RIGHT) - (text_width)));
+ x_ofs = MAX(style->get_margin(SIDE_LEFT), int(size.width - Math::ceil(style->get_margin(SIDE_RIGHT) + (text_width))));
}
} break;
}
@@ -953,24 +948,37 @@ void LineEdit::_notification(int p_what) {
// Draw carets.
ofs.x = x_ofs + scroll_offset;
- if (draw_caret || drag_caret_force_displayed) {
+ if ((caret_can_draw && draw_caret) || drag_caret_force_displayed) {
// Prevent carets from disappearing at theme scales below 1.0 (if the caret width is 1).
const int caret_width = theme_cache.caret_width * MAX(1, theme_cache.base_scale);
if (ime_text.length() == 0) {
// Normal caret.
CaretInfo caret = TS->shaped_text_get_carets(text_rid, caret_column);
-
- if (caret.l_caret == Rect2() && caret.t_caret == Rect2()) {
+ if (using_placeholder || (caret.l_caret == Rect2() && caret.t_caret == Rect2())) {
// No carets, add one at the start.
int h = theme_cache.font->get_height(theme_cache.font_size);
int y = style->get_offset().y + (y_area - h) / 2;
- if (rtl) {
- caret.l_dir = TextServer::DIRECTION_RTL;
- caret.l_caret = Rect2(Vector2(ofs_max, y), Size2(caret_width, h));
- } else {
- caret.l_dir = TextServer::DIRECTION_LTR;
- caret.l_caret = Rect2(Vector2(x_ofs, y), Size2(caret_width, h));
+ caret.l_dir = (rtl) ? TextServer::DIRECTION_RTL : TextServer::DIRECTION_LTR;
+ switch (alignment) {
+ case HORIZONTAL_ALIGNMENT_FILL:
+ case HORIZONTAL_ALIGNMENT_LEFT: {
+ if (rtl) {
+ caret.l_caret = Rect2(Vector2(ofs_max, y), Size2(caret_width, h));
+ } else {
+ caret.l_caret = Rect2(Vector2(style->get_offset().x, y), Size2(caret_width, h));
+ }
+ } break;
+ case HORIZONTAL_ALIGNMENT_CENTER: {
+ caret.l_caret = Rect2(Vector2(size.x / 2, y), Size2(caret_width, h));
+ } break;
+ case HORIZONTAL_ALIGNMENT_RIGHT: {
+ if (rtl) {
+ caret.l_caret = Rect2(Vector2(style->get_offset().x, y), Size2(caret_width, h));
+ } else {
+ caret.l_caret = Rect2(Vector2(ofs_max, y), Size2(caret_width, h));
+ }
+ } break;
}
RenderingServer::get_singleton()->canvas_item_add_rect(ci, caret.l_caret, caret_color);
} else {
@@ -1050,16 +1058,7 @@ void LineEdit::_notification(int p_what) {
} break;
case NOTIFICATION_FOCUS_ENTER: {
- if (!caret_force_displayed) {
- if (caret_blink_enabled) {
- if (!caret_blinking) {
- caret_blinking = true;
- caret_blink_timer = 0.0;
- }
- } else {
- draw_caret = true;
- }
- }
+ _validate_caret_can_draw();
if (select_all_on_focus) {
if (Input::get_singleton()->is_mouse_button_pressed(MouseButton::LEFT)) {
@@ -1080,9 +1079,7 @@ void LineEdit::_notification(int p_what) {
} break;
case NOTIFICATION_FOCUS_EXIT: {
- if (caret_blink_enabled && !caret_force_displayed) {
- caret_blinking = false;
- }
+ _validate_caret_can_draw();
if (get_viewport()->get_window_id() != DisplayServer::INVALID_WINDOW_ID && DisplayServer::get_singleton()->has_feature(DisplayServer::FEATURE_IME)) {
DisplayServer::get_singleton()->window_set_ime_position(Point2(), get_viewport()->get_window_id());
@@ -1388,21 +1385,18 @@ bool LineEdit::is_caret_blink_enabled() const {
}
void LineEdit::set_caret_blink_enabled(const bool p_enabled) {
+ if (caret_blink_enabled == p_enabled) {
+ return;
+ }
+
caret_blink_enabled = p_enabled;
set_process_internal(p_enabled);
- if (has_focus() || caret_force_displayed) {
- if (p_enabled) {
- if (!caret_blinking) {
- caret_blinking = true;
- caret_blink_timer = 0.0;
- }
- } else {
- caret_blinking = false;
- }
+ draw_caret = !caret_blink_enabled;
+ if (caret_blink_enabled) {
+ caret_blink_timer = 0.0;
}
-
- draw_caret = true;
+ queue_redraw();
notify_property_list_changed();
}
@@ -1412,8 +1406,13 @@ bool LineEdit::is_caret_force_displayed() const {
}
void LineEdit::set_caret_force_displayed(const bool p_enabled) {
+ if (caret_force_displayed == p_enabled) {
+ return;
+ }
+
caret_force_displayed = p_enabled;
- set_caret_blink_enabled(caret_blink_enabled);
+ _validate_caret_can_draw();
+
queue_redraw();
}
@@ -1429,7 +1428,7 @@ void LineEdit::set_caret_blink_interval(const float p_interval) {
void LineEdit::_reset_caret_blink_timer() {
if (caret_blink_enabled) {
draw_caret = true;
- if (has_focus()) {
+ if (caret_can_draw) {
caret_blink_timer = 0.0;
queue_redraw();
}
@@ -1438,11 +1437,19 @@ void LineEdit::_reset_caret_blink_timer() {
void LineEdit::_toggle_draw_caret() {
draw_caret = !draw_caret;
- if (is_visible_in_tree() && ((has_focus() && window_has_focus) || caret_force_displayed)) {
+ if (is_visible_in_tree() && caret_can_draw) {
queue_redraw();
}
}
+void LineEdit::_validate_caret_can_draw() {
+ if (caret_blink_enabled) {
+ draw_caret = true;
+ caret_blink_timer = 0.0;
+ }
+ caret_can_draw = editable && (window_has_focus || (menu && menu->has_focus())) && (has_focus() || caret_force_displayed);
+}
+
void LineEdit::delete_char() {
if ((text.length() <= 0) || (caret_column == 0)) {
return;
@@ -1833,6 +1840,7 @@ void LineEdit::set_editable(bool p_editable) {
}
editable = p_editable;
+ _validate_caret_can_draw();
update_minimum_size();
queue_redraw();
@@ -2510,6 +2518,8 @@ void LineEdit::_ensure_menu() {
menu->add_child(menu_ctl, false, INTERNAL_MODE_FRONT);
menu->connect("id_pressed", callable_mp(this, &LineEdit::menu_option));
+ menu->connect(SNAME("focus_entered"), callable_mp(this, &LineEdit::_validate_caret_can_draw));
+ menu->connect(SNAME("focus_exited"), callable_mp(this, &LineEdit::_validate_caret_can_draw));
menu_dir->connect("id_pressed", callable_mp(this, &LineEdit::menu_option));
menu_ctl->connect("id_pressed", callable_mp(this, &LineEdit::menu_option));
}
diff --git a/scene/gui/line_edit.h b/scene/gui/line_edit.h
index e0a079b623..79db9dce21 100644
--- a/scene/gui/line_edit.h
+++ b/scene/gui/line_edit.h
@@ -172,7 +172,7 @@ private:
bool draw_caret = true;
float caret_blink_interval = 0.65;
double caret_blink_timer = 0.0;
- bool caret_blinking = false;
+ bool caret_can_draw = false;
bool pending_select_all_on_focus = false;
bool select_all_on_focus = false;
@@ -225,6 +225,7 @@ private:
void _reset_caret_blink_timer();
void _toggle_draw_caret();
+ void _validate_caret_can_draw();
void clear_internal();
diff --git a/scene/gui/link_button.cpp b/scene/gui/link_button.cpp
index 7219e86f52..2c43ca7143 100644
--- a/scene/gui/link_button.cpp
+++ b/scene/gui/link_button.cpp
@@ -108,6 +108,14 @@ String LinkButton::get_language() const {
return language;
}
+void LinkButton::set_uri(const String &p_uri) {
+ uri = p_uri;
+}
+
+String LinkButton::get_uri() const {
+ return uri;
+}
+
void LinkButton::set_underline_mode(UnderlineMode p_underline_mode) {
if (underline_mode == p_underline_mode) {
return;
@@ -121,6 +129,14 @@ LinkButton::UnderlineMode LinkButton::get_underline_mode() const {
return underline_mode;
}
+void LinkButton::pressed() {
+ if (uri.is_empty()) {
+ return;
+ }
+
+ OS::get_singleton()->shell_open(uri);
+}
+
Size2 LinkButton::get_minimum_size() const {
return text_buf->get_size();
}
@@ -245,6 +261,8 @@ void LinkButton::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_text_direction"), &LinkButton::get_text_direction);
ClassDB::bind_method(D_METHOD("set_language", "language"), &LinkButton::set_language);
ClassDB::bind_method(D_METHOD("get_language"), &LinkButton::get_language);
+ ClassDB::bind_method(D_METHOD("set_uri", "uri"), &LinkButton::set_uri);
+ ClassDB::bind_method(D_METHOD("get_uri"), &LinkButton::get_uri);
ClassDB::bind_method(D_METHOD("set_underline_mode", "underline_mode"), &LinkButton::set_underline_mode);
ClassDB::bind_method(D_METHOD("get_underline_mode"), &LinkButton::get_underline_mode);
ClassDB::bind_method(D_METHOD("set_structured_text_bidi_override", "parser"), &LinkButton::set_structured_text_bidi_override);
@@ -258,6 +276,7 @@ void LinkButton::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::STRING, "text"), "set_text", "get_text");
ADD_PROPERTY(PropertyInfo(Variant::INT, "underline", PROPERTY_HINT_ENUM, "Always,On Hover,Never"), "set_underline_mode", "get_underline_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "uri"), "set_uri", "get_uri");
ADD_GROUP("BiDi", "");
ADD_PROPERTY(PropertyInfo(Variant::INT, "text_direction", PROPERTY_HINT_ENUM, "Auto,Left-to-Right,Right-to-Left,Inherited"), "set_text_direction", "get_text_direction");
diff --git a/scene/gui/link_button.h b/scene/gui/link_button.h
index accd848163..c71872fc86 100644
--- a/scene/gui/link_button.h
+++ b/scene/gui/link_button.h
@@ -49,6 +49,7 @@ private:
String xl_text;
Ref<TextLine> text_buf;
UnderlineMode underline_mode = UNDERLINE_MODE_ALWAYS;
+ String uri;
String language;
TextDirection text_direction = TEXT_DIRECTION_AUTO;
@@ -76,6 +77,7 @@ private:
void _shape();
protected:
+ virtual void pressed() override;
virtual Size2 get_minimum_size() const override;
virtual void _update_theme_item_cache() override;
void _notification(int p_what);
@@ -84,6 +86,8 @@ protected:
public:
void set_text(const String &p_text);
String get_text() const;
+ void set_uri(const String &p_uri);
+ String get_uri() const;
void set_structured_text_bidi_override(TextServer::StructuredTextParser p_parser);
TextServer::StructuredTextParser get_structured_text_bidi_override() const;
diff --git a/scene/gui/option_button.cpp b/scene/gui/option_button.cpp
index 0940b4c07b..6d0bbdd6af 100644
--- a/scene/gui/option_button.cpp
+++ b/scene/gui/option_button.cpp
@@ -491,9 +491,9 @@ void OptionButton::show_popup() {
return;
}
- Size2 size = get_size() * get_viewport()->get_canvas_transform().get_scale();
- popup->set_position(get_screen_position() + Size2(0, size.height * get_global_transform().get_scale().y));
- popup->set_size(Size2(size.width, 0));
+ Size2 button_size = get_global_transform_with_canvas().get_scale() * get_size();
+ popup->set_position(get_screen_position() + Size2(0, button_size.height));
+ popup->set_size(Size2i(button_size.width, 0));
// If not triggered by the mouse, start the popup with the checked item (or the first enabled one) focused.
if (current != NONE_SELECTED && !popup->is_item_disabled(current)) {
diff --git a/scene/gui/popup_menu.cpp b/scene/gui/popup_menu.cpp
index 82f56a56c9..5d8e106e26 100644
--- a/scene/gui/popup_menu.cpp
+++ b/scene/gui/popup_menu.cpp
@@ -221,7 +221,7 @@ void PopupMenu::_activate_submenu(int p_over, bool p_by_keyboard) {
Rect2 safe_area = this_rect;
safe_area.position.y += items[p_over]._ofs_cache + scroll_offset + theme_cache.panel_style->get_offset().height - theme_cache.v_separation / 2;
- safe_area.size.y = items[p_over]._height_cache;
+ safe_area.size.y = items[p_over]._height_cache + theme_cache.v_separation;
DisplayServer::get_singleton()->window_set_popup_safe_rect(submenu_popup->get_window_id(), safe_area);
// Make the position of the parent popup relative to submenu popup.
@@ -558,7 +558,7 @@ void PopupMenu::_draw_items() {
check_ofs += theme_cache.h_separation;
}
- Point2 ofs = Point2();
+ Point2 ofs;
// Loop through all items and draw each.
for (int i = 0; i < items.size(); i++) {
diff --git a/scene/gui/progress_bar.cpp b/scene/gui/progress_bar.cpp
index 8369eaa227..50bcfa6a0c 100644
--- a/scene/gui/progress_bar.cpp
+++ b/scene/gui/progress_bar.cpp
@@ -103,7 +103,12 @@ void ProgressBar::_notification(int p_what) {
}
if (show_percentage) {
- String txt = TS->format_number(itos(int(get_as_ratio() * 100))) + TS->percent_sign();
+ String txt = itos(int(get_as_ratio() * 100));
+ if (is_localizing_numeral_system()) {
+ txt = TS->format_number(txt) + TS->percent_sign();
+ } else {
+ txt += String("%");
+ }
TextLine tl = TextLine(txt, theme_cache.font, theme_cache.font_size);
Vector2 text_pos = (Point2(get_size().width - tl.get_size().x, get_size().height - tl.get_size().y) / 2).round();
diff --git a/scene/gui/range.cpp b/scene/gui/range.cpp
index 27002fad38..00c81c8616 100644
--- a/scene/gui/range.cpp
+++ b/scene/gui/range.cpp
@@ -64,11 +64,6 @@ void Range::_changed_notify(const char *p_what) {
queue_redraw();
}
-void Range::_validate_values() {
- shared->max = MAX(shared->max, shared->min);
- shared->page = CLAMP(shared->page, 0, shared->max - shared->min);
-}
-
void Range::Shared::emit_changed(const char *p_what) {
for (Range *E : owners) {
Range *r = E;
@@ -90,7 +85,7 @@ void Range::set_value(double p_val) {
void Range::set_value_no_signal(double p_val) {
if (shared->step > 0) {
- p_val = Math::round(p_val / shared->step) * shared->step;
+ p_val = Math::round((p_val - shared->min) / shared->step) * shared->step + shared->min;
}
if (_rounded_values) {
@@ -118,8 +113,9 @@ void Range::set_min(double p_min) {
}
shared->min = p_min;
+ shared->max = MAX(shared->max, shared->min);
+ shared->page = CLAMP(shared->page, 0, shared->max - shared->min);
set_value(shared->val);
- _validate_values();
shared->emit_changed("min");
@@ -127,13 +123,14 @@ void Range::set_min(double p_min) {
}
void Range::set_max(double p_max) {
- if (shared->max == p_max) {
+ double max_validated = MAX(p_max, shared->min);
+ if (shared->max == max_validated) {
return;
}
- shared->max = p_max;
+ shared->max = max_validated;
+ shared->page = CLAMP(shared->page, 0, shared->max - shared->min);
set_value(shared->val);
- _validate_values();
shared->emit_changed("max");
}
@@ -148,13 +145,13 @@ void Range::set_step(double p_step) {
}
void Range::set_page(double p_page) {
- if (shared->page == p_page) {
+ double page_validated = CLAMP(p_page, 0, shared->max - shared->min);
+ if (shared->page == page_validated) {
return;
}
- shared->page = p_page;
+ shared->page = page_validated;
set_value(shared->val);
- _validate_values();
shared->emit_changed("page");
}
diff --git a/scene/gui/range.h b/scene/gui/range.h
index f804155dec..5267216f12 100644
--- a/scene/gui/range.h
+++ b/scene/gui/range.h
@@ -59,7 +59,6 @@ class Range : public Control {
void _value_changed_notify();
void _changed_notify(const char *p_what = "");
- void _validate_values();
protected:
virtual void _value_changed(double p_value);
diff --git a/scene/gui/rich_text_effect.cpp b/scene/gui/rich_text_effect.cpp
index 0dece1c287..20d82095a1 100644
--- a/scene/gui/rich_text_effect.cpp
+++ b/scene/gui/rich_text_effect.cpp
@@ -88,6 +88,9 @@ void CharFXTransform::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_glyph_index"), &CharFXTransform::get_glyph_index);
ClassDB::bind_method(D_METHOD("set_glyph_index", "glyph_index"), &CharFXTransform::set_glyph_index);
+ ClassDB::bind_method(D_METHOD("get_relative_index"), &CharFXTransform::get_relative_index);
+ ClassDB::bind_method(D_METHOD("set_relative_index", "relative_index"), &CharFXTransform::set_relative_index);
+
ClassDB::bind_method(D_METHOD("get_glyph_count"), &CharFXTransform::get_glyph_count);
ClassDB::bind_method(D_METHOD("set_glyph_count", "glyph_count"), &CharFXTransform::set_glyph_count);
@@ -107,5 +110,6 @@ void CharFXTransform::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::INT, "glyph_index"), "set_glyph_index", "get_glyph_index");
ADD_PROPERTY(PropertyInfo(Variant::INT, "glyph_count"), "set_glyph_count", "get_glyph_count");
ADD_PROPERTY(PropertyInfo(Variant::INT, "glyph_flags"), "set_glyph_flags", "get_glyph_flags");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "relative_index"), "set_relative_index", "get_relative_index");
ADD_PROPERTY(PropertyInfo(Variant::RID, "font"), "set_font", "get_font");
}
diff --git a/scene/gui/rich_text_effect.h b/scene/gui/rich_text_effect.h
index 4532a812ee..886442bc80 100644
--- a/scene/gui/rich_text_effect.h
+++ b/scene/gui/rich_text_effect.h
@@ -52,6 +52,7 @@ public:
uint32_t glyph_index = 0;
uint16_t glyph_flags = 0;
uint8_t glyph_count = 0;
+ int32_t relative_index = 0;
RID font;
CharFXTransform();
@@ -78,12 +79,15 @@ public:
uint32_t get_glyph_index() const { return glyph_index; };
void set_glyph_index(uint32_t p_glyph_index) { glyph_index = p_glyph_index; };
- uint16_t get_glyph_flags() const { return glyph_index; };
+ uint16_t get_glyph_flags() const { return glyph_flags; };
void set_glyph_flags(uint16_t p_glyph_flags) { glyph_flags = p_glyph_flags; };
uint8_t get_glyph_count() const { return glyph_count; };
void set_glyph_count(uint8_t p_glyph_count) { glyph_count = p_glyph_count; };
+ int32_t get_relative_index() const { return relative_index; };
+ void set_relative_index(int32_t p_relative_index) { relative_index = p_relative_index; };
+
RID get_font() const { return font; };
void set_font(RID p_font) { font = p_font; };
diff --git a/scene/gui/rich_text_label.cpp b/scene/gui/rich_text_label.cpp
index 7f487175dc..d5c4fd3f07 100644
--- a/scene/gui/rich_text_label.cpp
+++ b/scene/gui/rich_text_label.cpp
@@ -150,7 +150,12 @@ RichTextLabel::Item *RichTextLabel::_get_item_at_pos(RichTextLabel::Item *p_item
return it;
}
} break;
- case ITEM_IMAGE:
+ case ITEM_IMAGE: {
+ offset += 1;
+ if (offset > p_position) {
+ return it;
+ }
+ } break;
case ITEM_TABLE: {
offset += 1;
} break;
@@ -325,7 +330,11 @@ float RichTextLabel::_resize_line(ItemFrame *p_frame, int p_line, const Ref<Font
if (table->columns[i].expand && total_ratio > 0 && remaining_width > 0) {
table->columns[i].width += table->columns[i].expand_ratio * remaining_width / total_ratio;
}
- table->total_width += table->columns[i].width + theme_cache.table_h_separation;
+ if (i != col_count - 1) {
+ table->total_width += table->columns[i].width + theme_cache.table_h_separation;
+ } else {
+ table->total_width += table->columns[i].width;
+ }
}
// Resize to max_width if needed and distribute the remaining space.
@@ -366,6 +375,7 @@ float RichTextLabel::_resize_line(ItemFrame *p_frame, int p_line, const Ref<Font
idx = 0;
table->total_height = 0;
table->rows.clear();
+ table->rows_baseline.clear();
Vector2 offset;
float row_height = 0.0;
@@ -379,13 +389,13 @@ float RichTextLabel::_resize_line(ItemFrame *p_frame, int p_line, const Ref<Font
offset.x += frame->padding.position.x;
float yofs = frame->padding.position.y;
float prev_h = 0;
+ float row_baseline = 0.0;
for (int i = 0; i < (int)frame->lines.size(); i++) {
MutexLock sub_lock(frame->lines[i].text_buf->get_mutex());
frame->lines[i].text_buf->set_width(table->columns[column].width);
table->columns[column].width = MAX(table->columns[column].width, ceil(frame->lines[i].text_buf->get_size().x));
frame->lines[i].offset.y = prev_h;
- frame->lines[i].offset += offset;
float h = frame->lines[i].text_buf->get_size().y + (frame->lines[i].text_buf->get_line_count() - 1) * theme_cache.line_separation;
if (i > 0) {
@@ -399,6 +409,9 @@ float RichTextLabel::_resize_line(ItemFrame *p_frame, int p_line, const Ref<Font
}
yofs += h;
prev_h = frame->lines[i].offset.y + frame->lines[i].text_buf->get_size().y + frame->lines[i].text_buf->get_line_count() * theme_cache.line_separation;
+
+ frame->lines[i].offset += offset;
+ row_baseline = MAX(row_baseline, frame->lines[i].text_buf->get_line_ascent(frame->lines[i].text_buf->get_line_count() - 1));
}
yofs += frame->padding.size.y;
offset.x += table->columns[column].width + theme_cache.table_h_separation + frame->padding.size.x;
@@ -410,11 +423,17 @@ float RichTextLabel::_resize_line(ItemFrame *p_frame, int p_line, const Ref<Font
table->total_height += row_height;
offset.y += row_height;
table->rows.push_back(row_height);
+ table->rows_baseline.push_back(table->total_height - row_height + row_baseline);
row_height = 0;
}
idx++;
}
- l.text_buf->resize_object((uint64_t)it, Size2(table->total_width, table->total_height), table->inline_align);
+ int row_idx = (table->align_to_row < 0) ? table->rows_baseline.size() - 1 : table->align_to_row;
+ if (table->rows_baseline.size() != 0 && row_idx < (int)table->rows_baseline.size() - 1) {
+ l.text_buf->resize_object((uint64_t)it, Size2(table->total_width, table->total_height), table->inline_align, Math::round(table->rows_baseline[row_idx]));
+ } else {
+ l.text_buf->resize_object((uint64_t)it, Size2(table->total_width, table->total_height), table->inline_align);
+ }
} break;
default:
break;
@@ -600,7 +619,11 @@ float RichTextLabel::_shape_line(ItemFrame *p_frame, int p_line, const Ref<Font>
if (table->columns[i].expand && total_ratio > 0 && remaining_width > 0) {
table->columns[i].width += table->columns[i].expand_ratio * remaining_width / total_ratio;
}
- table->total_width += table->columns[i].width + theme_cache.table_h_separation;
+ if (i != col_count - 1) {
+ table->total_width += table->columns[i].width + theme_cache.table_h_separation;
+ } else {
+ table->total_width += table->columns[i].width;
+ }
}
// Resize to max_width if needed and distribute the remaining space.
@@ -641,6 +664,7 @@ float RichTextLabel::_shape_line(ItemFrame *p_frame, int p_line, const Ref<Font>
idx = 0;
table->total_height = 0;
table->rows.clear();
+ table->rows_baseline.clear();
Vector2 offset;
float row_height = 0.0;
@@ -654,6 +678,7 @@ float RichTextLabel::_shape_line(ItemFrame *p_frame, int p_line, const Ref<Font>
offset.x += frame->padding.position.x;
float yofs = frame->padding.position.y;
float prev_h = 0;
+ float row_baseline = 0.0;
for (int i = 0; i < (int)frame->lines.size(); i++) {
MutexLock sub_lock(frame->lines[i].text_buf->get_mutex());
@@ -661,7 +686,6 @@ float RichTextLabel::_shape_line(ItemFrame *p_frame, int p_line, const Ref<Font>
table->columns[column].width = MAX(table->columns[column].width, ceil(frame->lines[i].text_buf->get_size().x));
frame->lines[i].offset.y = prev_h;
- frame->lines[i].offset += offset;
float h = frame->lines[i].text_buf->get_size().y + (frame->lines[i].text_buf->get_line_count() - 1) * theme_cache.line_separation;
if (i > 0) {
@@ -675,6 +699,9 @@ float RichTextLabel::_shape_line(ItemFrame *p_frame, int p_line, const Ref<Font>
}
yofs += h;
prev_h = frame->lines[i].offset.y + frame->lines[i].text_buf->get_size().y + frame->lines[i].text_buf->get_line_count() * theme_cache.line_separation;
+
+ frame->lines[i].offset += offset;
+ row_baseline = MAX(row_baseline, frame->lines[i].text_buf->get_line_ascent(frame->lines[i].text_buf->get_line_count() - 1));
}
yofs += frame->padding.size.y;
offset.x += table->columns[column].width + theme_cache.table_h_separation + frame->padding.size.x;
@@ -687,12 +714,17 @@ float RichTextLabel::_shape_line(ItemFrame *p_frame, int p_line, const Ref<Font>
table->total_height += row_height;
offset.y += row_height;
table->rows.push_back(row_height);
+ table->rows_baseline.push_back(table->total_height - row_height + row_baseline);
row_height = 0;
}
idx++;
}
-
- l.text_buf->add_object((uint64_t)it, Size2(table->total_width, table->total_height), table->inline_align, t_char_count);
+ int row_idx = (table->align_to_row < 0) ? table->rows_baseline.size() - 1 : table->align_to_row;
+ if (table->rows_baseline.size() != 0 && row_idx < (int)table->rows_baseline.size() - 1) {
+ l.text_buf->add_object((uint64_t)it, Size2(table->total_width, table->total_height), table->inline_align, t_char_count, Math::round(table->rows_baseline[row_idx]));
+ } else {
+ l.text_buf->add_object((uint64_t)it, Size2(table->total_width, table->total_height), table->inline_align, t_char_count);
+ }
txt += String::chr(0xfffc).repeat(t_char_count);
} break;
default:
@@ -752,7 +784,10 @@ int RichTextLabel::_draw_line(ItemFrame *p_frame, int p_line, const Vector2 &p_o
prefix = _prefix;
break;
} else if (list_items[i]->list_type == LIST_NUMBERS) {
- segment = TS->format_number(itos(list_index[i]), _find_language(l.from));
+ segment = itos(list_index[i]);
+ if (is_localizing_numeral_system()) {
+ segment = TS->format_number(segment, _find_language(l.from));
+ }
} else if (list_items[i]->list_type == LIST_LETTERS) {
segment = _letters(list_index[i], list_items[i]->capitalize);
} else if (list_items[i]->list_type == LIST_ROMAN) {
@@ -887,7 +922,7 @@ int RichTextLabel::_draw_line(ItemFrame *p_frame, int p_line, const Vector2 &p_o
Color odd_row_bg = theme_cache.table_odd_row_bg;
Color even_row_bg = theme_cache.table_even_row_bg;
Color border = theme_cache.table_border;
- int hseparation = theme_cache.table_h_separation;
+ int h_separation = theme_cache.table_h_separation;
int col_count = table->columns.size();
int row_count = table->rows.size();
@@ -905,11 +940,11 @@ int RichTextLabel::_draw_line(ItemFrame *p_frame, int p_line, const Vector2 &p_o
coff.x = rect.size.width - table->columns[col].width - coff.x;
}
if (row % 2 == 0) {
- draw_rect(Rect2(p_ofs + rect.position + off + coff - frame->padding.position, Size2(table->columns[col].width + hseparation + frame->padding.position.x + frame->padding.size.x, table->rows[row])), (frame->odd_row_bg != Color(0, 0, 0, 0) ? frame->odd_row_bg : odd_row_bg), true);
+ draw_rect(Rect2(p_ofs + rect.position + off + coff - frame->padding.position, Size2(table->columns[col].width + h_separation + frame->padding.position.x + frame->padding.size.x, table->rows[row])), (frame->odd_row_bg != Color(0, 0, 0, 0) ? frame->odd_row_bg : odd_row_bg), true);
} else {
- draw_rect(Rect2(p_ofs + rect.position + off + coff - frame->padding.position, Size2(table->columns[col].width + hseparation + frame->padding.position.x + frame->padding.size.x, table->rows[row])), (frame->even_row_bg != Color(0, 0, 0, 0) ? frame->even_row_bg : even_row_bg), true);
+ draw_rect(Rect2(p_ofs + rect.position + off + coff - frame->padding.position, Size2(table->columns[col].width + h_separation + frame->padding.position.x + frame->padding.size.x, table->rows[row])), (frame->even_row_bg != Color(0, 0, 0, 0) ? frame->even_row_bg : even_row_bg), true);
}
- draw_rect(Rect2(p_ofs + rect.position + off + coff - frame->padding.position, Size2(table->columns[col].width + hseparation + frame->padding.position.x + frame->padding.size.x, table->rows[row])), (frame->border != Color(0, 0, 0, 0) ? frame->border : border), false);
+ draw_rect(Rect2(p_ofs + rect.position + off + coff - frame->padding.position, Size2(table->columns[col].width + h_separation + frame->padding.position.x + frame->padding.size.x, table->rows[row])), (frame->border != Color(0, 0, 0, 0) ? frame->border : border), false);
}
for (int j = 0; j < (int)frame->lines.size(); j++) {
@@ -1002,6 +1037,7 @@ int RichTextLabel::_draw_line(ItemFrame *p_frame, int p_line, const Vector2 &p_o
if (!custom_effect.is_null()) {
charfx->elapsed_time = item_custom->elapsed_time;
charfx->range = Vector2i(l.char_offset + glyphs[i].start, l.char_offset + glyphs[i].end);
+ charfx->relative_index = l.char_offset + glyphs[i].start - item_fx->char_ofs;
charfx->visibility = txt_visible;
charfx->outline = true;
charfx->font = frid;
@@ -1219,6 +1255,7 @@ int RichTextLabel::_draw_line(ItemFrame *p_frame, int p_line, const Vector2 &p_o
if (!custom_effect.is_null()) {
charfx->elapsed_time = item_custom->elapsed_time;
charfx->range = Vector2i(l.char_offset + glyphs[i].start, l.char_offset + glyphs[i].end);
+ charfx->relative_index = l.char_offset + glyphs[i].start - item_fx->char_ofs;
charfx->visibility = txt_visible;
charfx->outline = false;
charfx->font = frid;
@@ -1849,10 +1886,6 @@ void RichTextLabel::_notification(int p_what) {
}
Control::CursorShape RichTextLabel::get_cursor_shape(const Point2 &p_pos) const {
- if (!underline_meta) {
- return get_default_cursor_shape();
- }
-
if (selection.click_item) {
return CURSOR_IBEAM;
}
@@ -2686,6 +2719,7 @@ bool RichTextLabel::_validate_line_caches() {
int ctrl_height = get_size().height;
// Update fonts.
+ float old_scroll = vscroll->get_value();
if (main->first_invalid_font_line.load() != (int)main->lines.size()) {
for (int i = main->first_invalid_font_line.load(); i < (int)main->lines.size(); i++) {
_update_line_font(main, i, theme_cache.normal_font, theme_cache.normal_font_size);
@@ -2695,6 +2729,7 @@ bool RichTextLabel::_validate_line_caches() {
}
if (main->first_resized_line.load() == (int)main->lines.size()) {
+ vscroll->set_value(old_scroll);
return true;
}
@@ -2733,6 +2768,8 @@ bool RichTextLabel::_validate_line_caches() {
vscroll->set_page(text_rect.size.height);
if (scroll_follow && scroll_following) {
vscroll->set_value(total_height);
+ } else {
+ vscroll->set_value(old_scroll);
}
updating_scroll = false;
@@ -3034,18 +3071,18 @@ void RichTextLabel::add_newline() {
queue_redraw();
}
-bool RichTextLabel::remove_line(const int p_line) {
+bool RichTextLabel::remove_paragraph(const int p_paragraph) {
_stop_thread();
MutexLock data_lock(data_mutex);
- if (p_line >= (int)current_frame->lines.size() || p_line < 0) {
+ if (p_paragraph >= (int)current_frame->lines.size() || p_paragraph < 0) {
return false;
}
// Remove all subitems with the same line as that provided.
Vector<int> subitem_indices_to_remove;
for (int i = 0; i < current->subitems.size(); i++) {
- if (current->subitems[i]->line == p_line) {
+ if (current->subitems[i]->line == p_paragraph) {
subitem_indices_to_remove.push_back(i);
}
}
@@ -3055,17 +3092,17 @@ bool RichTextLabel::remove_line(const int p_line) {
for (int i = subitem_indices_to_remove.size() - 1; i >= 0; i--) {
int subitem_idx = subitem_indices_to_remove[i];
had_newline = had_newline || current->subitems[subitem_idx]->type == ITEM_NEWLINE;
- _remove_item(current->subitems[subitem_idx], current->subitems[subitem_idx]->line, p_line);
+ _remove_item(current->subitems[subitem_idx], current->subitems[subitem_idx]->line, p_paragraph);
}
if (!had_newline) {
- current_frame->lines.remove_at(p_line);
+ current_frame->lines.remove_at(p_paragraph);
if (current_frame->lines.size() == 0) {
current_frame->lines.resize(1);
}
}
- if (p_line == 0 && current->subitems.size() > 0) {
+ if (p_paragraph == 0 && current->subitems.size() > 0) {
main->lines[0].from = main;
}
@@ -3145,7 +3182,8 @@ void RichTextLabel::push_normal() {
void RichTextLabel::push_bold() {
ERR_FAIL_COND(theme_cache.bold_font.is_null());
- _push_def_font(BOLD_FONT);
+ ItemFont *item_font = _find_font(current);
+ _push_def_font((item_font && item_font->def_font == ITALICS_FONT) ? BOLD_ITALICS_FONT : BOLD_FONT);
}
void RichTextLabel::push_bold_italics() {
@@ -3157,7 +3195,8 @@ void RichTextLabel::push_bold_italics() {
void RichTextLabel::push_italics() {
ERR_FAIL_COND(theme_cache.italics_font.is_null());
- _push_def_font(ITALICS_FONT);
+ ItemFont *item_font = _find_font(current);
+ _push_def_font((item_font && item_font->def_font == BOLD_FONT) ? BOLD_ITALICS_FONT : ITALICS_FONT);
}
void RichTextLabel::push_mono() {
@@ -3293,7 +3332,7 @@ void RichTextLabel::push_hint(const String &p_string) {
_add_item(item, true);
}
-void RichTextLabel::push_table(int p_columns, InlineAlignment p_alignment) {
+void RichTextLabel::push_table(int p_columns, InlineAlignment p_alignment, int p_align_to_row) {
_stop_thread();
MutexLock data_lock(data_mutex);
@@ -3303,6 +3342,7 @@ void RichTextLabel::push_table(int p_columns, InlineAlignment p_alignment) {
item->columns.resize(p_columns);
item->total_width = 0;
item->inline_align = p_alignment;
+ item->align_to_row = p_align_to_row;
for (int i = 0; i < (int)item->columns.size(); i++) {
item->columns[i].expand = false;
item->columns[i].expand_ratio = 1;
@@ -3783,6 +3823,8 @@ void RichTextLabel::append_text(const String &p_bbcode) {
alignment = INLINE_ALIGNMENT_TOP_TO;
} else if (subtag[1] == "center" || subtag[1] == "c") {
alignment = INLINE_ALIGNMENT_CENTER_TO;
+ } else if (subtag[1] == "baseline" || subtag[1] == "l") {
+ alignment = INLINE_ALIGNMENT_BASELINE_TO;
} else if (subtag[1] == "bottom" || subtag[1] == "b") {
alignment = INLINE_ALIGNMENT_BOTTOM_TO;
}
@@ -3804,8 +3846,12 @@ void RichTextLabel::append_text(const String &p_bbcode) {
alignment = INLINE_ALIGNMENT_BOTTOM;
}
}
+ int row = -1;
+ if (subtag.size() > 3) {
+ row = subtag[3].to_int();
+ }
- push_table(columns, (InlineAlignment)alignment);
+ push_table(columns, (InlineAlignment)alignment, row);
pos = brk_end + 1;
tag_stack.push_front("table");
} else if (tag == "cell") {
@@ -3853,6 +3899,15 @@ void RichTextLabel::append_text(const String &p_bbcode) {
Color color2 = Color::from_string(subtag_b[1], fallback_color);
set_cell_row_background_color(color1, color2);
}
+ if (subtag_b.size() == 1) {
+ Color color1 = Color::from_string(subtag_a[1], fallback_color);
+ set_cell_row_background_color(color1, color1);
+ }
+ } else if (subtag_a[0] == "padding") {
+ Vector<String> subtag_b = subtag_a[1].split(",");
+ if (subtag_b.size() == 4) {
+ set_cell_padding(Rect2(subtag_b[0].to_float(), subtag_b[1].to_float(), subtag_b[2].to_float(), subtag_b[3].to_float()));
+ }
}
}
}
@@ -4057,7 +4112,7 @@ void RichTextLabel::append_text(const String &p_bbcode) {
Color color = theme_cache.default_color;
Color outline_color = theme_cache.font_outline_color;
int outline_size = theme_cache.outline_size;
- Rect2 dropcap_margins = Rect2();
+ Rect2 dropcap_margins;
for (int i = 0; i < subtag.size(); i++) {
Vector<String> subtag_a = subtag[i].split("=");
@@ -4515,6 +4570,30 @@ void RichTextLabel::append_text(const String &p_bbcode) {
}
}
+void RichTextLabel::scroll_to_selection() {
+ if (selection.active && selection.from_frame && selection.from_line >= 0 && selection.from_line < (int)selection.from_frame->lines.size()) {
+ // Selected frame paragraph offset.
+ float line_offset = selection.from_frame->lines[selection.from_line].offset.y;
+
+ // Add wrapped line offset.
+ for (int i = 0; i < selection.from_frame->lines[selection.from_line].text_buf->get_line_count(); i++) {
+ Vector2i range = selection.from_frame->lines[selection.from_line].text_buf->get_line_range(i);
+ if (range.x <= selection.from_char && range.y >= selection.from_char) {
+ break;
+ }
+ line_offset += selection.from_frame->lines[selection.from_line].text_buf->get_line_size(i).y + theme_cache.line_separation;
+ }
+
+ // Add nested frame (e.g. table cell) offset.
+ ItemFrame *it = selection.from_frame;
+ while (it->parent_frame != nullptr) {
+ line_offset += it->parent_frame->lines[it->line].offset.y;
+ it = it->parent_frame;
+ }
+ vscroll->set_value(line_offset);
+ }
+}
+
void RichTextLabel::scroll_to_paragraph(int p_paragraph) {
_validate_line_caches();
@@ -4759,7 +4838,7 @@ bool RichTextLabel::search(const String &p_string, bool p_from_selection, bool p
char_idx = p_search_previous ? selection.from_char - 1 : selection.to_char;
if (!(p_search_previous && char_idx < 0) &&
_search_line(selection.from_frame, selection.from_line, p_string, char_idx, p_search_previous)) {
- scroll_to_line(selection.from_frame->line + selection.from_line);
+ scroll_to_selection();
queue_redraw();
return true;
}
@@ -4784,7 +4863,7 @@ bool RichTextLabel::search(const String &p_string, bool p_from_selection, bool p
// Search for next element
if (_search_table(parent_table, parent_element, p_string, p_search_previous)) {
- scroll_to_line(selection.from_frame->line + selection.from_line);
+ scroll_to_selection();
queue_redraw();
return true;
}
@@ -4808,7 +4887,7 @@ bool RichTextLabel::search(const String &p_string, bool p_from_selection, bool p
}
if (_search_line(main, current_line, p_string, char_idx, p_search_previous)) {
- scroll_to_line(current_line);
+ scroll_to_selection();
queue_redraw();
return true;
}
@@ -5236,7 +5315,7 @@ void RichTextLabel::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_text", "text"), &RichTextLabel::set_text);
ClassDB::bind_method(D_METHOD("add_image", "image", "width", "height", "color", "inline_align", "region"), &RichTextLabel::add_image, DEFVAL(0), DEFVAL(0), DEFVAL(Color(1.0, 1.0, 1.0)), DEFVAL(INLINE_ALIGNMENT_CENTER), DEFVAL(Rect2(0, 0, 0, 0)));
ClassDB::bind_method(D_METHOD("newline"), &RichTextLabel::add_newline);
- ClassDB::bind_method(D_METHOD("remove_line", "line"), &RichTextLabel::remove_line);
+ ClassDB::bind_method(D_METHOD("remove_paragraph", "paragraph"), &RichTextLabel::remove_paragraph);
ClassDB::bind_method(D_METHOD("push_font", "font", "font_size"), &RichTextLabel::push_font);
ClassDB::bind_method(D_METHOD("push_font_size", "font_size"), &RichTextLabel::push_font_size);
ClassDB::bind_method(D_METHOD("push_normal"), &RichTextLabel::push_normal);
@@ -5254,7 +5333,7 @@ void RichTextLabel::_bind_methods() {
ClassDB::bind_method(D_METHOD("push_hint", "description"), &RichTextLabel::push_hint);
ClassDB::bind_method(D_METHOD("push_underline"), &RichTextLabel::push_underline);
ClassDB::bind_method(D_METHOD("push_strikethrough"), &RichTextLabel::push_strikethrough);
- ClassDB::bind_method(D_METHOD("push_table", "columns", "inline_align"), &RichTextLabel::push_table, DEFVAL(INLINE_ALIGNMENT_TOP));
+ ClassDB::bind_method(D_METHOD("push_table", "columns", "inline_align", "align_to_row"), &RichTextLabel::push_table, DEFVAL(INLINE_ALIGNMENT_TOP), DEFVAL(-1));
ClassDB::bind_method(D_METHOD("push_dropcap", "string", "font", "size", "dropcap_margins", "color", "outline_size", "outline_color"), &RichTextLabel::push_dropcap, DEFVAL(Rect2()), DEFVAL(Color(1, 1, 1)), DEFVAL(0), DEFVAL(Color(0, 0, 0, 0)));
ClassDB::bind_method(D_METHOD("set_table_column_expand", "column", "expand", "ratio"), &RichTextLabel::set_table_column_expand);
ClassDB::bind_method(D_METHOD("set_cell_row_background_color", "odd_row_bg", "even_row_bg"), &RichTextLabel::set_cell_row_background_color);
@@ -5296,6 +5375,7 @@ void RichTextLabel::_bind_methods() {
ClassDB::bind_method(D_METHOD("scroll_to_line", "line"), &RichTextLabel::scroll_to_line);
ClassDB::bind_method(D_METHOD("scroll_to_paragraph", "paragraph"), &RichTextLabel::scroll_to_paragraph);
+ ClassDB::bind_method(D_METHOD("scroll_to_selection"), &RichTextLabel::scroll_to_selection);
ClassDB::bind_method(D_METHOD("set_tab_size", "spaces"), &RichTextLabel::set_tab_size);
ClassDB::bind_method(D_METHOD("get_tab_size"), &RichTextLabel::get_tab_size);
@@ -5385,7 +5465,7 @@ void RichTextLabel::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "shortcut_keys_enabled"), "set_shortcut_keys_enabled", "is_shortcut_keys_enabled");
ADD_GROUP("Markup", "");
- ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "custom_effects", PROPERTY_HINT_ARRAY_TYPE, vformat("%s/%s:%s", Variant::OBJECT, PROPERTY_HINT_RESOURCE_TYPE, "RichTextEffect"), (PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_SCRIPT_VARIABLE)), "set_effects", "get_effects");
+ ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "custom_effects", PROPERTY_HINT_ARRAY_TYPE, MAKE_RESOURCE_TYPE_HINT("RichTextEffect"), (PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_SCRIPT_VARIABLE)), "set_effects", "get_effects");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "meta_underlined"), "set_meta_underline", "is_meta_underlined");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "hint_underlined"), "set_hint_underline", "is_hint_underlined");
@@ -5716,11 +5796,11 @@ Ref<RichTextEffect> RichTextLabel::_get_custom_effect_by_code(String p_bbcode_id
}
Dictionary RichTextLabel::parse_expressions_for_values(Vector<String> p_expressions) {
- Dictionary d = Dictionary();
+ Dictionary d;
for (int i = 0; i < p_expressions.size(); i++) {
String expression = p_expressions[i];
- Array a = Array();
+ Array a;
Vector<String> parts = expression.split("=", true);
String key = parts[0];
if (parts.size() != 2) {
diff --git a/scene/gui/rich_text_label.h b/scene/gui/rich_text_label.h
index d30baaa8d3..a4bc1c8e03 100644
--- a/scene/gui/rich_text_label.h
+++ b/scene/gui/rich_text_label.h
@@ -268,7 +268,9 @@ private:
LocalVector<Column> columns;
LocalVector<float> rows;
+ LocalVector<float> rows_baseline;
+ int align_to_row = -1;
int total_width = 0;
int total_height = 0;
InlineAlignment inline_align = INLINE_ALIGNMENT_TOP;
@@ -571,7 +573,7 @@ public:
void add_text(const String &p_text);
void add_image(const Ref<Texture2D> &p_image, const int p_width = 0, const int p_height = 0, const Color &p_color = Color(1.0, 1.0, 1.0), InlineAlignment p_alignment = INLINE_ALIGNMENT_CENTER, const Rect2 &p_region = Rect2(0, 0, 0, 0));
void add_newline();
- bool remove_line(const int p_line);
+ bool remove_paragraph(const int p_paragraph);
void push_dropcap(const String &p_string, const Ref<Font> &p_font, int p_size, const Rect2 &p_dropcap_margins = Rect2(), const Color &p_color = Color(1, 1, 1), int p_ol_size = 0, const Color &p_ol_color = Color(0, 0, 0, 0));
void _push_def_font(DefaultFont p_def_font);
void _push_def_font_var(DefaultFont p_def_font, const Ref<Font> &p_font, int p_size = -1);
@@ -592,7 +594,7 @@ public:
void push_list(int p_level, ListType p_list, bool p_capitalize);
void push_meta(const Variant &p_meta);
void push_hint(const String &p_string);
- void push_table(int p_columns, InlineAlignment p_alignment = INLINE_ALIGNMENT_TOP);
+ void push_table(int p_columns, InlineAlignment p_alignment = INLINE_ALIGNMENT_TOP, int p_align_to_row = -1);
void push_fade(int p_start_index, int p_length);
void push_shake(int p_strength, float p_rate, bool p_connected);
void push_wave(float p_frequency, float p_amplitude, bool p_connected);
@@ -657,6 +659,8 @@ public:
int get_content_height() const;
int get_content_width() const;
+ void scroll_to_selection();
+
VScrollBar *get_v_scroll_bar() { return vscroll; }
virtual CursorShape get_cursor_shape(const Point2 &p_pos) const override;
diff --git a/scene/gui/scroll_bar.cpp b/scene/gui/scroll_bar.cpp
index 6899178885..a44ddff507 100644
--- a/scene/gui/scroll_bar.cpp
+++ b/scene/gui/scroll_bar.cpp
@@ -550,7 +550,7 @@ void ScrollBar::_drag_node_input(const Ref<InputEvent> &p_input) {
drag_node_accum = Vector2();
last_drag_node_accum = Vector2();
drag_node_from = Vector2(orientation == HORIZONTAL ? get_value() : 0, orientation == VERTICAL ? get_value() : 0);
- drag_node_touching = DisplayServer::get_singleton()->screen_is_touchscreen(DisplayServer::get_singleton()->window_get_current_screen(get_viewport()->get_window_id()));
+ drag_node_touching = DisplayServer::get_singleton()->is_touchscreen_available();
drag_node_touching_deaccel = false;
time_since_motion = 0;
diff --git a/scene/gui/scroll_bar.h b/scene/gui/scroll_bar.h
index 13ca62d7ff..d62acd52af 100644
--- a/scene/gui/scroll_bar.h
+++ b/scene/gui/scroll_bar.h
@@ -72,7 +72,7 @@ class ScrollBar : public Range {
NodePath drag_node_path;
bool drag_node_enabled = true;
- Vector2 drag_node_speed = Vector2();
+ Vector2 drag_node_speed;
Vector2 drag_node_accum;
Vector2 drag_node_from;
Vector2 last_drag_node_accum;
diff --git a/scene/gui/scroll_container.cpp b/scene/gui/scroll_container.cpp
index 531226f938..73d30b7568 100644
--- a/scene/gui/scroll_container.cpp
+++ b/scene/gui/scroll_container.cpp
@@ -164,8 +164,8 @@ void ScrollContainer::gui_input(const Ref<InputEvent> &p_gui_input) {
}
}
- bool screen_is_touchscreen = DisplayServer::get_singleton()->screen_is_touchscreen(DisplayServer::get_singleton()->window_get_current_screen(get_viewport()->get_window_id()));
- if (!screen_is_touchscreen) {
+ bool is_touchscreen_available = DisplayServer::get_singleton()->is_touchscreen_available();
+ if (!is_touchscreen_available) {
return;
}
diff --git a/scene/gui/spin_box.cpp b/scene/gui/spin_box.cpp
index c4000120c8..e15b3b7bd4 100644
--- a/scene/gui/spin_box.cpp
+++ b/scene/gui/spin_box.cpp
@@ -40,7 +40,10 @@ Size2 SpinBox::get_minimum_size() const {
}
void SpinBox::_value_changed(double p_value) {
- String value = TS->format_number(String::num(get_value(), Math::range_step_decimals(get_step())));
+ String value = String::num(get_value(), Math::range_step_decimals(get_step()));
+ if (is_localizing_numeral_system()) {
+ value = TS->format_number(value);
+ }
if (!line_edit->has_focus()) {
if (!prefix.is_empty()) {
diff --git a/scene/gui/split_container.cpp b/scene/gui/split_container.cpp
index 2ca1d6239e..9830b41389 100644
--- a/scene/gui/split_container.cpp
+++ b/scene/gui/split_container.cpp
@@ -71,7 +71,7 @@ void SplitContainerDragger::gui_input(const Ref<InputEvent> &p_event) {
Vector2i in_parent_pos = get_transform().xform(mm->get_position());
if (!sc->vertical && is_layout_rtl()) {
- sc->split_offset = drag_ofs - ((sc->vertical ? in_parent_pos.y : in_parent_pos.x) - drag_from);
+ sc->split_offset = drag_ofs - (in_parent_pos.x - drag_from);
} else {
sc->split_offset = drag_ofs + ((sc->vertical ? in_parent_pos.y : in_parent_pos.x) - drag_from);
}
@@ -194,7 +194,6 @@ void SplitContainer::_compute_middle_sep(bool p_clamp) {
// Clamp the split_offset if requested.
if (p_clamp) {
split_offset -= wished_middle_sep - middle_sep;
- p_clamp = false;
}
}
diff --git a/scene/gui/subviewport_container.cpp b/scene/gui/subviewport_container.cpp
index 3ad84cbc6d..f3d9a22342 100644
--- a/scene/gui/subviewport_container.cpp
+++ b/scene/gui/subviewport_container.cpp
@@ -227,6 +227,18 @@ void SubViewportContainer::unhandled_input(const Ref<InputEvent> &p_event) {
}
}
+void SubViewportContainer::add_child_notify(Node *p_child) {
+ if (Object::cast_to<SubViewport>(p_child)) {
+ queue_redraw();
+ }
+}
+
+void SubViewportContainer::remove_child_notify(Node *p_child) {
+ if (Object::cast_to<SubViewport>(p_child)) {
+ queue_redraw();
+ }
+}
+
PackedStringArray SubViewportContainer::get_configuration_warnings() const {
PackedStringArray warnings = Node::get_configuration_warnings();
diff --git a/scene/gui/subviewport_container.h b/scene/gui/subviewport_container.h
index 63a58b5f07..fdd8fe9486 100644
--- a/scene/gui/subviewport_container.h
+++ b/scene/gui/subviewport_container.h
@@ -44,6 +44,9 @@ protected:
void _notification(int p_what);
static void _bind_methods();
+ virtual void add_child_notify(Node *p_child) override;
+ virtual void remove_child_notify(Node *p_child) override;
+
public:
void set_stretch(bool p_enable);
bool is_stretch_enabled() const;
diff --git a/scene/gui/tab_bar.cpp b/scene/gui/tab_bar.cpp
index cf6681f809..f87829cf71 100644
--- a/scene/gui/tab_bar.cpp
+++ b/scene/gui/tab_bar.cpp
@@ -385,9 +385,6 @@ void TabBar::_notification(int p_what) {
if (tabs[i].disabled) {
sb = theme_cache.tab_disabled_style;
col = theme_cache.font_disabled_color;
- } else if (i == current) {
- sb = theme_cache.tab_selected_style;
- col = theme_cache.font_selected_color;
} else {
sb = theme_cache.tab_unselected_style;
col = theme_cache.font_unselected_color;
diff --git a/scene/gui/text_edit.cpp b/scene/gui/text_edit.cpp
index 56f7281721..6d9e8a90c2 100644
--- a/scene/gui/text_edit.cpp
+++ b/scene/gui/text_edit.cpp
@@ -680,7 +680,7 @@ void TextEdit::_notification(int p_what) {
}
}
- bool draw_placeholder = text.size() == 1 && text[0].length() == 0;
+ bool draw_placeholder = text.size() == 1 && text[0].is_empty() && ime_text.is_empty();
// Get the highlighted words.
String highlighted_text = get_selected_text(0);
@@ -1108,8 +1108,9 @@ void TextEdit::_notification(int p_what) {
int start = TS->shaped_text_get_range(rid).x;
if (!clipped && !search_text.is_empty()) { // Search highhlight
int search_text_col = _get_column_pos_of_word(search_text, str, search_flags, 0);
+ int search_text_len = search_text.length();
while (search_text_col != -1) {
- Vector<Vector2> sel = TS->shaped_text_get_selection(rid, search_text_col + start, search_text_col + search_text.length() + start);
+ Vector<Vector2> sel = TS->shaped_text_get_selection(rid, search_text_col + start, search_text_col + search_text_len + start);
for (int j = 0; j < sel.size(); j++) {
Rect2 rect = Rect2(sel[j].x + char_margin + ofs_x, ofs_y, sel[j].y - sel[j].x, row_height);
if (rect.position.x + rect.size.x <= xmargin_beg || rect.position.x > xmargin_end) {
@@ -1125,14 +1126,15 @@ void TextEdit::_notification(int p_what) {
draw_rect(rect, search_result_border_color, false);
}
- search_text_col = _get_column_pos_of_word(search_text, str, search_flags, search_text_col + 1);
+ search_text_col = _get_column_pos_of_word(search_text, str, search_flags, search_text_col + search_text_len);
}
}
if (!clipped && highlight_all_occurrences && !only_whitespaces_highlighted && !highlighted_text.is_empty()) { // Highlight
int highlighted_text_col = _get_column_pos_of_word(highlighted_text, str, SEARCH_MATCH_CASE | SEARCH_WHOLE_WORDS, 0);
+ int highlighted_text_len = highlighted_text.length();
while (highlighted_text_col != -1) {
- Vector<Vector2> sel = TS->shaped_text_get_selection(rid, highlighted_text_col + start, highlighted_text_col + highlighted_text.length() + start);
+ Vector<Vector2> sel = TS->shaped_text_get_selection(rid, highlighted_text_col + start, highlighted_text_col + highlighted_text_len + start);
for (int j = 0; j < sel.size(); j++) {
Rect2 rect = Rect2(sel[j].x + char_margin + ofs_x, ofs_y, sel[j].y - sel[j].x, row_height);
if (rect.position.x + rect.size.x <= xmargin_beg || rect.position.x > xmargin_end) {
@@ -1147,15 +1149,16 @@ void TextEdit::_notification(int p_what) {
draw_rect(rect, word_highlighted_color);
}
- highlighted_text_col = _get_column_pos_of_word(highlighted_text, str, SEARCH_MATCH_CASE | SEARCH_WHOLE_WORDS, highlighted_text_col + 1);
+ highlighted_text_col = _get_column_pos_of_word(highlighted_text, str, SEARCH_MATCH_CASE | SEARCH_WHOLE_WORDS, highlighted_text_col + highlighted_text_len);
}
}
if (!clipped && lookup_symbol_word.length() != 0) { // Highlight word
if (is_ascii_char(lookup_symbol_word[0]) || lookup_symbol_word[0] == '_' || lookup_symbol_word[0] == '.') {
- int highlighted_word_col = _get_column_pos_of_word(lookup_symbol_word, str, SEARCH_MATCH_CASE | SEARCH_WHOLE_WORDS, 0);
- while (highlighted_word_col != -1) {
- Vector<Vector2> sel = TS->shaped_text_get_selection(rid, highlighted_word_col + start, highlighted_word_col + lookup_symbol_word.length() + start);
+ int lookup_symbol_word_col = _get_column_pos_of_word(lookup_symbol_word, str, SEARCH_MATCH_CASE | SEARCH_WHOLE_WORDS, 0);
+ int lookup_symbol_word_len = lookup_symbol_word.length();
+ while (lookup_symbol_word_col != -1) {
+ Vector<Vector2> sel = TS->shaped_text_get_selection(rid, lookup_symbol_word_col + start, lookup_symbol_word_col + lookup_symbol_word_len + start);
for (int j = 0; j < sel.size(); j++) {
Rect2 rect = Rect2(sel[j].x + char_margin + ofs_x, ofs_y + (line_spacing / 2), sel[j].y - sel[j].x, row_height);
if (rect.position.x + rect.size.x <= xmargin_beg || rect.position.x > xmargin_end) {
@@ -1172,7 +1175,7 @@ void TextEdit::_notification(int p_what) {
draw_rect(rect, color);
}
- highlighted_word_col = _get_column_pos_of_word(lookup_symbol_word, str, SEARCH_MATCH_CASE | SEARCH_WHOLE_WORDS, highlighted_word_col + 1);
+ lookup_symbol_word_col = _get_column_pos_of_word(lookup_symbol_word, str, SEARCH_MATCH_CASE | SEARCH_WHOLE_WORDS, lookup_symbol_word_col + lookup_symbol_word_len);
}
}
}
@@ -4234,7 +4237,7 @@ Point2i TextEdit::get_line_column_at_pos(const Point2i &p_pos, bool p_allow_out_
if (!p_allow_out_of_bounds) {
return Point2i(-1, -1);
}
- return Point2i(text[row].size(), row);
+ return Point2i(text[row].length(), row);
}
int col = 0;
@@ -7038,8 +7041,8 @@ void TextEdit::_update_selection_mode_word() {
if ((col <= carets[caret_idx].selection.selected_word_origin && line == get_selection_line(caret_idx)) || line < get_selection_line(caret_idx)) {
carets.write[caret_idx].selection.selecting_column = carets[caret_idx].selection.selected_word_end;
select(line, beg, get_selection_line(caret_idx), carets[caret_idx].selection.selected_word_end, caret_idx);
- set_caret_line(get_selection_from_line(caret_idx), false, true, 0, caret_idx);
- set_caret_column(get_selection_from_column(caret_idx), true, caret_idx);
+ set_caret_line(line, false, true, 0, caret_idx);
+ set_caret_column(beg, true, caret_idx);
} else {
carets.write[caret_idx].selection.selecting_column = carets[caret_idx].selection.selected_word_beg;
select(get_selection_line(caret_idx), carets[caret_idx].selection.selected_word_beg, line, end, caret_idx);
diff --git a/scene/gui/texture_button.cpp b/scene/gui/texture_button.cpp
index d9ab1c2c55..ccdf56c1d7 100644
--- a/scene/gui/texture_button.cpp
+++ b/scene/gui/texture_button.cpp
@@ -64,7 +64,7 @@ Size2 TextureButton::get_minimum_size() const {
bool TextureButton::has_point(const Point2 &p_point) const {
if (click_mask.is_valid()) {
Point2 point = p_point;
- Rect2 rect = Rect2();
+ Rect2 rect;
Size2 mask_size = click_mask->get_size();
if (!_position_rect.has_area()) {
@@ -250,11 +250,11 @@ void TextureButton::_notification(int p_what) {
}
void TextureButton::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_normal_texture", "texture"), &TextureButton::set_normal_texture);
- ClassDB::bind_method(D_METHOD("set_pressed_texture", "texture"), &TextureButton::set_pressed_texture);
- ClassDB::bind_method(D_METHOD("set_hover_texture", "texture"), &TextureButton::set_hover_texture);
- ClassDB::bind_method(D_METHOD("set_disabled_texture", "texture"), &TextureButton::set_disabled_texture);
- ClassDB::bind_method(D_METHOD("set_focused_texture", "texture"), &TextureButton::set_focused_texture);
+ ClassDB::bind_method(D_METHOD("set_texture_normal", "texture"), &TextureButton::set_texture_normal);
+ ClassDB::bind_method(D_METHOD("set_texture_pressed", "texture"), &TextureButton::set_texture_pressed);
+ ClassDB::bind_method(D_METHOD("set_texture_hover", "texture"), &TextureButton::set_texture_hover);
+ ClassDB::bind_method(D_METHOD("set_texture_disabled", "texture"), &TextureButton::set_texture_disabled);
+ ClassDB::bind_method(D_METHOD("set_texture_focused", "texture"), &TextureButton::set_texture_focused);
ClassDB::bind_method(D_METHOD("set_click_mask", "mask"), &TextureButton::set_click_mask);
ClassDB::bind_method(D_METHOD("set_ignore_texture_size", "ignore"), &TextureButton::set_ignore_texture_size);
ClassDB::bind_method(D_METHOD("set_stretch_mode", "mode"), &TextureButton::set_stretch_mode);
@@ -263,21 +263,21 @@ void TextureButton::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_flip_v", "enable"), &TextureButton::set_flip_v);
ClassDB::bind_method(D_METHOD("is_flipped_v"), &TextureButton::is_flipped_v);
- ClassDB::bind_method(D_METHOD("get_normal_texture"), &TextureButton::get_normal_texture);
- ClassDB::bind_method(D_METHOD("get_pressed_texture"), &TextureButton::get_pressed_texture);
- ClassDB::bind_method(D_METHOD("get_hover_texture"), &TextureButton::get_hover_texture);
- ClassDB::bind_method(D_METHOD("get_disabled_texture"), &TextureButton::get_disabled_texture);
- ClassDB::bind_method(D_METHOD("get_focused_texture"), &TextureButton::get_focused_texture);
+ ClassDB::bind_method(D_METHOD("get_texture_normal"), &TextureButton::get_texture_normal);
+ ClassDB::bind_method(D_METHOD("get_texture_pressed"), &TextureButton::get_texture_pressed);
+ ClassDB::bind_method(D_METHOD("get_texture_hover"), &TextureButton::get_texture_hover);
+ ClassDB::bind_method(D_METHOD("get_texture_disabled"), &TextureButton::get_texture_disabled);
+ ClassDB::bind_method(D_METHOD("get_texture_focused"), &TextureButton::get_texture_focused);
ClassDB::bind_method(D_METHOD("get_click_mask"), &TextureButton::get_click_mask);
ClassDB::bind_method(D_METHOD("get_ignore_texture_size"), &TextureButton::get_ignore_texture_size);
ClassDB::bind_method(D_METHOD("get_stretch_mode"), &TextureButton::get_stretch_mode);
ADD_GROUP("Textures", "texture_");
- ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture_normal", PROPERTY_HINT_RESOURCE_TYPE, "Texture2D"), "set_normal_texture", "get_normal_texture");
- ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture_pressed", PROPERTY_HINT_RESOURCE_TYPE, "Texture2D"), "set_pressed_texture", "get_pressed_texture");
- ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture_hover", PROPERTY_HINT_RESOURCE_TYPE, "Texture2D"), "set_hover_texture", "get_hover_texture");
- ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture_disabled", PROPERTY_HINT_RESOURCE_TYPE, "Texture2D"), "set_disabled_texture", "get_disabled_texture");
- ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture_focused", PROPERTY_HINT_RESOURCE_TYPE, "Texture2D"), "set_focused_texture", "get_focused_texture");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture_normal", PROPERTY_HINT_RESOURCE_TYPE, "Texture2D"), "set_texture_normal", "get_texture_normal");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture_pressed", PROPERTY_HINT_RESOURCE_TYPE, "Texture2D"), "set_texture_pressed", "get_texture_pressed");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture_hover", PROPERTY_HINT_RESOURCE_TYPE, "Texture2D"), "set_texture_hover", "get_texture_hover");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture_disabled", PROPERTY_HINT_RESOURCE_TYPE, "Texture2D"), "set_texture_disabled", "get_texture_disabled");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture_focused", PROPERTY_HINT_RESOURCE_TYPE, "Texture2D"), "set_texture_focused", "get_texture_focused");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture_click_mask", PROPERTY_HINT_RESOURCE_TYPE, "BitMap"), "set_click_mask", "get_click_mask");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "ignore_texture_size", PROPERTY_HINT_RESOURCE_TYPE, "bool"), "set_ignore_texture_size", "get_ignore_texture_size");
ADD_PROPERTY(PropertyInfo(Variant::INT, "stretch_mode", PROPERTY_HINT_ENUM, "Scale,Tile,Keep,Keep Centered,Keep Aspect,Keep Aspect Centered,Keep Aspect Covered"), "set_stretch_mode", "get_stretch_mode");
@@ -293,7 +293,7 @@ void TextureButton::_bind_methods() {
BIND_ENUM_CONSTANT(STRETCH_KEEP_ASPECT_COVERED);
}
-void TextureButton::set_normal_texture(const Ref<Texture2D> &p_normal) {
+void TextureButton::set_texture_normal(const Ref<Texture2D> &p_normal) {
if (normal == p_normal) {
return;
}
@@ -303,7 +303,7 @@ void TextureButton::set_normal_texture(const Ref<Texture2D> &p_normal) {
update_minimum_size();
}
-void TextureButton::set_pressed_texture(const Ref<Texture2D> &p_pressed) {
+void TextureButton::set_texture_pressed(const Ref<Texture2D> &p_pressed) {
if (pressed == p_pressed) {
return;
}
@@ -313,7 +313,7 @@ void TextureButton::set_pressed_texture(const Ref<Texture2D> &p_pressed) {
update_minimum_size();
}
-void TextureButton::set_hover_texture(const Ref<Texture2D> &p_hover) {
+void TextureButton::set_texture_hover(const Ref<Texture2D> &p_hover) {
if (hover == p_hover) {
return;
}
@@ -323,7 +323,7 @@ void TextureButton::set_hover_texture(const Ref<Texture2D> &p_hover) {
update_minimum_size();
}
-void TextureButton::set_disabled_texture(const Ref<Texture2D> &p_disabled) {
+void TextureButton::set_texture_disabled(const Ref<Texture2D> &p_disabled) {
if (disabled == p_disabled) {
return;
}
@@ -341,19 +341,19 @@ void TextureButton::set_click_mask(const Ref<BitMap> &p_click_mask) {
update_minimum_size();
}
-Ref<Texture2D> TextureButton::get_normal_texture() const {
+Ref<Texture2D> TextureButton::get_texture_normal() const {
return normal;
}
-Ref<Texture2D> TextureButton::get_pressed_texture() const {
+Ref<Texture2D> TextureButton::get_texture_pressed() const {
return pressed;
}
-Ref<Texture2D> TextureButton::get_hover_texture() const {
+Ref<Texture2D> TextureButton::get_texture_hover() const {
return hover;
}
-Ref<Texture2D> TextureButton::get_disabled_texture() const {
+Ref<Texture2D> TextureButton::get_texture_disabled() const {
return disabled;
}
@@ -361,11 +361,11 @@ Ref<BitMap> TextureButton::get_click_mask() const {
return click_mask;
}
-Ref<Texture2D> TextureButton::get_focused_texture() const {
+Ref<Texture2D> TextureButton::get_texture_focused() const {
return focused;
};
-void TextureButton::set_focused_texture(const Ref<Texture2D> &p_focused) {
+void TextureButton::set_texture_focused(const Ref<Texture2D> &p_focused) {
focused = p_focused;
};
diff --git a/scene/gui/texture_button.h b/scene/gui/texture_button.h
index 9f6f7c1515..4b6d5b5bec 100644
--- a/scene/gui/texture_button.h
+++ b/scene/gui/texture_button.h
@@ -71,18 +71,18 @@ protected:
static void _bind_methods();
public:
- void set_normal_texture(const Ref<Texture2D> &p_normal);
- void set_pressed_texture(const Ref<Texture2D> &p_pressed);
- void set_hover_texture(const Ref<Texture2D> &p_hover);
- void set_disabled_texture(const Ref<Texture2D> &p_disabled);
- void set_focused_texture(const Ref<Texture2D> &p_focused);
+ void set_texture_normal(const Ref<Texture2D> &p_normal);
+ void set_texture_pressed(const Ref<Texture2D> &p_pressed);
+ void set_texture_hover(const Ref<Texture2D> &p_hover);
+ void set_texture_disabled(const Ref<Texture2D> &p_disabled);
+ void set_texture_focused(const Ref<Texture2D> &p_focused);
void set_click_mask(const Ref<BitMap> &p_click_mask);
- Ref<Texture2D> get_normal_texture() const;
- Ref<Texture2D> get_pressed_texture() const;
- Ref<Texture2D> get_hover_texture() const;
- Ref<Texture2D> get_disabled_texture() const;
- Ref<Texture2D> get_focused_texture() const;
+ Ref<Texture2D> get_texture_normal() const;
+ Ref<Texture2D> get_texture_pressed() const;
+ Ref<Texture2D> get_texture_hover() const;
+ Ref<Texture2D> get_texture_disabled() const;
+ Ref<Texture2D> get_texture_focused() const;
Ref<BitMap> get_click_mask() const;
bool get_ignore_texture_size() const;
diff --git a/scene/gui/tree.cpp b/scene/gui/tree.cpp
index 1c96858da7..79bad44e15 100644
--- a/scene/gui/tree.cpp
+++ b/scene/gui/tree.cpp
@@ -1018,7 +1018,7 @@ void TreeItem::set_as_cursor(int p_column) {
if (tree->select_mode != Tree::SELECT_MULTI) {
return;
}
- if (tree->selected_col == p_column) {
+ if (tree->selected_item == this && tree->selected_col == p_column) {
return;
}
tree->selected_item = this;
@@ -1337,14 +1337,14 @@ Size2 TreeItem::get_minimum_size(int p_column) {
// Icon.
if (cell.mode == CELL_MODE_CHECK) {
- size.width += parent_tree->theme_cache.checked->get_width() + parent_tree->theme_cache.hseparation;
+ size.width += parent_tree->theme_cache.checked->get_width() + parent_tree->theme_cache.h_separation;
}
if (cell.icon.is_valid()) {
Size2i icon_size = cell.get_icon_size();
if (cell.icon_max_w > 0 && icon_size.width > cell.icon_max_w) {
icon_size.width = cell.icon_max_w;
}
- size.width += icon_size.width + parent_tree->theme_cache.hseparation;
+ size.width += icon_size.width + parent_tree->theme_cache.h_separation;
size.height = MAX(size.height, icon_size.height);
}
@@ -1624,8 +1624,8 @@ void Tree::_update_theme_item_cache() {
theme_cache.font_color = get_theme_color(SNAME("font_color"));
theme_cache.font_selected_color = get_theme_color(SNAME("font_selected_color"));
theme_cache.drop_position_color = get_theme_color(SNAME("drop_position_color"));
- theme_cache.hseparation = get_theme_constant(SNAME("h_separation"));
- theme_cache.vseparation = get_theme_constant(SNAME("v_separation"));
+ theme_cache.h_separation = get_theme_constant(SNAME("h_separation"));
+ theme_cache.v_separation = get_theme_constant(SNAME("v_separation"));
theme_cache.item_margin = get_theme_constant(SNAME("item_margin"));
theme_cache.button_margin = get_theme_constant(SNAME("button_margin"));
@@ -1710,7 +1710,7 @@ int Tree::compute_item_height(TreeItem *p_item) const {
height = item_min_height;
}
- height += theme_cache.vseparation;
+ height += theme_cache.v_separation;
return height;
}
@@ -1720,7 +1720,7 @@ int Tree::get_item_height(TreeItem *p_item) const {
return 0;
}
int height = compute_item_height(p_item);
- height += theme_cache.vseparation;
+ height += theme_cache.v_separation;
if (!p_item->collapsed) { /* if not collapsed, check the children */
@@ -1749,7 +1749,7 @@ void Tree::draw_item_rect(TreeItem::Cell &p_cell, const Rect2i &p_rect, const Co
if (p_cell.icon_max_w > 0 && bmsize.width > p_cell.icon_max_w) {
bmsize.width = p_cell.icon_max_w;
}
- w += bmsize.width + theme_cache.hseparation;
+ w += bmsize.width + theme_cache.h_separation;
if (rect.size.width > 0 && (w + ts.width) > rect.size.width) {
ts.width = rect.size.width - w;
}
@@ -1783,8 +1783,8 @@ void Tree::draw_item_rect(TreeItem::Cell &p_cell, const Rect2i &p_rect, const Co
p_cell.text_buf->draw_outline(ci, draw_pos, p_ol_size, p_ol_color);
}
p_cell.text_buf->draw(ci, draw_pos, p_color);
- rect.position.x += ts.width + theme_cache.hseparation;
- rect.size.x -= ts.width + theme_cache.hseparation;
+ rect.position.x += ts.width + theme_cache.h_separation;
+ rect.size.x -= ts.width + theme_cache.h_separation;
}
if (!p_cell.icon.is_null()) {
@@ -1796,8 +1796,8 @@ void Tree::draw_item_rect(TreeItem::Cell &p_cell, const Rect2i &p_rect, const Co
}
p_cell.draw_icon(ci, rect.position + Size2i(0, Math::floor((real_t)(rect.size.y - bmsize.y) / 2)), bmsize, p_icon_color);
- rect.position.x += bmsize.x + theme_cache.hseparation;
- rect.size.x -= bmsize.x + theme_cache.hseparation;
+ rect.position.x += bmsize.x + theme_cache.h_separation;
+ rect.size.x -= bmsize.x + theme_cache.h_separation;
}
if (!rtl) {
@@ -1911,7 +1911,7 @@ int Tree::draw_item(const Point2i &p_pos, const Point2 &p_draw_ofs, const Size2
bool rtl = cache.rtl;
/* Calculate height of the label part */
- label_h += theme_cache.vseparation;
+ label_h += theme_cache.v_separation;
/* Draw label, if height fits */
@@ -1922,7 +1922,7 @@ int Tree::draw_item(const Point2i &p_pos, const Point2 &p_draw_ofs, const Size2
ERR_FAIL_COND_V(theme_cache.font.is_null(), -1);
- int ofs = p_pos.x + ((p_item->disable_folding || hide_folding) ? theme_cache.hseparation : theme_cache.item_margin);
+ int ofs = p_pos.x + ((p_item->disable_folding || hide_folding) ? theme_cache.h_separation : theme_cache.item_margin);
int skip2 = 0;
for (int i = 0; i < columns.size(); i++) {
if (skip2) {
@@ -1940,8 +1940,8 @@ int Tree::draw_item(const Point2i &p_pos, const Point2 &p_draw_ofs, const Size2
continue;
}
} else {
- ofs += theme_cache.hseparation;
- w -= theme_cache.hseparation;
+ ofs += theme_cache.h_separation;
+ w -= theme_cache.h_separation;
}
if (p_item->cells[i].expand_right) {
@@ -1998,8 +1998,8 @@ int Tree::draw_item(const Point2i &p_pos, const Point2 &p_draw_ofs, const Size2
Rect2i item_rect = Rect2i(Point2i(ofs, p_pos.y) - theme_cache.offset + p_draw_ofs, Size2i(w, label_h));
Rect2i cell_rect = item_rect;
if (i != 0) {
- cell_rect.position.x -= theme_cache.hseparation;
- cell_rect.size.x += theme_cache.hseparation;
+ cell_rect.position.x -= theme_cache.h_separation;
+ cell_rect.size.x += theme_cache.h_separation;
}
if (theme_cache.draw_guides) {
@@ -2051,8 +2051,8 @@ int Tree::draw_item(const Point2i &p_pos, const Point2 &p_draw_ofs, const Size2
r.position.x = p_draw_ofs.x;
r.size.x = w + ofs;
} else {
- r.position.x -= theme_cache.hseparation;
- r.size.x += theme_cache.hseparation;
+ r.position.x -= theme_cache.h_separation;
+ r.size.x += theme_cache.h_separation;
}
if (rtl) {
r.position.x = get_size().width - r.position.x - r.size.x;
@@ -2136,7 +2136,7 @@ int Tree::draw_item(const Point2i &p_pos, const Point2 &p_draw_ofs, const Size2
unchecked->draw(ci, check_ofs);
}
- int check_w = checked->get_width() + theme_cache.hseparation;
+ int check_w = checked->get_width() + theme_cache.h_separation;
text_pos.x += check_w;
@@ -2328,7 +2328,7 @@ int Tree::draw_item(const Point2i &p_pos, const Point2 &p_draw_ofs, const Size2
// Draw relationship lines.
if (theme_cache.draw_relationship_lines > 0 && (!hide_root || c->parent != root) && c->is_visible()) {
- int root_ofs = children_pos.x + ((p_item->disable_folding || hide_folding) ? theme_cache.hseparation : theme_cache.item_margin);
+ int root_ofs = children_pos.x + ((p_item->disable_folding || hide_folding) ? theme_cache.h_separation : theme_cache.item_margin);
int parent_ofs = p_pos.x + theme_cache.item_margin;
Point2i root_pos = Point2i(root_ofs, children_pos.y + label_h / 2) - theme_cache.offset + p_draw_ofs;
@@ -2471,6 +2471,8 @@ bool Tree::_is_sibling_branch_selected(TreeItem *p_from) const {
}
void Tree::select_single_item(TreeItem *p_selected, TreeItem *p_current, int p_col, TreeItem *p_prev, bool *r_in_range, bool p_force_deselect) {
+ popup_editor->hide();
+
TreeItem::Cell &selected_cell = p_selected->cells.write[p_col];
bool switched = false;
@@ -2615,7 +2617,7 @@ int Tree::propagate_mouse_event(const Point2i &p_pos, int x_ofs, int y_ofs, int
return 0;
}
- int item_h = compute_item_height(p_item) + theme_cache.vseparation;
+ int item_h = compute_item_height(p_item) + theme_cache.v_separation;
bool skip = (p_item == root && hide_root);
@@ -2649,7 +2651,7 @@ int Tree::propagate_mouse_event(const Point2i &p_pos, int x_ofs, int y_ofs, int
if (p_item->cells[i].expand_right) {
int plus = 1;
while (i + plus < columns.size() && !p_item->cells[i + plus].editable && p_item->cells[i + plus].mode == TreeItem::CELL_MODE_STRING && p_item->cells[i + plus].text.is_empty() && p_item->cells[i + plus].icon.is_null()) {
- col_width += theme_cache.hseparation;
+ col_width += theme_cache.h_separation;
col_width += get_column_width(i + plus);
plus++;
}
@@ -2669,16 +2671,16 @@ int Tree::propagate_mouse_event(const Point2i &p_pos, int x_ofs, int y_ofs, int
if (col == -1) {
return -1;
} else if (col == 0) {
- int margin = x_ofs + theme_cache.item_margin; //-theme_cache.hseparation;
+ int margin = x_ofs + theme_cache.item_margin; //-theme_cache.h_separation;
//int lm = theme_cache.panel_style->get_margin(SIDE_LEFT);
col_width -= margin;
limit_w -= margin;
col_ofs += margin;
x -= margin;
} else {
- col_width -= theme_cache.hseparation;
- limit_w -= theme_cache.hseparation;
- x -= theme_cache.hseparation;
+ col_width -= theme_cache.h_separation;
+ limit_w -= theme_cache.h_separation;
+ x -= theme_cache.h_separation;
}
if (!p_item->disable_folding && !hide_folding && !p_item->cells[col].editable && !p_item->cells[col].selectable && p_item->get_first_child()) {
@@ -3671,7 +3673,7 @@ void Tree::gui_input(const Ref<InputEvent> &p_event) {
drag_accum = 0;
//last_drag_accum=0;
drag_from = v_scroll->get_value();
- drag_touching = DisplayServer::get_singleton()->screen_is_touchscreen(DisplayServer::get_singleton()->window_get_current_screen(get_viewport()->get_window_id()));
+ drag_touching = DisplayServer::get_singleton()->is_touchscreen_available();
drag_touching_deaccel = false;
if (drag_touching) {
set_physics_process_internal(true);
@@ -3783,7 +3785,9 @@ bool Tree::edit_selected() {
} else if (c.mode == TreeItem::CELL_MODE_STRING || c.mode == TreeItem::CELL_MODE_RANGE) {
Rect2 popup_rect;
- Vector2 ofs(0, Math::floor((text_editor->get_size().height - rect.size.height) / 2)); // "floor()" centers vertically.
+ int value_editor_height = c.mode == TreeItem::CELL_MODE_RANGE ? value_editor->get_minimum_size().height : 0;
+ // "floor()" centers vertically.
+ Vector2 ofs(0, Math::floor((MAX(text_editor->get_minimum_size().height, rect.size.height - value_editor_height) - rect.size.height) / 2));
Point2i textedpos = get_screen_position() + rect.position - ofs;
cache.text_editor_position = textedpos;
@@ -3799,7 +3803,7 @@ bool Tree::edit_selected() {
text_editor->select_all();
if (c.mode == TreeItem::CELL_MODE_RANGE) {
- popup_rect.size.y += value_editor->get_minimum_size().height;
+ popup_rect.size.y += value_editor_height;
value_editor->show();
updating_value_editor = true;
@@ -4216,7 +4220,9 @@ Tree::SelectMode Tree::get_select_mode() const {
void Tree::deselect_all() {
TreeItem *item = get_next_selected(get_root());
while (item) {
- item->deselect(selected_col);
+ for (int i = 0; i < columns.size(); i++) {
+ item->deselect(i);
+ }
TreeItem *prev_item = item;
item = get_next_selected(get_root());
ERR_FAIL_COND(item == prev_item);
@@ -4338,6 +4344,12 @@ TreeItem *Tree::get_selected() const {
return selected_item;
}
+void Tree::set_selected(TreeItem *p_item, int p_column) {
+ ERR_FAIL_INDEX(p_column, columns.size());
+ ERR_FAIL_COND(!p_item);
+ select_single_item(p_item, get_root(), p_column);
+}
+
int Tree::get_selected_column() const {
return selected_col;
}
@@ -4420,7 +4432,7 @@ int Tree::get_column_minimum_width(int p_column) const {
if (p_column == 0) {
item_size.width += theme_cache.item_margin * depth;
} else {
- item_size.width += theme_cache.hseparation;
+ item_size.width += theme_cache.h_separation;
}
// Check if the item is wider.
@@ -4516,7 +4528,7 @@ int Tree::get_item_offset(TreeItem *p_item) const {
ofs += compute_item_height(it);
if (it != root || !hide_root) {
- ofs += theme_cache.vseparation;
+ ofs += theme_cache.v_separation;
}
if (it->first_child && !it->collapsed) {
@@ -4547,6 +4559,7 @@ void Tree::ensure_cursor_is_visible() {
return; // Nothing under cursor.
}
+ // Note: Code below similar to Tree::scroll_to_item(), in case of bug fix both.
const Size2 area_size = get_size() - theme_cache.panel_style->get_minimum_size();
int y_offset = get_item_offset(selected_item);
@@ -4554,8 +4567,11 @@ void Tree::ensure_cursor_is_visible() {
const int tbh = _get_title_button_height();
y_offset -= tbh;
- const int cell_h = compute_item_height(selected_item) + theme_cache.vseparation;
- const int screen_h = area_size.height - h_scroll->get_combined_minimum_size().height - tbh;
+ const int cell_h = compute_item_height(selected_item) + theme_cache.v_separation;
+ int screen_h = area_size.height - tbh;
+ if (h_scroll->is_visible()) {
+ screen_h -= h_scroll->get_combined_minimum_size().height;
+ }
if (cell_h > screen_h) { // Screen size is too small, maybe it was not resized yet.
v_scroll->set_value(y_offset);
@@ -4706,26 +4722,32 @@ Point2 Tree::get_scroll() const {
void Tree::scroll_to_item(TreeItem *p_item, bool p_center_on_item) {
ERR_FAIL_NULL(p_item);
- if (!is_visible_in_tree() || !p_item->is_visible()) {
- return; // Hack to work around crash in get_item_rect() if Tree is not in tree.
- }
update_scrollbars();
- const real_t tree_height = get_size().y;
- const Rect2 item_rect = get_item_rect(p_item);
- const real_t item_y = item_rect.position.y;
- const real_t item_height = item_rect.size.y + theme_cache.vseparation;
+ // Note: Code below similar to Tree::ensure_cursor_is_visible(), in case of bug fix both.
+ const Size2 area_size = get_size() - theme_cache.panel_style->get_minimum_size();
- if (p_center_on_item) {
- v_scroll->set_value(item_y - (tree_height - item_height) / 2.0f);
- } else {
- if (item_y < v_scroll->get_value()) {
- v_scroll->set_value(item_y);
+ int y_offset = get_item_offset(p_item);
+ if (y_offset != -1) {
+ const int tbh = _get_title_button_height();
+ y_offset -= tbh;
+
+ const int cell_h = compute_item_height(p_item) + theme_cache.v_separation;
+ int screen_h = area_size.height - tbh;
+ if (h_scroll->is_visible()) {
+ screen_h -= h_scroll->get_combined_minimum_size().height;
+ }
+
+ if (p_center_on_item) {
+ v_scroll->set_value(y_offset - (screen_h - cell_h) / 2.0f);
} else {
- const real_t new_position = item_y + item_height - tree_height;
- if (new_position > v_scroll->get_value()) {
- v_scroll->set_value(new_position);
+ if (cell_h > screen_h) { // Screen size is too small, maybe it was not resized yet.
+ v_scroll->set_value(y_offset);
+ } else if (y_offset + cell_h > v_scroll->get_value() + screen_h) {
+ v_scroll->set_value(y_offset - screen_h + cell_h);
+ } else if (y_offset < v_scroll->get_value()) {
+ v_scroll->set_value(y_offset);
}
}
}
@@ -4839,7 +4861,7 @@ TreeItem *Tree::_find_item_at_pos(TreeItem *p_item, const Point2 &p_pos, int &r_
Point2 pos = p_pos;
if ((root != p_item || !hide_root) && p_item->is_visible()) {
- h = compute_item_height(p_item) + theme_cache.vseparation;
+ h = compute_item_height(p_item) + theme_cache.v_separation;
if (pos.y < h) {
if (drop_mode_flags == DROP_MODE_ON_ITEM) {
section = 0;
@@ -5156,6 +5178,7 @@ void Tree::_bind_methods() {
ClassDB::bind_method(D_METHOD("is_root_hidden"), &Tree::is_root_hidden);
ClassDB::bind_method(D_METHOD("get_next_selected", "from"), &Tree::get_next_selected);
ClassDB::bind_method(D_METHOD("get_selected"), &Tree::get_selected);
+ ClassDB::bind_method(D_METHOD("set_selected", "item", "column"), &Tree::set_selected);
ClassDB::bind_method(D_METHOD("get_selected_column"), &Tree::get_selected_column);
ClassDB::bind_method(D_METHOD("get_pressed_button"), &Tree::get_pressed_button);
ClassDB::bind_method(D_METHOD("set_select_mode", "mode"), &Tree::set_select_mode);
@@ -5260,7 +5283,6 @@ Tree::Tree() {
add_child(popup_menu, false, INTERNAL_MODE_FRONT);
popup_editor = memnew(Popup);
- popup_editor->set_wrap_controls(true);
add_child(popup_editor, false, INTERNAL_MODE_FRONT);
popup_editor_vb = memnew(VBoxContainer);
popup_editor->add_child(popup_editor_vb);
@@ -5269,11 +5291,9 @@ Tree::Tree() {
text_editor = memnew(LineEdit);
popup_editor_vb->add_child(text_editor);
text_editor->set_v_size_flags(SIZE_EXPAND_FILL);
- text_editor->set_h_size_flags(SIZE_EXPAND_FILL);
value_editor = memnew(HSlider);
- value_editor->set_v_size_flags(SIZE_EXPAND_FILL);
- value_editor->set_h_size_flags(SIZE_EXPAND_FILL);
popup_editor_vb->add_child(value_editor);
+ value_editor->set_v_size_flags(SIZE_EXPAND_FILL);
value_editor->hide();
h_scroll = memnew(HScrollBar);
diff --git a/scene/gui/tree.h b/scene/gui/tree.h
index f994a5cec1..cdd90fe4c7 100644
--- a/scene/gui/tree.h
+++ b/scene/gui/tree.h
@@ -531,8 +531,8 @@ private:
float base_scale = 1.0;
- int hseparation = 0;
- int vseparation = 0;
+ int h_separation = 0;
+ int v_separation = 0;
int item_margin = 0;
int button_margin = 0;
Point2 offset;
@@ -666,6 +666,7 @@ public:
bool is_root_hidden() const;
TreeItem *get_next_selected(TreeItem *p_item);
TreeItem *get_selected() const;
+ void set_selected(TreeItem *p_item, int p_column = 0);
int get_selected_column() const;
int get_pressed_button() const;
void set_select_mode(SelectMode p_mode);
diff --git a/scene/main/canvas_item.cpp b/scene/main/canvas_item.cpp
index 7bcd4721fc..f3812eb497 100644
--- a/scene/main/canvas_item.cpp
+++ b/scene/main/canvas_item.cpp
@@ -144,7 +144,7 @@ void CanvasItem::_redraw_callback() {
Transform2D CanvasItem::get_global_transform_with_canvas() const {
if (canvas_layer) {
- return canvas_layer->get_transform() * get_global_transform();
+ return canvas_layer->get_final_transform() * get_global_transform();
} else if (is_inside_tree()) {
return get_viewport()->get_canvas_transform() * get_global_transform();
} else {
@@ -450,6 +450,39 @@ void CanvasItem::item_rect_changed(bool p_size_changed) {
emit_signal(SceneStringNames::get_singleton()->item_rect_changed);
}
+void CanvasItem::set_z_index(int p_z) {
+ ERR_FAIL_COND(p_z < RS::CANVAS_ITEM_Z_MIN);
+ ERR_FAIL_COND(p_z > RS::CANVAS_ITEM_Z_MAX);
+ z_index = p_z;
+ RS::get_singleton()->canvas_item_set_z_index(canvas_item, z_index);
+ update_configuration_warnings();
+}
+
+void CanvasItem::set_z_as_relative(bool p_enabled) {
+ if (z_relative == p_enabled) {
+ return;
+ }
+ z_relative = p_enabled;
+ RS::get_singleton()->canvas_item_set_z_as_relative_to_parent(canvas_item, p_enabled);
+}
+
+bool CanvasItem::is_z_relative() const {
+ return z_relative;
+}
+
+int CanvasItem::get_z_index() const {
+ return z_index;
+}
+
+void CanvasItem::set_y_sort_enabled(bool p_enabled) {
+ y_sort_enabled = p_enabled;
+ RS::get_singleton()->canvas_item_set_sort_children_by_y(canvas_item, y_sort_enabled);
+}
+
+bool CanvasItem::is_y_sort_enabled() const {
+ return y_sort_enabled;
+}
+
void CanvasItem::draw_dashed_line(const Point2 &p_from, const Point2 &p_to, const Color &p_color, real_t p_width, real_t p_dash) {
ERR_FAIL_COND_MSG(!drawing, "Drawing is only allowed inside NOTIFICATION_DRAW, _draw() function or 'draw' signal.");
@@ -588,10 +621,10 @@ void CanvasItem::draw_texture_rect_region(const Ref<Texture2D> &p_texture, const
p_texture->draw_rect_region(canvas_item, p_rect, p_src_rect, p_modulate, p_transpose, p_clip_uv);
}
-void CanvasItem::draw_msdf_texture_rect_region(const Ref<Texture2D> &p_texture, const Rect2 &p_rect, const Rect2 &p_src_rect, const Color &p_modulate, double p_outline, double p_pixel_range) {
+void CanvasItem::draw_msdf_texture_rect_region(const Ref<Texture2D> &p_texture, const Rect2 &p_rect, const Rect2 &p_src_rect, const Color &p_modulate, double p_outline, double p_pixel_range, double p_scale) {
ERR_FAIL_COND_MSG(!drawing, "Drawing is only allowed inside NOTIFICATION_DRAW, _draw() function or 'draw' signal.");
ERR_FAIL_COND(p_texture.is_null());
- RenderingServer::get_singleton()->canvas_item_add_msdf_texture_rect_region(canvas_item, p_rect, p_texture->get_rid(), p_src_rect, p_modulate, p_outline, p_pixel_range);
+ RenderingServer::get_singleton()->canvas_item_add_msdf_texture_rect_region(canvas_item, p_rect, p_texture->get_rid(), p_src_rect, p_modulate, p_outline, p_pixel_range, p_scale);
}
void CanvasItem::draw_lcd_texture_rect_region(const Ref<Texture2D> &p_texture, const Rect2 &p_rect, const Rect2 &p_src_rect, const Color &p_modulate) {
@@ -913,9 +946,19 @@ void CanvasItem::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_modulate", "modulate"), &CanvasItem::set_modulate);
ClassDB::bind_method(D_METHOD("get_modulate"), &CanvasItem::get_modulate);
+
ClassDB::bind_method(D_METHOD("set_self_modulate", "self_modulate"), &CanvasItem::set_self_modulate);
ClassDB::bind_method(D_METHOD("get_self_modulate"), &CanvasItem::get_self_modulate);
+ ClassDB::bind_method(D_METHOD("set_z_index", "z_index"), &CanvasItem::set_z_index);
+ ClassDB::bind_method(D_METHOD("get_z_index"), &CanvasItem::get_z_index);
+
+ ClassDB::bind_method(D_METHOD("set_z_as_relative", "enable"), &CanvasItem::set_z_as_relative);
+ ClassDB::bind_method(D_METHOD("is_z_relative"), &CanvasItem::is_z_relative);
+
+ ClassDB::bind_method(D_METHOD("set_y_sort_enabled", "enabled"), &CanvasItem::set_y_sort_enabled);
+ ClassDB::bind_method(D_METHOD("is_y_sort_enabled"), &CanvasItem::is_y_sort_enabled);
+
ClassDB::bind_method(D_METHOD("set_draw_behind_parent", "enable"), &CanvasItem::set_draw_behind_parent);
ClassDB::bind_method(D_METHOD("is_draw_behind_parent_enabled"), &CanvasItem::is_draw_behind_parent_enabled);
@@ -931,7 +974,7 @@ void CanvasItem::_bind_methods() {
ClassDB::bind_method(D_METHOD("draw_texture", "texture", "position", "modulate"), &CanvasItem::draw_texture, DEFVAL(Color(1, 1, 1, 1)));
ClassDB::bind_method(D_METHOD("draw_texture_rect", "texture", "rect", "tile", "modulate", "transpose"), &CanvasItem::draw_texture_rect, DEFVAL(Color(1, 1, 1, 1)), DEFVAL(false));
ClassDB::bind_method(D_METHOD("draw_texture_rect_region", "texture", "rect", "src_rect", "modulate", "transpose", "clip_uv"), &CanvasItem::draw_texture_rect_region, DEFVAL(Color(1, 1, 1, 1)), DEFVAL(false), DEFVAL(true));
- ClassDB::bind_method(D_METHOD("draw_msdf_texture_rect_region", "texture", "rect", "src_rect", "modulate", "outline", "pixel_range"), &CanvasItem::draw_msdf_texture_rect_region, DEFVAL(Color(1, 1, 1, 1)), DEFVAL(0.0), DEFVAL(4.0));
+ ClassDB::bind_method(D_METHOD("draw_msdf_texture_rect_region", "texture", "rect", "src_rect", "modulate", "outline", "pixel_range", "scale"), &CanvasItem::draw_msdf_texture_rect_region, DEFVAL(Color(1, 1, 1, 1)), DEFVAL(0.0), DEFVAL(4.0), DEFVAL(1.0));
ClassDB::bind_method(D_METHOD("draw_lcd_texture_rect_region", "texture", "rect", "src_rect", "modulate"), &CanvasItem::draw_lcd_texture_rect_region, DEFVAL(Color(1, 1, 1, 1)));
ClassDB::bind_method(D_METHOD("draw_style_box", "style_box", "rect"), &CanvasItem::draw_style_box);
ClassDB::bind_method(D_METHOD("draw_primitive", "points", "colors", "uvs", "texture", "width"), &CanvasItem::draw_primitive, DEFVAL(Ref<Texture2D>()), DEFVAL(1.0));
@@ -1005,6 +1048,11 @@ void CanvasItem::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::INT, "light_mask", PROPERTY_HINT_LAYERS_2D_RENDER), "set_light_mask", "get_light_mask");
ADD_PROPERTY(PropertyInfo(Variant::INT, "visibility_layer", PROPERTY_HINT_LAYERS_2D_RENDER), "set_visibility_layer", "get_visibility_layer");
+ ADD_GROUP("Ordering", "");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "z_index", PROPERTY_HINT_RANGE, itos(RS::CANVAS_ITEM_Z_MIN) + "," + itos(RS::CANVAS_ITEM_Z_MAX) + ",1"), "set_z_index", "get_z_index");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "z_as_relative"), "set_z_as_relative", "is_z_relative");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "y_sort_enabled"), "set_y_sort_enabled", "is_y_sort_enabled");
+
ADD_GROUP("Texture", "texture_");
ADD_PROPERTY(PropertyInfo(Variant::INT, "texture_filter", PROPERTY_HINT_ENUM, "Inherit,Nearest,Linear,Nearest Mipmap,Linear Mipmap,Nearest Mipmap Anisotropic,Linear Mipmap Anisotropic"), "set_texture_filter", "get_texture_filter");
ADD_PROPERTY(PropertyInfo(Variant::INT, "texture_repeat", PROPERTY_HINT_ENUM, "Inherit,Disabled,Enabled,Mirror"), "set_texture_repeat", "get_texture_repeat");
@@ -1051,7 +1099,7 @@ Transform2D CanvasItem::get_canvas_transform() const {
ERR_FAIL_COND_V(!is_inside_tree(), Transform2D());
if (canvas_layer) {
- return canvas_layer->get_transform();
+ return canvas_layer->get_final_transform();
} else if (Object::cast_to<CanvasItem>(get_parent())) {
return Object::cast_to<CanvasItem>(get_parent())->get_canvas_transform();
} else {
@@ -1063,7 +1111,7 @@ Transform2D CanvasItem::get_viewport_transform() const {
ERR_FAIL_COND_V(!is_inside_tree(), Transform2D());
if (canvas_layer) {
- return get_viewport()->get_final_transform() * canvas_layer->get_transform();
+ return get_viewport()->get_final_transform() * canvas_layer->get_final_transform();
} else {
return get_viewport()->get_final_transform() * get_viewport()->get_canvas_transform();
}
diff --git a/scene/main/canvas_item.h b/scene/main/canvas_item.h
index 4e78a175dc..bae03d706a 100644
--- a/scene/main/canvas_item.h
+++ b/scene/main/canvas_item.h
@@ -91,6 +91,10 @@ private:
int light_mask = 1;
uint32_t visibility_layer = 1;
+ int z_index = 0;
+ bool z_relative = true;
+ bool y_sort_enabled = false;
+
Window *window = nullptr;
bool visible = true;
bool parent_visible_in_tree = false;
@@ -230,6 +234,17 @@ public:
void set_visibility_layer_bit(uint32_t p_visibility_layer, bool p_enable);
bool get_visibility_layer_bit(uint32_t p_visibility_layer) const;
+ /* ORDERING */
+
+ void set_z_index(int p_z);
+ int get_z_index() const;
+
+ void set_z_as_relative(bool p_enabled);
+ bool is_z_relative() const;
+
+ virtual void set_y_sort_enabled(bool p_enabled);
+ virtual bool is_y_sort_enabled() const;
+
/* DRAWING API */
void draw_dashed_line(const Point2 &p_from, const Point2 &p_to, const Color &p_color, real_t p_width = 1.0, real_t p_dash = 2.0);
@@ -244,7 +259,7 @@ public:
void draw_texture(const Ref<Texture2D> &p_texture, const Point2 &p_pos, const Color &p_modulate = Color(1, 1, 1, 1));
void draw_texture_rect(const Ref<Texture2D> &p_texture, const Rect2 &p_rect, bool p_tile = false, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false);
void draw_texture_rect_region(const Ref<Texture2D> &p_texture, const Rect2 &p_rect, const Rect2 &p_src_rect, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false, bool p_clip_uv = false);
- void draw_msdf_texture_rect_region(const Ref<Texture2D> &p_texture, const Rect2 &p_rect, const Rect2 &p_src_rect, const Color &p_modulate = Color(1, 1, 1), double p_outline = 0.0, double p_pixel_range = 4.0);
+ void draw_msdf_texture_rect_region(const Ref<Texture2D> &p_texture, const Rect2 &p_rect, const Rect2 &p_src_rect, const Color &p_modulate = Color(1, 1, 1), double p_outline = 0.0, double p_pixel_range = 4.0, double p_scale = 1.0);
void draw_lcd_texture_rect_region(const Ref<Texture2D> &p_texture, const Rect2 &p_rect, const Rect2 &p_src_rect, const Color &p_modulate = Color(1, 1, 1));
void draw_style_box(const Ref<StyleBox> &p_style_box, const Rect2 &p_rect);
void draw_primitive(const Vector<Point2> &p_points, const Vector<Color> &p_colors, const Vector<Point2> &p_uvs, Ref<Texture2D> p_texture = Ref<Texture2D>(), real_t p_width = 1);
diff --git a/scene/main/canvas_layer.cpp b/scene/main/canvas_layer.cpp
index be5788739b..97b784e9d0 100644
--- a/scene/main/canvas_layer.cpp
+++ b/scene/main/canvas_layer.cpp
@@ -38,7 +38,7 @@ void CanvasLayer::set_layer(int p_xform) {
layer = p_xform;
if (viewport.is_valid()) {
RenderingServer::get_singleton()->viewport_set_canvas_stacking(viewport, canvas, layer, get_index());
- vp->_gui_set_root_order_dirty();
+ vp->gui_set_root_order_dirty();
}
}
@@ -88,6 +88,18 @@ Transform2D CanvasLayer::get_transform() const {
return transform;
}
+Transform2D CanvasLayer::get_final_transform() const {
+ if (is_following_viewport()) {
+ Transform2D follow;
+ follow.scale(Vector2(get_follow_viewport_scale(), get_follow_viewport_scale()));
+ if (vp) {
+ follow = vp->get_canvas_transform() * follow;
+ }
+ return follow * transform;
+ }
+ return transform;
+}
+
void CanvasLayer::_update_xform() {
transform.set_rotation_and_scale(rot, scale);
transform.set_origin(ofs);
@@ -304,6 +316,7 @@ void CanvasLayer::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_transform", "transform"), &CanvasLayer::set_transform);
ClassDB::bind_method(D_METHOD("get_transform"), &CanvasLayer::get_transform);
+ ClassDB::bind_method(D_METHOD("get_final_transform"), &CanvasLayer::get_final_transform);
ClassDB::bind_method(D_METHOD("set_offset", "offset"), &CanvasLayer::set_offset);
ClassDB::bind_method(D_METHOD("get_offset"), &CanvasLayer::get_offset);
diff --git a/scene/main/canvas_layer.h b/scene/main/canvas_layer.h
index 74b5ebd453..2afc842a50 100644
--- a/scene/main/canvas_layer.h
+++ b/scene/main/canvas_layer.h
@@ -77,6 +77,7 @@ public:
void set_transform(const Transform2D &p_xform);
Transform2D get_transform() const;
+ Transform2D get_final_transform() const;
void set_offset(const Vector2 &p_offset);
Vector2 get_offset() const;
diff --git a/scene/main/http_request.cpp b/scene/main/http_request.cpp
index 2c395ec07d..62f362553f 100644
--- a/scene/main/http_request.cpp
+++ b/scene/main/http_request.cpp
@@ -276,10 +276,10 @@ bool HTTPRequest::_handle_response(bool *ret_value) {
}
if (content_encoding == "gzip") {
decompressor.instantiate();
- decompressor->start_decompression(false, get_download_chunk_size() * 2);
+ decompressor->start_decompression(false, get_download_chunk_size());
} else if (content_encoding == "deflate") {
decompressor.instantiate();
- decompressor->start_decompression(true, get_download_chunk_size() * 2);
+ decompressor->start_decompression(true, get_download_chunk_size());
}
return false;
@@ -390,19 +390,38 @@ bool HTTPRequest::_update_connection() {
return false;
}
- PackedByteArray chunk = client->read_response_body_chunk();
- downloaded.add(chunk.size());
-
- // Decompress chunk if needed.
- if (decompressor.is_valid()) {
- Error err = decompressor->put_data(chunk.ptr(), chunk.size());
- if (err == OK) {
- chunk.resize(decompressor->get_available_bytes());
- err = decompressor->get_data(chunk.ptrw(), chunk.size());
- }
- if (err != OK) {
- _defer_done(RESULT_BODY_DECOMPRESS_FAILED, response_code, response_headers, PackedByteArray());
- return true;
+ PackedByteArray chunk;
+ if (decompressor.is_null()) {
+ // Chunk can be read directly.
+ chunk = client->read_response_body_chunk();
+ downloaded.add(chunk.size());
+ } else {
+ // Chunk is the result of decompression.
+ PackedByteArray compressed = client->read_response_body_chunk();
+ downloaded.add(compressed.size());
+
+ int pos = 0;
+ int left = compressed.size();
+ while (left) {
+ int w = 0;
+ Error err = decompressor->put_partial_data(compressed.ptr() + pos, left, w);
+ if (err == OK) {
+ PackedByteArray dc;
+ dc.resize(decompressor->get_available_bytes());
+ err = decompressor->get_data(dc.ptrw(), dc.size());
+ chunk.append_array(dc);
+ }
+ if (err != OK) {
+ _defer_done(RESULT_BODY_DECOMPRESS_FAILED, response_code, response_headers, PackedByteArray());
+ return true;
+ }
+ // We need this check here because a "zip bomb" could result in a chunk of few kilos decompressing into gigabytes of data.
+ if (body_size_limit >= 0 && final_body_size.get() + chunk.size() > body_size_limit) {
+ _defer_done(RESULT_BODY_SIZE_LIMIT_EXCEEDED, response_code, response_headers, PackedByteArray());
+ return true;
+ }
+ pos += w;
+ left -= w;
}
}
final_body_size.add(chunk.size());
diff --git a/scene/main/multiplayer_api.cpp b/scene/main/multiplayer_api.cpp
index 946929aa89..8b4b98c172 100644
--- a/scene/main/multiplayer_api.cpp
+++ b/scene/main/multiplayer_api.cpp
@@ -39,7 +39,7 @@
#include "core/os/os.h"
#endif
-StringName MultiplayerAPI::default_interface = StringName();
+StringName MultiplayerAPI::default_interface;
void MultiplayerAPI::set_default_interface(const StringName &p_interface) {
ERR_FAIL_COND_MSG(!ClassDB::is_parent_class(p_interface, MultiplayerAPI::get_class_static()), vformat("Can't make %s the default multiplayer interface since it does not extend MultiplayerAPI.", p_interface));
diff --git a/scene/main/multiplayer_peer.h b/scene/main/multiplayer_peer.h
index 4b5909538e..fa6b11e5db 100644
--- a/scene/main/multiplayer_peer.h
+++ b/scene/main/multiplayer_peer.h
@@ -112,11 +112,11 @@ protected:
public:
/* PacketPeer extension */
virtual Error get_packet(const uint8_t **r_buffer, int &r_buffer_size) override; ///< buffer is GONE after next get_packet
- GDVIRTUAL2R(Error, _get_packet, GDNativeConstPtr<const uint8_t *>, GDNativePtr<int>);
+ GDVIRTUAL2R(Error, _get_packet, GDExtensionConstPtr<const uint8_t *>, GDExtensionPtr<int>);
GDVIRTUAL0R(PackedByteArray, _get_packet_script); // For GDScript.
virtual Error put_packet(const uint8_t *p_buffer, int p_buffer_size) override;
- GDVIRTUAL2R(Error, _put_packet, GDNativeConstPtr<const uint8_t>, int);
+ GDVIRTUAL2R(Error, _put_packet, GDExtensionConstPtr<const uint8_t>, int);
GDVIRTUAL1R(Error, _put_packet_script, PackedByteArray); // For GDScript.
EXBIND0RC(int, get_available_packet_count);
diff --git a/scene/main/node.cpp b/scene/main/node.cpp
index 304504a82e..680c4cd7e4 100644
--- a/scene/main/node.cpp
+++ b/scene/main/node.cpp
@@ -349,7 +349,7 @@ void Node::move_child(Node *p_child, int p_index) {
}
void Node::_move_child(Node *p_child, int p_index, bool p_ignore_end) {
- ERR_FAIL_COND_MSG(data.blocked > 0, "Parent node is busy setting up children, move_child() failed. Consider using call_deferred(\"move_child\") instead (or \"popup\" if this is from a popup).");
+ ERR_FAIL_COND_MSG(data.blocked > 0, "Parent node is busy setting up children, `move_child()` failed. Consider using `move_child.call_deferred(child, index)` instead (or `popup.call_deferred()` if this is from a popup).");
// Specifying one place beyond the end
// means the same as moving to the last index
@@ -1130,7 +1130,7 @@ void Node::add_child(Node *p_child, bool p_force_readable_name, InternalMode p_i
#ifdef DEBUG_ENABLED
ERR_FAIL_COND_MSG(p_child->is_ancestor_of(this), vformat("Can't add child '%s' to '%s' as it would result in a cyclic dependency since '%s' is already a parent of '%s'.", p_child->get_name(), get_name(), p_child->get_name(), get_name()));
#endif
- ERR_FAIL_COND_MSG(data.blocked > 0, "Parent node is busy setting up children, add_node() failed. Consider using call_deferred(\"add_child\", child) instead.");
+ ERR_FAIL_COND_MSG(data.blocked > 0, "Parent node is busy setting up children, `add_child()` failed. Consider using `add_child.call_deferred(child)` instead.");
_validate_child_name(p_child, p_force_readable_name);
_add_child_nocheck(p_child, p_child->data.name);
@@ -1150,7 +1150,7 @@ void Node::add_sibling(Node *p_sibling, bool p_force_readable_name) {
ERR_FAIL_NULL(p_sibling);
ERR_FAIL_NULL(data.parent);
ERR_FAIL_COND_MSG(p_sibling == this, vformat("Can't add sibling '%s' to itself.", p_sibling->get_name())); // adding to itself!
- ERR_FAIL_COND_MSG(data.blocked > 0, "Parent node is busy setting up children, add_sibling() failed. Consider using call_deferred(\"add_sibling\", sibling) instead.");
+ ERR_FAIL_COND_MSG(data.blocked > 0, "Parent node is busy setting up children, `add_sibling()` failed. Consider using `add_sibling.call_deferred(sibling)` instead.");
InternalMode internal = INTERNAL_MODE_DISABLED;
if (_is_internal_front()) { // The sibling will have the same internal status.
@@ -1165,7 +1165,7 @@ void Node::add_sibling(Node *p_sibling, bool p_force_readable_name) {
void Node::remove_child(Node *p_child) {
ERR_FAIL_NULL(p_child);
- ERR_FAIL_COND_MSG(data.blocked > 0, "Parent node is busy setting up children, remove_node() failed. Consider using call_deferred(\"remove_child\", child) instead.");
+ ERR_FAIL_COND_MSG(data.blocked > 0, "Parent node is busy setting up children, `remove_child()` failed. Consider using `remove_child.call_deferred(child)` instead.");
int child_count = data.children.size();
Node **children = data.children.ptrw();
@@ -1660,7 +1660,7 @@ Node *Node::find_common_parent_with(const Node *p_node) const {
return const_cast<Node *>(common_parent);
}
-NodePath Node::get_path_to(const Node *p_node) const {
+NodePath Node::get_path_to(const Node *p_node, bool p_use_unique_path) const {
ERR_FAIL_NULL_V(p_node, NodePath());
if (this == p_node) {
@@ -1690,20 +1690,58 @@ NodePath Node::get_path_to(const Node *p_node) const {
visited.clear();
Vector<StringName> path;
+ StringName up = String("..");
- n = p_node;
+ if (p_use_unique_path) {
+ n = p_node;
- while (n != common_parent) {
- path.push_back(n->get_name());
- n = n->data.parent;
- }
+ bool is_detected = false;
+ while (n != common_parent) {
+ if (n->is_unique_name_in_owner() && n->get_owner() == get_owner()) {
+ path.push_back(UNIQUE_NODE_PREFIX + String(n->get_name()));
+ is_detected = true;
+ break;
+ }
+ path.push_back(n->get_name());
+ n = n->data.parent;
+ }
- n = this;
- StringName up = String("..");
+ if (!is_detected) {
+ n = this;
- while (n != common_parent) {
- path.push_back(up);
- n = n->data.parent;
+ String detected_name;
+ int up_count = 0;
+ while (n != common_parent) {
+ if (n->is_unique_name_in_owner() && n->get_owner() == get_owner()) {
+ detected_name = n->get_name();
+ up_count = 0;
+ }
+ up_count++;
+ n = n->data.parent;
+ }
+
+ for (int i = 0; i < up_count; i++) {
+ path.push_back(up);
+ }
+
+ if (!detected_name.is_empty()) {
+ path.push_back(UNIQUE_NODE_PREFIX + detected_name);
+ }
+ }
+ } else {
+ n = p_node;
+
+ while (n != common_parent) {
+ path.push_back(n->get_name());
+ n = n->data.parent;
+ }
+
+ n = this;
+
+ while (n != common_parent) {
+ path.push_back(up);
+ n = n->data.parent;
+ }
}
path.reverse();
@@ -1759,11 +1797,11 @@ void Node::add_to_group(const StringName &p_identifier, bool p_persistent) {
}
void Node::remove_from_group(const StringName &p_identifier) {
- ERR_FAIL_COND(!data.grouped.has(p_identifier));
-
HashMap<StringName, GroupData>::Iterator E = data.grouped.find(p_identifier);
- ERR_FAIL_COND(!E);
+ if (!E) {
+ return;
+ }
if (data.tree) {
data.tree->remove_from_group(E->key, this);
@@ -2060,7 +2098,7 @@ Node *Node::_duplicate(int p_flags, HashMap<const Node *, Node *> *r_duplimap) c
nip->set_instance_path(ip->get_instance_path());
node = nip;
- } else if ((p_flags & DUPLICATE_USE_INSTANCING) && !get_scene_file_path().is_empty()) {
+ } else if ((p_flags & DUPLICATE_USE_INSTANTIATION) && !get_scene_file_path().is_empty()) {
Ref<PackedScene> res = ResourceLoader::load(get_scene_file_path());
ERR_FAIL_COND_V(res.is_null(), nullptr);
PackedScene::GenEditState ges = PackedScene::GEN_EDIT_STATE_DISABLED;
@@ -2246,7 +2284,7 @@ Node *Node::duplicate_from_editor(HashMap<const Node *, Node *> &r_duplimap) con
}
Node *Node::duplicate_from_editor(HashMap<const Node *, Node *> &r_duplimap, const HashMap<Ref<Resource>, Ref<Resource>> &p_resource_remap) const {
- Node *dupe = _duplicate(DUPLICATE_SIGNALS | DUPLICATE_GROUPS | DUPLICATE_SCRIPTS | DUPLICATE_USE_INSTANCING | DUPLICATE_FROM_EDITOR, &r_duplimap);
+ Node *dupe = _duplicate(DUPLICATE_SIGNALS | DUPLICATE_GROUPS | DUPLICATE_SCRIPTS | DUPLICATE_USE_INSTANTIATION | DUPLICATE_FROM_EDITOR, &r_duplimap);
// This is used by SceneTreeDock's paste functionality. When pasting to foreign scene, resources are duplicated.
if (!p_resource_remap.is_empty()) {
@@ -2570,10 +2608,6 @@ static void _Node_debug_sn(Object *p_obj) {
}
#endif // DEBUG_ENABLED
-void Node::_print_orphan_nodes() {
- print_orphan_nodes();
-}
-
void Node::print_orphan_nodes() {
#ifdef DEBUG_ENABLED
ObjectDB::debug_objects(_Node_debug_sn);
@@ -2581,10 +2615,14 @@ void Node::print_orphan_nodes() {
}
void Node::queue_free() {
+ // There are users which instantiate multiple scene trees for their games.
+ // Use the node's own tree to handle its deletion when relevant.
if (is_inside_tree()) {
get_tree()->queue_delete(this);
} else {
- SceneTree::get_singleton()->queue_delete(this);
+ SceneTree *tree = SceneTree::get_singleton();
+ ERR_FAIL_NULL_MSG(tree, "Can't queue free a node when no SceneTree is available.");
+ tree->queue_delete(this);
}
}
@@ -2652,7 +2690,7 @@ PackedStringArray Node::get_configuration_warnings() const {
String Node::get_configuration_warnings_as_string() const {
PackedStringArray warnings = get_configuration_warnings();
- String all_warnings = String();
+ String all_warnings;
for (int i = 0; i < warnings.size(); i++) {
if (i > 0) {
all_warnings += "\n\n";
@@ -2741,6 +2779,7 @@ void Node::_bind_methods() {
GLOBAL_DEF("editor/node_naming/name_casing", NAME_CASING_PASCAL_CASE);
ProjectSettings::get_singleton()->set_custom_property_info("editor/node_naming/name_casing", PropertyInfo(Variant::INT, "editor/node_naming/name_casing", PROPERTY_HINT_ENUM, "PascalCase,camelCase,snake_case"));
+ ClassDB::bind_static_method("Node", D_METHOD("print_orphan_nodes"), &Node::print_orphan_nodes);
ClassDB::bind_method(D_METHOD("add_sibling", "sibling", "force_readable_name"), &Node::add_sibling, DEFVAL(false));
ClassDB::bind_method(D_METHOD("set_name", "name"), &Node::set_name);
@@ -2764,7 +2803,7 @@ void Node::_bind_methods() {
ClassDB::bind_method(D_METHOD("is_ancestor_of", "node"), &Node::is_ancestor_of);
ClassDB::bind_method(D_METHOD("is_greater_than", "node"), &Node::is_greater_than);
ClassDB::bind_method(D_METHOD("get_path"), &Node::get_path);
- ClassDB::bind_method(D_METHOD("get_path_to", "node"), &Node::get_path_to);
+ ClassDB::bind_method(D_METHOD("get_path_to", "node", "use_unique_path"), &Node::get_path_to, DEFVAL(false));
ClassDB::bind_method(D_METHOD("add_to_group", "group", "persistent"), &Node::add_to_group, DEFVAL(false));
ClassDB::bind_method(D_METHOD("remove_from_group", "group"), &Node::remove_from_group);
ClassDB::bind_method(D_METHOD("is_in_group", "group"), &Node::is_in_group);
@@ -2798,7 +2837,6 @@ void Node::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_process_mode", "mode"), &Node::set_process_mode);
ClassDB::bind_method(D_METHOD("get_process_mode"), &Node::get_process_mode);
ClassDB::bind_method(D_METHOD("can_process"), &Node::can_process);
- ClassDB::bind_method(D_METHOD("print_orphan_nodes"), &Node::_print_orphan_nodes);
ClassDB::bind_method(D_METHOD("set_display_folded", "fold"), &Node::set_display_folded);
ClassDB::bind_method(D_METHOD("is_displayed_folded"), &Node::is_displayed_folded);
@@ -2812,7 +2850,7 @@ void Node::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_tree"), &Node::get_tree);
ClassDB::bind_method(D_METHOD("create_tween"), &Node::create_tween);
- ClassDB::bind_method(D_METHOD("duplicate", "flags"), &Node::duplicate, DEFVAL(DUPLICATE_USE_INSTANCING | DUPLICATE_SIGNALS | DUPLICATE_GROUPS | DUPLICATE_SCRIPTS));
+ ClassDB::bind_method(D_METHOD("duplicate", "flags"), &Node::duplicate, DEFVAL(DUPLICATE_USE_INSTANTIATION | DUPLICATE_SIGNALS | DUPLICATE_GROUPS | DUPLICATE_SCRIPTS));
ClassDB::bind_method(D_METHOD("replace_by", "node", "keep_groups"), &Node::replace_by, DEFVAL(false));
ClassDB::bind_method(D_METHOD("set_scene_instance_load_placeholder", "load_placeholder"), &Node::set_scene_instance_load_placeholder);
@@ -2918,7 +2956,7 @@ void Node::_bind_methods() {
BIND_ENUM_CONSTANT(DUPLICATE_SIGNALS);
BIND_ENUM_CONSTANT(DUPLICATE_GROUPS);
BIND_ENUM_CONSTANT(DUPLICATE_SCRIPTS);
- BIND_ENUM_CONSTANT(DUPLICATE_USE_INSTANCING);
+ BIND_ENUM_CONSTANT(DUPLICATE_USE_INSTANTIATION);
BIND_ENUM_CONSTANT(INTERNAL_MODE_DISABLED);
BIND_ENUM_CONSTANT(INTERNAL_MODE_FRONT);
diff --git a/scene/main/node.h b/scene/main/node.h
index 4a3ec253b1..574f5063e8 100644
--- a/scene/main/node.h
+++ b/scene/main/node.h
@@ -57,7 +57,7 @@ public:
DUPLICATE_SIGNALS = 1,
DUPLICATE_GROUPS = 2,
DUPLICATE_SCRIPTS = 4,
- DUPLICATE_USE_INSTANCING = 8,
+ DUPLICATE_USE_INSTANTIATION = 8,
#ifdef TOOLS_ENABLED
DUPLICATE_FROM_EDITOR = 16,
#endif
@@ -173,7 +173,6 @@ private:
void _propagate_ready();
void _propagate_exit_tree();
void _propagate_after_exit_tree();
- void _print_orphan_nodes();
void _propagate_process_owner(Node *p_owner, int p_pause_notification, int p_enabled_notification);
void _propagate_groups_dirty();
Array _get_node_and_resource(const NodePath &p_path);
@@ -332,7 +331,7 @@ public:
bool is_greater_than(const Node *p_node) const;
NodePath get_path() const;
- NodePath get_path_to(const Node *p_node) const;
+ NodePath get_path_to(const Node *p_node, bool p_use_unique_path = false) const;
Node *find_common_parent_with(const Node *p_node) const;
void add_to_group(const StringName &p_identifier, bool p_persistent = false);
diff --git a/scene/main/scene_tree.cpp b/scene/main/scene_tree.cpp
index 41eefe0f85..e61cca0a0f 100644
--- a/scene/main/scene_tree.cpp
+++ b/scene/main/scene_tree.cpp
@@ -594,6 +594,12 @@ void SceneTree::finalize() {
timer->release_connections();
}
timers.clear();
+
+ // Cleanup tweens.
+ for (Ref<Tween> &tween : tweens) {
+ tween->clear();
+ }
+ tweens.clear();
}
void SceneTree::quit(int p_exit_code) {
@@ -942,6 +948,9 @@ void SceneTree::_call_input_pause(const StringName &p_group, CallInputType p_cal
}
for (const ObjectID &id : no_context_node_ids) {
+ if (p_viewport->is_input_handled()) {
+ break;
+ }
Node *n = Object::cast_to<Node>(ObjectDB::get_instance(id));
if (n) {
n->_call_shortcut_input(p_input);
@@ -1413,7 +1422,7 @@ SceneTree::SceneTree() {
ProjectSettings::get_singleton()->set_custom_property_info("rendering/anti_aliasing/quality/msaa_3d", PropertyInfo(Variant::INT, "rendering/anti_aliasing/quality/msaa_3d", PROPERTY_HINT_ENUM, String::utf8("Disabled (Fastest),2× (Average),4× (Slow),8× (Slowest)")));
root->set_msaa_3d(Viewport::MSAA(msaa_mode_3d));
- const bool transparent_background = GLOBAL_DEF("rendering/transparent_background", false);
+ const bool transparent_background = GLOBAL_DEF("rendering/viewport/transparent_background", false);
root->set_transparent_background(transparent_background);
const int ssaa_mode = GLOBAL_DEF_BASIC("rendering/anti_aliasing/quality/screen_space_aa", 0);
@@ -1447,7 +1456,7 @@ SceneTree::SceneTree() {
ProjectSettings::get_singleton()->set_custom_property_info("rendering/vrs/texture",
PropertyInfo(Variant::STRING,
"rendering/vrs/texture",
- PROPERTY_HINT_FILE, "*.png"));
+ PROPERTY_HINT_FILE, "*.bmp,*.png,*.tga,*.webp"));
if (vrs_mode == 1 && !vrs_texture_path.is_empty()) {
Ref<Image> vrs_image;
vrs_image.instantiate();
diff --git a/scene/main/viewport.cpp b/scene/main/viewport.cpp
index f8b0a66a71..afc31ae480 100644
--- a/scene/main/viewport.cpp
+++ b/scene/main/viewport.cpp
@@ -362,6 +362,7 @@ void Viewport::_notification(int p_what) {
current_canvas = find_world_2d()->get_canvas();
RenderingServer::get_singleton()->viewport_attach_canvas(viewport, current_canvas);
+ RenderingServer::get_singleton()->viewport_set_canvas_transform(viewport, current_canvas, canvas_transform);
RenderingServer::get_singleton()->viewport_set_canvas_cull_mask(viewport, canvas_cull_mask);
_update_audio_listener_2d();
#ifndef _3D_DISABLED
@@ -491,6 +492,7 @@ void Viewport::_notification(int p_what) {
} break;
case NOTIFICATION_WM_WINDOW_FOCUS_OUT: {
+ _gui_cancel_tooltip();
_drop_physics_mouseover();
if (gui.mouse_focus && !gui.forced_mouse_focus) {
_drop_mouse_focus();
@@ -640,7 +642,7 @@ void Viewport::_process_picking() {
ObjectID canvas_layer_id;
if (E) {
// A descendant CanvasLayer.
- canvas_layer_transform = E->get_transform();
+ canvas_layer_transform = E->get_final_transform();
canvas_layer_id = E->get_instance_id();
} else {
// This Viewport's builtin canvas.
@@ -1561,44 +1563,15 @@ void Viewport::_gui_input_event(Ref<InputEvent> p_event) {
set_input_as_handled();
}
- if (gui.drag_data.get_type() != Variant::NIL && mb->get_button_index() == MouseButton::LEFT) {
+ if (gui.dragging && mb->get_button_index() == MouseButton::LEFT) {
// Alternate drop use (when using force_drag(), as proposed by #5342).
- gui.drag_successful = false;
- if (gui.mouse_focus) {
- gui.drag_successful = _gui_drop(gui.mouse_focus, pos, false);
- }
-
- gui.drag_data = Variant();
- gui.dragging = false;
-
- Control *drag_preview = _gui_get_drag_preview();
- if (drag_preview) {
- memdelete(drag_preview);
- gui.drag_preview_id = ObjectID();
- }
- _propagate_viewport_notification(this, NOTIFICATION_DRAG_END);
- get_base_window()->update_mouse_cursor_shape();
+ _perform_drop(gui.mouse_focus, pos);
}
_gui_cancel_tooltip();
} else {
- if (gui.drag_data.get_type() != Variant::NIL && mb->get_button_index() == MouseButton::LEFT) {
- gui.drag_successful = false;
- if (gui.drag_mouse_over) {
- gui.drag_successful = _gui_drop(gui.drag_mouse_over, gui.drag_mouse_over_pos, false);
- }
-
- Control *drag_preview = _gui_get_drag_preview();
- if (drag_preview) {
- memdelete(drag_preview);
- gui.drag_preview_id = ObjectID();
- }
-
- gui.drag_data = Variant();
- gui.dragging = false;
- gui.drag_mouse_over = nullptr;
- _propagate_viewport_notification(this, NOTIFICATION_DRAG_END);
- get_base_window()->update_mouse_cursor_shape();
+ if (gui.dragging && mb->get_button_index() == MouseButton::LEFT) {
+ _perform_drop(gui.drag_mouse_over, gui.drag_mouse_over_pos);
}
gui.mouse_focus_mask &= ~mouse_button_to_mask(mb->get_button_index()); // Remove from mask.
@@ -1652,7 +1625,7 @@ void Viewport::_gui_input_event(Ref<InputEvent> p_event) {
Control *control = Object::cast_to<Control>(ci);
if (control) {
gui.dragging = true;
- gui.drag_data = control->get_drag_data(control->get_global_transform_with_canvas().affine_inverse().xform(mpos) - gui.drag_accum);
+ gui.drag_data = control->get_drag_data(control->get_global_transform_with_canvas().affine_inverse().xform(mpos - gui.drag_accum));
if (gui.drag_data.get_type() != Variant::NIL) {
gui.mouse_focus = nullptr;
gui.forced_mouse_focus = false;
@@ -1682,7 +1655,7 @@ void Viewport::_gui_input_event(Ref<InputEvent> p_event) {
}
gui.drag_attempted = true;
- if (gui.drag_data.get_type() != Variant::NIL) {
+ if (gui.dragging) {
_propagate_viewport_notification(this, NOTIFICATION_DRAG_BEGIN);
}
}
@@ -1698,6 +1671,9 @@ void Viewport::_gui_input_event(Ref<InputEvent> p_event) {
_gui_cancel_tooltip();
if (over) {
+ if (!gui.mouse_over) {
+ _drop_physics_mouseover();
+ }
_gui_call_notification(over, Control::NOTIFICATION_MOUSE_ENTER);
gui.mouse_over = over;
}
@@ -1795,7 +1771,7 @@ void Viewport::_gui_input_event(Ref<InputEvent> p_event) {
}
}
- if (gui.drag_data.get_type() != Variant::NIL) {
+ if (gui.dragging) {
// Handle drag & drop.
Control *drag_preview = _gui_get_drag_preview();
@@ -1904,9 +1880,11 @@ void Viewport::_gui_input_event(Ref<InputEvent> p_event) {
Ref<InputEventScreenTouch> touch_event = p_event;
if (touch_event.is_valid()) {
Size2 pos = touch_event->get_position();
+ const int touch_index = touch_event->get_index();
if (touch_event->is_pressed()) {
Control *over = gui_find_control(pos);
if (over) {
+ gui.touch_focus[touch_index] = over->get_instance_id();
bool stopped = false;
if (over->can_process()) {
touch_event = touch_event->xformed_by(Transform2D()); // Make a copy.
@@ -1923,17 +1901,25 @@ void Viewport::_gui_input_event(Ref<InputEvent> p_event) {
}
return;
}
- } else if (touch_event->get_index() == 0 && gui.last_mouse_focus) {
+ } else {
bool stopped = false;
- if (gui.last_mouse_focus->can_process()) {
+ ObjectID control_id = gui.touch_focus[touch_index];
+ Control *over = control_id.is_valid() ? Object::cast_to<Control>(ObjectDB::get_instance(control_id)) : nullptr;
+ if (over && over->can_process()) {
touch_event = touch_event->xformed_by(Transform2D()); // Make a copy.
- touch_event->set_position(gui.focus_inv_xform.xform(pos));
+ if (over == gui.last_mouse_focus) {
+ pos = gui.focus_inv_xform.xform(pos);
+ } else {
+ pos = over->get_global_transform_with_canvas().affine_inverse().xform(pos);
+ }
+ touch_event->set_position(pos);
- stopped = _gui_call_input(gui.last_mouse_focus, touch_event);
+ stopped = _gui_call_input(over, touch_event);
}
if (stopped) {
set_input_as_handled();
}
+ gui.touch_focus.erase(touch_index);
return;
}
}
@@ -1968,7 +1954,9 @@ void Viewport::_gui_input_event(Ref<InputEvent> p_event) {
Ref<InputEventScreenDrag> drag_event = p_event;
if (drag_event.is_valid()) {
- Control *over = gui.mouse_focus;
+ const int drag_event_index = drag_event->get_index();
+ ObjectID control_id = gui.touch_focus[drag_event_index];
+ Control *over = control_id.is_valid() ? Object::cast_to<Control>(ObjectDB::get_instance(control_id)) : nullptr;
if (!over) {
over = gui_find_control(drag_event->get_position());
}
@@ -1997,6 +1985,12 @@ void Viewport::_gui_input_event(Ref<InputEvent> p_event) {
}
if (mm.is_null() && mb.is_null() && p_event->is_action_type()) {
+ if (gui.dragging && p_event->is_action_pressed("ui_cancel") && Input::get_singleton()->is_action_just_pressed("ui_cancel")) {
+ _perform_drop();
+ set_input_as_handled();
+ return;
+ }
+
if (gui.key_focus && !gui.key_focus->is_visible_in_tree()) {
gui.key_focus->release_focus();
}
@@ -2078,6 +2072,27 @@ void Viewport::_gui_input_event(Ref<InputEvent> p_event) {
}
}
+void Viewport::_perform_drop(Control *p_control, Point2 p_pos) {
+ // Without any arguments, simply cancel Drag and Drop.
+ if (p_control) {
+ gui.drag_successful = _gui_drop(p_control, p_pos, false);
+ } else {
+ gui.drag_successful = false;
+ }
+
+ Control *drag_preview = _gui_get_drag_preview();
+ if (drag_preview) {
+ memdelete(drag_preview);
+ gui.drag_preview_id = ObjectID();
+ }
+
+ gui.drag_data = Variant();
+ gui.dragging = false;
+ gui.drag_mouse_over = nullptr;
+ _propagate_viewport_notification(this, NOTIFICATION_DRAG_END);
+ get_base_window()->update_mouse_cursor_shape();
+}
+
void Viewport::_gui_cleanup_internal_state(Ref<InputEvent> p_event) {
ERR_FAIL_COND(p_event.is_null());
@@ -2094,7 +2109,7 @@ List<Control *>::Element *Viewport::_gui_add_root_control(Control *p_control) {
return gui.roots.push_back(p_control);
}
-void Viewport::_gui_set_root_order_dirty() {
+void Viewport::gui_set_root_order_dirty() {
gui.roots_order_dirty = true;
}
@@ -2662,6 +2677,11 @@ bool Viewport::_sub_windows_forward_input(const Ref<InputEvent> &p_event) {
} else {
gui.subwindow_resize_mode = _sub_window_get_resize_margin(sw.window, mb->get_position());
if (gui.subwindow_resize_mode != SUB_WINDOW_RESIZE_DISABLED) {
+ if (gui.subwindow_focused != sw.window) {
+ // Refocus.
+ _sub_window_grab_focus(sw.window);
+ }
+
gui.subwindow_resize_from_rect = r;
gui.subwindow_drag_from = mb->get_position();
gui.subwindow_drag = SUB_WINDOW_DRAG_RESIZE;
@@ -3041,8 +3061,6 @@ bool Viewport::gui_is_drag_successful() const {
}
void Viewport::set_input_as_handled() {
- _drop_physics_mouseover();
-
if (!handle_input_locally) {
ERR_FAIL_COND(!is_inside_tree());
Viewport *vp = this;
@@ -4161,7 +4179,7 @@ DisplayServer::WindowID SubViewport::get_window_id() const {
}
Transform2D SubViewport::_stretch_transform() {
- Transform2D transform = Transform2D();
+ Transform2D transform;
Size2i view_size_2d_override = _get_size_2d_override();
if (size_2d_override_stretch && view_size_2d_override.width > 0 && view_size_2d_override.height > 0) {
Size2 scale = Size2(_get_size()) / Size2(view_size_2d_override);
@@ -4172,7 +4190,7 @@ Transform2D SubViewport::_stretch_transform() {
}
Transform2D SubViewport::get_screen_transform() const {
- Transform2D container_transform = Transform2D();
+ Transform2D container_transform;
SubViewportContainer *c = Object::cast_to<SubViewportContainer>(get_parent());
if (c) {
if (c->is_stretch_enabled()) {
@@ -4231,6 +4249,8 @@ void SubViewport::_bind_methods() {
BIND_ENUM_CONSTANT(UPDATE_ALWAYS);
}
-SubViewport::SubViewport() {}
+SubViewport::SubViewport() {
+ RS::get_singleton()->viewport_set_size(get_viewport_rid(), get_size().width, get_size().height);
+}
SubViewport::~SubViewport() {}
diff --git a/scene/main/viewport.h b/scene/main/viewport.h
index 8911aea335..bc8cd54603 100644
--- a/scene/main/viewport.h
+++ b/scene/main/viewport.h
@@ -354,6 +354,7 @@ private:
bool forced_mouse_focus = false; //used for menu buttons
bool mouse_in_viewport = true;
bool key_event_accepted = false;
+ HashMap<int, ObjectID> touch_focus;
Control *mouse_focus = nullptr;
Control *last_mouse_focus = nullptr;
Control *mouse_click_grabber = nullptr;
@@ -405,6 +406,7 @@ private:
Control *_gui_find_control_at_pos(CanvasItem *p_node, const Point2 &p_global, const Transform2D &p_xform, Transform2D &r_inv_xform);
void _gui_input_event(Ref<InputEvent> p_event);
+ void _perform_drop(Control *p_control = nullptr, Point2 p_pos = Point2());
void _gui_cleanup_internal_state(Ref<InputEvent> p_event);
_FORCE_INLINE_ Transform2D _get_input_pre_xform() const;
@@ -455,8 +457,6 @@ private:
void _update_canvas_items(Node *p_node);
- void _gui_set_root_order_dirty();
-
friend class Window;
void _sub_window_update_order();
@@ -513,6 +513,8 @@ public:
Transform2D get_final_transform() const;
+ void gui_set_root_order_dirty();
+
void set_transparent_background(bool p_enable);
bool has_transparent_background() const;
diff --git a/scene/main/window.cpp b/scene/main/window.cpp
index ebb11ecee8..c71c3e195b 100644
--- a/scene/main/window.cpp
+++ b/scene/main/window.cpp
@@ -40,6 +40,218 @@
#include "scene/theme/theme_db.h"
#include "scene/theme/theme_owner.h"
+// Dynamic properties.
+
+bool Window::_set(const StringName &p_name, const Variant &p_value) {
+ String name = p_name;
+ if (!name.begins_with("theme_override")) {
+ return false;
+ }
+
+ if (p_value.get_type() == Variant::NIL || (p_value.get_type() == Variant::OBJECT && (Object *)p_value == nullptr)) {
+ if (name.begins_with("theme_override_icons/")) {
+ String dname = name.get_slicec('/', 1);
+ if (theme_icon_override.has(dname)) {
+ theme_icon_override[dname]->disconnect("changed", callable_mp(this, &Window::_notify_theme_override_changed));
+ }
+ theme_icon_override.erase(dname);
+ _notify_theme_override_changed();
+ } else if (name.begins_with("theme_override_styles/")) {
+ String dname = name.get_slicec('/', 1);
+ if (theme_style_override.has(dname)) {
+ theme_style_override[dname]->disconnect("changed", callable_mp(this, &Window::_notify_theme_override_changed));
+ }
+ theme_style_override.erase(dname);
+ _notify_theme_override_changed();
+ } else if (name.begins_with("theme_override_fonts/")) {
+ String dname = name.get_slicec('/', 1);
+ if (theme_font_override.has(dname)) {
+ theme_font_override[dname]->disconnect("changed", callable_mp(this, &Window::_notify_theme_override_changed));
+ }
+ theme_font_override.erase(dname);
+ _notify_theme_override_changed();
+ } else if (name.begins_with("theme_override_font_sizes/")) {
+ String dname = name.get_slicec('/', 1);
+ theme_font_size_override.erase(dname);
+ _notify_theme_override_changed();
+ } else if (name.begins_with("theme_override_colors/")) {
+ String dname = name.get_slicec('/', 1);
+ theme_color_override.erase(dname);
+ _notify_theme_override_changed();
+ } else if (name.begins_with("theme_override_constants/")) {
+ String dname = name.get_slicec('/', 1);
+ theme_constant_override.erase(dname);
+ _notify_theme_override_changed();
+ } else {
+ return false;
+ }
+
+ } else {
+ if (name.begins_with("theme_override_icons/")) {
+ String dname = name.get_slicec('/', 1);
+ add_theme_icon_override(dname, p_value);
+ } else if (name.begins_with("theme_override_styles/")) {
+ String dname = name.get_slicec('/', 1);
+ add_theme_style_override(dname, p_value);
+ } else if (name.begins_with("theme_override_fonts/")) {
+ String dname = name.get_slicec('/', 1);
+ add_theme_font_override(dname, p_value);
+ } else if (name.begins_with("theme_override_font_sizes/")) {
+ String dname = name.get_slicec('/', 1);
+ add_theme_font_size_override(dname, p_value);
+ } else if (name.begins_with("theme_override_colors/")) {
+ String dname = name.get_slicec('/', 1);
+ add_theme_color_override(dname, p_value);
+ } else if (name.begins_with("theme_override_constants/")) {
+ String dname = name.get_slicec('/', 1);
+ add_theme_constant_override(dname, p_value);
+ } else {
+ return false;
+ }
+ }
+ return true;
+}
+
+bool Window::_get(const StringName &p_name, Variant &r_ret) const {
+ String sname = p_name;
+ if (!sname.begins_with("theme_override")) {
+ return false;
+ }
+
+ if (sname.begins_with("theme_override_icons/")) {
+ String name = sname.get_slicec('/', 1);
+ r_ret = theme_icon_override.has(name) ? Variant(theme_icon_override[name]) : Variant();
+ } else if (sname.begins_with("theme_override_styles/")) {
+ String name = sname.get_slicec('/', 1);
+ r_ret = theme_style_override.has(name) ? Variant(theme_style_override[name]) : Variant();
+ } else if (sname.begins_with("theme_override_fonts/")) {
+ String name = sname.get_slicec('/', 1);
+ r_ret = theme_font_override.has(name) ? Variant(theme_font_override[name]) : Variant();
+ } else if (sname.begins_with("theme_override_font_sizes/")) {
+ String name = sname.get_slicec('/', 1);
+ r_ret = theme_font_size_override.has(name) ? Variant(theme_font_size_override[name]) : Variant();
+ } else if (sname.begins_with("theme_override_colors/")) {
+ String name = sname.get_slicec('/', 1);
+ r_ret = theme_color_override.has(name) ? Variant(theme_color_override[name]) : Variant();
+ } else if (sname.begins_with("theme_override_constants/")) {
+ String name = sname.get_slicec('/', 1);
+ r_ret = theme_constant_override.has(name) ? Variant(theme_constant_override[name]) : Variant();
+ } else {
+ return false;
+ }
+
+ return true;
+}
+
+void Window::_get_property_list(List<PropertyInfo> *p_list) const {
+ Ref<Theme> default_theme = ThemeDB::get_singleton()->get_default_theme();
+
+ p_list->push_back(PropertyInfo(Variant::NIL, TTRC("Theme Overrides"), PROPERTY_HINT_NONE, "theme_override_", PROPERTY_USAGE_GROUP));
+
+ {
+ List<StringName> names;
+ default_theme->get_color_list(get_class_name(), &names);
+ for (const StringName &E : names) {
+ uint32_t usage = PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_CHECKABLE;
+ if (theme_color_override.has(E)) {
+ usage |= PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_CHECKED;
+ }
+
+ p_list->push_back(PropertyInfo(Variant::COLOR, "theme_override_colors/" + E, PROPERTY_HINT_NONE, "", usage));
+ }
+ }
+ {
+ List<StringName> names;
+ default_theme->get_constant_list(get_class_name(), &names);
+ for (const StringName &E : names) {
+ uint32_t usage = PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_CHECKABLE;
+ if (theme_constant_override.has(E)) {
+ usage |= PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_CHECKED;
+ }
+
+ p_list->push_back(PropertyInfo(Variant::INT, "theme_override_constants/" + E, PROPERTY_HINT_RANGE, "-16384,16384", usage));
+ }
+ }
+ {
+ List<StringName> names;
+ default_theme->get_font_list(get_class_name(), &names);
+ for (const StringName &E : names) {
+ uint32_t usage = PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_CHECKABLE;
+ if (theme_font_override.has(E)) {
+ usage |= PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_CHECKED;
+ }
+
+ p_list->push_back(PropertyInfo(Variant::OBJECT, "theme_override_fonts/" + E, PROPERTY_HINT_RESOURCE_TYPE, "Font", usage));
+ }
+ }
+ {
+ List<StringName> names;
+ default_theme->get_font_size_list(get_class_name(), &names);
+ for (const StringName &E : names) {
+ uint32_t usage = PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_CHECKABLE;
+ if (theme_font_size_override.has(E)) {
+ usage |= PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_CHECKED;
+ }
+
+ p_list->push_back(PropertyInfo(Variant::INT, "theme_override_font_sizes/" + E, PROPERTY_HINT_RANGE, "1,256,1,or_greater,suffix:px", usage));
+ }
+ }
+ {
+ List<StringName> names;
+ default_theme->get_icon_list(get_class_name(), &names);
+ for (const StringName &E : names) {
+ uint32_t usage = PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_CHECKABLE;
+ if (theme_icon_override.has(E)) {
+ usage |= PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_CHECKED;
+ }
+
+ p_list->push_back(PropertyInfo(Variant::OBJECT, "theme_override_icons/" + E, PROPERTY_HINT_RESOURCE_TYPE, "Texture2D", usage));
+ }
+ }
+ {
+ List<StringName> names;
+ default_theme->get_stylebox_list(get_class_name(), &names);
+ for (const StringName &E : names) {
+ uint32_t usage = PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_CHECKABLE;
+ if (theme_style_override.has(E)) {
+ usage |= PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_CHECKED;
+ }
+
+ p_list->push_back(PropertyInfo(Variant::OBJECT, "theme_override_styles/" + E, PROPERTY_HINT_RESOURCE_TYPE, "StyleBox", usage));
+ }
+ }
+}
+
+void Window::_validate_property(PropertyInfo &p_property) const {
+ if (p_property.name == "theme_type_variation") {
+ List<StringName> names;
+
+ // Only the default theme and the project theme are used for the list of options.
+ // This is an imposed limitation to simplify the logic needed to leverage those options.
+ ThemeDB::get_singleton()->get_default_theme()->get_type_variation_list(get_class_name(), &names);
+ if (ThemeDB::get_singleton()->get_project_theme().is_valid()) {
+ ThemeDB::get_singleton()->get_project_theme()->get_type_variation_list(get_class_name(), &names);
+ }
+ names.sort_custom<StringName::AlphCompare>();
+
+ Vector<StringName> unique_names;
+ String hint_string;
+ for (const StringName &E : names) {
+ // Skip duplicate values.
+ if (unique_names.has(E)) {
+ continue;
+ }
+
+ hint_string += String(E) + ",";
+ unique_names.append(E);
+ }
+
+ p_property.hint_string = hint_string;
+ }
+}
+
+//
+
void Window::set_title(const String &p_title) {
title = p_title;
@@ -106,9 +318,16 @@ void Window::reset_size() {
set_size(Size2i());
}
-Size2i Window::get_real_size() const {
+Point2i Window::get_position_with_decorations() const {
+ if (window_id != DisplayServer::INVALID_WINDOW_ID) {
+ return DisplayServer::get_singleton()->window_get_position_with_decorations(window_id);
+ }
+ return position;
+}
+
+Size2i Window::get_size_with_decorations() const {
if (window_id != DisplayServer::INVALID_WINDOW_ID) {
- return DisplayServer::get_singleton()->window_get_real_size(window_id);
+ return DisplayServer::get_singleton()->window_get_size_with_decorations(window_id);
}
return size;
}
@@ -1316,6 +1535,8 @@ void Window::remove_child_notify(Node *p_child) {
}
}
+// Theming.
+
void Window::set_theme_owner_node(Node *p_node) {
theme_owner->set_owner_node(p_node);
}
@@ -1369,6 +1590,12 @@ void Window::_theme_changed() {
}
}
+void Window::_notify_theme_override_changed() {
+ if (!bulk_theme_override && is_inside_tree()) {
+ notification(NOTIFICATION_THEME_CHANGED);
+ }
+}
+
void Window::_invalidate_theme_cache() {
theme_icon_cache.clear();
theme_style_cache.clear();
@@ -1379,6 +1606,9 @@ void Window::_invalidate_theme_cache() {
}
void Window::_update_theme_item_cache() {
+ // Request an update on the next frame to reflect theme changes.
+ // Updating without a delay can cause a lot of lag.
+ child_controls_changed();
}
void Window::set_theme_type_variation(const StringName &p_theme_type) {
@@ -1392,7 +1622,16 @@ StringName Window::get_theme_type_variation() const {
return theme_type_variation;
}
+/// Theme property lookup.
+
Ref<Texture2D> Window::get_theme_icon(const StringName &p_name, const StringName &p_theme_type) const {
+ if (p_theme_type == StringName() || p_theme_type == get_class_name() || p_theme_type == theme_type_variation) {
+ const Ref<Texture2D> *tex = theme_icon_override.getptr(p_name);
+ if (tex) {
+ return *tex;
+ }
+ }
+
if (theme_icon_cache.has(p_theme_type) && theme_icon_cache[p_theme_type].has(p_name)) {
return theme_icon_cache[p_theme_type][p_name];
}
@@ -1405,6 +1644,13 @@ Ref<Texture2D> Window::get_theme_icon(const StringName &p_name, const StringName
}
Ref<StyleBox> Window::get_theme_stylebox(const StringName &p_name, const StringName &p_theme_type) const {
+ if (p_theme_type == StringName() || p_theme_type == get_class_name() || p_theme_type == theme_type_variation) {
+ const Ref<StyleBox> *style = theme_style_override.getptr(p_name);
+ if (style) {
+ return *style;
+ }
+ }
+
if (theme_style_cache.has(p_theme_type) && theme_style_cache[p_theme_type].has(p_name)) {
return theme_style_cache[p_theme_type][p_name];
}
@@ -1417,6 +1663,13 @@ Ref<StyleBox> Window::get_theme_stylebox(const StringName &p_name, const StringN
}
Ref<Font> Window::get_theme_font(const StringName &p_name, const StringName &p_theme_type) const {
+ if (p_theme_type == StringName() || p_theme_type == get_class_name() || p_theme_type == theme_type_variation) {
+ const Ref<Font> *font = theme_font_override.getptr(p_name);
+ if (font) {
+ return *font;
+ }
+ }
+
if (theme_font_cache.has(p_theme_type) && theme_font_cache[p_theme_type].has(p_name)) {
return theme_font_cache[p_theme_type][p_name];
}
@@ -1429,6 +1682,13 @@ Ref<Font> Window::get_theme_font(const StringName &p_name, const StringName &p_t
}
int Window::get_theme_font_size(const StringName &p_name, const StringName &p_theme_type) const {
+ if (p_theme_type == StringName() || p_theme_type == get_class_name() || p_theme_type == theme_type_variation) {
+ const int *font_size = theme_font_size_override.getptr(p_name);
+ if (font_size && (*font_size) > 0) {
+ return *font_size;
+ }
+ }
+
if (theme_font_size_cache.has(p_theme_type) && theme_font_size_cache[p_theme_type].has(p_name)) {
return theme_font_size_cache[p_theme_type][p_name];
}
@@ -1441,6 +1701,13 @@ int Window::get_theme_font_size(const StringName &p_name, const StringName &p_th
}
Color Window::get_theme_color(const StringName &p_name, const StringName &p_theme_type) const {
+ if (p_theme_type == StringName() || p_theme_type == get_class_name() || p_theme_type == theme_type_variation) {
+ const Color *color = theme_color_override.getptr(p_name);
+ if (color) {
+ return *color;
+ }
+ }
+
if (theme_color_cache.has(p_theme_type) && theme_color_cache[p_theme_type].has(p_name)) {
return theme_color_cache[p_theme_type][p_name];
}
@@ -1453,6 +1720,13 @@ Color Window::get_theme_color(const StringName &p_name, const StringName &p_them
}
int Window::get_theme_constant(const StringName &p_name, const StringName &p_theme_type) const {
+ if (p_theme_type == StringName() || p_theme_type == get_class_name() || p_theme_type == theme_type_variation) {
+ const int *constant = theme_constant_override.getptr(p_name);
+ if (constant) {
+ return *constant;
+ }
+ }
+
if (theme_constant_cache.has(p_theme_type) && theme_constant_cache[p_theme_type].has(p_name)) {
return theme_constant_cache[p_theme_type][p_name];
}
@@ -1465,41 +1739,204 @@ int Window::get_theme_constant(const StringName &p_name, const StringName &p_the
}
bool Window::has_theme_icon(const StringName &p_name, const StringName &p_theme_type) const {
+ if (p_theme_type == StringName() || p_theme_type == get_class_name() || p_theme_type == theme_type_variation) {
+ if (has_theme_icon_override(p_name)) {
+ return true;
+ }
+ }
+
List<StringName> theme_types;
theme_owner->get_theme_type_dependencies(this, p_theme_type, &theme_types);
return theme_owner->has_theme_item_in_types(Theme::DATA_TYPE_ICON, p_name, theme_types);
}
bool Window::has_theme_stylebox(const StringName &p_name, const StringName &p_theme_type) const {
+ if (p_theme_type == StringName() || p_theme_type == get_class_name() || p_theme_type == theme_type_variation) {
+ if (has_theme_stylebox_override(p_name)) {
+ return true;
+ }
+ }
+
List<StringName> theme_types;
theme_owner->get_theme_type_dependencies(this, p_theme_type, &theme_types);
return theme_owner->has_theme_item_in_types(Theme::DATA_TYPE_STYLEBOX, p_name, theme_types);
}
bool Window::has_theme_font(const StringName &p_name, const StringName &p_theme_type) const {
+ if (p_theme_type == StringName() || p_theme_type == get_class_name() || p_theme_type == theme_type_variation) {
+ if (has_theme_font_override(p_name)) {
+ return true;
+ }
+ }
+
List<StringName> theme_types;
theme_owner->get_theme_type_dependencies(this, p_theme_type, &theme_types);
return theme_owner->has_theme_item_in_types(Theme::DATA_TYPE_FONT, p_name, theme_types);
}
bool Window::has_theme_font_size(const StringName &p_name, const StringName &p_theme_type) const {
+ if (p_theme_type == StringName() || p_theme_type == get_class_name() || p_theme_type == theme_type_variation) {
+ if (has_theme_font_size_override(p_name)) {
+ return true;
+ }
+ }
+
List<StringName> theme_types;
theme_owner->get_theme_type_dependencies(this, p_theme_type, &theme_types);
return theme_owner->has_theme_item_in_types(Theme::DATA_TYPE_FONT_SIZE, p_name, theme_types);
}
bool Window::has_theme_color(const StringName &p_name, const StringName &p_theme_type) const {
+ if (p_theme_type == StringName() || p_theme_type == get_class_name() || p_theme_type == theme_type_variation) {
+ if (has_theme_color_override(p_name)) {
+ return true;
+ }
+ }
+
List<StringName> theme_types;
theme_owner->get_theme_type_dependencies(this, p_theme_type, &theme_types);
return theme_owner->has_theme_item_in_types(Theme::DATA_TYPE_COLOR, p_name, theme_types);
}
bool Window::has_theme_constant(const StringName &p_name, const StringName &p_theme_type) const {
+ if (p_theme_type == StringName() || p_theme_type == get_class_name() || p_theme_type == theme_type_variation) {
+ if (has_theme_constant_override(p_name)) {
+ return true;
+ }
+ }
+
List<StringName> theme_types;
theme_owner->get_theme_type_dependencies(this, p_theme_type, &theme_types);
return theme_owner->has_theme_item_in_types(Theme::DATA_TYPE_CONSTANT, p_name, theme_types);
}
+/// Local property overrides.
+
+void Window::add_theme_icon_override(const StringName &p_name, const Ref<Texture2D> &p_icon) {
+ ERR_FAIL_COND(!p_icon.is_valid());
+
+ if (theme_icon_override.has(p_name)) {
+ theme_icon_override[p_name]->disconnect("changed", callable_mp(this, &Window::_notify_theme_override_changed));
+ }
+
+ theme_icon_override[p_name] = p_icon;
+ theme_icon_override[p_name]->connect("changed", callable_mp(this, &Window::_notify_theme_override_changed), CONNECT_REFERENCE_COUNTED);
+ _notify_theme_override_changed();
+}
+
+void Window::add_theme_style_override(const StringName &p_name, const Ref<StyleBox> &p_style) {
+ ERR_FAIL_COND(!p_style.is_valid());
+
+ if (theme_style_override.has(p_name)) {
+ theme_style_override[p_name]->disconnect("changed", callable_mp(this, &Window::_notify_theme_override_changed));
+ }
+
+ theme_style_override[p_name] = p_style;
+ theme_style_override[p_name]->connect("changed", callable_mp(this, &Window::_notify_theme_override_changed), CONNECT_REFERENCE_COUNTED);
+ _notify_theme_override_changed();
+}
+
+void Window::add_theme_font_override(const StringName &p_name, const Ref<Font> &p_font) {
+ ERR_FAIL_COND(!p_font.is_valid());
+
+ if (theme_font_override.has(p_name)) {
+ theme_font_override[p_name]->disconnect("changed", callable_mp(this, &Window::_notify_theme_override_changed));
+ }
+
+ theme_font_override[p_name] = p_font;
+ theme_font_override[p_name]->connect("changed", callable_mp(this, &Window::_notify_theme_override_changed), CONNECT_REFERENCE_COUNTED);
+ _notify_theme_override_changed();
+}
+
+void Window::add_theme_font_size_override(const StringName &p_name, int p_font_size) {
+ theme_font_size_override[p_name] = p_font_size;
+ _notify_theme_override_changed();
+}
+
+void Window::add_theme_color_override(const StringName &p_name, const Color &p_color) {
+ theme_color_override[p_name] = p_color;
+ _notify_theme_override_changed();
+}
+
+void Window::add_theme_constant_override(const StringName &p_name, int p_constant) {
+ theme_constant_override[p_name] = p_constant;
+ _notify_theme_override_changed();
+}
+
+void Window::remove_theme_icon_override(const StringName &p_name) {
+ if (theme_icon_override.has(p_name)) {
+ theme_icon_override[p_name]->disconnect("changed", callable_mp(this, &Window::_notify_theme_override_changed));
+ }
+
+ theme_icon_override.erase(p_name);
+ _notify_theme_override_changed();
+}
+
+void Window::remove_theme_style_override(const StringName &p_name) {
+ if (theme_style_override.has(p_name)) {
+ theme_style_override[p_name]->disconnect("changed", callable_mp(this, &Window::_notify_theme_override_changed));
+ }
+
+ theme_style_override.erase(p_name);
+ _notify_theme_override_changed();
+}
+
+void Window::remove_theme_font_override(const StringName &p_name) {
+ if (theme_font_override.has(p_name)) {
+ theme_font_override[p_name]->disconnect("changed", callable_mp(this, &Window::_notify_theme_override_changed));
+ }
+
+ theme_font_override.erase(p_name);
+ _notify_theme_override_changed();
+}
+
+void Window::remove_theme_font_size_override(const StringName &p_name) {
+ theme_font_size_override.erase(p_name);
+ _notify_theme_override_changed();
+}
+
+void Window::remove_theme_color_override(const StringName &p_name) {
+ theme_color_override.erase(p_name);
+ _notify_theme_override_changed();
+}
+
+void Window::remove_theme_constant_override(const StringName &p_name) {
+ theme_constant_override.erase(p_name);
+ _notify_theme_override_changed();
+}
+
+bool Window::has_theme_icon_override(const StringName &p_name) const {
+ const Ref<Texture2D> *tex = theme_icon_override.getptr(p_name);
+ return tex != nullptr;
+}
+
+bool Window::has_theme_stylebox_override(const StringName &p_name) const {
+ const Ref<StyleBox> *style = theme_style_override.getptr(p_name);
+ return style != nullptr;
+}
+
+bool Window::has_theme_font_override(const StringName &p_name) const {
+ const Ref<Font> *font = theme_font_override.getptr(p_name);
+ return font != nullptr;
+}
+
+bool Window::has_theme_font_size_override(const StringName &p_name) const {
+ const int *font_size = theme_font_size_override.getptr(p_name);
+ return font_size != nullptr;
+}
+
+bool Window::has_theme_color_override(const StringName &p_name) const {
+ const Color *color = theme_color_override.getptr(p_name);
+ return color != nullptr;
+}
+
+bool Window::has_theme_constant_override(const StringName &p_name) const {
+ const int *constant = theme_constant_override.getptr(p_name);
+ return constant != nullptr;
+}
+
+/// Default theme properties.
+
float Window::get_theme_default_base_scale() const {
return theme_owner->get_theme_default_base_scale();
}
@@ -1512,6 +1949,21 @@ int Window::get_theme_default_font_size() const {
return theme_owner->get_theme_default_font_size();
}
+/// Bulk actions.
+
+void Window::begin_bulk_theme_override() {
+ bulk_theme_override = true;
+}
+
+void Window::end_bulk_theme_override() {
+ ERR_FAIL_COND(!bulk_theme_override);
+
+ bulk_theme_override = false;
+ _notify_theme_override_changed();
+}
+
+//
+
Rect2i Window::get_parent_rect() const {
ERR_FAIL_COND_V(!is_inside_tree(), Rect2i());
if (is_embedded()) {
@@ -1604,36 +2056,8 @@ bool Window::is_auto_translating() const {
return auto_translate;
}
-void Window::_validate_property(PropertyInfo &p_property) const {
- if (p_property.name == "theme_type_variation") {
- List<StringName> names;
-
- // Only the default theme and the project theme are used for the list of options.
- // This is an imposed limitation to simplify the logic needed to leverage those options.
- ThemeDB::get_singleton()->get_default_theme()->get_type_variation_list(get_class_name(), &names);
- if (ThemeDB::get_singleton()->get_project_theme().is_valid()) {
- ThemeDB::get_singleton()->get_project_theme()->get_type_variation_list(get_class_name(), &names);
- }
- names.sort_custom<StringName::AlphCompare>();
-
- Vector<StringName> unique_names;
- String hint_string;
- for (const StringName &E : names) {
- // Skip duplicate values.
- if (unique_names.has(E)) {
- continue;
- }
-
- hint_string += String(E) + ",";
- unique_names.append(E);
- }
-
- p_property.hint_string = hint_string;
- }
-}
-
Transform2D Window::get_screen_transform() const {
- Transform2D embedder_transform = Transform2D();
+ Transform2D embedder_transform;
if (_get_embedder()) {
embedder_transform.translate_local(get_position());
embedder_transform = _get_embedder()->get_screen_transform() * embedder_transform;
@@ -1655,7 +2079,8 @@ void Window::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_size"), &Window::get_size);
ClassDB::bind_method(D_METHOD("reset_size"), &Window::reset_size);
- ClassDB::bind_method(D_METHOD("get_real_size"), &Window::get_real_size);
+ ClassDB::bind_method(D_METHOD("get_position_with_decorations"), &Window::get_position_with_decorations);
+ ClassDB::bind_method(D_METHOD("get_size_with_decorations"), &Window::get_size_with_decorations);
ClassDB::bind_method(D_METHOD("set_max_size", "max_size"), &Window::set_max_size);
ClassDB::bind_method(D_METHOD("get_max_size"), &Window::get_max_size);
@@ -1725,6 +2150,23 @@ void Window::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_theme_type_variation", "theme_type"), &Window::set_theme_type_variation);
ClassDB::bind_method(D_METHOD("get_theme_type_variation"), &Window::get_theme_type_variation);
+ ClassDB::bind_method(D_METHOD("begin_bulk_theme_override"), &Window::begin_bulk_theme_override);
+ ClassDB::bind_method(D_METHOD("end_bulk_theme_override"), &Window::end_bulk_theme_override);
+
+ ClassDB::bind_method(D_METHOD("add_theme_icon_override", "name", "texture"), &Window::add_theme_icon_override);
+ ClassDB::bind_method(D_METHOD("add_theme_stylebox_override", "name", "stylebox"), &Window::add_theme_style_override);
+ ClassDB::bind_method(D_METHOD("add_theme_font_override", "name", "font"), &Window::add_theme_font_override);
+ ClassDB::bind_method(D_METHOD("add_theme_font_size_override", "name", "font_size"), &Window::add_theme_font_size_override);
+ ClassDB::bind_method(D_METHOD("add_theme_color_override", "name", "color"), &Window::add_theme_color_override);
+ ClassDB::bind_method(D_METHOD("add_theme_constant_override", "name", "constant"), &Window::add_theme_constant_override);
+
+ ClassDB::bind_method(D_METHOD("remove_theme_icon_override", "name"), &Window::remove_theme_icon_override);
+ ClassDB::bind_method(D_METHOD("remove_theme_stylebox_override", "name"), &Window::remove_theme_style_override);
+ ClassDB::bind_method(D_METHOD("remove_theme_font_override", "name"), &Window::remove_theme_font_override);
+ ClassDB::bind_method(D_METHOD("remove_theme_font_size_override", "name"), &Window::remove_theme_font_size_override);
+ ClassDB::bind_method(D_METHOD("remove_theme_color_override", "name"), &Window::remove_theme_color_override);
+ ClassDB::bind_method(D_METHOD("remove_theme_constant_override", "name"), &Window::remove_theme_constant_override);
+
ClassDB::bind_method(D_METHOD("get_theme_icon", "name", "theme_type"), &Window::get_theme_icon, DEFVAL(""));
ClassDB::bind_method(D_METHOD("get_theme_stylebox", "name", "theme_type"), &Window::get_theme_stylebox, DEFVAL(""));
ClassDB::bind_method(D_METHOD("get_theme_font", "name", "theme_type"), &Window::get_theme_font, DEFVAL(""));
@@ -1732,6 +2174,13 @@ void Window::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_theme_color", "name", "theme_type"), &Window::get_theme_color, DEFVAL(""));
ClassDB::bind_method(D_METHOD("get_theme_constant", "name", "theme_type"), &Window::get_theme_constant, DEFVAL(""));
+ ClassDB::bind_method(D_METHOD("has_theme_icon_override", "name"), &Window::has_theme_icon_override);
+ ClassDB::bind_method(D_METHOD("has_theme_stylebox_override", "name"), &Window::has_theme_stylebox_override);
+ ClassDB::bind_method(D_METHOD("has_theme_font_override", "name"), &Window::has_theme_font_override);
+ ClassDB::bind_method(D_METHOD("has_theme_font_size_override", "name"), &Window::has_theme_font_size_override);
+ ClassDB::bind_method(D_METHOD("has_theme_color_override", "name"), &Window::has_theme_color_override);
+ ClassDB::bind_method(D_METHOD("has_theme_constant_override", "name"), &Window::has_theme_constant_override);
+
ClassDB::bind_method(D_METHOD("has_theme_icon", "name", "theme_type"), &Window::has_theme_icon, DEFVAL(""));
ClassDB::bind_method(D_METHOD("has_theme_stylebox", "name", "theme_type"), &Window::has_theme_stylebox, DEFVAL(""));
ClassDB::bind_method(D_METHOD("has_theme_font", "name", "theme_type"), &Window::has_theme_font, DEFVAL(""));
@@ -1785,13 +2234,13 @@ void Window::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::INT, "content_scale_aspect", PROPERTY_HINT_ENUM, "Ignore,Keep,Keep Width,Keep Height,Expand"), "set_content_scale_aspect", "get_content_scale_aspect");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "content_scale_factor"), "set_content_scale_factor", "get_content_scale_factor");
+ ADD_GROUP("Localization", "");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "auto_translate"), "set_auto_translate", "is_auto_translating");
+
ADD_GROUP("Theme", "theme_");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "theme", PROPERTY_HINT_RESOURCE_TYPE, "Theme"), "set_theme", "get_theme");
ADD_PROPERTY(PropertyInfo(Variant::STRING, "theme_type_variation", PROPERTY_HINT_ENUM_SUGGESTION), "set_theme_type_variation", "get_theme_type_variation");
- ADD_GROUP("Auto Translate", "");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL, "auto_translate"), "set_auto_translate", "is_auto_translating");
-
ADD_SIGNAL(MethodInfo("window_input", PropertyInfo(Variant::OBJECT, "event", PROPERTY_HINT_RESOURCE_TYPE, "InputEvent")));
ADD_SIGNAL(MethodInfo("files_dropped", PropertyInfo(Variant::PACKED_STRING_ARRAY, "files")));
ADD_SIGNAL(MethodInfo("mouse_entered"));
@@ -1851,4 +2300,23 @@ Window::Window() {
Window::~Window() {
memdelete(theme_owner);
+
+ // Resources need to be disconnected.
+ for (KeyValue<StringName, Ref<Texture2D>> &E : theme_icon_override) {
+ E.value->disconnect("changed", callable_mp(this, &Window::_notify_theme_override_changed));
+ }
+ for (KeyValue<StringName, Ref<StyleBox>> &E : theme_style_override) {
+ E.value->disconnect("changed", callable_mp(this, &Window::_notify_theme_override_changed));
+ }
+ for (KeyValue<StringName, Ref<Font>> &E : theme_font_override) {
+ E.value->disconnect("changed", callable_mp(this, &Window::_notify_theme_override_changed));
+ }
+
+ // Then override maps can be simply cleared.
+ theme_icon_override.clear();
+ theme_style_override.clear();
+ theme_font_override.clear();
+ theme_font_size_override.clear();
+ theme_color_override.clear();
+ theme_constant_override.clear();
}
diff --git a/scene/main/window.h b/scene/main/window.h
index 03597b309a..5024b42587 100644
--- a/scene/main/window.h
+++ b/scene/main/window.h
@@ -140,6 +140,14 @@ private:
Ref<Theme> theme;
StringName theme_type_variation;
+ bool bulk_theme_override = false;
+ Theme::ThemeIconMap theme_icon_override;
+ Theme::ThemeStyleMap theme_style_override;
+ Theme::ThemeFontMap theme_font_override;
+ Theme::ThemeFontSizeMap theme_font_size_override;
+ Theme::ThemeColorMap theme_color_override;
+ Theme::ThemeConstantMap theme_constant_override;
+
mutable HashMap<StringName, Theme::ThemeIconMap> theme_icon_cache;
mutable HashMap<StringName, Theme::ThemeStyleMap> theme_style_cache;
mutable HashMap<StringName, Theme::ThemeFontMap> theme_font_cache;
@@ -148,6 +156,7 @@ private:
mutable HashMap<StringName, Theme::ThemeConstantMap> theme_constant_cache;
void _theme_changed();
+ void _notify_theme_override_changed();
void _invalidate_theme_cache();
Viewport *embedder = nullptr;
@@ -173,6 +182,10 @@ protected:
virtual Size2 _get_contents_minimum_size() const;
static void _bind_methods();
void _notification(int p_what);
+
+ bool _set(const StringName &p_name, const Variant &p_value);
+ bool _get(const StringName &p_name, Variant &r_ret) const;
+ void _get_property_list(List<PropertyInfo> *p_list) const;
void _validate_property(PropertyInfo &p_property) const;
virtual void add_child_notify(Node *p_child) override;
@@ -198,7 +211,8 @@ public:
Size2i get_size() const;
void reset_size();
- Size2i get_real_size() const;
+ Point2i get_position_with_decorations() const;
+ Size2i get_size_with_decorations() const;
void set_max_size(const Size2i &p_max_size);
Size2i get_max_size() const;
@@ -270,16 +284,6 @@ public:
void popup_centered(const Size2i &p_minsize = Size2i());
void popup_centered_clamped(const Size2i &p_size = Size2i(), float p_fallback_ratio = 0.75);
- void set_theme_owner_node(Node *p_node);
- Node *get_theme_owner_node() const;
- bool has_theme_owner_node() const;
-
- void set_theme(const Ref<Theme> &p_theme);
- Ref<Theme> get_theme() const;
-
- void set_theme_type_variation(const StringName &p_theme_type);
- StringName get_theme_type_variation() const;
-
Size2 get_contents_minimum_size() const;
void grab_focus();
@@ -295,6 +299,35 @@ public:
Rect2i get_usable_parent_rect() const;
+ // Theming.
+
+ void set_theme_owner_node(Node *p_node);
+ Node *get_theme_owner_node() const;
+ bool has_theme_owner_node() const;
+
+ void set_theme(const Ref<Theme> &p_theme);
+ Ref<Theme> get_theme() const;
+
+ void set_theme_type_variation(const StringName &p_theme_type);
+ StringName get_theme_type_variation() const;
+
+ void begin_bulk_theme_override();
+ void end_bulk_theme_override();
+
+ void add_theme_icon_override(const StringName &p_name, const Ref<Texture2D> &p_icon);
+ void add_theme_style_override(const StringName &p_name, const Ref<StyleBox> &p_style);
+ void add_theme_font_override(const StringName &p_name, const Ref<Font> &p_font);
+ void add_theme_font_size_override(const StringName &p_name, int p_font_size);
+ void add_theme_color_override(const StringName &p_name, const Color &p_color);
+ void add_theme_constant_override(const StringName &p_name, int p_constant);
+
+ void remove_theme_icon_override(const StringName &p_name);
+ void remove_theme_style_override(const StringName &p_name);
+ void remove_theme_font_override(const StringName &p_name);
+ void remove_theme_font_size_override(const StringName &p_name);
+ void remove_theme_color_override(const StringName &p_name);
+ void remove_theme_constant_override(const StringName &p_name);
+
Ref<Texture2D> get_theme_icon(const StringName &p_name, const StringName &p_theme_type = StringName()) const;
Ref<StyleBox> get_theme_stylebox(const StringName &p_name, const StringName &p_theme_type = StringName()) const;
Ref<Font> get_theme_font(const StringName &p_name, const StringName &p_theme_type = StringName()) const;
@@ -302,6 +335,13 @@ public:
Color get_theme_color(const StringName &p_name, const StringName &p_theme_type = StringName()) const;
int get_theme_constant(const StringName &p_name, const StringName &p_theme_type = StringName()) const;
+ bool has_theme_icon_override(const StringName &p_name) const;
+ bool has_theme_stylebox_override(const StringName &p_name) const;
+ bool has_theme_font_override(const StringName &p_name) const;
+ bool has_theme_font_size_override(const StringName &p_name) const;
+ bool has_theme_color_override(const StringName &p_name) const;
+ bool has_theme_constant_override(const StringName &p_name) const;
+
bool has_theme_icon(const StringName &p_name, const StringName &p_theme_type = StringName()) const;
bool has_theme_stylebox(const StringName &p_name, const StringName &p_theme_type = StringName()) const;
bool has_theme_font(const StringName &p_name, const StringName &p_theme_type = StringName()) const;
@@ -313,6 +353,8 @@ public:
Ref<Font> get_theme_default_font() const;
int get_theme_default_font_size() const;
+ //
+
virtual Transform2D get_screen_transform() const override;
Rect2i get_parent_rect() const;
diff --git a/scene/property_utils.h b/scene/property_utils.h
index 5ada35fdd7..5b0200b491 100644
--- a/scene/property_utils.h
+++ b/scene/property_utils.h
@@ -42,7 +42,7 @@ public:
// Gets the instance/inheritance states of this node, in order of precedence,
// that is, from the topmost (the most able to override values) to the lowermost
- // (Note that in nested instancing the one with the greatest precedence is the furthest
+ // (Note that in nested instantiation, the one with the greatest precedence is the furthest
// in the tree, since every owner found while traversing towards the root gets a chance
// to override property values.)
static Vector<SceneState::PackState> get_node_states_stack(const Node *p_node, const Node *p_owner = nullptr, bool *r_instantiated_by_owner = nullptr);
diff --git a/scene/register_scene_types.cpp b/scene/register_scene_types.cpp
index 0f55c7b3b8..4f300cb5d6 100644
--- a/scene/register_scene_types.cpp
+++ b/scene/register_scene_types.cpp
@@ -31,7 +31,7 @@
#include "register_scene_types.h"
#include "core/config/project_settings.h"
-#include "core/extension/native_extension_manager.h"
+#include "core/extension/gdextension_manager.h"
#include "core/object/class_db.h"
#include "core/os/os.h"
#include "scene/2d/animated_sprite_2d.h"
@@ -56,6 +56,7 @@
#include "scene/2d/navigation_agent_2d.h"
#include "scene/2d/navigation_link_2d.h"
#include "scene/2d/navigation_obstacle_2d.h"
+#include "scene/2d/navigation_region_2d.h"
#include "scene/2d/parallax_background.h"
#include "scene/2d/parallax_layer.h"
#include "scene/2d/path_2d.h"
@@ -163,6 +164,7 @@
#include "scene/resources/mesh_data_tool.h"
#include "scene/resources/multimesh.h"
#include "scene/resources/navigation_mesh.h"
+#include "scene/resources/navigation_polygon.h"
#include "scene/resources/packed_scene.h"
#include "scene/resources/particle_process_material.h"
#include "scene/resources/physics_material.h"
@@ -827,14 +829,14 @@ void register_scene_types() {
GDREGISTER_CLASS(ConvexPolygonShape3D);
GDREGISTER_CLASS(ConcavePolygonShape3D);
- ClassDB::register_class<SkeletonModificationStack3D>();
- ClassDB::register_class<SkeletonModification3D>();
- ClassDB::register_class<SkeletonModification3DLookAt>();
- ClassDB::register_class<SkeletonModification3DCCDIK>();
- ClassDB::register_class<SkeletonModification3DFABRIK>();
- ClassDB::register_class<SkeletonModification3DJiggle>();
- ClassDB::register_class<SkeletonModification3DTwoBoneIK>();
- ClassDB::register_class<SkeletonModification3DStackHolder>();
+ GDREGISTER_CLASS(SkeletonModificationStack3D);
+ GDREGISTER_CLASS(SkeletonModification3D);
+ GDREGISTER_CLASS(SkeletonModification3DLookAt);
+ GDREGISTER_CLASS(SkeletonModification3DCCDIK);
+ GDREGISTER_CLASS(SkeletonModification3DFABRIK);
+ GDREGISTER_CLASS(SkeletonModification3DJiggle);
+ GDREGISTER_CLASS(SkeletonModification3DTwoBoneIK);
+ GDREGISTER_CLASS(SkeletonModification3DStackHolder);
OS::get_singleton()->yield(); // may take time to init
#endif // _3D_DISABLED
@@ -960,6 +962,7 @@ void register_scene_types() {
ClassDB::add_compatibility_class("Navigation3D", "Node3D");
ClassDB::add_compatibility_class("Navigation2D", "Node2D");
ClassDB::add_compatibility_class("OpenSimplexNoise", "FastNoiseLite");
+ ClassDB::add_compatibility_class("ProximityGroup", "Node3D");
ClassDB::add_compatibility_class("ToolButton", "Button");
ClassDB::add_compatibility_class("YSort", "Node2D");
// Portal and room occlusion was replaced by raster occlusion (OccluderInstance3D node).
diff --git a/scene/resources/animation.cpp b/scene/resources/animation.cpp
index dfd9c6eb2f..37407edc33 100644
--- a/scene/resources/animation.cpp
+++ b/scene/resources/animation.cpp
@@ -888,7 +888,6 @@ int Animation::add_track(TrackType p_type, int p_at_pos) {
}
}
emit_changed();
- emit_signal(SceneStringNames::get_singleton()->tracks_changed);
return p_at_pos;
}
@@ -951,7 +950,6 @@ void Animation::remove_track(int p_track) {
memdelete(t);
tracks.remove_at(p_track);
emit_changed();
- emit_signal(SceneStringNames::get_singleton()->tracks_changed);
}
int Animation::get_track_count() const {
@@ -967,7 +965,6 @@ void Animation::track_set_path(int p_track, const NodePath &p_path) {
ERR_FAIL_INDEX(p_track, tracks.size());
tracks[p_track]->path = p_path;
emit_changed();
- emit_signal(SceneStringNames::get_singleton()->tracks_changed);
}
NodePath Animation::track_get_path(int p_track) const {
@@ -1322,7 +1319,7 @@ Error Animation::blend_shape_track_interpolate(int p_track, double p_time, float
}
void Animation::track_remove_key_at_time(int p_track, double p_time) {
- int idx = track_find_key(p_track, p_time, true);
+ int idx = track_find_key(p_track, p_time, FIND_MODE_APPROX);
ERR_FAIL_COND(idx < 0);
track_remove_key(p_track, idx);
}
@@ -1403,7 +1400,7 @@ void Animation::track_remove_key(int p_track, int p_idx) {
emit_changed();
}
-int Animation::track_find_key(int p_track, double p_time, bool p_exact) const {
+int Animation::track_find_key(int p_track, double p_time, FindMode p_find_mode) const {
ERR_FAIL_INDEX_V(p_track, tracks.size(), -1);
Track *t = tracks[p_track];
@@ -1419,7 +1416,7 @@ int Animation::track_find_key(int p_track, double p_time, bool p_exact) const {
uint32_t key_index;
bool fetch_compressed_success = _fetch_compressed<3>(tt->compressed_track, p_time, key, time, key_next, time_next, &key_index);
ERR_FAIL_COND_V(!fetch_compressed_success, -1);
- if (p_exact && time != p_time) {
+ if ((p_find_mode == FIND_MODE_APPROX && !Math::is_equal_approx(time, p_time)) || (p_find_mode == FIND_MODE_EXACT && time != p_time)) {
return -1;
}
return key_index;
@@ -1429,7 +1426,7 @@ int Animation::track_find_key(int p_track, double p_time, bool p_exact) const {
if (k < 0 || k >= tt->positions.size()) {
return -1;
}
- if (tt->positions[k].time != p_time && p_exact) {
+ if ((p_find_mode == FIND_MODE_APPROX && !Math::is_equal_approx(tt->positions[k].time, p_time)) || (p_find_mode == FIND_MODE_EXACT && tt->positions[k].time != p_time)) {
return -1;
}
return k;
@@ -1446,7 +1443,7 @@ int Animation::track_find_key(int p_track, double p_time, bool p_exact) const {
uint32_t key_index;
bool fetch_compressed_success = _fetch_compressed<3>(rt->compressed_track, p_time, key, time, key_next, time_next, &key_index);
ERR_FAIL_COND_V(!fetch_compressed_success, -1);
- if (p_exact && time != p_time) {
+ if ((p_find_mode == FIND_MODE_APPROX && !Math::is_equal_approx(time, p_time)) || (p_find_mode == FIND_MODE_EXACT && time != p_time)) {
return -1;
}
return key_index;
@@ -1456,7 +1453,7 @@ int Animation::track_find_key(int p_track, double p_time, bool p_exact) const {
if (k < 0 || k >= rt->rotations.size()) {
return -1;
}
- if (rt->rotations[k].time != p_time && p_exact) {
+ if ((p_find_mode == FIND_MODE_APPROX && !Math::is_equal_approx(rt->rotations[k].time, p_time)) || (p_find_mode == FIND_MODE_EXACT && rt->rotations[k].time != p_time)) {
return -1;
}
return k;
@@ -1473,7 +1470,7 @@ int Animation::track_find_key(int p_track, double p_time, bool p_exact) const {
uint32_t key_index;
bool fetch_compressed_success = _fetch_compressed<3>(st->compressed_track, p_time, key, time, key_next, time_next, &key_index);
ERR_FAIL_COND_V(!fetch_compressed_success, -1);
- if (p_exact && time != p_time) {
+ if ((p_find_mode == FIND_MODE_APPROX && !Math::is_equal_approx(time, p_time)) || (p_find_mode == FIND_MODE_EXACT && time != p_time)) {
return -1;
}
return key_index;
@@ -1483,7 +1480,7 @@ int Animation::track_find_key(int p_track, double p_time, bool p_exact) const {
if (k < 0 || k >= st->scales.size()) {
return -1;
}
- if (st->scales[k].time != p_time && p_exact) {
+ if ((p_find_mode == FIND_MODE_APPROX && !Math::is_equal_approx(st->scales[k].time, p_time)) || (p_find_mode == FIND_MODE_EXACT && st->scales[k].time != p_time)) {
return -1;
}
return k;
@@ -1500,7 +1497,7 @@ int Animation::track_find_key(int p_track, double p_time, bool p_exact) const {
uint32_t key_index;
bool fetch_compressed_success = _fetch_compressed<1>(bst->compressed_track, p_time, key, time, key_next, time_next, &key_index);
ERR_FAIL_COND_V(!fetch_compressed_success, -1);
- if (p_exact && time != p_time) {
+ if ((p_find_mode == FIND_MODE_APPROX && !Math::is_equal_approx(time, p_time)) || (p_find_mode == FIND_MODE_EXACT && time != p_time)) {
return -1;
}
return key_index;
@@ -1510,7 +1507,7 @@ int Animation::track_find_key(int p_track, double p_time, bool p_exact) const {
if (k < 0 || k >= bst->blend_shapes.size()) {
return -1;
}
- if (bst->blend_shapes[k].time != p_time && p_exact) {
+ if ((p_find_mode == FIND_MODE_APPROX && !Math::is_equal_approx(bst->blend_shapes[k].time, p_time)) || (p_find_mode == FIND_MODE_EXACT && bst->blend_shapes[k].time != p_time)) {
return -1;
}
return k;
@@ -1522,7 +1519,7 @@ int Animation::track_find_key(int p_track, double p_time, bool p_exact) const {
if (k < 0 || k >= vt->values.size()) {
return -1;
}
- if (vt->values[k].time != p_time && p_exact) {
+ if ((p_find_mode == FIND_MODE_APPROX && !Math::is_equal_approx(vt->values[k].time, p_time)) || (p_find_mode == FIND_MODE_EXACT && vt->values[k].time != p_time)) {
return -1;
}
return k;
@@ -1534,7 +1531,7 @@ int Animation::track_find_key(int p_track, double p_time, bool p_exact) const {
if (k < 0 || k >= mt->methods.size()) {
return -1;
}
- if (mt->methods[k].time != p_time && p_exact) {
+ if ((p_find_mode == FIND_MODE_APPROX && !Math::is_equal_approx(mt->methods[k].time, p_time)) || (p_find_mode == FIND_MODE_EXACT && mt->methods[k].time != p_time)) {
return -1;
}
return k;
@@ -1546,7 +1543,7 @@ int Animation::track_find_key(int p_track, double p_time, bool p_exact) const {
if (k < 0 || k >= bt->values.size()) {
return -1;
}
- if (bt->values[k].time != p_time && p_exact) {
+ if ((p_find_mode == FIND_MODE_APPROX && !Math::is_equal_approx(bt->values[k].time, p_time)) || (p_find_mode == FIND_MODE_EXACT && bt->values[k].time != p_time)) {
return -1;
}
return k;
@@ -1558,7 +1555,7 @@ int Animation::track_find_key(int p_track, double p_time, bool p_exact) const {
if (k < 0 || k >= at->values.size()) {
return -1;
}
- if (at->values[k].time != p_time && p_exact) {
+ if ((p_find_mode == FIND_MODE_APPROX && !Math::is_equal_approx(at->values[k].time, p_time)) || (p_find_mode == FIND_MODE_EXACT && at->values[k].time != p_time)) {
return -1;
}
return k;
@@ -1570,7 +1567,7 @@ int Animation::track_find_key(int p_track, double p_time, bool p_exact) const {
if (k < 0 || k >= at->values.size()) {
return -1;
}
- if (at->values[k].time != p_time && p_exact) {
+ if ((p_find_mode == FIND_MODE_APPROX && !Math::is_equal_approx(at->values[k].time, p_time)) || (p_find_mode == FIND_MODE_EXACT && at->values[k].time != p_time)) {
return -1;
}
return k;
@@ -2467,7 +2464,6 @@ T Animation::_interpolate(const Vector<TKey<T>> &p_keys, double p_time, Interpol
ERR_FAIL_COND_V(idx == -2, T());
- bool result = true;
int next = 0;
real_t c = 0.0;
// prepare for all cases of interpolation
@@ -2599,10 +2595,7 @@ T Animation::_interpolate(const Vector<TKey<T>> &p_keys, double p_time, Interpol
}
if (p_ok) {
- *p_ok = result;
- }
- if (!result) {
- return T();
+ *p_ok = true;
}
real_t tr = p_keys[idx].transition;
@@ -2712,111 +2705,11 @@ Variant Animation::value_track_interpolate(int p_track, double p_time) const {
return Variant();
}
-void Animation::_value_track_get_key_indices_in_range(const ValueTrack *vt, double from_time, double to_time, List<int> *p_indices) const {
- if (from_time != length && to_time == length) {
- to_time = length + CMP_EPSILON; //include a little more if at the end
- }
- int to = _find(vt->values, to_time);
-
- if (to >= 0 && from_time == to_time && vt->values[to].time == from_time) {
- //find exact (0 delta), return if found
- p_indices->push_back(to);
- return;
- }
- // can't really send the events == time, will be sent in the next frame.
- // if event>=len then it will probably never be requested by the anim player.
-
- if (to >= 0 && vt->values[to].time >= to_time) {
- to--;
- }
-
- if (to < 0) {
- return; // not bother
- }
-
- int from = _find(vt->values, from_time);
-
- // position in the right first event.+
- if (from < 0 || vt->values[from].time < from_time) {
- from++;
- }
-
- int max = vt->values.size();
-
- for (int i = from; i <= to; i++) {
- ERR_CONTINUE(i < 0 || i >= max); // shouldn't happen
- p_indices->push_back(i);
- }
-}
-
-void Animation::value_track_get_key_indices(int p_track, double p_time, double p_delta, List<int> *p_indices, int p_pingponged) const {
- ERR_FAIL_INDEX(p_track, tracks.size());
- Track *t = tracks[p_track];
- ERR_FAIL_COND(t->type != TYPE_VALUE);
-
- ValueTrack *vt = static_cast<ValueTrack *>(t);
-
- double from_time = p_time - p_delta;
- double to_time = p_time;
-
- if (from_time > to_time) {
- SWAP(from_time, to_time);
- }
-
- switch (loop_mode) {
- case LOOP_NONE: {
- if (from_time < 0) {
- from_time = 0;
- }
- if (from_time > length) {
- from_time = length;
- }
-
- if (to_time < 0) {
- to_time = 0;
- }
- if (to_time > length) {
- to_time = length;
- }
- } break;
- case LOOP_LINEAR: {
- from_time = Math::fposmod(from_time, length);
- to_time = Math::fposmod(to_time, length);
-
- if (from_time > to_time) {
- // handle loop by splitting
- _value_track_get_key_indices_in_range(vt, from_time, length, p_indices);
- _value_track_get_key_indices_in_range(vt, 0, to_time, p_indices);
- return;
- }
- } break;
- case LOOP_PINGPONG: {
- from_time = Math::pingpong(from_time, length);
- to_time = Math::pingpong(to_time, length);
-
- if (p_pingponged == -1) {
- // handle loop by splitting
- _value_track_get_key_indices_in_range(vt, 0, from_time, p_indices);
- _value_track_get_key_indices_in_range(vt, 0, to_time, p_indices);
- return;
- }
- if (p_pingponged == 1) {
- // handle loop by splitting
- _value_track_get_key_indices_in_range(vt, from_time, length, p_indices);
- _value_track_get_key_indices_in_range(vt, to_time, length, p_indices);
- return;
- }
- } break;
- }
-
- _value_track_get_key_indices_in_range(vt, from_time, to_time, p_indices);
-}
-
void Animation::value_track_set_update_mode(int p_track, UpdateMode p_mode) {
ERR_FAIL_INDEX(p_track, tracks.size());
Track *t = tracks[p_track];
ERR_FAIL_COND(t->type != TYPE_VALUE);
- ERR_FAIL_INDEX((int)p_mode, 4);
+ ERR_FAIL_INDEX((int)p_mode, 3);
ValueTrack *vt = static_cast<ValueTrack *>(t);
vt->update_mode = p_mode;
@@ -2833,47 +2726,74 @@ Animation::UpdateMode Animation::value_track_get_update_mode(int p_track) const
}
template <class T>
-void Animation::_track_get_key_indices_in_range(const Vector<T> &p_array, double from_time, double to_time, List<int> *p_indices) const {
- if (from_time != length && to_time == length) {
- to_time = length + CMP_EPSILON; //include a little more if at the end
+void Animation::_track_get_key_indices_in_range(const Vector<T> &p_array, double from_time, double to_time, List<int> *p_indices, bool p_is_backward) const {
+ int len = p_array.size();
+ if (len == 0) {
+ return;
}
- int to = _find(p_array, to_time);
-
- // can't really send the events == time, will be sent in the next frame.
- // if event>=len then it will probably never be requested by the anim player.
+ int from = 0;
+ int to = len - 1;
- if (to >= 0 && p_array[to].time >= to_time) {
- to--;
+ if (!p_is_backward) {
+ while (p_array[from].time < from_time || Math::is_equal_approx(p_array[from].time, from_time)) {
+ from++;
+ if (to < from) {
+ return;
+ }
+ }
+ while (p_array[to].time > to_time && !Math::is_equal_approx(p_array[to].time, to_time)) {
+ to--;
+ if (to < from) {
+ return;
+ }
+ }
+ } else {
+ while (p_array[from].time < from_time && !Math::is_equal_approx(p_array[from].time, from_time)) {
+ from++;
+ if (to < from) {
+ return;
+ }
+ }
+ while (p_array[to].time > to_time || Math::is_equal_approx(p_array[to].time, to_time)) {
+ to--;
+ if (to < from) {
+ return;
+ }
+ }
}
- if (to < 0) {
- return; // not bother
+ if (from == to) {
+ p_indices->push_back(from);
+ return;
}
- int from = _find(p_array, from_time);
-
- // position in the right first event.+
- if (from < 0 || p_array[from].time < from_time) {
- from++;
+ if (!p_is_backward) {
+ for (int i = from; i <= to; i++) {
+ p_indices->push_back(i);
+ }
+ } else {
+ for (int i = to; i >= to; i--) {
+ p_indices->push_back(i);
+ }
}
+}
- int max = p_array.size();
+void Animation::track_get_key_indices_in_range(int p_track, double p_time, double p_delta, List<int> *p_indices, Animation::LoopedFlag p_looped_flag) const {
+ ERR_FAIL_INDEX(p_track, tracks.size());
- for (int i = from; i <= to; i++) {
- ERR_CONTINUE(i < 0 || i >= max); // shouldn't happen
- p_indices->push_back(i);
+ if (p_delta == 0) {
+ return; // Prevent to get key continuously.
}
-}
-void Animation::track_get_key_indices_in_range(int p_track, double p_time, double p_delta, List<int> *p_indices, int p_pingponged) const {
- ERR_FAIL_INDEX(p_track, tracks.size());
const Track *t = tracks[p_track];
double from_time = p_time - p_delta;
double to_time = p_time;
+ bool is_backward = false;
if (from_time > to_time) {
+ is_backward = true;
SWAP(from_time, to_time);
}
@@ -2902,7 +2822,10 @@ void Animation::track_get_key_indices_in_range(int p_track, double p_time, doubl
}
if (from_time > to_time) {
- // handle loop by splitting
+ // Handle loop by splitting.
+ double anim_end = length + CMP_EPSILON;
+ double anim_start = -CMP_EPSILON;
+
switch (t->type) {
case TYPE_POSITION_3D: {
const PositionTrack *tt = static_cast<const PositionTrack *>(t);
@@ -2910,8 +2833,13 @@ void Animation::track_get_key_indices_in_range(int p_track, double p_time, doubl
_get_compressed_key_indices_in_range<3>(tt->compressed_track, from_time, length, p_indices);
_get_compressed_key_indices_in_range<3>(tt->compressed_track, 0, to_time, p_indices);
} else {
- _track_get_key_indices_in_range(tt->positions, from_time, length, p_indices);
- _track_get_key_indices_in_range(tt->positions, 0, to_time, p_indices);
+ if (!is_backward) {
+ _track_get_key_indices_in_range(tt->positions, from_time, anim_end, p_indices, is_backward);
+ _track_get_key_indices_in_range(tt->positions, anim_start, to_time, p_indices, is_backward);
+ } else {
+ _track_get_key_indices_in_range(tt->positions, anim_start, to_time, p_indices, is_backward);
+ _track_get_key_indices_in_range(tt->positions, from_time, anim_end, p_indices, is_backward);
+ }
}
} break;
case TYPE_ROTATION_3D: {
@@ -2920,8 +2848,13 @@ void Animation::track_get_key_indices_in_range(int p_track, double p_time, doubl
_get_compressed_key_indices_in_range<3>(rt->compressed_track, from_time, length, p_indices);
_get_compressed_key_indices_in_range<3>(rt->compressed_track, 0, to_time, p_indices);
} else {
- _track_get_key_indices_in_range(rt->rotations, from_time, length, p_indices);
- _track_get_key_indices_in_range(rt->rotations, 0, to_time, p_indices);
+ if (!is_backward) {
+ _track_get_key_indices_in_range(rt->rotations, from_time, anim_end, p_indices, is_backward);
+ _track_get_key_indices_in_range(rt->rotations, anim_start, to_time, p_indices, is_backward);
+ } else {
+ _track_get_key_indices_in_range(rt->rotations, anim_start, to_time, p_indices, is_backward);
+ _track_get_key_indices_in_range(rt->rotations, from_time, anim_end, p_indices, is_backward);
+ }
}
} break;
case TYPE_SCALE_3D: {
@@ -2930,8 +2863,13 @@ void Animation::track_get_key_indices_in_range(int p_track, double p_time, doubl
_get_compressed_key_indices_in_range<3>(st->compressed_track, from_time, length, p_indices);
_get_compressed_key_indices_in_range<3>(st->compressed_track, 0, to_time, p_indices);
} else {
- _track_get_key_indices_in_range(st->scales, from_time, length, p_indices);
- _track_get_key_indices_in_range(st->scales, 0, to_time, p_indices);
+ if (!is_backward) {
+ _track_get_key_indices_in_range(st->scales, from_time, anim_end, p_indices, is_backward);
+ _track_get_key_indices_in_range(st->scales, anim_start, to_time, p_indices, is_backward);
+ } else {
+ _track_get_key_indices_in_range(st->scales, anim_start, to_time, p_indices, is_backward);
+ _track_get_key_indices_in_range(st->scales, from_time, anim_end, p_indices, is_backward);
+ }
}
} break;
case TYPE_BLEND_SHAPE: {
@@ -2940,38 +2878,83 @@ void Animation::track_get_key_indices_in_range(int p_track, double p_time, doubl
_get_compressed_key_indices_in_range<1>(bst->compressed_track, from_time, length, p_indices);
_get_compressed_key_indices_in_range<1>(bst->compressed_track, 0, to_time, p_indices);
} else {
- _track_get_key_indices_in_range(bst->blend_shapes, from_time, length, p_indices);
- _track_get_key_indices_in_range(bst->blend_shapes, 0, to_time, p_indices);
+ if (!is_backward) {
+ _track_get_key_indices_in_range(bst->blend_shapes, from_time, anim_end, p_indices, is_backward);
+ _track_get_key_indices_in_range(bst->blend_shapes, anim_start, to_time, p_indices, is_backward);
+ } else {
+ _track_get_key_indices_in_range(bst->blend_shapes, anim_start, to_time, p_indices, is_backward);
+ _track_get_key_indices_in_range(bst->blend_shapes, from_time, anim_end, p_indices, is_backward);
+ }
}
} break;
case TYPE_VALUE: {
const ValueTrack *vt = static_cast<const ValueTrack *>(t);
- _track_get_key_indices_in_range(vt->values, from_time, length, p_indices);
- _track_get_key_indices_in_range(vt->values, 0, to_time, p_indices);
+ if (!is_backward) {
+ _track_get_key_indices_in_range(vt->values, from_time, anim_end, p_indices, is_backward);
+ _track_get_key_indices_in_range(vt->values, anim_start, to_time, p_indices, is_backward);
+ } else {
+ _track_get_key_indices_in_range(vt->values, anim_start, to_time, p_indices, is_backward);
+ _track_get_key_indices_in_range(vt->values, from_time, anim_end, p_indices, is_backward);
+ }
} break;
case TYPE_METHOD: {
const MethodTrack *mt = static_cast<const MethodTrack *>(t);
- _track_get_key_indices_in_range(mt->methods, from_time, length, p_indices);
- _track_get_key_indices_in_range(mt->methods, 0, to_time, p_indices);
+ if (!is_backward) {
+ _track_get_key_indices_in_range(mt->methods, from_time, anim_end, p_indices, is_backward);
+ _track_get_key_indices_in_range(mt->methods, anim_start, to_time, p_indices, is_backward);
+ } else {
+ _track_get_key_indices_in_range(mt->methods, anim_start, to_time, p_indices, is_backward);
+ _track_get_key_indices_in_range(mt->methods, from_time, anim_end, p_indices, is_backward);
+ }
} break;
case TYPE_BEZIER: {
const BezierTrack *bz = static_cast<const BezierTrack *>(t);
- _track_get_key_indices_in_range(bz->values, from_time, length, p_indices);
- _track_get_key_indices_in_range(bz->values, 0, to_time, p_indices);
+ if (!is_backward) {
+ _track_get_key_indices_in_range(bz->values, from_time, anim_end, p_indices, is_backward);
+ _track_get_key_indices_in_range(bz->values, anim_start, to_time, p_indices, is_backward);
+ } else {
+ _track_get_key_indices_in_range(bz->values, anim_start, to_time, p_indices, is_backward);
+ _track_get_key_indices_in_range(bz->values, from_time, anim_end, p_indices, is_backward);
+ }
} break;
case TYPE_AUDIO: {
const AudioTrack *ad = static_cast<const AudioTrack *>(t);
- _track_get_key_indices_in_range(ad->values, from_time, length, p_indices);
- _track_get_key_indices_in_range(ad->values, 0, to_time, p_indices);
+ if (!is_backward) {
+ _track_get_key_indices_in_range(ad->values, from_time, anim_end, p_indices, is_backward);
+ _track_get_key_indices_in_range(ad->values, anim_start, to_time, p_indices, is_backward);
+ } else {
+ _track_get_key_indices_in_range(ad->values, anim_start, to_time, p_indices, is_backward);
+ _track_get_key_indices_in_range(ad->values, from_time, anim_end, p_indices, is_backward);
+ }
} break;
case TYPE_ANIMATION: {
const AnimationTrack *an = static_cast<const AnimationTrack *>(t);
- _track_get_key_indices_in_range(an->values, from_time, length, p_indices);
- _track_get_key_indices_in_range(an->values, 0, to_time, p_indices);
+ if (!is_backward) {
+ _track_get_key_indices_in_range(an->values, from_time, anim_end, p_indices, is_backward);
+ _track_get_key_indices_in_range(an->values, anim_start, to_time, p_indices, is_backward);
+ } else {
+ _track_get_key_indices_in_range(an->values, anim_start, to_time, p_indices, is_backward);
+ _track_get_key_indices_in_range(an->values, from_time, anim_end, p_indices, is_backward);
+ }
} break;
}
return;
}
+
+ // Not from_time > to_time but most recent of looping...
+ if (p_looped_flag != Animation::LOOPED_FLAG_NONE) {
+ if (!is_backward && Math::is_equal_approx(from_time, 0)) {
+ int edge = track_find_key(p_track, 0, FIND_MODE_EXACT);
+ if (edge >= 0) {
+ p_indices->push_back(edge);
+ }
+ } else if (is_backward && Math::is_equal_approx(to_time, length)) {
+ int edge = track_find_key(p_track, length, FIND_MODE_EXACT);
+ if (edge >= 0) {
+ p_indices->push_back(edge);
+ }
+ }
+ }
} break;
case LOOP_PINGPONG: {
if (from_time > length || from_time < 0) {
@@ -2981,160 +2964,164 @@ void Animation::track_get_key_indices_in_range(int p_track, double p_time, doubl
to_time = Math::pingpong(to_time, length);
}
- if ((int)Math::floor(abs(p_delta) / length) % 2 == 0) {
- if (p_pingponged == -1) {
- // handle loop by splitting
- switch (t->type) {
- case TYPE_POSITION_3D: {
- const PositionTrack *tt = static_cast<const PositionTrack *>(t);
- if (tt->compressed_track >= 0) {
- _get_compressed_key_indices_in_range<3>(tt->compressed_track, 0, from_time, p_indices);
- _get_compressed_key_indices_in_range<3>(tt->compressed_track, 0, to_time, p_indices);
- } else {
- _track_get_key_indices_in_range(tt->positions, 0, from_time, p_indices);
- _track_get_key_indices_in_range(tt->positions, 0, to_time, p_indices);
- }
- } break;
- case TYPE_ROTATION_3D: {
- const RotationTrack *rt = static_cast<const RotationTrack *>(t);
- if (rt->compressed_track >= 0) {
- _get_compressed_key_indices_in_range<3>(rt->compressed_track, 0, from_time, p_indices);
- _get_compressed_key_indices_in_range<3>(rt->compressed_track, 0, to_time, p_indices);
- } else {
- _track_get_key_indices_in_range(rt->rotations, 0, from_time, p_indices);
- _track_get_key_indices_in_range(rt->rotations, 0, to_time, p_indices);
- }
- } break;
- case TYPE_SCALE_3D: {
- const ScaleTrack *st = static_cast<const ScaleTrack *>(t);
- if (st->compressed_track >= 0) {
- _get_compressed_key_indices_in_range<3>(st->compressed_track, 0, from_time, p_indices);
- _get_compressed_key_indices_in_range<3>(st->compressed_track, 0, to_time, p_indices);
- } else {
- _track_get_key_indices_in_range(st->scales, 0, from_time, p_indices);
- _track_get_key_indices_in_range(st->scales, 0, to_time, p_indices);
- }
- } break;
- case TYPE_BLEND_SHAPE: {
- const BlendShapeTrack *bst = static_cast<const BlendShapeTrack *>(t);
- if (bst->compressed_track >= 0) {
- _get_compressed_key_indices_in_range<1>(bst->compressed_track, 0, from_time, p_indices);
- _get_compressed_key_indices_in_range<1>(bst->compressed_track, 0, to_time, p_indices);
- } else {
- _track_get_key_indices_in_range(bst->blend_shapes, 0, from_time, p_indices);
- _track_get_key_indices_in_range(bst->blend_shapes, 0, to_time, p_indices);
- }
- } break;
- case TYPE_VALUE: {
- const ValueTrack *vt = static_cast<const ValueTrack *>(t);
- _track_get_key_indices_in_range(vt->values, 0, from_time, p_indices);
- _track_get_key_indices_in_range(vt->values, 0, to_time, p_indices);
- } break;
- case TYPE_METHOD: {
- const MethodTrack *mt = static_cast<const MethodTrack *>(t);
- _track_get_key_indices_in_range(mt->methods, 0, from_time, p_indices);
- _track_get_key_indices_in_range(mt->methods, 0, to_time, p_indices);
- } break;
- case TYPE_BEZIER: {
- const BezierTrack *bz = static_cast<const BezierTrack *>(t);
- _track_get_key_indices_in_range(bz->values, 0, from_time, p_indices);
- _track_get_key_indices_in_range(bz->values, 0, to_time, p_indices);
- } break;
- case TYPE_AUDIO: {
- const AudioTrack *ad = static_cast<const AudioTrack *>(t);
- _track_get_key_indices_in_range(ad->values, 0, from_time, p_indices);
- _track_get_key_indices_in_range(ad->values, 0, to_time, p_indices);
- } break;
- case TYPE_ANIMATION: {
- const AnimationTrack *an = static_cast<const AnimationTrack *>(t);
- _track_get_key_indices_in_range(an->values, 0, from_time, p_indices);
- _track_get_key_indices_in_range(an->values, 0, to_time, p_indices);
- } break;
- }
- return;
+ if (p_looped_flag == Animation::LOOPED_FLAG_START) {
+ // Handle loop by splitting.
+ switch (t->type) {
+ case TYPE_POSITION_3D: {
+ const PositionTrack *tt = static_cast<const PositionTrack *>(t);
+ if (tt->compressed_track >= 0) {
+ _get_compressed_key_indices_in_range<3>(tt->compressed_track, 0, from_time, p_indices);
+ _get_compressed_key_indices_in_range<3>(tt->compressed_track, 0, to_time, p_indices);
+ } else {
+ _track_get_key_indices_in_range(tt->positions, 0, from_time, p_indices, true);
+ _track_get_key_indices_in_range(tt->positions, 0, to_time, p_indices, false);
+ }
+ } break;
+ case TYPE_ROTATION_3D: {
+ const RotationTrack *rt = static_cast<const RotationTrack *>(t);
+ if (rt->compressed_track >= 0) {
+ _get_compressed_key_indices_in_range<3>(rt->compressed_track, 0, from_time, p_indices);
+ _get_compressed_key_indices_in_range<3>(rt->compressed_track, 0, to_time, p_indices);
+ } else {
+ _track_get_key_indices_in_range(rt->rotations, 0, from_time, p_indices, true);
+ _track_get_key_indices_in_range(rt->rotations, 0, to_time, p_indices, false);
+ }
+ } break;
+ case TYPE_SCALE_3D: {
+ const ScaleTrack *st = static_cast<const ScaleTrack *>(t);
+ if (st->compressed_track >= 0) {
+ _get_compressed_key_indices_in_range<3>(st->compressed_track, 0, from_time, p_indices);
+ _get_compressed_key_indices_in_range<3>(st->compressed_track, 0, to_time, p_indices);
+ } else {
+ _track_get_key_indices_in_range(st->scales, 0, from_time, p_indices, true);
+ _track_get_key_indices_in_range(st->scales, 0, to_time, p_indices, false);
+ }
+ } break;
+ case TYPE_BLEND_SHAPE: {
+ const BlendShapeTrack *bst = static_cast<const BlendShapeTrack *>(t);
+ if (bst->compressed_track >= 0) {
+ _get_compressed_key_indices_in_range<1>(bst->compressed_track, 0, from_time, p_indices);
+ _get_compressed_key_indices_in_range<1>(bst->compressed_track, 0, to_time, p_indices);
+ } else {
+ _track_get_key_indices_in_range(bst->blend_shapes, 0, from_time, p_indices, true);
+ _track_get_key_indices_in_range(bst->blend_shapes, 0, to_time, p_indices, false);
+ }
+ } break;
+ case TYPE_VALUE: {
+ const ValueTrack *vt = static_cast<const ValueTrack *>(t);
+ _track_get_key_indices_in_range(vt->values, 0, from_time, p_indices, true);
+ _track_get_key_indices_in_range(vt->values, 0, to_time, p_indices, false);
+ } break;
+ case TYPE_METHOD: {
+ const MethodTrack *mt = static_cast<const MethodTrack *>(t);
+ _track_get_key_indices_in_range(mt->methods, 0, from_time, p_indices, true);
+ _track_get_key_indices_in_range(mt->methods, 0, to_time, p_indices, false);
+ } break;
+ case TYPE_BEZIER: {
+ const BezierTrack *bz = static_cast<const BezierTrack *>(t);
+ _track_get_key_indices_in_range(bz->values, 0, from_time, p_indices, true);
+ _track_get_key_indices_in_range(bz->values, 0, to_time, p_indices, false);
+ } break;
+ case TYPE_AUDIO: {
+ const AudioTrack *ad = static_cast<const AudioTrack *>(t);
+ _track_get_key_indices_in_range(ad->values, 0, from_time, p_indices, true);
+ _track_get_key_indices_in_range(ad->values, 0, to_time, p_indices, false);
+ } break;
+ case TYPE_ANIMATION: {
+ const AnimationTrack *an = static_cast<const AnimationTrack *>(t);
+ _track_get_key_indices_in_range(an->values, 0, from_time, p_indices, true);
+ _track_get_key_indices_in_range(an->values, 0, to_time, p_indices, false);
+ } break;
}
- if (p_pingponged == 1) {
- // handle loop by splitting
- switch (t->type) {
- case TYPE_POSITION_3D: {
- const PositionTrack *tt = static_cast<const PositionTrack *>(t);
- if (tt->compressed_track >= 0) {
- _get_compressed_key_indices_in_range<3>(tt->compressed_track, from_time, length, p_indices);
- _get_compressed_key_indices_in_range<3>(tt->compressed_track, to_time, length, p_indices);
- } else {
- _track_get_key_indices_in_range(tt->positions, from_time, length, p_indices);
- _track_get_key_indices_in_range(tt->positions, to_time, length, p_indices);
- }
- } break;
- case TYPE_ROTATION_3D: {
- const RotationTrack *rt = static_cast<const RotationTrack *>(t);
- if (rt->compressed_track >= 0) {
- _get_compressed_key_indices_in_range<3>(rt->compressed_track, from_time, length, p_indices);
- _get_compressed_key_indices_in_range<3>(rt->compressed_track, to_time, length, p_indices);
- } else {
- _track_get_key_indices_in_range(rt->rotations, from_time, length, p_indices);
- _track_get_key_indices_in_range(rt->rotations, to_time, length, p_indices);
- }
- } break;
- case TYPE_SCALE_3D: {
- const ScaleTrack *st = static_cast<const ScaleTrack *>(t);
- if (st->compressed_track >= 0) {
- _get_compressed_key_indices_in_range<3>(st->compressed_track, from_time, length, p_indices);
- _get_compressed_key_indices_in_range<3>(st->compressed_track, to_time, length, p_indices);
- } else {
- _track_get_key_indices_in_range(st->scales, from_time, length, p_indices);
- _track_get_key_indices_in_range(st->scales, to_time, length, p_indices);
- }
- } break;
- case TYPE_BLEND_SHAPE: {
- const BlendShapeTrack *bst = static_cast<const BlendShapeTrack *>(t);
- if (bst->compressed_track >= 0) {
- _get_compressed_key_indices_in_range<1>(bst->compressed_track, from_time, length, p_indices);
- _get_compressed_key_indices_in_range<1>(bst->compressed_track, to_time, length, p_indices);
- } else {
- _track_get_key_indices_in_range(bst->blend_shapes, from_time, length, p_indices);
- _track_get_key_indices_in_range(bst->blend_shapes, to_time, length, p_indices);
- }
- } break;
- case TYPE_VALUE: {
- const ValueTrack *vt = static_cast<const ValueTrack *>(t);
- _track_get_key_indices_in_range(vt->values, from_time, length, p_indices);
- _track_get_key_indices_in_range(vt->values, to_time, length, p_indices);
- } break;
- case TYPE_METHOD: {
- const MethodTrack *mt = static_cast<const MethodTrack *>(t);
- _track_get_key_indices_in_range(mt->methods, from_time, length, p_indices);
- _track_get_key_indices_in_range(mt->methods, to_time, length, p_indices);
- } break;
- case TYPE_BEZIER: {
- const BezierTrack *bz = static_cast<const BezierTrack *>(t);
- _track_get_key_indices_in_range(bz->values, from_time, length, p_indices);
- _track_get_key_indices_in_range(bz->values, to_time, length, p_indices);
- } break;
- case TYPE_AUDIO: {
- const AudioTrack *ad = static_cast<const AudioTrack *>(t);
- _track_get_key_indices_in_range(ad->values, from_time, length, p_indices);
- _track_get_key_indices_in_range(ad->values, to_time, length, p_indices);
- } break;
- case TYPE_ANIMATION: {
- const AnimationTrack *an = static_cast<const AnimationTrack *>(t);
- _track_get_key_indices_in_range(an->values, from_time, length, p_indices);
- _track_get_key_indices_in_range(an->values, to_time, length, p_indices);
- } break;
- }
- return;
+ return;
+ }
+ if (p_looped_flag == Animation::LOOPED_FLAG_END) {
+ // Handle loop by splitting.
+ switch (t->type) {
+ case TYPE_POSITION_3D: {
+ const PositionTrack *tt = static_cast<const PositionTrack *>(t);
+ if (tt->compressed_track >= 0) {
+ _get_compressed_key_indices_in_range<3>(tt->compressed_track, from_time, length, p_indices);
+ _get_compressed_key_indices_in_range<3>(tt->compressed_track, to_time, length, p_indices);
+ } else {
+ _track_get_key_indices_in_range(tt->positions, from_time, length, p_indices, false);
+ _track_get_key_indices_in_range(tt->positions, to_time, length, p_indices, true);
+ }
+ } break;
+ case TYPE_ROTATION_3D: {
+ const RotationTrack *rt = static_cast<const RotationTrack *>(t);
+ if (rt->compressed_track >= 0) {
+ _get_compressed_key_indices_in_range<3>(rt->compressed_track, from_time, length, p_indices);
+ _get_compressed_key_indices_in_range<3>(rt->compressed_track, to_time, length, p_indices);
+ } else {
+ _track_get_key_indices_in_range(rt->rotations, from_time, length, p_indices, false);
+ _track_get_key_indices_in_range(rt->rotations, to_time, length, p_indices, true);
+ }
+ } break;
+ case TYPE_SCALE_3D: {
+ const ScaleTrack *st = static_cast<const ScaleTrack *>(t);
+ if (st->compressed_track >= 0) {
+ _get_compressed_key_indices_in_range<3>(st->compressed_track, from_time, length, p_indices);
+ _get_compressed_key_indices_in_range<3>(st->compressed_track, to_time, length, p_indices);
+ } else {
+ _track_get_key_indices_in_range(st->scales, from_time, length, p_indices, false);
+ _track_get_key_indices_in_range(st->scales, to_time, length, p_indices, true);
+ }
+ } break;
+ case TYPE_BLEND_SHAPE: {
+ const BlendShapeTrack *bst = static_cast<const BlendShapeTrack *>(t);
+ if (bst->compressed_track >= 0) {
+ _get_compressed_key_indices_in_range<1>(bst->compressed_track, from_time, length, p_indices);
+ _get_compressed_key_indices_in_range<1>(bst->compressed_track, to_time, length, p_indices);
+ } else {
+ _track_get_key_indices_in_range(bst->blend_shapes, from_time, length, p_indices, false);
+ _track_get_key_indices_in_range(bst->blend_shapes, to_time, length, p_indices, true);
+ }
+ } break;
+ case TYPE_VALUE: {
+ const ValueTrack *vt = static_cast<const ValueTrack *>(t);
+ _track_get_key_indices_in_range(vt->values, from_time, length, p_indices, false);
+ _track_get_key_indices_in_range(vt->values, to_time, length, p_indices, true);
+ } break;
+ case TYPE_METHOD: {
+ const MethodTrack *mt = static_cast<const MethodTrack *>(t);
+ _track_get_key_indices_in_range(mt->methods, from_time, length, p_indices, false);
+ _track_get_key_indices_in_range(mt->methods, to_time, length, p_indices, true);
+ } break;
+ case TYPE_BEZIER: {
+ const BezierTrack *bz = static_cast<const BezierTrack *>(t);
+ _track_get_key_indices_in_range(bz->values, from_time, length, p_indices, false);
+ _track_get_key_indices_in_range(bz->values, to_time, length, p_indices, true);
+ } break;
+ case TYPE_AUDIO: {
+ const AudioTrack *ad = static_cast<const AudioTrack *>(t);
+ _track_get_key_indices_in_range(ad->values, from_time, length, p_indices, false);
+ _track_get_key_indices_in_range(ad->values, to_time, length, p_indices, true);
+ } break;
+ case TYPE_ANIMATION: {
+ const AnimationTrack *an = static_cast<const AnimationTrack *>(t);
+ _track_get_key_indices_in_range(an->values, from_time, length, p_indices, false);
+ _track_get_key_indices_in_range(an->values, to_time, length, p_indices, true);
+ } break;
}
+ return;
+ }
+
+ // The edge will be pingponged in the next frame and processed there, so let's ignore it now...
+ if (!is_backward && Math::is_equal_approx(to_time, length)) {
+ to_time -= CMP_EPSILON;
+ } else if (is_backward && Math::is_equal_approx(from_time, 0)) {
+ from_time += CMP_EPSILON;
}
} break;
}
-
switch (t->type) {
case TYPE_POSITION_3D: {
const PositionTrack *tt = static_cast<const PositionTrack *>(t);
if (tt->compressed_track >= 0) {
_get_compressed_key_indices_in_range<3>(tt->compressed_track, from_time, to_time - from_time, p_indices);
} else {
- _track_get_key_indices_in_range(tt->positions, from_time, to_time, p_indices);
+ _track_get_key_indices_in_range(tt->positions, from_time, to_time, p_indices, is_backward);
}
} break;
case TYPE_ROTATION_3D: {
@@ -3142,7 +3129,7 @@ void Animation::track_get_key_indices_in_range(int p_track, double p_time, doubl
if (rt->compressed_track >= 0) {
_get_compressed_key_indices_in_range<3>(rt->compressed_track, from_time, to_time - from_time, p_indices);
} else {
- _track_get_key_indices_in_range(rt->rotations, from_time, to_time, p_indices);
+ _track_get_key_indices_in_range(rt->rotations, from_time, to_time, p_indices, is_backward);
}
} break;
case TYPE_SCALE_3D: {
@@ -3150,7 +3137,7 @@ void Animation::track_get_key_indices_in_range(int p_track, double p_time, doubl
if (st->compressed_track >= 0) {
_get_compressed_key_indices_in_range<3>(st->compressed_track, from_time, to_time - from_time, p_indices);
} else {
- _track_get_key_indices_in_range(st->scales, from_time, to_time, p_indices);
+ _track_get_key_indices_in_range(st->scales, from_time, to_time, p_indices, is_backward);
}
} break;
case TYPE_BLEND_SHAPE: {
@@ -3158,136 +3145,32 @@ void Animation::track_get_key_indices_in_range(int p_track, double p_time, doubl
if (bst->compressed_track >= 0) {
_get_compressed_key_indices_in_range<1>(bst->compressed_track, from_time, to_time - from_time, p_indices);
} else {
- _track_get_key_indices_in_range(bst->blend_shapes, from_time, to_time, p_indices);
+ _track_get_key_indices_in_range(bst->blend_shapes, from_time, to_time, p_indices, is_backward);
}
} break;
case TYPE_VALUE: {
const ValueTrack *vt = static_cast<const ValueTrack *>(t);
- _track_get_key_indices_in_range(vt->values, from_time, to_time, p_indices);
+ _track_get_key_indices_in_range(vt->values, from_time, to_time, p_indices, is_backward);
} break;
case TYPE_METHOD: {
const MethodTrack *mt = static_cast<const MethodTrack *>(t);
- _track_get_key_indices_in_range(mt->methods, from_time, to_time, p_indices);
+ _track_get_key_indices_in_range(mt->methods, from_time, to_time, p_indices, is_backward);
} break;
case TYPE_BEZIER: {
const BezierTrack *bz = static_cast<const BezierTrack *>(t);
- _track_get_key_indices_in_range(bz->values, from_time, to_time, p_indices);
+ _track_get_key_indices_in_range(bz->values, from_time, to_time, p_indices, is_backward);
} break;
case TYPE_AUDIO: {
const AudioTrack *ad = static_cast<const AudioTrack *>(t);
- _track_get_key_indices_in_range(ad->values, from_time, to_time, p_indices);
+ _track_get_key_indices_in_range(ad->values, from_time, to_time, p_indices, is_backward);
} break;
case TYPE_ANIMATION: {
const AnimationTrack *an = static_cast<const AnimationTrack *>(t);
- _track_get_key_indices_in_range(an->values, from_time, to_time, p_indices);
+ _track_get_key_indices_in_range(an->values, from_time, to_time, p_indices, is_backward);
} break;
}
}
-void Animation::_method_track_get_key_indices_in_range(const MethodTrack *mt, double from_time, double to_time, List<int> *p_indices) const {
- if (from_time != length && to_time == length) {
- to_time = length + CMP_EPSILON; //include a little more if at the end
- }
-
- int to = _find(mt->methods, to_time);
-
- // can't really send the events == time, will be sent in the next frame.
- // if event>=len then it will probably never be requested by the anim player.
-
- if (to >= 0 && mt->methods[to].time >= to_time) {
- to--;
- }
-
- if (to < 0) {
- return; // not bother
- }
-
- int from = _find(mt->methods, from_time);
-
- // position in the right first event.+
- if (from < 0 || mt->methods[from].time < from_time) {
- from++;
- }
-
- int max = mt->methods.size();
-
- for (int i = from; i <= to; i++) {
- ERR_CONTINUE(i < 0 || i >= max); // shouldn't happen
- p_indices->push_back(i);
- }
-}
-
-void Animation::method_track_get_key_indices(int p_track, double p_time, double p_delta, List<int> *p_indices, int p_pingponged) const {
- ERR_FAIL_INDEX(p_track, tracks.size());
- Track *t = tracks[p_track];
- ERR_FAIL_COND(t->type != TYPE_METHOD);
-
- MethodTrack *mt = static_cast<MethodTrack *>(t);
-
- double from_time = p_time - p_delta;
- double to_time = p_time;
-
- if (from_time > to_time) {
- SWAP(from_time, to_time);
- }
-
- switch (loop_mode) {
- case LOOP_NONE: {
- if (from_time < 0) {
- from_time = 0;
- }
- if (from_time > length) {
- from_time = length;
- }
-
- if (to_time < 0) {
- to_time = 0;
- }
- if (to_time > length) {
- to_time = length;
- }
- } break;
- case LOOP_LINEAR: {
- if (from_time > length || from_time < 0) {
- from_time = Math::fposmod(from_time, length);
- }
- if (to_time > length || to_time < 0) {
- to_time = Math::fposmod(to_time, length);
- }
-
- if (from_time > to_time) {
- // handle loop by splitting
- _method_track_get_key_indices_in_range(mt, from_time, length, p_indices);
- _method_track_get_key_indices_in_range(mt, 0, to_time, p_indices);
- return;
- }
- } break;
- case LOOP_PINGPONG: {
- if (from_time > length || from_time < 0) {
- from_time = Math::pingpong(from_time, length);
- }
- if (to_time > length || to_time < 0) {
- to_time = Math::pingpong(to_time, length);
- }
-
- if (p_pingponged == -1) {
- _method_track_get_key_indices_in_range(mt, 0, from_time, p_indices);
- _method_track_get_key_indices_in_range(mt, 0, to_time, p_indices);
- return;
- }
- if (p_pingponged == 1) {
- _method_track_get_key_indices_in_range(mt, from_time, length, p_indices);
- _method_track_get_key_indices_in_range(mt, to_time, length, p_indices);
- return;
- }
- } break;
- default:
- break;
- }
-
- _method_track_get_key_indices_in_range(mt, from_time, to_time, p_indices);
-}
-
Vector<Variant> Animation::method_track_get_params(int p_track, int p_key_idx) const {
ERR_FAIL_INDEX_V(p_track, tracks.size(), Vector<Variant>());
Track *t = tracks[p_track];
@@ -3834,7 +3717,6 @@ void Animation::track_move_up(int p_track) {
}
emit_changed();
- emit_signal(SceneStringNames::get_singleton()->tracks_changed);
}
void Animation::track_move_down(int p_track) {
@@ -3843,7 +3725,6 @@ void Animation::track_move_down(int p_track) {
}
emit_changed();
- emit_signal(SceneStringNames::get_singleton()->tracks_changed);
}
void Animation::track_move_to(int p_track, int p_to_index) {
@@ -3859,7 +3740,6 @@ void Animation::track_move_to(int p_track, int p_to_index) {
tracks.insert(p_to_index > p_track ? p_to_index - 1 : p_to_index, track);
emit_changed();
- emit_signal(SceneStringNames::get_singleton()->tracks_changed);
}
void Animation::track_swap(int p_track, int p_with_track) {
@@ -3871,7 +3751,6 @@ void Animation::track_swap(int p_track, int p_with_track) {
SWAP(tracks.write[p_track], tracks.write[p_with_track]);
emit_changed();
- emit_signal(SceneStringNames::get_singleton()->tracks_changed);
}
void Animation::set_step(real_t p_step) {
@@ -3939,7 +3818,7 @@ void Animation::_bind_methods() {
ClassDB::bind_method(D_METHOD("track_get_key_count", "track_idx"), &Animation::track_get_key_count);
ClassDB::bind_method(D_METHOD("track_get_key_value", "track_idx", "key_idx"), &Animation::track_get_key_value);
ClassDB::bind_method(D_METHOD("track_get_key_time", "track_idx", "key_idx"), &Animation::track_get_key_time);
- ClassDB::bind_method(D_METHOD("track_find_key", "track_idx", "time", "exact"), &Animation::track_find_key, DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("track_find_key", "track_idx", "time", "find_mode"), &Animation::track_find_key, DEFVAL(FIND_MODE_NEAREST));
ClassDB::bind_method(D_METHOD("track_set_interpolation_type", "track_idx", "interpolation"), &Animation::track_set_interpolation_type);
ClassDB::bind_method(D_METHOD("track_get_interpolation_type", "track_idx"), &Animation::track_get_interpolation_type);
@@ -3952,10 +3831,8 @@ void Animation::_bind_methods() {
ClassDB::bind_method(D_METHOD("value_track_set_update_mode", "track_idx", "mode"), &Animation::value_track_set_update_mode);
ClassDB::bind_method(D_METHOD("value_track_get_update_mode", "track_idx"), &Animation::value_track_get_update_mode);
- ClassDB::bind_method(D_METHOD("value_track_get_key_indices", "track_idx", "time_sec", "delta"), &Animation::_value_track_get_key_indices);
ClassDB::bind_method(D_METHOD("value_track_interpolate", "track_idx", "time_sec"), &Animation::value_track_interpolate);
- ClassDB::bind_method(D_METHOD("method_track_get_key_indices", "track_idx", "time_sec", "delta"), &Animation::_method_track_get_key_indices);
ClassDB::bind_method(D_METHOD("method_track_get_name", "track_idx", "key_idx"), &Animation::method_track_get_name);
ClassDB::bind_method(D_METHOD("method_track_get_params", "track_idx", "key_idx"), &Animation::method_track_get_params);
@@ -4001,8 +3878,6 @@ void Animation::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::INT, "loop_mode", PROPERTY_HINT_ENUM, "None,Linear,Ping-Pong"), "set_loop_mode", "get_loop_mode");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "step", PROPERTY_HINT_RANGE, "0,4096,0.001,suffix:s"), "set_step", "get_step");
- ADD_SIGNAL(MethodInfo("tracks_changed"));
-
BIND_ENUM_CONSTANT(TYPE_VALUE);
BIND_ENUM_CONSTANT(TYPE_POSITION_3D);
BIND_ENUM_CONSTANT(TYPE_ROTATION_3D);
@@ -4021,12 +3896,19 @@ void Animation::_bind_methods() {
BIND_ENUM_CONSTANT(UPDATE_CONTINUOUS);
BIND_ENUM_CONSTANT(UPDATE_DISCRETE);
- BIND_ENUM_CONSTANT(UPDATE_TRIGGER);
BIND_ENUM_CONSTANT(UPDATE_CAPTURE);
BIND_ENUM_CONSTANT(LOOP_NONE);
BIND_ENUM_CONSTANT(LOOP_LINEAR);
BIND_ENUM_CONSTANT(LOOP_PINGPONG);
+
+ BIND_ENUM_CONSTANT(LOOPED_FLAG_NONE);
+ BIND_ENUM_CONSTANT(LOOPED_FLAG_END);
+ BIND_ENUM_CONSTANT(LOOPED_FLAG_START);
+
+ BIND_ENUM_CONSTANT(FIND_MODE_NEAREST);
+ BIND_ENUM_CONSTANT(FIND_MODE_APPROX);
+ BIND_ENUM_CONSTANT(FIND_MODE_EXACT);
}
void Animation::clear() {
@@ -4041,7 +3923,6 @@ void Animation::clear() {
compression.pages.clear();
compression.fps = 120;
emit_changed();
- emit_signal(SceneStringNames::get_singleton()->tracks_changed);
}
bool Animation::_float_track_optimize_key(const TKey<float> t0, const TKey<float> t1, const TKey<float> t2, real_t p_allowed_velocity_err, real_t p_allowed_precision_error) {
@@ -4964,7 +4845,7 @@ void Animation::compress(uint32_t p_page_size, uint32_t p_fps, float p_split_tol
if (rollback || best_frame == FRAME_MAX) {
// Commit the page if had to rollback or if no track was found
- print_animc("\tCommiting page..");
+ print_animc("\tCommiting page...");
// The end frame for the page depends entirely on whether its valid or
// no more keys were found.
@@ -5851,18 +5732,18 @@ Variant Animation::interpolate_variant(const Variant &a, const Variant &b, float
return dst;
}
case Variant::PACKED_INT32_ARRAY: {
- const Vector<int32_t> *arr_a = Object::cast_to<Vector<int32_t>>(a);
- const Vector<int32_t> *arr_b = Object::cast_to<Vector<int32_t>>(b);
- int32_t sz = arr_a->size();
- if (sz == 0 || arr_b->size() != sz) {
+ const Vector<int32_t> arr_a = a;
+ const Vector<int32_t> arr_b = b;
+ int32_t sz = arr_a.size();
+ if (sz == 0 || arr_b.size() != sz) {
return a;
} else {
Vector<int32_t> v;
v.resize(sz);
{
int32_t *vw = v.ptrw();
- const int32_t *ar = arr_a->ptr();
- const int32_t *br = arr_b->ptr();
+ const int32_t *ar = arr_a.ptr();
+ const int32_t *br = arr_b.ptr();
Variant va;
for (int32_t i = 0; i < sz; i++) {
@@ -5874,18 +5755,18 @@ Variant Animation::interpolate_variant(const Variant &a, const Variant &b, float
}
}
case Variant::PACKED_INT64_ARRAY: {
- const Vector<int64_t> *arr_a = Object::cast_to<Vector<int64_t>>(a);
- const Vector<int64_t> *arr_b = Object::cast_to<Vector<int64_t>>(b);
- int64_t sz = arr_a->size();
- if (sz == 0 || arr_b->size() != sz) {
+ const Vector<int64_t> arr_a = a;
+ const Vector<int64_t> arr_b = b;
+ int64_t sz = arr_a.size();
+ if (sz == 0 || arr_b.size() != sz) {
return a;
} else {
Vector<int64_t> v;
v.resize(sz);
{
int64_t *vw = v.ptrw();
- const int64_t *ar = arr_a->ptr();
- const int64_t *br = arr_b->ptr();
+ const int64_t *ar = arr_a.ptr();
+ const int64_t *br = arr_b.ptr();
Variant va;
for (int64_t i = 0; i < sz; i++) {
@@ -5897,18 +5778,18 @@ Variant Animation::interpolate_variant(const Variant &a, const Variant &b, float
}
}
case Variant::PACKED_FLOAT32_ARRAY: {
- const Vector<float> *arr_a = Object::cast_to<Vector<float>>(a);
- const Vector<float> *arr_b = Object::cast_to<Vector<float>>(b);
- int sz = arr_a->size();
- if (sz == 0 || arr_b->size() != sz) {
+ const Vector<float> arr_a = a;
+ const Vector<float> arr_b = b;
+ int sz = arr_a.size();
+ if (sz == 0 || arr_b.size() != sz) {
return a;
} else {
Vector<float> v;
v.resize(sz);
{
float *vw = v.ptrw();
- const float *ar = arr_a->ptr();
- const float *br = arr_b->ptr();
+ const float *ar = arr_a.ptr();
+ const float *br = arr_b.ptr();
Variant va;
for (int i = 0; i < sz; i++) {
@@ -5920,18 +5801,18 @@ Variant Animation::interpolate_variant(const Variant &a, const Variant &b, float
}
}
case Variant::PACKED_FLOAT64_ARRAY: {
- const Vector<double> *arr_a = Object::cast_to<Vector<double>>(a);
- const Vector<double> *arr_b = Object::cast_to<Vector<double>>(b);
- int sz = arr_a->size();
- if (sz == 0 || arr_b->size() != sz) {
+ const Vector<double> arr_a = a;
+ const Vector<double> arr_b = b;
+ int sz = arr_a.size();
+ if (sz == 0 || arr_b.size() != sz) {
return a;
} else {
Vector<double> v;
v.resize(sz);
{
double *vw = v.ptrw();
- const double *ar = arr_a->ptr();
- const double *br = arr_b->ptr();
+ const double *ar = arr_a.ptr();
+ const double *br = arr_b.ptr();
Variant va;
for (int i = 0; i < sz; i++) {
@@ -5943,18 +5824,18 @@ Variant Animation::interpolate_variant(const Variant &a, const Variant &b, float
}
}
case Variant::PACKED_VECTOR2_ARRAY: {
- const Vector<Vector2> *arr_a = Object::cast_to<Vector<Vector2>>(a);
- const Vector<Vector2> *arr_b = Object::cast_to<Vector<Vector2>>(b);
- int sz = arr_a->size();
- if (sz == 0 || arr_b->size() != sz) {
+ const Vector<Vector2> arr_a = a;
+ const Vector<Vector2> arr_b = b;
+ int sz = arr_a.size();
+ if (sz == 0 || arr_b.size() != sz) {
return a;
} else {
Vector<Vector2> v;
v.resize(sz);
{
Vector2 *vw = v.ptrw();
- const Vector2 *ar = arr_a->ptr();
- const Vector2 *br = arr_b->ptr();
+ const Vector2 *ar = arr_a.ptr();
+ const Vector2 *br = arr_b.ptr();
for (int i = 0; i < sz; i++) {
vw[i] = ar[i].lerp(br[i], c);
@@ -5964,18 +5845,18 @@ Variant Animation::interpolate_variant(const Variant &a, const Variant &b, float
}
}
case Variant::PACKED_VECTOR3_ARRAY: {
- const Vector<Vector3> *arr_a = Object::cast_to<Vector<Vector3>>(a);
- const Vector<Vector3> *arr_b = Object::cast_to<Vector<Vector3>>(b);
- int sz = arr_a->size();
- if (sz == 0 || arr_b->size() != sz) {
+ const Vector<Vector3> arr_a = a;
+ const Vector<Vector3> arr_b = b;
+ int sz = arr_a.size();
+ if (sz == 0 || arr_b.size() != sz) {
return a;
} else {
Vector<Vector3> v;
v.resize(sz);
{
Vector3 *vw = v.ptrw();
- const Vector3 *ar = arr_a->ptr();
- const Vector3 *br = arr_b->ptr();
+ const Vector3 *ar = arr_a.ptr();
+ const Vector3 *br = arr_b.ptr();
for (int i = 0; i < sz; i++) {
vw[i] = ar[i].lerp(br[i], c);
@@ -5985,18 +5866,18 @@ Variant Animation::interpolate_variant(const Variant &a, const Variant &b, float
}
}
case Variant::PACKED_COLOR_ARRAY: {
- const Vector<Color> *arr_a = Object::cast_to<Vector<Color>>(a);
- const Vector<Color> *arr_b = Object::cast_to<Vector<Color>>(b);
- int sz = arr_a->size();
- if (sz == 0 || arr_b->size() != sz) {
+ const Vector<Color> arr_a = a;
+ const Vector<Color> arr_b = b;
+ int sz = arr_a.size();
+ if (sz == 0 || arr_b.size() != sz) {
return a;
} else {
Vector<Color> v;
v.resize(sz);
{
Color *vw = v.ptrw();
- const Color *ar = arr_a->ptr();
- const Color *br = arr_b->ptr();
+ const Color *ar = arr_a.ptr();
+ const Color *br = arr_b.ptr();
for (int i = 0; i < sz; i++) {
vw[i] = ar[i].lerp(br[i], c);
@@ -6011,7 +5892,8 @@ Variant Animation::interpolate_variant(const Variant &a, const Variant &b, float
}
}
-Animation::Animation() {}
+Animation::Animation() {
+}
Animation::~Animation() {
for (int i = 0; i < tracks.size(); i++) {
diff --git a/scene/resources/animation.h b/scene/resources/animation.h
index 49c8fa4c22..b7d5a683db 100644
--- a/scene/resources/animation.h
+++ b/scene/resources/animation.h
@@ -64,7 +64,6 @@ public:
enum UpdateMode {
UPDATE_CONTINUOUS,
UPDATE_DISCRETE,
- UPDATE_TRIGGER,
UPDATE_CAPTURE,
};
@@ -74,6 +73,18 @@ public:
LOOP_PINGPONG,
};
+ enum LoopedFlag {
+ LOOPED_FLAG_NONE,
+ LOOPED_FLAG_END,
+ LOOPED_FLAG_START,
+ };
+
+ enum FindMode {
+ FIND_MODE_NEAREST,
+ FIND_MODE_APPROX,
+ FIND_MODE_EXACT,
+ };
+
#ifdef TOOLS_ENABLED
enum HandleMode {
HANDLE_MODE_FREE,
@@ -250,15 +261,11 @@ private:
_FORCE_INLINE_ T _interpolate(const Vector<TKey<T>> &p_keys, double p_time, InterpolationType p_interp, bool p_loop_wrap, bool *p_ok, bool p_backward = false) const;
template <class T>
- _FORCE_INLINE_ void _track_get_key_indices_in_range(const Vector<T> &p_array, double from_time, double to_time, List<int> *p_indices) const;
-
- _FORCE_INLINE_ void _value_track_get_key_indices_in_range(const ValueTrack *vt, double from_time, double to_time, List<int> *p_indices) const;
- _FORCE_INLINE_ void _method_track_get_key_indices_in_range(const MethodTrack *mt, double from_time, double to_time, List<int> *p_indices) const;
+ _FORCE_INLINE_ void _track_get_key_indices_in_range(const Vector<T> &p_array, double from_time, double to_time, List<int> *p_indices, bool p_is_backward) const;
double length = 1.0;
real_t step = 0.1;
LoopMode loop_mode = LOOP_NONE;
- int pingponged = 0;
/* Animation compression page format (version 1):
*
@@ -345,27 +352,6 @@ private:
// bind helpers
private:
- Vector<int> _value_track_get_key_indices(int p_track, double p_time, double p_delta) const {
- List<int> idxs;
- value_track_get_key_indices(p_track, p_time, p_delta, &idxs);
- Vector<int> idxr;
-
- for (int &E : idxs) {
- idxr.push_back(E);
- }
- return idxr;
- }
- Vector<int> _method_track_get_key_indices(int p_track, double p_time, double p_delta) const {
- List<int> idxs;
- method_track_get_key_indices(p_track, p_time, p_delta, &idxs);
- Vector<int> idxr;
-
- for (int &E : idxs) {
- idxr.push_back(E);
- }
- return idxr;
- }
-
bool _float_track_optimize_key(const TKey<float> t0, const TKey<float> t1, const TKey<float> t2, real_t p_allowed_velocity_err, real_t p_allowed_precision_error);
bool _vector2_track_optimize_key(const TKey<Vector2> t0, const TKey<Vector2> t1, const TKey<Vector2> t2, real_t p_alowed_velocity_err, real_t p_allowed_angular_error, real_t p_allowed_precision_error);
bool _vector3_track_optimize_key(const TKey<Vector3> t0, const TKey<Vector3> t1, const TKey<Vector3> t2, real_t p_alowed_velocity_err, real_t p_allowed_angular_error, real_t p_allowed_precision_error);
@@ -412,7 +398,7 @@ public:
void track_set_key_transition(int p_track, int p_key_idx, real_t p_transition);
void track_set_key_value(int p_track, int p_key_idx, const Variant &p_value);
void track_set_key_time(int p_track, int p_key_idx, double p_time);
- int track_find_key(int p_track, double p_time, bool p_exact = false) const;
+ int track_find_key(int p_track, double p_time, FindMode p_find_mode = FIND_MODE_NEAREST) const;
void track_remove_key(int p_track, int p_idx);
void track_remove_key_at_time(int p_track, double p_time);
int track_get_key_count(int p_track) const;
@@ -470,17 +456,15 @@ public:
bool track_get_interpolation_loop_wrap(int p_track) const;
Variant value_track_interpolate(int p_track, double p_time) const;
- void value_track_get_key_indices(int p_track, double p_time, double p_delta, List<int> *p_indices, int p_pingponged = 0) const;
void value_track_set_update_mode(int p_track, UpdateMode p_mode);
UpdateMode value_track_get_update_mode(int p_track) const;
- void method_track_get_key_indices(int p_track, double p_time, double p_delta, List<int> *p_indices, int p_pingponged = 0) const;
Vector<Variant> method_track_get_params(int p_track, int p_key_idx) const;
StringName method_track_get_name(int p_track, int p_key_idx) const;
void copy_track(int p_track, Ref<Animation> p_to_animation);
- void track_get_key_indices_in_range(int p_track, double p_time, double p_delta, List<int> *p_indices, int p_pingponged = 0) const;
+ void track_get_key_indices_in_range(int p_track, double p_time, double p_delta, List<int> *p_indices, Animation::LoopedFlag p_looped_flag = Animation::LOOPED_FLAG_NONE) const;
void set_length(real_t p_length);
real_t get_length() const;
@@ -510,6 +494,8 @@ VARIANT_ENUM_CAST(Animation::TrackType);
VARIANT_ENUM_CAST(Animation::InterpolationType);
VARIANT_ENUM_CAST(Animation::UpdateMode);
VARIANT_ENUM_CAST(Animation::LoopMode);
+VARIANT_ENUM_CAST(Animation::LoopedFlag);
+VARIANT_ENUM_CAST(Animation::FindMode);
#ifdef TOOLS_ENABLED
VARIANT_ENUM_CAST(Animation::HandleMode);
VARIANT_ENUM_CAST(Animation::HandleSetMode);
diff --git a/scene/resources/animation_library.cpp b/scene/resources/animation_library.cpp
index 427d418551..b37bfbae62 100644
--- a/scene/resources/animation_library.cpp
+++ b/scene/resources/animation_library.cpp
@@ -52,11 +52,13 @@ Error AnimationLibrary::add_animation(const StringName &p_name, const Ref<Animat
ERR_FAIL_COND_V(p_animation.is_null(), ERR_INVALID_PARAMETER);
if (animations.has(p_name)) {
+ animations.get(p_name)->disconnect(SNAME("changed"), callable_mp(this, &AnimationLibrary::_animation_changed));
animations.erase(p_name);
emit_signal(SNAME("animation_removed"), p_name);
}
animations.insert(p_name, p_animation);
+ animations.get(p_name)->connect(SNAME("changed"), callable_mp(this, &AnimationLibrary::_animation_changed).bind(p_name));
emit_signal(SNAME("animation_added"), p_name);
notify_property_list_changed();
return OK;
@@ -65,6 +67,7 @@ Error AnimationLibrary::add_animation(const StringName &p_name, const Ref<Animat
void AnimationLibrary::remove_animation(const StringName &p_name) {
ERR_FAIL_COND_MSG(!animations.has(p_name), vformat("Animation not found: %s.", p_name));
+ animations.get(p_name)->disconnect(SNAME("changed"), callable_mp(this, &AnimationLibrary::_animation_changed));
animations.erase(p_name);
emit_signal(SNAME("animation_removed"), p_name);
notify_property_list_changed();
@@ -75,6 +78,8 @@ void AnimationLibrary::rename_animation(const StringName &p_name, const StringNa
ERR_FAIL_COND_MSG(!is_valid_animation_name(p_new_name), "Invalid animation name: '" + String(p_new_name) + "'.");
ERR_FAIL_COND_MSG(animations.has(p_new_name), vformat("Animation name \"%s\" already exists in library.", p_new_name));
+ animations.get(p_name)->disconnect(SNAME("changed"), callable_mp(this, &AnimationLibrary::_animation_changed));
+ animations.get(p_name)->connect(SNAME("changed"), callable_mp(this, &AnimationLibrary::_animation_changed).bind(p_new_name));
animations.insert(p_new_name, animations[p_name]);
animations.erase(p_name);
emit_signal(SNAME("animation_renamed"), p_name, p_new_name);
@@ -100,6 +105,10 @@ TypedArray<StringName> AnimationLibrary::_get_animation_list() const {
return ret;
}
+void AnimationLibrary::_animation_changed(const StringName &p_name) {
+ emit_signal(SNAME("animation_changed"), p_name);
+}
+
void AnimationLibrary::get_animation_list(List<StringName> *p_animations) const {
List<StringName> anims;
@@ -115,6 +124,9 @@ void AnimationLibrary::get_animation_list(List<StringName> *p_animations) const
}
void AnimationLibrary::_set_data(const Dictionary &p_data) {
+ for (KeyValue<StringName, Ref<Animation>> &K : animations) {
+ K.value->disconnect(SNAME("changed"), callable_mp(this, &AnimationLibrary::_animation_changed));
+ }
animations.clear();
List<Variant> keys;
p_data.get_key_list(&keys);
@@ -146,6 +158,7 @@ void AnimationLibrary::_bind_methods() {
ADD_SIGNAL(MethodInfo("animation_added", PropertyInfo(Variant::STRING_NAME, "name")));
ADD_SIGNAL(MethodInfo("animation_removed", PropertyInfo(Variant::STRING_NAME, "name")));
ADD_SIGNAL(MethodInfo("animation_renamed", PropertyInfo(Variant::STRING_NAME, "name"), PropertyInfo(Variant::STRING_NAME, "to_name")));
+ ADD_SIGNAL(MethodInfo("animation_changed", PropertyInfo(Variant::STRING_NAME, "name")));
}
AnimationLibrary::AnimationLibrary() {
}
diff --git a/scene/resources/animation_library.h b/scene/resources/animation_library.h
index d63807b6d7..54bd641b6d 100644
--- a/scene/resources/animation_library.h
+++ b/scene/resources/animation_library.h
@@ -42,6 +42,8 @@ class AnimationLibrary : public Resource {
TypedArray<StringName> _get_animation_list() const;
+ void _animation_changed(const StringName &p_name);
+
friend class AnimationPlayer; //for faster access
HashMap<StringName, Ref<Animation>> animations;
diff --git a/scene/resources/bit_map.cpp b/scene/resources/bit_map.cpp
index 1b06e09bb8..86b806bc4f 100644
--- a/scene/resources/bit_map.cpp
+++ b/scene/resources/bit_map.cpp
@@ -169,7 +169,7 @@ Dictionary BitMap::_get_data() const {
return d;
}
-Vector<Vector2> BitMap::_march_square(const Rect2i &p_rect, const Point2i &p_start) const {
+Vector<Vector<Vector2>> BitMap::_march_square(const Rect2i &p_rect, const Point2i &p_start) const {
int stepx = 0;
int stepy = 0;
int prevx = 0;
@@ -179,9 +179,17 @@ Vector<Vector2> BitMap::_march_square(const Rect2i &p_rect, const Point2i &p_sta
int curx = startx;
int cury = starty;
unsigned int count = 0;
- HashSet<Point2i> case9s;
- HashSet<Point2i> case6s;
+
+ HashMap<Point2i, int> cross_map;
+
Vector<Vector2> _points;
+ int points_size = 0;
+
+ Vector<Vector<Vector2>> ret;
+
+ // Add starting entry at start of return.
+ ret.resize(1);
+
do {
int sv = 0;
{ // Square value
@@ -202,7 +210,7 @@ Vector<Vector2> BitMap::_march_square(const Rect2i &p_rect, const Point2i &p_sta
sv += (p_rect.has_point(bl) && get_bitv(bl)) ? 4 : 0;
Point2i br = Point2i(curx, cury);
sv += (p_rect.has_point(br) && get_bitv(br)) ? 8 : 0;
- ERR_FAIL_COND_V(sv == 0 || sv == 15, Vector<Vector2>());
+ ERR_FAIL_COND_V(sv == 0 || sv == 15, Vector<Vector<Vector2>>());
}
switch (sv) {
@@ -266,70 +274,95 @@ Vector<Vector2> BitMap::_march_square(const Rect2i &p_rect, const Point2i &p_sta
stepy = 0;
break;
case 9:
- /*
+ /* Going DOWN if coming from the LEFT, otherwise go UP.
+ 9
+---+---+
| 1 | |
+---+---+
| | 8 |
+---+---+
- this should normally go UP, but if we already been here, we go down
*/
- if (case9s.has(Point2i(curx, cury))) {
- //found, so we go down, and delete from case9s;
+
+ if (prevx == 1) {
stepx = 0;
stepy = 1;
- case9s.erase(Point2i(curx, cury));
} else {
- //not found, we go up, and add to case9s;
stepx = 0;
stepy = -1;
- case9s.insert(Point2i(curx, cury));
}
break;
case 6:
- /*
+ /* Going RIGHT if coming from BELOW, otherwise go LEFT.
6
+---+---+
| | 2 |
+---+---+
| 4 | |
+---+---+
- this normally go RIGHT, but if it's coming from RIGHT, it should go LEFT
*/
- if (case6s.has(Point2i(curx, cury))) {
- //found, so we go left, and delete from case6s;
- stepx = -1;
+
+ if (prevy == -1) {
+ stepx = 1;
stepy = 0;
- case6s.erase(Point2i(curx, cury));
} else {
- //not found, we go right, and add to case6s;
- stepx = 1;
+ stepx = -1;
stepy = 0;
- case6s.insert(Point2i(curx, cury));
}
break;
default:
ERR_PRINT("this shouldn't happen.");
}
+
+ // Handle crossing points.
+ if (sv == 6 || sv == 9) {
+ const Point2i cur_pos(curx, cury);
+
+ // Find if this point has occurred before.
+ if (HashMap<Point2i, int>::Iterator found = cross_map.find(cur_pos)) {
+ // Add points after the previous crossing to the result.
+ ret.push_back(_points.slice(found->value + 1, points_size));
+
+ // Remove points after crossing point.
+ points_size = found->value + 1;
+
+ // Erase trailing map elements.
+ while (cross_map.last() != found) {
+ cross_map.remove(cross_map.last());
+ }
+
+ cross_map.erase(cur_pos);
+ } else {
+ // Add crossing point to map.
+ cross_map.insert(cur_pos, points_size - 1);
+ }
+ }
+
// Small optimization:
// If the previous direction is same as the current direction,
// then we should modify the last vector to current.
curx += stepx;
cury += stepy;
if (stepx == prevx && stepy == prevy) {
- _points.write[_points.size() - 1].x = (float)(curx - p_rect.position.x);
- _points.write[_points.size() - 1].y = (float)(cury + p_rect.position.y);
+ _points.set(points_size - 1, Vector2(curx, cury) - p_rect.position);
} else {
- _points.push_back(Vector2((float)(curx - p_rect.position.x), (float)(cury + p_rect.position.y)));
+ _points.resize(MAX(points_size + 1, _points.size()));
+ _points.set(points_size, Vector2(curx, cury) - p_rect.position);
+ points_size++;
}
count++;
prevx = stepx;
prevy = stepy;
- ERR_FAIL_COND_V((int)count > width * height, _points);
+ ERR_FAIL_COND_V((int)count > width * height, Vector<Vector<Vector2>>());
} while (curx != startx || cury != starty);
- return _points;
+
+ // Add remaining points to result.
+ _points.resize(points_size);
+
+ ret.set(0, _points);
+
+ return ret;
}
static float perpendicular_distance(const Vector2 &i, const Vector2 &start, const Vector2 &end) {
@@ -442,7 +475,7 @@ static void fill_bits(const BitMap *p_src, Ref<BitMap> &p_map, const Point2i &p_
for (int j = next_j; j <= pos.y + 1; j++) {
if (popped) {
// The next loop over j must start normally.
- next_j = pos.y;
+ next_j = pos.y - 1;
popped = false;
// Skip because an iteration was already executed with current counter values.
continue;
@@ -486,13 +519,10 @@ static void fill_bits(const BitMap *p_src, Ref<BitMap> &p_map, const Point2i &p_
}
}
} while (reenter || popped);
-
- print_verbose("BitMap: Max stack size: " + itos(stack.size()));
}
Vector<Vector<Vector2>> BitMap::clip_opaque_to_polygons(const Rect2i &p_rect, float p_epsilon) const {
Rect2i r = Rect2i(0, 0, width, height).intersection(p_rect);
- print_verbose("BitMap: Rect: " + r);
Point2i from;
Ref<BitMap> fill;
@@ -505,17 +535,16 @@ Vector<Vector<Vector2>> BitMap::clip_opaque_to_polygons(const Rect2i &p_rect, fl
if (!fill->get_bit(j, i) && get_bit(j, i)) {
fill_bits(this, fill, Point2i(j, i), r);
- Vector<Vector2> polygon = _march_square(r, Point2i(j, i));
- print_verbose("BitMap: Pre reduce: " + itos(polygon.size()));
- polygon = reduce(polygon, r, p_epsilon);
- print_verbose("BitMap: Post reduce: " + itos(polygon.size()));
+ for (Vector<Vector2> polygon : _march_square(r, Point2i(j, i))) {
+ polygon = reduce(polygon, r, p_epsilon);
- if (polygon.size() < 3) {
- print_verbose("Invalid polygon, skipped");
- continue;
- }
+ if (polygon.size() < 3) {
+ print_verbose("Invalid polygon, skipped");
+ continue;
+ }
- polygons.push_back(polygon);
+ polygons.push_back(polygon);
+ }
}
}
}
diff --git a/scene/resources/bit_map.h b/scene/resources/bit_map.h
index 291ed8c4d0..0ec5772fd1 100644
--- a/scene/resources/bit_map.h
+++ b/scene/resources/bit_map.h
@@ -46,7 +46,7 @@ class BitMap : public Resource {
int width = 0;
int height = 0;
- Vector<Vector2> _march_square(const Rect2i &p_rect, const Point2i &p_start) const;
+ Vector<Vector<Vector2>> _march_square(const Rect2i &p_rect, const Point2i &p_start) const;
TypedArray<PackedVector2Array> _opaque_to_polygons_bind(const Rect2i &p_rect, float p_epsilon) const;
diff --git a/scene/resources/bone_map.cpp b/scene/resources/bone_map.cpp
index dfaf82f36a..5698e61004 100644
--- a/scene/resources/bone_map.cpp
+++ b/scene/resources/bone_map.cpp
@@ -93,7 +93,7 @@ void BoneMap::set_skeleton_bone_name(StringName p_profile_bone_name, const Strin
}
StringName BoneMap::find_profile_bone_name(StringName p_skeleton_bone_name) const {
- StringName profile_bone_name = StringName();
+ StringName profile_bone_name;
HashMap<StringName, StringName>::ConstIterator E = bone_map.begin();
while (E) {
if (E->value == p_skeleton_bone_name) {
diff --git a/scene/resources/camera_attributes.cpp b/scene/resources/camera_attributes.cpp
index 3c322f32b6..8e4876e01f 100644
--- a/scene/resources/camera_attributes.cpp
+++ b/scene/resources/camera_attributes.cpp
@@ -120,7 +120,7 @@ void CameraAttributes::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_auto_exposure_scale", "exposure_grey"), &CameraAttributes::set_auto_exposure_scale);
ClassDB::bind_method(D_METHOD("get_auto_exposure_scale"), &CameraAttributes::get_auto_exposure_scale);
- ADD_GROUP("Exposure", "exposure");
+ ADD_GROUP("Exposure", "exposure_");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "exposure_sensitivity", PROPERTY_HINT_RANGE, "0.1,32000.0,0.1,suffix:ISO"), "set_exposure_sensitivity", "get_exposure_sensitivity");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "exposure_multiplier", PROPERTY_HINT_RANGE, "0.0,2048.0,0.001"), "set_exposure_multiplier", "get_exposure_multiplier");
@@ -472,7 +472,7 @@ void CameraAttributesPhysical::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "frustum_near", PROPERTY_HINT_RANGE, "0.001,10,0.001,or_greater,exp,suffix:m"), "set_near", "get_near");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "frustum_far", PROPERTY_HINT_RANGE, "0.01,4000,0.01,or_greater,exp,suffix:m"), "set_far", "get_far");
- ADD_GROUP("Exposure", "exposure");
+ ADD_GROUP("Exposure", "exposure_");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "exposure_aperture", PROPERTY_HINT_RANGE, "0.5,64.0,0.01,exp,suffix:f-stop"), "set_aperture", "get_aperture");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "exposure_shutter_speed", PROPERTY_HINT_RANGE, "0.1,8000.0,0.001,suffix:1/s"), "set_shutter_speed", "get_shutter_speed");
diff --git a/scene/resources/curve.cpp b/scene/resources/curve.cpp
index eda9af9dde..be9c0dc725 100644
--- a/scene/resources/curve.cpp
+++ b/scene/resources/curve.cpp
@@ -31,6 +31,7 @@
#include "curve.h"
#include "core/core_string_names.h"
+#include "core/math/math_funcs.h"
const char *Curve::SIGNAL_RANGE_CHANGED = "range_changed";
@@ -340,7 +341,7 @@ real_t Curve::sample_local_nocheck(int p_index, real_t p_local_offset) const {
const Point a = _points[p_index];
const Point b = _points[p_index + 1];
- /* Cubic bezier
+ /* Cubic bézier
*
* ac-----bc
* / \
@@ -773,6 +774,35 @@ void Curve2D::_bake_segment2d(RBMap<real_t, Vector2> &r_bake, real_t p_begin, re
}
}
+void Curve2D::_bake_segment2d_even_length(RBMap<real_t, Vector2> &r_bake, real_t p_begin, real_t p_end, const Vector2 &p_a, const Vector2 &p_out, const Vector2 &p_b, const Vector2 &p_in, int p_depth, int p_max_depth, real_t p_length) const {
+ Vector2 beg = p_a.bezier_interpolate(p_a + p_out, p_b + p_in, p_b, p_begin);
+ Vector2 end = p_a.bezier_interpolate(p_a + p_out, p_b + p_in, p_b, p_end);
+
+ real_t length = beg.distance_to(end);
+
+ if (length > p_length && p_depth < p_max_depth) {
+ real_t mp = (p_begin + p_end) * 0.5;
+ Vector2 mid = p_a.bezier_interpolate(p_a + p_out, p_b + p_in, p_b, mp);
+ r_bake[mp] = mid;
+
+ _bake_segment2d_even_length(r_bake, p_begin, mp, p_a, p_out, p_b, p_in, p_depth + 1, p_max_depth, p_length);
+ _bake_segment2d_even_length(r_bake, mp, p_end, p_a, p_out, p_b, p_in, p_depth + 1, p_max_depth, p_length);
+ }
+}
+
+Vector2 Curve2D::_calculate_tangent(const Vector2 &p_begin, const Vector2 &p_control_1, const Vector2 &p_control_2, const Vector2 &p_end, const real_t p_t) {
+ // Handle corner cases.
+ if (Math::is_zero_approx(p_t - 0.0f) && p_control_1.is_equal_approx(p_begin)) {
+ return (p_end - p_begin).normalized();
+ }
+
+ if (Math::is_zero_approx(p_t - 1.0f) && p_control_2.is_equal_approx(p_end)) {
+ return (p_end - p_begin).normalized();
+ }
+
+ return p_begin.bezier_derivative(p_control_1, p_control_2, p_end, p_t).normalized();
+}
+
void Curve2D::_bake() const {
if (!baked_cache_dirty) {
return;
@@ -784,94 +814,62 @@ void Curve2D::_bake() const {
if (points.size() == 0) {
baked_point_cache.clear();
baked_dist_cache.clear();
+ baked_forward_vector_cache.clear();
return;
}
if (points.size() == 1) {
baked_point_cache.resize(1);
baked_point_cache.set(0, points[0].position);
-
baked_dist_cache.resize(1);
baked_dist_cache.set(0, 0.0);
+ baked_forward_vector_cache.resize(1);
+ baked_forward_vector_cache.set(0, Vector2(0.0, 0.1));
+
return;
}
- Vector2 position = points[0].position;
- real_t dist = 0.0;
-
- List<Vector2> pointlist;
- List<real_t> distlist;
-
- // Start always from origin.
- pointlist.push_back(position);
- distlist.push_back(0.0);
-
- for (int i = 0; i < points.size() - 1; i++) {
- real_t step = 0.1; // at least 10 substeps ought to be enough?
- real_t p = 0.0;
-
- while (p < 1.0) {
- real_t np = p + step;
- if (np > 1.0) {
- np = 1.0;
- }
-
- Vector2 npp = points[i].position.bezier_interpolate(points[i].position + points[i].out, points[i + 1].position + points[i + 1].in, points[i + 1].position, np);
- real_t d = position.distance_to(npp);
-
- if (d > bake_interval) {
- // OK! between P and NP there _has_ to be Something, let's go searching!
-
- int iterations = 10; //lots of detail!
-
- real_t low = p;
- real_t hi = np;
- real_t mid = low + (hi - low) * 0.5;
+ // Tessellate curve to (almost) even length segments
+ {
+ Vector<RBMap<real_t, Vector2>> midpoints = _tessellate_even_length(10, bake_interval);
- for (int j = 0; j < iterations; j++) {
- npp = points[i].position.bezier_interpolate(points[i].position + points[i].out, points[i + 1].position + points[i + 1].in, points[i + 1].position, mid);
- d = position.distance_to(npp);
-
- if (bake_interval < d) {
- hi = mid;
- } else {
- low = mid;
- }
- mid = low + (hi - low) * 0.5;
- }
-
- position = npp;
- p = mid;
- dist += d;
-
- pointlist.push_back(position);
- distlist.push_back(dist);
- } else {
- p = np;
- }
+ int pc = 1;
+ for (int i = 0; i < points.size() - 1; i++) {
+ pc++;
+ pc += midpoints[i].size();
}
- Vector2 npp = points[i + 1].position;
- real_t d = position.distance_to(npp);
-
- position = npp;
- dist += d;
+ baked_point_cache.resize(pc);
+ baked_dist_cache.resize(pc);
+ baked_forward_vector_cache.resize(pc);
- pointlist.push_back(position);
- distlist.push_back(dist);
- }
+ Vector2 *bpw = baked_point_cache.ptrw();
+ Vector2 *bfw = baked_forward_vector_cache.ptrw();
- baked_max_ofs = dist;
+ // Collect positions and sample tilts and tangents for each baked points.
+ bpw[0] = points[0].position;
+ bfw[0] = _calculate_tangent(points[0].position, points[0].position + points[0].out, points[1].position + points[1].in, points[1].position, 0.0);
+ int pidx = 0;
- baked_point_cache.resize(pointlist.size());
- baked_dist_cache.resize(distlist.size());
+ for (int i = 0; i < points.size() - 1; i++) {
+ for (const KeyValue<real_t, Vector2> &E : midpoints[i]) {
+ pidx++;
+ bpw[pidx] = E.value;
+ bfw[pidx] = _calculate_tangent(points[i].position, points[i].position + points[i].out, points[i + 1].position + points[i + 1].in, points[i + 1].position, E.key);
+ }
- Vector2 *w = baked_point_cache.ptrw();
- real_t *wd = baked_dist_cache.ptrw();
+ pidx++;
+ bpw[pidx] = points[i + 1].position;
+ bfw[pidx] = _calculate_tangent(points[i].position, points[i].position + points[i].out, points[i + 1].position + points[i + 1].in, points[i + 1].position, 1.0);
+ }
- for (int i = 0; i < pointlist.size(); i++) {
- w[i] = pointlist[i];
- wd[i] = distlist[i];
+ // Recalculate the baked distances.
+ real_t *bdw = baked_dist_cache.ptrw();
+ bdw[0] = 0.0;
+ for (int i = 0; i < pc - 1; i++) {
+ bdw[i + 1] = bdw[i] + bpw[i].distance_to(bpw[i + 1]);
+ }
+ baked_max_ofs = bdw[pc - 1];
}
}
@@ -883,27 +881,15 @@ real_t Curve2D::get_baked_length() const {
return baked_max_ofs;
}
-Vector2 Curve2D::sample_baked(real_t p_offset, bool p_cubic) const {
- if (baked_cache_dirty) {
- _bake();
- }
+Curve2D::Interval Curve2D::_find_interval(real_t p_offset) const {
+ Interval interval = {
+ -1,
+ 0.0
+ };
+ ERR_FAIL_COND_V_MSG(baked_cache_dirty, interval, "Backed cache is dirty");
- // Validate: Curve may not have baked points.
int pc = baked_point_cache.size();
- ERR_FAIL_COND_V_MSG(pc == 0, Vector2(), "No points in Curve2D.");
-
- if (pc == 1) {
- return baked_point_cache.get(0);
- }
-
- const Vector2 *r = baked_point_cache.ptr();
-
- if (p_offset < 0) {
- return r[0];
- }
- if (p_offset >= baked_max_ofs) {
- return r[pc - 1];
- }
+ ERR_FAIL_COND_V_MSG(pc < 2, interval, "Less than two points in cache");
int start = 0;
int end = pc;
@@ -923,9 +909,27 @@ Vector2 Curve2D::sample_baked(real_t p_offset, bool p_cubic) const {
real_t offset_end = baked_dist_cache[idx + 1];
real_t idx_interval = offset_end - offset_begin;
- ERR_FAIL_COND_V_MSG(p_offset < offset_begin || p_offset > offset_end, Vector2(), "Couldn't find baked segment.");
+ ERR_FAIL_COND_V_MSG(p_offset < offset_begin || p_offset > offset_end, interval, "Offset out of range.");
+
+ interval.idx = idx;
+ if (idx_interval < FLT_EPSILON) {
+ interval.frac = 0.5; // For a very short interval, 0.5 is a reasonable choice.
+ ERR_FAIL_V_MSG(interval, "Zero length interval.");
+ }
+
+ interval.frac = (p_offset - offset_begin) / idx_interval;
+ return interval;
+}
- real_t frac = (p_offset - offset_begin) / idx_interval;
+Vector2 Curve2D::_sample_baked(Interval p_interval, bool p_cubic) const {
+ // Assuming p_interval is valid.
+ ERR_FAIL_INDEX_V_MSG(p_interval.idx, baked_point_cache.size(), Vector2(), "Invalid interval");
+
+ int idx = p_interval.idx;
+ real_t frac = p_interval.frac;
+
+ const Vector2 *r = baked_point_cache.ptr();
+ int pc = baked_point_cache.size();
if (p_cubic) {
Vector2 pre = idx > 0 ? r[idx - 1] : r[idx];
@@ -936,44 +940,70 @@ Vector2 Curve2D::sample_baked(real_t p_offset, bool p_cubic) const {
}
}
-Transform2D Curve2D::sample_baked_with_rotation(real_t p_offset, bool p_cubic, bool p_loop, real_t p_lookahead) const {
- real_t path_length = get_baked_length(); // Ensure baked.
- ERR_FAIL_COND_V_MSG(path_length == 0, Transform2D(), "Length of Curve2D is 0.");
+Transform2D Curve2D::_sample_posture(Interval p_interval) const {
+ // Assuming that p_interval is valid.
+ ERR_FAIL_INDEX_V_MSG(p_interval.idx, baked_point_cache.size(), Transform2D(), "Invalid interval");
- Vector2 pos = sample_baked(p_offset, p_cubic);
+ int idx = p_interval.idx;
+ real_t frac = p_interval.frac;
- real_t ahead = p_offset + p_lookahead;
+ Vector2 forward_begin = baked_forward_vector_cache[idx];
+ Vector2 forward_end = baked_forward_vector_cache[idx + 1];
- if (p_loop && ahead >= path_length) {
- // If our lookahead will loop, we need to check if the path is closed.
- int point_count = get_point_count();
- if (point_count > 0) {
- Vector2 start_point = get_point_position(0);
- Vector2 end_point = get_point_position(point_count - 1);
- if (start_point == end_point) {
- // Since the path is closed we want to 'smooth off'
- // the corner at the start/end.
- // So we wrap the lookahead back round.
- ahead = Math::fmod(ahead, path_length);
- }
- }
+ // Build frames at both ends of the interval, then interpolate.
+ const Vector2 forward = forward_begin.slerp(forward_end, frac).normalized();
+ const Vector2 side = Vector2(-forward.y, forward.x);
+
+ return Transform2D(side, forward, Vector2(0.0, 0.0));
+}
+
+Vector2 Curve2D::sample_baked(real_t p_offset, bool p_cubic) const {
+ if (baked_cache_dirty) {
+ _bake();
}
- Vector2 ahead_pos = sample_baked(ahead, p_cubic);
+ // Validate: Curve may not have baked points.
+ int pc = baked_point_cache.size();
+ ERR_FAIL_COND_V_MSG(pc == 0, Vector2(), "No points in Curve2D.");
- Vector2 tangent_to_curve;
- if (ahead_pos == pos) {
- // This will happen at the end of non-looping or non-closed paths.
- // We'll try a look behind instead, in order to get a meaningful angle.
- tangent_to_curve =
- (pos - sample_baked(p_offset - p_lookahead, p_cubic)).normalized();
- } else {
- tangent_to_curve = (ahead_pos - pos).normalized();
+ if (pc == 1) {
+ return baked_point_cache[0];
}
- Vector2 normal_of_curve = -tangent_to_curve.orthogonal();
+ p_offset = CLAMP(p_offset, 0.0, get_baked_length()); // PathFollower implement wrapping logic.
- return Transform2D(normal_of_curve, tangent_to_curve, pos);
+ Curve2D::Interval interval = _find_interval(p_offset);
+ return _sample_baked(interval, p_cubic);
+}
+
+Transform2D Curve2D::sample_baked_with_rotation(real_t p_offset, bool p_cubic) const {
+ if (baked_cache_dirty) {
+ _bake();
+ }
+
+ // Validate: Curve may not have baked points.
+ const int point_count = baked_point_cache.size();
+ ERR_FAIL_COND_V_MSG(point_count == 0, Transform2D(), "No points in Curve3D.");
+
+ if (point_count == 1) {
+ Transform2D t;
+ t.set_origin(baked_point_cache.get(0));
+ ERR_FAIL_V_MSG(t, "Only 1 point in Curve2D.");
+ }
+
+ p_offset = CLAMP(p_offset, 0.0, get_baked_length()); // PathFollower implement wrapping logic.
+
+ // 0. Find interval for all sampling steps.
+ Curve2D::Interval interval = _find_interval(p_offset);
+
+ // 1. Sample position.
+ Vector2 pos = _sample_baked(interval, p_cubic);
+
+ // 2. Sample rotation frame.
+ Transform2D frame = _sample_posture(interval);
+ frame.set_origin(pos);
+
+ return frame;
}
PackedVector2Array Curve2D::get_baked_points() const {
@@ -1014,10 +1044,11 @@ Vector2 Curve2D::get_closest_point(const Vector2 &p_to_point) const {
real_t nearest_dist = -1.0f;
for (int i = 0; i < pc - 1; i++) {
+ const real_t interval = baked_dist_cache[i + 1] - baked_dist_cache[i];
Vector2 origin = r[i];
- Vector2 direction = (r[i + 1] - origin) / bake_interval;
+ Vector2 direction = (r[i + 1] - origin) / interval;
- real_t d = CLAMP((p_to_point - origin).dot(direction), 0.0f, bake_interval);
+ real_t d = CLAMP((p_to_point - origin).dot(direction), 0.0f, interval);
Vector2 proj = origin + direction * d;
real_t dist = proj.distance_squared_to(p_to_point);
@@ -1053,10 +1084,13 @@ real_t Curve2D::get_closest_offset(const Vector2 &p_to_point) const {
real_t offset = 0.0f;
for (int i = 0; i < pc - 1; i++) {
+ offset = baked_dist_cache[i];
+
+ const real_t interval = baked_dist_cache[i + 1] - baked_dist_cache[i];
Vector2 origin = r[i];
- Vector2 direction = (r[i + 1] - origin) / bake_interval;
+ Vector2 direction = (r[i + 1] - origin) / interval;
- real_t d = CLAMP((p_to_point - origin).dot(direction), 0.0f, bake_interval);
+ real_t d = CLAMP((p_to_point - origin).dot(direction), 0.0f, interval);
Vector2 proj = origin + direction * d;
real_t dist = proj.distance_squared_to(p_to_point);
@@ -1065,8 +1099,6 @@ real_t Curve2D::get_closest_offset(const Vector2 &p_to_point) const {
nearest = offset + d;
nearest_dist = dist;
}
-
- offset += bake_interval;
}
return nearest;
@@ -1146,6 +1178,50 @@ PackedVector2Array Curve2D::tessellate(int p_max_stages, real_t p_tolerance) con
return tess;
}
+Vector<RBMap<real_t, Vector2>> Curve2D::_tessellate_even_length(int p_max_stages, real_t p_length) const {
+ Vector<RBMap<real_t, Vector2>> midpoints;
+ ERR_FAIL_COND_V_MSG(points.size() < 2, midpoints, "Curve must have at least 2 control point");
+
+ midpoints.resize(points.size() - 1);
+
+ for (int i = 0; i < points.size() - 1; i++) {
+ _bake_segment2d_even_length(midpoints.write[i], 0, 1, points[i].position, points[i].out, points[i + 1].position, points[i + 1].in, 0, p_max_stages, p_length);
+ }
+ return midpoints;
+}
+
+PackedVector2Array Curve2D::tessellate_even_length(int p_max_stages, real_t p_length) const {
+ PackedVector2Array tess;
+
+ Vector<RBMap<real_t, Vector2>> midpoints = _tessellate_even_length(p_max_stages, p_length);
+ if (midpoints.size() == 0) {
+ return tess;
+ }
+
+ int pc = 1;
+ for (int i = 0; i < points.size() - 1; i++) {
+ pc++;
+ pc += midpoints[i].size();
+ }
+
+ tess.resize(pc);
+ Vector2 *bpw = tess.ptrw();
+ bpw[0] = points[0].position;
+ int pidx = 0;
+
+ for (int i = 0; i < points.size() - 1; i++) {
+ for (const KeyValue<real_t, Vector2> &E : midpoints[i]) {
+ pidx++;
+ bpw[pidx] = E.value;
+ }
+
+ pidx++;
+ bpw[pidx] = points[i + 1].position;
+ }
+
+ return tess;
+}
+
bool Curve2D::_set(const StringName &p_name, const Variant &p_value) {
Vector<String> components = String(p_name).split("/", true, 2);
if (components.size() >= 2 && components[0].begins_with("point_") && components[0].trim_prefix("point_").is_valid_int()) {
@@ -1223,12 +1299,13 @@ void Curve2D::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_bake_interval"), &Curve2D::get_bake_interval);
ClassDB::bind_method(D_METHOD("get_baked_length"), &Curve2D::get_baked_length);
- ClassDB::bind_method(D_METHOD("sample_baked", "offset", "cubic"), &Curve2D::sample_baked, DEFVAL(false));
- ClassDB::bind_method(D_METHOD("sample_baked_with_rotation", "offset", "cubic", "loop", "lookahead"), &Curve2D::sample_baked_with_rotation, DEFVAL(false), DEFVAL(true), DEFVAL(4.0));
+ ClassDB::bind_method(D_METHOD("sample_baked", "offset", "cubic"), &Curve2D::sample_baked, DEFVAL(0.0), DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("sample_baked_with_rotation", "offset", "cubic"), &Curve2D::sample_baked_with_rotation, DEFVAL(0.0), DEFVAL(false));
ClassDB::bind_method(D_METHOD("get_baked_points"), &Curve2D::get_baked_points);
ClassDB::bind_method(D_METHOD("get_closest_point", "to_point"), &Curve2D::get_closest_point);
ClassDB::bind_method(D_METHOD("get_closest_offset", "to_point"), &Curve2D::get_closest_offset);
ClassDB::bind_method(D_METHOD("tessellate", "max_stages", "tolerance_degrees"), &Curve2D::tessellate, DEFVAL(5), DEFVAL(4));
+ ClassDB::bind_method(D_METHOD("tessellate_even_length", "max_stages", "tolerance_length"), &Curve2D::tessellate_even_length, DEFVAL(5), DEFVAL(20.0));
ClassDB::bind_method(D_METHOD("_get_data"), &Curve2D::_get_data);
ClassDB::bind_method(D_METHOD("_set_data", "data"), &Curve2D::_set_data);
@@ -1402,6 +1479,35 @@ void Curve3D::_bake_segment3d(RBMap<real_t, Vector3> &r_bake, real_t p_begin, re
}
}
+void Curve3D::_bake_segment3d_even_length(RBMap<real_t, Vector3> &r_bake, real_t p_begin, real_t p_end, const Vector3 &p_a, const Vector3 &p_out, const Vector3 &p_b, const Vector3 &p_in, int p_depth, int p_max_depth, real_t p_length) const {
+ Vector3 beg = p_a.bezier_interpolate(p_a + p_out, p_b + p_in, p_b, p_begin);
+ Vector3 end = p_a.bezier_interpolate(p_a + p_out, p_b + p_in, p_b, p_end);
+
+ real_t length = beg.distance_to(end);
+
+ if (length > p_length && p_depth < p_max_depth) {
+ real_t mp = (p_begin + p_end) * 0.5;
+ Vector3 mid = p_a.bezier_interpolate(p_a + p_out, p_b + p_in, p_b, mp);
+ r_bake[mp] = mid;
+
+ _bake_segment3d_even_length(r_bake, p_begin, mp, p_a, p_out, p_b, p_in, p_depth + 1, p_max_depth, p_length);
+ _bake_segment3d_even_length(r_bake, mp, p_end, p_a, p_out, p_b, p_in, p_depth + 1, p_max_depth, p_length);
+ }
+}
+
+Vector3 Curve3D::_calculate_tangent(const Vector3 &p_begin, const Vector3 &p_control_1, const Vector3 &p_control_2, const Vector3 &p_end, const real_t p_t) {
+ // Handle corner cases.
+ if (Math::is_zero_approx(p_t - 0.0f) && p_control_1.is_equal_approx(p_begin)) {
+ return (p_end - p_begin).normalized();
+ }
+
+ if (Math::is_zero_approx(p_t - 1.0f) && p_control_2.is_equal_approx(p_end)) {
+ return (p_end - p_begin).normalized();
+ }
+
+ return p_begin.bezier_derivative(p_control_1, p_control_2, p_end, p_t).normalized();
+}
+
void Curve3D::_bake() const {
if (!baked_cache_dirty) {
return;
@@ -1413,8 +1519,10 @@ void Curve3D::_bake() const {
if (points.size() == 0) {
baked_point_cache.clear();
baked_tilt_cache.clear();
- baked_up_vector_cache.clear();
baked_dist_cache.clear();
+
+ baked_forward_vector_cache.clear();
+ baked_up_vector_cache.clear();
return;
}
@@ -1425,10 +1533,12 @@ void Curve3D::_bake() const {
baked_tilt_cache.set(0, points[0].tilt);
baked_dist_cache.resize(1);
baked_dist_cache.set(0, 0.0);
+ baked_forward_vector_cache.resize(1);
+ baked_forward_vector_cache.set(0, Vector3(0.0, 0.0, 1.0));
if (up_vector_enabled) {
baked_up_vector_cache.resize(1);
- baked_up_vector_cache.set(0, Vector3(0, 1, 0));
+ baked_up_vector_cache.set(0, Vector3(0.0, 1.0, 0.0));
} else {
baked_up_vector_cache.clear();
}
@@ -1436,136 +1546,135 @@ void Curve3D::_bake() const {
return;
}
- Vector3 position = points[0].position;
- real_t dist = 0.0;
- List<Plane> pointlist;
- List<real_t> distlist;
-
- // Start always from origin.
- pointlist.push_back(Plane(position, points[0].tilt));
- distlist.push_back(0.0);
+ // Step 1: Tessellate curve to (almost) even length segments
+ {
+ Vector<RBMap<real_t, Vector3>> midpoints = _tessellate_even_length(10, bake_interval);
- for (int i = 0; i < points.size() - 1; i++) {
- real_t step = 0.1; // at least 10 substeps ought to be enough?
- real_t p = 0.0;
+ int pc = 1;
+ for (int i = 0; i < points.size() - 1; i++) {
+ pc++;
+ pc += midpoints[i].size();
+ }
- while (p < 1.0) {
- real_t np = p + step;
- if (np > 1.0) {
- np = 1.0;
+ baked_point_cache.resize(pc);
+ baked_tilt_cache.resize(pc);
+ baked_dist_cache.resize(pc);
+ baked_forward_vector_cache.resize(pc);
+
+ Vector3 *bpw = baked_point_cache.ptrw();
+ real_t *btw = baked_tilt_cache.ptrw();
+ Vector3 *bfw = baked_forward_vector_cache.ptrw();
+
+ // Collect positions and sample tilts and tangents for each baked points.
+ bpw[0] = points[0].position;
+ bfw[0] = _calculate_tangent(points[0].position, points[0].position + points[0].out, points[1].position + points[1].in, points[1].position, 0.0);
+ btw[0] = points[0].tilt;
+ int pidx = 0;
+
+ for (int i = 0; i < points.size() - 1; i++) {
+ for (const KeyValue<real_t, Vector3> &E : midpoints[i]) {
+ pidx++;
+ bpw[pidx] = E.value;
+ bfw[pidx] = _calculate_tangent(points[i].position, points[i].position + points[i].out, points[i + 1].position + points[i + 1].in, points[i + 1].position, E.key);
+ btw[pidx] = Math::lerp(points[i].tilt, points[i + 1].tilt, E.key);
}
- Vector3 npp = points[i].position.bezier_interpolate(points[i].position + points[i].out, points[i + 1].position + points[i + 1].in, points[i + 1].position, np);
- real_t d = position.distance_to(npp);
-
- if (d > bake_interval) {
- // OK! between P and NP there _has_ to be Something, let's go searching!
-
- int iterations = 10; //lots of detail!
-
- real_t low = p;
- real_t hi = np;
- real_t mid = low + (hi - low) * 0.5;
-
- for (int j = 0; j < iterations; j++) {
- npp = points[i].position.bezier_interpolate(points[i].position + points[i].out, points[i + 1].position + points[i + 1].in, points[i + 1].position, mid);
- d = position.distance_to(npp);
-
- if (bake_interval < d) {
- hi = mid;
- } else {
- low = mid;
- }
- mid = low + (hi - low) * 0.5;
- }
-
- position = npp;
- p = mid;
- Plane post;
- post.normal = position;
- post.d = Math::lerp(points[i].tilt, points[i + 1].tilt, mid);
- dist += d;
-
- pointlist.push_back(post);
- distlist.push_back(dist);
- } else {
- p = np;
- }
+ pidx++;
+ bpw[pidx] = points[i + 1].position;
+ bfw[pidx] = _calculate_tangent(points[i].position, points[i].position + points[i].out, points[i + 1].position + points[i + 1].in, points[i + 1].position, 1.0);
+ btw[pidx] = points[i + 1].tilt;
}
- Vector3 npp = points[i + 1].position;
- real_t d = position.distance_to(npp);
-
- position = npp;
- Plane post;
- post.normal = position;
- post.d = points[i + 1].tilt;
-
- dist += d;
-
- pointlist.push_back(post);
- distlist.push_back(dist);
+ // Recalculate the baked distances.
+ real_t *bdw = baked_dist_cache.ptrw();
+ bdw[0] = 0.0;
+ for (int i = 0; i < pc - 1; i++) {
+ bdw[i + 1] = bdw[i] + bpw[i].distance_to(bpw[i + 1]);
+ }
+ baked_max_ofs = bdw[pc - 1];
}
- baked_max_ofs = dist;
-
- baked_point_cache.resize(pointlist.size());
- Vector3 *w = baked_point_cache.ptrw();
- int idx = 0;
+ if (!up_vector_enabled) {
+ baked_up_vector_cache.resize(0);
+ return;
+ }
- baked_tilt_cache.resize(pointlist.size());
- real_t *wt = baked_tilt_cache.ptrw();
+ // Step 2: Calculate the up vectors and the whole local reference frame
+ //
+ // See Dougan, Carl. "The parallel transport frame." Game Programming Gems 2 (2001): 215-219.
+ // for an example discussing about why not the Frenet frame.
+ {
+ int point_count = baked_point_cache.size();
- baked_up_vector_cache.resize(up_vector_enabled ? pointlist.size() : 0);
- Vector3 *up_write = baked_up_vector_cache.ptrw();
+ baked_up_vector_cache.resize(point_count);
+ Vector3 *up_write = baked_up_vector_cache.ptrw();
- baked_dist_cache.resize(pointlist.size());
- real_t *wd = baked_dist_cache.ptrw();
+ const Vector3 *forward_ptr = baked_forward_vector_cache.ptr();
+ const Vector3 *points_ptr = baked_point_cache.ptr();
- Vector3 sideways;
- Vector3 up;
- Vector3 forward;
+ Basis frame; // X-right, Y-up, Z-forward.
+ Basis frame_prev;
- Vector3 prev_sideways = Vector3(1, 0, 0);
- Vector3 prev_up = Vector3(0, 1, 0);
- Vector3 prev_forward = Vector3(0, 0, 1);
+ // Set the initial frame based on Y-up rule.
+ {
+ Vector3 forward = forward_ptr[0];
- for (const Plane &E : pointlist) {
- w[idx] = E.normal;
- wt[idx] = E.d;
- wd[idx] = distlist[idx];
+ if (abs(forward.dot(Vector3(0, 1, 0))) > 1.0 - UNIT_EPSILON) {
+ frame_prev = Basis::looking_at(-forward, Vector3(1, 0, 0));
+ } else {
+ frame_prev = Basis::looking_at(-forward, Vector3(0, 1, 0));
+ }
- if (!up_vector_enabled) {
- idx++;
- continue;
+ up_write[0] = frame_prev.get_column(1);
}
- forward = idx > 0 ? (w[idx] - w[idx - 1]).normalized() : prev_forward;
+ // Calculate the Parallel Transport Frame.
+ for (int idx = 1; idx < point_count; idx++) {
+ Vector3 forward = forward_ptr[idx];
- real_t y_dot = prev_up.dot(forward);
+ Basis rotate;
+ rotate.rotate_to_align(frame_prev.get_column(2), forward);
+ frame = rotate * frame_prev;
+ frame.orthonormalize(); // guard against float error accumulation
- if (y_dot > (1.0f - CMP_EPSILON)) {
- sideways = prev_sideways;
- up = -prev_forward;
- } else if (y_dot < -(1.0f - CMP_EPSILON)) {
- sideways = prev_sideways;
- up = prev_forward;
- } else {
- sideways = prev_up.cross(forward).normalized();
- up = forward.cross(sideways).normalized();
+ up_write[idx] = frame.get_column(1);
+ frame_prev = frame;
}
- if (idx == 1) {
- up_write[0] = up;
+ bool is_loop = true;
+ // Loop smoothing only applies when the curve is a loop, which means two ends meet, and share forward directions.
+ {
+ if (!points_ptr[0].is_equal_approx(points_ptr[point_count - 1])) {
+ is_loop = false;
+ }
+
+ real_t dot = forward_ptr[0].dot(forward_ptr[point_count - 1]);
+ if (dot < 1.0 - UNIT_EPSILON) { // Alignment should not be too tight, or it doesn't work for coarse bake interval.
+ is_loop = false;
+ }
}
- up_write[idx] = up;
+ // Twist up vectors, so that they align at two ends of the curve.
+ if (is_loop) {
+ const Vector3 up_start = up_write[0];
+ const Vector3 up_end = up_write[point_count - 1];
- prev_sideways = sideways;
- prev_up = up;
- prev_forward = forward;
+ real_t sign = SIGN(up_end.cross(up_start).dot(forward_ptr[0]));
+ real_t full_angle = Quaternion(up_end, up_start).get_angle();
- idx++;
+ if (abs(full_angle) < CMP_EPSILON) {
+ return;
+ } else {
+ const real_t *dists = baked_dist_cache.ptr();
+ for (int idx = 1; idx < point_count; idx++) {
+ const real_t frac = dists[idx] / baked_max_ofs;
+ const real_t angle = Math::lerp((real_t)0.0, full_angle, frac);
+ Basis twist(forward_ptr[idx] * sign, angle);
+
+ up_write[idx] = twist.xform(up_write[idx]);
+ }
+ }
+ }
}
}
@@ -1577,27 +1686,15 @@ real_t Curve3D::get_baked_length() const {
return baked_max_ofs;
}
-Vector3 Curve3D::sample_baked(real_t p_offset, bool p_cubic) const {
- if (baked_cache_dirty) {
- _bake();
- }
+Curve3D::Interval Curve3D::_find_interval(real_t p_offset) const {
+ Interval interval = {
+ -1,
+ 0.0
+ };
+ ERR_FAIL_COND_V_MSG(baked_cache_dirty, interval, "Backed cache is dirty");
- // Validate: Curve may not have baked points.
int pc = baked_point_cache.size();
- ERR_FAIL_COND_V_MSG(pc == 0, Vector3(), "No points in Curve3D.");
-
- if (pc == 1) {
- return baked_point_cache.get(0);
- }
-
- const Vector3 *r = baked_point_cache.ptr();
-
- if (p_offset < 0) {
- return r[0];
- }
- if (p_offset >= baked_max_ofs) {
- return r[pc - 1];
- }
+ ERR_FAIL_COND_V_MSG(pc < 2, interval, "Less than two points in cache");
int start = 0;
int end = pc;
@@ -1617,9 +1714,27 @@ Vector3 Curve3D::sample_baked(real_t p_offset, bool p_cubic) const {
real_t offset_end = baked_dist_cache[idx + 1];
real_t idx_interval = offset_end - offset_begin;
- ERR_FAIL_COND_V_MSG(p_offset < offset_begin || p_offset > offset_end, Vector3(), "Couldn't find baked segment.");
+ ERR_FAIL_COND_V_MSG(p_offset < offset_begin || p_offset > offset_end, interval, "Offset out of range.");
+
+ interval.idx = idx;
+ if (idx_interval < FLT_EPSILON) {
+ interval.frac = 0.5; // For a very short interval, 0.5 is a reasonable choice.
+ ERR_FAIL_V_MSG(interval, "Zero length interval.");
+ }
+
+ interval.frac = (p_offset - offset_begin) / idx_interval;
+ return interval;
+}
+
+Vector3 Curve3D::_sample_baked(Interval p_interval, bool p_cubic) const {
+ // Assuming p_interval is valid.
+ ERR_FAIL_INDEX_V_MSG(p_interval.idx, baked_point_cache.size(), Vector3(), "Invalid interval");
+
+ int idx = p_interval.idx;
+ real_t frac = p_interval.frac;
- real_t frac = (p_offset - offset_begin) / idx_interval;
+ const Vector3 *r = baked_point_cache.ptr();
+ int pc = baked_point_cache.size();
if (p_cubic) {
Vector3 pre = idx > 0 ? r[idx - 1] : r[idx];
@@ -1630,114 +1745,142 @@ Vector3 Curve3D::sample_baked(real_t p_offset, bool p_cubic) const {
}
}
-real_t Curve3D::sample_baked_tilt(real_t p_offset) const {
- if (baked_cache_dirty) {
- _bake();
- }
+real_t Curve3D::_sample_baked_tilt(Interval p_interval) const {
+ // Assuming that p_interval is valid.
+ ERR_FAIL_INDEX_V_MSG(p_interval.idx, baked_tilt_cache.size(), 0.0, "Invalid interval");
- // Validate: Curve may not have baked tilts.
- int pc = baked_tilt_cache.size();
- ERR_FAIL_COND_V_MSG(pc == 0, 0, "No tilts in Curve3D.");
+ int idx = p_interval.idx;
+ real_t frac = p_interval.frac;
- if (pc == 1) {
- return baked_tilt_cache.get(0);
+ const real_t *r = baked_tilt_cache.ptr();
+
+ return Math::lerp(r[idx], r[idx + 1], frac);
+}
+
+Basis Curve3D::_sample_posture(Interval p_interval, bool p_apply_tilt) const {
+ // Assuming that p_interval is valid.
+ ERR_FAIL_INDEX_V_MSG(p_interval.idx, baked_point_cache.size(), Basis(), "Invalid interval");
+ if (up_vector_enabled) {
+ ERR_FAIL_INDEX_V_MSG(p_interval.idx, baked_up_vector_cache.size(), Basis(), "Invalid interval");
}
- const real_t *r = baked_tilt_cache.ptr();
+ int idx = p_interval.idx;
+ real_t frac = p_interval.frac;
- if (p_offset < 0) {
- return r[0];
+ Vector3 forward_begin = baked_forward_vector_cache[idx];
+ Vector3 forward_end = baked_forward_vector_cache[idx + 1];
+
+ Vector3 up_begin;
+ Vector3 up_end;
+ if (up_vector_enabled) {
+ up_begin = baked_up_vector_cache[idx];
+ up_end = baked_up_vector_cache[idx + 1];
+ } else {
+ up_begin = Vector3(0.0, 1.0, 0.0);
+ up_end = Vector3(0.0, 1.0, 0.0);
}
- if (p_offset >= baked_max_ofs) {
- return r[pc - 1];
+
+ // Build frames at both ends of the interval, then interpolate.
+ const Basis frame_begin = Basis::looking_at(-forward_begin, up_begin);
+ const Basis frame_end = Basis::looking_at(-forward_end, up_end);
+ const Basis frame = frame_begin.slerp(frame_end, frac).orthonormalized();
+
+ if (!p_apply_tilt) {
+ return frame;
}
- int start = 0;
- int end = pc;
- int idx = (end + start) / 2;
- // Binary search to find baked points.
- while (start < idx) {
- real_t offset = baked_dist_cache[idx];
- if (p_offset <= offset) {
- end = idx;
- } else {
- start = idx;
- }
- idx = (end + start) / 2;
+ // Applying tilt.
+ const real_t tilt = _sample_baked_tilt(p_interval);
+ Vector3 forward = frame.get_column(2);
+
+ const Basis twist(forward, tilt);
+ return twist * frame;
+}
+
+Vector3 Curve3D::sample_baked(real_t p_offset, bool p_cubic) const {
+ if (baked_cache_dirty) {
+ _bake();
}
- real_t offset_begin = baked_dist_cache[idx];
- real_t offset_end = baked_dist_cache[idx + 1];
+ // Validate: Curve may not have baked points.
+ int pc = baked_point_cache.size();
+ ERR_FAIL_COND_V_MSG(pc == 0, Vector3(), "No points in Curve3D.");
- real_t idx_interval = offset_end - offset_begin;
- ERR_FAIL_COND_V_MSG(p_offset < offset_begin || p_offset > offset_end, 0, "Couldn't find baked segment.");
+ if (pc == 1) {
+ return baked_point_cache[0];
+ }
- real_t frac = (p_offset - offset_begin) / idx_interval;
+ p_offset = CLAMP(p_offset, 0.0, get_baked_length()); // PathFollower implement wrapping logic.
- return Math::lerp(r[idx], r[idx + 1], (real_t)frac);
+ Curve3D::Interval interval = _find_interval(p_offset);
+ return _sample_baked(interval, p_cubic);
}
-Vector3 Curve3D::sample_baked_up_vector(real_t p_offset, bool p_apply_tilt) const {
+Transform3D Curve3D::sample_baked_with_rotation(real_t p_offset, bool p_cubic, bool p_apply_tilt) const {
if (baked_cache_dirty) {
_bake();
}
- // Validate: Curve may not have baked up vectors.
- int count = baked_up_vector_cache.size();
- ERR_FAIL_COND_V_MSG(count == 0, Vector3(0, 1, 0), "No up vectors in Curve3D.");
+ // Validate: Curve may not have baked points.
+ const int point_count = baked_point_cache.size();
+ ERR_FAIL_COND_V_MSG(point_count == 0, Transform3D(), "No points in Curve3D.");
- if (count == 1) {
- return baked_up_vector_cache.get(0);
+ if (point_count == 1) {
+ Transform3D t;
+ t.origin = baked_point_cache.get(0);
+ ERR_FAIL_V_MSG(t, "Only 1 point in Curve3D.");
}
- const Vector3 *r = baked_up_vector_cache.ptr();
- const Vector3 *rp = baked_point_cache.ptr();
- const real_t *rt = baked_tilt_cache.ptr();
+ p_offset = CLAMP(p_offset, 0.0, get_baked_length()); // PathFollower implement wrapping logic.
- int start = 0;
- int end = count;
- int idx = (end + start) / 2;
- // Binary search to find baked points.
- while (start < idx) {
- real_t offset = baked_dist_cache[idx];
- if (p_offset <= offset) {
- end = idx;
- } else {
- start = idx;
- }
- idx = (end + start) / 2;
- }
+ // 0. Find interval for all sampling steps.
+ Curve3D::Interval interval = _find_interval(p_offset);
- if (idx == count - 1) {
- return p_apply_tilt ? r[idx].rotated((rp[idx] - rp[idx - 1]).normalized(), rt[idx]) : r[idx];
+ // 1. Sample position.
+ Vector3 pos = _sample_baked(interval, p_cubic);
+
+ // 2. Sample rotation frame.
+ Basis frame = _sample_posture(interval, p_apply_tilt);
+
+ return Transform3D(frame, pos);
+}
+
+real_t Curve3D::sample_baked_tilt(real_t p_offset) const {
+ if (baked_cache_dirty) {
+ _bake();
}
- real_t offset_begin = baked_dist_cache[idx];
- real_t offset_end = baked_dist_cache[idx + 1];
+ // Validate: Curve may not have baked tilts.
+ int pc = baked_tilt_cache.size();
+ ERR_FAIL_COND_V_MSG(pc == 0, 0, "No tilts in Curve3D.");
- real_t idx_interval = offset_end - offset_begin;
- ERR_FAIL_COND_V_MSG(p_offset < offset_begin || p_offset > offset_end, Vector3(0, 1, 0), "Couldn't find baked segment.");
+ if (pc == 1) {
+ return baked_tilt_cache.get(0);
+ }
- real_t frac = (p_offset - offset_begin) / idx_interval;
+ p_offset = CLAMP(p_offset, 0.0, get_baked_length()); // PathFollower implement wrapping logic
- Vector3 forward = (rp[idx + 1] - rp[idx]).normalized();
- Vector3 up = r[idx];
- Vector3 up1 = r[idx + 1];
+ Curve3D::Interval interval = _find_interval(p_offset);
+ return _sample_baked_tilt(interval);
+}
- if (p_apply_tilt) {
- up.rotate(forward, rt[idx]);
- up1.rotate(idx + 2 >= count ? forward : (rp[idx + 2] - rp[idx + 1]).normalized(), rt[idx + 1]);
+Vector3 Curve3D::sample_baked_up_vector(real_t p_offset, bool p_apply_tilt) const {
+ if (baked_cache_dirty) {
+ _bake();
}
- Vector3 axis = up.cross(up1);
+ // Validate: Curve may not have baked up vectors.
+ ERR_FAIL_COND_V_MSG(!up_vector_enabled, Vector3(0, 1, 0), "No up vectors in Curve3D.");
- if (axis.length_squared() < CMP_EPSILON2) {
- axis = forward;
- } else {
- axis.normalize();
+ int count = baked_up_vector_cache.size();
+ if (count == 1) {
+ return baked_up_vector_cache.get(0);
}
- return up.rotated(axis, up.angle_to(up1) * frac);
+ p_offset = CLAMP(p_offset, 0.0, get_baked_length()); // PathFollower implement wrapping logic.
+
+ Curve3D::Interval interval = _find_interval(p_offset);
+ return _sample_posture(interval, p_apply_tilt).get_column(1);
}
PackedVector3Array Curve3D::get_baked_points() const {
@@ -1785,10 +1928,11 @@ Vector3 Curve3D::get_closest_point(const Vector3 &p_to_point) const {
real_t nearest_dist = -1.0f;
for (int i = 0; i < pc - 1; i++) {
+ const real_t interval = baked_dist_cache[i + 1] - baked_dist_cache[i];
Vector3 origin = r[i];
- Vector3 direction = (r[i + 1] - origin) / bake_interval;
+ Vector3 direction = (r[i + 1] - origin) / interval;
- real_t d = CLAMP((p_to_point - origin).dot(direction), 0.0f, bake_interval);
+ real_t d = CLAMP((p_to_point - origin).dot(direction), 0.0f, interval);
Vector3 proj = origin + direction * d;
real_t dist = proj.distance_squared_to(p_to_point);
@@ -1821,13 +1965,16 @@ real_t Curve3D::get_closest_offset(const Vector3 &p_to_point) const {
real_t nearest = 0.0f;
real_t nearest_dist = -1.0f;
- real_t offset = 0.0f;
+ real_t offset;
for (int i = 0; i < pc - 1; i++) {
+ offset = baked_dist_cache[i];
+
+ const real_t interval = baked_dist_cache[i + 1] - baked_dist_cache[i];
Vector3 origin = r[i];
- Vector3 direction = (r[i + 1] - origin) / bake_interval;
+ Vector3 direction = (r[i + 1] - origin) / interval;
- real_t d = CLAMP((p_to_point - origin).dot(direction), 0.0f, bake_interval);
+ real_t d = CLAMP((p_to_point - origin).dot(direction), 0.0f, interval);
Vector3 proj = origin + direction * d;
real_t dist = proj.distance_squared_to(p_to_point);
@@ -1836,8 +1983,6 @@ real_t Curve3D::get_closest_offset(const Vector3 &p_to_point) const {
nearest = offset + d;
nearest_dist = dist;
}
-
- offset += bake_interval;
}
return nearest;
@@ -1942,6 +2087,50 @@ PackedVector3Array Curve3D::tessellate(int p_max_stages, real_t p_tolerance) con
return tess;
}
+Vector<RBMap<real_t, Vector3>> Curve3D::_tessellate_even_length(int p_max_stages, real_t p_length) const {
+ Vector<RBMap<real_t, Vector3>> midpoints;
+ ERR_FAIL_COND_V_MSG(points.size() < 2, midpoints, "Curve must have at least 2 control point");
+
+ midpoints.resize(points.size() - 1);
+
+ for (int i = 0; i < points.size() - 1; i++) {
+ _bake_segment3d_even_length(midpoints.write[i], 0, 1, points[i].position, points[i].out, points[i + 1].position, points[i + 1].in, 0, p_max_stages, p_length);
+ }
+ return midpoints;
+}
+
+PackedVector3Array Curve3D::tessellate_even_length(int p_max_stages, real_t p_length) const {
+ PackedVector3Array tess;
+
+ Vector<RBMap<real_t, Vector3>> midpoints = _tessellate_even_length(p_max_stages, p_length);
+ if (midpoints.size() == 0) {
+ return tess;
+ }
+
+ int pc = 1;
+ for (int i = 0; i < points.size() - 1; i++) {
+ pc++;
+ pc += midpoints[i].size();
+ }
+
+ tess.resize(pc);
+ Vector3 *bpw = tess.ptrw();
+ bpw[0] = points[0].position;
+ int pidx = 0;
+
+ for (int i = 0; i < points.size() - 1; i++) {
+ for (const KeyValue<real_t, Vector3> &E : midpoints[i]) {
+ pidx++;
+ bpw[pidx] = E.value;
+ }
+
+ pidx++;
+ bpw[pidx] = points[i + 1].position;
+ }
+
+ return tess;
+}
+
bool Curve3D::_set(const StringName &p_name, const Variant &p_value) {
Vector<String> components = String(p_name).split("/", true, 2);
if (components.size() >= 2 && components[0].begins_with("point_") && components[0].trim_prefix("point_").is_valid_int()) {
@@ -2033,7 +2222,8 @@ void Curve3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("is_up_vector_enabled"), &Curve3D::is_up_vector_enabled);
ClassDB::bind_method(D_METHOD("get_baked_length"), &Curve3D::get_baked_length);
- ClassDB::bind_method(D_METHOD("sample_baked", "offset", "cubic"), &Curve3D::sample_baked, DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("sample_baked", "offset", "cubic"), &Curve3D::sample_baked, DEFVAL(0.0), DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("sample_baked_with_rotation", "offset", "cubic", "apply_tilt"), &Curve3D::sample_baked_with_rotation, DEFVAL(0.0), DEFVAL(false), DEFVAL(false));
ClassDB::bind_method(D_METHOD("sample_baked_up_vector", "offset", "apply_tilt"), &Curve3D::sample_baked_up_vector, DEFVAL(false));
ClassDB::bind_method(D_METHOD("get_baked_points"), &Curve3D::get_baked_points);
ClassDB::bind_method(D_METHOD("get_baked_tilts"), &Curve3D::get_baked_tilts);
@@ -2041,6 +2231,7 @@ void Curve3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_closest_point", "to_point"), &Curve3D::get_closest_point);
ClassDB::bind_method(D_METHOD("get_closest_offset", "to_point"), &Curve3D::get_closest_offset);
ClassDB::bind_method(D_METHOD("tessellate", "max_stages", "tolerance_degrees"), &Curve3D::tessellate, DEFVAL(5), DEFVAL(4));
+ ClassDB::bind_method(D_METHOD("tessellate_even_length", "max_stages", "tolerance_length"), &Curve3D::tessellate_even_length, DEFVAL(5), DEFVAL(0.2));
ClassDB::bind_method(D_METHOD("_get_data"), &Curve3D::_get_data);
ClassDB::bind_method(D_METHOD("_set_data", "data"), &Curve3D::_set_data);
diff --git a/scene/resources/curve.h b/scene/resources/curve.h
index fa1d35aab1..26608c47cd 100644
--- a/scene/resources/curve.h
+++ b/scene/resources/curve.h
@@ -172,16 +172,27 @@ class Curve2D : public Resource {
mutable bool baked_cache_dirty = false;
mutable PackedVector2Array baked_point_cache;
+ mutable PackedVector2Array baked_forward_vector_cache;
mutable Vector<real_t> baked_dist_cache;
mutable real_t baked_max_ofs = 0.0;
void mark_dirty();
+ static Vector2 _calculate_tangent(const Vector2 &p_begin, const Vector2 &p_control_1, const Vector2 &p_control_2, const Vector2 &p_end, const real_t p_t);
void _bake() const;
real_t bake_interval = 5.0;
+ struct Interval {
+ int idx;
+ real_t frac;
+ };
+ Interval _find_interval(real_t p_offset) const;
+ Vector2 _sample_baked(Interval p_interval, bool p_cubic) const;
+ Transform2D _sample_posture(Interval p_interval) const;
+
void _bake_segment2d(RBMap<real_t, Vector2> &r_bake, real_t p_begin, real_t p_end, const Vector2 &p_a, const Vector2 &p_out, const Vector2 &p_b, const Vector2 &p_in, int p_depth, int p_max_depth, real_t p_tol) const;
+ void _bake_segment2d_even_length(RBMap<real_t, Vector2> &r_bake, real_t p_begin, real_t p_end, const Vector2 &p_a, const Vector2 &p_out, const Vector2 &p_b, const Vector2 &p_in, int p_depth, int p_max_depth, real_t p_length) const;
Dictionary _get_data() const;
void _set_data(const Dictionary &p_data);
@@ -192,6 +203,8 @@ class Curve2D : public Resource {
void _add_point(const Vector2 &p_position, const Vector2 &p_in = Vector2(), const Vector2 &p_out = Vector2(), int p_atpos = -1);
void _remove_point(int p_index);
+ Vector<RBMap<real_t, Vector2>> _tessellate_even_length(int p_max_stages = 5, real_t p_length = 0.2) const;
+
protected:
static void _bind_methods();
@@ -216,12 +229,13 @@ public:
real_t get_baked_length() const;
Vector2 sample_baked(real_t p_offset, bool p_cubic = false) const;
- Transform2D sample_baked_with_rotation(real_t p_offset, bool p_cubic = false, bool p_loop = true, real_t p_lookahead = 4.0) const;
+ Transform2D sample_baked_with_rotation(real_t p_offset, bool p_cubic = false) const;
PackedVector2Array get_baked_points() const; //useful for going through
Vector2 get_closest_point(const Vector2 &p_to_point) const;
real_t get_closest_offset(const Vector2 &p_to_point) const;
PackedVector2Array tessellate(int p_max_stages = 5, real_t p_tolerance = 4) const; //useful for display
+ PackedVector2Array tessellate_even_length(int p_max_stages = 5, real_t p_length = 20.0) const; // Useful for baking.
Curve2D();
};
@@ -238,26 +252,33 @@ class Curve3D : public Resource {
Vector<Point> points;
- struct BakedPoint {
- real_t ofs = 0.0;
- Vector3 point;
- };
-
mutable bool baked_cache_dirty = false;
mutable PackedVector3Array baked_point_cache;
mutable Vector<real_t> baked_tilt_cache;
mutable PackedVector3Array baked_up_vector_cache;
+ mutable PackedVector3Array baked_forward_vector_cache;
mutable Vector<real_t> baked_dist_cache;
mutable real_t baked_max_ofs = 0.0;
void mark_dirty();
+ static Vector3 _calculate_tangent(const Vector3 &p_begin, const Vector3 &p_control_1, const Vector3 &p_control_2, const Vector3 &p_end, const real_t p_t);
void _bake() const;
+ struct Interval {
+ int idx;
+ real_t frac;
+ };
+ Interval _find_interval(real_t p_offset) const;
+ Vector3 _sample_baked(Interval p_interval, bool p_cubic) const;
+ real_t _sample_baked_tilt(Interval p_interval) const;
+ Basis _sample_posture(Interval p_interval, bool p_apply_tilt = false) const;
+
real_t bake_interval = 0.2;
bool up_vector_enabled = true;
void _bake_segment3d(RBMap<real_t, Vector3> &r_bake, real_t p_begin, real_t p_end, const Vector3 &p_a, const Vector3 &p_out, const Vector3 &p_b, const Vector3 &p_in, int p_depth, int p_max_depth, real_t p_tol) const;
+ void _bake_segment3d_even_length(RBMap<real_t, Vector3> &r_bake, real_t p_begin, real_t p_end, const Vector3 &p_a, const Vector3 &p_out, const Vector3 &p_b, const Vector3 &p_in, int p_depth, int p_max_depth, real_t p_length) const;
Dictionary _get_data() const;
void _set_data(const Dictionary &p_data);
@@ -268,6 +289,8 @@ class Curve3D : public Resource {
void _add_point(const Vector3 &p_position, const Vector3 &p_in = Vector3(), const Vector3 &p_out = Vector3(), int p_atpos = -1);
void _remove_point(int p_index);
+ Vector<RBMap<real_t, Vector3>> _tessellate_even_length(int p_max_stages = 5, real_t p_length = 0.2) const;
+
protected:
static void _bind_methods();
@@ -296,15 +319,17 @@ public:
real_t get_baked_length() const;
Vector3 sample_baked(real_t p_offset, bool p_cubic = false) const;
+ Transform3D sample_baked_with_rotation(real_t p_offset, bool p_cubic = false, bool p_apply_tilt = false) const;
real_t sample_baked_tilt(real_t p_offset) const;
Vector3 sample_baked_up_vector(real_t p_offset, bool p_apply_tilt = false) const;
- PackedVector3Array get_baked_points() const; //useful for going through
+ PackedVector3Array get_baked_points() const; // Useful for going through.
Vector<real_t> get_baked_tilts() const; //useful for going through
PackedVector3Array get_baked_up_vectors() const;
Vector3 get_closest_point(const Vector3 &p_to_point) const;
real_t get_closest_offset(const Vector3 &p_to_point) const;
- PackedVector3Array tessellate(int p_max_stages = 5, real_t p_tolerance = 4) const; //useful for display
+ PackedVector3Array tessellate(int p_max_stages = 5, real_t p_tolerance = 4) const; // Useful for display.
+ PackedVector3Array tessellate_even_length(int p_max_stages = 5, real_t p_length = 0.2) const; // Useful for baking.
Curve3D();
};
diff --git a/scene/resources/default_theme/default_theme.cpp b/scene/resources/default_theme/default_theme.cpp
index 894936acd7..571ddee763 100644
--- a/scene/resources/default_theme/default_theme.cpp
+++ b/scene/resources/default_theme/default_theme.cpp
@@ -84,7 +84,8 @@ static Ref<ImageTexture> generate_icon(int p_index) {
// with integer scales.
const bool upsample = !Math::is_equal_approx(Math::round(scale), scale);
ImageLoaderSVG img_loader;
- img_loader.create_image_from_string(img, default_theme_icons_sources[p_index], scale, upsample, HashMap<Color, Color>());
+ Error err = img_loader.create_image_from_string(img, default_theme_icons_sources[p_index], scale, upsample, HashMap<Color, Color>());
+ ERR_FAIL_COND_V_MSG(err != OK, Ref<ImageTexture>(), "Failed generating icon, unsupported or invalid SVG data in default theme.");
#endif
return ImageTexture::create_from_image(img);
@@ -99,6 +100,11 @@ static Ref<StyleBox> make_empty_stylebox(float p_margin_left = -1, float p_margi
void fill_default_theme(Ref<Theme> &theme, const Ref<Font> &default_font, const Ref<Font> &bold_font, const Ref<Font> &bold_italics_font, const Ref<Font> &italics_font, Ref<Texture2D> &default_icon, Ref<StyleBox> &default_style, float p_scale) {
scale = p_scale;
+ // Default theme properties.
+ theme->set_default_font(default_font);
+ theme->set_default_font_size(default_font_size * scale);
+ theme->set_default_base_scale(scale);
+
// Font colors
const Color control_font_color = Color(0.875, 0.875, 0.875);
const Color control_font_low_color = Color(0.7, 0.7, 0.7);
diff --git a/scene/resources/font.cpp b/scene/resources/font.cpp
index 185b6f4bdc..584a7e7eac 100644
--- a/scene/resources/font.cpp
+++ b/scene/resources/font.cpp
@@ -63,6 +63,8 @@ void Font::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_font_name"), &Font::get_font_name);
ClassDB::bind_method(D_METHOD("get_font_style_name"), &Font::get_font_style_name);
ClassDB::bind_method(D_METHOD("get_font_style"), &Font::get_font_style);
+ ClassDB::bind_method(D_METHOD("get_font_weight"), &Font::get_font_weight);
+ ClassDB::bind_method(D_METHOD("get_font_stretch"), &Font::get_font_stretch);
ClassDB::bind_method(D_METHOD("get_spacing", "spacing"), &Font::get_spacing);
ClassDB::bind_method(D_METHOD("get_opentype_features"), &Font::get_opentype_features);
@@ -249,6 +251,14 @@ BitField<TextServer::FontStyle> Font::get_font_style() const {
return TS->font_get_style(_get_rid());
}
+int Font::get_font_weight() const {
+ return TS->font_get_weight(_get_rid());
+}
+
+int Font::get_font_stretch() const {
+ return TS->font_get_stretch(_get_rid());
+}
+
Dictionary Font::get_opentype_features() const {
return Dictionary();
}
@@ -590,6 +600,7 @@ _FORCE_INLINE_ void FontFile::_ensure_rid(int p_cache_index) const {
TS->font_set_msdf_size(cache[p_cache_index], msdf_size);
TS->font_set_fixed_size(cache[p_cache_index], fixed_size);
TS->font_set_force_autohinter(cache[p_cache_index], force_autohinter);
+ TS->font_set_allow_system_fallback(cache[p_cache_index], allow_system_fallback);
TS->font_set_hinting(cache[p_cache_index], hinting);
TS->font_set_subpixel_positioning(cache[p_cache_index], subpixel_positioning);
TS->font_set_oversampling(cache[p_cache_index], oversampling);
@@ -881,6 +892,8 @@ void FontFile::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_font_name", "name"), &FontFile::set_font_name);
ClassDB::bind_method(D_METHOD("set_font_style_name", "name"), &FontFile::set_font_style_name);
ClassDB::bind_method(D_METHOD("set_font_style", "style"), &FontFile::set_font_style);
+ ClassDB::bind_method(D_METHOD("set_font_weight", "weight"), &FontFile::set_font_weight);
+ ClassDB::bind_method(D_METHOD("set_font_stretch", "stretch"), &FontFile::set_font_stretch);
ClassDB::bind_method(D_METHOD("set_antialiasing", "antialiasing"), &FontFile::set_antialiasing);
ClassDB::bind_method(D_METHOD("get_antialiasing"), &FontFile::get_antialiasing);
@@ -900,6 +913,9 @@ void FontFile::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_fixed_size", "fixed_size"), &FontFile::set_fixed_size);
ClassDB::bind_method(D_METHOD("get_fixed_size"), &FontFile::get_fixed_size);
+ ClassDB::bind_method(D_METHOD("set_allow_system_fallback", "allow_system_fallback"), &FontFile::set_allow_system_fallback);
+ ClassDB::bind_method(D_METHOD("is_allow_system_fallback"), &FontFile::is_allow_system_fallback);
+
ClassDB::bind_method(D_METHOD("set_force_autohinter", "force_autohinter"), &FontFile::set_force_autohinter);
ClassDB::bind_method(D_METHOD("is_force_autohinter"), &FontFile::is_force_autohinter);
@@ -1007,16 +1023,20 @@ void FontFile::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::STRING, "font_name", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE), "set_font_name", "get_font_name");
ADD_PROPERTY(PropertyInfo(Variant::STRING, "style_name", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE), "set_font_style_name", "get_font_style_name");
ADD_PROPERTY(PropertyInfo(Variant::INT, "font_style", PROPERTY_HINT_FLAGS, "Bold,Italic,Fixed Size", PROPERTY_USAGE_STORAGE), "set_font_style", "get_font_style");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "font_weight", PROPERTY_HINT_RANGE, "100,999,25", PROPERTY_USAGE_STORAGE), "set_font_weight", "get_font_weight");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "font_stretch", PROPERTY_HINT_RANGE, "50,200,25", PROPERTY_USAGE_STORAGE), "set_font_stretch", "get_font_stretch");
+
ADD_PROPERTY(PropertyInfo(Variant::INT, "subpixel_positioning", PROPERTY_HINT_ENUM, "Disabled,Auto,One Half of a Pixel,One Quarter of a Pixel", PROPERTY_USAGE_STORAGE), "set_subpixel_positioning", "get_subpixel_positioning");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "multichannel_signed_distance_field", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE), "set_multichannel_signed_distance_field", "is_multichannel_signed_distance_field");
ADD_PROPERTY(PropertyInfo(Variant::INT, "msdf_pixel_range", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE), "set_msdf_pixel_range", "get_msdf_pixel_range");
ADD_PROPERTY(PropertyInfo(Variant::INT, "msdf_size", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE), "set_msdf_size", "get_msdf_size");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "allow_system_fallback", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE), "set_allow_system_fallback", "is_allow_system_fallback");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "force_autohinter", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE), "set_force_autohinter", "is_force_autohinter");
ADD_PROPERTY(PropertyInfo(Variant::INT, "hinting", PROPERTY_HINT_ENUM, "None,Light,Normal", PROPERTY_USAGE_STORAGE), "set_hinting", "get_hinting");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "oversampling", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE), "set_oversampling", "get_oversampling");
ADD_PROPERTY(PropertyInfo(Variant::INT, "fixed_size", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE), "set_fixed_size", "get_fixed_size");
ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "opentype_feature_overrides", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE), "set_opentype_feature_overrides", "get_opentype_feature_overrides");
- ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "fallbacks", PROPERTY_HINT_ARRAY_TYPE, vformat("%s/%s:%s", Variant::OBJECT, PROPERTY_HINT_RESOURCE_TYPE, "Font"), PROPERTY_USAGE_STORAGE), "set_fallbacks", "get_fallbacks");
+ ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "fallbacks", PROPERTY_HINT_ARRAY_TYPE, MAKE_RESOURCE_TYPE_HINT("Font"), PROPERTY_USAGE_STORAGE), "set_fallbacks", "get_fallbacks");
}
bool FontFile::_set(const StringName &p_name, const Variant &p_value) {
@@ -1329,6 +1349,7 @@ void FontFile::reset_state() {
mipmaps = false;
msdf = false;
force_autohinter = false;
+ allow_system_fallback = true;
hinting = TextServer::HINTING_LIGHT;
subpixel_positioning = TextServer::SUBPIXEL_POSITIONING_DISABLED;
msdf_pixel_range = 14;
@@ -1361,6 +1382,7 @@ Error FontFile::load_bitmap_font(const String &p_path) {
mipmaps = false;
msdf = false;
force_autohinter = false;
+ allow_system_fallback = true;
hinting = TextServer::HINTING_NONE;
oversampling = 1.0f;
@@ -1396,6 +1418,9 @@ Error FontFile::load_bitmap_font(const String &p_path) {
case 1: /* info */ {
ERR_FAIL_COND_V_MSG(block_size < 15, ERR_CANT_CREATE, RTR("Invalid BMFont info block size."));
base_size = f->get_16();
+ if (base_size <= 0) {
+ base_size = 16;
+ }
uint8_t flags = f->get_8();
if (flags & (1 << 3)) {
st_flags.set_flag(TextServer::FONT_BOLD);
@@ -1681,7 +1706,6 @@ Error FontFile::load_bitmap_font(const String &p_path) {
if (type == "info") {
if (keys.has("size")) {
base_size = keys["size"].to_int();
- set_fixed_size(base_size);
}
if (keys.has("outline")) {
outline = keys["outline"].to_int();
@@ -1730,6 +1754,7 @@ Error FontFile::load_bitmap_font(const String &p_path) {
encoding = 2;
}
}
+ set_fixed_size(base_size);
} else if (type == "common") {
if (keys.has("lineHeight")) {
height = keys["lineHeight"].to_int();
@@ -1788,7 +1813,10 @@ Error FontFile::load_bitmap_font(const String &p_path) {
ERR_FAIL_V_MSG(ERR_CANT_CREATE, RTR("Unsupported BMFont texture format."));
}
} else {
- if ((ch[0] == 0) && (ch[1] == 0) && (ch[2] == 0) && (ch[3] == 0)) { // RGBA8 color, no outline
+ if ((ch[3] == 0) && (ch[0] == 4) && (ch[1] == 4) && (ch[2] == 4) && img->get_format() == Image::FORMAT_RGBA8) { // might be RGBA8 color, no outline (color part of the image should be sold white, but some apps designed for Godot 3 generate color fonts with this config)
+ outline = 0;
+ set_texture_image(0, Vector2i(base_size, 0), page, img);
+ } else if ((ch[0] == 0) && (ch[1] == 0) && (ch[2] == 0) && (ch[3] == 0)) { // RGBA8 color, no outline
outline = 0;
ERR_FAIL_COND_V_MSG(img->get_format() != Image::FORMAT_RGBA8, ERR_FILE_CANT_READ, RTR("Unsupported BMFont texture format."));
set_texture_image(0, Vector2i(base_size, 0), page, img);
@@ -1931,6 +1959,9 @@ Error FontFile::load_bitmap_font(const String &p_path) {
set_font_name(font_name);
set_font_style(st_flags);
+ if (st_flags & TextServer::FONT_BOLD) {
+ set_font_weight(700);
+ }
set_cache_ascent(0, base_size, ascent);
set_cache_descent(0, base_size, height - ascent);
@@ -1940,7 +1971,7 @@ Error FontFile::load_bitmap_font(const String &p_path) {
Error FontFile::load_dynamic_font(const String &p_path) {
reset_state();
- Vector<uint8_t> font_data = FileAccess::get_file_as_array(p_path);
+ Vector<uint8_t> font_data = FileAccess::get_file_as_bytes(p_path);
set_data(font_data);
return OK;
@@ -1994,6 +2025,16 @@ void FontFile::set_font_style(BitField<TextServer::FontStyle> p_style) {
TS->font_set_style(cache[0], p_style);
}
+void FontFile::set_font_weight(int p_weight) {
+ _ensure_rid(0);
+ TS->font_set_weight(cache[0], p_weight);
+}
+
+void FontFile::set_font_stretch(int p_stretch) {
+ _ensure_rid(0);
+ TS->font_set_stretch(cache[0], p_stretch);
+}
+
void FontFile::set_antialiasing(TextServer::FontAntialiasing p_antialiasing) {
if (antialiasing != p_antialiasing) {
antialiasing = p_antialiasing;
@@ -2084,6 +2125,21 @@ int FontFile::get_fixed_size() const {
return fixed_size;
}
+void FontFile::set_allow_system_fallback(bool p_allow_system_fallback) {
+ if (allow_system_fallback != p_allow_system_fallback) {
+ allow_system_fallback = p_allow_system_fallback;
+ for (int i = 0; i < cache.size(); i++) {
+ _ensure_rid(i);
+ TS->font_set_allow_system_fallback(cache[i], allow_system_fallback);
+ }
+ emit_changed();
+ }
+}
+
+bool FontFile::is_allow_system_fallback() const {
+ return allow_system_fallback;
+}
+
void FontFile::set_force_autohinter(bool p_force_autohinter) {
if (force_autohinter != p_force_autohinter) {
force_autohinter = p_force_autohinter;
@@ -2597,18 +2653,18 @@ void FontVariation::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_spacing", "spacing", "value"), &FontVariation::set_spacing);
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "base_font", PROPERTY_HINT_RESOURCE_TYPE, "Font"), "set_base_font", "get_base_font");
- ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "fallbacks", PROPERTY_HINT_ARRAY_TYPE, vformat("%s/%s:%s", Variant::OBJECT, PROPERTY_HINT_RESOURCE_TYPE, "Font")), "set_fallbacks", "get_fallbacks");
+ ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "fallbacks", PROPERTY_HINT_ARRAY_TYPE, MAKE_RESOURCE_TYPE_HINT("Font")), "set_fallbacks", "get_fallbacks");
- ADD_GROUP("Variation", "variation");
+ ADD_GROUP("Variation", "variation_");
ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "variation_opentype"), "set_variation_opentype", "get_variation_opentype");
ADD_PROPERTY(PropertyInfo(Variant::INT, "variation_face_index"), "set_variation_face_index", "get_variation_face_index");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "variation_embolden", PROPERTY_HINT_RANGE, "-2,2,0.01"), "set_variation_embolden", "get_variation_embolden");
ADD_PROPERTY(PropertyInfo(Variant::TRANSFORM2D, "variation_transform", PROPERTY_HINT_NONE, "suffix:px"), "set_variation_transform", "get_variation_transform");
- ADD_GROUP("OpenType Features", "opentype");
+ ADD_GROUP("OpenType Features", "opentype_");
ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "opentype_features"), "set_opentype_features", "get_opentype_features");
- ADD_GROUP("Extra Spacing", "spacing");
+ ADD_GROUP("Extra Spacing", "spacing_");
ADD_PROPERTYI(PropertyInfo(Variant::INT, "spacing_glyph", PROPERTY_HINT_NONE, "suffix:px"), "set_spacing", "get_spacing", TextServer::SPACING_GLYPH);
ADD_PROPERTYI(PropertyInfo(Variant::INT, "spacing_space", PROPERTY_HINT_NONE, "suffix:px"), "set_spacing", "get_spacing", TextServer::SPACING_SPACE);
ADD_PROPERTYI(PropertyInfo(Variant::INT, "spacing_top", PROPERTY_HINT_NONE, "suffix:px"), "set_spacing", "get_spacing", TextServer::SPACING_TOP);
@@ -2833,6 +2889,9 @@ void SystemFont::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_generate_mipmaps", "generate_mipmaps"), &SystemFont::set_generate_mipmaps);
ClassDB::bind_method(D_METHOD("get_generate_mipmaps"), &SystemFont::get_generate_mipmaps);
+ ClassDB::bind_method(D_METHOD("set_allow_system_fallback", "allow_system_fallback"), &SystemFont::set_allow_system_fallback);
+ ClassDB::bind_method(D_METHOD("is_allow_system_fallback"), &SystemFont::is_allow_system_fallback);
+
ClassDB::bind_method(D_METHOD("set_force_autohinter", "force_autohinter"), &SystemFont::set_force_autohinter);
ClassDB::bind_method(D_METHOD("is_force_autohinter"), &SystemFont::is_force_autohinter);
@@ -2851,18 +2910,24 @@ void SystemFont::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_font_names"), &SystemFont::get_font_names);
ClassDB::bind_method(D_METHOD("set_font_names", "names"), &SystemFont::set_font_names);
- ClassDB::bind_method(D_METHOD("set_font_style", "style"), &SystemFont::set_font_style);
+ ClassDB::bind_method(D_METHOD("get_font_italic"), &SystemFont::get_font_italic);
+ ClassDB::bind_method(D_METHOD("set_font_italic", "italic"), &SystemFont::set_font_italic);
+ ClassDB::bind_method(D_METHOD("set_font_weight", "weight"), &SystemFont::set_font_weight);
+ ClassDB::bind_method(D_METHOD("set_font_stretch", "stretch"), &SystemFont::set_font_stretch);
ADD_PROPERTY(PropertyInfo(Variant::PACKED_STRING_ARRAY, "font_names"), "set_font_names", "get_font_names");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "font_style", PROPERTY_HINT_FLAGS, "Bold,Italic"), "set_font_style", "get_font_style");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "font_italic"), "set_font_italic", "get_font_italic");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "font_weight", PROPERTY_HINT_RANGE, "100,999,25"), "set_font_weight", "get_font_weight");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "font_stretch", PROPERTY_HINT_RANGE, "50,200,25"), "set_font_stretch", "get_font_stretch");
ADD_PROPERTY(PropertyInfo(Variant::INT, "antialiasing", PROPERTY_HINT_ENUM, "None,Grayscale,LCD Subpixel", PROPERTY_USAGE_STORAGE), "set_antialiasing", "get_antialiasing");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "generate_mipmaps"), "set_generate_mipmaps", "get_generate_mipmaps");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "allow_system_fallback"), "set_allow_system_fallback", "is_allow_system_fallback");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "force_autohinter"), "set_force_autohinter", "is_force_autohinter");
ADD_PROPERTY(PropertyInfo(Variant::INT, "hinting", PROPERTY_HINT_ENUM, "None,Light,Normal"), "set_hinting", "get_hinting");
ADD_PROPERTY(PropertyInfo(Variant::INT, "subpixel_positioning", PROPERTY_HINT_ENUM, "Disabled,Auto,One Half of a Pixel,One Quarter of a Pixel"), "set_subpixel_positioning", "get_subpixel_positioning");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "multichannel_signed_distance_field"), "set_multichannel_signed_distance_field", "is_multichannel_signed_distance_field");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "oversampling", PROPERTY_HINT_RANGE, "0,10,0.1"), "set_oversampling", "get_oversampling");
- ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "fallbacks", PROPERTY_HINT_ARRAY_TYPE, vformat("%s/%s:%s", Variant::OBJECT, PROPERTY_HINT_RESOURCE_TYPE, "Font")), "set_fallbacks", "get_fallbacks");
+ ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "fallbacks", PROPERTY_HINT_ARRAY_TYPE, MAKE_RESOURCE_TYPE_HINT("Font")), "set_fallbacks", "get_fallbacks");
}
void SystemFont::_update_rids() const {
@@ -2893,13 +2958,14 @@ void SystemFont::_update_base_font() {
face_indeces.clear();
ftr_weight = 0;
+ ftr_stretch = 0;
ftr_italic = 0;
for (const String &E : names) {
if (E.is_empty()) {
continue;
}
- String path = OS::get_singleton()->get_system_font_path(E, style & TextServer::FONT_BOLD, style & TextServer::FONT_ITALIC);
+ String path = OS::get_singleton()->get_system_font_path(E, weight, stretch, italic);
if (path.is_empty()) {
continue;
}
@@ -2911,9 +2977,22 @@ void SystemFont::_update_base_font() {
}
// If it's a font collection check all faces to match requested style.
+ int best_score = 0;
for (int i = 0; i < file->get_face_count(); i++) {
file->set_face_index(0, i);
- if (((file->get_font_style() & TextServer::FONT_BOLD) == (style & TextServer::FONT_BOLD)) && ((file->get_font_style() & TextServer::FONT_ITALIC) == (style & TextServer::FONT_ITALIC))) {
+ BitField<TextServer::FontStyle> style = file->get_font_style();
+ int font_weight = file->get_font_weight();
+ int font_stretch = file->get_font_stretch();
+ int score = (20 - Math::abs(font_weight - weight) / 50);
+ score += (20 - Math::abs(font_stretch - stretch) / 10);
+ if (bool(style & TextServer::FONT_ITALIC) == italic) {
+ score += 30;
+ }
+ if (score > best_score) {
+ face_indeces.clear();
+ }
+ if (score >= best_score) {
+ best_score = score;
face_indeces.push_back(i);
}
}
@@ -2922,19 +3001,25 @@ void SystemFont::_update_base_font() {
}
file->set_face_index(0, face_indeces[0]);
- // If it's a variable font, apply weight and italic coordinates to match requested style.
- Dictionary ftr = file->get_supported_variation_list();
- if ((style & TextServer::FONT_BOLD) && ftr.has(TS->name_to_tag("weight"))) {
- ftr_weight = 700;
- }
- if ((style & TextServer::FONT_ITALIC) && ftr.has(TS->name_to_tag("italic"))) {
- ftr_italic = 1;
+ // If it's a variable font, apply weight, stretch and italic coordinates to match requested style.
+ if (best_score != 50) {
+ Dictionary ftr = file->get_supported_variation_list();
+ if (ftr.has(TS->name_to_tag("width"))) {
+ ftr_stretch = stretch;
+ }
+ if (ftr.has(TS->name_to_tag("weight"))) {
+ ftr_weight = weight;
+ }
+ if (italic && ftr.has(TS->name_to_tag("italic"))) {
+ ftr_italic = 1;
+ }
}
// Apply font rendering settings.
file->set_antialiasing(antialiasing);
file->set_generate_mipmaps(mipmaps);
file->set_force_autohinter(force_autohinter);
+ file->set_allow_system_fallback(allow_system_fallback);
file->set_hinting(hinting);
file->set_subpixel_positioning(subpixel_positioning);
file->set_multichannel_signed_distance_field(msdf);
@@ -2967,11 +3052,15 @@ void SystemFont::reset_state() {
names.clear();
face_indeces.clear();
ftr_weight = 0;
+ ftr_stretch = 0;
ftr_italic = 0;
- style = 0;
+ italic = false;
+ weight = 400;
+ stretch = 100;
antialiasing = TextServer::FONT_ANTIALIASING_GRAY;
mipmaps = false;
force_autohinter = false;
+ allow_system_fallback = true;
hinting = TextServer::HINTING_LIGHT;
subpixel_positioning = TextServer::SUBPIXEL_POSITIONING_DISABLED;
oversampling = 0.f;
@@ -3063,6 +3152,20 @@ bool SystemFont::get_generate_mipmaps() const {
return mipmaps;
}
+void SystemFont::set_allow_system_fallback(bool p_allow_system_fallback) {
+ if (allow_system_fallback != p_allow_system_fallback) {
+ allow_system_fallback = p_allow_system_fallback;
+ if (base_font.is_valid()) {
+ base_font->set_allow_system_fallback(allow_system_fallback);
+ }
+ emit_changed();
+ }
+}
+
+bool SystemFont::is_allow_system_fallback() const {
+ return allow_system_fallback;
+}
+
void SystemFont::set_force_autohinter(bool p_force_autohinter) {
if (force_autohinter != p_force_autohinter) {
force_autohinter = p_force_autohinter;
@@ -3144,15 +3247,37 @@ PackedStringArray SystemFont::get_font_names() const {
return names;
}
-void SystemFont::set_font_style(BitField<TextServer::FontStyle> p_style) {
- if (style != p_style) {
- style = p_style;
+void SystemFont::set_font_italic(bool p_italic) {
+ if (italic != p_italic) {
+ italic = p_italic;
_update_base_font();
}
}
-BitField<TextServer::FontStyle> SystemFont::get_font_style() const {
- return style;
+bool SystemFont::get_font_italic() const {
+ return italic;
+}
+
+void SystemFont::set_font_weight(int p_weight) {
+ if (weight != p_weight) {
+ weight = CLAMP(p_weight, 100, 999);
+ _update_base_font();
+ }
+}
+
+int SystemFont::get_font_weight() const {
+ return weight;
+}
+
+void SystemFont::set_font_stretch(int p_stretch) {
+ if (stretch != p_stretch) {
+ stretch = CLAMP(p_stretch, 50, 200);
+ _update_base_font();
+ }
+}
+
+int SystemFont::get_font_stretch() const {
+ return stretch;
}
int SystemFont::get_spacing(TextServer::SpacingType p_spacing) const {
@@ -3170,6 +3295,9 @@ RID SystemFont::find_variation(const Dictionary &p_variation_coordinates, int p_
if (ftr_weight > 0 && !var.has(TS->name_to_tag("weight"))) {
var[TS->name_to_tag("weight")] = ftr_weight;
}
+ if (ftr_stretch > 0 && !var.has(TS->name_to_tag("width"))) {
+ var[TS->name_to_tag("width")] = ftr_stretch;
+ }
if (ftr_italic > 0 && !var.has(TS->name_to_tag("italic"))) {
var[TS->name_to_tag("italic")] = ftr_italic;
}
@@ -3192,6 +3320,9 @@ RID SystemFont::_get_rid() const {
if (ftr_weight > 0) {
var[TS->name_to_tag("weight")] = ftr_weight;
}
+ if (ftr_stretch > 0) {
+ var[TS->name_to_tag("width")] = ftr_stretch;
+ }
if (ftr_italic > 0) {
var[TS->name_to_tag("italic")] = ftr_italic;
}
diff --git a/scene/resources/font.h b/scene/resources/font.h
index 5cf596b41d..e9f7507652 100644
--- a/scene/resources/font.h
+++ b/scene/resources/font.h
@@ -92,6 +92,8 @@ public:
virtual String get_font_name() const;
virtual String get_font_style_name() const;
virtual BitField<TextServer::FontStyle> get_font_style() const;
+ virtual int get_font_weight() const;
+ virtual int get_font_stretch() const;
virtual int get_spacing(TextServer::SpacingType p_spacing) const { return 0; };
virtual Dictionary get_opentype_features() const;
@@ -148,6 +150,7 @@ class FontFile : public Font {
int msdf_size = 48;
int fixed_size = 0;
bool force_autohinter = false;
+ bool allow_system_fallback = true;
TextServer::Hinting hinting = TextServer::HINTING_LIGHT;
TextServer::SubpixelPositioning subpixel_positioning = TextServer::SUBPIXEL_POSITIONING_AUTO;
real_t oversampling = 0.f;
@@ -191,6 +194,8 @@ public:
virtual void set_font_name(const String &p_name);
virtual void set_font_style_name(const String &p_name);
virtual void set_font_style(BitField<TextServer::FontStyle> p_style);
+ virtual void set_font_weight(int p_weight);
+ virtual void set_font_stretch(int p_stretch);
virtual void set_antialiasing(TextServer::FontAntialiasing p_antialiasing);
virtual TextServer::FontAntialiasing get_antialiasing() const;
@@ -210,6 +215,9 @@ public:
virtual void set_fixed_size(int p_fixed_size);
virtual int get_fixed_size() const;
+ virtual void set_allow_system_fallback(bool p_allow_system_fallback);
+ virtual bool is_allow_system_fallback() const;
+
virtual void set_force_autohinter(bool p_force_autohinter);
virtual bool is_force_autohinter() const;
@@ -389,18 +397,22 @@ class SystemFont : public Font {
GDCLASS(SystemFont, Font);
PackedStringArray names;
- BitField<TextServer::FontStyle> style = 0;
+ bool italic = false;
+ int weight = 400;
+ int stretch = 100;
mutable Ref<Font> theme_font;
Ref<FontFile> base_font;
Vector<int> face_indeces;
int ftr_weight = 0;
+ int ftr_stretch = 0;
int ftr_italic = 0;
TextServer::FontAntialiasing antialiasing = TextServer::FONT_ANTIALIASING_GRAY;
bool mipmaps = false;
bool force_autohinter = false;
+ bool allow_system_fallback = true;
TextServer::Hinting hinting = TextServer::HINTING_LIGHT;
TextServer::SubpixelPositioning subpixel_positioning = TextServer::SUBPIXEL_POSITIONING_AUTO;
real_t oversampling = 0.f;
@@ -423,6 +435,9 @@ public:
virtual void set_generate_mipmaps(bool p_generate_mipmaps);
virtual bool get_generate_mipmaps() const;
+ virtual void set_allow_system_fallback(bool p_allow_system_fallback);
+ virtual bool is_allow_system_fallback() const;
+
virtual void set_force_autohinter(bool p_force_autohinter);
virtual bool is_force_autohinter() const;
@@ -441,8 +456,14 @@ public:
virtual void set_font_names(const PackedStringArray &p_names);
virtual PackedStringArray get_font_names() const;
- virtual void set_font_style(BitField<TextServer::FontStyle> p_style);
- virtual BitField<TextServer::FontStyle> get_font_style() const override;
+ virtual void set_font_italic(bool p_italic);
+ virtual bool get_font_italic() const;
+
+ virtual void set_font_weight(int p_weight);
+ virtual int get_font_weight() const override;
+
+ virtual void set_font_stretch(int p_stretch);
+ virtual int get_font_stretch() const override;
virtual int get_spacing(TextServer::SpacingType p_spacing) const override;
diff --git a/scene/resources/importer_mesh.cpp b/scene/resources/importer_mesh.cpp
index b728c24e0d..d1278f9340 100644
--- a/scene/resources/importer_mesh.cpp
+++ b/scene/resources/importer_mesh.cpp
@@ -255,7 +255,7 @@ void ImporterMesh::set_surface_material(int p_surface, const Ref<Material> &p_ma
}
#define VERTEX_SKIN_FUNC(bone_count, vert_idx, read_array, write_array, transform_array, bone_array, weight_array) \
- Vector3 transformed_vert = Vector3(); \
+ Vector3 transformed_vert; \
for (unsigned int weight_idx = 0; weight_idx < bone_count; weight_idx++) { \
int bone_idx = bone_array[vert_idx * bone_count + weight_idx]; \
float w = weight_array[vert_idx * bone_count + weight_idx]; \
@@ -971,10 +971,10 @@ Vector<Ref<Shape3D>> ImporterMesh::convex_decompose(const Mesh::ConvexDecomposit
return ret;
}
-Ref<Shape3D> ImporterMesh::create_trimesh_shape() const {
+Ref<ConcavePolygonShape3D> ImporterMesh::create_trimesh_shape() const {
Vector<Face3> faces = get_faces();
if (faces.size() == 0) {
- return Ref<Shape3D>();
+ return Ref<ConcavePolygonShape3D>();
}
Vector<Vector3> face_points;
diff --git a/scene/resources/importer_mesh.h b/scene/resources/importer_mesh.h
index 088a77edd1..bbd6498fcf 100644
--- a/scene/resources/importer_mesh.h
+++ b/scene/resources/importer_mesh.h
@@ -119,7 +119,7 @@ public:
Vector<Face3> get_faces() const;
Vector<Ref<Shape3D>> convex_decompose(const Mesh::ConvexDecompositionSettings &p_settings) const;
- Ref<Shape3D> create_trimesh_shape() const;
+ Ref<ConcavePolygonShape3D> create_trimesh_shape() const;
Ref<NavigationMesh> create_navigation_mesh();
Error lightmap_unwrap_cached(const Transform3D &p_base_transform, float p_texel_size, const Vector<uint8_t> &p_src_cache, Vector<uint8_t> &r_dst_cache);
diff --git a/scene/resources/label_settings.cpp b/scene/resources/label_settings.cpp
index ef380a68f9..c49620ce27 100644
--- a/scene/resources/label_settings.cpp
+++ b/scene/resources/label_settings.cpp
@@ -66,16 +66,16 @@ void LabelSettings::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "line_spacing", PROPERTY_HINT_NONE, "suffix:px"), "set_line_spacing", "get_line_spacing");
- ADD_GROUP("Font", "font");
+ ADD_GROUP("Font", "font_");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "font", PROPERTY_HINT_RESOURCE_TYPE, "Font"), "set_font", "get_font");
ADD_PROPERTY(PropertyInfo(Variant::INT, "font_size", PROPERTY_HINT_RANGE, "1,1024,1,or_greater,suffix:px"), "set_font_size", "get_font_size");
ADD_PROPERTY(PropertyInfo(Variant::COLOR, "font_color"), "set_font_color", "get_font_color");
- ADD_GROUP("Outline", "outline");
+ ADD_GROUP("Outline", "outline_");
ADD_PROPERTY(PropertyInfo(Variant::INT, "outline_size", PROPERTY_HINT_RANGE, "0,127,1,or_greater,suffix:px"), "set_outline_size", "get_outline_size");
ADD_PROPERTY(PropertyInfo(Variant::COLOR, "outline_color"), "set_outline_color", "get_outline_color");
- ADD_GROUP("Shadow", "shadow");
+ ADD_GROUP("Shadow", "shadow_");
ADD_PROPERTY(PropertyInfo(Variant::INT, "shadow_size", PROPERTY_HINT_RANGE, "0,127,1,or_greater,suffix:px"), "set_shadow_size", "get_shadow_size");
ADD_PROPERTY(PropertyInfo(Variant::COLOR, "shadow_color"), "set_shadow_color", "get_shadow_color");
ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "shadow_offset", PROPERTY_HINT_NONE, "suffix:px"), "set_shadow_offset", "get_shadow_offset");
diff --git a/scene/resources/material.cpp b/scene/resources/material.cpp
index 10d193f950..a16d2c2072 100644
--- a/scene/resources/material.cpp
+++ b/scene/resources/material.cpp
@@ -92,18 +92,13 @@ void Material::inspect_native_shader_code() {
RID Material::get_shader_rid() const {
RID ret;
- if (GDVIRTUAL_REQUIRED_CALL(_get_shader_rid, ret)) {
- return ret;
- }
- return RID();
+ GDVIRTUAL_REQUIRED_CALL(_get_shader_rid, ret);
+ return ret;
}
Shader::Mode Material::get_shader_mode() const {
- Shader::Mode ret;
- if (GDVIRTUAL_REQUIRED_CALL(_get_shader_mode, ret)) {
- return ret;
- }
-
- return Shader::MODE_MAX;
+ Shader::Mode ret = Shader::MODE_MAX;
+ GDVIRTUAL_REQUIRED_CALL(_get_shader_mode, ret);
+ return ret;
}
bool Material::_can_do_next_pass() const {
@@ -1257,15 +1252,16 @@ void BaseMaterial3D::_update_shader() {
}
if (distance_fade != DISTANCE_FADE_DISABLED) {
+ // Use the slightly more expensive circular fade (distance to the object) instead of linear
+ // (Z distance), so that the fade is always the same regardless of the camera angle.
if ((distance_fade == DISTANCE_FADE_OBJECT_DITHER || distance_fade == DISTANCE_FADE_PIXEL_DITHER)) {
if (!RenderingServer::get_singleton()->is_low_end()) {
code += " {\n";
if (distance_fade == DISTANCE_FADE_OBJECT_DITHER) {
- code += " float fade_distance = abs((VIEW_MATRIX * MODEL_MATRIX[3]).z);\n";
-
+ code += " float fade_distance = length((VIEW_MATRIX * MODEL_MATRIX[3]));\n";
} else {
- code += " float fade_distance = -VERTEX.z;\n";
+ code += " float fade_distance = length(VERTEX);\n";
}
// Use interleaved gradient noise, which is fast but still looks good.
code += " const vec3 magic = vec3(0.06711056f, 0.00583715f, 52.9829189f);";
@@ -1279,7 +1275,7 @@ void BaseMaterial3D::_update_shader() {
}
} else {
- code += " ALPHA*=clamp(smoothstep(distance_fade_min,distance_fade_max,-VERTEX.z),0.0,1.0);\n";
+ code += " ALPHA *= clamp(smoothstep(distance_fade_min, distance_fade_max, length(VERTEX)), 0.0, 1.0);\n";
}
}
diff --git a/scene/resources/mesh.cpp b/scene/resources/mesh.cpp
index 706db3af16..af770ddede 100644
--- a/scene/resources/mesh.cpp
+++ b/scene/resources/mesh.cpp
@@ -40,119 +40,83 @@
Mesh::ConvexDecompositionFunc Mesh::convex_decomposition_function = nullptr;
int Mesh::get_surface_count() const {
- int ret;
- if (GDVIRTUAL_REQUIRED_CALL(_get_surface_count, ret)) {
- return ret;
- }
- return 0;
+ int ret = 0;
+ GDVIRTUAL_REQUIRED_CALL(_get_surface_count, ret);
+ return ret;
}
int Mesh::surface_get_array_len(int p_idx) const {
- int ret;
- if (GDVIRTUAL_REQUIRED_CALL(_surface_get_array_len, p_idx, ret)) {
- return ret;
- }
- return 0;
+ int ret = 0;
+ GDVIRTUAL_REQUIRED_CALL(_surface_get_array_len, p_idx, ret);
+ return ret;
}
int Mesh::surface_get_array_index_len(int p_idx) const {
- int ret;
- if (GDVIRTUAL_REQUIRED_CALL(_surface_get_array_index_len, p_idx, ret)) {
- return ret;
- }
- return 0;
+ int ret = 0;
+ GDVIRTUAL_REQUIRED_CALL(_surface_get_array_index_len, p_idx, ret);
+ return ret;
}
Array Mesh::surface_get_arrays(int p_surface) const {
Array ret;
- if (GDVIRTUAL_REQUIRED_CALL(_surface_get_arrays, p_surface, ret)) {
- return ret;
- }
- return Array();
+ GDVIRTUAL_REQUIRED_CALL(_surface_get_arrays, p_surface, ret);
+ return ret;
}
TypedArray<Array> Mesh::surface_get_blend_shape_arrays(int p_surface) const {
TypedArray<Array> ret;
- if (GDVIRTUAL_REQUIRED_CALL(_surface_get_blend_shape_arrays, p_surface, ret)) {
- return ret;
- }
-
- return TypedArray<Array>();
+ GDVIRTUAL_REQUIRED_CALL(_surface_get_blend_shape_arrays, p_surface, ret);
+ return ret;
}
Dictionary Mesh::surface_get_lods(int p_surface) const {
Dictionary ret;
- if (GDVIRTUAL_REQUIRED_CALL(_surface_get_lods, p_surface, ret)) {
- return ret;
- }
-
- return Dictionary();
+ GDVIRTUAL_REQUIRED_CALL(_surface_get_lods, p_surface, ret);
+ return ret;
}
uint32_t Mesh::surface_get_format(int p_idx) const {
- uint32_t ret;
- if (GDVIRTUAL_REQUIRED_CALL(_surface_get_format, p_idx, ret)) {
- return ret;
- }
-
- return 0;
+ uint32_t ret = 0;
+ GDVIRTUAL_REQUIRED_CALL(_surface_get_format, p_idx, ret);
+ return ret;
}
Mesh::PrimitiveType Mesh::surface_get_primitive_type(int p_idx) const {
- uint32_t ret;
- if (GDVIRTUAL_REQUIRED_CALL(_surface_get_primitive_type, p_idx, ret)) {
- return (Mesh::PrimitiveType)ret;
- }
-
- return PRIMITIVE_MAX;
+ uint32_t ret = PRIMITIVE_MAX;
+ GDVIRTUAL_REQUIRED_CALL(_surface_get_primitive_type, p_idx, ret);
+ return (Mesh::PrimitiveType)ret;
}
void Mesh::surface_set_material(int p_idx, const Ref<Material> &p_material) {
- if (GDVIRTUAL_REQUIRED_CALL(_surface_set_material, p_idx, p_material)) {
- return;
- }
+ GDVIRTUAL_REQUIRED_CALL(_surface_set_material, p_idx, p_material);
}
Ref<Material> Mesh::surface_get_material(int p_idx) const {
Ref<Material> ret;
- if (GDVIRTUAL_REQUIRED_CALL(_surface_get_material, p_idx, ret)) {
- return ret;
- }
-
- return Ref<Material>();
+ GDVIRTUAL_REQUIRED_CALL(_surface_get_material, p_idx, ret);
+ return ret;
}
int Mesh::get_blend_shape_count() const {
- int ret;
- if (GDVIRTUAL_REQUIRED_CALL(_get_blend_shape_count, ret)) {
- return ret;
- }
-
- return 0;
+ int ret = 0;
+ GDVIRTUAL_REQUIRED_CALL(_get_blend_shape_count, ret);
+ return ret;
}
StringName Mesh::get_blend_shape_name(int p_index) const {
StringName ret;
- if (GDVIRTUAL_REQUIRED_CALL(_get_blend_shape_name, p_index, ret)) {
- return ret;
- }
-
- return StringName();
+ GDVIRTUAL_REQUIRED_CALL(_get_blend_shape_name, p_index, ret);
+ return ret;
}
void Mesh::set_blend_shape_name(int p_index, const StringName &p_name) {
- if (GDVIRTUAL_REQUIRED_CALL(_set_blend_shape_name, p_index, p_name)) {
- return;
- }
+ GDVIRTUAL_REQUIRED_CALL(_set_blend_shape_name, p_index, p_name);
}
AABB Mesh::get_aabb() const {
AABB ret;
- if (GDVIRTUAL_REQUIRED_CALL(_get_aabb, ret)) {
- return ret;
- }
-
- return AABB();
+ GDVIRTUAL_REQUIRED_CALL(_get_aabb, ret);
+ return ret;
}
Ref<TriangleMesh> Mesh::generate_triangle_mesh() const {
@@ -388,7 +352,7 @@ Vector<Face3> Mesh::get_surface_faces(int p_surface) const {
return Vector<Face3>();
}
-Ref<Shape3D> Mesh::create_convex_shape(bool p_clean, bool p_simplify) const {
+Ref<ConvexPolygonShape3D> Mesh::create_convex_shape(bool p_clean, bool p_simplify) const {
if (p_simplify) {
ConvexDecompositionSettings settings;
settings.max_convex_hulls = 1;
@@ -425,10 +389,10 @@ Ref<Shape3D> Mesh::create_convex_shape(bool p_clean, bool p_simplify) const {
return shape;
}
-Ref<Shape3D> Mesh::create_trimesh_shape() const {
+Ref<ConcavePolygonShape3D> Mesh::create_trimesh_shape() const {
Vector<Face3> faces = get_faces();
if (faces.size() == 0) {
- return Ref<Shape3D>();
+ return Ref<ConcavePolygonShape3D>();
}
Vector<Vector3> face_points;
@@ -940,7 +904,7 @@ void _fix_array_compatibility(const Vector<uint8_t> &p_src, uint32_t p_old_forma
dst[0] = (int16_t)CLAMP(src[0] / 127.0f * 32767, -32768, 32767);
dst[1] = (int16_t)CLAMP(src[1] / 127.0f * 32767, -32768, 32767);
}
- src_offset += sizeof(int16_t) * 2;
+ src_offset += sizeof(int8_t) * 2;
} else {
for (uint32_t i = 0; i < p_elements; i++) {
const int16_t *src = (const int16_t *)&src_vertex_ptr[i * src_vertex_stride + src_offset];
@@ -962,7 +926,7 @@ void _fix_array_compatibility(const Vector<uint8_t> &p_src, uint32_t p_old_forma
dst[0] = (uint16_t)CLAMP(res.x * 65535, 0, 65535);
dst[1] = (uint16_t)CLAMP(res.y * 65535, 0, 65535);
}
- src_offset += sizeof(uint16_t) * 2;
+ src_offset += sizeof(uint8_t) * 4; // 1 byte padding
} else {
for (uint32_t i = 0; i < p_elements; i++) {
const float *src = (const float *)&src_vertex_ptr[i * src_vertex_stride + src_offset];
@@ -973,7 +937,7 @@ void _fix_array_compatibility(const Vector<uint8_t> &p_src, uint32_t p_old_forma
dst[0] = (uint16_t)CLAMP(res.x * 65535, 0, 65535);
dst[1] = (uint16_t)CLAMP(res.y * 65535, 0, 65535);
}
- src_offset += sizeof(uint16_t) * 2;
+ src_offset += sizeof(float) * 3;
}
}
@@ -988,7 +952,7 @@ void _fix_array_compatibility(const Vector<uint8_t> &p_src, uint32_t p_old_forma
dst[0] = (uint16_t)CLAMP((src[0] / 127.0f * .5f + .5f) * 65535, 0, 65535);
dst[1] = (uint16_t)CLAMP((src[1] / 127.0f * .5f + .5f) * 65535, 0, 65535);
}
- src_offset += sizeof(uint16_t) * 2;
+ src_offset += sizeof(uint8_t) * 2;
} else { // int16 SNORM -> uint16 UNORM
for (uint32_t i = 0; i < p_elements; i++) {
const int16_t *src = (const int16_t *)&src_vertex_ptr[i * src_vertex_stride + src_offset];
@@ -1010,7 +974,7 @@ void _fix_array_compatibility(const Vector<uint8_t> &p_src, uint32_t p_old_forma
dst[0] = (uint16_t)CLAMP(res.x * 65535, 0, 65535);
dst[1] = (uint16_t)CLAMP(res.y * 65535, 0, 65535);
}
- src_offset += sizeof(uint16_t) * 2;
+ src_offset += sizeof(uint8_t) * 4;
} else {
for (uint32_t i = 0; i < p_elements; i++) {
const float *src = (const float *)&src_vertex_ptr[i * src_vertex_stride + src_offset];
@@ -1021,7 +985,7 @@ void _fix_array_compatibility(const Vector<uint8_t> &p_src, uint32_t p_old_forma
dst[0] = (uint16_t)CLAMP(res.x * 65535, 0, 65535);
dst[1] = (uint16_t)CLAMP(res.y * 65535, 0, 65535);
}
- src_offset += sizeof(uint16_t) * 2;
+ src_offset += sizeof(float) * 4;
}
}
} break;
@@ -1154,7 +1118,19 @@ bool ArrayMesh::_set(const StringName &p_name, const Variant &p_value) {
if (sl == -1) {
return false;
}
- int idx = sname.substr(8, sl - 8).to_int() - 1;
+ int idx = sname.substr(8, sl - 8).to_int();
+
+ // This is a bit of a hack to ensure compatibility with older material
+ // overrides that start indexing at 1.
+ // We assume that idx 0 is always read first, if its not, this won't work.
+ if (idx == 0) {
+ surface_index_0 = true;
+ }
+ if (!surface_index_0) {
+ // This means the file was created when the indexing started at 1, so decrease by one.
+ idx--;
+ }
+
String what = sname.get_slicec('/', 1);
if (what == "material") {
surface_set_material(idx, p_value);
@@ -1527,7 +1503,7 @@ bool ArrayMesh::_get(const StringName &p_name, Variant &r_ret) const {
if (sl == -1) {
return false;
}
- int idx = sname.substr(8, sl - 8).to_int() - 1;
+ int idx = sname.substr(8, sl - 8).to_int();
String what = sname.get_slicec('/', 1);
if (what == "material") {
r_ret = surface_get_material(idx);
@@ -1555,11 +1531,11 @@ void ArrayMesh::_get_property_list(List<PropertyInfo> *p_list) const {
}
for (int i = 0; i < surfaces.size(); i++) {
- p_list->push_back(PropertyInfo(Variant::STRING, "surface_" + itos(i + 1) + "/name", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR));
+ p_list->push_back(PropertyInfo(Variant::STRING, "surface_" + itos(i) + "/name", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR));
if (surfaces[i].is_2d) {
- p_list->push_back(PropertyInfo(Variant::OBJECT, "surface_" + itos(i + 1) + "/material", PROPERTY_HINT_RESOURCE_TYPE, "CanvasItemMaterial,ShaderMaterial", PROPERTY_USAGE_EDITOR));
+ p_list->push_back(PropertyInfo(Variant::OBJECT, "surface_" + itos(i) + "/material", PROPERTY_HINT_RESOURCE_TYPE, "CanvasItemMaterial,ShaderMaterial", PROPERTY_USAGE_EDITOR));
} else {
- p_list->push_back(PropertyInfo(Variant::OBJECT, "surface_" + itos(i + 1) + "/material", PROPERTY_HINT_RESOURCE_TYPE, "BaseMaterial3D,ShaderMaterial", PROPERTY_USAGE_EDITOR));
+ p_list->push_back(PropertyInfo(Variant::OBJECT, "surface_" + itos(i) + "/material", PROPERTY_HINT_RESOURCE_TYPE, "BaseMaterial3D,ShaderMaterial", PROPERTY_USAGE_EDITOR));
}
}
}
diff --git a/scene/resources/mesh.h b/scene/resources/mesh.h
index 5ed4164117..fabc09a42c 100644
--- a/scene/resources/mesh.h
+++ b/scene/resources/mesh.h
@@ -35,9 +35,12 @@
#include "core/math/face3.h"
#include "core/math/triangle_mesh.h"
#include "scene/resources/material.h"
-#include "scene/resources/shape_3d.h"
#include "servers/rendering_server.h"
+class ConcavePolygonShape3D;
+class ConvexPolygonShape3D;
+class Shape3D;
+
class Mesh : public Resource {
GDCLASS(Mesh, Resource);
@@ -211,8 +214,8 @@ public:
static ConvexDecompositionFunc convex_decomposition_function;
Vector<Ref<Shape3D>> convex_decompose(const ConvexDecompositionSettings &p_settings) const;
- Ref<Shape3D> create_convex_shape(bool p_clean = true, bool p_simplify = false) const;
- Ref<Shape3D> create_trimesh_shape() const;
+ Ref<ConvexPolygonShape3D> create_convex_shape(bool p_clean = true, bool p_simplify = false) const;
+ Ref<ConcavePolygonShape3D> create_trimesh_shape() const;
virtual int get_builtin_bind_pose_count() const;
virtual Transform3D get_builtin_bind_pose(int p_index) const;
@@ -259,6 +262,7 @@ protected:
bool _set(const StringName &p_name, const Variant &p_value);
bool _get(const StringName &p_name, Variant &r_ret) const;
void _get_property_list(List<PropertyInfo> *p_list) const;
+ bool surface_index_0 = false;
virtual void reset_state() override;
diff --git a/scene/resources/mesh_library.cpp b/scene/resources/mesh_library.cpp
index 7c78b757c7..858146da96 100644
--- a/scene/resources/mesh_library.cpp
+++ b/scene/resources/mesh_library.cpp
@@ -57,10 +57,18 @@ bool MeshLibrary::_set(const StringName &p_name, const Variant &p_value) {
_set_item_shapes(idx, p_value);
} else if (what == "preview") {
set_item_preview(idx, p_value);
- } else if (what == "navmesh") {
- set_item_navmesh(idx, p_value);
- } else if (what == "navmesh_transform") {
- set_item_navmesh_transform(idx, p_value);
+ } else if (what == "navigation_mesh") {
+ set_item_navigation_mesh(idx, p_value);
+ } else if (what == "navigation_mesh_transform") {
+ set_item_navigation_mesh_transform(idx, p_value);
+#ifndef DISABLE_DEPRECATED
+ } else if (what == "navmesh") { // Renamed in 4.0 beta 9.
+ set_item_navigation_mesh(idx, p_value);
+ } else if (what == "navmesh_transform") { // Renamed in 4.0 beta 9.
+ set_item_navigation_mesh_transform(idx, p_value);
+#endif // DISABLE_DEPRECATED
+ } else if (what == "navigation_layers") {
+ set_item_navigation_layers(idx, p_value);
} else {
return false;
}
@@ -85,10 +93,18 @@ bool MeshLibrary::_get(const StringName &p_name, Variant &r_ret) const {
r_ret = get_item_mesh_transform(idx);
} else if (what == "shapes") {
r_ret = _get_item_shapes(idx);
- } else if (what == "navmesh") {
- r_ret = get_item_navmesh(idx);
- } else if (what == "navmesh_transform") {
- r_ret = get_item_navmesh_transform(idx);
+ } else if (what == "navigation_mesh") {
+ r_ret = get_item_navigation_mesh(idx);
+ } else if (what == "navigation_mesh_transform") {
+ r_ret = get_item_navigation_mesh_transform(idx);
+#ifndef DISABLE_DEPRECATED
+ } else if (what == "navmesh") { // Renamed in 4.0 beta 9.
+ r_ret = get_item_navigation_mesh(idx);
+ } else if (what == "navmesh_transform") { // Renamed in 4.0 beta 9.
+ r_ret = get_item_navigation_mesh_transform(idx);
+#endif // DISABLE_DEPRECATED
+ } else if (what == "navigation_layers") {
+ r_ret = get_item_navigation_layers(idx);
} else if (what == "preview") {
r_ret = get_item_preview(idx);
} else {
@@ -105,8 +121,9 @@ void MeshLibrary::_get_property_list(List<PropertyInfo> *p_list) const {
p_list->push_back(PropertyInfo(Variant::OBJECT, prop_name + PNAME("mesh"), PROPERTY_HINT_RESOURCE_TYPE, "Mesh"));
p_list->push_back(PropertyInfo(Variant::TRANSFORM3D, prop_name + PNAME("mesh_transform"), PROPERTY_HINT_NONE, "suffix:m"));
p_list->push_back(PropertyInfo(Variant::ARRAY, prop_name + PNAME("shapes")));
- p_list->push_back(PropertyInfo(Variant::OBJECT, prop_name + PNAME("navmesh"), PROPERTY_HINT_RESOURCE_TYPE, "NavigationMesh"));
- p_list->push_back(PropertyInfo(Variant::TRANSFORM3D, prop_name + PNAME("navmesh_transform"), PROPERTY_HINT_NONE, "suffix:m"));
+ p_list->push_back(PropertyInfo(Variant::OBJECT, prop_name + PNAME("navigation_mesh"), PROPERTY_HINT_RESOURCE_TYPE, "NavigationMesh"));
+ p_list->push_back(PropertyInfo(Variant::TRANSFORM3D, prop_name + PNAME("navigation_mesh_transform"), PROPERTY_HINT_NONE, "suffix:m"));
+ p_list->push_back(PropertyInfo(Variant::INT, prop_name + PNAME("navigation_layers"), PROPERTY_HINT_LAYERS_3D_NAVIGATION));
p_list->push_back(PropertyInfo(Variant::OBJECT, prop_name + PNAME("preview"), PROPERTY_HINT_RESOURCE_TYPE, "Texture2D", PROPERTY_USAGE_DEFAULT));
}
}
@@ -150,18 +167,27 @@ void MeshLibrary::set_item_shapes(int p_item, const Vector<ShapeData> &p_shapes)
notify_property_list_changed();
}
-void MeshLibrary::set_item_navmesh(int p_item, const Ref<NavigationMesh> &p_navmesh) {
+void MeshLibrary::set_item_navigation_mesh(int p_item, const Ref<NavigationMesh> &p_navigation_mesh) {
ERR_FAIL_COND_MSG(!item_map.has(p_item), "Requested for nonexistent MeshLibrary item '" + itos(p_item) + "'.");
- item_map[p_item].navmesh = p_navmesh;
+ item_map[p_item].navigation_mesh = p_navigation_mesh;
notify_property_list_changed();
notify_change_to_owners();
emit_changed();
notify_property_list_changed();
}
-void MeshLibrary::set_item_navmesh_transform(int p_item, const Transform3D &p_transform) {
+void MeshLibrary::set_item_navigation_mesh_transform(int p_item, const Transform3D &p_transform) {
ERR_FAIL_COND_MSG(!item_map.has(p_item), "Requested for nonexistent MeshLibrary item '" + itos(p_item) + "'.");
- item_map[p_item].navmesh_transform = p_transform;
+ item_map[p_item].navigation_mesh_transform = p_transform;
+ notify_change_to_owners();
+ emit_changed();
+ notify_property_list_changed();
+}
+
+void MeshLibrary::set_item_navigation_layers(int p_item, uint32_t p_navigation_layers) {
+ ERR_FAIL_COND_MSG(!item_map.has(p_item), "Requested for nonexistent MeshLibrary item '" + itos(p_item) + "'.");
+ item_map[p_item].navigation_layers = p_navigation_layers;
+ notify_property_list_changed();
notify_change_to_owners();
emit_changed();
notify_property_list_changed();
@@ -194,14 +220,19 @@ Vector<MeshLibrary::ShapeData> MeshLibrary::get_item_shapes(int p_item) const {
return item_map[p_item].shapes;
}
-Ref<NavigationMesh> MeshLibrary::get_item_navmesh(int p_item) const {
+Ref<NavigationMesh> MeshLibrary::get_item_navigation_mesh(int p_item) const {
ERR_FAIL_COND_V_MSG(!item_map.has(p_item), Ref<NavigationMesh>(), "Requested for nonexistent MeshLibrary item '" + itos(p_item) + "'.");
- return item_map[p_item].navmesh;
+ return item_map[p_item].navigation_mesh;
}
-Transform3D MeshLibrary::get_item_navmesh_transform(int p_item) const {
+Transform3D MeshLibrary::get_item_navigation_mesh_transform(int p_item) const {
ERR_FAIL_COND_V_MSG(!item_map.has(p_item), Transform3D(), "Requested for nonexistent MeshLibrary item '" + itos(p_item) + "'.");
- return item_map[p_item].navmesh_transform;
+ return item_map[p_item].navigation_mesh_transform;
+}
+
+uint32_t MeshLibrary::get_item_navigation_layers(int p_item) const {
+ ERR_FAIL_COND_V_MSG(!item_map.has(p_item), 0, "Requested for nonexistent MeshLibrary item '" + itos(p_item) + "'.");
+ return item_map[p_item].navigation_layers;
}
Ref<Texture2D> MeshLibrary::get_item_preview(int p_item) const {
@@ -314,15 +345,17 @@ void MeshLibrary::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_item_name", "id", "name"), &MeshLibrary::set_item_name);
ClassDB::bind_method(D_METHOD("set_item_mesh", "id", "mesh"), &MeshLibrary::set_item_mesh);
ClassDB::bind_method(D_METHOD("set_item_mesh_transform", "id", "mesh_transform"), &MeshLibrary::set_item_mesh_transform);
- ClassDB::bind_method(D_METHOD("set_item_navmesh", "id", "navmesh"), &MeshLibrary::set_item_navmesh);
- ClassDB::bind_method(D_METHOD("set_item_navmesh_transform", "id", "navmesh"), &MeshLibrary::set_item_navmesh_transform);
+ ClassDB::bind_method(D_METHOD("set_item_navigation_mesh", "id", "navigation_mesh"), &MeshLibrary::set_item_navigation_mesh);
+ ClassDB::bind_method(D_METHOD("set_item_navigation_mesh_transform", "id", "navigation_mesh"), &MeshLibrary::set_item_navigation_mesh_transform);
+ ClassDB::bind_method(D_METHOD("set_item_navigation_layers", "id", "navigation_layers"), &MeshLibrary::set_item_navigation_layers);
ClassDB::bind_method(D_METHOD("set_item_shapes", "id", "shapes"), &MeshLibrary::_set_item_shapes);
ClassDB::bind_method(D_METHOD("set_item_preview", "id", "texture"), &MeshLibrary::set_item_preview);
ClassDB::bind_method(D_METHOD("get_item_name", "id"), &MeshLibrary::get_item_name);
ClassDB::bind_method(D_METHOD("get_item_mesh", "id"), &MeshLibrary::get_item_mesh);
ClassDB::bind_method(D_METHOD("get_item_mesh_transform", "id"), &MeshLibrary::get_item_mesh_transform);
- ClassDB::bind_method(D_METHOD("get_item_navmesh", "id"), &MeshLibrary::get_item_navmesh);
- ClassDB::bind_method(D_METHOD("get_item_navmesh_transform", "id"), &MeshLibrary::get_item_navmesh_transform);
+ ClassDB::bind_method(D_METHOD("get_item_navigation_mesh", "id"), &MeshLibrary::get_item_navigation_mesh);
+ ClassDB::bind_method(D_METHOD("get_item_navigation_mesh_transform", "id"), &MeshLibrary::get_item_navigation_mesh_transform);
+ ClassDB::bind_method(D_METHOD("get_item_navigation_layers", "id"), &MeshLibrary::get_item_navigation_layers);
ClassDB::bind_method(D_METHOD("get_item_shapes", "id"), &MeshLibrary::_get_item_shapes);
ClassDB::bind_method(D_METHOD("get_item_preview", "id"), &MeshLibrary::get_item_preview);
ClassDB::bind_method(D_METHOD("remove_item", "id"), &MeshLibrary::remove_item);
diff --git a/scene/resources/mesh_library.h b/scene/resources/mesh_library.h
index 79acb41c4e..1d5af9e176 100644
--- a/scene/resources/mesh_library.h
+++ b/scene/resources/mesh_library.h
@@ -49,11 +49,12 @@ public:
struct Item {
String name;
Ref<Mesh> mesh;
+ Transform3D mesh_transform;
Vector<ShapeData> shapes;
Ref<Texture2D> preview;
- Transform3D navmesh_transform;
- Transform3D mesh_transform;
- Ref<NavigationMesh> navmesh;
+ Ref<NavigationMesh> navigation_mesh;
+ Transform3D navigation_mesh_transform;
+ uint32_t navigation_layers = 1;
};
RBMap<int, Item> item_map;
@@ -74,15 +75,17 @@ public:
void set_item_name(int p_item, const String &p_name);
void set_item_mesh(int p_item, const Ref<Mesh> &p_mesh);
void set_item_mesh_transform(int p_item, const Transform3D &p_transform);
- void set_item_navmesh(int p_item, const Ref<NavigationMesh> &p_navmesh);
- void set_item_navmesh_transform(int p_item, const Transform3D &p_transform);
+ void set_item_navigation_mesh(int p_item, const Ref<NavigationMesh> &p_navigation_mesh);
+ void set_item_navigation_mesh_transform(int p_item, const Transform3D &p_transform);
+ void set_item_navigation_layers(int p_item, uint32_t p_navigation_layers);
void set_item_shapes(int p_item, const Vector<ShapeData> &p_shapes);
void set_item_preview(int p_item, const Ref<Texture2D> &p_preview);
String get_item_name(int p_item) const;
Ref<Mesh> get_item_mesh(int p_item) const;
Transform3D get_item_mesh_transform(int p_item) const;
- Ref<NavigationMesh> get_item_navmesh(int p_item) const;
- Transform3D get_item_navmesh_transform(int p_item) const;
+ Ref<NavigationMesh> get_item_navigation_mesh(int p_item) const;
+ Transform3D get_item_navigation_mesh_transform(int p_item) const;
+ uint32_t get_item_navigation_layers(int p_item) const;
Vector<ShapeData> get_item_shapes(int p_item) const;
Ref<Texture2D> get_item_preview(int p_item) const;
diff --git a/scene/resources/multimesh.cpp b/scene/resources/multimesh.cpp
index ff4a7a4560..8afb0563b2 100644
--- a/scene/resources/multimesh.cpp
+++ b/scene/resources/multimesh.cpp
@@ -242,6 +242,7 @@ void MultiMesh::set_instance_transform(int p_instance, const Transform3D &p_tran
void MultiMesh::set_instance_transform_2d(int p_instance, const Transform2D &p_transform) {
RenderingServer::get_singleton()->multimesh_instance_set_transform_2d(multimesh, p_instance, p_transform);
+ emit_changed();
}
Transform3D MultiMesh::get_instance_transform(int p_instance) const {
diff --git a/scene/resources/navigation_mesh.cpp b/scene/resources/navigation_mesh.cpp
index de97498674..bf4291869f 100644
--- a/scene/resources/navigation_mesh.cpp
+++ b/scene/resources/navigation_mesh.cpp
@@ -225,13 +225,13 @@ float NavigationMesh::get_edge_max_error() const {
return edge_max_error;
}
-void NavigationMesh::set_verts_per_poly(float p_value) {
+void NavigationMesh::set_vertices_per_polygon(float p_value) {
ERR_FAIL_COND(p_value < 3);
- verts_per_poly = p_value;
+ vertices_per_polygon = p_value;
}
-float NavigationMesh::get_verts_per_poly() const {
- return verts_per_poly;
+float NavigationMesh::get_vertices_per_polygon() const {
+ return vertices_per_polygon;
}
void NavigationMesh::set_detail_sample_distance(float p_value) {
@@ -483,8 +483,8 @@ void NavigationMesh::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_edge_max_error", "edge_max_error"), &NavigationMesh::set_edge_max_error);
ClassDB::bind_method(D_METHOD("get_edge_max_error"), &NavigationMesh::get_edge_max_error);
- ClassDB::bind_method(D_METHOD("set_verts_per_poly", "verts_per_poly"), &NavigationMesh::set_verts_per_poly);
- ClassDB::bind_method(D_METHOD("get_verts_per_poly"), &NavigationMesh::get_verts_per_poly);
+ ClassDB::bind_method(D_METHOD("set_vertices_per_polygon", "vertices_per_polygon"), &NavigationMesh::set_vertices_per_polygon);
+ ClassDB::bind_method(D_METHOD("get_vertices_per_polygon"), &NavigationMesh::get_vertices_per_polygon);
ClassDB::bind_method(D_METHOD("set_detail_sample_distance", "detail_sample_dist"), &NavigationMesh::set_detail_sample_distance);
ClassDB::bind_method(D_METHOD("get_detail_sample_distance"), &NavigationMesh::get_detail_sample_distance);
@@ -527,9 +527,9 @@ void NavigationMesh::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::INT, "geometry_parsed_geometry_type", PROPERTY_HINT_ENUM, "Mesh Instances,Static Colliders,Both"), "set_parsed_geometry_type", "get_parsed_geometry_type");
ADD_PROPERTY(PropertyInfo(Variant::INT, "geometry_collision_mask", PROPERTY_HINT_LAYERS_3D_PHYSICS), "set_collision_mask", "get_collision_mask");
ADD_PROPERTY_DEFAULT("geometry_collision_mask", 0xFFFFFFFF);
- ADD_PROPERTY(PropertyInfo(Variant::INT, "geometry_source_geometry_mode", PROPERTY_HINT_ENUM, "NavMesh Children,Group With Children,Group Explicit"), "set_source_geometry_mode", "get_source_geometry_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "geometry_source_geometry_mode", PROPERTY_HINT_ENUM, "Root Node Children,Group With Children,Group Explicit"), "set_source_geometry_mode", "get_source_geometry_mode");
ADD_PROPERTY(PropertyInfo(Variant::STRING, "geometry_source_group_name"), "set_source_group_name", "get_source_group_name");
- ADD_PROPERTY_DEFAULT("geometry_source_group_name", StringName("navmesh"));
+ ADD_PROPERTY_DEFAULT("geometry_source_group_name", StringName("navigation_mesh_source_group"));
ADD_GROUP("Cells", "cell_");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "cell_size", PROPERTY_HINT_RANGE, "0.01,500.0,0.01,or_greater,suffix:m"), "set_cell_size", "get_cell_size");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "cell_height", PROPERTY_HINT_RANGE, "0.01,500.0,0.01,or_greater,suffix:m"), "set_cell_height", "get_cell_height");
@@ -544,8 +544,8 @@ void NavigationMesh::_bind_methods() {
ADD_GROUP("Edges", "edge_");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "edge_max_length", PROPERTY_HINT_RANGE, "0.0,50.0,0.01,or_greater,suffix:m"), "set_edge_max_length", "get_edge_max_length");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "edge_max_error", PROPERTY_HINT_RANGE, "0.1,3.0,0.01,or_greater,suffix:m"), "set_edge_max_error", "get_edge_max_error");
- ADD_GROUP("Polygons", "polygon_");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "polygon_verts_per_poly", PROPERTY_HINT_RANGE, "3.0,12.0,1.0,or_greater"), "set_verts_per_poly", "get_verts_per_poly");
+ ADD_GROUP("Polygons", "");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "vertices_per_polygon", PROPERTY_HINT_RANGE, "3.0,12.0,1.0,or_greater"), "set_vertices_per_polygon", "get_vertices_per_polygon");
ADD_GROUP("Details", "detail_");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "detail_sample_distance", PROPERTY_HINT_RANGE, "0.1,16.0,0.01,or_greater,suffix:m"), "set_detail_sample_distance", "get_detail_sample_distance");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "detail_sample_max_error", PROPERTY_HINT_RANGE, "0.0,16.0,0.01,or_greater,suffix:m"), "set_detail_sample_max_error", "get_detail_sample_max_error");
@@ -566,7 +566,7 @@ void NavigationMesh::_bind_methods() {
BIND_ENUM_CONSTANT(PARSED_GEOMETRY_BOTH);
BIND_ENUM_CONSTANT(PARSED_GEOMETRY_MAX);
- BIND_ENUM_CONSTANT(SOURCE_GEOMETRY_NAVMESH_CHILDREN);
+ BIND_ENUM_CONSTANT(SOURCE_GEOMETRY_ROOT_NODE_CHILDREN);
BIND_ENUM_CONSTANT(SOURCE_GEOMETRY_GROUPS_WITH_CHILDREN);
BIND_ENUM_CONSTANT(SOURCE_GEOMETRY_GROUPS_EXPLICIT);
BIND_ENUM_CONSTANT(SOURCE_GEOMETRY_MAX);
@@ -581,7 +581,7 @@ void NavigationMesh::_validate_property(PropertyInfo &p_property) const {
}
if (p_property.name == "geometry_source_group_name") {
- if (source_geometry_mode == SOURCE_GEOMETRY_NAVMESH_CHILDREN) {
+ if (source_geometry_mode == SOURCE_GEOMETRY_ROOT_NODE_CHILDREN) {
p_property.usage = PROPERTY_USAGE_NONE;
return;
}
@@ -590,35 +590,16 @@ void NavigationMesh::_validate_property(PropertyInfo &p_property) const {
#ifndef DISABLE_DEPRECATED
bool NavigationMesh::_set(const StringName &p_name, const Variant &p_value) {
- String prop_name = p_name;
- if (prop_name.find("/") != -1) {
- // Compatibility with pre-3.5 "category/path" property names.
- prop_name = prop_name.replace("/", "_");
- if (prop_name == "sample_partition_type_sample_partition_type") {
- set("sample_partition_type", p_value);
- } else if (prop_name == "filter_filter_walkable_low_height_spans") {
- set("filter_walkable_low_height_spans", p_value);
- } else {
- set(prop_name, p_value);
- }
-
+ if (p_name == "polygon_verts_per_poly") { // Renamed in 4.0 beta 9.
+ set_vertices_per_polygon(p_value);
return true;
}
return false;
}
bool NavigationMesh::_get(const StringName &p_name, Variant &r_ret) const {
- String prop_name = p_name;
- if (prop_name.find("/") != -1) {
- // Compatibility with pre-3.5 "category/path" property names.
- prop_name = prop_name.replace("/", "_");
- if (prop_name == "sample_partition_type_sample_partition_type") {
- r_ret = get("sample_partition_type");
- } else if (prop_name == "filter_filter_walkable_low_height_spans") {
- r_ret = get("filter_walkable_low_height_spans");
- } else {
- r_ret = get(prop_name);
- }
+ if (p_name == "polygon_verts_per_poly") { // Renamed in 4.0 beta 9.
+ r_ret = get_vertices_per_polygon();
return true;
}
return false;
diff --git a/scene/resources/navigation_mesh.h b/scene/resources/navigation_mesh.h
index 5ddbd75dcb..3d072423db 100644
--- a/scene/resources/navigation_mesh.h
+++ b/scene/resources/navigation_mesh.h
@@ -84,7 +84,7 @@ public:
};
enum SourceGeometryMode {
- SOURCE_GEOMETRY_NAVMESH_CHILDREN = 0,
+ SOURCE_GEOMETRY_ROOT_NODE_CHILDREN = 0,
SOURCE_GEOMETRY_GROUPS_WITH_CHILDREN,
SOURCE_GEOMETRY_GROUPS_EXPLICIT,
SOURCE_GEOMETRY_MAX
@@ -101,7 +101,7 @@ protected:
float region_merge_size = 20.0f;
float edge_max_length = 12.0f;
float edge_max_error = 1.3f;
- float verts_per_poly = 6.0f;
+ float vertices_per_polygon = 6.0f;
float detail_sample_distance = 6.0f;
float detail_sample_max_error = 1.0f;
@@ -109,8 +109,8 @@ protected:
ParsedGeometryType parsed_geometry_type = PARSED_GEOMETRY_MESH_INSTANCES;
uint32_t collision_mask = 0xFFFFFFFF;
- SourceGeometryMode source_geometry_mode = SOURCE_GEOMETRY_NAVMESH_CHILDREN;
- StringName source_group_name = "navmesh";
+ SourceGeometryMode source_geometry_mode = SOURCE_GEOMETRY_ROOT_NODE_CHILDREN;
+ StringName source_group_name = "navigation_mesh_source_group";
bool filter_low_hanging_obstacles = false;
bool filter_ledge_spans = false;
@@ -168,8 +168,8 @@ public:
void set_edge_max_error(float p_value);
float get_edge_max_error() const;
- void set_verts_per_poly(float p_value);
- float get_verts_per_poly() const;
+ void set_vertices_per_polygon(float p_value);
+ float get_vertices_per_polygon() const;
void set_detail_sample_distance(float p_value);
float get_detail_sample_distance() const;
diff --git a/scene/resources/navigation_polygon.cpp b/scene/resources/navigation_polygon.cpp
new file mode 100644
index 0000000000..04077e95a7
--- /dev/null
+++ b/scene/resources/navigation_polygon.cpp
@@ -0,0 +1,354 @@
+/*************************************************************************/
+/* navigation_polygon.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 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 "navigation_polygon.h"
+
+#include "core/core_string_names.h"
+#include "core/math/geometry_2d.h"
+#include "core/os/mutex.h"
+
+#include "thirdparty/misc/polypartition.h"
+
+#ifdef TOOLS_ENABLED
+Rect2 NavigationPolygon::_edit_get_rect() const {
+ if (rect_cache_dirty) {
+ item_rect = Rect2();
+ bool first = true;
+
+ for (int i = 0; i < outlines.size(); i++) {
+ const Vector<Vector2> &outline = outlines[i];
+ const int outline_size = outline.size();
+ if (outline_size < 3) {
+ continue;
+ }
+ const Vector2 *p = outline.ptr();
+ for (int j = 0; j < outline_size; j++) {
+ if (first) {
+ item_rect = Rect2(p[j], Vector2(0, 0));
+ first = false;
+ } else {
+ item_rect.expand_to(p[j]);
+ }
+ }
+ }
+
+ rect_cache_dirty = false;
+ }
+ return item_rect;
+}
+
+bool NavigationPolygon::_edit_is_selected_on_click(const Point2 &p_point, double p_tolerance) const {
+ for (int i = 0; i < outlines.size(); i++) {
+ const Vector<Vector2> &outline = outlines[i];
+ const int outline_size = outline.size();
+ if (outline_size < 3) {
+ continue;
+ }
+ if (Geometry2D::is_point_in_polygon(p_point, Variant(outline))) {
+ return true;
+ }
+ }
+ return false;
+}
+#endif
+
+void NavigationPolygon::set_vertices(const Vector<Vector2> &p_vertices) {
+ {
+ MutexLock lock(navigation_mesh_generation);
+ navigation_mesh.unref();
+ }
+ vertices = p_vertices;
+ rect_cache_dirty = true;
+}
+
+Vector<Vector2> NavigationPolygon::get_vertices() const {
+ return vertices;
+}
+
+void NavigationPolygon::_set_polygons(const TypedArray<Vector<int32_t>> &p_array) {
+ {
+ MutexLock lock(navigation_mesh_generation);
+ navigation_mesh.unref();
+ }
+ polygons.resize(p_array.size());
+ for (int i = 0; i < p_array.size(); i++) {
+ polygons.write[i].indices = p_array[i];
+ }
+}
+
+TypedArray<Vector<int32_t>> NavigationPolygon::_get_polygons() const {
+ TypedArray<Vector<int32_t>> ret;
+ ret.resize(polygons.size());
+ for (int i = 0; i < ret.size(); i++) {
+ ret[i] = polygons[i].indices;
+ }
+
+ return ret;
+}
+
+void NavigationPolygon::_set_outlines(const TypedArray<Vector<Vector2>> &p_array) {
+ outlines.resize(p_array.size());
+ for (int i = 0; i < p_array.size(); i++) {
+ outlines.write[i] = p_array[i];
+ }
+ rect_cache_dirty = true;
+}
+
+TypedArray<Vector<Vector2>> NavigationPolygon::_get_outlines() const {
+ TypedArray<Vector<Vector2>> ret;
+ ret.resize(outlines.size());
+ for (int i = 0; i < ret.size(); i++) {
+ ret[i] = outlines[i];
+ }
+
+ return ret;
+}
+
+void NavigationPolygon::add_polygon(const Vector<int> &p_polygon) {
+ Polygon polygon;
+ polygon.indices = p_polygon;
+ polygons.push_back(polygon);
+ {
+ MutexLock lock(navigation_mesh_generation);
+ navigation_mesh.unref();
+ }
+}
+
+void NavigationPolygon::add_outline_at_index(const Vector<Vector2> &p_outline, int p_index) {
+ outlines.insert(p_index, p_outline);
+ rect_cache_dirty = true;
+}
+
+int NavigationPolygon::get_polygon_count() const {
+ return polygons.size();
+}
+
+Vector<int> NavigationPolygon::get_polygon(int p_idx) {
+ ERR_FAIL_INDEX_V(p_idx, polygons.size(), Vector<int>());
+ return polygons[p_idx].indices;
+}
+
+void NavigationPolygon::clear_polygons() {
+ polygons.clear();
+ {
+ MutexLock lock(navigation_mesh_generation);
+ navigation_mesh.unref();
+ }
+}
+
+Ref<NavigationMesh> NavigationPolygon::get_navigation_mesh() {
+ MutexLock lock(navigation_mesh_generation);
+
+ if (navigation_mesh.is_null()) {
+ navigation_mesh.instantiate();
+ Vector<Vector3> verts;
+ {
+ verts.resize(get_vertices().size());
+ Vector3 *w = verts.ptrw();
+
+ const Vector2 *r = get_vertices().ptr();
+
+ for (int i(0); i < get_vertices().size(); i++) {
+ w[i] = Vector3(r[i].x, 0.0, r[i].y);
+ }
+ }
+ navigation_mesh->set_vertices(verts);
+
+ for (int i(0); i < get_polygon_count(); i++) {
+ navigation_mesh->add_polygon(get_polygon(i));
+ }
+ }
+
+ return navigation_mesh;
+}
+
+void NavigationPolygon::add_outline(const Vector<Vector2> &p_outline) {
+ outlines.push_back(p_outline);
+ rect_cache_dirty = true;
+}
+
+int NavigationPolygon::get_outline_count() const {
+ return outlines.size();
+}
+
+void NavigationPolygon::set_outline(int p_idx, const Vector<Vector2> &p_outline) {
+ ERR_FAIL_INDEX(p_idx, outlines.size());
+ outlines.write[p_idx] = p_outline;
+ rect_cache_dirty = true;
+}
+
+void NavigationPolygon::remove_outline(int p_idx) {
+ ERR_FAIL_INDEX(p_idx, outlines.size());
+ outlines.remove_at(p_idx);
+ rect_cache_dirty = true;
+}
+
+Vector<Vector2> NavigationPolygon::get_outline(int p_idx) const {
+ ERR_FAIL_INDEX_V(p_idx, outlines.size(), Vector<Vector2>());
+ return outlines[p_idx];
+}
+
+void NavigationPolygon::clear_outlines() {
+ outlines.clear();
+ rect_cache_dirty = true;
+}
+
+void NavigationPolygon::make_polygons_from_outlines() {
+ {
+ MutexLock lock(navigation_mesh_generation);
+ navigation_mesh.unref();
+ }
+ List<TPPLPoly> in_poly, out_poly;
+
+ Vector2 outside_point(-1e10, -1e10);
+
+ for (int i = 0; i < outlines.size(); i++) {
+ Vector<Vector2> ol = outlines[i];
+ int olsize = ol.size();
+ if (olsize < 3) {
+ continue;
+ }
+ const Vector2 *r = ol.ptr();
+ for (int j = 0; j < olsize; j++) {
+ outside_point.x = MAX(r[j].x, outside_point.x);
+ outside_point.y = MAX(r[j].y, outside_point.y);
+ }
+ }
+
+ outside_point += Vector2(0.7239784, 0.819238); //avoid precision issues
+
+ for (int i = 0; i < outlines.size(); i++) {
+ Vector<Vector2> ol = outlines[i];
+ int olsize = ol.size();
+ if (olsize < 3) {
+ continue;
+ }
+ const Vector2 *r = ol.ptr();
+
+ int interscount = 0;
+ //test if this is an outer outline
+ for (int k = 0; k < outlines.size(); k++) {
+ if (i == k) {
+ continue; //no self intersect
+ }
+
+ Vector<Vector2> ol2 = outlines[k];
+ int olsize2 = ol2.size();
+ if (olsize2 < 3) {
+ continue;
+ }
+ const Vector2 *r2 = ol2.ptr();
+
+ for (int l = 0; l < olsize2; l++) {
+ if (Geometry2D::segment_intersects_segment(r[0], outside_point, r2[l], r2[(l + 1) % olsize2], nullptr)) {
+ interscount++;
+ }
+ }
+ }
+
+ bool outer = (interscount % 2) == 0;
+
+ TPPLPoly tp;
+ tp.Init(olsize);
+ for (int j = 0; j < olsize; j++) {
+ tp[j] = r[j];
+ }
+
+ if (outer) {
+ tp.SetOrientation(TPPL_ORIENTATION_CCW);
+ } else {
+ tp.SetOrientation(TPPL_ORIENTATION_CW);
+ tp.SetHole(true);
+ }
+
+ in_poly.push_back(tp);
+ }
+
+ TPPLPartition tpart;
+ if (tpart.ConvexPartition_HM(&in_poly, &out_poly) == 0) { //failed!
+ ERR_PRINT("NavigationPolygon: Convex partition failed! Failed to convert outlines to a valid NavigationMesh."
+ "\nNavigationPolygon outlines can not overlap vertices or edges inside same outline or with other outlines or have any intersections."
+ "\nAdd the outmost and largest outline first. To add holes inside this outline add the smaller outlines with opposite winding order.");
+ return;
+ }
+
+ polygons.clear();
+ vertices.clear();
+
+ HashMap<Vector2, int> points;
+ for (List<TPPLPoly>::Element *I = out_poly.front(); I; I = I->next()) {
+ TPPLPoly &tp = I->get();
+
+ struct Polygon p;
+
+ for (int64_t i = 0; i < tp.GetNumPoints(); i++) {
+ HashMap<Vector2, int>::Iterator E = points.find(tp[i]);
+ if (!E) {
+ E = points.insert(tp[i], vertices.size());
+ vertices.push_back(tp[i]);
+ }
+ p.indices.push_back(E->value);
+ }
+
+ polygons.push_back(p);
+ }
+
+ emit_signal(CoreStringNames::get_singleton()->changed);
+}
+
+void NavigationPolygon::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("set_vertices", "vertices"), &NavigationPolygon::set_vertices);
+ ClassDB::bind_method(D_METHOD("get_vertices"), &NavigationPolygon::get_vertices);
+
+ ClassDB::bind_method(D_METHOD("add_polygon", "polygon"), &NavigationPolygon::add_polygon);
+ ClassDB::bind_method(D_METHOD("get_polygon_count"), &NavigationPolygon::get_polygon_count);
+ ClassDB::bind_method(D_METHOD("get_polygon", "idx"), &NavigationPolygon::get_polygon);
+ ClassDB::bind_method(D_METHOD("clear_polygons"), &NavigationPolygon::clear_polygons);
+ ClassDB::bind_method(D_METHOD("get_navigation_mesh"), &NavigationPolygon::get_navigation_mesh);
+
+ ClassDB::bind_method(D_METHOD("add_outline", "outline"), &NavigationPolygon::add_outline);
+ ClassDB::bind_method(D_METHOD("add_outline_at_index", "outline", "index"), &NavigationPolygon::add_outline_at_index);
+ ClassDB::bind_method(D_METHOD("get_outline_count"), &NavigationPolygon::get_outline_count);
+ ClassDB::bind_method(D_METHOD("set_outline", "idx", "outline"), &NavigationPolygon::set_outline);
+ ClassDB::bind_method(D_METHOD("get_outline", "idx"), &NavigationPolygon::get_outline);
+ ClassDB::bind_method(D_METHOD("remove_outline", "idx"), &NavigationPolygon::remove_outline);
+ ClassDB::bind_method(D_METHOD("clear_outlines"), &NavigationPolygon::clear_outlines);
+ ClassDB::bind_method(D_METHOD("make_polygons_from_outlines"), &NavigationPolygon::make_polygons_from_outlines);
+
+ ClassDB::bind_method(D_METHOD("_set_polygons", "polygons"), &NavigationPolygon::_set_polygons);
+ ClassDB::bind_method(D_METHOD("_get_polygons"), &NavigationPolygon::_get_polygons);
+
+ ClassDB::bind_method(D_METHOD("_set_outlines", "outlines"), &NavigationPolygon::_set_outlines);
+ ClassDB::bind_method(D_METHOD("_get_outlines"), &NavigationPolygon::_get_outlines);
+
+ ADD_PROPERTY(PropertyInfo(Variant::PACKED_VECTOR2_ARRAY, "vertices", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL), "set_vertices", "get_vertices");
+ ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "polygons", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL), "_set_polygons", "_get_polygons");
+ ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "outlines", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL), "_set_outlines", "_get_outlines");
+}
diff --git a/scene/resources/navigation_polygon.h b/scene/resources/navigation_polygon.h
new file mode 100644
index 0000000000..e943cff04e
--- /dev/null
+++ b/scene/resources/navigation_polygon.h
@@ -0,0 +1,94 @@
+/*************************************************************************/
+/* navigation_polygon.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 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 NAVIGATION_POLYGON_H
+#define NAVIGATION_POLYGON_H
+
+#include "scene/2d/node_2d.h"
+#include "scene/resources/navigation_mesh.h"
+
+class NavigationPolygon : public Resource {
+ GDCLASS(NavigationPolygon, Resource);
+
+ Vector<Vector2> vertices;
+ struct Polygon {
+ Vector<int> indices;
+ };
+ Vector<Polygon> polygons;
+ Vector<Vector<Vector2>> outlines;
+
+ mutable Rect2 item_rect;
+ mutable bool rect_cache_dirty = true;
+
+ Mutex navigation_mesh_generation;
+ // Navigation mesh
+ Ref<NavigationMesh> navigation_mesh;
+
+protected:
+ static void _bind_methods();
+
+ void _set_polygons(const TypedArray<Vector<int32_t>> &p_array);
+ TypedArray<Vector<int32_t>> _get_polygons() const;
+
+ void _set_outlines(const TypedArray<Vector<Vector2>> &p_array);
+ TypedArray<Vector<Vector2>> _get_outlines() const;
+
+public:
+#ifdef TOOLS_ENABLED
+ Rect2 _edit_get_rect() const;
+ bool _edit_is_selected_on_click(const Point2 &p_point, double p_tolerance) const;
+#endif
+
+ void set_vertices(const Vector<Vector2> &p_vertices);
+ Vector<Vector2> get_vertices() const;
+
+ void add_polygon(const Vector<int> &p_polygon);
+ int get_polygon_count() const;
+
+ void add_outline(const Vector<Vector2> &p_outline);
+ void add_outline_at_index(const Vector<Vector2> &p_outline, int p_index);
+ void set_outline(int p_idx, const Vector<Vector2> &p_outline);
+ Vector<Vector2> get_outline(int p_idx) const;
+ void remove_outline(int p_idx);
+ int get_outline_count() const;
+
+ void clear_outlines();
+ void make_polygons_from_outlines();
+
+ Vector<int> get_polygon(int p_idx);
+ void clear_polygons();
+
+ Ref<NavigationMesh> get_navigation_mesh();
+
+ NavigationPolygon() {}
+ ~NavigationPolygon() {}
+};
+
+#endif // NAVIGATION_POLYGON_H
diff --git a/scene/resources/packed_scene.cpp b/scene/resources/packed_scene.cpp
index 1c99fa5554..5316b524ba 100644
--- a/scene/resources/packed_scene.cpp
+++ b/scene/resources/packed_scene.cpp
@@ -71,7 +71,7 @@ static Array _sanitize_node_pinned_properties(Node *p_node) {
}
Node *SceneState::instantiate(GenEditState p_edit_state) const {
- // nodes where instancing failed (because something is missing)
+ // Nodes where instantiation failed (because something is missing.)
List<Node *> stray_instances;
#define NODE_FROM_ID(p_name, p_id) \
@@ -122,7 +122,7 @@ Node *SceneState::instantiate(GenEditState p_edit_state) const {
NODE_FROM_ID(nparent, n.parent);
#ifdef DEBUG_ENABLED
if (!nparent && (n.parent & FLAG_ID_IS_PATH)) {
- WARN_PRINT(String("Parent path '" + String(node_paths[n.parent & FLAG_MASK]) + "' for node '" + String(snames[n.name]) + "' has vanished when instancing: '" + get_path() + "'.").ascii().get_data());
+ WARN_PRINT(String("Parent path '" + String(node_paths[n.parent & FLAG_MASK]) + "' for node '" + String(snames[n.name]) + "' has vanished when instantiating: '" + get_path() + "'.").ascii().get_data());
old_parent_path = String(node_paths[n.parent & FLAG_MASK]).trim_prefix("./").replace("/", "@");
nparent = ret_nodes[0];
}
@@ -131,7 +131,7 @@ Node *SceneState::instantiate(GenEditState p_edit_state) const {
} else {
// i == 0 is root node.
ERR_FAIL_COND_V_MSG(n.parent != -1, nullptr, vformat("Invalid scene: root node %s cannot specify a parent node.", snames[n.name]));
- ERR_FAIL_COND_V_MSG(n.type == TYPE_INSTANCED && base_scene_idx < 0, nullptr, vformat("Invalid scene: root node %s in an instance, but there's no base scene.", snames[n.name]));
+ ERR_FAIL_COND_V_MSG(n.type == TYPE_INSTANTIATED && base_scene_idx < 0, nullptr, vformat("Invalid scene: root node %s in an instance, but there's no base scene.", snames[n.name]));
}
Node *node = nullptr;
@@ -169,7 +169,7 @@ Node *SceneState::instantiate(GenEditState p_edit_state) const {
ERR_FAIL_COND_V(!node, nullptr);
}
- } else if (n.type == TYPE_INSTANCED) {
+ } else if (n.type == TYPE_INSTANTIATED) {
//get the node from somewhere, it likely already exists from another instance
if (parent) {
node = parent->_get_child_by_name(snames[n.name]);
@@ -345,7 +345,7 @@ Node *SceneState::instantiate(GenEditState p_edit_state) const {
node->add_to_group(snames[n.groups[j]], true);
}
- if (n.instance >= 0 || n.type != TYPE_INSTANCED || i == 0) {
+ if (n.instance >= 0 || n.type != TYPE_INSTANTIATED || i == 0) {
//if node was not part of instance, must set its name, parenthood and ownership
if (i > 0) {
if (parent) {
@@ -382,7 +382,7 @@ Node *SceneState::instantiate(GenEditState p_edit_state) const {
}
}
- // we only want to deal with pinned flag if instancing as pure main (no instance, no inheriting)
+ // We only want to deal with pinned flag if instantiating as pure main (no instance, no inheriting.)
if (p_edit_state == GEN_EDIT_STATE_MAIN) {
_sanitize_node_pinned_properties(node);
} else {
@@ -450,7 +450,7 @@ Node *SceneState::instantiate(GenEditState p_edit_state) const {
callable = callable.bindp(argptrs, binds.size());
}
- cfrom->connect(snames[c.signal], callable, CONNECT_PERSIST | c.flags);
+ cfrom->connect(snames[c.signal], callable, CONNECT_PERSIST | c.flags | (p_edit_state == GEN_EDIT_STATE_MAIN ? 0 : CONNECT_INHERITED));
}
//Node *s = ret_nodes[0];
@@ -665,7 +665,7 @@ Error SceneState::_parse_node(Node *p_owner, Node *p_node, int p_parent_idx, Has
// Save the right type. If this node was created by an instance
// then flag that the node should not be created but reused
if (states_stack.is_empty() && !is_editable_instance) {
- //this node is not part of an instancing process, so save the type
+ //This node is not part of an instantiation process, so save the type.
if (missing_node != nullptr) {
// It's a missing node (type non existent on load).
nd.type = _nm_get_string(missing_node->get_original_class(), name_map);
@@ -675,7 +675,7 @@ Error SceneState::_parse_node(Node *p_owner, Node *p_node, int p_parent_idx, Has
} else {
// this node is part of an instantiated process, so do not save the type.
// instead, save that it was instantiated
- nd.type = TYPE_INSTANCED;
+ nd.type = TYPE_INSTANTIATED;
}
// determine whether to save this node or not
@@ -1005,6 +1005,37 @@ void SceneState::clear() {
base_scene_idx = -1;
}
+Error SceneState::copy_from(const Ref<SceneState> &p_scene_state) {
+ ERR_FAIL_COND_V(p_scene_state.is_null(), ERR_INVALID_PARAMETER);
+
+ clear();
+
+ for (const StringName &E : p_scene_state->names) {
+ names.append(E);
+ }
+ for (const Variant &E : p_scene_state->variants) {
+ variants.append(E);
+ }
+ for (const SceneState::NodeData &E : p_scene_state->nodes) {
+ nodes.append(E);
+ }
+ for (const SceneState::ConnectionData &E : p_scene_state->connections) {
+ connections.append(E);
+ }
+ for (KeyValue<NodePath, int> &E : p_scene_state->node_path_cache) {
+ node_path_cache.insert(E.key, E.value);
+ }
+ for (const NodePath &E : p_scene_state->node_paths) {
+ node_paths.append(E);
+ }
+ for (const NodePath &E : p_scene_state->editable_instances) {
+ editable_instances.append(E);
+ }
+ base_scene_idx = p_scene_state->base_scene_idx;
+
+ return OK;
+}
+
Ref<SceneState> SceneState::get_base_scene_state() const {
if (base_scene_idx >= 0) {
Ref<PackedScene> ps = variants[base_scene_idx];
@@ -1351,7 +1382,7 @@ int SceneState::get_node_count() const {
StringName SceneState::get_node_type(int p_idx) const {
ERR_FAIL_INDEX_V(p_idx, nodes.size(), StringName());
- if (nodes[p_idx].type == TYPE_INSTANCED) {
+ if (nodes[p_idx].type == TYPE_INSTANTIATED) {
return StringName();
}
return names[nodes[p_idx].type];
@@ -1737,6 +1768,28 @@ void PackedScene::clear() {
state->clear();
}
+void PackedScene::reload_from_file() {
+ String path = get_path();
+ if (!path.is_resource_file()) {
+ return;
+ }
+
+ Ref<PackedScene> s = ResourceLoader::load(ResourceLoader::path_remap(path), get_class(), ResourceFormatLoader::CACHE_MODE_IGNORE);
+ if (!s.is_valid()) {
+ return;
+ }
+
+ // Backup the loaded_state
+ Ref<SceneState> loaded_state = s->get_state();
+ // This assigns a new state to s->state
+ // We do this because of the next step
+ s->recreate_state();
+ // This has a side-effect to clear s->state
+ copy_from(s);
+ // Then, we copy the backed-up loaded_state to state
+ state->copy_from(loaded_state);
+}
+
bool PackedScene::can_instantiate() const {
return state->can_instantiate();
}
diff --git a/scene/resources/packed_scene.h b/scene/resources/packed_scene.h
index c6f82ddd5e..ad1f50cd39 100644
--- a/scene/resources/packed_scene.h
+++ b/scene/resources/packed_scene.h
@@ -108,7 +108,7 @@ protected:
public:
enum {
FLAG_ID_IS_PATH = (1 << 30),
- TYPE_INSTANCED = 0x7FFFFFFF,
+ TYPE_INSTANTIATED = 0x7FFFFFFF,
FLAG_INSTANCE_IS_PLACEHOLDER = (1 << 30),
FLAG_PATH_PROPERTY_IS_NODE = (1 << 30),
FLAG_PROP_NAME_MASK = FLAG_PATH_PROPERTY_IS_NODE - 1,
@@ -143,6 +143,7 @@ public:
String get_path() const;
void clear();
+ Error copy_from(const Ref<SceneState> &p_scene_state);
bool can_instantiate() const;
Node *instantiate(GenEditState p_edit_state) const;
@@ -235,6 +236,8 @@ public:
void recreate_state();
void replace_state(Ref<SceneState> p_by);
+ virtual void reload_from_file() override;
+
virtual void set_path(const String &p_path, bool p_take_over = false) override;
#ifdef TOOLS_ENABLED
virtual void set_last_modified_time(uint64_t p_time) override {
diff --git a/scene/resources/primitive_meshes.cpp b/scene/resources/primitive_meshes.cpp
index eb83a37c7b..54d3676c15 100644
--- a/scene/resources/primitive_meshes.cpp
+++ b/scene/resources/primitive_meshes.cpp
@@ -30,6 +30,7 @@
#include "primitive_meshes.h"
+#include "core/config/project_settings.h"
#include "core/core_string_names.h"
#include "scene/resources/theme.h"
#include "scene/theme/theme_db.h"
@@ -37,6 +38,8 @@
#include "thirdparty/misc/clipper.hpp"
#include "thirdparty/misc/polypartition.h"
+#define PADDING_REF_SIZE 1024.0
+
/**
PrimitiveMesh
*/
@@ -94,6 +97,26 @@ void PrimitiveMesh::_update() const {
}
}
+ if (add_uv2) {
+ // _create_mesh_array should populate our UV2, this is a fallback in case it doesn't.
+ // As we don't know anything about the geometry we only pad the right and bottom edge
+ // of our texture.
+ Vector<Vector2> uv = arr[RS::ARRAY_TEX_UV];
+ Vector<Vector2> uv2 = arr[RS::ARRAY_TEX_UV2];
+
+ if (uv.size() > 0 && uv2.size() == 0) {
+ Vector2 uv2_scale = get_uv2_scale();
+ uv2.resize(uv.size());
+
+ Vector2 *uv2w = uv2.ptrw();
+ for (int i = 0; i < uv.size(); i++) {
+ uv2w[i] = uv[i] * uv2_scale;
+ }
+ }
+
+ arr[RS::ARRAY_TEX_UV2] = uv2;
+ }
+
array_len = pc;
index_array_len = indices.size();
// in with the new
@@ -160,7 +183,12 @@ TypedArray<Array> PrimitiveMesh::surface_get_blend_shape_arrays(int p_surface) c
uint32_t PrimitiveMesh::surface_get_format(int p_idx) const {
ERR_FAIL_INDEX_V(p_idx, 1, 0);
- return RS::ARRAY_FORMAT_VERTEX | RS::ARRAY_FORMAT_NORMAL | RS::ARRAY_FORMAT_TANGENT | RS::ARRAY_FORMAT_TEX_UV | RS::ARRAY_FORMAT_INDEX;
+ uint32_t mesh_format = RS::ARRAY_FORMAT_VERTEX | RS::ARRAY_FORMAT_NORMAL | RS::ARRAY_FORMAT_TANGENT | RS::ARRAY_FORMAT_TEX_UV | RS::ARRAY_FORMAT_INDEX;
+ if (add_uv2) {
+ mesh_format |= RS::ARRAY_FORMAT_TEX_UV2;
+ }
+
+ return mesh_format;
}
Mesh::PrimitiveType PrimitiveMesh::surface_get_primitive_type(int p_idx) const {
@@ -219,9 +247,17 @@ void PrimitiveMesh::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_flip_faces", "flip_faces"), &PrimitiveMesh::set_flip_faces);
ClassDB::bind_method(D_METHOD("get_flip_faces"), &PrimitiveMesh::get_flip_faces);
+ ClassDB::bind_method(D_METHOD("set_add_uv2", "add_uv2"), &PrimitiveMesh::set_add_uv2);
+ ClassDB::bind_method(D_METHOD("get_add_uv2"), &PrimitiveMesh::get_add_uv2);
+
+ ClassDB::bind_method(D_METHOD("set_uv2_padding", "uv2_padding"), &PrimitiveMesh::set_uv2_padding);
+ ClassDB::bind_method(D_METHOD("get_uv2_padding"), &PrimitiveMesh::get_uv2_padding);
+
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "material", PROPERTY_HINT_RESOURCE_TYPE, "BaseMaterial3D,ShaderMaterial"), "set_material", "get_material");
ADD_PROPERTY(PropertyInfo(Variant::AABB, "custom_aabb", PROPERTY_HINT_NONE, "suffix:m"), "set_custom_aabb", "get_custom_aabb");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "flip_faces"), "set_flip_faces", "get_flip_faces");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "add_uv2"), "set_add_uv2", "get_add_uv2");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "uv2_padding"), "set_uv2_padding", "get_uv2_padding");
GDVIRTUAL_BIND(_create_mesh_array);
}
@@ -233,7 +269,7 @@ void PrimitiveMesh::set_material(const Ref<Material> &p_material) {
RenderingServer::get_singleton()->mesh_surface_set_material(mesh, 0, material.is_null() ? RID() : material->get_rid());
notify_property_list_changed();
emit_changed();
- };
+ }
}
Ref<Material> PrimitiveMesh::get_material() const {
@@ -263,6 +299,42 @@ bool PrimitiveMesh::get_flip_faces() const {
return flip_faces;
}
+void PrimitiveMesh::set_add_uv2(bool p_enable) {
+ add_uv2 = p_enable;
+ _update_lightmap_size();
+ _request_update();
+}
+
+void PrimitiveMesh::set_uv2_padding(float p_padding) {
+ uv2_padding = p_padding;
+ _update_lightmap_size();
+ _request_update();
+}
+
+Vector2 PrimitiveMesh::get_uv2_scale(Vector2 p_margin_scale) const {
+ Vector2 uv2_scale;
+ Vector2 lightmap_size = get_lightmap_size_hint();
+
+ // Calculate it as a margin, if no lightmap size hint is given we assume "PADDING_REF_SIZE" as our texture size.
+ uv2_scale.x = p_margin_scale.x * uv2_padding / (lightmap_size.x == 0.0 ? PADDING_REF_SIZE : lightmap_size.x);
+ uv2_scale.y = p_margin_scale.y * uv2_padding / (lightmap_size.y == 0.0 ? PADDING_REF_SIZE : lightmap_size.y);
+
+ // Inverse it to turn our margin into a scale
+ uv2_scale = Vector2(1.0, 1.0) - uv2_scale;
+
+ return uv2_scale;
+}
+
+float PrimitiveMesh::get_lightmap_texel_size() const {
+ float texel_size = GLOBAL_GET("rendering/lightmapping/primitive_meshes/texel_size");
+
+ if (texel_size <= 0.0) {
+ texel_size = 0.2;
+ }
+
+ return texel_size;
+}
+
PrimitiveMesh::PrimitiveMesh() {
mesh = RenderingServer::get_singleton()->mesh_create();
}
@@ -275,22 +347,52 @@ PrimitiveMesh::~PrimitiveMesh() {
CapsuleMesh
*/
+void CapsuleMesh::_update_lightmap_size() {
+ if (get_add_uv2()) {
+ // size must have changed, update lightmap size hint
+ Size2i _lightmap_size_hint;
+ float texel_size = get_lightmap_texel_size();
+ float padding = get_uv2_padding();
+
+ float radial_length = radius * Math_PI * 0.5; // circumference of 90 degree bend
+ float vertical_length = radial_length * 2 + (height - 2.0 * radius); // total vertical length
+
+ _lightmap_size_hint.x = MAX(1.0, 4.0 * radial_length / texel_size) + padding;
+ _lightmap_size_hint.y = MAX(1.0, vertical_length / texel_size) + padding;
+
+ set_lightmap_size_hint(_lightmap_size_hint);
+ }
+}
+
void CapsuleMesh::_create_mesh_array(Array &p_arr) const {
- create_mesh_array(p_arr, radius, height, radial_segments, rings);
+ bool _add_uv2 = get_add_uv2();
+ float texel_size = get_lightmap_texel_size();
+ float _uv2_padding = get_uv2_padding() * texel_size;
+
+ create_mesh_array(p_arr, radius, height, radial_segments, rings, _add_uv2, _uv2_padding);
}
-void CapsuleMesh::create_mesh_array(Array &p_arr, const float radius, const float height, const int radial_segments, const int rings) {
+void CapsuleMesh::create_mesh_array(Array &p_arr, const float radius, const float height, const int radial_segments, const int rings, bool p_add_uv2, const float p_uv2_padding) {
int i, j, prevrow, thisrow, point;
float x, y, z, u, v, w;
float onethird = 1.0 / 3.0;
float twothirds = 2.0 / 3.0;
+ // Only used if we calculate UV2
+ float radial_width = 2.0 * radius * Math_PI;
+ float radial_h = radial_width / (radial_width + p_uv2_padding);
+ float radial_length = radius * Math_PI * 0.5; // circumference of 90 degree bend
+ float vertical_length = radial_length * 2 + (height - 2.0 * radius) + p_uv2_padding; // total vertical length
+ float radial_v = radial_length / vertical_length; // v size of top and bottom section
+ float height_v = (height - 2.0 * radius) / vertical_length; // v size of height section
+
// note, this has been aligned with our collision shape but I've left the descriptions as top/middle/bottom
Vector<Vector3> points;
Vector<Vector3> normals;
Vector<float> tangents;
Vector<Vector2> uvs;
+ Vector<Vector2> uv2s;
Vector<int> indices;
point = 0;
@@ -322,6 +424,9 @@ void CapsuleMesh::create_mesh_array(Array &p_arr, const float radius, const floa
normals.push_back(p.normalized());
ADD_TANGENT(-z, 0.0, -x, 1.0)
uvs.push_back(Vector2(u, v * onethird));
+ if (p_add_uv2) {
+ uv2s.push_back(Vector2(u * radial_h, v * radial_v));
+ }
point++;
if (i > 0 && j > 0) {
@@ -332,12 +437,12 @@ void CapsuleMesh::create_mesh_array(Array &p_arr, const float radius, const floa
indices.push_back(prevrow + i);
indices.push_back(thisrow + i);
indices.push_back(thisrow + i - 1);
- };
- };
+ }
+ }
prevrow = thisrow;
thisrow = point;
- };
+ }
/* cylinder */
thisrow = point;
@@ -361,6 +466,9 @@ void CapsuleMesh::create_mesh_array(Array &p_arr, const float radius, const floa
normals.push_back(Vector3(x, 0.0, -z));
ADD_TANGENT(-z, 0.0, -x, 1.0)
uvs.push_back(Vector2(u, onethird + (v * onethird)));
+ if (p_add_uv2) {
+ uv2s.push_back(Vector2(u * radial_h, radial_v + (v * height_v)));
+ }
point++;
if (i > 0 && j > 0) {
@@ -371,12 +479,12 @@ void CapsuleMesh::create_mesh_array(Array &p_arr, const float radius, const floa
indices.push_back(prevrow + i);
indices.push_back(thisrow + i);
indices.push_back(thisrow + i - 1);
- };
- };
+ }
+ }
prevrow = thisrow;
thisrow = point;
- };
+ }
/* bottom hemisphere */
thisrow = point;
@@ -390,17 +498,20 @@ void CapsuleMesh::create_mesh_array(Array &p_arr, const float radius, const floa
y = radius * cos(0.5 * Math_PI * v);
for (i = 0; i <= radial_segments; i++) {
- float u2 = i;
- u2 /= radial_segments;
+ u = i;
+ u /= radial_segments;
- x = -sin(u2 * Math_TAU);
- z = cos(u2 * Math_TAU);
+ x = -sin(u * Math_TAU);
+ z = cos(u * Math_TAU);
Vector3 p = Vector3(x * radius * w, y, -z * radius * w);
points.push_back(p + Vector3(0.0, -0.5 * height + radius, 0.0));
normals.push_back(p.normalized());
ADD_TANGENT(-z, 0.0, -x, 1.0)
- uvs.push_back(Vector2(u2, twothirds + ((v - 1.0) * onethird)));
+ uvs.push_back(Vector2(u, twothirds + ((v - 1.0) * onethird)));
+ if (p_add_uv2) {
+ uv2s.push_back(Vector2(u * radial_h, radial_v + height_v + ((v - 1.0) * radial_v)));
+ }
point++;
if (i > 0 && j > 0) {
@@ -411,17 +522,20 @@ void CapsuleMesh::create_mesh_array(Array &p_arr, const float radius, const floa
indices.push_back(prevrow + i);
indices.push_back(thisrow + i);
indices.push_back(thisrow + i - 1);
- };
- };
+ }
+ }
prevrow = thisrow;
thisrow = point;
- };
+ }
p_arr[RS::ARRAY_VERTEX] = points;
p_arr[RS::ARRAY_NORMAL] = normals;
p_arr[RS::ARRAY_TANGENT] = tangents;
p_arr[RS::ARRAY_TEX_UV] = uvs;
+ if (p_add_uv2) {
+ p_arr[RS::ARRAY_TEX_UV2] = uv2s;
+ }
p_arr[RS::ARRAY_INDEX] = indices;
}
@@ -450,6 +564,7 @@ void CapsuleMesh::set_radius(const float p_radius) {
if (radius > height * 0.5) {
height = radius * 2.0;
}
+ _update_lightmap_size();
_request_update();
}
@@ -462,6 +577,7 @@ void CapsuleMesh::set_height(const float p_height) {
if (radius > height * 0.5) {
radius = height * 0.5;
}
+ _update_lightmap_size();
_request_update();
}
@@ -493,16 +609,53 @@ CapsuleMesh::CapsuleMesh() {}
BoxMesh
*/
+void BoxMesh::_update_lightmap_size() {
+ if (get_add_uv2()) {
+ // size must have changed, update lightmap size hint
+ Size2i _lightmap_size_hint;
+ float texel_size = get_lightmap_texel_size();
+ float padding = get_uv2_padding();
+
+ float width = (size.x + size.z) / texel_size;
+ float length = (size.y + size.y + MAX(size.x, size.z)) / texel_size;
+
+ _lightmap_size_hint.x = MAX(1.0, width) + 2.0 * padding;
+ _lightmap_size_hint.y = MAX(1.0, length) + 3.0 * padding;
+
+ set_lightmap_size_hint(_lightmap_size_hint);
+ }
+}
+
void BoxMesh::_create_mesh_array(Array &p_arr) const {
- BoxMesh::create_mesh_array(p_arr, size, subdivide_w, subdivide_h, subdivide_d);
+ // Note about padding, with our box each face of the box faces a different direction so we want a seam
+ // around every face. We thus add our padding to the right and bottom of each face.
+ // With 3 faces along the width and 2 along the height of the texture we need to adjust our scale
+ // accordingly.
+ bool _add_uv2 = get_add_uv2();
+ float texel_size = get_lightmap_texel_size();
+ float _uv2_padding = get_uv2_padding() * texel_size;
+
+ BoxMesh::create_mesh_array(p_arr, size, subdivide_w, subdivide_h, subdivide_d, _add_uv2, _uv2_padding);
}
-void BoxMesh::create_mesh_array(Array &p_arr, Vector3 size, int subdivide_w, int subdivide_h, int subdivide_d) {
+void BoxMesh::create_mesh_array(Array &p_arr, Vector3 size, int subdivide_w, int subdivide_h, int subdivide_d, bool p_add_uv2, const float p_uv2_padding) {
int i, j, prevrow, thisrow, point;
float x, y, z;
float onethird = 1.0 / 3.0;
float twothirds = 2.0 / 3.0;
+ // Only used if we calculate UV2
+ // TODO this could be improved by changing the order depending on which side is the longest (basically the below works best if size.y is the longest)
+ float total_h = (size.x + size.z + (2.0 * p_uv2_padding));
+ float padding_h = p_uv2_padding / total_h;
+ float width_h = size.x / total_h;
+ float depth_h = size.z / total_h;
+ float total_v = (size.y + size.y + MAX(size.x, size.z) + (3.0 * p_uv2_padding));
+ float padding_v = p_uv2_padding / total_v;
+ float width_v = size.x / total_v;
+ float height_v = size.y / total_v;
+ float depth_v = size.z / total_v;
+
Vector3 start_pos = size * -0.5;
// set our bounding box
@@ -511,6 +664,7 @@ void BoxMesh::create_mesh_array(Array &p_arr, Vector3 size, int subdivide_w, int
Vector<Vector3> normals;
Vector<float> tangents;
Vector<Vector2> uvs;
+ Vector<Vector2> uv2s;
Vector<int> indices;
point = 0;
@@ -525,18 +679,24 @@ void BoxMesh::create_mesh_array(Array &p_arr, Vector3 size, int subdivide_w, int
thisrow = point;
prevrow = 0;
for (j = 0; j <= subdivide_h + 1; j++) {
+ float v = j;
+ float v2 = v / (subdivide_w + 1.0);
+ v /= (2.0 * (subdivide_h + 1.0));
+
x = start_pos.x;
for (i = 0; i <= subdivide_w + 1; i++) {
float u = i;
- float v = j;
+ float u2 = u / (subdivide_w + 1.0);
u /= (3.0 * (subdivide_w + 1.0));
- v /= (2.0 * (subdivide_h + 1.0));
// front
points.push_back(Vector3(x, -y, -start_pos.z)); // double negative on the Z!
normals.push_back(Vector3(0.0, 0.0, 1.0));
ADD_TANGENT(1.0, 0.0, 0.0, 1.0);
uvs.push_back(Vector2(u, v));
+ if (p_add_uv2) {
+ uv2s.push_back(Vector2(u2 * width_h, v2 * height_v));
+ }
point++;
// back
@@ -544,6 +704,9 @@ void BoxMesh::create_mesh_array(Array &p_arr, Vector3 size, int subdivide_w, int
normals.push_back(Vector3(0.0, 0.0, -1.0));
ADD_TANGENT(-1.0, 0.0, 0.0, 1.0);
uvs.push_back(Vector2(twothirds + u, v));
+ if (p_add_uv2) {
+ uv2s.push_back(Vector2(u2 * width_h, height_v + padding_v + (v2 * height_v)));
+ }
point++;
if (i > 0 && j > 0) {
@@ -564,33 +727,39 @@ void BoxMesh::create_mesh_array(Array &p_arr, Vector3 size, int subdivide_w, int
indices.push_back(prevrow + i2 + 1);
indices.push_back(thisrow + i2 + 1);
indices.push_back(thisrow + i2 - 1);
- };
+ }
x += size.x / (subdivide_w + 1.0);
- };
+ }
y += size.y / (subdivide_h + 1.0);
prevrow = thisrow;
thisrow = point;
- };
+ }
// left + right
y = start_pos.y;
thisrow = point;
prevrow = 0;
for (j = 0; j <= (subdivide_h + 1); j++) {
+ float v = j;
+ float v2 = v / (subdivide_h + 1.0);
+ v /= (2.0 * (subdivide_h + 1.0));
+
z = start_pos.z;
for (i = 0; i <= (subdivide_d + 1); i++) {
float u = i;
- float v = j;
+ float u2 = u / (subdivide_d + 1.0);
u /= (3.0 * (subdivide_d + 1.0));
- v /= (2.0 * (subdivide_h + 1.0));
// right
points.push_back(Vector3(-start_pos.x, -y, -z));
normals.push_back(Vector3(1.0, 0.0, 0.0));
ADD_TANGENT(0.0, 0.0, -1.0, 1.0);
uvs.push_back(Vector2(onethird + u, v));
+ if (p_add_uv2) {
+ uv2s.push_back(Vector2(width_h + padding_h + (u2 * depth_h), v2 * height_v));
+ }
point++;
// left
@@ -598,6 +767,9 @@ void BoxMesh::create_mesh_array(Array &p_arr, Vector3 size, int subdivide_w, int
normals.push_back(Vector3(-1.0, 0.0, 0.0));
ADD_TANGENT(0.0, 0.0, 1.0, 1.0);
uvs.push_back(Vector2(u, 0.5 + v));
+ if (p_add_uv2) {
+ uv2s.push_back(Vector2(width_h + padding_h + (u2 * depth_h), height_v + padding_v + (v2 * height_v)));
+ }
point++;
if (i > 0 && j > 0) {
@@ -618,33 +790,39 @@ void BoxMesh::create_mesh_array(Array &p_arr, Vector3 size, int subdivide_w, int
indices.push_back(prevrow + i2 + 1);
indices.push_back(thisrow + i2 + 1);
indices.push_back(thisrow + i2 - 1);
- };
+ }
z += size.z / (subdivide_d + 1.0);
- };
+ }
y += size.y / (subdivide_h + 1.0);
prevrow = thisrow;
thisrow = point;
- };
+ }
// top + bottom
z = start_pos.z;
thisrow = point;
prevrow = 0;
for (j = 0; j <= (subdivide_d + 1); j++) {
+ float v = j;
+ float v2 = v / (subdivide_d + 1.0);
+ v /= (2.0 * (subdivide_d + 1.0));
+
x = start_pos.x;
for (i = 0; i <= (subdivide_w + 1); i++) {
float u = i;
- float v = j;
+ float u2 = u / (subdivide_w + 1.0);
u /= (3.0 * (subdivide_w + 1.0));
- v /= (2.0 * (subdivide_d + 1.0));
// top
points.push_back(Vector3(-x, -start_pos.y, -z));
normals.push_back(Vector3(0.0, 1.0, 0.0));
ADD_TANGENT(-1.0, 0.0, 0.0, 1.0);
uvs.push_back(Vector2(onethird + u, 0.5 + v));
+ if (p_add_uv2) {
+ uv2s.push_back(Vector2(u2 * width_h, ((height_v + padding_v) * 2.0) + (v2 * depth_v)));
+ }
point++;
// bottom
@@ -652,6 +830,9 @@ void BoxMesh::create_mesh_array(Array &p_arr, Vector3 size, int subdivide_w, int
normals.push_back(Vector3(0.0, -1.0, 0.0));
ADD_TANGENT(1.0, 0.0, 0.0, 1.0);
uvs.push_back(Vector2(twothirds + u, 0.5 + v));
+ if (p_add_uv2) {
+ uv2s.push_back(Vector2(width_h + padding_h + (u2 * depth_h), ((height_v + padding_v) * 2.0) + (v2 * width_v)));
+ }
point++;
if (i > 0 && j > 0) {
@@ -672,20 +853,23 @@ void BoxMesh::create_mesh_array(Array &p_arr, Vector3 size, int subdivide_w, int
indices.push_back(prevrow + i2 + 1);
indices.push_back(thisrow + i2 + 1);
indices.push_back(thisrow + i2 - 1);
- };
+ }
x += size.x / (subdivide_w + 1.0);
- };
+ }
z += size.z / (subdivide_d + 1.0);
prevrow = thisrow;
thisrow = point;
- };
+ }
p_arr[RS::ARRAY_VERTEX] = points;
p_arr[RS::ARRAY_NORMAL] = normals;
p_arr[RS::ARRAY_TANGENT] = tangents;
p_arr[RS::ARRAY_TEX_UV] = uvs;
+ if (p_add_uv2) {
+ p_arr[RS::ARRAY_TEX_UV2] = uv2s;
+ }
p_arr[RS::ARRAY_INDEX] = indices;
}
@@ -708,6 +892,7 @@ void BoxMesh::_bind_methods() {
void BoxMesh::set_size(const Vector3 &p_size) {
size = p_size;
+ _update_lightmap_size();
_request_update();
}
@@ -748,18 +933,58 @@ BoxMesh::BoxMesh() {}
CylinderMesh
*/
+void CylinderMesh::_update_lightmap_size() {
+ if (get_add_uv2()) {
+ // size must have changed, update lightmap size hint
+ Size2i _lightmap_size_hint;
+ float texel_size = get_lightmap_texel_size();
+ float padding = get_uv2_padding();
+
+ float top_circumference = top_radius * Math_PI * 2.0;
+ float bottom_circumference = bottom_radius * Math_PI * 2.0;
+
+ float _width = MAX(top_circumference, bottom_circumference) / texel_size + padding;
+ _width = MAX(_width, (((top_radius + bottom_radius) / texel_size) + padding) * 2.0); // this is extremely unlikely to be larger, will only happen if padding is larger then our diameter.
+ _lightmap_size_hint.x = MAX(1.0, _width);
+
+ float _height = ((height + (MAX(top_radius, bottom_radius) * 2.0)) / texel_size) + (2.0 * padding);
+
+ _lightmap_size_hint.y = MAX(1.0, _height);
+
+ set_lightmap_size_hint(_lightmap_size_hint);
+ }
+}
+
void CylinderMesh::_create_mesh_array(Array &p_arr) const {
- create_mesh_array(p_arr, top_radius, bottom_radius, height, radial_segments, rings, cap_top, cap_bottom);
+ bool _add_uv2 = get_add_uv2();
+ float texel_size = get_lightmap_texel_size();
+ float _uv2_padding = get_uv2_padding() * texel_size;
+
+ create_mesh_array(p_arr, top_radius, bottom_radius, height, radial_segments, rings, cap_top, cap_bottom, _add_uv2, _uv2_padding);
}
-void CylinderMesh::create_mesh_array(Array &p_arr, float top_radius, float bottom_radius, float height, int radial_segments, int rings, bool cap_top, bool cap_bottom) {
+void CylinderMesh::create_mesh_array(Array &p_arr, float top_radius, float bottom_radius, float height, int radial_segments, int rings, bool cap_top, bool cap_bottom, bool p_add_uv2, const float p_uv2_padding) {
int i, j, prevrow, thisrow, point;
- float x, y, z, u, v, radius;
+ float x, y, z, u, v, radius, radius_h;
+
+ // Only used if we calculate UV2
+ float top_circumference = top_radius * Math_PI * 2.0;
+ float bottom_circumference = bottom_radius * Math_PI * 2.0;
+ float vertical_length = height + MAX(2.0 * top_radius, 2.0 * bottom_radius) + (2.0 * p_uv2_padding);
+ float height_v = height / vertical_length;
+ float padding_v = p_uv2_padding / vertical_length;
+
+ float horizonal_length = MAX(MAX(2.0 * (top_radius + bottom_radius + p_uv2_padding), top_circumference + p_uv2_padding), bottom_circumference + p_uv2_padding);
+ float center_h = 0.5 * (horizonal_length - p_uv2_padding) / horizonal_length;
+ float top_h = top_circumference / horizonal_length;
+ float bottom_h = bottom_circumference / horizonal_length;
+ float padding_h = p_uv2_padding / horizonal_length;
Vector<Vector3> points;
Vector<Vector3> normals;
Vector<float> tangents;
Vector<Vector2> uvs;
+ Vector<Vector2> uv2s;
Vector<int> indices;
point = 0;
@@ -777,6 +1002,7 @@ void CylinderMesh::create_mesh_array(Array &p_arr, float top_radius, float botto
v /= (rings + 1);
radius = top_radius + ((bottom_radius - top_radius) * v);
+ radius_h = top_h + ((bottom_h - top_h) * v);
y = height * v;
y = (height * 0.5) - y;
@@ -793,6 +1019,9 @@ void CylinderMesh::create_mesh_array(Array &p_arr, float top_radius, float botto
normals.push_back(Vector3(x, side_normal_y, z).normalized());
ADD_TANGENT(z, 0.0, -x, 1.0)
uvs.push_back(Vector2(u, v * 0.5));
+ if (p_add_uv2) {
+ uv2s.push_back(Vector2(center_h + (u - 0.5) * radius_h, v * height_v));
+ }
point++;
if (i > 0 && j > 0) {
@@ -803,14 +1032,20 @@ void CylinderMesh::create_mesh_array(Array &p_arr, float top_radius, float botto
indices.push_back(prevrow + i);
indices.push_back(thisrow + i);
indices.push_back(thisrow + i - 1);
- };
- };
+ }
+ }
prevrow = thisrow;
thisrow = point;
- };
+ }
+
+ // Adjust for bottom section, only used if we calculate UV2s.
+ top_h = top_radius / horizonal_length;
+ float top_v = top_radius / vertical_length;
+ bottom_h = bottom_radius / horizonal_length;
+ float bottom_v = bottom_radius / vertical_length;
- // add top
+ // Add top.
if (cap_top && top_radius > 0.0) {
y = height * 0.5;
@@ -819,6 +1054,9 @@ void CylinderMesh::create_mesh_array(Array &p_arr, float top_radius, float botto
normals.push_back(Vector3(0.0, 1.0, 0.0));
ADD_TANGENT(1.0, 0.0, 0.0, 1.0)
uvs.push_back(Vector2(0.25, 0.75));
+ if (p_add_uv2) {
+ uv2s.push_back(Vector2(top_h, height_v + padding_v + MAX(top_v, bottom_v)));
+ }
point++;
for (i = 0; i <= radial_segments; i++) {
@@ -836,17 +1074,20 @@ void CylinderMesh::create_mesh_array(Array &p_arr, float top_radius, float botto
normals.push_back(Vector3(0.0, 1.0, 0.0));
ADD_TANGENT(1.0, 0.0, 0.0, 1.0)
uvs.push_back(Vector2(u, v));
+ if (p_add_uv2) {
+ uv2s.push_back(Vector2(top_h + (x * top_h), height_v + padding_v + MAX(top_v, bottom_v) + (z * top_v)));
+ }
point++;
if (i > 0) {
indices.push_back(thisrow);
indices.push_back(point - 1);
indices.push_back(point - 2);
- };
- };
- };
+ }
+ }
+ }
- // add bottom
+ // Add bottom.
if (cap_bottom && bottom_radius > 0.0) {
y = height * -0.5;
@@ -855,6 +1096,9 @@ void CylinderMesh::create_mesh_array(Array &p_arr, float top_radius, float botto
normals.push_back(Vector3(0.0, -1.0, 0.0));
ADD_TANGENT(1.0, 0.0, 0.0, 1.0)
uvs.push_back(Vector2(0.75, 0.75));
+ if (p_add_uv2) {
+ uv2s.push_back(Vector2(top_h + top_h + padding_h + bottom_h, height_v + padding_v + MAX(top_v, bottom_v)));
+ }
point++;
for (i = 0; i <= radial_segments; i++) {
@@ -872,20 +1116,26 @@ void CylinderMesh::create_mesh_array(Array &p_arr, float top_radius, float botto
normals.push_back(Vector3(0.0, -1.0, 0.0));
ADD_TANGENT(1.0, 0.0, 0.0, 1.0)
uvs.push_back(Vector2(u, v));
+ if (p_add_uv2) {
+ uv2s.push_back(Vector2(top_h + top_h + padding_h + bottom_h + (x * bottom_h), height_v + padding_v + MAX(top_v, bottom_v) - (z * bottom_v)));
+ }
point++;
if (i > 0) {
indices.push_back(thisrow);
indices.push_back(point - 2);
indices.push_back(point - 1);
- };
- };
- };
+ }
+ }
+ }
p_arr[RS::ARRAY_VERTEX] = points;
p_arr[RS::ARRAY_NORMAL] = normals;
p_arr[RS::ARRAY_TANGENT] = tangents;
p_arr[RS::ARRAY_TEX_UV] = uvs;
+ if (p_add_uv2) {
+ p_arr[RS::ARRAY_TEX_UV2] = uv2s;
+ }
p_arr[RS::ARRAY_INDEX] = indices;
}
@@ -919,6 +1169,7 @@ void CylinderMesh::_bind_methods() {
void CylinderMesh::set_top_radius(const float p_radius) {
top_radius = p_radius;
+ _update_lightmap_size();
_request_update();
}
@@ -928,6 +1179,7 @@ float CylinderMesh::get_top_radius() const {
void CylinderMesh::set_bottom_radius(const float p_radius) {
bottom_radius = p_radius;
+ _update_lightmap_size();
_request_update();
}
@@ -937,6 +1189,7 @@ float CylinderMesh::get_bottom_radius() const {
void CylinderMesh::set_height(const float p_height) {
height = p_height;
+ _update_lightmap_size();
_request_update();
}
@@ -986,10 +1239,26 @@ CylinderMesh::CylinderMesh() {}
PlaneMesh
*/
+void PlaneMesh::_update_lightmap_size() {
+ if (get_add_uv2()) {
+ // size must have changed, update lightmap size hint
+ Size2i _lightmap_size_hint;
+ float texel_size = get_lightmap_texel_size();
+ float padding = get_uv2_padding();
+
+ _lightmap_size_hint.x = MAX(1.0, (size.x / texel_size) + padding);
+ _lightmap_size_hint.y = MAX(1.0, (size.y / texel_size) + padding);
+
+ set_lightmap_size_hint(_lightmap_size_hint);
+ }
+}
+
void PlaneMesh::_create_mesh_array(Array &p_arr) const {
int i, j, prevrow, thisrow, point;
float x, z;
+ // Plane mesh can use default UV2 calculation as implemented in Primitive Mesh
+
Size2 start_pos = size * -0.5;
Vector3 normal = Vector3(0.0, 1.0, 0.0);
@@ -1043,15 +1312,15 @@ void PlaneMesh::_create_mesh_array(Array &p_arr) const {
indices.push_back(prevrow + i);
indices.push_back(thisrow + i);
indices.push_back(thisrow + i - 1);
- };
+ }
x += size.x / (subdivide_w + 1.0);
- };
+ }
z += size.y / (subdivide_d + 1.0);
prevrow = thisrow;
thisrow = point;
- };
+ }
p_arr[RS::ARRAY_VERTEX] = points;
p_arr[RS::ARRAY_NORMAL] = normals;
@@ -1088,6 +1357,7 @@ void PlaneMesh::_bind_methods() {
void PlaneMesh::set_size(const Size2 &p_size) {
size = p_size;
+ _update_lightmap_size();
_request_update();
}
@@ -1137,12 +1407,49 @@ PlaneMesh::PlaneMesh() {}
PrismMesh
*/
+void PrismMesh::_update_lightmap_size() {
+ if (get_add_uv2()) {
+ // size must have changed, update lightmap size hint
+ Size2i _lightmap_size_hint;
+ float texel_size = get_lightmap_texel_size();
+ float padding = get_uv2_padding();
+
+ // left_to_right does not effect the surface area of the prism so we ignore that.
+ // TODO we could combine the two triangles and save some space but we need to re-align the uv1 and adjust the tangent.
+
+ float width = (size.x + size.z) / texel_size;
+ float length = (size.y + size.y + size.z) / texel_size;
+
+ _lightmap_size_hint.x = MAX(1.0, width) + 2.0 * padding;
+ _lightmap_size_hint.y = MAX(1.0, length) + 3.0 * padding;
+
+ set_lightmap_size_hint(_lightmap_size_hint);
+ }
+}
+
void PrismMesh::_create_mesh_array(Array &p_arr) const {
int i, j, prevrow, thisrow, point;
float x, y, z;
float onethird = 1.0 / 3.0;
float twothirds = 2.0 / 3.0;
+ // Only used if we calculate UV2
+ bool _add_uv2 = get_add_uv2();
+ float texel_size = get_lightmap_texel_size();
+ float _uv2_padding = get_uv2_padding() * texel_size;
+
+ float horizontal_total = size.x + size.z + 2.0 * _uv2_padding;
+ float width_h = size.x / horizontal_total;
+ float depth_h = size.z / horizontal_total;
+ float padding_h = _uv2_padding / horizontal_total;
+
+ float vertical_total = (size.y + size.y + size.z) + (3.0 * _uv2_padding);
+ float height_v = size.y / vertical_total;
+ float depth_v = size.z / vertical_total;
+ float padding_v = _uv2_padding / vertical_total;
+
+ // and start building
+
Vector3 start_pos = size * -0.5;
// set our bounding box
@@ -1151,6 +1458,7 @@ void PrismMesh::_create_mesh_array(Array &p_arr) const {
Vector<Vector3> normals;
Vector<float> tangents;
Vector<Vector2> uvs;
+ Vector<Vector2> uv2s;
Vector<int> indices;
point = 0;
@@ -1171,12 +1479,15 @@ void PrismMesh::_create_mesh_array(Array &p_arr) const {
float offset_front = (1.0 - scale) * onethird * left_to_right;
float offset_back = (1.0 - scale) * onethird * (1.0 - left_to_right);
+ float v = j;
+ float v2 = j / (subdivide_h + 1.0);
+ v /= (2.0 * (subdivide_h + 1.0));
+
x = 0.0;
for (i = 0; i <= (subdivide_w + 1); i++) {
float u = i;
- float v = j;
+ float u2 = i / (subdivide_w + 1.0);
u /= (3.0 * (subdivide_w + 1.0));
- v /= (2.0 * (subdivide_h + 1.0));
u *= scale;
@@ -1185,6 +1496,9 @@ void PrismMesh::_create_mesh_array(Array &p_arr) const {
normals.push_back(Vector3(0.0, 0.0, 1.0));
ADD_TANGENT(1.0, 0.0, 0.0, 1.0);
uvs.push_back(Vector2(offset_front + u, v));
+ if (_add_uv2) {
+ uv2s.push_back(Vector2(u2 * scale * width_h, v2 * height_v));
+ }
point++;
/* back */
@@ -1192,6 +1506,9 @@ void PrismMesh::_create_mesh_array(Array &p_arr) const {
normals.push_back(Vector3(0.0, 0.0, -1.0));
ADD_TANGENT(-1.0, 0.0, 0.0, 1.0);
uvs.push_back(Vector2(twothirds + offset_back + u, v));
+ if (_add_uv2) {
+ uv2s.push_back(Vector2(u2 * scale * width_h, height_v + padding_v + v2 * height_v));
+ }
point++;
if (i > 0 && j == 1) {
@@ -1224,15 +1541,15 @@ void PrismMesh::_create_mesh_array(Array &p_arr) const {
indices.push_back(prevrow + i2 + 1);
indices.push_back(thisrow + i2 + 1);
indices.push_back(thisrow + i2 - 1);
- };
+ }
x += scale * size.x / (subdivide_w + 1.0);
- };
+ }
y += size.y / (subdivide_h + 1.0);
prevrow = thisrow;
thisrow = point;
- };
+ }
/* left + right */
Vector3 normal_left, normal_right;
@@ -1246,6 +1563,10 @@ void PrismMesh::_create_mesh_array(Array &p_arr) const {
thisrow = point;
prevrow = 0;
for (j = 0; j <= (subdivide_h + 1); j++) {
+ float v = j;
+ float v2 = j / (subdivide_h + 1.0);
+ v /= (2.0 * (subdivide_h + 1.0));
+
float left, right;
float scale = (y - start_pos.y) / size.y;
@@ -1255,15 +1576,17 @@ void PrismMesh::_create_mesh_array(Array &p_arr) const {
z = start_pos.z;
for (i = 0; i <= (subdivide_d + 1); i++) {
float u = i;
- float v = j;
+ float u2 = u / (subdivide_d + 1.0);
u /= (3.0 * (subdivide_d + 1.0));
- v /= (2.0 * (subdivide_h + 1.0));
/* right */
points.push_back(Vector3(right, -y, -z));
normals.push_back(normal_right);
ADD_TANGENT(0.0, 0.0, -1.0, 1.0);
uvs.push_back(Vector2(onethird + u, v));
+ if (_add_uv2) {
+ uv2s.push_back(Vector2(width_h + padding_h + u2 * depth_h, v2 * height_v));
+ }
point++;
/* left */
@@ -1271,6 +1594,9 @@ void PrismMesh::_create_mesh_array(Array &p_arr) const {
normals.push_back(normal_left);
ADD_TANGENT(0.0, 0.0, 1.0, 1.0);
uvs.push_back(Vector2(u, 0.5 + v));
+ if (_add_uv2) {
+ uv2s.push_back(Vector2(width_h + padding_h + u2 * depth_h, height_v + padding_v + v2 * height_v));
+ }
point++;
if (i > 0 && j > 0) {
@@ -1291,33 +1617,39 @@ void PrismMesh::_create_mesh_array(Array &p_arr) const {
indices.push_back(prevrow + i2 + 1);
indices.push_back(thisrow + i2 + 1);
indices.push_back(thisrow + i2 - 1);
- };
+ }
z += size.z / (subdivide_d + 1.0);
- };
+ }
y += size.y / (subdivide_h + 1.0);
prevrow = thisrow;
thisrow = point;
- };
+ }
/* bottom */
z = start_pos.z;
thisrow = point;
prevrow = 0;
for (j = 0; j <= (subdivide_d + 1); j++) {
+ float v = j;
+ float v2 = v / (subdivide_d + 1.0);
+ v /= (2.0 * (subdivide_d + 1.0));
+
x = start_pos.x;
for (i = 0; i <= (subdivide_w + 1); i++) {
float u = i;
- float v = j;
+ float u2 = u / (subdivide_w + 1.0);
u /= (3.0 * (subdivide_w + 1.0));
- v /= (2.0 * (subdivide_d + 1.0));
/* bottom */
points.push_back(Vector3(x, start_pos.y, -z));
normals.push_back(Vector3(0.0, -1.0, 0.0));
ADD_TANGENT(1.0, 0.0, 0.0, 1.0);
uvs.push_back(Vector2(twothirds + u, 0.5 + v));
+ if (_add_uv2) {
+ uv2s.push_back(Vector2(u2 * width_h, 2.0 * (height_v + padding_v) + v2 * depth_v));
+ }
point++;
if (i > 0 && j > 0) {
@@ -1328,20 +1660,23 @@ void PrismMesh::_create_mesh_array(Array &p_arr) const {
indices.push_back(prevrow + i);
indices.push_back(thisrow + i);
indices.push_back(thisrow + i - 1);
- };
+ }
x += size.x / (subdivide_w + 1.0);
- };
+ }
z += size.z / (subdivide_d + 1.0);
prevrow = thisrow;
thisrow = point;
- };
+ }
p_arr[RS::ARRAY_VERTEX] = points;
p_arr[RS::ARRAY_NORMAL] = normals;
p_arr[RS::ARRAY_TANGENT] = tangents;
p_arr[RS::ARRAY_TEX_UV] = uvs;
+ if (_add_uv2) {
+ p_arr[RS::ARRAY_TEX_UV2] = uv2s;
+ }
p_arr[RS::ARRAY_INDEX] = indices;
}
@@ -1377,6 +1712,7 @@ float PrismMesh::get_left_to_right() const {
void PrismMesh::set_size(const Vector3 &p_size) {
size = p_size;
+ _update_lightmap_size();
_request_update();
}
@@ -1417,22 +1753,50 @@ PrismMesh::PrismMesh() {}
SphereMesh
*/
+void SphereMesh::_update_lightmap_size() {
+ if (get_add_uv2()) {
+ // size must have changed, update lightmap size hint
+ Size2i _lightmap_size_hint;
+ float texel_size = get_lightmap_texel_size();
+ float padding = get_uv2_padding();
+
+ float _width = radius * Math_TAU;
+ _lightmap_size_hint.x = MAX(1.0, (_width / texel_size) + padding);
+ float _height = (is_hemisphere ? 1.0 : 0.5) * height * Math_PI; // note, with hemisphere height is our radius, while with a full sphere it is the diameter..
+ _lightmap_size_hint.y = MAX(1.0, (_height / texel_size) + padding);
+
+ set_lightmap_size_hint(_lightmap_size_hint);
+ }
+}
+
void SphereMesh::_create_mesh_array(Array &p_arr) const {
- create_mesh_array(p_arr, radius, height, radial_segments, rings, is_hemisphere);
+ bool _add_uv2 = get_add_uv2();
+ float texel_size = get_lightmap_texel_size();
+ float _uv2_padding = get_uv2_padding() * texel_size;
+
+ create_mesh_array(p_arr, radius, height, radial_segments, rings, is_hemisphere, _add_uv2, _uv2_padding);
}
-void SphereMesh::create_mesh_array(Array &p_arr, float radius, float height, int radial_segments, int rings, bool is_hemisphere) {
+void SphereMesh::create_mesh_array(Array &p_arr, float radius, float height, int radial_segments, int rings, bool is_hemisphere, bool p_add_uv2, const float p_uv2_padding) {
int i, j, prevrow, thisrow, point;
float x, y, z;
float scale = height * (is_hemisphere ? 1.0 : 0.5);
+ // Only used if we calculate UV2
+ float circumference = radius * Math_TAU;
+ float horizontal_length = circumference + p_uv2_padding;
+ float center_h = 0.5 * circumference / horizontal_length;
+
+ float height_v = scale * Math_PI / ((scale * Math_PI) + p_uv2_padding);
+
// set our bounding box
Vector<Vector3> points;
Vector<Vector3> normals;
Vector<float> tangents;
Vector<Vector2> uvs;
+ Vector<Vector2> uv2s;
Vector<int> indices;
point = 0;
@@ -1467,9 +1831,13 @@ void SphereMesh::create_mesh_array(Array &p_arr, float radius, float height, int
points.push_back(p);
Vector3 normal = Vector3(x * w * scale, radius * (y / scale), z * w * scale);
normals.push_back(normal.normalized());
- };
+ }
ADD_TANGENT(z, 0.0, -x, 1.0)
uvs.push_back(Vector2(u, v));
+ if (p_add_uv2) {
+ float w_h = w * 2.0 * center_h;
+ uv2s.push_back(Vector2(center_h + ((u - 0.5) * w_h), v * height_v));
+ }
point++;
if (i > 0 && j > 0) {
@@ -1480,17 +1848,20 @@ void SphereMesh::create_mesh_array(Array &p_arr, float radius, float height, int
indices.push_back(prevrow + i);
indices.push_back(thisrow + i);
indices.push_back(thisrow + i - 1);
- };
- };
+ }
+ }
prevrow = thisrow;
thisrow = point;
- };
+ }
p_arr[RS::ARRAY_VERTEX] = points;
p_arr[RS::ARRAY_NORMAL] = normals;
p_arr[RS::ARRAY_TANGENT] = tangents;
p_arr[RS::ARRAY_TEX_UV] = uvs;
+ if (p_add_uv2) {
+ p_arr[RS::ARRAY_TEX_UV2] = uv2s;
+ }
p_arr[RS::ARRAY_INDEX] = indices;
}
@@ -1517,6 +1888,7 @@ void SphereMesh::_bind_methods() {
void SphereMesh::set_radius(const float p_radius) {
radius = p_radius;
+ _update_lightmap_size();
_request_update();
}
@@ -1526,6 +1898,7 @@ float SphereMesh::get_radius() const {
void SphereMesh::set_height(const float p_height) {
height = p_height;
+ _update_lightmap_size();
_request_update();
}
@@ -1553,6 +1926,7 @@ int SphereMesh::get_rings() const {
void SphereMesh::set_is_hemisphere(const bool p_is_hemisphere) {
is_hemisphere = p_is_hemisphere;
+ _update_lightmap_size();
_request_update();
}
@@ -1566,6 +1940,31 @@ SphereMesh::SphereMesh() {}
TorusMesh
*/
+void TorusMesh::_update_lightmap_size() {
+ if (get_add_uv2()) {
+ // size must have changed, update lightmap size hint
+ Size2i _lightmap_size_hint;
+ float texel_size = get_lightmap_texel_size();
+ float padding = get_uv2_padding();
+
+ float min_radius = inner_radius;
+ float max_radius = outer_radius;
+
+ if (min_radius > max_radius) {
+ SWAP(min_radius, max_radius);
+ }
+
+ float radius = (max_radius - min_radius) * 0.5;
+
+ float _width = max_radius * Math_TAU;
+ _lightmap_size_hint.x = MAX(1.0, (_width / texel_size) + padding);
+ float _height = radius * Math_TAU;
+ _lightmap_size_hint.y = MAX(1.0, (_height / texel_size) + padding);
+
+ set_lightmap_size_hint(_lightmap_size_hint);
+ }
+}
+
void TorusMesh::_create_mesh_array(Array &p_arr) const {
// set our bounding box
@@ -1573,6 +1972,7 @@ void TorusMesh::_create_mesh_array(Array &p_arr) const {
Vector<Vector3> normals;
Vector<float> tangents;
Vector<Vector2> uvs;
+ Vector<Vector2> uv2s;
Vector<int> indices;
#define ADD_TANGENT(m_x, m_y, m_z, m_d) \
@@ -1592,6 +1992,17 @@ void TorusMesh::_create_mesh_array(Array &p_arr) const {
float radius = (max_radius - min_radius) * 0.5;
+ // Only used if we calculate UV2
+ bool _add_uv2 = get_add_uv2();
+ float texel_size = get_lightmap_texel_size();
+ float _uv2_padding = get_uv2_padding() * texel_size;
+
+ float horizontal_total = max_radius * Math_TAU + _uv2_padding;
+ float max_h = max_radius * Math_TAU / horizontal_total;
+ float delta_h = (max_radius - min_radius) * Math_TAU / horizontal_total;
+
+ float height_v = radius * Math_TAU / (radius * Math_TAU + _uv2_padding);
+
for (int i = 0; i <= rings; i++) {
int prevrow = (i - 1) * (ring_segments + 1);
int thisrow = i * (ring_segments + 1);
@@ -1607,10 +2018,17 @@ void TorusMesh::_create_mesh_array(Array &p_arr) const {
Vector2 normalj = Vector2(-Math::cos(angj), Math::sin(angj));
Vector2 normalk = normalj * radius + Vector2(min_radius + radius, 0);
+ float offset_h = 0.5 * (1.0 - normalj.x) * delta_h;
+ float adj_h = max_h - offset_h;
+ offset_h *= 0.5;
+
points.push_back(Vector3(normali.x * normalk.x, normalk.y, normali.y * normalk.x));
normals.push_back(Vector3(normali.x * normalj.x, normalj.y, normali.y * normalj.x));
ADD_TANGENT(-Math::cos(angi), 0.0, Math::sin(angi), 1.0);
uvs.push_back(Vector2(inci, incj));
+ if (_add_uv2) {
+ uv2s.push_back(Vector2(offset_h + inci * adj_h, incj * height_v));
+ }
if (i > 0 && j > 0) {
indices.push_back(thisrow + j - 1);
@@ -1628,6 +2046,9 @@ void TorusMesh::_create_mesh_array(Array &p_arr) const {
p_arr[RS::ARRAY_NORMAL] = normals;
p_arr[RS::ARRAY_TANGENT] = tangents;
p_arr[RS::ARRAY_TEX_UV] = uvs;
+ if (_add_uv2) {
+ p_arr[RS::ARRAY_TEX_UV2] = uv2s;
+ }
p_arr[RS::ARRAY_INDEX] = indices;
}
@@ -1750,6 +2171,24 @@ int TubeTrailMesh::get_section_rings() const {
return section_rings;
}
+void TubeTrailMesh::set_cap_top(bool p_cap_top) {
+ cap_top = p_cap_top;
+ _request_update();
+}
+
+bool TubeTrailMesh::is_cap_top() const {
+ return cap_top;
+}
+
+void TubeTrailMesh::set_cap_bottom(bool p_cap_bottom) {
+ cap_bottom = p_cap_bottom;
+ _request_update();
+}
+
+bool TubeTrailMesh::is_cap_bottom() const {
+ return cap_bottom;
+}
+
void TubeTrailMesh::set_curve(const Ref<Curve> &p_curve) {
if (curve == p_curve) {
return;
@@ -1785,6 +2224,8 @@ Transform3D TubeTrailMesh::get_builtin_bind_pose(int p_index) const {
}
void TubeTrailMesh::_create_mesh_array(Array &p_arr) const {
+ // Seeing use case for TubeTrailMesh, no need to do anything more then default UV2 calculation
+
PackedVector3Array points;
PackedVector3Array normals;
PackedFloat32Array tangents;
@@ -1861,49 +2302,21 @@ void TubeTrailMesh::_create_mesh_array(Array &p_arr) const {
thisrow = point;
}
- // add top
- float scale_pos = 1.0;
- if (curve.is_valid() && curve->get_point_count() > 0) {
- scale_pos = curve->sample_baked(0);
- }
-
- if (scale_pos > CMP_EPSILON) {
- float y = depth * 0.5;
-
- thisrow = point;
- points.push_back(Vector3(0.0, y, 0));
- normals.push_back(Vector3(0.0, 1.0, 0.0));
- ADD_TANGENT(1.0, 0.0, 0.0, 1.0)
- uvs.push_back(Vector2(0.25, 0.75));
- point++;
-
- bone_indices.push_back(0);
- bone_indices.push_back(0);
- bone_indices.push_back(0);
- bone_indices.push_back(0);
-
- bone_weights.push_back(1.0);
- bone_weights.push_back(0);
- bone_weights.push_back(0);
- bone_weights.push_back(0);
-
- float rm = radius * scale_pos;
-
- for (int i = 0; i <= radial_steps; i++) {
- float r = i;
- r /= radial_steps;
-
- float x = sin(r * Math_TAU);
- float z = cos(r * Math_TAU);
+ if (cap_top) {
+ // add top
+ float scale_pos = 1.0;
+ if (curve.is_valid() && curve->get_point_count() > 0) {
+ scale_pos = curve->sample_baked(0);
+ }
- float u = ((x + 1.0) * 0.25);
- float v = 0.5 + ((z + 1.0) * 0.25);
+ if (scale_pos > CMP_EPSILON) {
+ float y = depth * 0.5;
- Vector3 p = Vector3(x * rm, y, z * rm);
- points.push_back(p);
+ thisrow = point;
+ points.push_back(Vector3(0.0, y, 0));
normals.push_back(Vector3(0.0, 1.0, 0.0));
ADD_TANGENT(1.0, 0.0, 0.0, 1.0)
- uvs.push_back(Vector2(u, v));
+ uvs.push_back(Vector2(0.25, 0.75));
point++;
bone_indices.push_back(0);
@@ -1916,57 +2329,59 @@ void TubeTrailMesh::_create_mesh_array(Array &p_arr) const {
bone_weights.push_back(0);
bone_weights.push_back(0);
- if (i > 0) {
- indices.push_back(thisrow);
- indices.push_back(point - 1);
- indices.push_back(point - 2);
- };
- };
- };
+ float rm = radius * scale_pos;
- float scale_neg = 1.0;
- if (curve.is_valid() && curve->get_point_count() > 0) {
- scale_neg = curve->sample_baked(1.0);
- }
+ for (int i = 0; i <= radial_steps; i++) {
+ float r = i;
+ r /= radial_steps;
- // add bottom
- if (scale_neg > CMP_EPSILON) {
- float y = depth * -0.5;
+ float x = sin(r * Math_TAU);
+ float z = cos(r * Math_TAU);
- thisrow = point;
- points.push_back(Vector3(0.0, y, 0.0));
- normals.push_back(Vector3(0.0, -1.0, 0.0));
- ADD_TANGENT(1.0, 0.0, 0.0, 1.0)
- uvs.push_back(Vector2(0.75, 0.75));
- point++;
+ float u = ((x + 1.0) * 0.25);
+ float v = 0.5 + ((z + 1.0) * 0.25);
- bone_indices.push_back(sections);
- bone_indices.push_back(0);
- bone_indices.push_back(0);
- bone_indices.push_back(0);
+ Vector3 p = Vector3(x * rm, y, z * rm);
+ points.push_back(p);
+ normals.push_back(Vector3(0.0, 1.0, 0.0));
+ ADD_TANGENT(1.0, 0.0, 0.0, 1.0)
+ uvs.push_back(Vector2(u, v));
+ point++;
- bone_weights.push_back(1.0);
- bone_weights.push_back(0);
- bone_weights.push_back(0);
- bone_weights.push_back(0);
+ bone_indices.push_back(0);
+ bone_indices.push_back(0);
+ bone_indices.push_back(0);
+ bone_indices.push_back(0);
- float rm = radius * scale_neg;
+ bone_weights.push_back(1.0);
+ bone_weights.push_back(0);
+ bone_weights.push_back(0);
+ bone_weights.push_back(0);
- for (int i = 0; i <= radial_steps; i++) {
- float r = i;
- r /= radial_steps;
+ if (i > 0) {
+ indices.push_back(thisrow);
+ indices.push_back(point - 1);
+ indices.push_back(point - 2);
+ }
+ }
+ }
+ }
- float x = sin(r * Math_TAU);
- float z = cos(r * Math_TAU);
+ if (cap_bottom) {
+ float scale_neg = 1.0;
+ if (curve.is_valid() && curve->get_point_count() > 0) {
+ scale_neg = curve->sample_baked(1.0);
+ }
- float u = 0.5 + ((x + 1.0) * 0.25);
- float v = 1.0 - ((z + 1.0) * 0.25);
+ if (scale_neg > CMP_EPSILON) {
+ // add bottom
+ float y = depth * -0.5;
- Vector3 p = Vector3(x * rm, y, z * rm);
- points.push_back(p);
+ thisrow = point;
+ points.push_back(Vector3(0.0, y, 0.0));
normals.push_back(Vector3(0.0, -1.0, 0.0));
ADD_TANGENT(1.0, 0.0, 0.0, 1.0)
- uvs.push_back(Vector2(u, v));
+ uvs.push_back(Vector2(0.75, 0.75));
point++;
bone_indices.push_back(sections);
@@ -1979,13 +2394,43 @@ void TubeTrailMesh::_create_mesh_array(Array &p_arr) const {
bone_weights.push_back(0);
bone_weights.push_back(0);
- if (i > 0) {
- indices.push_back(thisrow);
- indices.push_back(point - 2);
- indices.push_back(point - 1);
- };
- };
- };
+ float rm = radius * scale_neg;
+
+ for (int i = 0; i <= radial_steps; i++) {
+ float r = i;
+ r /= radial_steps;
+
+ float x = sin(r * Math_TAU);
+ float z = cos(r * Math_TAU);
+
+ float u = 0.5 + ((x + 1.0) * 0.25);
+ float v = 1.0 - ((z + 1.0) * 0.25);
+
+ Vector3 p = Vector3(x * rm, y, z * rm);
+ points.push_back(p);
+ normals.push_back(Vector3(0.0, -1.0, 0.0));
+ ADD_TANGENT(1.0, 0.0, 0.0, 1.0)
+ uvs.push_back(Vector2(u, v));
+ point++;
+
+ bone_indices.push_back(sections);
+ bone_indices.push_back(0);
+ bone_indices.push_back(0);
+ bone_indices.push_back(0);
+
+ bone_weights.push_back(1.0);
+ bone_weights.push_back(0);
+ bone_weights.push_back(0);
+ bone_weights.push_back(0);
+
+ if (i > 0) {
+ indices.push_back(thisrow);
+ indices.push_back(point - 2);
+ indices.push_back(point - 1);
+ }
+ }
+ }
+ }
p_arr[RS::ARRAY_VERTEX] = points;
p_arr[RS::ARRAY_NORMAL] = normals;
@@ -2012,6 +2457,12 @@ void TubeTrailMesh::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_section_rings", "section_rings"), &TubeTrailMesh::set_section_rings);
ClassDB::bind_method(D_METHOD("get_section_rings"), &TubeTrailMesh::get_section_rings);
+ ClassDB::bind_method(D_METHOD("set_cap_top", "cap_top"), &TubeTrailMesh::set_cap_top);
+ ClassDB::bind_method(D_METHOD("is_cap_top"), &TubeTrailMesh::is_cap_top);
+
+ ClassDB::bind_method(D_METHOD("set_cap_bottom", "cap_bottom"), &TubeTrailMesh::set_cap_bottom);
+ ClassDB::bind_method(D_METHOD("is_cap_bottom"), &TubeTrailMesh::is_cap_bottom);
+
ClassDB::bind_method(D_METHOD("set_curve", "curve"), &TubeTrailMesh::set_curve);
ClassDB::bind_method(D_METHOD("get_curve"), &TubeTrailMesh::get_curve);
@@ -2024,13 +2475,16 @@ void TubeTrailMesh::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::INT, "section_rings", PROPERTY_HINT_RANGE, "1,128,1"), "set_section_rings", "get_section_rings");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "cap_top"), "set_cap_top", "is_cap_top");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "cap_bottom"), "set_cap_bottom", "is_cap_bottom");
+
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "curve", PROPERTY_HINT_RESOURCE_TYPE, "Curve"), "set_curve", "get_curve");
}
TubeTrailMesh::TubeTrailMesh() {
}
-// TUBE TRAIL
+// RIBBON TRAIL
void RibbonTrailMesh::set_shape(Shape p_shape) {
shape = p_shape;
@@ -2109,6 +2563,8 @@ Transform3D RibbonTrailMesh::get_builtin_bind_pose(int p_index) const {
}
void RibbonTrailMesh::_create_mesh_array(Array &p_arr) const {
+ // Seeing use case of ribbon trail mesh, no need to implement special UV2 calculation
+
PackedVector3Array points;
PackedVector3Array normals;
PackedFloat32Array tangents;
@@ -2354,13 +2810,7 @@ void TextMesh::_generate_glyph_mesh_data(const GlyphMeshKey &p_key, const Glyph
real_t step = CLAMP(curve_step / (p0 - p3).length(), 0.01, 0.5);
real_t t = step;
while (t < 1.0) {
- real_t omt = (1.0 - t);
- real_t omt2 = omt * omt;
- real_t omt3 = omt2 * omt;
- real_t t2 = t * t;
- real_t t3 = t2 * t;
-
- Vector2 point = p0 * omt3 + p1 * omt2 * t * 3.0 + p2 * omt * t2 * 3.0 + p3 * t3;
+ Vector2 point = p0.bezier_interpolate(p1, p2, p3, t);
Vector2 p = point * pixel_size + origin;
polygon.push_back(ContourPoint(p, false));
t += step;
diff --git a/scene/resources/primitive_meshes.h b/scene/resources/primitive_meshes.h
index ee61f0ac55..5cef042a18 100644
--- a/scene/resources/primitive_meshes.h
+++ b/scene/resources/primitive_meshes.h
@@ -56,6 +56,9 @@ private:
Ref<Material> material;
bool flip_faces = false;
+ bool add_uv2 = false;
+ float uv2_padding = 2.0;
+
// make sure we do an update after we've finished constructing our object
mutable bool pending_request = true;
void _update() const;
@@ -70,6 +73,10 @@ protected:
void _request_update();
GDVIRTUAL0RC(Array, _create_mesh_array)
+ Vector2 get_uv2_scale(Vector2 p_margin_scale = Vector2(1.0, 1.0)) const;
+ float get_lightmap_texel_size() const;
+ virtual void _update_lightmap_size(){};
+
public:
virtual int get_surface_count() const override;
virtual int surface_get_array_len(int p_idx) const override;
@@ -98,6 +105,12 @@ public:
void set_flip_faces(bool p_enable);
bool get_flip_faces() const;
+ void set_add_uv2(bool p_enable);
+ bool get_add_uv2() const { return add_uv2; }
+
+ void set_uv2_padding(float p_padding);
+ float get_uv2_padding() const { return uv2_padding; }
+
PrimitiveMesh();
~PrimitiveMesh();
};
@@ -118,8 +131,10 @@ protected:
static void _bind_methods();
virtual void _create_mesh_array(Array &p_arr) const override;
+ virtual void _update_lightmap_size() override;
+
public:
- static void create_mesh_array(Array &p_arr, float radius, float height, int radial_segments = 64, int rings = 8);
+ static void create_mesh_array(Array &p_arr, float radius, float height, int radial_segments = 64, int rings = 8, bool p_add_uv2 = false, const float p_uv2_padding = 1.0);
void set_radius(const float p_radius);
float get_radius() const;
@@ -152,8 +167,10 @@ protected:
static void _bind_methods();
virtual void _create_mesh_array(Array &p_arr) const override;
+ virtual void _update_lightmap_size() override;
+
public:
- static void create_mesh_array(Array &p_arr, Vector3 size, int subdivide_w = 0, int subdivide_h = 0, int subdivide_d = 0);
+ static void create_mesh_array(Array &p_arr, Vector3 size, int subdivide_w = 0, int subdivide_h = 0, int subdivide_d = 0, bool p_add_uv2 = false, const float p_uv2_padding = 1.0);
void set_size(const Vector3 &p_size);
Vector3 get_size() const;
@@ -190,8 +207,10 @@ protected:
static void _bind_methods();
virtual void _create_mesh_array(Array &p_arr) const override;
+ virtual void _update_lightmap_size() override;
+
public:
- static void create_mesh_array(Array &p_arr, float top_radius, float bottom_radius, float height, int radial_segments = 64, int rings = 4, bool cap_top = true, bool cap_bottom = true);
+ static void create_mesh_array(Array &p_arr, float top_radius, float bottom_radius, float height, int radial_segments = 64, int rings = 4, bool cap_top = true, bool cap_bottom = true, bool p_add_uv2 = false, const float p_uv2_padding = 1.0);
void set_top_radius(const float p_radius);
float get_top_radius() const;
@@ -241,6 +260,8 @@ protected:
static void _bind_methods();
virtual void _create_mesh_array(Array &p_arr) const override;
+ virtual void _update_lightmap_size() override;
+
public:
void set_size(const Size2 &p_size);
Size2 get_size() const;
@@ -292,6 +313,8 @@ protected:
static void _bind_methods();
virtual void _create_mesh_array(Array &p_arr) const override;
+ virtual void _update_lightmap_size() override;
+
public:
void set_left_to_right(const float p_left_to_right);
float get_left_to_right() const;
@@ -328,8 +351,10 @@ protected:
static void _bind_methods();
virtual void _create_mesh_array(Array &p_arr) const override;
+ virtual void _update_lightmap_size() override;
+
public:
- static void create_mesh_array(Array &p_arr, float radius, float height, int radial_segments = 64, int rings = 32, bool is_hemisphere = false);
+ static void create_mesh_array(Array &p_arr, float radius, float height, int radial_segments = 64, int rings = 32, bool is_hemisphere = false, bool p_add_uv2 = false, const float p_uv2_padding = 1.0);
void set_radius(const float p_radius);
float get_radius() const;
@@ -365,6 +390,8 @@ protected:
static void _bind_methods();
virtual void _create_mesh_array(Array &p_arr) const override;
+ virtual void _update_lightmap_size() override;
+
public:
void set_inner_radius(const float p_inner_radius);
float get_inner_radius() const;
@@ -404,6 +431,8 @@ private:
int sections = 5;
float section_length = 0.2;
int section_rings = 3;
+ bool cap_top = true;
+ bool cap_bottom = true;
Ref<Curve> curve;
@@ -429,6 +458,12 @@ public:
void set_section_rings(const int p_section_rings);
int get_section_rings() const;
+ void set_cap_top(bool p_cap_top);
+ bool is_cap_top() const;
+
+ void set_cap_bottom(bool p_cap_bottom);
+ bool is_cap_bottom() const;
+
void set_curve(const Ref<Curve> &p_curve);
Ref<Curve> get_curve() const;
diff --git a/scene/resources/resource_format_text.cpp b/scene/resources/resource_format_text.cpp
index 85b538b1d9..092f672cba 100644
--- a/scene/resources/resource_format_text.cpp
+++ b/scene/resources/resource_format_text.cpp
@@ -144,6 +144,7 @@ Error ResourceLoaderText::_parse_ext_resource(VariantParser::Stream *p_stream, R
}
String id = token.value;
+ Error err = OK;
if (!ignore_resource_parsing) {
if (!ext_resources.has(id)) {
@@ -163,7 +164,7 @@ Error ResourceLoaderText::_parse_ext_resource(VariantParser::Stream *p_stream, R
error = ERR_FILE_MISSING_DEPENDENCIES;
error_text = "[ext_resource] referenced nonexistent resource at: " + path;
_printerr();
- return error;
+ err = error;
} else {
ResourceLoader::notify_dependency_error(local_path, path, type);
}
@@ -175,7 +176,7 @@ Error ResourceLoaderText::_parse_ext_resource(VariantParser::Stream *p_stream, R
error = ERR_FILE_MISSING_DEPENDENCIES;
error_text = "[ext_resource] referenced non-loaded resource at: " + path;
_printerr();
- return error;
+ err = error;
}
} else {
r_res = Ref<Resource>();
@@ -187,7 +188,7 @@ Error ResourceLoaderText::_parse_ext_resource(VariantParser::Stream *p_stream, R
return ERR_PARSE_ERROR;
}
- return OK;
+ return err;
}
Ref<PackedScene> ResourceLoaderText::_parse_node_tag(VariantParser::ResourceParser &parser) {
@@ -217,7 +218,7 @@ Ref<PackedScene> ResourceLoaderText::_parse_node_tag(VariantParser::ResourcePars
if (next_tag.fields.has("type")) {
type = packed_scene->get_state()->add_name(next_tag.fields["type"]);
} else {
- type = SceneState::TYPE_INSTANCED; //no type? assume this was instantiated
+ type = SceneState::TYPE_INSTANTIATED; //no type? assume this was instantiated
}
HashSet<StringName> path_properties;
@@ -256,7 +257,7 @@ Ref<PackedScene> ResourceLoaderText::_parse_node_tag(VariantParser::ResourcePars
if (next_tag.fields.has("owner")) {
owner = packed_scene->get_state()->add_node_path(next_tag.fields["owner"]);
} else {
- if (parent != -1 && !(type == SceneState::TYPE_INSTANCED && instance == -1)) {
+ if (parent != -1 && !(type == SceneState::TYPE_INSTANTIATED && instance == -1)) {
owner = 0; //if no owner, owner is root
}
}
@@ -511,6 +512,7 @@ Error ResourceLoaderText::load() {
if (error) {
_printerr();
+ return error;
}
resource_current++;
@@ -600,9 +602,13 @@ Error ResourceLoaderText::load() {
resource_current++;
int_resources[id] = res; //always assign int resources
- if (do_assign && cache_mode != ResourceFormatLoader::CACHE_MODE_IGNORE) {
- res->set_path(path, cache_mode == ResourceFormatLoader::CACHE_MODE_REPLACE);
- res->set_scene_unique_id(id);
+ if (do_assign) {
+ if (cache_mode == ResourceFormatLoader::CACHE_MODE_IGNORE) {
+ res->set_path(path);
+ } else {
+ res->set_path(path, cache_mode == ResourceFormatLoader::CACHE_MODE_REPLACE);
+ res->set_scene_unique_id(id);
+ }
}
Dictionary missing_resource_properties;
@@ -830,7 +836,8 @@ void ResourceLoaderText::set_translation_remapped(bool p_remapped) {
translation_remapped = p_remapped;
}
-ResourceLoaderText::ResourceLoaderText() {}
+ResourceLoaderText::ResourceLoaderText() :
+ stream(false) {}
void ResourceLoaderText::get_dependencies(Ref<FileAccess> p_f, List<String> *p_dependencies, bool p_add_types) {
open(p_f);
@@ -884,6 +891,7 @@ void ResourceLoaderText::get_dependencies(Ref<FileAccess> p_f, List<String> *p_d
error_text = "Unexpected end of file";
_printerr();
error = ERR_FILE_CORRUPT;
+ return;
}
}
}
@@ -974,15 +982,26 @@ Error ResourceLoaderText::rename_dependencies(Ref<FileAccess> p_f, const String
f->seek(tag_end);
- uint8_t c = f->get_8();
- if (c == '\n' && !f->eof_reached()) {
- // Skip first newline character since we added one
- c = f->get_8();
+ const uint32_t buffer_size = 2048;
+ uint8_t *buffer = (uint8_t *)alloca(buffer_size);
+ uint32_t num_read;
+
+ num_read = f->get_buffer(buffer, buffer_size);
+ ERR_FAIL_COND_V_MSG(num_read == UINT32_MAX, ERR_CANT_CREATE, "Failed to allocate memory for buffer.");
+ ERR_FAIL_COND_V(num_read == 0, ERR_FILE_CORRUPT);
+
+ if (*buffer == '\n') {
+ // Skip first newline character since we added one.
+ if (num_read > 1) {
+ fw->store_buffer(buffer + 1, num_read - 1);
+ }
+ } else {
+ fw->store_buffer(buffer, num_read);
}
while (!f->eof_reached()) {
- fw->store_8(c);
- c = f->get_8();
+ num_read = f->get_buffer(buffer, buffer_size);
+ fw->store_buffer(buffer, num_read);
}
bool all_ok = fw->get_error() == OK;
@@ -1349,7 +1368,7 @@ Error ResourceLoaderText::save_as_binary(const String &p_path) {
wf->seek_end();
- Vector<uint8_t> data = FileAccess::get_file_as_array(temp_file);
+ Vector<uint8_t> data = FileAccess::get_file_as_bytes(temp_file);
wf->store_buffer(data.ptr(), data.size());
{
Ref<DirAccess> dar = DirAccess::open(temp_file.get_base_dir());
diff --git a/scene/resources/shader.cpp b/scene/resources/shader.cpp
index 4d566178a5..48ec084b02 100644
--- a/scene/resources/shader.cpp
+++ b/scene/resources/shader.cpp
@@ -177,7 +177,7 @@ bool Shader::is_text_shader() const {
}
bool Shader::has_parameter(const StringName &p_name) const {
- return params_cache.has("shader_parameter/" + p_name);
+ return params_cache.has(p_name);
}
void Shader::_update_shader() const {
@@ -221,7 +221,7 @@ Ref<Resource> ResourceFormatLoaderShader::load(const String &p_path, const Strin
Ref<Shader> shader;
shader.instantiate();
- Vector<uint8_t> buffer = FileAccess::get_file_as_array(p_path);
+ Vector<uint8_t> buffer = FileAccess::get_file_as_bytes(p_path);
String str;
str.parse_utf8((const char *)buffer.ptr(), buffer.size());
diff --git a/scene/resources/shader_include.cpp b/scene/resources/shader_include.cpp
index fe628dd323..a680e66a50 100644
--- a/scene/resources/shader_include.cpp
+++ b/scene/resources/shader_include.cpp
@@ -81,7 +81,7 @@ Ref<Resource> ResourceFormatLoaderShaderInclude::load(const String &p_path, cons
Ref<ShaderInclude> shader_inc;
shader_inc.instantiate();
- Vector<uint8_t> buffer = FileAccess::get_file_as_array(p_path);
+ Vector<uint8_t> buffer = FileAccess::get_file_as_bytes(p_path);
String str;
str.parse_utf8((const char *)buffer.ptr(), buffer.size());
diff --git a/scene/resources/shape_2d.cpp b/scene/resources/shape_2d.cpp
index af84144591..87c6c36ee9 100644
--- a/scene/resources/shape_2d.cpp
+++ b/scene/resources/shape_2d.cpp
@@ -124,5 +124,6 @@ Shape2D::Shape2D(const RID &p_rid) {
}
Shape2D::~Shape2D() {
+ ERR_FAIL_NULL(PhysicsServer2D::get_singleton());
PhysicsServer2D::get_singleton()->free(shape);
}
diff --git a/scene/resources/shape_3d.cpp b/scene/resources/shape_3d.cpp
index 4423c1d7bb..7992ba9fd4 100644
--- a/scene/resources/shape_3d.cpp
+++ b/scene/resources/shape_3d.cpp
@@ -128,5 +128,6 @@ Shape3D::Shape3D(RID p_shape) :
shape(p_shape) {}
Shape3D::~Shape3D() {
+ ERR_FAIL_NULL(PhysicsServer3D::get_singleton());
PhysicsServer3D::get_singleton()->free(shape);
}
diff --git a/scene/resources/skeleton_modification_2d_fabrik.h b/scene/resources/skeleton_modification_2d_fabrik.h
index 4a875d039f..0ca6582965 100644
--- a/scene/resources/skeleton_modification_2d_fabrik.h
+++ b/scene/resources/skeleton_modification_2d_fabrik.h
@@ -68,8 +68,8 @@ private:
float chain_tolarance = 0.01;
int chain_max_iterations = 10;
int chain_iterations = 0;
- Transform2D target_global_pose = Transform2D();
- Transform2D origin_global_pose = Transform2D();
+ Transform2D target_global_pose;
+ Transform2D origin_global_pose;
void fabrik_joint_update_bone2d_cache(int p_joint_idx);
void chain_backwards();
diff --git a/scene/resources/skeleton_modification_3d_fabrik.h b/scene/resources/skeleton_modification_3d_fabrik.h
index e2e490d636..3e3aa5e587 100644
--- a/scene/resources/skeleton_modification_3d_fabrik.h
+++ b/scene/resources/skeleton_modification_3d_fabrik.h
@@ -47,7 +47,7 @@ private:
bool auto_calculate_length = true;
bool use_tip_node = false;
- NodePath tip_node = NodePath();
+ NodePath tip_node;
ObjectID tip_node_cache;
bool use_target_basis = false;
@@ -68,8 +68,8 @@ private:
void update_joint_tip_cache(int p_joint_idx);
int final_joint_idx = 0;
- Transform3D target_global_pose = Transform3D();
- Transform3D origin_global_pose = Transform3D();
+ Transform3D target_global_pose;
+ Transform3D origin_global_pose;
void chain_backwards();
void chain_forwards();
diff --git a/scene/resources/style_box.cpp b/scene/resources/style_box.cpp
index f379f88bed..ea341152e6 100644
--- a/scene/resources/style_box.cpp
+++ b/scene/resources/style_box.cpp
@@ -35,11 +35,9 @@
#include <limits.h>
float StyleBox::get_style_margin(Side p_side) const {
- float ret;
- if (GDVIRTUAL_REQUIRED_CALL(_get_style_margin, p_side, ret)) {
- return ret;
- }
- return 0;
+ float ret = 0;
+ GDVIRTUAL_REQUIRED_CALL(_get_style_margin, p_side, ret);
+ return ret;
}
bool StyleBox::test_mask(const Point2 &p_point, const Rect2 &p_rect) const {
@@ -49,9 +47,7 @@ bool StyleBox::test_mask(const Point2 &p_point, const Rect2 &p_rect) const {
}
void StyleBox::draw(RID p_canvas_item, const Rect2 &p_rect) const {
- if (GDVIRTUAL_REQUIRED_CALL(_draw, p_canvas_item, p_rect)) {
- return;
- }
+ GDVIRTUAL_REQUIRED_CALL(_draw, p_canvas_item, p_rect);
}
void StyleBox::set_default_margin(Side p_side, float p_value) {
diff --git a/scene/resources/syntax_highlighter.cpp b/scene/resources/syntax_highlighter.cpp
index f1eddd8ffc..cb5cb4ef96 100644
--- a/scene/resources/syntax_highlighter.cpp
+++ b/scene/resources/syntax_highlighter.cpp
@@ -336,7 +336,7 @@ Dictionary CodeHighlighter::_get_line_syntax_highlighting_impl(int p_line) {
}
String word = str.substr(j, to - j);
- Color col = Color();
+ Color col;
if (keywords.has(word)) {
col = keywords[word];
} else if (member_keywords.has(word)) {
diff --git a/scene/resources/text_line.cpp b/scene/resources/text_line.cpp
index afab44834d..d094563e6a 100644
--- a/scene/resources/text_line.cpp
+++ b/scene/resources/text_line.cpp
@@ -56,8 +56,8 @@ void TextLine::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_bidi_override", "override"), &TextLine::set_bidi_override);
ClassDB::bind_method(D_METHOD("add_string", "text", "font", "font_size", "language", "meta"), &TextLine::add_string, DEFVAL(""), DEFVAL(Variant()));
- ClassDB::bind_method(D_METHOD("add_object", "key", "size", "inline_align", "length"), &TextLine::add_object, DEFVAL(INLINE_ALIGNMENT_CENTER), DEFVAL(1));
- ClassDB::bind_method(D_METHOD("resize_object", "key", "size", "inline_align"), &TextLine::resize_object, DEFVAL(INLINE_ALIGNMENT_CENTER));
+ ClassDB::bind_method(D_METHOD("add_object", "key", "size", "inline_align", "length", "baseline"), &TextLine::add_object, DEFVAL(INLINE_ALIGNMENT_CENTER), DEFVAL(1), DEFVAL(0.0));
+ ClassDB::bind_method(D_METHOD("resize_object", "key", "size", "inline_align", "baseline"), &TextLine::resize_object, DEFVAL(INLINE_ALIGNMENT_CENTER), DEFVAL(0.0));
ClassDB::bind_method(D_METHOD("set_width", "width"), &TextLine::set_width);
ClassDB::bind_method(D_METHOD("get_width"), &TextLine::get_width);
@@ -202,15 +202,15 @@ bool TextLine::add_string(const String &p_text, const Ref<Font> &p_font, int p_f
return res;
}
-bool TextLine::add_object(Variant p_key, const Size2 &p_size, InlineAlignment p_inline_align, int p_length) {
- bool res = TS->shaped_text_add_object(rid, p_key, p_size, p_inline_align, p_length);
+bool TextLine::add_object(Variant p_key, const Size2 &p_size, InlineAlignment p_inline_align, int p_length, float p_baseline) {
+ bool res = TS->shaped_text_add_object(rid, p_key, p_size, p_inline_align, p_length, p_baseline);
dirty = true;
return res;
}
-bool TextLine::resize_object(Variant p_key, const Size2 &p_size, InlineAlignment p_inline_align) {
+bool TextLine::resize_object(Variant p_key, const Size2 &p_size, InlineAlignment p_inline_align, float p_baseline) {
const_cast<TextLine *>(this)->_shape();
- return TS->shaped_text_resize_object(rid, p_key, p_size, p_inline_align);
+ return TS->shaped_text_resize_object(rid, p_key, p_size, p_inline_align, p_baseline);
}
Array TextLine::get_objects() const {
diff --git a/scene/resources/text_line.h b/scene/resources/text_line.h
index e70e82cf2b..801a8a8c11 100644
--- a/scene/resources/text_line.h
+++ b/scene/resources/text_line.h
@@ -76,8 +76,8 @@ public:
bool get_preserve_control() const;
bool add_string(const String &p_text, const Ref<Font> &p_font, int p_font_size, const String &p_language = "", const Variant &p_meta = Variant());
- bool add_object(Variant p_key, const Size2 &p_size, InlineAlignment p_inline_align = INLINE_ALIGNMENT_CENTER, int p_length = 1);
- bool resize_object(Variant p_key, const Size2 &p_size, InlineAlignment p_inline_align = INLINE_ALIGNMENT_CENTER);
+ bool add_object(Variant p_key, const Size2 &p_size, InlineAlignment p_inline_align = INLINE_ALIGNMENT_CENTER, int p_length = 1, float p_baseline = 0.0);
+ bool resize_object(Variant p_key, const Size2 &p_size, InlineAlignment p_inline_align = INLINE_ALIGNMENT_CENTER, float p_baseline = 0.0);
void set_horizontal_alignment(HorizontalAlignment p_alignment);
HorizontalAlignment get_horizontal_alignment() const;
diff --git a/scene/resources/text_paragraph.cpp b/scene/resources/text_paragraph.cpp
index 59bb24c8b8..d2e85d28e6 100644
--- a/scene/resources/text_paragraph.cpp
+++ b/scene/resources/text_paragraph.cpp
@@ -64,8 +64,8 @@ void TextParagraph::_bind_methods() {
ClassDB::bind_method(D_METHOD("clear_dropcap"), &TextParagraph::clear_dropcap);
ClassDB::bind_method(D_METHOD("add_string", "text", "font", "font_size", "language", "meta"), &TextParagraph::add_string, DEFVAL(""), DEFVAL(Variant()));
- ClassDB::bind_method(D_METHOD("add_object", "key", "size", "inline_align", "length"), &TextParagraph::add_object, DEFVAL(INLINE_ALIGNMENT_CENTER), DEFVAL(1));
- ClassDB::bind_method(D_METHOD("resize_object", "key", "size", "inline_align"), &TextParagraph::resize_object, DEFVAL(INLINE_ALIGNMENT_CENTER));
+ ClassDB::bind_method(D_METHOD("add_object", "key", "size", "inline_align", "length", "baseline"), &TextParagraph::add_object, DEFVAL(INLINE_ALIGNMENT_CENTER), DEFVAL(1), DEFVAL(0.0));
+ ClassDB::bind_method(D_METHOD("resize_object", "key", "size", "inline_align", "baseline"), &TextParagraph::resize_object, DEFVAL(INLINE_ALIGNMENT_CENTER), DEFVAL(0.0));
ClassDB::bind_method(D_METHOD("set_alignment", "alignment"), &TextParagraph::set_alignment);
ClassDB::bind_method(D_METHOD("get_alignment"), &TextParagraph::get_alignment);
@@ -385,18 +385,18 @@ void TextParagraph::set_bidi_override(const Array &p_override) {
lines_dirty = true;
}
-bool TextParagraph::add_object(Variant p_key, const Size2 &p_size, InlineAlignment p_inline_align, int p_length) {
+bool TextParagraph::add_object(Variant p_key, const Size2 &p_size, InlineAlignment p_inline_align, int p_length, float p_baseline) {
_THREAD_SAFE_METHOD_
- bool res = TS->shaped_text_add_object(rid, p_key, p_size, p_inline_align, p_length);
+ bool res = TS->shaped_text_add_object(rid, p_key, p_size, p_inline_align, p_length, p_baseline);
lines_dirty = true;
return res;
}
-bool TextParagraph::resize_object(Variant p_key, const Size2 &p_size, InlineAlignment p_inline_align) {
+bool TextParagraph::resize_object(Variant p_key, const Size2 &p_size, InlineAlignment p_inline_align, float p_baseline) {
_THREAD_SAFE_METHOD_
- bool res = TS->shaped_text_resize_object(rid, p_key, p_size, p_inline_align);
+ bool res = TS->shaped_text_resize_object(rid, p_key, p_size, p_inline_align, p_baseline);
lines_dirty = true;
return res;
}
diff --git a/scene/resources/text_paragraph.h b/scene/resources/text_paragraph.h
index 0fe82b4364..dced278db4 100644
--- a/scene/resources/text_paragraph.h
+++ b/scene/resources/text_paragraph.h
@@ -95,8 +95,8 @@ public:
void clear_dropcap();
bool add_string(const String &p_text, const Ref<Font> &p_font, int p_font_size, const String &p_language = "", const Variant &p_meta = Variant());
- bool add_object(Variant p_key, const Size2 &p_size, InlineAlignment p_inline_align = INLINE_ALIGNMENT_CENTER, int p_length = 1);
- bool resize_object(Variant p_key, const Size2 &p_size, InlineAlignment p_inline_align = INLINE_ALIGNMENT_CENTER);
+ bool add_object(Variant p_key, const Size2 &p_size, InlineAlignment p_inline_align = INLINE_ALIGNMENT_CENTER, int p_length = 1, float p_baseline = 0.0);
+ bool resize_object(Variant p_key, const Size2 &p_size, InlineAlignment p_inline_align = INLINE_ALIGNMENT_CENTER, float p_baseline = 0.0);
void set_alignment(HorizontalAlignment p_alignment);
HorizontalAlignment get_alignment() const;
diff --git a/scene/resources/texture.cpp b/scene/resources/texture.cpp
index a6fb359051..18915e294e 100644
--- a/scene/resources/texture.cpp
+++ b/scene/resources/texture.cpp
@@ -40,19 +40,15 @@
#include "servers/camera/camera_feed.h"
int Texture2D::get_width() const {
- int ret;
- if (GDVIRTUAL_REQUIRED_CALL(_get_width, ret)) {
- return ret;
- }
- return 0;
+ int ret = 0;
+ GDVIRTUAL_REQUIRED_CALL(_get_width, ret);
+ return ret;
}
int Texture2D::get_height() const {
- int ret;
- if (GDVIRTUAL_REQUIRED_CALL(_get_height, ret)) {
- return ret;
- }
- return 0;
+ int ret = 0;
+ GDVIRTUAL_REQUIRED_CALL(_get_height, ret);
+ return ret;
}
Size2 Texture2D::get_size() const {
@@ -64,6 +60,7 @@ bool Texture2D::is_pixel_opaque(int p_x, int p_y) const {
GDVIRTUAL_CALL(_is_pixel_opaque, p_x, p_y, ret);
return ret;
}
+
bool Texture2D::has_alpha() const {
bool ret = true;
GDVIRTUAL_CALL(_has_alpha, ret);
@@ -1091,57 +1088,44 @@ TypedArray<Image> Texture3D::_get_datai() const {
}
Image::Format Texture3D::get_format() const {
- Image::Format ret;
- if (GDVIRTUAL_REQUIRED_CALL(_get_format, ret)) {
- return ret;
- }
- return Image::FORMAT_MAX;
+ Image::Format ret = Image::FORMAT_MAX;
+ GDVIRTUAL_REQUIRED_CALL(_get_format, ret);
+ return ret;
}
int Texture3D::get_width() const {
- int ret;
- if (GDVIRTUAL_REQUIRED_CALL(_get_width, ret)) {
- return ret;
- }
- return 0;
+ int ret = 0;
+ GDVIRTUAL_REQUIRED_CALL(_get_width, ret);
+ return ret;
}
int Texture3D::get_height() const {
- int ret;
- if (GDVIRTUAL_REQUIRED_CALL(_get_height, ret)) {
- return ret;
- }
- return 0;
+ int ret = 0;
+ GDVIRTUAL_REQUIRED_CALL(_get_height, ret);
+ return ret;
}
int Texture3D::get_depth() const {
- int ret;
- if (GDVIRTUAL_REQUIRED_CALL(_get_depth, ret)) {
- return ret;
- }
-
- return 0;
+ int ret = 0;
+ GDVIRTUAL_REQUIRED_CALL(_get_depth, ret);
+ return ret;
}
bool Texture3D::has_mipmaps() const {
- bool ret;
- if (GDVIRTUAL_REQUIRED_CALL(_has_mipmaps, ret)) {
- return ret;
- }
- return false;
+ bool ret = false;
+ GDVIRTUAL_REQUIRED_CALL(_has_mipmaps, ret);
+ return ret;
}
Vector<Ref<Image>> Texture3D::get_data() const {
TypedArray<Image> ret;
- if (GDVIRTUAL_REQUIRED_CALL(_get_data, ret)) {
- Vector<Ref<Image>> data;
- data.resize(ret.size());
- for (int i = 0; i < data.size(); i++) {
- data.write[i] = ret[i];
- }
- return data;
+ GDVIRTUAL_REQUIRED_CALL(_get_data, ret);
+ Vector<Ref<Image>> data;
+ data.resize(ret.size());
+ for (int i = 0; i < data.size(); i++) {
+ data.write[i] = ret[i];
}
- return Vector<Ref<Image>>();
+ return data;
}
void Texture3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_format"), &Texture3D::get_format);
@@ -1607,35 +1591,28 @@ bool AtlasTexture::get_rect_region(const Rect2 &p_rect, const Rect2 &p_src_rect,
return false;
}
- Rect2 rc = region;
-
Rect2 src = p_src_rect;
if (src.size == Size2()) {
- src.size = rc.size;
+ src.size = region.size;
}
Vector2 scale = p_rect.size / src.size;
- src.position += (rc.position - margin.position);
- Rect2 src_c = rc.intersection(src);
- if (src_c.size == Size2()) {
+ src.position += (region.position - margin.position);
+ Rect2 src_clipped = region.intersection(src);
+ if (src_clipped.size == Size2()) {
return false;
}
- Vector2 ofs = (src_c.position - src.position);
+ Vector2 ofs = (src_clipped.position - src.position);
if (scale.x < 0) {
- float mx = (margin.size.width - margin.position.x);
- mx -= margin.position.x;
- ofs.x = -(ofs.x + mx);
+ ofs.x += (src_clipped.size.x - src.size.x);
}
if (scale.y < 0) {
- float my = margin.size.height - margin.position.y;
- my -= margin.position.y;
- ofs.y = -(ofs.y + my);
+ ofs.y += (src_clipped.size.y - src.size.y);
}
- Rect2 dr(p_rect.position + ofs * scale, src_c.size * scale);
- r_rect = dr;
- r_src_rect = src_c;
+ r_rect = Rect2(p_rect.position + ofs * scale, src_clipped.size * scale);
+ r_src_rect = src_clipped;
return true;
}
@@ -2858,60 +2835,45 @@ AnimatedTexture::~AnimatedTexture() {
///////////////////////////////
Image::Format TextureLayered::get_format() const {
- Image::Format ret;
- if (GDVIRTUAL_REQUIRED_CALL(_get_format, ret)) {
- return ret;
- }
- return Image::FORMAT_MAX;
+ Image::Format ret = Image::FORMAT_MAX;
+ GDVIRTUAL_REQUIRED_CALL(_get_format, ret);
+ return ret;
}
TextureLayered::LayeredType TextureLayered::get_layered_type() const {
- uint32_t ret;
- if (GDVIRTUAL_REQUIRED_CALL(_get_layered_type, ret)) {
- return (LayeredType)ret;
- }
- return LAYERED_TYPE_2D_ARRAY;
+ uint32_t ret = LAYERED_TYPE_2D_ARRAY;
+ GDVIRTUAL_REQUIRED_CALL(_get_layered_type, ret);
+ return (LayeredType)ret;
}
int TextureLayered::get_width() const {
- int ret;
- if (GDVIRTUAL_REQUIRED_CALL(_get_width, ret)) {
- return ret;
- }
- return 0;
+ int ret = 0;
+ GDVIRTUAL_REQUIRED_CALL(_get_width, ret);
+ return ret;
}
int TextureLayered::get_height() const {
- int ret;
- if (GDVIRTUAL_REQUIRED_CALL(_get_height, ret)) {
- return ret;
- }
- return 0;
+ int ret = 0;
+ GDVIRTUAL_REQUIRED_CALL(_get_height, ret);
+ return ret;
}
int TextureLayered::get_layers() const {
- int ret;
- if (GDVIRTUAL_REQUIRED_CALL(_get_layers, ret)) {
- return ret;
- }
-
- return 0;
+ int ret = 0;
+ GDVIRTUAL_REQUIRED_CALL(_get_layers, ret);
+ return ret;
}
bool TextureLayered::has_mipmaps() const {
- bool ret;
- if (GDVIRTUAL_REQUIRED_CALL(_has_mipmaps, ret)) {
- return ret;
- }
- return false;
+ bool ret = false;
+ GDVIRTUAL_REQUIRED_CALL(_has_mipmaps, ret);
+ return ret;
}
Ref<Image> TextureLayered::get_layer_data(int p_layer) const {
Ref<Image> ret;
- if (GDVIRTUAL_REQUIRED_CALL(_get_layer_data, p_layer, ret)) {
- return ret;
- }
- return Ref<Image>();
+ GDVIRTUAL_REQUIRED_CALL(_get_layer_data, p_layer, ret);
+ return ret;
}
void TextureLayered::_bind_methods() {
diff --git a/scene/resources/tile_set.cpp b/scene/resources/tile_set.cpp
index 3caf6484d9..0b0461432b 100644
--- a/scene/resources/tile_set.cpp
+++ b/scene/resources/tile_set.cpp
@@ -35,7 +35,6 @@
#include "core/math/geometry_2d.h"
#include "core/templates/local_vector.h"
#include "core/templates/rb_set.h"
-#include "scene/2d/navigation_region_2d.h"
#include "scene/gui/control.h"
#include "scene/resources/convex_polygon_shape_2d.h"
#include "servers/navigation_server_2d.h"
@@ -477,7 +476,7 @@ int TileSet::add_source(Ref<TileSetSource> p_tile_set_source, int p_atlas_source
int new_source_id = p_atlas_source_id_override >= 0 ? p_atlas_source_id_override : next_source_id;
sources[new_source_id] = p_tile_set_source;
- source_ids.append(new_source_id);
+ source_ids.push_back(new_source_id);
source_ids.sort();
p_tile_set_source->set_tile_set(this);
_compute_next_source_id();
@@ -517,7 +516,7 @@ void TileSet::set_source_id(int p_source_id, int p_new_source_id) {
sources.erase(p_source_id);
source_ids.erase(p_source_id);
- source_ids.append(p_new_source_id);
+ source_ids.push_back(p_new_source_id);
source_ids.sort();
_compute_next_source_id();
@@ -1297,7 +1296,7 @@ void TileSet::cleanup_invalid_tile_proxies() {
Vector<int> source_to_remove;
for (const KeyValue<int, int> &E : source_level_proxies) {
if (has_source(E.key)) {
- source_to_remove.append(E.key);
+ source_to_remove.push_back(E.key);
}
}
for (int i = 0; i < source_to_remove.size(); i++) {
@@ -1309,7 +1308,7 @@ void TileSet::cleanup_invalid_tile_proxies() {
for (const KeyValue<Array, Array> &E : coords_level_proxies) {
Array a = E.key;
if (has_source(a[0]) && get_source(a[0])->has_tile(a[1])) {
- coords_to_remove.append(a);
+ coords_to_remove.push_back(a);
}
}
for (int i = 0; i < coords_to_remove.size(); i++) {
@@ -1322,7 +1321,7 @@ void TileSet::cleanup_invalid_tile_proxies() {
for (const KeyValue<Array, Array> &E : alternative_level_proxies) {
Array a = E.key;
if (has_source(a[0]) && get_source(a[0])->has_tile(a[1]) && get_source(a[0])->has_alternative_tile(a[1], a[2])) {
- alternative_to_remove.append(a);
+ alternative_to_remove.push_back(a);
}
}
for (int i = 0; i < alternative_to_remove.size(); i++) {
@@ -1439,16 +1438,18 @@ TileMapCell TileSet::get_random_tile_from_terrains_pattern(int p_terrain_set, Ti
Vector<Vector2> TileSet::get_tile_shape_polygon() {
Vector<Vector2> points;
if (tile_shape == TileSet::TILE_SHAPE_SQUARE) {
- points.append(Vector2(-0.5, -0.5));
- points.append(Vector2(0.5, -0.5));
- points.append(Vector2(0.5, 0.5));
- points.append(Vector2(-0.5, 0.5));
+ points.push_back(Vector2(-0.5, -0.5));
+ points.push_back(Vector2(0.5, -0.5));
+ points.push_back(Vector2(0.5, 0.5));
+ points.push_back(Vector2(-0.5, 0.5));
+ } else if (tile_shape == TileSet::TILE_SHAPE_ISOMETRIC) {
+ points.push_back(Vector2(0.0, -0.5));
+ points.push_back(Vector2(-0.5, 0.0));
+ points.push_back(Vector2(0.0, 0.5));
+ points.push_back(Vector2(0.5, 0.0));
} else {
float overlap = 0.0;
switch (tile_shape) {
- case TileSet::TILE_SHAPE_ISOMETRIC:
- overlap = 0.5;
- break;
case TileSet::TILE_SHAPE_HEXAGON:
overlap = 0.25;
break;
@@ -1459,12 +1460,13 @@ Vector<Vector2> TileSet::get_tile_shape_polygon() {
break;
}
- points.append(Vector2(0.0, -0.5));
- points.append(Vector2(-0.5, overlap - 0.5));
- points.append(Vector2(-0.5, 0.5 - overlap));
- points.append(Vector2(0.0, 0.5));
- points.append(Vector2(0.5, 0.5 - overlap));
- points.append(Vector2(0.5, overlap - 0.5));
+ points.push_back(Vector2(0.0, -0.5));
+ points.push_back(Vector2(-0.5, overlap - 0.5));
+ points.push_back(Vector2(-0.5, 0.5 - overlap));
+ points.push_back(Vector2(0.0, 0.5));
+ points.push_back(Vector2(0.5, 0.5 - overlap));
+ points.push_back(Vector2(0.5, overlap - 0.5));
+
if (get_tile_offset_axis() == TileSet::TILE_OFFSET_AXIS_VERTICAL) {
for (int i = 0; i < points.size(); i++) {
points.write[i] = Vector2(points[i].y, points[i].x);
@@ -3789,7 +3791,7 @@ Vector2i TileSetAtlasSource::get_atlas_grid_size() const {
Size2i valid_area = txt->get_size() - margins;
// Compute the number of valid tiles in the tiles atlas
- Size2i grid_size = Size2i();
+ Size2i grid_size;
if (valid_area.x >= texture_region_size.x && valid_area.y >= texture_region_size.y) {
valid_area -= texture_region_size;
grid_size = Size2i(1, 1) + valid_area / (texture_region_size + separation);
@@ -3854,7 +3856,7 @@ bool TileSetAtlasSource::_set(const StringName &p_name, const Variant &p_value)
tiles[coords].alternatives[alternative_id] = memnew(TileData);
tiles[coords].alternatives[alternative_id]->set_tile_set(tile_set);
tiles[coords].alternatives[alternative_id]->set_allow_transform(alternative_id > 0);
- tiles[coords].alternatives_ids.append(alternative_id);
+ tiles[coords].alternatives_ids.push_back(alternative_id);
}
if (components.size() >= 3) {
bool valid;
@@ -4028,11 +4030,11 @@ void TileSetAtlasSource::create_tile(const Vector2i p_atlas_coords, const Vector
tad.alternatives[0]->set_allow_transform(false);
tad.alternatives[0]->connect("changed", callable_mp((Resource *)this, &TileSetAtlasSource::emit_changed));
tad.alternatives[0]->notify_property_list_changed();
- tad.alternatives_ids.append(0);
+ tad.alternatives_ids.push_back(0);
// Create and resize the tile.
tiles.insert(p_atlas_coords, tad);
- tiles_ids.append(p_atlas_coords);
+ tiles_ids.push_back(p_atlas_coords);
tiles_ids.sort();
_create_coords_mapping_cache(p_atlas_coords);
@@ -4343,7 +4345,7 @@ void TileSetAtlasSource::move_tile_in_atlas(Vector2i p_atlas_coords, Vector2i p_
tiles.erase(p_atlas_coords);
tiles_ids.erase(p_atlas_coords);
- tiles_ids.append(new_atlas_coords);
+ tiles_ids.push_back(new_atlas_coords);
tiles_ids.sort();
}
tiles[new_atlas_coords].size_in_atlas = new_size;
@@ -4363,8 +4365,9 @@ int TileSetAtlasSource::create_alternative_tile(const Vector2i p_atlas_coords, i
tiles[p_atlas_coords].alternatives[new_alternative_id] = memnew(TileData);
tiles[p_atlas_coords].alternatives[new_alternative_id]->set_tile_set(tile_set);
tiles[p_atlas_coords].alternatives[new_alternative_id]->set_allow_transform(true);
+ tiles[p_atlas_coords].alternatives[new_alternative_id]->connect("changed", callable_mp((Resource *)this, &TileSetAtlasSource::emit_changed));
tiles[p_atlas_coords].alternatives[new_alternative_id]->notify_property_list_changed();
- tiles[p_atlas_coords].alternatives_ids.append(new_alternative_id);
+ tiles[p_atlas_coords].alternatives_ids.push_back(new_alternative_id);
tiles[p_atlas_coords].alternatives_ids.sort();
_compute_next_alternative_id(p_atlas_coords);
@@ -4394,7 +4397,7 @@ void TileSetAtlasSource::set_alternative_tile_id(const Vector2i p_atlas_coords,
ERR_FAIL_COND_MSG(tiles[p_atlas_coords].alternatives.has(p_new_id), vformat("TileSetAtlasSource has already an alternative with id %d at %s.", p_new_id, String(p_atlas_coords)));
tiles[p_atlas_coords].alternatives[p_new_id] = tiles[p_atlas_coords].alternatives[p_alternative_tile];
- tiles[p_atlas_coords].alternatives_ids.append(p_new_id);
+ tiles[p_atlas_coords].alternatives_ids.push_back(p_new_id);
tiles[p_atlas_coords].alternatives.erase(p_alternative_tile);
tiles[p_atlas_coords].alternatives_ids.erase(p_alternative_tile);
@@ -4682,7 +4685,7 @@ int TileSetScenesCollectionSource::create_scene_tile(Ref<PackedScene> p_packed_s
int new_scene_id = p_id_override >= 0 ? p_id_override : next_scene_id;
scenes[new_scene_id] = SceneData();
- scenes_ids.append(new_scene_id);
+ scenes_ids.push_back(new_scene_id);
scenes_ids.sort();
set_scene_tile_scene(new_scene_id, p_packed_scene);
_compute_next_alternative_id();
@@ -4699,7 +4702,7 @@ void TileSetScenesCollectionSource::set_scene_tile_id(int p_id, int p_new_id) {
scenes[p_new_id] = SceneData();
scenes[p_new_id] = scenes[p_id];
- scenes_ids.append(p_new_id);
+ scenes_ids.push_back(p_new_id);
scenes_ids.sort();
_compute_next_alternative_id();
diff --git a/scene/resources/tile_set.h b/scene/resources/tile_set.h
index 8f175e99a6..88bbbd157a 100644
--- a/scene/resources/tile_set.h
+++ b/scene/resources/tile_set.h
@@ -36,10 +36,10 @@
#include "core/templates/local_vector.h"
#include "core/templates/rb_set.h"
#include "scene/2d/light_occluder_2d.h"
-#include "scene/2d/navigation_region_2d.h"
#include "scene/main/canvas_item.h"
#include "scene/resources/concave_polygon_shape_2d.h"
#include "scene/resources/convex_polygon_shape_2d.h"
+#include "scene/resources/navigation_polygon.h"
#include "scene/resources/packed_scene.h"
#include "scene/resources/physics_material.h"
#include "scene/resources/shape_2d.h"
@@ -785,7 +785,7 @@ private:
bool flip_h = false;
bool flip_v = false;
bool transpose = false;
- Vector2i tex_offset = Vector2i();
+ Vector2i tex_offset;
Ref<Material> material = Ref<Material>();
Color modulate = Color(1.0, 1.0, 1.0, 1.0);
int z_index = 0;
diff --git a/scene/resources/visual_shader.cpp b/scene/resources/visual_shader.cpp
index b30ca3e721..6b8f8097a8 100644
--- a/scene/resources/visual_shader.cpp
+++ b/scene/resources/visual_shader.cpp
@@ -2066,10 +2066,9 @@ Error VisualShader::_write_node(Type type, StringBuilder *p_global_code, StringB
}
if (!node_code.is_empty()) {
- r_code += "\n";
+ r_code += "\n\n";
}
- r_code += "\n"; //
r_processed.insert(p_node);
return OK;
@@ -2366,71 +2365,62 @@ void VisualShader::_update_shader() const {
String global_compute_code;
if (shader_mode == Shader::MODE_PARTICLES) {
- bool has_start = !code_map[TYPE_START].is_empty();
bool has_start_custom = !code_map[TYPE_START_CUSTOM].is_empty();
bool has_process = !code_map[TYPE_PROCESS].is_empty();
bool has_process_custom = !code_map[TYPE_PROCESS_CUSTOM].is_empty();
bool has_collide = !code_map[TYPE_COLLIDE].is_empty();
shader_code += "void start() {\n";
- if (has_start || has_start_custom) {
- shader_code += " uint __seed = __hash(NUMBER + uint(1) + RANDOM_SEED);\n";
- shader_code += " vec3 __diff = TRANSFORM[3].xyz - EMISSION_TRANSFORM[3].xyz;\n";
- shader_code += " float __radians;\n";
- shader_code += " vec3 __vec3_buff1;\n";
- shader_code += " vec3 __vec3_buff2;\n";
- shader_code += " float __scalar_buff1;\n";
- shader_code += " float __scalar_buff2;\n";
- shader_code += " int __scalar_ibuff;\n";
- shader_code += " vec4 __vec4_buff;\n";
- shader_code += " vec3 __ndiff = normalize(__diff);\n\n";
- }
- if (has_start) {
- shader_code += " {\n";
- shader_code += code_map[TYPE_START].replace("\n ", "\n ");
- shader_code += " }\n";
- if (has_start_custom) {
- shader_code += " \n";
- }
- }
+ shader_code += " uint __seed = __hash(NUMBER + uint(1) + RANDOM_SEED);\n";
+ shader_code += "\n";
+ shader_code += " {\n";
+ shader_code += code_map[TYPE_START].replace("\n ", "\n ");
+ shader_code += " }\n";
if (has_start_custom) {
+ shader_code += " \n";
shader_code += " {\n";
shader_code += code_map[TYPE_START_CUSTOM].replace("\n ", "\n ");
shader_code += " }\n";
}
shader_code += "}\n\n";
- shader_code += "void process() {\n";
+
if (has_process || has_process_custom || has_collide) {
+ shader_code += "void process() {\n";
shader_code += " uint __seed = __hash(NUMBER + uint(1) + RANDOM_SEED);\n";
- shader_code += " vec3 __vec3_buff1;\n";
- shader_code += " vec3 __diff = TRANSFORM[3].xyz - EMISSION_TRANSFORM[3].xyz;\n";
- shader_code += " vec3 __ndiff = normalize(__diff);\n\n";
- }
- shader_code += " {\n";
- String tab = " ";
- if (has_collide) {
- shader_code += " if (COLLIDED) {\n\n";
- shader_code += code_map[TYPE_COLLIDE].replace("\n ", "\n ");
+ shader_code += "\n";
+ if (has_process || has_collide) {
+ shader_code += " {\n";
+ }
+ String tab = " ";
+ if (has_collide) {
+ shader_code += " if (COLLIDED) {\n\n";
+ shader_code += code_map[TYPE_COLLIDE].replace("\n ", "\n ");
+ if (has_process) {
+ shader_code += " } else {\n\n";
+ tab += " ";
+ }
+ }
if (has_process) {
- shader_code += " } else {\n\n";
- tab += " ";
+ shader_code += code_map[TYPE_PROCESS].replace("\n ", "\n " + tab);
+ }
+ if (has_collide) {
+ shader_code += " }\n";
+ }
+ if (has_process || has_collide) {
+ shader_code += " }\n";
}
- }
- if (has_process) {
- shader_code += code_map[TYPE_PROCESS].replace("\n ", "\n " + tab);
- }
- if (has_collide) {
- shader_code += " }\n";
- }
- shader_code += " }\n";
- if (has_process_custom) {
- shader_code += " {\n\n";
- shader_code += code_map[TYPE_PROCESS_CUSTOM].replace("\n ", "\n ");
- shader_code += " }\n";
- }
+ if (has_process_custom) {
+ if (has_process || has_collide) {
+ shader_code += " \n";
+ }
+ shader_code += " {\n";
+ shader_code += code_map[TYPE_PROCESS_CUSTOM].replace("\n ", "\n ");
+ shader_code += " }\n";
+ }
- shader_code += "}\n\n";
+ shader_code += "}\n\n";
+ }
global_compute_code += "float __rand_from_seed(inout uint seed) {\n";
global_compute_code += " int k;\n";
@@ -2658,6 +2648,7 @@ const VisualShaderNodeInput::Port VisualShaderNodeInput::ports[] = {
{ Shader::MODE_SPATIAL, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_VECTOR_3D, "node_position_world", "NODE_POSITION_WORLD" },
{ Shader::MODE_SPATIAL, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_VECTOR_3D, "camera_position_world", "CAMERA_POSITION_WORLD" },
{ Shader::MODE_SPATIAL, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_VECTOR_3D, "camera_direction_world", "CAMERA_DIRECTION_WORLD" },
+ { Shader::MODE_SPATIAL, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_SCALAR_INT, "camera_visible_layers", "CAMERA_VISIBLE_LAYERS" },
{ Shader::MODE_SPATIAL, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_VECTOR_3D, "node_position_view", "NODE_POSITION_VIEW" },
// Node3D, Fragment
@@ -2690,6 +2681,7 @@ const VisualShaderNodeInput::Port VisualShaderNodeInput::ports[] = {
{ Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_VECTOR_3D, "node_position_world", "NODE_POSITION_WORLD" },
{ Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_VECTOR_3D, "camera_position_world", "CAMERA_POSITION_WORLD" },
{ Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_VECTOR_3D, "camera_direction_world", "CAMERA_DIRECTION_WORLD" },
+ { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_SCALAR_INT, "camera_visible_layers", "CAMERA_VISIBLE_LAYERS" },
{ Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_VECTOR_3D, "node_position_view", "NODE_POSITION_VIEW" },
// Node3D, Light
diff --git a/scene/resources/visual_shader_nodes.cpp b/scene/resources/visual_shader_nodes.cpp
index 04637983b5..03abac1b3e 100644
--- a/scene/resources/visual_shader_nodes.cpp
+++ b/scene/resources/visual_shader_nodes.cpp
@@ -3108,9 +3108,9 @@ void VisualShaderNodeUVFunc::set_function(VisualShaderNodeUVFunc::Function p_fun
return;
}
if (p_func == FUNC_PANNING) {
- set_input_port_default_value(2, Vector2()); // offset
+ set_input_port_default_value(2, Vector2(), get_input_port_default_value(2)); // offset
} else { // FUNC_SCALING
- set_input_port_default_value(2, Vector2(0.5, 0.5)); // pivot
+ set_input_port_default_value(2, Vector2(0.5, 0.5), get_input_port_default_value(2)); // pivot
}
func = p_func;
emit_changed();
diff --git a/scene/resources/visual_shader_particle_nodes.cpp b/scene/resources/visual_shader_particle_nodes.cpp
index f125b05a26..d61a343688 100644
--- a/scene/resources/visual_shader_particle_nodes.cpp
+++ b/scene/resources/visual_shader_particle_nodes.cpp
@@ -374,13 +374,13 @@ String VisualShaderNodeParticleMeshEmitter::_generate_code(VisualShader::Type p_
if (is_output_port_connected(p_index)) {
switch (p_port_type) {
case PORT_TYPE_VECTOR_2D: {
- code += vformat(" %s = texelFetch(%s, ivec2(__scalar_ibuff, 0), 0).xy;\n", p_output_vars[p_index], make_unique_id(p_type, p_id, p_texture_name));
+ code += vformat(" %s = texelFetch(%s, ivec2(__scalar_ibuff, 0), 0).xy;\n", p_output_vars[p_index], make_unique_id(p_type, p_id, p_texture_name));
} break;
case PORT_TYPE_VECTOR_3D: {
if (mode_2d) {
- code += vformat(" %s = texelFetch(%s, ivec2(__scalar_ibuff, 0), 0).xy;\n", p_output_vars[p_index], make_unique_id(p_type, p_id, p_texture_name));
+ code += vformat(" %s = texelFetch(%s, ivec2(__scalar_ibuff, 0), 0).xy;\n", p_output_vars[p_index], make_unique_id(p_type, p_id, p_texture_name));
} else {
- code += vformat(" %s = texelFetch(%s, ivec2(__scalar_ibuff, 0), 0).xyz;\n", p_output_vars[p_index], make_unique_id(p_type, p_id, p_texture_name));
+ code += vformat(" %s = texelFetch(%s, ivec2(__scalar_ibuff, 0), 0).xyz;\n", p_output_vars[p_index], make_unique_id(p_type, p_id, p_texture_name));
}
} break;
default:
@@ -392,25 +392,27 @@ String VisualShaderNodeParticleMeshEmitter::_generate_code(VisualShader::Type p_
String VisualShaderNodeParticleMeshEmitter::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars, bool p_for_preview) const {
String code;
- code += " __scalar_ibuff = int(__rand_from_seed(__seed) * 65535.0) % " + itos(position_texture->get_width()) + ";\n";
+ code += " {\n";
+ code += " int __scalar_ibuff = int(__rand_from_seed(__seed) * 65535.0) % " + itos(position_texture->get_width()) + ";\n";
code += _generate_code(p_type, p_id, p_output_vars, 0, "mesh_vx", VisualShaderNode::PORT_TYPE_VECTOR_3D);
code += _generate_code(p_type, p_id, p_output_vars, 1, "mesh_nm", VisualShaderNode::PORT_TYPE_VECTOR_3D);
if (is_output_port_connected(2) || is_output_port_connected(3)) {
- code += vformat(" __vec4_buff = texelFetch(%s, ivec2(__scalar_ibuff, 0), 0);\n", make_unique_id(p_type, p_id, "mesh_col"));
+ code += vformat(" vec4 __vec4_buff = texelFetch(%s, ivec2(__scalar_ibuff, 0), 0);\n", make_unique_id(p_type, p_id, "mesh_col"));
if (is_output_port_connected(2)) {
- code += " " + p_output_vars[2] + " = __vec4_buff.rgb;\n";
+ code += " " + p_output_vars[2] + " = __vec4_buff.rgb;\n";
}
if (is_output_port_connected(3)) {
- code += " " + p_output_vars[3] + " = __vec4_buff.a;\n";
+ code += " " + p_output_vars[3] + " = __vec4_buff.a;\n";
}
}
code += _generate_code(p_type, p_id, p_output_vars, 4, "mesh_uv", VisualShaderNode::PORT_TYPE_VECTOR_2D);
code += _generate_code(p_type, p_id, p_output_vars, 5, "mesh_uv2", VisualShaderNode::PORT_TYPE_VECTOR_2D);
+ code += " }\n";
return code;
}
@@ -737,6 +739,8 @@ VisualShaderNodeParticleMeshEmitter::VisualShaderNodeParticleMeshEmitter() {
color_texture.instantiate();
uv_texture.instantiate();
uv2_texture.instantiate();
+
+ simple_decl = false;
}
// VisualShaderNodeParticleMultiplyByAxisAngle
@@ -879,22 +883,26 @@ bool VisualShaderNodeParticleConeVelocity::has_output_port_preview(int p_port) c
String VisualShaderNodeParticleConeVelocity::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars, bool p_for_preview) const {
String code;
- code += " __radians = radians(" + (p_input_vars[1].is_empty() ? (String)get_input_port_default_value(1) : p_input_vars[1]) + ");\n";
- code += " __scalar_buff1 = __rand_from_seed_m1_p1(__seed) * __radians;\n";
- code += " __scalar_buff2 = __rand_from_seed_m1_p1(__seed) * __radians;\n";
- code += " __vec3_buff1 = " + (p_input_vars[0].is_empty() ? "vec3" + (String)get_input_port_default_value(0) : p_input_vars[0]) + ";\n";
- code += " __scalar_buff1 += __vec3_buff1.z != 0.0 ? atan(__vec3_buff1.x, __vec3_buff1.z) : sign(__vec3_buff1.x) * (PI / 2.0);\n";
- code += " __scalar_buff2 += __vec3_buff1.z != 0.0 ? atan(__vec3_buff1.y, abs(__vec3_buff1.z)) : (__vec3_buff1.x != 0.0 ? atan(__vec3_buff1.y, abs(__vec3_buff1.x)) : sign(__vec3_buff1.y) * (PI / 2.0));\n";
- code += " __vec3_buff1 = vec3(sin(__scalar_buff1), 0.0, cos(__scalar_buff1));\n";
- code += " __vec3_buff2 = vec3(0.0, sin(__scalar_buff2), cos(__scalar_buff2));\n";
- code += " __vec3_buff2.z = __vec3_buff2.z / max(0.0001, sqrt(abs(__vec3_buff2.z)));\n";
- code += " " + p_output_vars[0] + " = normalize(vec3(__vec3_buff1.x * __vec3_buff2.z, __vec3_buff2.y, __vec3_buff1.z * __vec3_buff2.z));\n";
+ code += " {\n";
+ code += " float __radians = radians(" + (p_input_vars[1].is_empty() ? (String)get_input_port_default_value(1) : p_input_vars[1]) + ");\n";
+ code += " float __scalar_buff1 = __rand_from_seed_m1_p1(__seed) * __radians;\n";
+ code += " float __scalar_buff2 = __rand_from_seed_m1_p1(__seed) * __radians;\n";
+ code += " vec3 __vec3_buff1 = " + (p_input_vars[0].is_empty() ? "vec3" + (String)get_input_port_default_value(0) : p_input_vars[0]) + ";\n";
+ code += " __scalar_buff1 += __vec3_buff1.z != 0.0 ? atan(__vec3_buff1.x, __vec3_buff1.z) : sign(__vec3_buff1.x) * (PI / 2.0);\n";
+ code += " __scalar_buff2 += __vec3_buff1.z != 0.0 ? atan(__vec3_buff1.y, abs(__vec3_buff1.z)) : (__vec3_buff1.x != 0.0 ? atan(__vec3_buff1.y, abs(__vec3_buff1.x)) : sign(__vec3_buff1.y) * (PI / 2.0));\n";
+ code += " __vec3_buff1 = vec3(sin(__scalar_buff1), 0.0, cos(__scalar_buff1));\n";
+ code += " vec3 __vec3_buff2 = vec3(0.0, sin(__scalar_buff2), cos(__scalar_buff2));\n";
+ code += " __vec3_buff2.z = __vec3_buff2.z / max(0.0001, sqrt(abs(__vec3_buff2.z)));\n";
+ code += " " + p_output_vars[0] + " = normalize(vec3(__vec3_buff1.x * __vec3_buff2.z, __vec3_buff2.y, __vec3_buff1.z * __vec3_buff2.z));\n";
+ code += " }\n";
return code;
}
VisualShaderNodeParticleConeVelocity::VisualShaderNodeParticleConeVelocity() {
set_input_port_default_value(0, Vector3(1, 0, 0));
set_input_port_default_value(1, 45.0);
+
+ simple_decl = false;
}
// VisualShaderNodeParticleRandomness
@@ -1086,21 +1094,26 @@ String VisualShaderNodeParticleAccelerator::get_input_port_name(int p_port) cons
String VisualShaderNodeParticleAccelerator::generate_code(Shader::Mode p_mode, VisualShader::Type p_type, int p_id, const String *p_input_vars, const String *p_output_vars, bool p_for_preview) const {
String code;
+ code += " {\n";
switch (mode) {
case MODE_LINEAR:
- code += " " + p_output_vars[0] + " = length(VELOCITY) > 0.0 ? " + "normalize(VELOCITY) * " + (p_input_vars[0].is_empty() ? "vec3" + (String)get_input_port_default_value(0) : p_input_vars[0]) + " * mix(1.0, __rand_from_seed(__seed), " + (p_input_vars[1].is_empty() ? (String)get_input_port_default_value(1) : p_input_vars[1]) + ") : vec3(0.0);\n";
+ code += " " + p_output_vars[0] + " = length(VELOCITY) > 0.0 ? " + "normalize(VELOCITY) * " + (p_input_vars[0].is_empty() ? "vec3" + (String)get_input_port_default_value(0) : p_input_vars[0]) + " * mix(1.0, __rand_from_seed(__seed), " + (p_input_vars[1].is_empty() ? (String)get_input_port_default_value(1) : p_input_vars[1]) + ") : vec3(0.0);\n";
break;
case MODE_RADIAL:
- code += " " + p_output_vars[0] + " = length(__diff) > 0.0 ? __ndiff * " + (p_input_vars[0].is_empty() ? "vec3" + (String)get_input_port_default_value(0) : p_input_vars[0]) + " * mix(1.0, __rand_from_seed(__seed), " + (p_input_vars[1].is_empty() ? (String)get_input_port_default_value(1) : p_input_vars[1]) + ") : vec3(0.0);\n";
+ code += " vec3 __diff = TRANSFORM[3].xyz - EMISSION_TRANSFORM[3].xyz;\n";
+ code += " vec3 __ndiff = normalize(__diff);\n\n";
+ code += " " + p_output_vars[0] + " = length(__diff) > 0.0 ? __ndiff * " + (p_input_vars[0].is_empty() ? "vec3" + (String)get_input_port_default_value(0) : p_input_vars[0]) + " * mix(1.0, __rand_from_seed(__seed), " + (p_input_vars[1].is_empty() ? (String)get_input_port_default_value(1) : p_input_vars[1]) + ") : vec3(0.0);\n";
break;
case MODE_TANGENTIAL:
- code += " __vec3_buff1 = cross(__ndiff, normalize(" + (p_input_vars[2].is_empty() ? "vec3" + (String)get_input_port_default_value(2) : p_input_vars[2]) + "));\n";
- code += " " + p_output_vars[0] + " = length(__vec3_buff1) > 0.0 ? normalize(__vec3_buff1) * (" + (p_input_vars[0].is_empty() ? "vec3" + (String)get_input_port_default_value(0) : p_input_vars[0]) + " * mix(1.0, __rand_from_seed(__seed), " + (p_input_vars[1].is_empty() ? (String)get_input_port_default_value(1) : p_input_vars[1]) + ")) : vec3(0.0);\n";
+ code += " vec3 __diff = TRANSFORM[3].xyz - EMISSION_TRANSFORM[3].xyz;\n";
+ code += " vec3 __ndiff = normalize(__diff);\n\n";
+ code += " vec3 __vec3_buff1 = cross(__ndiff, normalize(" + (p_input_vars[2].is_empty() ? "vec3" + (String)get_input_port_default_value(2) : p_input_vars[2]) + "));\n";
+ code += " " + p_output_vars[0] + " = length(__vec3_buff1) > 0.0 ? normalize(__vec3_buff1) * (" + (p_input_vars[0].is_empty() ? "vec3" + (String)get_input_port_default_value(0) : p_input_vars[0]) + " * mix(1.0, __rand_from_seed(__seed), " + (p_input_vars[1].is_empty() ? (String)get_input_port_default_value(1) : p_input_vars[1]) + ")) : vec3(0.0);\n";
break;
default:
break;
}
-
+ code += " }\n";
return code;
}
@@ -1125,6 +1138,8 @@ VisualShaderNodeParticleAccelerator::VisualShaderNodeParticleAccelerator() {
set_input_port_default_value(0, Vector3(1, 1, 1));
set_input_port_default_value(1, 0.0);
set_input_port_default_value(2, Vector3(0, -9.8, 0));
+
+ simple_decl = false;
}
// VisualShaderNodeParticleOutput
diff --git a/scene/scene_string_names.cpp b/scene/scene_string_names.cpp
index a15c03d675..bc7918c662 100644
--- a/scene/scene_string_names.cpp
+++ b/scene/scene_string_names.cpp
@@ -206,8 +206,6 @@ SceneStringNames::SceneStringNames() {
theme_changed = StaticCString::create("theme_changed");
parameters_base_path = "parameters/";
- tracks_changed = "tracks_changed";
-
shader_overrides_group = StaticCString::create("_shader_overrides_group_");
shader_overrides_group_active = StaticCString::create("_shader_overrides_group_active_");
diff --git a/scene/scene_string_names.h b/scene/scene_string_names.h
index 5589ab327f..7ff866cacd 100644
--- a/scene/scene_string_names.h
+++ b/scene/scene_string_names.h
@@ -209,8 +209,6 @@ public:
StringName parameters_base_path;
- StringName tracks_changed;
-
StringName _window_group;
StringName _window_input;
StringName _window_unhandled_input;
diff --git a/scene/theme/theme_db.cpp b/scene/theme/theme_db.cpp
index 1025d40b05..ae64313741 100644
--- a/scene/theme/theme_db.cpp
+++ b/scene/theme/theme_db.cpp
@@ -49,7 +49,7 @@ void ThemeDB::initialize_theme() {
ProjectSettings::get_singleton()->set_custom_property_info("gui/theme/custom", PropertyInfo(Variant::STRING, "gui/theme/custom", PROPERTY_HINT_FILE, "*.tres,*.res,*.theme", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED));
String font_path = GLOBAL_DEF_RST("gui/theme/custom_font", "");
- ProjectSettings::get_singleton()->set_custom_property_info("gui/theme/custom_font", PropertyInfo(Variant::STRING, "gui/theme/custom_font", PROPERTY_HINT_FILE, "*.tres,*.res", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED));
+ ProjectSettings::get_singleton()->set_custom_property_info("gui/theme/custom_font", PropertyInfo(Variant::STRING, "gui/theme/custom_font", PROPERTY_HINT_FILE, "*.tres,*.res,*.otf,*.ttf,*.woff,*.woff2,*.fnt,*.font,*.pfb,*.pfm", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED));
TextServer::FontAntialiasing font_antialiasing = (TextServer::FontAntialiasing)(int)GLOBAL_DEF_RST("gui/theme/default_font_antialiasing", 1);
ProjectSettings::get_singleton()->set_custom_property_info("gui/theme/default_font_antialiasing", PropertyInfo(Variant::INT, "gui/theme/default_font_antialiasing", PROPERTY_HINT_ENUM, "None,Grayscale,LCD Subpixel", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED));
@@ -70,7 +70,9 @@ void ThemeDB::initialize_theme() {
Ref<Font> font;
if (!font_path.is_empty()) {
font = ResourceLoader::load(font_path);
- if (!font.is_valid()) {
+ if (font.is_valid()) {
+ set_fallback_font(font);
+ } else {
ERR_PRINT("Error loading custom font '" + font_path + "'");
}
}
@@ -84,9 +86,6 @@ void ThemeDB::initialize_theme() {
Ref<Theme> theme = ResourceLoader::load(theme_path);
if (theme.is_valid()) {
set_project_theme(theme);
- if (font.is_valid()) {
- set_fallback_font(font);
- }
} else {
ERR_PRINT("Error loading custom theme '" + theme_path + "'");
}
diff --git a/scene/theme/theme_owner.cpp b/scene/theme/theme_owner.cpp
index e89aa1b28d..44e0c5d0c8 100644
--- a/scene/theme/theme_owner.cpp
+++ b/scene/theme/theme_owner.cpp
@@ -205,16 +205,7 @@ Variant ThemeOwner::get_theme_item_in_types(Theme::DataType p_data_type, const S
while (owner_node) {
// For each theme resource check the theme types provided and see if p_name exists with any of them.
for (const StringName &E : p_theme_types) {
- Ref<Theme> owner_theme;
-
- Control *owner_c = Object::cast_to<Control>(owner_node);
- if (owner_c) {
- owner_theme = owner_c->get_theme();
- }
- Window *owner_w = Object::cast_to<Window>(owner_node);
- if (owner_w) {
- owner_theme = owner_w->get_theme();
- }
+ Ref<Theme> owner_theme = _get_owner_node_theme(owner_node);
if (owner_theme.is_valid() && owner_theme->has_theme_item(p_data_type, p_name, E)) {
return owner_theme->get_theme_item(p_data_type, p_name, E);
@@ -254,16 +245,7 @@ bool ThemeOwner::has_theme_item_in_types(Theme::DataType p_data_type, const Stri
while (owner_node) {
// For each theme resource check the theme types provided and see if p_name exists with any of them.
for (const StringName &E : p_theme_types) {
- Ref<Theme> owner_theme;
-
- Control *owner_c = Object::cast_to<Control>(owner_node);
- if (owner_c) {
- owner_theme = owner_c->get_theme();
- }
- Window *owner_w = Object::cast_to<Window>(owner_node);
- if (owner_w) {
- owner_theme = owner_w->get_theme();
- }
+ Ref<Theme> owner_theme = _get_owner_node_theme(owner_node);
if (owner_theme.is_valid() && owner_theme->has_theme_item(p_data_type, p_name, E)) {
return true;
@@ -299,16 +281,7 @@ float ThemeOwner::get_theme_default_base_scale() {
Node *owner_node = get_owner_node();
while (owner_node) {
- Ref<Theme> owner_theme;
-
- Control *owner_c = Object::cast_to<Control>(owner_node);
- if (owner_c) {
- owner_theme = owner_c->get_theme();
- }
- Window *owner_w = Object::cast_to<Window>(owner_node);
- if (owner_w) {
- owner_theme = owner_w->get_theme();
- }
+ Ref<Theme> owner_theme = _get_owner_node_theme(owner_node);
if (owner_theme.is_valid() && owner_theme->has_default_base_scale()) {
return owner_theme->get_default_base_scale();
@@ -338,16 +311,7 @@ Ref<Font> ThemeOwner::get_theme_default_font() {
Node *owner_node = get_owner_node();
while (owner_node) {
- Ref<Theme> owner_theme;
-
- Control *owner_c = Object::cast_to<Control>(owner_node);
- if (owner_c) {
- owner_theme = owner_c->get_theme();
- }
- Window *owner_w = Object::cast_to<Window>(owner_node);
- if (owner_w) {
- owner_theme = owner_w->get_theme();
- }
+ Ref<Theme> owner_theme = _get_owner_node_theme(owner_node);
if (owner_theme.is_valid() && owner_theme->has_default_font()) {
return owner_theme->get_default_font();
@@ -377,16 +341,7 @@ int ThemeOwner::get_theme_default_font_size() {
Node *owner_node = get_owner_node();
while (owner_node) {
- Ref<Theme> owner_theme;
-
- Control *owner_c = Object::cast_to<Control>(owner_node);
- if (owner_c) {
- owner_theme = owner_c->get_theme();
- }
- Window *owner_w = Object::cast_to<Window>(owner_node);
- if (owner_w) {
- owner_theme = owner_w->get_theme();
- }
+ Ref<Theme> owner_theme = _get_owner_node_theme(owner_node);
if (owner_theme.is_valid() && owner_theme->has_default_font_size()) {
return owner_theme->get_default_font_size();
@@ -408,3 +363,17 @@ int ThemeOwner::get_theme_default_font_size() {
}
return ThemeDB::get_singleton()->get_fallback_font_size();
}
+
+Ref<Theme> ThemeOwner::_get_owner_node_theme(Node *p_owner_node) const {
+ const Control *owner_c = Object::cast_to<Control>(p_owner_node);
+ if (owner_c) {
+ return owner_c->get_theme();
+ }
+
+ const Window *owner_w = Object::cast_to<Window>(p_owner_node);
+ if (owner_w) {
+ return owner_w->get_theme();
+ }
+
+ return Ref<Theme>();
+}
diff --git a/scene/theme/theme_owner.h b/scene/theme/theme_owner.h
index 59b72c1627..60d60f525c 100644
--- a/scene/theme/theme_owner.h
+++ b/scene/theme/theme_owner.h
@@ -43,6 +43,7 @@ class ThemeOwner : public Object {
Window *owner_window = nullptr;
Node *_get_next_owner_node(Node *p_from_node) const;
+ Ref<Theme> _get_owner_node_theme(Node *p_owner_node) const;
public:
// Theme owner node.