summaryrefslogtreecommitdiff
path: root/scene
diff options
context:
space:
mode:
Diffstat (limited to 'scene')
-rw-r--r--scene/2d/animated_sprite_2d.cpp308
-rw-r--r--scene/2d/animated_sprite_2d.h32
-rw-r--r--scene/2d/area_2d.cpp22
-rw-r--r--scene/2d/area_2d.h6
-rw-r--r--scene/2d/audio_listener_2d.cpp4
-rw-r--r--scene/2d/audio_listener_2d.h2
-rw-r--r--scene/2d/audio_stream_player_2d.cpp24
-rw-r--r--scene/2d/audio_stream_player_2d.h2
-rw-r--r--scene/2d/back_buffer_copy.cpp1
-rw-r--r--scene/2d/camera_2d.cpp83
-rw-r--r--scene/2d/camera_2d.h6
-rw-r--r--scene/2d/collision_object_2d.cpp21
-rw-r--r--scene/2d/collision_object_2d.h7
-rw-r--r--scene/2d/collision_polygon_2d.cpp16
-rw-r--r--scene/2d/collision_shape_2d.cpp1
-rw-r--r--scene/2d/cpu_particles_2d.cpp4
-rw-r--r--scene/2d/gpu_particles_2d.cpp2
-rw-r--r--scene/2d/joint_2d.cpp1
-rw-r--r--scene/2d/light_2d.cpp2
-rw-r--r--scene/2d/marker_2d.cpp1
-rw-r--r--scene/2d/mesh_instance_2d.cpp13
-rw-r--r--scene/2d/mesh_instance_2d.h4
-rw-r--r--scene/2d/multimesh_instance_2d.cpp13
-rw-r--r--scene/2d/multimesh_instance_2d.h4
-rw-r--r--scene/2d/navigation_agent_2d.cpp349
-rw-r--r--scene/2d/navigation_agent_2d.h60
-rw-r--r--scene/2d/navigation_link_2d.cpp79
-rw-r--r--scene/2d/navigation_link_2d.h17
-rw-r--r--scene/2d/navigation_obstacle_2d.cpp19
-rw-r--r--scene/2d/navigation_region_2d.cpp17
-rw-r--r--scene/2d/node_2d.cpp8
-rw-r--r--scene/2d/node_2d.h1
-rw-r--r--scene/2d/path_2d.cpp25
-rw-r--r--scene/2d/path_2d.h5
-rw-r--r--scene/2d/physics_body_2d.cpp4
-rw-r--r--scene/2d/ray_cast_2d.cpp1
-rw-r--r--scene/2d/remote_transform_2d.cpp1
-rw-r--r--scene/2d/shape_cast_2d.cpp4
-rw-r--r--scene/2d/shape_cast_2d.h2
-rw-r--r--scene/2d/skeleton_2d.cpp4
-rw-r--r--scene/2d/tile_map.cpp151
-rw-r--r--scene/2d/tile_map.h5
-rw-r--r--scene/2d/visible_on_screen_notifier_2d.cpp3
-rw-r--r--scene/3d/area_3d.cpp20
-rw-r--r--scene/3d/area_3d.h6
-rw-r--r--scene/3d/audio_stream_player_3d.cpp43
-rw-r--r--scene/3d/audio_stream_player_3d.h2
-rw-r--r--scene/3d/bone_attachment_3d.cpp57
-rw-r--r--scene/3d/bone_attachment_3d.h8
-rw-r--r--scene/3d/camera_3d.cpp4
-rw-r--r--scene/3d/collision_object_3d.cpp38
-rw-r--r--scene/3d/collision_object_3d.h7
-rw-r--r--scene/3d/collision_polygon_3d.cpp12
-rw-r--r--scene/3d/collision_shape_3d.cpp12
-rw-r--r--scene/3d/cpu_particles_3d.cpp4
-rw-r--r--scene/3d/decal.cpp42
-rw-r--r--scene/3d/decal.h10
-rw-r--r--scene/3d/fog_volume.cpp44
-rw-r--r--scene/3d/fog_volume.h10
-rw-r--r--scene/3d/gpu_particles_collision_3d.cpp184
-rw-r--r--scene/3d/gpu_particles_collision_3d.h50
-rw-r--r--scene/3d/label_3d.cpp65
-rw-r--r--scene/3d/label_3d.h18
-rw-r--r--scene/3d/light_3d.cpp13
-rw-r--r--scene/3d/lightmap_gi.cpp31
-rw-r--r--scene/3d/lightmap_gi.h2
-rw-r--r--scene/3d/navigation_agent_3d.cpp363
-rw-r--r--scene/3d/navigation_agent_3d.h53
-rw-r--r--scene/3d/navigation_link_3d.cpp106
-rw-r--r--scene/3d/navigation_link_3d.h17
-rw-r--r--scene/3d/navigation_obstacle_3d.cpp19
-rw-r--r--scene/3d/navigation_region_3d.cpp26
-rw-r--r--scene/3d/node_3d.cpp8
-rw-r--r--scene/3d/node_3d.h1
-rw-r--r--scene/3d/occluder_instance_3d.cpp5
-rw-r--r--scene/3d/physics_body_3d.cpp22
-rw-r--r--scene/3d/reflection_probe.cpp56
-rw-r--r--scene/3d/reflection_probe.h12
-rw-r--r--scene/3d/shape_cast_3d.cpp19
-rw-r--r--scene/3d/shape_cast_3d.h1
-rw-r--r--scene/3d/skeleton_3d.cpp263
-rw-r--r--scene/3d/skeleton_3d.h55
-rw-r--r--scene/3d/skeleton_ik_3d.cpp23
-rw-r--r--scene/3d/soft_body_3d.cpp15
-rw-r--r--scene/3d/sprite_3d.cpp394
-rw-r--r--scene/3d/sprite_3d.h51
-rw-r--r--scene/3d/visible_on_screen_notifier_3d.cpp2
-rw-r--r--scene/3d/visual_instance_3d.cpp12
-rw-r--r--scene/3d/visual_instance_3d.h2
-rw-r--r--scene/3d/voxel_gi.cpp48
-rw-r--r--scene/3d/voxel_gi.h10
-rw-r--r--scene/3d/xr_nodes.cpp37
-rw-r--r--scene/3d/xr_nodes.h9
-rw-r--r--scene/animation/animation_blend_space_1d.cpp200
-rw-r--r--scene/animation/animation_blend_space_1d.h24
-rw-r--r--scene/animation/animation_blend_space_2d.cpp26
-rw-r--r--scene/animation/animation_blend_space_2d.h7
-rw-r--r--scene/animation/animation_blend_tree.cpp382
-rw-r--r--scene/animation/animation_blend_tree.h74
-rw-r--r--scene/animation/animation_node_state_machine.cpp204
-rw-r--r--scene/animation/animation_node_state_machine.h36
-rw-r--r--scene/animation/animation_player.cpp439
-rw-r--r--scene/animation/animation_player.h38
-rw-r--r--scene/animation/animation_tree.cpp601
-rw-r--r--scene/animation/animation_tree.h70
-rw-r--r--scene/animation/root_motion_view.cpp10
-rw-r--r--scene/animation/tween.cpp52
-rw-r--r--scene/animation/tween.h5
-rw-r--r--scene/audio/audio_stream_player.cpp11
-rw-r--r--scene/audio/audio_stream_player.h1
-rw-r--r--scene/gui/base_button.cpp88
-rw-r--r--scene/gui/base_button.h19
-rw-r--r--scene/gui/box_container.cpp4
-rw-r--r--scene/gui/button.cpp8
-rw-r--r--scene/gui/code_edit.cpp66
-rw-r--r--scene/gui/code_edit.h1
-rw-r--r--scene/gui/color_picker.cpp94
-rw-r--r--scene/gui/color_picker.h8
-rw-r--r--scene/gui/container.cpp12
-rw-r--r--scene/gui/control.cpp210
-rw-r--r--scene/gui/control.h40
-rw-r--r--scene/gui/dialogs.cpp10
-rw-r--r--scene/gui/flow_container.cpp12
-rw-r--r--scene/gui/graph_edit.cpp52
-rw-r--r--scene/gui/graph_edit.h5
-rw-r--r--scene/gui/graph_node.cpp8
-rw-r--r--scene/gui/grid_container.cpp4
-rw-r--r--scene/gui/item_list.cpp6
-rw-r--r--scene/gui/item_list.h1
-rw-r--r--scene/gui/label.cpp11
-rw-r--r--scene/gui/label.h2
-rw-r--r--scene/gui/line_edit.cpp267
-rw-r--r--scene/gui/line_edit.h6
-rw-r--r--scene/gui/menu_bar.cpp29
-rw-r--r--scene/gui/menu_bar.h1
-rw-r--r--scene/gui/option_button.cpp12
-rw-r--r--scene/gui/option_button.h2
-rw-r--r--scene/gui/popup.cpp6
-rw-r--r--scene/gui/popup_menu.cpp21
-rw-r--r--scene/gui/popup_menu.h4
-rw-r--r--scene/gui/rich_text_label.cpp141
-rw-r--r--scene/gui/rich_text_label.h20
-rw-r--r--scene/gui/scroll_bar.cpp6
-rw-r--r--scene/gui/scroll_container.cpp4
-rw-r--r--scene/gui/separator.cpp2
-rw-r--r--scene/gui/slider.cpp6
-rw-r--r--scene/gui/spin_box.cpp4
-rw-r--r--scene/gui/split_container.cpp2
-rw-r--r--scene/gui/subviewport_container.cpp45
-rw-r--r--scene/gui/subviewport_container.h3
-rw-r--r--scene/gui/tab_bar.cpp1
-rw-r--r--scene/gui/tab_container.cpp21
-rw-r--r--scene/gui/tab_container.h2
-rw-r--r--scene/gui/text_edit.cpp243
-rw-r--r--scene/gui/text_edit.h7
-rw-r--r--scene/gui/texture_rect.cpp64
-rw-r--r--scene/gui/texture_rect.h19
-rw-r--r--scene/gui/tree.cpp124
-rw-r--r--scene/gui/tree.h22
-rw-r--r--scene/gui/video_stream_player.cpp7
-rw-r--r--scene/gui/video_stream_player.h1
-rw-r--r--scene/gui/view_panner.cpp86
-rw-r--r--scene/gui/view_panner.h16
-rw-r--r--scene/main/canvas_item.cpp183
-rw-r--r--scene/main/canvas_item.h27
-rw-r--r--scene/main/http_request.cpp21
-rw-r--r--scene/main/http_request.h8
-rw-r--r--scene/main/multiplayer_api.cpp18
-rw-r--r--scene/main/multiplayer_api.h8
-rw-r--r--scene/main/multiplayer_peer.cpp2
-rw-r--r--scene/main/node.cpp61
-rw-r--r--scene/main/node.h5
-rw-r--r--scene/main/scene_tree.cpp67
-rw-r--r--scene/main/scene_tree.h1
-rw-r--r--scene/main/viewport.cpp322
-rw-r--r--scene/main/viewport.h33
-rw-r--r--scene/main/window.cpp272
-rw-r--r--scene/main/window.h32
-rw-r--r--scene/register_scene_types.cpp27
-rw-r--r--scene/resources/animation.cpp85
-rw-r--r--scene/resources/animation.h3
-rw-r--r--scene/resources/audio_stream_polyphonic.cpp274
-rw-r--r--scene/resources/audio_stream_polyphonic.h (renamed from scene/resources/skeleton_modification_stack_3d.h)114
-rw-r--r--scene/resources/bone_map.cpp1
-rw-r--r--scene/resources/camera_attributes.cpp4
-rw-r--r--scene/resources/capsule_shape_2d.cpp2
-rw-r--r--scene/resources/circle_shape_2d.cpp1
-rw-r--r--scene/resources/convex_polygon_shape_2d.cpp9
-rw-r--r--scene/resources/default_theme/default_theme.cpp24
-rw-r--r--scene/resources/environment.cpp12
-rw-r--r--scene/resources/fog_material.cpp2
-rw-r--r--scene/resources/font.cpp70
-rw-r--r--scene/resources/font.h8
-rw-r--r--scene/resources/immediate_mesh.cpp39
-rw-r--r--scene/resources/immediate_mesh.h2
-rw-r--r--scene/resources/importer_mesh.cpp39
-rw-r--r--scene/resources/material.cpp139
-rw-r--r--scene/resources/material.h8
-rw-r--r--scene/resources/mesh.cpp91
-rw-r--r--scene/resources/mesh.h14
-rw-r--r--scene/resources/mesh_library.cpp3
-rw-r--r--scene/resources/navigation_mesh.cpp8
-rw-r--r--scene/resources/packed_scene.cpp42
-rw-r--r--scene/resources/packed_scene.h2
-rw-r--r--scene/resources/particle_process_material.cpp4
-rw-r--r--scene/resources/polygon_path_finder.cpp4
-rw-r--r--scene/resources/primitive_meshes.cpp6
-rw-r--r--scene/resources/primitive_meshes.h4
-rw-r--r--scene/resources/rectangle_shape_2d.cpp6
-rw-r--r--scene/resources/resource_format_text.cpp197
-rw-r--r--scene/resources/resource_format_text.h7
-rw-r--r--scene/resources/shader.cpp39
-rw-r--r--scene/resources/shader.h52
-rw-r--r--scene/resources/shader_include.cpp12
-rw-r--r--scene/resources/shader_include.h3
-rw-r--r--scene/resources/skeleton_modification_2d_stackholder.cpp2
-rw-r--r--scene/resources/skeleton_modification_3d.cpp151
-rw-r--r--scene/resources/skeleton_modification_3d.h79
-rw-r--r--scene/resources/skeleton_modification_3d_ccdik.cpp474
-rw-r--r--scene/resources/skeleton_modification_3d_ccdik.h114
-rw-r--r--scene/resources/skeleton_modification_3d_fabrik.cpp628
-rw-r--r--scene/resources/skeleton_modification_3d_fabrik.h124
-rw-r--r--scene/resources/skeleton_modification_3d_jiggle.cpp582
-rw-r--r--scene/resources/skeleton_modification_3d_jiggle.h138
-rw-r--r--scene/resources/skeleton_modification_3d_lookat.cpp267
-rw-r--r--scene/resources/skeleton_modification_3d_lookat.h89
-rw-r--r--scene/resources/skeleton_modification_3d_stackholder.cpp104
-rw-r--r--scene/resources/skeleton_modification_3d_stackholder.h59
-rw-r--r--scene/resources/skeleton_modification_3d_twoboneik.cpp617
-rw-r--r--scene/resources/skeleton_modification_3d_twoboneik.h118
-rw-r--r--scene/resources/skeleton_modification_stack_2d.cpp2
-rw-r--r--scene/resources/skeleton_modification_stack_3d.cpp224
-rw-r--r--scene/resources/sprite_frames.cpp6
-rw-r--r--scene/resources/sprite_frames.h8
-rw-r--r--scene/resources/style_box.cpp208
-rw-r--r--scene/resources/style_box.h59
-rw-r--r--scene/resources/surface_tool.cpp77
-rw-r--r--scene/resources/surface_tool.h24
-rw-r--r--scene/resources/text_file.cpp5
-rw-r--r--scene/resources/text_paragraph.cpp38
-rw-r--r--scene/resources/texture.cpp85
-rw-r--r--scene/resources/texture.h19
-rw-r--r--scene/resources/tile_set.cpp162
-rw-r--r--scene/resources/tile_set.h11
-rw-r--r--scene/resources/video_stream.cpp198
-rw-r--r--scene/resources/video_stream.h76
-rw-r--r--scene/resources/visual_shader.cpp149
-rw-r--r--scene/resources/visual_shader.h22
-rw-r--r--scene/resources/visual_shader_nodes.cpp966
-rw-r--r--scene/resources/visual_shader_nodes.h196
-rw-r--r--scene/resources/visual_shader_particle_nodes.cpp90
-rw-r--r--scene/resources/visual_shader_particle_nodes.h3
-rw-r--r--scene/resources/world_2d.cpp42
-rw-r--r--scene/resources/world_2d.h4
-rw-r--r--scene/resources/world_3d.cpp43
-rw-r--r--scene/resources/world_3d.h4
-rw-r--r--scene/resources/world_boundary_shape_2d.cpp7
-rw-r--r--scene/theme/theme_db.cpp21
258 files changed, 8585 insertions, 7807 deletions
diff --git a/scene/2d/animated_sprite_2d.cpp b/scene/2d/animated_sprite_2d.cpp
index a4a965aa41..8f7006caca 100644
--- a/scene/2d/animated_sprite_2d.cpp
+++ b/scene/2d/animated_sprite_2d.cpp
@@ -117,7 +117,6 @@ void AnimatedSprite2D::_validate_property(PropertyInfo &p_property) const {
}
if (p_property.name == "animation") {
- p_property.hint = PROPERTY_HINT_ENUM;
List<StringName> names;
frames->get_animation_list(&names);
names.sort_custom<StringName::AlphCompare>();
@@ -167,6 +166,12 @@ void AnimatedSprite2D::_validate_property(PropertyInfo &p_property) const {
void AnimatedSprite2D::_notification(int p_what) {
switch (p_what) {
+ case NOTIFICATION_READY: {
+ if (!Engine::get_singleton()->is_editor_hint() && !frames.is_null() && frames->has_animation(autoplay)) {
+ play(autoplay);
+ }
+ } break;
+
case NOTIFICATION_INTERNAL_PROCESS: {
if (frames.is_null() || !frames->has_animation(animation)) {
return;
@@ -176,7 +181,8 @@ void AnimatedSprite2D::_notification(int p_what) {
int i = 0;
while (remaining) {
// Animation speed may be changed by animation_finished or frame_changed signals.
- double speed = frames->get_animation_speed(animation) * Math::abs(speed_scale);
+ double speed = frames->get_animation_speed(animation) * speed_scale * custom_speed_scale * frame_speed_scale;
+ double abs_speed = Math::abs(speed);
if (speed == 0) {
return; // Do nothing.
@@ -185,53 +191,57 @@ void AnimatedSprite2D::_notification(int p_what) {
// Frame count may be changed by animation_finished or frame_changed signals.
int fc = frames->get_frame_count(animation);
- if (timeout <= 0) {
- int last_frame = fc - 1;
- if (!playing_backwards) {
- // Forward.
+ int last_frame = fc - 1;
+ if (!signbit(speed)) {
+ // Forwards.
+ if (frame_progress >= 1.0) {
if (frame >= last_frame) {
if (frames->get_animation_loop(animation)) {
frame = 0;
- emit_signal(SceneStringNames::get_singleton()->animation_finished);
+ emit_signal("animation_looped");
} else {
frame = last_frame;
- if (!is_over) {
- is_over = true;
- emit_signal(SceneStringNames::get_singleton()->animation_finished);
- }
+ pause();
+ emit_signal(SceneStringNames::get_singleton()->animation_finished);
+ return;
}
} else {
frame++;
}
- } else {
- // Reversed.
+ _calc_frame_speed_scale();
+ frame_progress = 0.0;
+ queue_redraw();
+ emit_signal(SceneStringNames::get_singleton()->frame_changed);
+ }
+ double to_process = MIN((1.0 - frame_progress) / abs_speed, remaining);
+ frame_progress += to_process * abs_speed;
+ remaining -= to_process;
+ } else {
+ // Backwards.
+ if (frame_progress <= 0) {
if (frame <= 0) {
if (frames->get_animation_loop(animation)) {
frame = last_frame;
- emit_signal(SceneStringNames::get_singleton()->animation_finished);
+ emit_signal("animation_looped");
} else {
frame = 0;
- if (!is_over) {
- is_over = true;
- emit_signal(SceneStringNames::get_singleton()->animation_finished);
- }
+ pause();
+ emit_signal(SceneStringNames::get_singleton()->animation_finished);
+ return;
}
} else {
frame--;
}
+ _calc_frame_speed_scale();
+ frame_progress = 1.0;
+ queue_redraw();
+ emit_signal(SceneStringNames::get_singleton()->frame_changed);
}
-
- timeout = _get_frame_duration();
-
- queue_redraw();
-
- emit_signal(SceneStringNames::get_singleton()->frame_changed);
+ double to_process = MIN(frame_progress / abs_speed, remaining);
+ frame_progress -= to_process * abs_speed;
+ remaining -= to_process;
}
- double to_process = MIN(timeout / speed, remaining);
- timeout -= to_process * speed;
- remaining -= to_process;
-
i++;
if (i > fc) {
return; // Prevents freezing if to_process is each time much less than remaining.
@@ -275,25 +285,37 @@ void AnimatedSprite2D::_notification(int p_what) {
}
void AnimatedSprite2D::set_sprite_frames(const Ref<SpriteFrames> &p_frames) {
+ if (frames == p_frames) {
+ return;
+ }
+
if (frames.is_valid()) {
frames->disconnect(SceneStringNames::get_singleton()->changed, callable_mp(this, &AnimatedSprite2D::_res_changed));
}
-
+ stop();
frames = p_frames;
if (frames.is_valid()) {
frames->connect(SceneStringNames::get_singleton()->changed, callable_mp(this, &AnimatedSprite2D::_res_changed));
- }
- if (frames.is_null()) {
- frame = 0;
- } else {
- set_frame(frame);
+ List<StringName> al;
+ frames->get_animation_list(&al);
+ if (al.size() == 0) {
+ set_animation(StringName());
+ set_autoplay(String());
+ } else {
+ if (!frames->has_animation(animation)) {
+ set_animation(al[0]);
+ }
+ if (!frames->has_animation(autoplay)) {
+ set_autoplay(String());
+ }
+ }
}
notify_property_list_changed();
- _reset_timeout();
queue_redraw();
update_configuration_warnings();
+ emit_signal("sprite_frames_changed");
}
Ref<SpriteFrames> AnimatedSprite2D::get_sprite_frames() const {
@@ -301,44 +323,63 @@ Ref<SpriteFrames> AnimatedSprite2D::get_sprite_frames() const {
}
void AnimatedSprite2D::set_frame(int p_frame) {
+ set_frame_and_progress(p_frame, signbit(get_playing_speed()) ? 1.0 : 0.0);
+}
+
+int AnimatedSprite2D::get_frame() const {
+ return frame;
+}
+
+void AnimatedSprite2D::set_frame_progress(real_t p_progress) {
+ frame_progress = p_progress;
+}
+
+real_t AnimatedSprite2D::get_frame_progress() const {
+ return frame_progress;
+}
+
+void AnimatedSprite2D::set_frame_and_progress(int p_frame, real_t p_progress) {
if (frames.is_null()) {
return;
}
- if (frames->has_animation(animation)) {
- int limit = frames->get_frame_count(animation);
- if (p_frame >= limit) {
- p_frame = limit - 1;
- }
- }
+ bool has_animation = frames->has_animation(animation);
+ int end_frame = has_animation ? MAX(0, frames->get_frame_count(animation) - 1) : 0;
+ bool is_changed = frame != p_frame;
if (p_frame < 0) {
- p_frame = 0;
+ frame = 0;
+ } else if (has_animation && p_frame > end_frame) {
+ frame = end_frame;
+ } else {
+ frame = p_frame;
}
- if (frame == p_frame) {
- return;
- }
+ _calc_frame_speed_scale();
+ frame_progress = p_progress;
- frame = p_frame;
- _reset_timeout();
+ if (!is_changed) {
+ return; // No change, don't redraw.
+ }
queue_redraw();
emit_signal(SceneStringNames::get_singleton()->frame_changed);
}
-int AnimatedSprite2D::get_frame() const {
- return frame;
-}
-
void AnimatedSprite2D::set_speed_scale(float p_speed_scale) {
speed_scale = p_speed_scale;
- playing_backwards = signbit(speed_scale) != backwards;
}
float AnimatedSprite2D::get_speed_scale() const {
return speed_scale;
}
+float AnimatedSprite2D::get_playing_speed() const {
+ if (!playing) {
+ return 0;
+ }
+ return speed_scale * custom_speed_scale;
+}
+
void AnimatedSprite2D::set_centered(bool p_center) {
centered = p_center;
queue_redraw();
@@ -378,69 +419,131 @@ bool AnimatedSprite2D::is_flipped_v() const {
}
void AnimatedSprite2D::_res_changed() {
- set_frame(frame);
+ set_frame_and_progress(frame, frame_progress);
queue_redraw();
notify_property_list_changed();
}
-void AnimatedSprite2D::set_playing(bool p_playing) {
- if (playing == p_playing) {
- return;
+bool AnimatedSprite2D::is_playing() const {
+ return playing;
+}
+
+void AnimatedSprite2D::set_autoplay(const String &p_name) {
+ if (is_inside_tree() && !Engine::get_singleton()->is_editor_hint()) {
+ WARN_PRINT("Setting autoplay after the node has been added to the scene has no effect.");
}
- playing = p_playing;
- playing_backwards = signbit(speed_scale) != backwards;
- set_process_internal(playing);
- notify_property_list_changed();
+
+ autoplay = p_name;
}
-bool AnimatedSprite2D::is_playing() const {
- return playing;
+String AnimatedSprite2D::get_autoplay() const {
+ return autoplay;
}
-void AnimatedSprite2D::play(const StringName &p_animation, bool p_backwards) {
- backwards = p_backwards;
- playing_backwards = signbit(speed_scale) != backwards;
+void AnimatedSprite2D::play(const StringName &p_name, float p_custom_scale, bool p_from_end) {
+ StringName name = p_name;
- if (p_animation) {
- set_animation(p_animation);
- if (frames.is_valid() && playing_backwards && get_frame() == 0) {
- set_frame(frames->get_frame_count(p_animation) - 1);
+ if (name == StringName()) {
+ name = animation;
+ }
+
+ ERR_FAIL_COND_MSG(frames == nullptr, vformat("There is no animation with name '%s'.", name));
+ ERR_FAIL_COND_MSG(!frames->get_animation_names().has(name), vformat("There is no animation with name '%s'.", name));
+
+ if (frames->get_frame_count(name) == 0) {
+ return;
+ }
+
+ playing = true;
+ custom_speed_scale = p_custom_scale;
+
+ int end_frame = MAX(0, frames->get_frame_count(animation) - 1);
+ if (name != animation) {
+ animation = name;
+ if (p_from_end) {
+ set_frame_and_progress(end_frame, 1.0);
+ } else {
+ set_frame_and_progress(0, 0.0);
+ }
+ emit_signal("animation_changed");
+ } else {
+ bool is_backward = signbit(speed_scale * custom_speed_scale);
+ if (p_from_end && is_backward && frame == 0 && frame_progress <= 0.0) {
+ set_frame_and_progress(end_frame, 1.0);
+ } else if (!p_from_end && !is_backward && frame == end_frame && frame_progress >= 1.0) {
+ set_frame_and_progress(0, 0.0);
}
}
- is_over = false;
- set_playing(true);
+ set_process_internal(true);
+ notify_property_list_changed();
+ queue_redraw();
+}
+
+void AnimatedSprite2D::play_backwards(const StringName &p_name) {
+ play(p_name, -1, true);
+}
+
+void AnimatedSprite2D::_stop_internal(bool p_reset) {
+ playing = false;
+ if (p_reset) {
+ custom_speed_scale = 1.0;
+ set_frame_and_progress(0, 0.0);
+ }
+ notify_property_list_changed();
+ set_process_internal(false);
+}
+
+void AnimatedSprite2D::pause() {
+ _stop_internal(false);
}
void AnimatedSprite2D::stop() {
- set_playing(false);
- backwards = false;
- _reset_timeout();
+ _stop_internal(true);
}
double AnimatedSprite2D::_get_frame_duration() {
if (frames.is_valid() && frames->has_animation(animation)) {
return frames->get_frame_duration(animation, frame);
}
- return 0.0;
+ return 1.0;
}
-void AnimatedSprite2D::_reset_timeout() {
- timeout = _get_frame_duration();
- is_over = false;
+void AnimatedSprite2D::_calc_frame_speed_scale() {
+ frame_speed_scale = 1.0 / _get_frame_duration();
}
-void AnimatedSprite2D::set_animation(const StringName &p_animation) {
- ERR_FAIL_COND_MSG(frames == nullptr, vformat("There is no animation with name '%s'.", p_animation));
- ERR_FAIL_COND_MSG(!frames->get_animation_names().has(p_animation), vformat("There is no animation with name '%s'.", p_animation));
+void AnimatedSprite2D::set_animation(const StringName &p_name) {
+ if (animation == p_name) {
+ return;
+ }
+
+ animation = p_name;
+
+ emit_signal("animation_changed");
- if (animation == p_animation) {
+ if (frames == nullptr) {
+ animation = StringName();
+ stop();
+ ERR_FAIL_MSG(vformat("There is no animation with name '%s'.", p_name));
+ }
+
+ int frame_count = frames->get_frame_count(animation);
+ if (animation == StringName() || frame_count == 0) {
+ stop();
return;
+ } else if (!frames->get_animation_names().has(animation)) {
+ animation = StringName();
+ stop();
+ ERR_FAIL_MSG(vformat("There is no animation with name '%s'.", p_name));
+ }
+
+ if (signbit(get_playing_speed())) {
+ set_frame_and_progress(frame_count - 1, 1.0);
+ } else {
+ set_frame_and_progress(0, 0.0);
}
- animation = p_animation;
- set_frame(0);
- _reset_timeout();
notify_property_list_changed();
queue_redraw();
}
@@ -468,17 +571,30 @@ void AnimatedSprite2D::get_argument_options(const StringName &p_function, int p_
Node::get_argument_options(p_function, p_idx, r_options);
}
+#ifndef DISABLE_DEPRECATED
+bool AnimatedSprite2D::_set(const StringName &p_name, const Variant &p_value) {
+ if ((p_name == SNAME("frames"))) {
+ set_sprite_frames(p_value);
+ return true;
+ }
+ return false;
+}
+#endif
void AnimatedSprite2D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_sprite_frames", "sprite_frames"), &AnimatedSprite2D::set_sprite_frames);
ClassDB::bind_method(D_METHOD("get_sprite_frames"), &AnimatedSprite2D::get_sprite_frames);
- ClassDB::bind_method(D_METHOD("set_animation", "animation"), &AnimatedSprite2D::set_animation);
+ ClassDB::bind_method(D_METHOD("set_animation", "name"), &AnimatedSprite2D::set_animation);
ClassDB::bind_method(D_METHOD("get_animation"), &AnimatedSprite2D::get_animation);
- ClassDB::bind_method(D_METHOD("set_playing", "playing"), &AnimatedSprite2D::set_playing);
+ ClassDB::bind_method(D_METHOD("set_autoplay", "name"), &AnimatedSprite2D::set_autoplay);
+ ClassDB::bind_method(D_METHOD("get_autoplay"), &AnimatedSprite2D::get_autoplay);
+
ClassDB::bind_method(D_METHOD("is_playing"), &AnimatedSprite2D::is_playing);
- ClassDB::bind_method(D_METHOD("play", "anim", "backwards"), &AnimatedSprite2D::play, DEFVAL(StringName()), DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("play", "name", "custom_speed", "from_end"), &AnimatedSprite2D::play, DEFVAL(StringName()), DEFVAL(1.0), DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("play_backwards", "name"), &AnimatedSprite2D::play_backwards, DEFVAL(StringName()));
+ ClassDB::bind_method(D_METHOD("pause"), &AnimatedSprite2D::pause);
ClassDB::bind_method(D_METHOD("stop"), &AnimatedSprite2D::stop);
ClassDB::bind_method(D_METHOD("set_centered", "centered"), &AnimatedSprite2D::set_centered);
@@ -496,18 +612,28 @@ void AnimatedSprite2D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_frame", "frame"), &AnimatedSprite2D::set_frame);
ClassDB::bind_method(D_METHOD("get_frame"), &AnimatedSprite2D::get_frame);
+ ClassDB::bind_method(D_METHOD("set_frame_progress", "progress"), &AnimatedSprite2D::set_frame_progress);
+ ClassDB::bind_method(D_METHOD("get_frame_progress"), &AnimatedSprite2D::get_frame_progress);
+
+ ClassDB::bind_method(D_METHOD("set_frame_and_progress", "frame", "progress"), &AnimatedSprite2D::set_frame_and_progress);
+
ClassDB::bind_method(D_METHOD("set_speed_scale", "speed_scale"), &AnimatedSprite2D::set_speed_scale);
ClassDB::bind_method(D_METHOD("get_speed_scale"), &AnimatedSprite2D::get_speed_scale);
+ ClassDB::bind_method(D_METHOD("get_playing_speed"), &AnimatedSprite2D::get_playing_speed);
+ ADD_SIGNAL(MethodInfo("sprite_frames_changed"));
+ ADD_SIGNAL(MethodInfo("animation_changed"));
ADD_SIGNAL(MethodInfo("frame_changed"));
+ ADD_SIGNAL(MethodInfo("animation_looped"));
ADD_SIGNAL(MethodInfo("animation_finished"));
ADD_GROUP("Animation", "");
- ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "frames", PROPERTY_HINT_RESOURCE_TYPE, "SpriteFrames"), "set_sprite_frames", "get_sprite_frames");
- ADD_PROPERTY(PropertyInfo(Variant::STRING_NAME, "animation"), "set_animation", "get_animation");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "sprite_frames", PROPERTY_HINT_RESOURCE_TYPE, "SpriteFrames"), "set_sprite_frames", "get_sprite_frames");
+ ADD_PROPERTY(PropertyInfo(Variant::STRING_NAME, "animation", PROPERTY_HINT_ENUM, ""), "set_animation", "get_animation");
+ ADD_PROPERTY(PropertyInfo(Variant::STRING_NAME, "autoplay", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "set_autoplay", "get_autoplay");
ADD_PROPERTY(PropertyInfo(Variant::INT, "frame"), "set_frame", "get_frame");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "frame_progress", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "set_frame_progress", "get_frame_progress");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "speed_scale"), "set_speed_scale", "get_speed_scale");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL, "playing"), "set_playing", "is_playing");
ADD_GROUP("Offset", "");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "centered"), "set_centered", "is_centered");
ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "offset", PROPERTY_HINT_NONE, "suffix:px"), "set_offset", "get_offset");
diff --git a/scene/2d/animated_sprite_2d.h b/scene/2d/animated_sprite_2d.h
index c1d35f3a2f..ac53bd26ee 100644
--- a/scene/2d/animated_sprite_2d.h
+++ b/scene/2d/animated_sprite_2d.h
@@ -38,18 +38,19 @@ class AnimatedSprite2D : public Node2D {
GDCLASS(AnimatedSprite2D, Node2D);
Ref<SpriteFrames> frames;
+ String autoplay;
+
bool playing = false;
- bool playing_backwards = false;
- bool backwards = false;
StringName animation = "default";
int frame = 0;
float speed_scale = 1.0;
+ float custom_speed_scale = 1.0;
bool centered = true;
Point2 offset;
- bool is_over = false;
- float timeout = 0.0;
+ real_t frame_speed_scale = 1.0;
+ real_t frame_progress = 0.0;
bool hflip = false;
bool vflip = false;
@@ -57,10 +58,15 @@ class AnimatedSprite2D : public Node2D {
void _res_changed();
double _get_frame_duration();
- void _reset_timeout();
+ void _calc_frame_speed_scale();
+ void _stop_internal(bool p_reset);
+
Rect2 _get_rect() const;
protected:
+#ifndef DISABLE_DEPRECATED
+ bool _set(const StringName &p_name, const Variant &p_value);
+#endif
static void _bind_methods();
void _notification(int p_what);
void _validate_property(PropertyInfo &p_property) const;
@@ -82,20 +88,30 @@ public:
void set_sprite_frames(const Ref<SpriteFrames> &p_frames);
Ref<SpriteFrames> get_sprite_frames() const;
- void play(const StringName &p_animation = StringName(), bool p_backwards = false);
+ void play(const StringName &p_name = StringName(), float p_custom_scale = 1.0, bool p_from_end = false);
+ void play_backwards(const StringName &p_name = StringName());
+ void pause();
void stop();
- void set_playing(bool p_playing);
bool is_playing() const;
- void set_animation(const StringName &p_animation);
+ void set_animation(const StringName &p_name);
StringName get_animation() const;
+ void set_autoplay(const String &p_name);
+ String get_autoplay() const;
+
void set_frame(int p_frame);
int get_frame() const;
+ void set_frame_progress(real_t p_progress);
+ real_t get_frame_progress() const;
+
+ void set_frame_and_progress(int p_frame, real_t p_progress);
+
void set_speed_scale(float p_speed_scale);
float get_speed_scale() const;
+ float get_playing_speed() const;
void set_centered(bool p_center);
bool is_centered() const;
diff --git a/scene/2d/area_2d.cpp b/scene/2d/area_2d.cpp
index 5eb76bdbb5..a37fabf21f 100644
--- a/scene/2d/area_2d.cpp
+++ b/scene/2d/area_2d.cpp
@@ -51,13 +51,13 @@ bool Area2D::is_gravity_a_point() const {
return gravity_is_point;
}
-void Area2D::set_gravity_point_distance_scale(real_t p_scale) {
- gravity_distance_scale = p_scale;
- PhysicsServer2D::get_singleton()->area_set_param(get_rid(), PhysicsServer2D::AREA_PARAM_GRAVITY_DISTANCE_SCALE, p_scale);
+void Area2D::set_gravity_point_unit_distance(real_t p_scale) {
+ gravity_point_unit_distance = p_scale;
+ PhysicsServer2D::get_singleton()->area_set_param(get_rid(), PhysicsServer2D::AREA_PARAM_GRAVITY_POINT_UNIT_DISTANCE, p_scale);
}
-real_t Area2D::get_gravity_point_distance_scale() const {
- return gravity_distance_scale;
+real_t Area2D::get_gravity_point_unit_distance() const {
+ return gravity_point_unit_distance;
}
void Area2D::set_gravity_point_center(const Vector2 &p_center) {
@@ -175,6 +175,7 @@ void Area2D::_body_inout(int p_status, const RID &p_body, ObjectID p_instance, i
return; //does not exist because it was likely removed from the tree
}
+ lock_callback();
locked = true;
if (body_in) {
@@ -224,6 +225,7 @@ void Area2D::_body_inout(int p_status, const RID &p_body, ObjectID p_instance, i
}
locked = false;
+ unlock_callback();
}
void Area2D::_area_enter_tree(ObjectID p_id) {
@@ -268,6 +270,8 @@ void Area2D::_area_inout(int p_status, const RID &p_area, ObjectID p_instance, i
if (!area_in && !E) {
return; //likely removed from the tree
}
+
+ lock_callback();
locked = true;
if (area_in) {
@@ -317,6 +321,7 @@ void Area2D::_area_inout(int p_status, const RID &p_area, ObjectID p_instance, i
}
locked = false;
+ unlock_callback();
}
void Area2D::_clear_monitoring() {
@@ -552,8 +557,8 @@ void Area2D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_gravity_is_point", "enable"), &Area2D::set_gravity_is_point);
ClassDB::bind_method(D_METHOD("is_gravity_a_point"), &Area2D::is_gravity_a_point);
- ClassDB::bind_method(D_METHOD("set_gravity_point_distance_scale", "distance_scale"), &Area2D::set_gravity_point_distance_scale);
- ClassDB::bind_method(D_METHOD("get_gravity_point_distance_scale"), &Area2D::get_gravity_point_distance_scale);
+ ClassDB::bind_method(D_METHOD("set_gravity_point_unit_distance", "distance_scale"), &Area2D::set_gravity_point_unit_distance);
+ ClassDB::bind_method(D_METHOD("get_gravity_point_unit_distance"), &Area2D::get_gravity_point_unit_distance);
ClassDB::bind_method(D_METHOD("set_gravity_point_center", "center"), &Area2D::set_gravity_point_center);
ClassDB::bind_method(D_METHOD("get_gravity_point_center"), &Area2D::get_gravity_point_center);
@@ -617,7 +622,7 @@ void Area2D::_bind_methods() {
ADD_GROUP("Gravity", "gravity_");
ADD_PROPERTY(PropertyInfo(Variant::INT, "gravity_space_override", PROPERTY_HINT_ENUM, "Disabled,Combine,Combine-Replace,Replace,Replace-Combine", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), "set_gravity_space_override_mode", "get_gravity_space_override_mode");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "gravity_point", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), "set_gravity_is_point", "is_gravity_a_point");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "gravity_point_distance_scale", PROPERTY_HINT_RANGE, "0,1024,0.001,or_greater,exp"), "set_gravity_point_distance_scale", "get_gravity_point_distance_scale");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "gravity_point_unit_distance", PROPERTY_HINT_RANGE, "0,1024,0.001,or_greater,exp,suffix:px"), "set_gravity_point_unit_distance", "get_gravity_point_unit_distance");
ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "gravity_point_center", PROPERTY_HINT_NONE, "suffix:px"), "set_gravity_point_center", "get_gravity_point_center");
ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "gravity_direction"), "set_gravity_direction", "get_gravity_direction");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "gravity", PROPERTY_HINT_RANGE, U"-4096,4096,0.001,or_less,or_greater,suffix:px/s\u00B2"), "set_gravity", "get_gravity");
@@ -647,6 +652,7 @@ Area2D::Area2D() :
set_gravity_direction(Vector2(0, 1));
set_monitoring(true);
set_monitorable(true);
+ set_hide_clip_children(true);
}
Area2D::~Area2D() {
diff --git a/scene/2d/area_2d.h b/scene/2d/area_2d.h
index aaf7ea28f8..8f4bbe3219 100644
--- a/scene/2d/area_2d.h
+++ b/scene/2d/area_2d.h
@@ -51,7 +51,7 @@ private:
Vector2 gravity_vec;
real_t gravity = 0.0;
bool gravity_is_point = false;
- real_t gravity_distance_scale = 0.0;
+ real_t gravity_point_unit_distance = 0.0;
SpaceOverride linear_damp_space_override = SPACE_OVERRIDE_DISABLED;
SpaceOverride angular_damp_space_override = SPACE_OVERRIDE_DISABLED;
@@ -144,8 +144,8 @@ public:
void set_gravity_is_point(bool p_enabled);
bool is_gravity_a_point() const;
- void set_gravity_point_distance_scale(real_t p_scale);
- real_t get_gravity_point_distance_scale() const;
+ void set_gravity_point_unit_distance(real_t p_scale);
+ real_t get_gravity_point_unit_distance() const;
void set_gravity_point_center(const Vector2 &p_center);
const Vector2 &get_gravity_point_center() const;
diff --git a/scene/2d/audio_listener_2d.cpp b/scene/2d/audio_listener_2d.cpp
index 5b8833ce62..b4484694a5 100644
--- a/scene/2d/audio_listener_2d.cpp
+++ b/scene/2d/audio_listener_2d.cpp
@@ -110,3 +110,7 @@ void AudioListener2D::_bind_methods() {
ClassDB::bind_method(D_METHOD("clear_current"), &AudioListener2D::clear_current);
ClassDB::bind_method(D_METHOD("is_current"), &AudioListener2D::is_current);
}
+
+AudioListener2D::AudioListener2D() {
+ set_hide_clip_children(true);
+}
diff --git a/scene/2d/audio_listener_2d.h b/scene/2d/audio_listener_2d.h
index 12a44f26ae..abada06971 100644
--- a/scene/2d/audio_listener_2d.h
+++ b/scene/2d/audio_listener_2d.h
@@ -54,6 +54,8 @@ public:
void make_current();
void clear_current();
bool is_current() const;
+
+ AudioListener2D();
};
#endif // AUDIO_LISTENER_2D_H
diff --git a/scene/2d/audio_stream_player_2d.cpp b/scene/2d/audio_stream_player_2d.cpp
index c4de3a124b..902fba38bf 100644
--- a/scene/2d/audio_stream_player_2d.cpp
+++ b/scene/2d/audio_stream_player_2d.cpp
@@ -72,12 +72,10 @@ void AudioStreamPlayer2D::_notification(int p_what) {
_update_panning();
}
- if (setplay.get() >= 0 && stream.is_valid()) {
+ if (setplayback.is_valid() && setplay.get() >= 0) {
active.set();
- Ref<AudioStreamPlayback> new_playback = stream->instantiate_playback();
- ERR_FAIL_COND_MSG(new_playback.is_null(), "Failed to instantiate playback.");
- AudioServer::get_singleton()->start_playback_stream(new_playback, _get_actual_bus(), volume_vector, setplay.get(), pitch_scale);
- stream_playbacks.push_back(new_playback);
+ AudioServer::get_singleton()->start_playback_stream(setplayback, _get_actual_bus(), volume_vector, setplay.get(), pitch_scale);
+ setplayback.unref();
setplay.set(-1);
}
@@ -255,7 +253,11 @@ void AudioStreamPlayer2D::play(float p_from_pos) {
if (stream->is_monophonic() && is_playing()) {
stop();
}
+ Ref<AudioStreamPlayback> stream_playback = stream->instantiate_playback();
+ ERR_FAIL_COND_MSG(stream_playback.is_null(), "Failed to instantiate playback.");
+ stream_playbacks.push_back(stream_playback);
+ setplayback = stream_playback;
setplay.set(p_from_pos);
active.set();
set_physics_process_internal(true);
@@ -390,11 +392,13 @@ bool AudioStreamPlayer2D::get_stream_paused() const {
return false;
}
+bool AudioStreamPlayer2D::has_stream_playback() {
+ return !stream_playbacks.is_empty();
+}
+
Ref<AudioStreamPlayback> AudioStreamPlayer2D::get_stream_playback() {
- if (!stream_playbacks.is_empty()) {
- return stream_playbacks[stream_playbacks.size() - 1];
- }
- return nullptr;
+ ERR_FAIL_COND_V_MSG(stream_playbacks.is_empty(), Ref<AudioStreamPlayback>(), "Player is inactive. Call play() before requesting get_stream_playback().");
+ return stream_playbacks[stream_playbacks.size() - 1];
}
void AudioStreamPlayer2D::set_max_polyphony(int p_max_polyphony) {
@@ -460,6 +464,7 @@ void AudioStreamPlayer2D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_panning_strength", "panning_strength"), &AudioStreamPlayer2D::set_panning_strength);
ClassDB::bind_method(D_METHOD("get_panning_strength"), &AudioStreamPlayer2D::get_panning_strength);
+ ClassDB::bind_method(D_METHOD("has_stream_playback"), &AudioStreamPlayer2D::has_stream_playback);
ClassDB::bind_method(D_METHOD("get_stream_playback"), &AudioStreamPlayer2D::get_stream_playback);
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "stream", PROPERTY_HINT_RESOURCE_TYPE, "AudioStream"), "set_stream", "get_stream");
@@ -481,6 +486,7 @@ void AudioStreamPlayer2D::_bind_methods() {
AudioStreamPlayer2D::AudioStreamPlayer2D() {
AudioServer::get_singleton()->connect("bus_layout_changed", callable_mp(this, &AudioStreamPlayer2D::_bus_layout_changed));
cached_global_panning_strength = GLOBAL_GET("audio/general/2d_panning_strength");
+ set_hide_clip_children(true);
}
AudioStreamPlayer2D::~AudioStreamPlayer2D() {
diff --git a/scene/2d/audio_stream_player_2d.h b/scene/2d/audio_stream_player_2d.h
index a5fd584513..79a026fed2 100644
--- a/scene/2d/audio_stream_player_2d.h
+++ b/scene/2d/audio_stream_player_2d.h
@@ -56,6 +56,7 @@ private:
SafeFlag active{ false };
SafeNumeric<float> setplay{ -1.0 };
+ Ref<AudioStreamPlayback> setplayback;
Vector<AudioFrame> volume_vector;
@@ -129,6 +130,7 @@ public:
void set_panning_strength(float p_panning_strength);
float get_panning_strength() const;
+ bool has_stream_playback();
Ref<AudioStreamPlayback> get_stream_playback();
AudioStreamPlayer2D();
diff --git a/scene/2d/back_buffer_copy.cpp b/scene/2d/back_buffer_copy.cpp
index ab048f0cd7..60b344b002 100644
--- a/scene/2d/back_buffer_copy.cpp
+++ b/scene/2d/back_buffer_copy.cpp
@@ -101,6 +101,7 @@ void BackBufferCopy::_bind_methods() {
BackBufferCopy::BackBufferCopy() {
_update_copy_mode();
+ set_hide_clip_children(true);
}
BackBufferCopy::~BackBufferCopy() {
diff --git a/scene/2d/camera_2d.cpp b/scene/2d/camera_2d.cpp
index c4647ae9ff..fe6bee0f1b 100644
--- a/scene/2d/camera_2d.cpp
+++ b/scene/2d/camera_2d.cpp
@@ -50,7 +50,7 @@ void Camera2D::_update_scroll() {
return;
}
- if (current) {
+ if (is_current()) {
ERR_FAIL_COND(custom_viewport && !ObjectDB::get_instance(custom_viewport_id));
Transform2D xform = get_camera_transform();
@@ -241,10 +241,6 @@ void Camera2D::_notification(int p_what) {
viewport = get_viewport();
}
- if (is_current()) {
- viewport->_camera_2d_set(this);
- }
-
canvas = get_canvas();
RID vp = viewport->get_viewport_rid();
@@ -254,21 +250,21 @@ void Camera2D::_notification(int p_what) {
add_to_group(group_name);
add_to_group(canvas_group_name);
+ if (!Engine::get_singleton()->is_editor_hint() && enabled && !viewport->get_camera_2d()) {
+ make_current();
+ }
+
_update_process_callback();
first = true;
_update_scroll();
} break;
case NOTIFICATION_EXIT_TREE: {
- if (is_current()) {
- if (viewport && !(custom_viewport && !ObjectDB::get_instance(custom_viewport_id))) {
- viewport->set_canvas_transform(Transform2D());
- clear_current();
- current = true;
- }
- }
remove_from_group(group_name);
remove_from_group(canvas_group_name);
+ if (is_current()) {
+ clear_current();
+ }
viewport = nullptr;
} break;
@@ -397,19 +393,31 @@ void Camera2D::set_process_callback(Camera2DProcessCallback p_mode) {
_update_process_callback();
}
+void Camera2D::set_enabled(bool p_enabled) {
+ enabled = p_enabled;
+
+ if (enabled && is_inside_tree() && !viewport->get_camera_2d()) {
+ make_current();
+ } else if (!enabled && is_current()) {
+ clear_current();
+ }
+}
+
+bool Camera2D::is_enabled() const {
+ return enabled;
+}
+
Camera2D::Camera2DProcessCallback Camera2D::get_process_callback() const {
return process_callback;
}
void Camera2D::_make_current(Object *p_which) {
if (p_which == this) {
- current = true;
if (is_inside_tree()) {
get_viewport()->_camera_2d_set(this);
queue_redraw();
}
} else {
- current = false;
if (is_inside_tree()) {
if (get_viewport()->get_camera_2d() == this) {
get_viewport()->_camera_2d_set(nullptr);
@@ -419,45 +427,34 @@ void Camera2D::_make_current(Object *p_which) {
}
}
-void Camera2D::set_current(bool p_current) {
- if (p_current) {
- make_current();
- } else {
- if (current) {
- clear_current();
- }
- }
-}
-
void Camera2D::_update_process_internal_for_smoothing() {
bool is_not_in_scene_or_editor = !(is_inside_tree() && Engine::get_singleton()->is_editor_hint());
bool is_any_smoothing_valid = position_smoothing_speed > 0 || rotation_smoothing_speed > 0;
- bool enabled = is_any_smoothing_valid && is_not_in_scene_or_editor;
- set_process_internal(enabled);
-}
-
-bool Camera2D::is_current() const {
- return current;
+ bool enable = is_any_smoothing_valid && is_not_in_scene_or_editor;
+ set_process_internal(enable);
}
void Camera2D::make_current() {
- if (is_inside_tree()) {
- get_tree()->call_group(group_name, "_make_current", this);
- } else {
- current = true;
- }
+ ERR_FAIL_COND(!enabled || !is_inside_tree());
+ get_tree()->call_group(group_name, "_make_current", this);
_update_scroll();
}
void Camera2D::clear_current() {
- if (is_inside_tree()) {
- get_tree()->call_group(group_name, "_make_current", (Object *)nullptr);
- } else {
- current = false;
+ ERR_FAIL_COND(!is_current());
+ if (viewport && !(custom_viewport && !ObjectDB::get_instance(custom_viewport_id))) {
+ viewport->assign_next_enabled_camera_2d(group_name);
}
}
+bool Camera2D::is_current() const {
+ if (viewport && !(custom_viewport && !ObjectDB::get_instance(custom_viewport_id))) {
+ return viewport->get_camera_2d() == this;
+ }
+ return false;
+}
+
void Camera2D::set_limit(Side p_side, int p_limit) {
ERR_FAIL_INDEX((int)p_side, 4);
limit[p_side] = p_limit;
@@ -715,7 +712,10 @@ void Camera2D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_process_callback", "mode"), &Camera2D::set_process_callback);
ClassDB::bind_method(D_METHOD("get_process_callback"), &Camera2D::get_process_callback);
- ClassDB::bind_method(D_METHOD("set_current", "current"), &Camera2D::set_current);
+ ClassDB::bind_method(D_METHOD("set_enabled", "enabled"), &Camera2D::set_enabled);
+ ClassDB::bind_method(D_METHOD("is_enabled"), &Camera2D::is_enabled);
+
+ ClassDB::bind_method(D_METHOD("make_current"), &Camera2D::make_current);
ClassDB::bind_method(D_METHOD("is_current"), &Camera2D::is_current);
ClassDB::bind_method(D_METHOD("_make_current"), &Camera2D::_make_current);
@@ -779,7 +779,7 @@ void Camera2D::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "offset", PROPERTY_HINT_NONE, "suffix:px"), "set_offset", "get_offset");
ADD_PROPERTY(PropertyInfo(Variant::INT, "anchor_mode", PROPERTY_HINT_ENUM, "Fixed TopLeft,Drag Center"), "set_anchor_mode", "get_anchor_mode");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "ignore_rotation"), "set_ignore_rotation", "is_ignoring_rotation");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL, "current"), "set_current", "is_current");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "enabled"), "set_enabled", "is_enabled");
ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "zoom", PROPERTY_HINT_LINK), "set_zoom", "get_zoom");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "custom_viewport", PROPERTY_HINT_RESOURCE_TYPE, "Viewport", PROPERTY_USAGE_NONE), "set_custom_viewport", "get_custom_viewport");
ADD_PROPERTY(PropertyInfo(Variant::INT, "process_callback", PROPERTY_HINT_ENUM, "Physics,Idle"), "set_process_callback", "get_process_callback");
@@ -832,4 +832,5 @@ Camera2D::Camera2D() {
drag_margin[SIDE_BOTTOM] = 0.2;
set_notify_transform(true);
+ set_hide_clip_children(true);
}
diff --git a/scene/2d/camera_2d.h b/scene/2d/camera_2d.h
index 304b4ceaa6..7a77266db8 100644
--- a/scene/2d/camera_2d.h
+++ b/scene/2d/camera_2d.h
@@ -64,7 +64,7 @@ protected:
Vector2 zoom_scale = Vector2(1, 1);
AnchorMode anchor_mode = ANCHOR_MODE_DRAG_CENTER;
bool ignore_rotation = true;
- bool current = false;
+ bool enabled = true;
real_t position_smoothing_speed = 5.0;
bool follow_smoothing_enabled = false;
@@ -88,7 +88,6 @@ protected:
void _update_scroll();
void _make_current(Object *p_which);
- void set_current(bool p_current);
void _set_old_smoothing(real_t p_enable);
@@ -155,6 +154,9 @@ public:
void set_process_callback(Camera2DProcessCallback p_mode);
Camera2DProcessCallback get_process_callback() const;
+ void set_enabled(bool p_enabled);
+ bool is_enabled() const;
+
void make_current();
void clear_current();
bool is_current() const;
diff --git a/scene/2d/collision_object_2d.cpp b/scene/2d/collision_object_2d.cpp
index b2fee6ad82..ba3b0cec5c 100644
--- a/scene/2d/collision_object_2d.cpp
+++ b/scene/2d/collision_object_2d.cpp
@@ -94,10 +94,14 @@ void CollisionObject2D::_notification(int p_what) {
bool disabled = !is_enabled();
if (!disabled || (disable_mode != DISABLE_MODE_REMOVE)) {
- if (area) {
- PhysicsServer2D::get_singleton()->area_set_space(rid, RID());
+ if (callback_lock > 0) {
+ ERR_PRINT("Removing a CollisionObject node during a physics callback is not allowed and will cause undesired behavior. Remove with call_deferred() instead.");
} else {
- PhysicsServer2D::get_singleton()->body_set_space(rid, RID());
+ if (area) {
+ PhysicsServer2D::get_singleton()->area_set_space(rid, RID());
+ } else {
+ PhysicsServer2D::get_singleton()->body_set_space(rid, RID());
+ }
}
}
@@ -225,10 +229,14 @@ void CollisionObject2D::_apply_disabled() {
switch (disable_mode) {
case DISABLE_MODE_REMOVE: {
if (is_inside_tree()) {
- if (area) {
- PhysicsServer2D::get_singleton()->area_set_space(rid, RID());
+ if (callback_lock > 0) {
+ ERR_PRINT("Disabling a CollisionObject node during a physics callback is not allowed and will cause undesired behavior. Disable with call_deferred() instead.");
} else {
- PhysicsServer2D::get_singleton()->body_set_space(rid, RID());
+ if (area) {
+ PhysicsServer2D::get_singleton()->area_set_space(rid, RID());
+ } else {
+ PhysicsServer2D::get_singleton()->body_set_space(rid, RID());
+ }
}
}
} break;
@@ -643,6 +651,7 @@ CollisionObject2D::CollisionObject2D(RID p_rid, bool p_area) {
area = p_area;
pickable = true;
set_notify_transform(true);
+ set_hide_clip_children(true);
total_subshapes = 0;
only_update_transform_changes = false;
diff --git a/scene/2d/collision_object_2d.h b/scene/2d/collision_object_2d.h
index d44e402e96..88429b145d 100644
--- a/scene/2d/collision_object_2d.h
+++ b/scene/2d/collision_object_2d.h
@@ -53,6 +53,7 @@ private:
bool area = false;
RID rid;
+ uint32_t callback_lock = 0;
bool pickable = false;
DisableMode disable_mode = DISABLE_MODE_REMOVE;
@@ -83,6 +84,12 @@ private:
void _apply_enabled();
protected:
+ _FORCE_INLINE_ void lock_callback() { callback_lock++; }
+ _FORCE_INLINE_ void unlock_callback() {
+ ERR_FAIL_COND(callback_lock == 0);
+ callback_lock--;
+ }
+
CollisionObject2D(RID p_rid, bool p_area);
void _notification(int p_what);
diff --git a/scene/2d/collision_polygon_2d.cpp b/scene/2d/collision_polygon_2d.cpp
index 0e18f77b8a..32dea80650 100644
--- a/scene/2d/collision_polygon_2d.cpp
+++ b/scene/2d/collision_polygon_2d.cpp
@@ -131,15 +131,7 @@ void CollisionPolygon2D::_notification(int p_what) {
break;
}
- int polygon_count = polygon.size();
- for (int i = 0; i < polygon_count; i++) {
- Vector2 p = polygon[i];
- Vector2 n = polygon[(i + 1) % polygon_count];
- // draw line with width <= 1, so it does not scale with zoom and break pixel exact editing
- draw_line(p, n, Color(0.9, 0.2, 0.0, 0.8), 1);
- }
-
- if (polygon_count > 2) {
+ if (polygon.size() > 2) {
#define DEBUG_DECOMPOSE
#if defined(TOOLS_ENABLED) && defined(DEBUG_DECOMPOSE)
Vector<Vector<Vector2>> decomp = _decompose_in_convex();
@@ -152,6 +144,11 @@ void CollisionPolygon2D::_notification(int p_what) {
#else
draw_colored_polygon(polygon, get_tree()->get_debug_collisions_color());
#endif
+
+ const Color stroke_color = Color(0.9, 0.2, 0.0);
+ draw_polyline(polygon, stroke_color);
+ // Draw the last segment.
+ draw_line(polygon[polygon.size() - 1], polygon[0], stroke_color);
}
if (one_way_collision) {
@@ -323,4 +320,5 @@ void CollisionPolygon2D::_bind_methods() {
CollisionPolygon2D::CollisionPolygon2D() {
set_notify_local_transform(true);
+ set_hide_clip_children(true);
}
diff --git a/scene/2d/collision_shape_2d.cpp b/scene/2d/collision_shape_2d.cpp
index 6ff789cad2..5951405bbe 100644
--- a/scene/2d/collision_shape_2d.cpp
+++ b/scene/2d/collision_shape_2d.cpp
@@ -288,5 +288,6 @@ void CollisionShape2D::_bind_methods() {
CollisionShape2D::CollisionShape2D() {
set_notify_local_transform(true);
+ set_hide_clip_children(true);
debug_color = _get_default_debug_color();
}
diff --git a/scene/2d/cpu_particles_2d.cpp b/scene/2d/cpu_particles_2d.cpp
index 39be51879d..afd4763d74 100644
--- a/scene/2d/cpu_particles_2d.cpp
+++ b/scene/2d/cpu_particles_2d.cpp
@@ -1430,8 +1430,8 @@ void CPUParticles2D::_bind_methods() {
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "anim_speed_min", PROPERTY_HINT_RANGE, "0,128,0.01,or_greater,or_less"), "set_param_min", "get_param_min", PARAM_ANIM_SPEED);
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "anim_speed_max", PROPERTY_HINT_RANGE, "0,128,0.01,or_greater,or_less"), "set_param_max", "get_param_max", PARAM_ANIM_SPEED);
ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "anim_speed_curve", PROPERTY_HINT_RESOURCE_TYPE, "Curve"), "set_param_curve", "get_param_curve", PARAM_ANIM_SPEED);
- ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "anim_offset_min", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_param_min", "get_param_min", PARAM_ANIM_OFFSET);
- ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "anim_offset_max", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_param_max", "get_param_max", PARAM_ANIM_OFFSET);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "anim_offset_min", PROPERTY_HINT_RANGE, "0,1,0.0001"), "set_param_min", "get_param_min", PARAM_ANIM_OFFSET);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "anim_offset_max", PROPERTY_HINT_RANGE, "0,1,0.0001"), "set_param_max", "get_param_max", PARAM_ANIM_OFFSET);
ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "anim_offset_curve", PROPERTY_HINT_RESOURCE_TYPE, "Curve"), "set_param_curve", "get_param_curve", PARAM_ANIM_OFFSET);
BIND_ENUM_CONSTANT(PARAM_INITIAL_LINEAR_VELOCITY);
diff --git a/scene/2d/gpu_particles_2d.cpp b/scene/2d/gpu_particles_2d.cpp
index 9a3b7c8687..00d13c59b9 100644
--- a/scene/2d/gpu_particles_2d.cpp
+++ b/scene/2d/gpu_particles_2d.cpp
@@ -638,7 +638,7 @@ void GPUParticles2D::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "interpolate"), "set_interpolate", "get_interpolate");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "fract_delta"), "set_fractional_delta", "get_fractional_delta");
ADD_GROUP("Collision", "collision_");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "collision_base_size", PROPERTY_HINT_RANGE, "0,128,0.01,or_greater,suffix:px"), "set_collision_base_size", "get_collision_base_size");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "collision_base_size", PROPERTY_HINT_RANGE, "0,128,0.01,or_greater"), "set_collision_base_size", "get_collision_base_size");
ADD_GROUP("Drawing", "");
ADD_PROPERTY(PropertyInfo(Variant::RECT2, "visibility_rect", PROPERTY_HINT_NONE, "suffix:px"), "set_visibility_rect", "get_visibility_rect");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "local_coords"), "set_use_local_coordinates", "get_use_local_coordinates");
diff --git a/scene/2d/joint_2d.cpp b/scene/2d/joint_2d.cpp
index 47d0ac6e35..ce427d47aa 100644
--- a/scene/2d/joint_2d.cpp
+++ b/scene/2d/joint_2d.cpp
@@ -243,6 +243,7 @@ void Joint2D::_bind_methods() {
Joint2D::Joint2D() {
joint = PhysicsServer2D::get_singleton()->joint_create();
+ set_hide_clip_children(true);
}
Joint2D::~Joint2D() {
diff --git a/scene/2d/light_2d.cpp b/scene/2d/light_2d.cpp
index fb53400fd6..15b638ed92 100644
--- a/scene/2d/light_2d.cpp
+++ b/scene/2d/light_2d.cpp
@@ -443,6 +443,7 @@ void PointLight2D::_bind_methods() {
PointLight2D::PointLight2D() {
RS::get_singleton()->canvas_light_set_mode(_get_light(), RS::CANVAS_LIGHT_MODE_POINT);
+ set_hide_clip_children(true);
}
//////////
@@ -467,4 +468,5 @@ void DirectionalLight2D::_bind_methods() {
DirectionalLight2D::DirectionalLight2D() {
RS::get_singleton()->canvas_light_set_mode(_get_light(), RS::CANVAS_LIGHT_MODE_DIRECTIONAL);
set_max_distance(max_distance); // Update RenderingServer.
+ set_hide_clip_children(true);
}
diff --git a/scene/2d/marker_2d.cpp b/scene/2d/marker_2d.cpp
index 512875833c..9595fcfffe 100644
--- a/scene/2d/marker_2d.cpp
+++ b/scene/2d/marker_2d.cpp
@@ -117,4 +117,5 @@ void Marker2D::_bind_methods() {
}
Marker2D::Marker2D() {
+ set_hide_clip_children(true);
}
diff --git a/scene/2d/mesh_instance_2d.cpp b/scene/2d/mesh_instance_2d.cpp
index f69b3728f7..4fc375ff8d 100644
--- a/scene/2d/mesh_instance_2d.cpp
+++ b/scene/2d/mesh_instance_2d.cpp
@@ -49,14 +49,10 @@ void MeshInstance2D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_texture", "texture"), &MeshInstance2D::set_texture);
ClassDB::bind_method(D_METHOD("get_texture"), &MeshInstance2D::get_texture);
- ClassDB::bind_method(D_METHOD("set_normal_map", "normal_map"), &MeshInstance2D::set_normal_map);
- ClassDB::bind_method(D_METHOD("get_normal_map"), &MeshInstance2D::get_normal_map);
-
ADD_SIGNAL(MethodInfo("texture_changed"));
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "mesh", PROPERTY_HINT_RESOURCE_TYPE, "Mesh"), "set_mesh", "get_mesh");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture2D"), "set_texture", "get_texture");
- ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "normal_map", PROPERTY_HINT_RESOURCE_TYPE, "Texture2D"), "set_normal_map", "get_normal_map");
}
void MeshInstance2D::set_mesh(const Ref<Mesh> &p_mesh) {
@@ -77,15 +73,6 @@ void MeshInstance2D::set_texture(const Ref<Texture2D> &p_texture) {
emit_signal(SceneStringNames::get_singleton()->texture_changed);
}
-void MeshInstance2D::set_normal_map(const Ref<Texture2D> &p_texture) {
- normal_map = p_texture;
- queue_redraw();
-}
-
-Ref<Texture2D> MeshInstance2D::get_normal_map() const {
- return normal_map;
-}
-
Ref<Texture2D> MeshInstance2D::get_texture() const {
return texture;
}
diff --git a/scene/2d/mesh_instance_2d.h b/scene/2d/mesh_instance_2d.h
index 795b3758e3..c914f13ade 100644
--- a/scene/2d/mesh_instance_2d.h
+++ b/scene/2d/mesh_instance_2d.h
@@ -39,7 +39,6 @@ class MeshInstance2D : public Node2D {
Ref<Mesh> mesh;
Ref<Texture2D> texture;
- Ref<Texture2D> normal_map;
protected:
void _notification(int p_what);
@@ -57,9 +56,6 @@ public:
void set_texture(const Ref<Texture2D> &p_texture);
Ref<Texture2D> get_texture() const;
- void set_normal_map(const Ref<Texture2D> &p_texture);
- Ref<Texture2D> get_normal_map() const;
-
MeshInstance2D();
};
diff --git a/scene/2d/multimesh_instance_2d.cpp b/scene/2d/multimesh_instance_2d.cpp
index ac7c350751..f347eb6520 100644
--- a/scene/2d/multimesh_instance_2d.cpp
+++ b/scene/2d/multimesh_instance_2d.cpp
@@ -50,14 +50,10 @@ void MultiMeshInstance2D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_texture", "texture"), &MultiMeshInstance2D::set_texture);
ClassDB::bind_method(D_METHOD("get_texture"), &MultiMeshInstance2D::get_texture);
- ClassDB::bind_method(D_METHOD("set_normal_map", "normal_map"), &MultiMeshInstance2D::set_normal_map);
- ClassDB::bind_method(D_METHOD("get_normal_map"), &MultiMeshInstance2D::get_normal_map);
-
ADD_SIGNAL(MethodInfo("texture_changed"));
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "multimesh", PROPERTY_HINT_RESOURCE_TYPE, "MultiMesh"), "set_multimesh", "get_multimesh");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture2D"), "set_texture", "get_texture");
- ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "normal_map", PROPERTY_HINT_RESOURCE_TYPE, "Texture2D"), "set_normal_map", "get_normal_map");
}
void MultiMeshInstance2D::set_multimesh(const Ref<MultiMesh> &p_multimesh) {
@@ -91,15 +87,6 @@ Ref<Texture2D> MultiMeshInstance2D::get_texture() const {
return texture;
}
-void MultiMeshInstance2D::set_normal_map(const Ref<Texture2D> &p_texture) {
- normal_map = p_texture;
- queue_redraw();
-}
-
-Ref<Texture2D> MultiMeshInstance2D::get_normal_map() const {
- return normal_map;
-}
-
#ifdef TOOLS_ENABLED
Rect2 MultiMeshInstance2D::_edit_get_rect() const {
if (multimesh.is_valid()) {
diff --git a/scene/2d/multimesh_instance_2d.h b/scene/2d/multimesh_instance_2d.h
index 64ecae6d6c..0647412294 100644
--- a/scene/2d/multimesh_instance_2d.h
+++ b/scene/2d/multimesh_instance_2d.h
@@ -40,7 +40,6 @@ class MultiMeshInstance2D : public Node2D {
Ref<MultiMesh> multimesh;
Ref<Texture2D> texture;
- Ref<Texture2D> normal_map;
protected:
void _notification(int p_what);
@@ -57,9 +56,6 @@ public:
void set_texture(const Ref<Texture2D> &p_texture);
Ref<Texture2D> get_texture() const;
- void set_normal_map(const Ref<Texture2D> &p_texture);
- Ref<Texture2D> get_normal_map() const;
-
MultiMeshInstance2D();
~MultiMeshInstance2D();
};
diff --git a/scene/2d/navigation_agent_2d.cpp b/scene/2d/navigation_agent_2d.cpp
index 4f6ba093cb..6aa7779b09 100644
--- a/scene/2d/navigation_agent_2d.cpp
+++ b/scene/2d/navigation_agent_2d.cpp
@@ -76,10 +76,10 @@ void NavigationAgent2D::_bind_methods() {
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);
- ClassDB::bind_method(D_METHOD("set_target_location", "location"), &NavigationAgent2D::set_target_location);
- ClassDB::bind_method(D_METHOD("get_target_location"), &NavigationAgent2D::get_target_location);
+ ClassDB::bind_method(D_METHOD("set_target_position", "position"), &NavigationAgent2D::set_target_position);
+ ClassDB::bind_method(D_METHOD("get_target_position"), &NavigationAgent2D::get_target_position);
- ClassDB::bind_method(D_METHOD("get_next_location"), &NavigationAgent2D::get_next_location);
+ ClassDB::bind_method(D_METHOD("get_next_path_position"), &NavigationAgent2D::get_next_path_position);
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_current_navigation_result"), &NavigationAgent2D::get_current_navigation_result);
@@ -88,15 +88,15 @@ void NavigationAgent2D::_bind_methods() {
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);
- ClassDB::bind_method(D_METHOD("get_final_location"), &NavigationAgent2D::get_final_location);
+ ClassDB::bind_method(D_METHOD("get_final_position"), &NavigationAgent2D::get_final_position);
ClassDB::bind_method(D_METHOD("_avoidance_done", "new_velocity"), &NavigationAgent2D::_avoidance_done);
ADD_GROUP("Pathfinding", "");
- ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "target_location", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "set_target_location", "get_target_location");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "path_desired_distance", PROPERTY_HINT_RANGE, "0.1,100,0.01,suffix:px"), "set_path_desired_distance", "get_path_desired_distance");
- 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::VECTOR2, "target_position", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "set_target_position", "get_target_position");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "path_desired_distance", PROPERTY_HINT_RANGE, "0.1,1000,0.01,suffix:px"), "set_path_desired_distance", "get_path_desired_distance");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "target_desired_distance", PROPERTY_HINT_RANGE, "0.1,1000,0.01,suffix:px"), "set_target_desired_distance", "get_target_desired_distance");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "path_max_distance", PROPERTY_HINT_RANGE, "10,1000,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");
@@ -105,8 +105,26 @@ void NavigationAgent2D::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "radius", PROPERTY_HINT_RANGE, "0.1,500,0.01,suffix:px"), "set_radius", "get_radius");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "neighbor_distance", PROPERTY_HINT_RANGE, "0.1,100000,0.01,suffix:px"), "set_neighbor_distance", "get_neighbor_distance");
ADD_PROPERTY(PropertyInfo(Variant::INT, "max_neighbors", PROPERTY_HINT_RANGE, "1,10000,1"), "set_max_neighbors", "get_max_neighbors");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "time_horizon", PROPERTY_HINT_RANGE, "0.1,10000,0.01,suffix:s"), "set_time_horizon", "get_time_horizon");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "max_speed", PROPERTY_HINT_RANGE, "0.1,100000,0.01,suffix:px/s"), "set_max_speed", "get_max_speed");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "time_horizon", PROPERTY_HINT_RANGE, "0.1,10,0.01,suffix:s"), "set_time_horizon", "get_time_horizon");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "max_speed", PROPERTY_HINT_RANGE, "0.1,10000,0.01,suffix:px/s"), "set_max_speed", "get_max_speed");
+
+ ClassDB::bind_method(D_METHOD("set_debug_enabled", "enabled"), &NavigationAgent2D::set_debug_enabled);
+ ClassDB::bind_method(D_METHOD("get_debug_enabled"), &NavigationAgent2D::get_debug_enabled);
+ ClassDB::bind_method(D_METHOD("set_debug_use_custom", "enabled"), &NavigationAgent2D::set_debug_use_custom);
+ ClassDB::bind_method(D_METHOD("get_debug_use_custom"), &NavigationAgent2D::get_debug_use_custom);
+ ClassDB::bind_method(D_METHOD("set_debug_path_custom_color", "color"), &NavigationAgent2D::set_debug_path_custom_color);
+ ClassDB::bind_method(D_METHOD("get_debug_path_custom_color"), &NavigationAgent2D::get_debug_path_custom_color);
+ ClassDB::bind_method(D_METHOD("set_debug_path_custom_point_size", "point_size"), &NavigationAgent2D::set_debug_path_custom_point_size);
+ ClassDB::bind_method(D_METHOD("get_debug_path_custom_point_size"), &NavigationAgent2D::get_debug_path_custom_point_size);
+ ClassDB::bind_method(D_METHOD("set_debug_path_custom_line_width", "line_width"), &NavigationAgent2D::set_debug_path_custom_line_width);
+ ClassDB::bind_method(D_METHOD("get_debug_path_custom_line_width"), &NavigationAgent2D::get_debug_path_custom_line_width);
+
+ ADD_GROUP("Debug", "");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "debug_enabled"), "set_debug_enabled", "get_debug_enabled");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "debug_use_custom"), "set_debug_use_custom", "get_debug_use_custom");
+ ADD_PROPERTY(PropertyInfo(Variant::COLOR, "debug_path_custom_color"), "set_debug_path_custom_color", "get_debug_path_custom_color");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "debug_path_custom_point_size", PROPERTY_HINT_RANGE, "1,50,1,suffix:px"), "set_debug_path_custom_point_size", "get_debug_path_custom_point_size");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "debug_path_custom_line_width", PROPERTY_HINT_RANGE, "1,50,1,suffix:px"), "set_debug_path_custom_line_width", "get_debug_path_custom_line_width");
ADD_SIGNAL(MethodInfo("path_changed"));
ADD_SIGNAL(MethodInfo("target_reached"));
@@ -120,9 +138,15 @@ void NavigationAgent2D::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_POST_ENTER_TREE: {
// need to use POST_ENTER_TREE cause with normal ENTER_TREE not all required Nodes are ready.
- // cannot use READY as ready does not get called if Node is readded to SceneTree
+ // cannot use READY as ready does not get called if Node is re-added to SceneTree
set_agent_parent(get_parent());
set_physics_process_internal(true);
+
+#ifdef DEBUG_ENABLED
+ if (NavigationServer2D::get_singleton()->get_debug_enabled()) {
+ debug_path_dirty = true;
+ }
+#endif // DEBUG_ENABLED
} break;
case NOTIFICATION_PARENTED: {
@@ -142,6 +166,17 @@ void NavigationAgent2D::_notification(int p_what) {
set_physics_process_internal(false);
} break;
+ case NOTIFICATION_EXIT_TREE: {
+ set_agent_parent(nullptr);
+ set_physics_process_internal(false);
+
+#ifdef DEBUG_ENABLED
+ if (debug_path_instance.is_valid()) {
+ RenderingServer::get_singleton()->canvas_item_set_visible(debug_path_instance, false);
+ }
+#endif // DEBUG_ENABLED
+ } break;
+
case NOTIFICATION_PAUSED: {
if (agent_parent && !agent_parent->can_process()) {
map_before_pause = NavigationServer2D::get_singleton()->agent_get_map(get_rid());
@@ -162,11 +197,6 @@ void NavigationAgent2D::_notification(int p_what) {
}
} break;
- case NOTIFICATION_EXIT_TREE: {
- agent_parent = nullptr;
- set_physics_process_internal(false);
- } break;
-
case NOTIFICATION_INTERNAL_PHYSICS_PROCESS: {
if (agent_parent && target_position_submitted) {
if (avoidance_enabled) {
@@ -176,17 +206,22 @@ void NavigationAgent2D::_notification(int p_what) {
}
_check_distance_to_target();
}
+#ifdef DEBUG_ENABLED
+ if (debug_path_dirty) {
+ _update_debug_path();
+ }
+#endif // DEBUG_ENABLED
} break;
}
}
NavigationAgent2D::NavigationAgent2D() {
agent = NavigationServer2D::get_singleton()->agent_create();
- set_neighbor_distance(500.0);
- set_max_neighbors(10);
- set_time_horizon(20.0);
- set_radius(10.0);
- set_max_speed(200.0);
+ NavigationServer2D::get_singleton()->agent_set_neighbor_distance(agent, neighbor_distance);
+ NavigationServer2D::get_singleton()->agent_set_max_neighbors(agent, max_neighbors);
+ NavigationServer2D::get_singleton()->agent_set_time_horizon(agent, time_horizon);
+ NavigationServer2D::get_singleton()->agent_set_radius(agent, radius);
+ NavigationServer2D::get_singleton()->agent_set_max_speed(agent, max_speed);
// Preallocate query and result objects to improve performance.
navigation_query = Ref<NavigationPathQueryParameters2D>();
@@ -194,20 +229,38 @@ NavigationAgent2D::NavigationAgent2D() {
navigation_result = Ref<NavigationPathQueryResult2D>();
navigation_result.instantiate();
+
+#ifdef DEBUG_ENABLED
+ NavigationServer2D::get_singleton()->connect(SNAME("navigation_debug_changed"), callable_mp(this, &NavigationAgent2D::_navigation_debug_changed));
+#endif // DEBUG_ENABLED
}
NavigationAgent2D::~NavigationAgent2D() {
ERR_FAIL_NULL(NavigationServer2D::get_singleton());
NavigationServer2D::get_singleton()->free(agent);
agent = RID(); // Pointless
+
+#ifdef DEBUG_ENABLED
+ NavigationServer2D::get_singleton()->disconnect(SNAME("navigation_debug_changed"), callable_mp(this, &NavigationAgent2D::_navigation_debug_changed));
+
+ ERR_FAIL_NULL(RenderingServer::get_singleton());
+ if (debug_path_instance.is_valid()) {
+ RenderingServer::get_singleton()->free(debug_path_instance);
+ }
+#endif // DEBUG_ENABLED
}
void NavigationAgent2D::set_avoidance_enabled(bool p_enabled) {
+ if (avoidance_enabled == p_enabled) {
+ return;
+ }
+
avoidance_enabled = p_enabled;
+
if (avoidance_enabled) {
- NavigationServer2D::get_singleton()->agent_set_callback(agent, get_instance_id(), "_avoidance_done");
+ NavigationServer2D::get_singleton()->agent_set_callback(agent, callable_mp(this, &NavigationAgent2D::_avoidance_done));
} else {
- NavigationServer2D::get_singleton()->agent_set_callback(agent, ObjectID(), "_avoidance_done");
+ NavigationServer2D::get_singleton()->agent_set_callback(agent, Callable());
}
}
@@ -216,8 +269,13 @@ bool NavigationAgent2D::get_avoidance_enabled() const {
}
void NavigationAgent2D::set_agent_parent(Node *p_agent_parent) {
+ if (agent_parent == p_agent_parent) {
+ return;
+ }
+
// 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, ObjectID(), "_avoidance_done");
+ NavigationServer2D::get_singleton()->agent_set_callback(agent, Callable());
+
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);
@@ -226,8 +284,11 @@ void NavigationAgent2D::set_agent_parent(Node *p_agent_parent) {
} else {
NavigationServer2D::get_singleton()->agent_set_map(get_rid(), agent_parent->get_world_2d()->get_navigation_map());
}
+
// create new avoidance callback if enabled
- set_avoidance_enabled(avoidance_enabled);
+ if (avoidance_enabled) {
+ NavigationServer2D::get_singleton()->agent_set_callback(agent, callable_mp(this, &NavigationAgent2D::_avoidance_done));
+ }
} else {
agent_parent = nullptr;
NavigationServer2D::get_singleton()->agent_set_map(get_rid(), RID());
@@ -235,11 +296,13 @@ void NavigationAgent2D::set_agent_parent(Node *p_agent_parent) {
}
void NavigationAgent2D::set_navigation_layers(uint32_t p_navigation_layers) {
- bool navigation_layers_changed = navigation_layers != p_navigation_layers;
- navigation_layers = p_navigation_layers;
- if (navigation_layers_changed) {
- _request_repath();
+ if (navigation_layers == p_navigation_layers) {
+ return;
}
+
+ navigation_layers = p_navigation_layers;
+
+ _request_repath();
}
uint32_t NavigationAgent2D::get_navigation_layers() const {
@@ -273,7 +336,12 @@ void NavigationAgent2D::set_path_metadata_flags(BitField<NavigationPathQueryPara
}
void NavigationAgent2D::set_navigation_map(RID p_navigation_map) {
+ if (map_override == p_navigation_map) {
+ return;
+ }
+
map_override = p_navigation_map;
+
NavigationServer2D::get_singleton()->agent_set_map(agent, map_override);
_request_repath();
}
@@ -287,58 +355,99 @@ RID NavigationAgent2D::get_navigation_map() const {
return RID();
}
-void NavigationAgent2D::set_path_desired_distance(real_t p_dd) {
- path_desired_distance = p_dd;
+void NavigationAgent2D::set_path_desired_distance(real_t p_path_desired_distance) {
+ if (Math::is_equal_approx(path_desired_distance, p_path_desired_distance)) {
+ return;
+ }
+
+ path_desired_distance = p_path_desired_distance;
}
-void NavigationAgent2D::set_target_desired_distance(real_t p_dd) {
- target_desired_distance = p_dd;
+void NavigationAgent2D::set_target_desired_distance(real_t p_target_desired_distance) {
+ if (Math::is_equal_approx(target_desired_distance, p_target_desired_distance)) {
+ return;
+ }
+
+ target_desired_distance = p_target_desired_distance;
}
void NavigationAgent2D::set_radius(real_t p_radius) {
+ if (Math::is_equal_approx(radius, p_radius)) {
+ return;
+ }
+
radius = p_radius;
+
NavigationServer2D::get_singleton()->agent_set_radius(agent, radius);
}
void NavigationAgent2D::set_neighbor_distance(real_t p_distance) {
+ if (Math::is_equal_approx(neighbor_distance, p_distance)) {
+ return;
+ }
+
neighbor_distance = p_distance;
+
NavigationServer2D::get_singleton()->agent_set_neighbor_distance(agent, neighbor_distance);
}
void NavigationAgent2D::set_max_neighbors(int p_count) {
+ if (max_neighbors == p_count) {
+ return;
+ }
+
max_neighbors = p_count;
+
NavigationServer2D::get_singleton()->agent_set_max_neighbors(agent, max_neighbors);
}
void NavigationAgent2D::set_time_horizon(real_t p_time) {
+ if (Math::is_equal_approx(time_horizon, p_time)) {
+ return;
+ }
+
time_horizon = p_time;
+
NavigationServer2D::get_singleton()->agent_set_time_horizon(agent, time_horizon);
}
void NavigationAgent2D::set_max_speed(real_t p_max_speed) {
+ if (Math::is_equal_approx(max_speed, p_max_speed)) {
+ return;
+ }
+
max_speed = p_max_speed;
+
NavigationServer2D::get_singleton()->agent_set_max_speed(agent, max_speed);
}
-void NavigationAgent2D::set_path_max_distance(real_t p_pmd) {
- path_max_distance = p_pmd;
+void NavigationAgent2D::set_path_max_distance(real_t p_path_max_distance) {
+ if (Math::is_equal_approx(path_max_distance, p_path_max_distance)) {
+ return;
+ }
+
+ path_max_distance = p_path_max_distance;
}
real_t NavigationAgent2D::get_path_max_distance() {
return path_max_distance;
}
-void NavigationAgent2D::set_target_location(Vector2 p_location) {
- target_location = p_location;
+void NavigationAgent2D::set_target_position(Vector2 p_position) {
+ // Intentionally not checking for equality of the parameter, as we want to update the path even if the target position is the same in case the world changed.
+ // Revisit later when the navigation server can update the path without requesting a new path.
+
+ target_position = p_position;
target_position_submitted = true;
+
_request_repath();
}
-Vector2 NavigationAgent2D::get_target_location() const {
- return target_location;
+Vector2 NavigationAgent2D::get_target_position() const {
+ return target_position;
}
-Vector2 NavigationAgent2D::get_next_location() {
+Vector2 NavigationAgent2D::get_next_path_position() {
update_navigation();
const Vector<Vector2> &navigation_path = navigation_result->get_path();
@@ -352,7 +461,7 @@ Vector2 NavigationAgent2D::get_next_location() {
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);
+ return agent_parent->get_global_position().distance_to(target_position);
}
bool NavigationAgent2D::is_target_reached() const {
@@ -360,7 +469,7 @@ bool NavigationAgent2D::is_target_reached() const {
}
bool NavigationAgent2D::is_target_reachable() {
- return target_desired_distance >= get_final_location().distance_to(target_location);
+ return target_desired_distance >= get_final_position().distance_to(target_position);
}
bool NavigationAgent2D::is_navigation_finished() {
@@ -368,7 +477,7 @@ bool NavigationAgent2D::is_navigation_finished() {
return navigation_finished;
}
-Vector2 NavigationAgent2D::get_final_location() {
+Vector2 NavigationAgent2D::get_final_position() {
update_navigation();
const Vector<Vector2> &navigation_path = navigation_result->get_path();
@@ -379,10 +488,15 @@ Vector2 NavigationAgent2D::get_final_location() {
}
void NavigationAgent2D::set_velocity(Vector2 p_velocity) {
+ // Intentionally not checking for equality of the parameter.
+ // We need to always submit the velocity to the navigation server, even when it is the same, in order to run avoidance every frame.
+ // Revisit later when the navigation server can update avoidance without users resubmitting the velocity.
+
target_velocity = p_velocity;
+ velocity_submitted = true;
+
NavigationServer2D::get_singleton()->agent_set_target_velocity(agent, target_velocity);
NavigationServer2D::get_singleton()->agent_set_velocity(agent, prev_safe_velocity);
- velocity_submitted = true;
}
void NavigationAgent2D::_avoidance_done(Vector3 p_new_velocity) {
@@ -450,7 +564,7 @@ void NavigationAgent2D::update_navigation() {
if (reload_path) {
navigation_query->set_start_position(origin);
- navigation_query->set_target_position(target_location);
+ navigation_query->set_target_position(target_position);
navigation_query->set_navigation_layers(navigation_layers);
navigation_query->set_metadata_flags(path_metadata_flags);
@@ -461,6 +575,9 @@ void NavigationAgent2D::update_navigation() {
}
NavigationServer2D::get_singleton()->query_path(navigation_query, navigation_result);
+#ifdef DEBUG_ENABLED
+ debug_path_dirty = true;
+#endif // DEBUG_ENABLED
navigation_finished = false;
navigation_path_index = 0;
emit_signal(SNAME("path_changed"));
@@ -472,7 +589,7 @@ void NavigationAgent2D::update_navigation() {
// Check if we can advance the navigation path
if (navigation_finished == false) {
- // Advances to the next far away location.
+ // Advances to the next far away position.
const Vector<Vector2> &navigation_path = navigation_result->get_path();
const Vector<int32_t> &navigation_path_types = navigation_result->get_path_types();
const TypedArray<RID> &navigation_path_rids = navigation_result->get_path_rids();
@@ -482,7 +599,7 @@ void NavigationAgent2D::update_navigation() {
Dictionary details;
const Vector2 waypoint = navigation_path[navigation_path_index];
- details[SNAME("location")] = waypoint;
+ details[SNAME("position")] = waypoint;
int waypoint_type = -1;
if (path_metadata_flags.has_flag(NavigationPathQueryParameters2D::PathMetadataFlags::PATH_METADATA_INCLUDE_TYPES)) {
@@ -547,3 +664,141 @@ void NavigationAgent2D::_check_distance_to_target() {
}
}
}
+
+////////DEBUG////////////////////////////////////////////////////////////
+
+void NavigationAgent2D::set_debug_enabled(bool p_enabled) {
+#ifdef DEBUG_ENABLED
+ if (debug_enabled == p_enabled) {
+ return;
+ }
+
+ debug_enabled = p_enabled;
+ debug_path_dirty = true;
+#endif // DEBUG_ENABLED
+}
+
+bool NavigationAgent2D::get_debug_enabled() const {
+ return debug_enabled;
+}
+
+void NavigationAgent2D::set_debug_use_custom(bool p_enabled) {
+#ifdef DEBUG_ENABLED
+ if (debug_use_custom == p_enabled) {
+ return;
+ }
+
+ debug_use_custom = p_enabled;
+ debug_path_dirty = true;
+#endif // DEBUG_ENABLED
+}
+
+bool NavigationAgent2D::get_debug_use_custom() const {
+ return debug_use_custom;
+}
+
+void NavigationAgent2D::set_debug_path_custom_color(Color p_color) {
+#ifdef DEBUG_ENABLED
+ if (debug_path_custom_color == p_color) {
+ return;
+ }
+
+ debug_path_custom_color = p_color;
+ debug_path_dirty = true;
+#endif // DEBUG_ENABLED
+}
+
+Color NavigationAgent2D::get_debug_path_custom_color() const {
+ return debug_path_custom_color;
+}
+
+void NavigationAgent2D::set_debug_path_custom_point_size(float p_point_size) {
+#ifdef DEBUG_ENABLED
+ if (Math::is_equal_approx(debug_path_custom_point_size, p_point_size)) {
+ return;
+ }
+
+ debug_path_custom_point_size = MAX(0.1, p_point_size);
+ debug_path_dirty = true;
+#endif // DEBUG_ENABLED
+}
+
+float NavigationAgent2D::get_debug_path_custom_point_size() const {
+ return debug_path_custom_point_size;
+}
+
+void NavigationAgent2D::set_debug_path_custom_line_width(float p_line_width) {
+#ifdef DEBUG_ENABLED
+ if (Math::is_equal_approx(debug_path_custom_line_width, p_line_width)) {
+ return;
+ }
+
+ debug_path_custom_line_width = p_line_width;
+ debug_path_dirty = true;
+#endif // DEBUG_ENABLED
+}
+
+float NavigationAgent2D::get_debug_path_custom_line_width() const {
+ return debug_path_custom_line_width;
+}
+
+#ifdef DEBUG_ENABLED
+void NavigationAgent2D::_navigation_debug_changed() {
+ debug_path_dirty = true;
+}
+
+void NavigationAgent2D::_update_debug_path() {
+ if (!debug_path_dirty) {
+ return;
+ }
+ debug_path_dirty = false;
+
+ if (!debug_path_instance.is_valid()) {
+ debug_path_instance = RenderingServer::get_singleton()->canvas_item_create();
+ }
+
+ RenderingServer::get_singleton()->canvas_item_clear(debug_path_instance);
+
+ if (!(debug_enabled && NavigationServer2D::get_singleton()->get_debug_navigation_enable_agent_paths())) {
+ return;
+ }
+
+ if (!(agent_parent && agent_parent->is_inside_tree())) {
+ return;
+ }
+
+ RenderingServer::get_singleton()->canvas_item_set_parent(debug_path_instance, agent_parent->get_canvas());
+ RenderingServer::get_singleton()->canvas_item_set_visible(debug_path_instance, agent_parent->is_visible_in_tree());
+
+ const Vector<Vector2> &navigation_path = navigation_result->get_path();
+
+ if (navigation_path.size() <= 1) {
+ return;
+ }
+
+ Color debug_path_color = NavigationServer2D::get_singleton()->get_debug_navigation_agent_path_color();
+ if (debug_use_custom) {
+ debug_path_color = debug_path_custom_color;
+ }
+
+ Vector<Color> debug_path_colors;
+ debug_path_colors.resize(navigation_path.size());
+ debug_path_colors.fill(debug_path_color);
+
+ RenderingServer::get_singleton()->canvas_item_add_polyline(debug_path_instance, navigation_path, debug_path_colors, debug_path_custom_line_width, false);
+
+ float point_size = NavigationServer2D::get_singleton()->get_debug_navigation_agent_path_point_size();
+ float half_point_size = point_size * 0.5;
+
+ if (debug_use_custom) {
+ point_size = debug_path_custom_point_size;
+ half_point_size = debug_path_custom_point_size * 0.5;
+ }
+
+ for (int i = 0; i < navigation_path.size(); i++) {
+ const Vector2 &vert = navigation_path[i];
+ Rect2 path_point_rect = Rect2(vert.x - half_point_size, vert.y - half_point_size, point_size, point_size);
+ RenderingServer::get_singleton()->canvas_item_add_rect(debug_path_instance, path_point_rect, debug_path_color);
+ }
+}
+#endif // DEBUG_ENABLED
diff --git a/scene/2d/navigation_agent_2d.h b/scene/2d/navigation_agent_2d.h
index 113b1e9623..1614c70229 100644
--- a/scene/2d/navigation_agent_2d.h
+++ b/scene/2d/navigation_agent_2d.h
@@ -50,17 +50,16 @@ class NavigationAgent2D : public Node {
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;
- real_t radius = 0.0;
- real_t neighbor_distance = 0.0;
- int max_neighbors = 0;
- real_t time_horizon = 0.0;
- real_t max_speed = 0.0;
-
- real_t path_max_distance = 3.0;
-
- Vector2 target_location;
+ real_t path_desired_distance = 20.0;
+ real_t target_desired_distance = 10.0;
+ real_t radius = 10.0;
+ real_t neighbor_distance = 500.0;
+ int max_neighbors = 10;
+ real_t time_horizon = 1.0;
+ real_t max_speed = 100.0;
+ real_t path_max_distance = 100.0;
+
+ Vector2 target_position;
bool target_position_submitted = false;
Ref<NavigationPathQueryParameters2D> navigation_query;
Ref<NavigationPathQueryResult2D> navigation_result;
@@ -74,6 +73,22 @@ class NavigationAgent2D : public Node {
// No initialized on purpose
uint32_t update_frame_id = 0;
+ // Debug properties for exposed bindings
+ bool debug_enabled = false;
+ float debug_path_custom_point_size = 4.0;
+ float debug_path_custom_line_width = 1.0;
+ bool debug_use_custom = false;
+ Color debug_path_custom_color = Color(1.0, 1.0, 1.0, 1.0);
+#ifdef DEBUG_ENABLED
+ // Debug properties internal only
+ bool debug_path_dirty = true;
+ RID debug_path_instance;
+
+private:
+ void _navigation_debug_changed();
+ void _update_debug_path();
+#endif // DEBUG_ENABLED
+
protected:
static void _bind_methods();
void _notification(int p_what);
@@ -143,10 +158,10 @@ public:
void set_path_max_distance(real_t p_pmd);
real_t get_path_max_distance();
- void set_target_location(Vector2 p_location);
- Vector2 get_target_location() const;
+ void set_target_position(Vector2 p_position);
+ Vector2 get_target_position() const;
- Vector2 get_next_location();
+ Vector2 get_next_path_position();
Ref<NavigationPathQueryResult2D> get_current_navigation_result() const {
return navigation_result;
@@ -162,13 +177,28 @@ public:
bool is_target_reached() const;
bool is_target_reachable();
bool is_navigation_finished();
- Vector2 get_final_location();
+ Vector2 get_final_position();
void set_velocity(Vector2 p_velocity);
void _avoidance_done(Vector3 p_new_velocity);
PackedStringArray get_configuration_warnings() const override;
+ void set_debug_enabled(bool p_enabled);
+ bool get_debug_enabled() const;
+
+ void set_debug_use_custom(bool p_enabled);
+ bool get_debug_use_custom() const;
+
+ void set_debug_path_custom_color(Color p_color);
+ Color get_debug_path_custom_color() const;
+
+ void set_debug_path_custom_point_size(float p_point_size);
+ float get_debug_path_custom_point_size() const;
+
+ void set_debug_path_custom_line_width(float p_line_width);
+ float get_debug_path_custom_line_width() const;
+
private:
void update_navigation();
void _request_repath();
diff --git a/scene/2d/navigation_link_2d.cpp b/scene/2d/navigation_link_2d.cpp
index 9ef0ba617e..26dca40176 100644
--- a/scene/2d/navigation_link_2d.cpp
+++ b/scene/2d/navigation_link_2d.cpp
@@ -48,11 +48,11 @@ void NavigationLink2D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_navigation_layer_value", "layer_number", "value"), &NavigationLink2D::set_navigation_layer_value);
ClassDB::bind_method(D_METHOD("get_navigation_layer_value", "layer_number"), &NavigationLink2D::get_navigation_layer_value);
- ClassDB::bind_method(D_METHOD("set_start_location", "location"), &NavigationLink2D::set_start_location);
- ClassDB::bind_method(D_METHOD("get_start_location"), &NavigationLink2D::get_start_location);
+ ClassDB::bind_method(D_METHOD("set_start_position", "position"), &NavigationLink2D::set_start_position);
+ ClassDB::bind_method(D_METHOD("get_start_position"), &NavigationLink2D::get_start_position);
- ClassDB::bind_method(D_METHOD("set_end_location", "location"), &NavigationLink2D::set_end_location);
- ClassDB::bind_method(D_METHOD("get_end_location"), &NavigationLink2D::get_end_location);
+ ClassDB::bind_method(D_METHOD("set_end_position", "position"), &NavigationLink2D::set_end_position);
+ ClassDB::bind_method(D_METHOD("get_end_position"), &NavigationLink2D::get_end_position);
ClassDB::bind_method(D_METHOD("set_enter_cost", "enter_cost"), &NavigationLink2D::set_enter_cost);
ClassDB::bind_method(D_METHOD("get_enter_cost"), &NavigationLink2D::get_enter_cost);
@@ -63,12 +63,38 @@ void NavigationLink2D::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "enabled"), "set_enabled", "is_enabled");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "bidirectional"), "set_bidirectional", "is_bidirectional");
ADD_PROPERTY(PropertyInfo(Variant::INT, "navigation_layers", PROPERTY_HINT_LAYERS_2D_NAVIGATION), "set_navigation_layers", "get_navigation_layers");
- ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "start_location"), "set_start_location", "get_start_location");
- ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "end_location"), "set_end_location", "get_end_location");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "start_position"), "set_start_position", "get_start_position");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "end_position"), "set_end_position", "get_end_position");
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
+bool NavigationLink2D::_set(const StringName &p_name, const Variant &p_value) {
+ if (p_name == "start_location") {
+ set_start_position(p_value);
+ return true;
+ }
+ if (p_name == "end_location") {
+ set_end_position(p_value);
+ return true;
+ }
+ return false;
+}
+
+bool NavigationLink2D::_get(const StringName &p_name, Variant &r_ret) const {
+ if (p_name == "start_location") {
+ r_ret = get_start_position();
+ return true;
+ }
+ if (p_name == "end_location") {
+ r_ret = get_end_position();
+ return true;
+ }
+ return false;
+}
+#endif // DISABLE_DEPRECATED
+
void NavigationLink2D::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
@@ -77,15 +103,15 @@ void NavigationLink2D::_notification(int p_what) {
// Update global positions for the link.
Transform2D gt = get_global_transform();
- NavigationServer2D::get_singleton()->link_set_start_location(link, gt.xform(start_location));
- NavigationServer2D::get_singleton()->link_set_end_location(link, gt.xform(end_location));
+ NavigationServer2D::get_singleton()->link_set_start_position(link, gt.xform(start_position));
+ NavigationServer2D::get_singleton()->link_set_end_position(link, gt.xform(end_position));
}
} break;
case NOTIFICATION_TRANSFORM_CHANGED: {
// Update global positions for the link.
Transform2D gt = get_global_transform();
- NavigationServer2D::get_singleton()->link_set_start_location(link, gt.xform(start_location));
- NavigationServer2D::get_singleton()->link_set_end_location(link, gt.xform(end_location));
+ NavigationServer2D::get_singleton()->link_set_start_position(link, gt.xform(start_position));
+ NavigationServer2D::get_singleton()->link_set_end_position(link, gt.xform(end_position));
} break;
case NOTIFICATION_EXIT_TREE: {
NavigationServer2D::get_singleton()->link_set_map(link, RID());
@@ -102,9 +128,9 @@ void NavigationLink2D::_notification(int p_what) {
real_t radius = NavigationServer2D::get_singleton()->map_get_link_connection_radius(get_world_2d()->get_navigation_map());
- draw_line(get_start_location(), get_end_location(), color);
- draw_arc(get_start_location(), radius, 0, Math_TAU, 10, color);
- draw_arc(get_end_location(), radius, 0, Math_TAU, 10, color);
+ draw_line(get_start_position(), get_end_position(), color);
+ draw_arc(get_start_position(), radius, 0, Math_TAU, 10, color);
+ draw_arc(get_end_position(), radius, 0, Math_TAU, 10, color);
}
#endif // DEBUG_ENABLED
} break;
@@ -119,14 +145,14 @@ Rect2 NavigationLink2D::_edit_get_rect() const {
real_t radius = NavigationServer2D::get_singleton()->map_get_link_connection_radius(get_world_2d()->get_navigation_map());
- Rect2 rect(get_start_location(), Size2());
- rect.expand_to(get_end_location());
+ Rect2 rect(get_start_position(), Size2());
+ rect.expand_to(get_end_position());
rect.grow_by(radius);
return rect;
}
bool NavigationLink2D::_edit_is_selected_on_click(const Point2 &p_point, double p_tolerance) const {
- Point2 segment[2] = { get_start_location(), get_end_location() };
+ Point2 segment[2] = { get_start_position(), get_end_position() };
Vector2 closest_point = Geometry2D::get_closest_point_to_segment(p_point, segment);
return p_point.distance_to(closest_point) < p_tolerance;
@@ -199,19 +225,19 @@ bool NavigationLink2D::get_navigation_layer_value(int p_layer_number) const {
return get_navigation_layers() & (1 << (p_layer_number - 1));
}
-void NavigationLink2D::set_start_location(Vector2 p_location) {
- if (start_location.is_equal_approx(p_location)) {
+void NavigationLink2D::set_start_position(Vector2 p_position) {
+ if (start_position.is_equal_approx(p_position)) {
return;
}
- start_location = p_location;
+ start_position = p_position;
if (!is_inside_tree()) {
return;
}
Transform2D gt = get_global_transform();
- NavigationServer2D::get_singleton()->link_set_start_location(link, gt.xform(start_location));
+ NavigationServer2D::get_singleton()->link_set_start_position(link, gt.xform(start_position));
update_configuration_warnings();
@@ -222,19 +248,19 @@ void NavigationLink2D::set_start_location(Vector2 p_location) {
#endif // DEBUG_ENABLED
}
-void NavigationLink2D::set_end_location(Vector2 p_location) {
- if (end_location.is_equal_approx(p_location)) {
+void NavigationLink2D::set_end_position(Vector2 p_position) {
+ if (end_position.is_equal_approx(p_position)) {
return;
}
- end_location = p_location;
+ end_position = p_position;
if (!is_inside_tree()) {
return;
}
Transform2D gt = get_global_transform();
- NavigationServer2D::get_singleton()->link_set_end_location(link, gt.xform(end_location));
+ NavigationServer2D::get_singleton()->link_set_end_position(link, gt.xform(end_position));
update_configuration_warnings();
@@ -270,8 +296,8 @@ void NavigationLink2D::set_travel_cost(real_t p_travel_cost) {
PackedStringArray NavigationLink2D::get_configuration_warnings() const {
PackedStringArray warnings = Node::get_configuration_warnings();
- if (start_location.is_equal_approx(end_location)) {
- warnings.push_back(RTR("NavigationLink2D start location should be different than the end location to be useful."));
+ if (start_position.is_equal_approx(end_position)) {
+ warnings.push_back(RTR("NavigationLink2D start position should be different than the end position to be useful."));
}
return warnings;
@@ -282,6 +308,7 @@ NavigationLink2D::NavigationLink2D() {
NavigationServer2D::get_singleton()->link_set_owner_id(link, get_instance_id());
set_notify_transform(true);
+ set_hide_clip_children(true);
}
NavigationLink2D::~NavigationLink2D() {
diff --git a/scene/2d/navigation_link_2d.h b/scene/2d/navigation_link_2d.h
index e14ee5adb9..5bf2a72358 100644
--- a/scene/2d/navigation_link_2d.h
+++ b/scene/2d/navigation_link_2d.h
@@ -40,8 +40,8 @@ class NavigationLink2D : public Node2D {
RID link;
bool bidirectional = true;
uint32_t navigation_layers = 1;
- Vector2 end_location;
- Vector2 start_location;
+ Vector2 end_position;
+ Vector2 start_position;
real_t enter_cost = 0.0;
real_t travel_cost = 1.0;
@@ -49,6 +49,11 @@ protected:
static void _bind_methods();
void _notification(int p_what);
+#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;
@@ -67,11 +72,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_start_location(Vector2 p_location);
- Vector2 get_start_location() const { return start_location; }
+ void set_start_position(Vector2 p_position);
+ Vector2 get_start_position() const { return start_position; }
- void set_end_location(Vector2 p_location);
- Vector2 get_end_location() const { return end_location; }
+ void set_end_position(Vector2 p_position);
+ Vector2 get_end_position() const { return end_position; }
void set_enter_cost(real_t p_enter_cost);
real_t get_enter_cost() const { return enter_cost; }
diff --git a/scene/2d/navigation_obstacle_2d.cpp b/scene/2d/navigation_obstacle_2d.cpp
index 4bd170301a..d7ef77e25b 100644
--- a/scene/2d/navigation_obstacle_2d.cpp
+++ b/scene/2d/navigation_obstacle_2d.cpp
@@ -185,6 +185,10 @@ real_t NavigationObstacle2D::estimate_agent_radius() const {
}
void NavigationObstacle2D::set_agent_parent(Node *p_agent_parent) {
+ if (parent_node2d == p_agent_parent) {
+ return;
+ }
+
if (Object::cast_to<Node2D>(p_agent_parent) != nullptr) {
parent_node2d = Object::cast_to<Node2D>(p_agent_parent);
if (map_override.is_valid()) {
@@ -200,7 +204,12 @@ void NavigationObstacle2D::set_agent_parent(Node *p_agent_parent) {
}
void NavigationObstacle2D::set_navigation_map(RID p_navigation_map) {
+ if (map_override == p_navigation_map) {
+ return;
+ }
+
map_override = p_navigation_map;
+
NavigationServer2D::get_singleton()->agent_set_map(agent, map_override);
}
@@ -214,13 +223,23 @@ RID NavigationObstacle2D::get_navigation_map() const {
}
void NavigationObstacle2D::set_estimate_radius(bool p_estimate_radius) {
+ if (estimate_radius == p_estimate_radius) {
+ return;
+ }
+
estimate_radius = p_estimate_radius;
+
notify_property_list_changed();
reevaluate_agent_radius();
}
void NavigationObstacle2D::set_radius(real_t p_radius) {
ERR_FAIL_COND_MSG(p_radius <= 0.0, "Radius must be greater than 0.");
+ if (Math::is_equal_approx(radius, p_radius)) {
+ return;
+ }
+
radius = p_radius;
+
reevaluate_agent_radius();
}
diff --git a/scene/2d/navigation_region_2d.cpp b/scene/2d/navigation_region_2d.cpp
index a205e704ba..3484a9de65 100644
--- a/scene/2d/navigation_region_2d.cpp
+++ b/scene/2d/navigation_region_2d.cpp
@@ -48,10 +48,10 @@ void NavigationRegion2D::set_enabled(bool p_enabled) {
if (!enabled) {
NavigationServer2D::get_singleton()->region_set_map(region, RID());
- NavigationServer2D::get_singleton_mut()->disconnect("map_changed", callable_mp(this, &NavigationRegion2D::_map_changed));
+ NavigationServer2D::get_singleton()->disconnect("map_changed", callable_mp(this, &NavigationRegion2D::_map_changed));
} else {
NavigationServer2D::get_singleton()->region_set_map(region, get_world_2d()->get_navigation_map());
- NavigationServer2D::get_singleton_mut()->connect("map_changed", callable_mp(this, &NavigationRegion2D::_map_changed));
+ NavigationServer2D::get_singleton()->connect("map_changed", callable_mp(this, &NavigationRegion2D::_map_changed));
}
#ifdef DEBUG_ENABLED
@@ -150,7 +150,7 @@ void NavigationRegion2D::_notification(int p_what) {
case NOTIFICATION_ENTER_TREE: {
if (enabled) {
NavigationServer2D::get_singleton()->region_set_map(region, get_world_2d()->get_navigation_map());
- NavigationServer2D::get_singleton_mut()->connect("map_changed", callable_mp(this, &NavigationRegion2D::_map_changed));
+ NavigationServer2D::get_singleton()->connect("map_changed", callable_mp(this, &NavigationRegion2D::_map_changed));
}
} break;
@@ -161,7 +161,7 @@ void NavigationRegion2D::_notification(int p_what) {
case NOTIFICATION_EXIT_TREE: {
NavigationServer2D::get_singleton()->region_set_map(region, RID());
if (enabled) {
- NavigationServer2D::get_singleton_mut()->disconnect("map_changed", callable_mp(this, &NavigationRegion2D::_map_changed));
+ NavigationServer2D::get_singleton()->disconnect("map_changed", callable_mp(this, &NavigationRegion2D::_map_changed));
}
} break;
@@ -330,6 +330,7 @@ bool NavigationRegion2D::_get(const StringName &p_name, Variant &r_ret) const {
NavigationRegion2D::NavigationRegion2D() {
set_notify_transform(true);
+ set_hide_clip_children(true);
region = NavigationServer2D::get_singleton()->region_create();
NavigationServer2D::get_singleton()->region_set_owner_id(region, get_instance_id());
@@ -337,8 +338,8 @@ NavigationRegion2D::NavigationRegion2D() {
NavigationServer2D::get_singleton()->region_set_travel_cost(region, get_travel_cost());
#ifdef DEBUG_ENABLED
- NavigationServer3D::get_singleton_mut()->connect("map_changed", callable_mp(this, &NavigationRegion2D::_map_changed));
- NavigationServer3D::get_singleton_mut()->connect("navigation_debug_changed", callable_mp(this, &NavigationRegion2D::_map_changed));
+ NavigationServer3D::get_singleton()->connect("map_changed", callable_mp(this, &NavigationRegion2D::_map_changed));
+ NavigationServer3D::get_singleton()->connect("navigation_debug_changed", callable_mp(this, &NavigationRegion2D::_map_changed));
#endif // DEBUG_ENABLED
}
@@ -347,7 +348,7 @@ NavigationRegion2D::~NavigationRegion2D() {
NavigationServer2D::get_singleton()->free(region);
#ifdef DEBUG_ENABLED
- NavigationServer3D::get_singleton_mut()->disconnect("map_changed", callable_mp(this, &NavigationRegion2D::_map_changed));
- NavigationServer3D::get_singleton_mut()->disconnect("navigation_debug_changed", callable_mp(this, &NavigationRegion2D::_map_changed));
+ NavigationServer3D::get_singleton()->disconnect("map_changed", callable_mp(this, &NavigationRegion2D::_map_changed));
+ NavigationServer3D::get_singleton()->disconnect("navigation_debug_changed", callable_mp(this, &NavigationRegion2D::_map_changed));
#endif // DEBUG_ENABLED
}
diff --git a/scene/2d/node_2d.cpp b/scene/2d/node_2d.cpp
index 0b7cdafdef..1c0efe773f 100644
--- a/scene/2d/node_2d.cpp
+++ b/scene/2d/node_2d.cpp
@@ -133,6 +133,14 @@ void Node2D::_update_transform() {
_notify_transform();
}
+void Node2D::reparent(Node *p_parent, bool p_keep_global_transform) {
+ Transform2D temp = get_global_transform();
+ Node::reparent(p_parent);
+ if (p_keep_global_transform) {
+ set_global_transform(temp);
+ }
+}
+
void Node2D::set_position(const Point2 &p_pos) {
if (_xform_dirty) {
const_cast<Node2D *>(this)->_update_xform_values();
diff --git a/scene/2d/node_2d.h b/scene/2d/node_2d.h
index e332745da5..119e23cd98 100644
--- a/scene/2d/node_2d.h
+++ b/scene/2d/node_2d.h
@@ -70,6 +70,7 @@ public:
virtual void _edit_set_rect(const Rect2 &p_edit_rect) override;
#endif
+ virtual void reparent(Node *p_parent, bool p_keep_global_transform = true) override;
void set_position(const Point2 &p_pos);
void set_rotation(real_t p_radians);
diff --git a/scene/2d/path_2d.cpp b/scene/2d/path_2d.cpp
index 09f4406ffe..5036dd30b1 100644
--- a/scene/2d/path_2d.cpp
+++ b/scene/2d/path_2d.cpp
@@ -31,6 +31,7 @@
#include "path_2d.h"
#include "core/math/geometry_2d.h"
+#include "scene/main/timer.h"
#ifdef TOOLS_ENABLED
#include "editor/editor_scale.h"
@@ -171,6 +172,12 @@ void Path2D::_curve_changed() {
}
queue_redraw();
+ for (int i = 0; i < get_child_count(); i++) {
+ PathFollow2D *follow = Object::cast_to<PathFollow2D>(get_child(i));
+ if (follow) {
+ follow->path_changed();
+ }
+ }
}
void Path2D::set_curve(const Ref<Curve2D> &p_curve) {
@@ -200,6 +207,14 @@ void Path2D::_bind_methods() {
/////////////////////////////////////////////////////////////////////////////////
+void PathFollow2D::path_changed() {
+ if (update_timer && !update_timer->is_stopped()) {
+ update_timer->start();
+ } else {
+ _update_transform();
+ }
+}
+
void PathFollow2D::_update_transform() {
if (!path) {
return;
@@ -230,6 +245,16 @@ void PathFollow2D::_update_transform() {
void PathFollow2D::_notification(int p_what) {
switch (p_what) {
+ case NOTIFICATION_READY: {
+ if (Engine::get_singleton()->is_editor_hint()) {
+ update_timer = memnew(Timer);
+ update_timer->set_wait_time(0.2);
+ update_timer->set_one_shot(true);
+ update_timer->connect("timeout", callable_mp(this, &PathFollow2D::_update_transform));
+ add_child(update_timer, false, Node::INTERNAL_MODE_BACK);
+ }
+ } break;
+
case NOTIFICATION_ENTER_TREE: {
path = Object::cast_to<Path2D>(get_parent());
if (path) {
diff --git a/scene/2d/path_2d.h b/scene/2d/path_2d.h
index 884743dd2a..89c77c49eb 100644
--- a/scene/2d/path_2d.h
+++ b/scene/2d/path_2d.h
@@ -34,6 +34,8 @@
#include "scene/2d/node_2d.h"
#include "scene/resources/curve.h"
+class Timer;
+
class Path2D : public Node2D {
GDCLASS(Path2D, Node2D);
@@ -65,6 +67,7 @@ public:
private:
Path2D *path = nullptr;
real_t progress = 0.0;
+ Timer *update_timer = nullptr;
real_t h_offset = 0.0;
real_t v_offset = 0.0;
real_t lookahead = 4.0;
@@ -81,6 +84,8 @@ protected:
static void _bind_methods();
public:
+ void path_changed();
+
void set_progress(real_t p_progress);
real_t get_progress() const;
diff --git a/scene/2d/physics_body_2d.cpp b/scene/2d/physics_body_2d.cpp
index 9fee99c6a7..1721bcde3b 100644
--- a/scene/2d/physics_body_2d.cpp
+++ b/scene/2d/physics_body_2d.cpp
@@ -434,6 +434,8 @@ struct _RigidBody2DInOut {
};
void RigidBody2D::_body_state_changed(PhysicsDirectBodyState2D *p_state) {
+ lock_callback();
+
set_block_transform_notify(true); // don't want notify (would feedback loop)
if (!freeze || freeze_mode != FREEZE_MODE_KINEMATIC) {
set_global_transform(p_state->get_transform());
@@ -527,6 +529,8 @@ void RigidBody2D::_body_state_changed(PhysicsDirectBodyState2D *p_state) {
contact_monitor->locked = false;
}
+
+ unlock_callback();
}
void RigidBody2D::_apply_body_mode() {
diff --git a/scene/2d/ray_cast_2d.cpp b/scene/2d/ray_cast_2d.cpp
index 39f88a0b5e..988ea87054 100644
--- a/scene/2d/ray_cast_2d.cpp
+++ b/scene/2d/ray_cast_2d.cpp
@@ -370,4 +370,5 @@ void RayCast2D::_bind_methods() {
}
RayCast2D::RayCast2D() {
+ set_hide_clip_children(true);
}
diff --git a/scene/2d/remote_transform_2d.cpp b/scene/2d/remote_transform_2d.cpp
index e9ce9560d3..c6730f7ab2 100644
--- a/scene/2d/remote_transform_2d.cpp
+++ b/scene/2d/remote_transform_2d.cpp
@@ -219,4 +219,5 @@ void RemoteTransform2D::_bind_methods() {
RemoteTransform2D::RemoteTransform2D() {
set_notify_transform(true);
+ set_hide_clip_children(true);
}
diff --git a/scene/2d/shape_cast_2d.cpp b/scene/2d/shape_cast_2d.cpp
index 24821858cf..bafb83361a 100644
--- a/scene/2d/shape_cast_2d.cpp
+++ b/scene/2d/shape_cast_2d.cpp
@@ -472,3 +472,7 @@ void ShapeCast2D::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "collide_with_areas", PROPERTY_HINT_LAYERS_3D_PHYSICS), "set_collide_with_areas", "is_collide_with_areas_enabled");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "collide_with_bodies", PROPERTY_HINT_LAYERS_3D_PHYSICS), "set_collide_with_bodies", "is_collide_with_bodies_enabled");
}
+
+ShapeCast2D::ShapeCast2D() {
+ set_hide_clip_children(true);
+}
diff --git a/scene/2d/shape_cast_2d.h b/scene/2d/shape_cast_2d.h
index 182614a721..8a62b799f8 100644
--- a/scene/2d/shape_cast_2d.h
+++ b/scene/2d/shape_cast_2d.h
@@ -119,6 +119,8 @@ public:
void clear_exceptions();
PackedStringArray get_configuration_warnings() const override;
+
+ ShapeCast2D();
};
#endif // SHAPE_CAST_2D_H
diff --git a/scene/2d/skeleton_2d.cpp b/scene/2d/skeleton_2d.cpp
index 02388a7681..96711bbe72 100644
--- a/scene/2d/skeleton_2d.cpp
+++ b/scene/2d/skeleton_2d.cpp
@@ -519,6 +519,7 @@ Bone2D::Bone2D() {
bone_angle = 0;
autocalculate_length_and_angle = true;
set_notify_local_transform(true);
+ set_hide_clip_children(true);
//this is a clever hack so the bone knows no rest has been set yet, allowing to show an error.
for (int i = 0; i < 3; i++) {
rest[i] = Vector2(0, 0);
@@ -562,7 +563,7 @@ void Skeleton2D::_get_property_list(List<PropertyInfo> *p_list) const {
PropertyInfo(Variant::OBJECT, PNAME("modification_stack"),
PROPERTY_HINT_RESOURCE_TYPE,
"SkeletonModificationStack2D",
- PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_DEFERRED_SET_RESOURCE | PROPERTY_USAGE_DO_NOT_SHARE_ON_DUPLICATE));
+ PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_DEFERRED_SET_RESOURCE | PROPERTY_USAGE_ALWAYS_DUPLICATE));
}
void Skeleton2D::_make_bone_setup_dirty() {
@@ -801,6 +802,7 @@ void Skeleton2D::_bind_methods() {
Skeleton2D::Skeleton2D() {
skeleton = RS::get_singleton()->skeleton_create();
set_notify_transform(true);
+ set_hide_clip_children(true);
}
Skeleton2D::~Skeleton2D() {
diff --git a/scene/2d/tile_map.cpp b/scene/2d/tile_map.cpp
index ed07d5d11e..95bf67d38d 100644
--- a/scene/2d/tile_map.cpp
+++ b/scene/2d/tile_map.cpp
@@ -482,7 +482,11 @@ void TileMap::set_selected_layer(int p_layer_id) {
ERR_FAIL_COND(p_layer_id < -1 || p_layer_id >= (int)layers.size());
selected_layer = p_layer_id;
emit_signal(SNAME("changed"));
- _make_all_quadrants_dirty();
+
+ // Update the layers modulation.
+ for (unsigned int layer = 0; layer < layers.size(); layer++) {
+ _rendering_update_layer(layer);
+ }
}
int TileMap::get_selected_layer() const {
@@ -653,8 +657,7 @@ void TileMap::set_layer_modulate(int p_layer, Color p_modulate) {
}
ERR_FAIL_INDEX(p_layer, (int)layers.size());
layers[p_layer].modulate = p_modulate;
- _clear_layer_internals(p_layer);
- _recreate_layer_internals(p_layer);
+ _rendering_update_layer(p_layer);
emit_signal(SNAME("changed"));
}
@@ -703,8 +706,7 @@ void TileMap::set_layer_z_index(int p_layer, int p_z_index) {
}
ERR_FAIL_INDEX(p_layer, (int)layers.size());
layers[p_layer].z_index = p_z_index;
- _clear_layer_internals(p_layer);
- _recreate_layer_internals(p_layer);
+ _rendering_update_layer(p_layer);
emit_signal(SNAME("changed"));
update_configuration_warnings();
@@ -801,10 +803,10 @@ void TileMap::_make_quadrant_dirty(HashMap<Vector2i, TileMapQuadrant>::Iterator
void TileMap::_make_all_quadrants_dirty() {
// Make all quandrants dirty, then trigger an update later.
- for (unsigned int layer = 0; layer < layers.size(); layer++) {
- for (KeyValue<Vector2i, TileMapQuadrant> &E : layers[layer].quadrant_map) {
+ for (TileMapLayer &layer : layers) {
+ for (KeyValue<Vector2i, TileMapQuadrant> &E : layer.quadrant_map) {
if (!E.value.dirty_list_element.in_list()) {
- layers[layer].dirty_quadrant_list.add(&E.value.dirty_list_element);
+ layer.dirty_quadrant_list.add(&E.value.dirty_list_element);
}
}
}
@@ -1012,8 +1014,8 @@ void TileMap::_rendering_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_ENTER_CANVAS: {
bool node_visible = is_visible_in_tree();
- for (int layer = 0; layer < (int)layers.size(); layer++) {
- for (KeyValue<Vector2i, TileMapQuadrant> &E_quadrant : layers[layer].quadrant_map) {
+ for (TileMapLayer &layer : layers) {
+ for (KeyValue<Vector2i, TileMapQuadrant> &E_quadrant : layer.quadrant_map) {
TileMapQuadrant &q = E_quadrant.value;
for (const KeyValue<Vector2i, RID> &kv : q.occluders) {
Transform2D xform;
@@ -1028,8 +1030,8 @@ void TileMap::_rendering_notification(int p_what) {
case NOTIFICATION_VISIBILITY_CHANGED: {
bool node_visible = is_visible_in_tree();
- for (int layer = 0; layer < (int)layers.size(); layer++) {
- for (KeyValue<Vector2i, TileMapQuadrant> &E_quadrant : layers[layer].quadrant_map) {
+ for (TileMapLayer &layer : layers) {
+ for (KeyValue<Vector2i, TileMapQuadrant> &E_quadrant : layer.quadrant_map) {
TileMapQuadrant &q = E_quadrant.value;
// Update occluders transform.
@@ -1048,8 +1050,8 @@ void TileMap::_rendering_notification(int p_what) {
if (!is_inside_tree()) {
return;
}
- for (int layer = 0; layer < (int)layers.size(); layer++) {
- for (KeyValue<Vector2i, TileMapQuadrant> &E_quadrant : layers[layer].quadrant_map) {
+ for (TileMapLayer &layer : layers) {
+ for (KeyValue<Vector2i, TileMapQuadrant> &E_quadrant : layer.quadrant_map) {
TileMapQuadrant &q = E_quadrant.value;
// Update occluders transform.
@@ -1069,8 +1071,8 @@ void TileMap::_rendering_notification(int p_what) {
} break;
case NOTIFICATION_EXIT_CANVAS: {
- for (int layer = 0; layer < (int)layers.size(); layer++) {
- for (KeyValue<Vector2i, TileMapQuadrant> &E_quadrant : layers[layer].quadrant_map) {
+ for (TileMapLayer &layer : layers) {
+ for (KeyValue<Vector2i, TileMapQuadrant> &E_quadrant : layer.quadrant_map) {
TileMapQuadrant &q = E_quadrant.value;
for (const KeyValue<Vector2i, RID> &kv : q.occluders) {
RS::get_singleton()->canvas_light_occluder_attach_to_canvas(kv.value, RID());
@@ -1103,6 +1105,19 @@ void TileMap::_rendering_update_layer(int p_layer) {
rs->canvas_item_set_default_texture_filter(ci, RS::CanvasItemTextureFilter(get_texture_filter_in_tree()));
rs->canvas_item_set_default_texture_repeat(ci, RS::CanvasItemTextureRepeat(get_texture_repeat_in_tree()));
rs->canvas_item_set_light_mask(ci, get_light_mask());
+
+ Color layer_modulate = get_layer_modulate(p_layer);
+ if (selected_layer >= 0 && p_layer != selected_layer) {
+ int z1 = get_layer_z_index(p_layer);
+ int z2 = get_layer_z_index(selected_layer);
+ if (z1 < z2 || (z1 == z2 && p_layer < selected_layer)) {
+ layer_modulate = layer_modulate.darkened(0.5);
+ } else if (z1 > z2 || (z1 == z2 && p_layer > selected_layer)) {
+ layer_modulate = layer_modulate.darkened(0.5);
+ layer_modulate.a *= 0.3;
+ }
+ }
+ rs->canvas_item_set_modulate(ci, layer_modulate);
}
void TileMap::_rendering_cleanup_layer(int p_layer) {
@@ -1145,19 +1160,6 @@ void TileMap::_rendering_update_dirty_quadrants(SelfList<TileMapQuadrant>::List
int prev_z_index = 0;
RID prev_ci;
- Color tile_modulate = get_self_modulate();
- tile_modulate *= get_layer_modulate(q.layer);
- if (selected_layer >= 0) {
- int z1 = get_layer_z_index(q.layer);
- int z2 = get_layer_z_index(selected_layer);
- if (z1 < z2 || (z1 == z2 && q.layer < selected_layer)) {
- tile_modulate = tile_modulate.darkened(0.5);
- } else if (z1 > z2 || (z1 == z2 && q.layer > selected_layer)) {
- tile_modulate = tile_modulate.darkened(0.5);
- tile_modulate.a *= 0.3;
- }
- }
-
// Iterate over the cells of the quadrant.
for (const KeyValue<Vector2i, Vector2i> &E_cell : q.local_to_map) {
TileMapCell c = get_cell(q.layer, E_cell.value, true);
@@ -1227,7 +1229,7 @@ void TileMap::_rendering_update_dirty_quadrants(SelfList<TileMapQuadrant>::List
}
// Drawing the tile in the canvas item.
- draw_tile(ci, E_cell.key - tile_position, tile_set, c.source_id, c.get_atlas_coords(), c.alternative_tile, -1, tile_modulate, tile_data);
+ draw_tile(ci, E_cell.key - tile_position, tile_set, c.source_id, c.get_atlas_coords(), c.alternative_tile, -1, get_self_modulate(), tile_data);
// --- Occluders ---
for (int i = 0; i < tile_set->get_occlusion_layers_count(); i++) {
@@ -1255,16 +1257,16 @@ void TileMap::_rendering_update_dirty_quadrants(SelfList<TileMapQuadrant>::List
if (_rendering_quadrant_order_dirty) {
int index = -(int64_t)0x80000000; //always must be drawn below children.
- for (int layer = 0; layer < (int)layers.size(); layer++) {
+ for (TileMapLayer &layer : layers) {
// Sort the quadrants coords per local coordinates.
RBMap<Vector2i, Vector2i, TileMapQuadrant::CoordsWorldComparator> local_to_map;
- for (const KeyValue<Vector2i, TileMapQuadrant> &E : layers[layer].quadrant_map) {
+ for (const KeyValue<Vector2i, TileMapQuadrant> &E : layer.quadrant_map) {
local_to_map[map_to_local(E.key)] = E.key;
}
// Sort the quadrants.
for (const KeyValue<Vector2i, Vector2i> &E : local_to_map) {
- TileMapQuadrant &q = layers[layer].quadrant_map[E.value];
+ TileMapQuadrant &q = layer.quadrant_map[E.value];
for (const RID &ci : q.canvas_items) {
RS::get_singleton()->canvas_item_set_draw_index(ci, index++);
}
@@ -1377,7 +1379,7 @@ void TileMap::draw_tile(RID p_canvas_item, const Vector2i &p_position, const Ref
Color modulate = tile_data->get_modulate() * p_modulation;
// Compute the offset.
- Vector2i tile_offset = atlas_source->get_tile_effective_texture_offset(p_atlas_coords, p_alternative_tile);
+ Vector2i tile_offset = tile_data->get_texture_origin();
// Get destination rect.
Rect2 dest_rect;
@@ -1451,8 +1453,8 @@ void TileMap::_physics_notification(int p_what) {
if (is_inside_tree() && (!collision_animatable || in_editor)) {
// Update the new transform directly if we are not in animatable mode.
Transform2D gl_transform = get_global_transform();
- for (int layer = 0; layer < (int)layers.size(); layer++) {
- for (KeyValue<Vector2i, TileMapQuadrant> &E : layers[layer].quadrant_map) {
+ for (TileMapLayer &layer : layers) {
+ for (KeyValue<Vector2i, TileMapQuadrant> &E : layer.quadrant_map) {
TileMapQuadrant &q = E.value;
for (RID body : q.bodies) {
@@ -1474,8 +1476,8 @@ void TileMap::_physics_notification(int p_what) {
if (is_inside_tree() && !in_editor && collision_animatable) {
// Only active when animatable. Send the new transform to the physics...
new_transform = get_global_transform();
- for (int layer = 0; layer < (int)layers.size(); layer++) {
- for (KeyValue<Vector2i, TileMapQuadrant> &E : layers[layer].quadrant_map) {
+ for (TileMapLayer &layer : layers) {
+ for (KeyValue<Vector2i, TileMapQuadrant> &E : layer.quadrant_map) {
TileMapQuadrant &q = E.value;
for (RID body : q.bodies) {
@@ -1665,13 +1667,12 @@ void TileMap::_navigation_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_TRANSFORM_CHANGED: {
if (is_inside_tree()) {
- for (int layer = 0; layer < (int)layers.size(); layer++) {
+ for (TileMapLayer &layer : layers) {
Transform2D tilemap_xform = get_global_transform();
- for (KeyValue<Vector2i, TileMapQuadrant> &E_quadrant : layers[layer].quadrant_map) {
+ for (KeyValue<Vector2i, TileMapQuadrant> &E_quadrant : layer.quadrant_map) {
TileMapQuadrant &q = E_quadrant.value;
for (const KeyValue<Vector2i, Vector<RID>> &E_region : q.navigation_regions) {
- for (int layer_index = 0; layer_index < E_region.value.size(); layer_index++) {
- RID region = E_region.value[layer_index];
+ for (const RID &region : E_region.value) {
if (!region.is_valid()) {
continue;
}
@@ -2071,7 +2072,7 @@ void TileMap::erase_cell(int p_layer, const Vector2i &p_coords) {
int TileMap::get_cell_source_id(int p_layer, const Vector2i &p_coords, bool p_use_proxies) const {
ERR_FAIL_INDEX_V(p_layer, (int)layers.size(), TileSet::INVALID_SOURCE);
- // Get a cell source id from position
+ // Get a cell source id from position.
const HashMap<Vector2i, TileMapCell> &tile_map = layers[p_layer].tile_map;
HashMap<Vector2i, TileMapCell>::ConstIterator E = tile_map.find(p_coords);
@@ -2127,7 +2128,9 @@ int TileMap::get_cell_alternative_tile(int p_layer, const Vector2i &p_coords, bo
TileData *TileMap::get_cell_tile_data(int p_layer, const Vector2i &p_coords, bool p_use_proxies) const {
int source_id = get_cell_source_id(p_layer, p_coords, p_use_proxies);
- ERR_FAIL_COND_V_MSG(source_id == TileSet::INVALID_SOURCE, nullptr, vformat("Invalid TileSetSource at cell %s. Make sure a tile exists at this cell.", p_coords));
+ if (source_id == TileSet::INVALID_SOURCE) {
+ return nullptr;
+ }
Ref<TileSetAtlasSource> source = tile_set->get_source(source_id);
if (source.is_valid()) {
@@ -2565,7 +2568,7 @@ HashMap<Vector2i, TileSet::TerrainsPattern> TileMap::terrain_fill_path(int p_lay
}
}
}
- ERR_FAIL_COND_V_MSG(found_bit == TileSet::CELL_NEIGHBOR_MAX, output, vformat("Invalid terrain path, %s is not a neighbouring tile of %s", p_path[i + 1], p_path[i]));
+ ERR_FAIL_COND_V_MSG(found_bit == TileSet::CELL_NEIGHBOR_MAX, output, vformat("Invalid terrain path, %s is not a neighboring tile of %s", p_path[i + 1], p_path[i]));
neighbor_list.push_back(found_bit);
}
@@ -2811,8 +2814,8 @@ void TileMap::clear_layer(int p_layer) {
void TileMap::clear() {
// Remove all tiles.
_clear_internals();
- for (unsigned int i = 0; i < layers.size(); i++) {
- layers[i].tile_map.clear();
+ for (TileMapLayer &layer : layers) {
+ layer.tile_map.clear();
}
_recreate_internals();
used_rect_cache_dirty = true;
@@ -2839,7 +2842,7 @@ void TileMap::_set_tile_data(int p_layer, const Vector<int> &p_data) {
const int *r = p_data.ptr();
int offset = (format >= FORMAT_2) ? 3 : 2;
- ERR_FAIL_COND_MSG(c % offset != 0, "Corrupted tile data.");
+ ERR_FAIL_COND_MSG(c % offset != 0, vformat("Corrupted tile data. Got size: %s. Expected modulo: %s", offset));
clear_layer(p_layer);
@@ -2979,11 +2982,7 @@ void TileMap::_build_runtime_update_tile_data(SelfList<TileMapQuadrant>::List &r
#ifdef TOOLS_ENABLED
Rect2 TileMap::_edit_get_rect() const {
// Return the visible rect of the tilemap
- if (pending_update) {
- const_cast<TileMap *>(this)->_update_dirty_quadrants();
- } else {
- const_cast<TileMap *>(this)->_recompute_rect_cache();
- }
+ const_cast<TileMap *>(this)->_recompute_rect_cache();
return rect_cache;
}
#endif
@@ -3221,7 +3220,7 @@ Vector2i TileMap::local_to_map(const Vector2 &p_local_position) const {
ret = ret.floor();
}
- // Compute the tile offset, and if we might the output for a neighbour top tile
+ // Compute the tile offset, and if we might the output for a neighbor top tile
Vector2 in_tile_pos = raw_pos - ret;
bool in_top_left_triangle = (in_tile_pos - Vector2(0.5, 0.0)).cross(Vector2(-0.5, 1.0 / overlapping_ratio - 1)) <= 0;
bool in_top_right_triangle = (in_tile_pos - Vector2(0.5, 0.0)).cross(Vector2(0.5, 1.0 / overlapping_ratio - 1)) > 0;
@@ -3285,7 +3284,7 @@ Vector2i TileMap::local_to_map(const Vector2 &p_local_position) const {
ret = ret.floor();
}
- // Compute the tile offset, and if we might the output for a neighbour top tile
+ // Compute the tile offset, and if we might the output for a neighbor top tile
Vector2 in_tile_pos = raw_pos - ret;
bool in_top_left_triangle = (in_tile_pos - Vector2(0.0, 0.5)).cross(Vector2(1.0 / overlapping_ratio - 1, -0.5)) > 0;
bool in_bottom_left_triangle = (in_tile_pos - Vector2(0.0, 0.5)).cross(Vector2(1.0 / overlapping_ratio - 1, 0.5)) <= 0;
@@ -3738,6 +3737,22 @@ TypedArray<Vector2i> TileMap::get_used_cells(int p_layer) const {
return a;
}
+TypedArray<Vector2i> TileMap::get_used_cells_by_id(int p_layer, int p_source_id, const Vector2i p_atlas_coords, int p_alternative_tile) const {
+ ERR_FAIL_INDEX_V(p_layer, (int)layers.size(), TypedArray<Vector2i>());
+
+ // Returns the cells used in the tilemap.
+ TypedArray<Vector2i> a;
+ for (const KeyValue<Vector2i, TileMapCell> &E : layers[p_layer].tile_map) {
+ if ((p_source_id == TileSet::INVALID_SOURCE || p_source_id == E.value.source_id) &&
+ (p_atlas_coords == TileSetSource::INVALID_ATLAS_COORDS || p_atlas_coords == E.value.get_atlas_coords()) &&
+ (p_alternative_tile == TileSetSource::INVALID_TILE_ALTERNATIVE || p_alternative_tile == E.value.alternative_tile)) {
+ a.push_back(E.key);
+ }
+ }
+
+ return a;
+}
+
Rect2i TileMap::get_used_rect() { // Not const because of cache
// Return the rect of the currently used area
if (used_rect_cache_dirty) {
@@ -3940,25 +3955,36 @@ PackedStringArray TileMap::get_configuration_warnings() const {
// Retrieve the set of Z index values with a Y-sorted layer.
RBSet<int> y_sorted_z_index;
- for (int layer = 0; layer < (int)layers.size(); layer++) {
- if (layers[layer].y_sort_enabled) {
- y_sorted_z_index.insert(layers[layer].z_index);
+ for (const TileMapLayer &layer : layers) {
+ if (layer.y_sort_enabled) {
+ y_sorted_z_index.insert(layer.z_index);
}
}
// Check if we have a non-sorted layer in a Z-index with a Y-sorted layer.
- for (int layer = 0; layer < (int)layers.size(); layer++) {
- if (!layers[layer].y_sort_enabled && y_sorted_z_index.has(layers[layer].z_index)) {
+ for (const TileMapLayer &layer : layers) {
+ if (!layer.y_sort_enabled && y_sorted_z_index.has(layer.z_index)) {
warnings.push_back(RTR("A Y-sorted layer has the same Z-index value as a not Y-sorted layer.\nThis may lead to unwanted behaviors, as a layer that is not Y-sorted will be Y-sorted as a whole with tiles from Y-sorted layers."));
break;
}
}
+ // Check if Y-sort is enabled on a layer but not on the node.
+ if (!is_y_sort_enabled()) {
+ for (const TileMapLayer &layer : layers) {
+ if (layer.y_sort_enabled) {
+ warnings.push_back(RTR("A TileMap layer is set as Y-sorted, but Y-sort is not enabled on the TileMap node itself."));
+ break;
+ }
+ }
+ }
+
+ // Check if we are in isometric mode without Y-sort enabled.
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) {
+ for (const TileMapLayer &layer : layers) {
+ if (!layer.y_sort_enabled) {
warn = true;
break;
}
@@ -4030,6 +4056,7 @@ void TileMap::_bind_methods() {
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_cells_by_id", "layer", "source_id", "atlas_coords", "alternative_tile"), &TileMap::get_used_cells_by_id, DEFVAL(TileSet::INVALID_SOURCE), DEFVAL(TileSetSource::INVALID_ATLAS_COORDS), DEFVAL(TileSetSource::INVALID_TILE_ALTERNATIVE));
ClassDB::bind_method(D_METHOD("get_used_rect"), &TileMap::get_used_rect);
ClassDB::bind_method(D_METHOD("map_to_local", "map_position"), &TileMap::map_to_local);
diff --git a/scene/2d/tile_map.h b/scene/2d/tile_map.h
index d187a917b5..7cf2a2eded 100644
--- a/scene/2d/tile_map.h
+++ b/scene/2d/tile_map.h
@@ -179,7 +179,7 @@ private:
FORMAT_2,
FORMAT_3
};
- mutable DataFormat format = FORMAT_1; // Assume lowest possible format if none is present;
+ mutable DataFormat format = FORMAT_3;
static constexpr float FP_ADJUST = 0.00001;
@@ -340,7 +340,7 @@ public:
VisibilityMode get_navigation_visibility_mode();
// Cells accessors.
- void set_cell(int p_layer, const Vector2i &p_coords, int p_source_id = -1, const Vector2i p_atlas_coords = TileSetSource::INVALID_ATLAS_COORDS, int p_alternative_tile = 0);
+ void set_cell(int p_layer, const Vector2i &p_coords, int p_source_id = TileSet::INVALID_SOURCE, const Vector2i p_atlas_coords = TileSetSource::INVALID_ATLAS_COORDS, int p_alternative_tile = 0);
void erase_cell(int p_layer, const Vector2i &p_coords);
int get_cell_source_id(int p_layer, const Vector2i &p_coords, bool p_use_proxies = false) const;
Vector2i get_cell_atlas_coords(int p_layer, const Vector2i &p_coords, bool p_use_proxies = false) const;
@@ -377,6 +377,7 @@ public:
Vector2i get_neighbor_cell(const Vector2i &p_coords, TileSet::CellNeighbor p_cell_neighbor) const;
TypedArray<Vector2i> get_used_cells(int p_layer) const;
+ TypedArray<Vector2i> get_used_cells_by_id(int p_layer, int p_source_id = TileSet::INVALID_SOURCE, const Vector2i p_atlas_coords = TileSetSource::INVALID_ATLAS_COORDS, int p_alternative_tile = TileSetSource::INVALID_TILE_ALTERNATIVE) const;
Rect2i get_used_rect(); // Not const because of cache
// Override some methods of the CanvasItem class to pass the changes to the quadrants CanvasItems
diff --git a/scene/2d/visible_on_screen_notifier_2d.cpp b/scene/2d/visible_on_screen_notifier_2d.cpp
index 9a3fe73be1..1177cdb811 100644
--- a/scene/2d/visible_on_screen_notifier_2d.cpp
+++ b/scene/2d/visible_on_screen_notifier_2d.cpp
@@ -110,6 +110,7 @@ void VisibleOnScreenNotifier2D::_bind_methods() {
VisibleOnScreenNotifier2D::VisibleOnScreenNotifier2D() {
rect = Rect2(-10, -10, 20, 20);
+ set_hide_clip_children(true);
}
//////////////////////////////////////
@@ -137,7 +138,7 @@ void VisibleOnScreenEnabler2D::set_enable_node_path(NodePath p_path) {
return;
}
enable_node_path = p_path;
- if (is_inside_tree()) {
+ if (is_inside_tree() && !Engine::get_singleton()->is_editor_hint()) {
node_id = ObjectID();
Node *node = get_node(enable_node_path);
if (node) {
diff --git a/scene/3d/area_3d.cpp b/scene/3d/area_3d.cpp
index fa61ce5546..5901e38bb4 100644
--- a/scene/3d/area_3d.cpp
+++ b/scene/3d/area_3d.cpp
@@ -51,13 +51,13 @@ bool Area3D::is_gravity_a_point() const {
return gravity_is_point;
}
-void Area3D::set_gravity_point_distance_scale(real_t p_scale) {
- gravity_distance_scale = p_scale;
- PhysicsServer3D::get_singleton()->area_set_param(get_rid(), PhysicsServer3D::AREA_PARAM_GRAVITY_DISTANCE_SCALE, p_scale);
+void Area3D::set_gravity_point_unit_distance(real_t p_scale) {
+ gravity_point_unit_distance = p_scale;
+ PhysicsServer3D::get_singleton()->area_set_param(get_rid(), PhysicsServer3D::AREA_PARAM_GRAVITY_POINT_UNIT_DISTANCE, p_scale);
}
-real_t Area3D::get_gravity_point_distance_scale() const {
- return gravity_distance_scale;
+real_t Area3D::get_gravity_point_unit_distance() const {
+ return gravity_point_unit_distance;
}
void Area3D::set_gravity_point_center(const Vector3 &p_center) {
@@ -230,6 +230,7 @@ void Area3D::_body_inout(int p_status, const RID &p_body, ObjectID p_instance, i
return; //likely removed from the tree
}
+ lock_callback();
locked = true;
if (body_in) {
@@ -279,6 +280,7 @@ void Area3D::_body_inout(int p_status, const RID &p_body, ObjectID p_instance, i
}
locked = false;
+ unlock_callback();
}
void Area3D::_clear_monitoring() {
@@ -417,6 +419,7 @@ void Area3D::_area_inout(int p_status, const RID &p_area, ObjectID p_instance, i
return; //likely removed from the tree
}
+ lock_callback();
locked = true;
if (area_in) {
@@ -466,6 +469,7 @@ void Area3D::_area_inout(int p_status, const RID &p_area, ObjectID p_instance, i
}
locked = false;
+ unlock_callback();
}
bool Area3D::is_monitoring() const {
@@ -651,8 +655,8 @@ void Area3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_gravity_is_point", "enable"), &Area3D::set_gravity_is_point);
ClassDB::bind_method(D_METHOD("is_gravity_a_point"), &Area3D::is_gravity_a_point);
- ClassDB::bind_method(D_METHOD("set_gravity_point_distance_scale", "distance_scale"), &Area3D::set_gravity_point_distance_scale);
- ClassDB::bind_method(D_METHOD("get_gravity_point_distance_scale"), &Area3D::get_gravity_point_distance_scale);
+ ClassDB::bind_method(D_METHOD("set_gravity_point_unit_distance", "distance_scale"), &Area3D::set_gravity_point_unit_distance);
+ ClassDB::bind_method(D_METHOD("get_gravity_point_unit_distance"), &Area3D::get_gravity_point_unit_distance);
ClassDB::bind_method(D_METHOD("set_gravity_point_center", "center"), &Area3D::set_gravity_point_center);
ClassDB::bind_method(D_METHOD("get_gravity_point_center"), &Area3D::get_gravity_point_center);
@@ -737,7 +741,7 @@ void Area3D::_bind_methods() {
ADD_GROUP("Gravity", "gravity_");
ADD_PROPERTY(PropertyInfo(Variant::INT, "gravity_space_override", PROPERTY_HINT_ENUM, "Disabled,Combine,Combine-Replace,Replace,Replace-Combine", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), "set_gravity_space_override_mode", "get_gravity_space_override_mode");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "gravity_point", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), "set_gravity_is_point", "is_gravity_a_point");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "gravity_point_distance_scale", PROPERTY_HINT_RANGE, "0,1024,0.001,or_greater,exp"), "set_gravity_point_distance_scale", "get_gravity_point_distance_scale");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "gravity_point_unit_distance", PROPERTY_HINT_RANGE, "0,1024,0.001,or_greater,exp,suffix:m"), "set_gravity_point_unit_distance", "get_gravity_point_unit_distance");
ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "gravity_point_center", PROPERTY_HINT_NONE, "suffix:m"), "set_gravity_point_center", "get_gravity_point_center");
ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "gravity_direction"), "set_gravity_direction", "get_gravity_direction");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "gravity", PROPERTY_HINT_RANGE, U"-32,32,0.001,or_less,or_greater,suffix:m/s\u00B2"), "set_gravity", "get_gravity");
diff --git a/scene/3d/area_3d.h b/scene/3d/area_3d.h
index 91b91f741a..607e0d2af8 100644
--- a/scene/3d/area_3d.h
+++ b/scene/3d/area_3d.h
@@ -51,7 +51,7 @@ private:
Vector3 gravity_vec;
real_t gravity = 0.0;
bool gravity_is_point = false;
- real_t gravity_distance_scale = 0.0;
+ real_t gravity_point_unit_distance = 0.0;
SpaceOverride linear_damp_space_override = SPACE_OVERRIDE_DISABLED;
SpaceOverride angular_damp_space_override = SPACE_OVERRIDE_DISABLED;
@@ -155,8 +155,8 @@ public:
void set_gravity_is_point(bool p_enabled);
bool is_gravity_a_point() const;
- void set_gravity_point_distance_scale(real_t p_scale);
- real_t get_gravity_point_distance_scale() const;
+ void set_gravity_point_unit_distance(real_t p_scale);
+ real_t get_gravity_point_unit_distance() const;
void set_gravity_point_center(const Vector3 &p_center);
const Vector3 &get_gravity_point_center() const;
diff --git a/scene/3d/audio_stream_player_3d.cpp b/scene/3d/audio_stream_player_3d.cpp
index 574f5363d4..77bf15125e 100644
--- a/scene/3d/audio_stream_player_3d.cpp
+++ b/scene/3d/audio_stream_player_3d.cpp
@@ -162,12 +162,10 @@ void AudioStreamPlayer3D::_calc_reverb_vol(Area3D *area, Vector3 listener_area_p
rev_pos.y = 0;
rev_pos.normalize();
- if (channel_count >= 1) {
- // Stereo pair
- float c = rev_pos.x * 0.5 + 0.5;
- reverb_vol.write[0].l = 1.0 - c;
- reverb_vol.write[0].r = c;
- }
+ // Stereo pair.
+ float c = rev_pos.x * 0.5 + 0.5;
+ reverb_vol.write[0].l = 1.0 - c;
+ reverb_vol.write[0].r = c;
if (channel_count >= 3) {
// Center pair + Side pair
@@ -183,7 +181,6 @@ void AudioStreamPlayer3D::_calc_reverb_vol(Area3D *area, Vector3 listener_area_p
if (channel_count >= 4) {
// Rear pair
// FIXME: Not sure what math should be done here
- float c = rev_pos.x * 0.5 + 0.5;
reverb_vol.write[3].l = 1.0 - c;
reverb_vol.write[3].r = c;
}
@@ -284,14 +281,12 @@ void AudioStreamPlayer3D::_notification(int p_what) {
volume_vector = _update_panning();
}
- if (setplay.get() >= 0 && stream.is_valid()) {
+ if (setplayback.is_valid() && setplay.get() >= 0) {
active.set();
- Ref<AudioStreamPlayback> new_playback = stream->instantiate_playback();
- ERR_FAIL_COND_MSG(new_playback.is_null(), "Failed to instantiate playback.");
HashMap<StringName, Vector<AudioFrame>> bus_map;
bus_map[_get_actual_bus()] = volume_vector;
- AudioServer::get_singleton()->start_playback_stream(new_playback, bus_map, setplay.get(), actual_pitch_scale, linear_attenuation, attenuation_filter_cutoff_hz);
- stream_playbacks.push_back(new_playback);
+ AudioServer::get_singleton()->start_playback_stream(setplayback, bus_map, setplay.get(), actual_pitch_scale, linear_attenuation, attenuation_filter_cutoff_hz);
+ setplayback.unref();
setplay.set(-1);
}
@@ -580,14 +575,21 @@ void AudioStreamPlayer3D::play(float p_from_pos) {
if (stream->is_monophonic() && is_playing()) {
stop();
}
+ Ref<AudioStreamPlayback> stream_playback = stream->instantiate_playback();
+ ERR_FAIL_COND_MSG(stream_playback.is_null(), "Failed to instantiate playback.");
+
+ stream_playbacks.push_back(stream_playback);
+ setplayback = stream_playback;
setplay.set(p_from_pos);
active.set();
set_physics_process_internal(true);
}
void AudioStreamPlayer3D::seek(float p_seconds) {
- stop();
- play(p_seconds);
+ if (is_playing()) {
+ stop();
+ play(p_seconds);
+ }
}
void AudioStreamPlayer3D::stop() {
@@ -783,11 +785,13 @@ bool AudioStreamPlayer3D::get_stream_paused() const {
return false;
}
+bool AudioStreamPlayer3D::has_stream_playback() {
+ return !stream_playbacks.is_empty();
+}
+
Ref<AudioStreamPlayback> AudioStreamPlayer3D::get_stream_playback() {
- if (!stream_playbacks.is_empty()) {
- return stream_playbacks[stream_playbacks.size() - 1];
- }
- return nullptr;
+ ERR_FAIL_COND_V_MSG(stream_playbacks.is_empty(), Ref<AudioStreamPlayback>(), "Player is inactive. Call play() before requesting get_stream_playback().");
+ return stream_playbacks[stream_playbacks.size() - 1];
}
void AudioStreamPlayer3D::set_max_polyphony(int p_max_polyphony) {
@@ -841,7 +845,7 @@ void AudioStreamPlayer3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("_set_playing", "enable"), &AudioStreamPlayer3D::_set_playing);
ClassDB::bind_method(D_METHOD("_is_active"), &AudioStreamPlayer3D::_is_active);
- ClassDB::bind_method(D_METHOD("set_max_distance", "metres"), &AudioStreamPlayer3D::set_max_distance);
+ ClassDB::bind_method(D_METHOD("set_max_distance", "meters"), &AudioStreamPlayer3D::set_max_distance);
ClassDB::bind_method(D_METHOD("get_max_distance"), &AudioStreamPlayer3D::get_max_distance);
ClassDB::bind_method(D_METHOD("set_area_mask", "mask"), &AudioStreamPlayer3D::set_area_mask);
@@ -877,6 +881,7 @@ void AudioStreamPlayer3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_panning_strength", "panning_strength"), &AudioStreamPlayer3D::set_panning_strength);
ClassDB::bind_method(D_METHOD("get_panning_strength"), &AudioStreamPlayer3D::get_panning_strength);
+ ClassDB::bind_method(D_METHOD("has_stream_playback"), &AudioStreamPlayer3D::has_stream_playback);
ClassDB::bind_method(D_METHOD("get_stream_playback"), &AudioStreamPlayer3D::get_stream_playback);
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "stream", PROPERTY_HINT_RESOURCE_TYPE, "AudioStream"), "set_stream", "get_stream");
diff --git a/scene/3d/audio_stream_player_3d.h b/scene/3d/audio_stream_player_3d.h
index 67cec91896..bba8f10761 100644
--- a/scene/3d/audio_stream_player_3d.h
+++ b/scene/3d/audio_stream_player_3d.h
@@ -69,6 +69,7 @@ private:
SafeFlag active{ false };
SafeNumeric<float> setplay{ -1.0 };
+ Ref<AudioStreamPlayback> setplayback;
AttenuationModel attenuation_model = ATTENUATION_INVERSE_DISTANCE;
float volume_db = 0.0;
@@ -188,6 +189,7 @@ public:
void set_panning_strength(float p_panning_strength);
float get_panning_strength() const;
+ bool has_stream_playback();
Ref<AudioStreamPlayback> get_stream_playback();
AudioStreamPlayer3D();
diff --git a/scene/3d/bone_attachment_3d.cpp b/scene/3d/bone_attachment_3d.cpp
index a44e66ce2a..ba5ff02862 100644
--- a/scene/3d/bone_attachment_3d.cpp
+++ b/scene/3d/bone_attachment_3d.cpp
@@ -61,11 +61,7 @@ void BoneAttachment3D::_validate_property(PropertyInfo &p_property) const {
}
bool BoneAttachment3D::_set(const StringName &p_path, const Variant &p_value) {
- if (p_path == SNAME("override_pose")) {
- set_override_pose(p_value);
- } else if (p_path == SNAME("override_mode")) {
- set_override_mode(p_value);
- } else if (p_path == SNAME("use_external_skeleton")) {
+ if (p_path == SNAME("use_external_skeleton")) {
set_use_external_skeleton(p_value);
} else if (p_path == SNAME("external_skeleton")) {
set_external_skeleton(p_value);
@@ -75,11 +71,7 @@ bool BoneAttachment3D::_set(const StringName &p_path, const Variant &p_value) {
}
bool BoneAttachment3D::_get(const StringName &p_path, Variant &r_ret) const {
- if (p_path == SNAME("override_pose")) {
- r_ret = get_override_pose();
- } else if (p_path == SNAME("override_mode")) {
- r_ret = get_override_mode();
- } else if (p_path == SNAME("use_external_skeleton")) {
+ if (p_path == SNAME("use_external_skeleton")) {
r_ret = get_use_external_skeleton();
} else if (p_path == SNAME("external_skeleton")) {
r_ret = get_external_skeleton();
@@ -89,11 +81,6 @@ bool BoneAttachment3D::_get(const StringName &p_path, Variant &r_ret) const {
}
void BoneAttachment3D::_get_property_list(List<PropertyInfo> *p_list) const {
- p_list->push_back(PropertyInfo(Variant::BOOL, "override_pose", PROPERTY_HINT_NONE, ""));
- if (override_pose) {
- p_list->push_back(PropertyInfo(Variant::INT, "override_mode", PROPERTY_HINT_ENUM, "Global Pose Override,Local Pose Override,Custom Pose"));
- }
-
p_list->push_back(PropertyInfo(Variant::BOOL, "use_external_skeleton", PROPERTY_HINT_NONE, ""));
if (use_external_skeleton) {
p_list->push_back(PropertyInfo(Variant::NODE_PATH, "external_skeleton", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Skeleton3D"));
@@ -208,14 +195,10 @@ void BoneAttachment3D::_transform_changed() {
Transform3D our_trans = get_transform();
if (use_external_skeleton) {
- our_trans = sk->world_transform_to_global_pose(get_global_transform());
+ our_trans = sk->get_global_transform().affine_inverse() * get_global_transform();
}
- if (override_mode == OVERRIDE_MODES::MODE_GLOBAL_POSE) {
- sk->set_bone_global_pose_override(bone_idx, our_trans, 1.0, true);
- } else if (override_mode == OVERRIDE_MODES::MODE_LOCAL_POSE) {
- sk->set_bone_local_pose_override(bone_idx, sk->global_pose_to_local_pose(bone_idx, our_trans), 1.0, true);
- }
+ sk->set_bone_global_pose_override(bone_idx, our_trans, 1.0, true);
}
}
@@ -267,11 +250,7 @@ void BoneAttachment3D::set_override_pose(bool p_override) {
if (!override_pose) {
Skeleton3D *sk = _get_skeleton3d();
if (sk) {
- if (override_mode == OVERRIDE_MODES::MODE_GLOBAL_POSE) {
- sk->set_bone_global_pose_override(bone_idx, Transform3D(), 0.0, false);
- } else if (override_mode == OVERRIDE_MODES::MODE_LOCAL_POSE) {
- sk->set_bone_local_pose_override(bone_idx, Transform3D(), 0.0, false);
- }
+ sk->set_bone_global_pose_override(bone_idx, Transform3D(), 0.0, false);
}
_transform_changed();
}
@@ -282,27 +261,6 @@ bool BoneAttachment3D::get_override_pose() const {
return override_pose;
}
-void BoneAttachment3D::set_override_mode(int p_mode) {
- if (override_pose) {
- Skeleton3D *sk = _get_skeleton3d();
- if (sk) {
- if (override_mode == OVERRIDE_MODES::MODE_GLOBAL_POSE) {
- sk->set_bone_global_pose_override(bone_idx, Transform3D(), 0.0, false);
- } else if (override_mode == OVERRIDE_MODES::MODE_LOCAL_POSE) {
- sk->set_bone_local_pose_override(bone_idx, Transform3D(), 0.0, false);
- }
- }
- override_mode = p_mode;
- _transform_changed();
- return;
- }
- override_mode = p_mode;
-}
-
-int BoneAttachment3D::get_override_mode() const {
- return override_mode;
-}
-
void BoneAttachment3D::set_use_external_skeleton(bool p_use_external) {
use_external_skeleton = p_use_external;
@@ -361,7 +319,7 @@ void BoneAttachment3D::on_bone_pose_update(int p_bone_index) {
if (sk) {
if (!override_pose) {
if (use_external_skeleton) {
- set_global_transform(sk->global_pose_to_world_transform(sk->get_bone_global_pose(bone_idx)));
+ set_global_transform(sk->get_global_transform() * sk->get_bone_global_pose(bone_idx));
} else {
set_transform(sk->get_bone_global_pose(bone_idx));
}
@@ -407,8 +365,6 @@ void BoneAttachment3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_override_pose", "override_pose"), &BoneAttachment3D::set_override_pose);
ClassDB::bind_method(D_METHOD("get_override_pose"), &BoneAttachment3D::get_override_pose);
- ClassDB::bind_method(D_METHOD("set_override_mode", "override_mode"), &BoneAttachment3D::set_override_mode);
- ClassDB::bind_method(D_METHOD("get_override_mode"), &BoneAttachment3D::get_override_mode);
ClassDB::bind_method(D_METHOD("set_use_external_skeleton", "use_external_skeleton"), &BoneAttachment3D::set_use_external_skeleton);
ClassDB::bind_method(D_METHOD("get_use_external_skeleton"), &BoneAttachment3D::get_use_external_skeleton);
@@ -420,4 +376,5 @@ void BoneAttachment3D::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::STRING_NAME, "bone_name"), "set_bone_name", "get_bone_name");
ADD_PROPERTY(PropertyInfo(Variant::INT, "bone_idx"), "set_bone_idx", "get_bone_idx");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "override_pose"), "set_override_pose", "get_override_pose");
}
diff --git a/scene/3d/bone_attachment_3d.h b/scene/3d/bone_attachment_3d.h
index 2065271bbe..327cbaa0ab 100644
--- a/scene/3d/bone_attachment_3d.h
+++ b/scene/3d/bone_attachment_3d.h
@@ -44,14 +44,8 @@ class BoneAttachment3D : public Node3D {
int bone_idx = -1;
bool override_pose = false;
- int override_mode = 0;
bool _override_dirty = false;
- enum OVERRIDE_MODES {
- MODE_GLOBAL_POSE,
- MODE_LOCAL_POSE,
- };
-
bool use_external_skeleton = false;
NodePath external_skeleton_node;
ObjectID external_skeleton_node_cache;
@@ -86,8 +80,6 @@ public:
void set_override_pose(bool p_override);
bool get_override_pose() const;
- void set_override_mode(int p_mode);
- int get_override_mode() const;
void set_use_external_skeleton(bool p_external_skeleton);
bool get_use_external_skeleton() const;
diff --git a/scene/3d/camera_3d.cpp b/scene/3d/camera_3d.cpp
index e91948c6e1..47eb1eaa40 100644
--- a/scene/3d/camera_3d.cpp
+++ b/scene/3d/camera_3d.cpp
@@ -554,7 +554,7 @@ void Camera3D::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::INT, "projection", PROPERTY_HINT_ENUM, "Perspective,Orthogonal,Frustum"), "set_projection", "get_projection");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "current"), "set_current", "is_current");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "fov", PROPERTY_HINT_RANGE, "1,179,0.1,degrees"), "set_fov", "get_fov");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "size", PROPERTY_HINT_RANGE, "0.001,16384,0.001,suffix:m"), "set_size", "get_size");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "size", PROPERTY_HINT_RANGE, "0.001,16384,0.001,or_greater,suffix:m"), "set_size", "get_size");
ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "frustum_offset", PROPERTY_HINT_NONE, "suffix:m"), "set_frustum_offset", "get_frustum_offset");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "near", PROPERTY_HINT_RANGE, "0.001,10,0.001,or_greater,exp,suffix:m"), "set_near", "get_near");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "far", PROPERTY_HINT_RANGE, "0.01,4000,0.01,or_greater,exp,suffix:m"), "set_far", "get_far");
@@ -602,7 +602,7 @@ void Camera3D::set_fov(real_t p_fov) {
}
void Camera3D::set_size(real_t p_size) {
- ERR_FAIL_COND(p_size < 0.001 || p_size > 16384);
+ ERR_FAIL_COND(p_size <= CMP_EPSILON);
size = p_size;
_update_camera_mode();
}
diff --git a/scene/3d/collision_object_3d.cpp b/scene/3d/collision_object_3d.cpp
index c408b0714a..19d1b83cab 100644
--- a/scene/3d/collision_object_3d.cpp
+++ b/scene/3d/collision_object_3d.cpp
@@ -43,6 +43,11 @@ void CollisionObject3D::_notification(int p_what) {
}
_update_debug_shapes();
}
+#ifdef TOOLS_ENABLED
+ if (Engine::get_singleton()->is_editor_hint()) {
+ set_notify_local_transform(true); // Used for warnings and only in editor.
+ }
+#endif
} break;
case NOTIFICATION_EXIT_TREE: {
@@ -78,6 +83,14 @@ void CollisionObject3D::_notification(int p_what) {
_update_pickable();
} break;
+#ifdef TOOLS_ENABLED
+ case NOTIFICATION_LOCAL_TRANSFORM_CHANGED: {
+ if (Engine::get_singleton()->is_editor_hint()) {
+ update_configuration_warnings();
+ }
+ } break;
+#endif
+
case NOTIFICATION_TRANSFORM_CHANGED: {
if (only_update_transform_changes) {
return;
@@ -100,10 +113,14 @@ void CollisionObject3D::_notification(int p_what) {
bool disabled = !is_enabled();
if (!disabled || (disable_mode != DISABLE_MODE_REMOVE)) {
- if (area) {
- PhysicsServer3D::get_singleton()->area_set_space(rid, RID());
+ if (callback_lock > 0) {
+ ERR_PRINT("Removing a CollisionObject node during a physics callback is not allowed and will cause undesired behavior. Remove with call_deferred() instead.");
} else {
- PhysicsServer3D::get_singleton()->body_set_space(rid, RID());
+ if (area) {
+ PhysicsServer3D::get_singleton()->area_set_space(rid, RID());
+ } else {
+ PhysicsServer3D::get_singleton()->body_set_space(rid, RID());
+ }
}
}
@@ -223,10 +240,14 @@ void CollisionObject3D::_apply_disabled() {
switch (disable_mode) {
case DISABLE_MODE_REMOVE: {
if (is_inside_tree()) {
- if (area) {
- PhysicsServer3D::get_singleton()->area_set_space(rid, RID());
+ if (callback_lock > 0) {
+ ERR_PRINT("Disabling a CollisionObject node during a physics callback is not allowed and will cause undesired behavior. Disable with call_deferred() instead.");
} else {
- PhysicsServer3D::get_singleton()->body_set_space(rid, RID());
+ if (area) {
+ PhysicsServer3D::get_singleton()->area_set_space(rid, RID());
+ } else {
+ PhysicsServer3D::get_singleton()->body_set_space(rid, RID());
+ }
}
}
} break;
@@ -716,6 +737,11 @@ PackedStringArray CollisionObject3D::get_configuration_warnings() const {
warnings.push_back(RTR("This node has no shape, so it can't collide or interact with other objects.\nConsider adding a CollisionShape3D or CollisionPolygon3D as a child to define its shape."));
}
+ Vector3 scale = get_transform().get_basis().get_scale();
+ if (!(Math::is_zero_approx(scale.x - scale.y) && Math::is_zero_approx(scale.y - scale.z))) {
+ warnings.push_back(RTR("With a non-uniform scale this node will probably not function as expected.\nPlease make its scale uniform (i.e. the same on all axes), and change the size in children collision shapes instead."));
+ }
+
return warnings;
}
diff --git a/scene/3d/collision_object_3d.h b/scene/3d/collision_object_3d.h
index 656b8c9bf1..ebcbb39e0d 100644
--- a/scene/3d/collision_object_3d.h
+++ b/scene/3d/collision_object_3d.h
@@ -52,6 +52,7 @@ private:
bool area = false;
RID rid;
+ uint32_t callback_lock = 0;
DisableMode disable_mode = DISABLE_MODE_REMOVE;
@@ -97,6 +98,12 @@ private:
protected:
CollisionObject3D(RID p_rid, bool p_area);
+ _FORCE_INLINE_ void lock_callback() { callback_lock++; }
+ _FORCE_INLINE_ void unlock_callback() {
+ ERR_FAIL_COND(callback_lock == 0);
+ callback_lock--;
+ }
+
void _notification(int p_what);
static void _bind_methods();
diff --git a/scene/3d/collision_polygon_3d.cpp b/scene/3d/collision_polygon_3d.cpp
index 5fb8970085..53a61c1368 100644
--- a/scene/3d/collision_polygon_3d.cpp
+++ b/scene/3d/collision_polygon_3d.cpp
@@ -104,6 +104,11 @@ void CollisionPolygon3D::_notification(int p_what) {
if (parent) {
_update_in_shape_owner(true);
}
+#ifdef TOOLS_ENABLED
+ if (Engine::get_singleton()->is_editor_hint()) {
+ update_configuration_warnings();
+ }
+#endif
} break;
case NOTIFICATION_UNPARENTED: {
@@ -171,13 +176,18 @@ PackedStringArray CollisionPolygon3D::get_configuration_warnings() const {
PackedStringArray warnings = Node::get_configuration_warnings();
if (!Object::cast_to<CollisionObject3D>(get_parent())) {
- warnings.push_back(RTR("CollisionPolygon3D only serves to provide a collision shape to a CollisionObject3D derived node. Please only use it as a child of Area3D, StaticBody3D, RigidBody3D, CharacterBody3D, etc. to give them a shape."));
+ warnings.push_back(RTR("CollisionPolygon3D only serves to provide a collision shape to a CollisionObject3D derived node.\nPlease only use it as a child of Area3D, StaticBody3D, RigidBody3D, CharacterBody3D, etc. to give them a shape."));
}
if (polygon.is_empty()) {
warnings.push_back(RTR("An empty CollisionPolygon3D has no effect on collision."));
}
+ Vector3 scale = get_transform().get_basis().get_scale();
+ if (!(Math::is_zero_approx(scale.x - scale.y) && Math::is_zero_approx(scale.y - scale.z))) {
+ warnings.push_back(RTR("A non-uniformly scaled CollisionPolygon3D node will probably not function as expected.\nPlease make its scale uniform (i.e. the same on all axes), and change its polygon's vertices instead."));
+ }
+
return warnings;
}
diff --git a/scene/3d/collision_shape_3d.cpp b/scene/3d/collision_shape_3d.cpp
index 1709a17bce..f1d918ad9b 100644
--- a/scene/3d/collision_shape_3d.cpp
+++ b/scene/3d/collision_shape_3d.cpp
@@ -99,6 +99,11 @@ void CollisionShape3D::_notification(int p_what) {
if (parent) {
_update_in_shape_owner(true);
}
+#ifdef TOOLS_ENABLED
+ if (Engine::get_singleton()->is_editor_hint()) {
+ update_configuration_warnings();
+ }
+#endif
} break;
case NOTIFICATION_UNPARENTED: {
@@ -119,7 +124,7 @@ PackedStringArray CollisionShape3D::get_configuration_warnings() const {
PackedStringArray warnings = Node::get_configuration_warnings();
if (!Object::cast_to<CollisionObject3D>(get_parent())) {
- warnings.push_back(RTR("CollisionShape3D only serves to provide a collision shape to a CollisionObject3D derived node. Please only use it as a child of Area3D, StaticBody3D, RigidBody3D, CharacterBody3D, etc. to give them a shape."));
+ warnings.push_back(RTR("CollisionShape3D only serves to provide a collision shape to a CollisionObject3D derived node.\nPlease only use it as a child of Area3D, StaticBody3D, RigidBody3D, CharacterBody3D, etc. to give them a shape."));
}
if (!shape.is_valid()) {
@@ -134,6 +139,11 @@ PackedStringArray CollisionShape3D::get_configuration_warnings() const {
}
}
+ Vector3 scale = get_transform().get_basis().get_scale();
+ if (!(Math::is_zero_approx(scale.x - scale.y) && Math::is_zero_approx(scale.y - scale.z))) {
+ warnings.push_back(RTR("A non-uniformly scaled CollisionShape3D node will probably not function as expected.\nPlease make its scale uniform (i.e. the same on all axes), and change the size of its shape resource instead."));
+ }
+
return warnings;
}
diff --git a/scene/3d/cpu_particles_3d.cpp b/scene/3d/cpu_particles_3d.cpp
index f24ed805c3..b9a161e476 100644
--- a/scene/3d/cpu_particles_3d.cpp
+++ b/scene/3d/cpu_particles_3d.cpp
@@ -1616,8 +1616,8 @@ void CPUParticles3D::_bind_methods() {
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "anim_speed_min", PROPERTY_HINT_RANGE, "0,128,0.01,or_greater,or_less"), "set_param_min", "get_param_min", PARAM_ANIM_SPEED);
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "anim_speed_max", PROPERTY_HINT_RANGE, "0,128,0.01,or_greater,or_less"), "set_param_max", "get_param_max", PARAM_ANIM_SPEED);
ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "anim_speed_curve", PROPERTY_HINT_RESOURCE_TYPE, "Curve"), "set_param_curve", "get_param_curve", PARAM_ANIM_SPEED);
- ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "anim_offset_min", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_param_min", "get_param_min", PARAM_ANIM_OFFSET);
- ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "anim_offset_max", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_param_max", "get_param_max", PARAM_ANIM_OFFSET);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "anim_offset_min", PROPERTY_HINT_RANGE, "0,1,0.0001"), "set_param_min", "get_param_min", PARAM_ANIM_OFFSET);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "anim_offset_max", PROPERTY_HINT_RANGE, "0,1,0.0001"), "set_param_max", "get_param_max", PARAM_ANIM_OFFSET);
ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "anim_offset_curve", PROPERTY_HINT_RESOURCE_TYPE, "Curve"), "set_param_curve", "get_param_curve", PARAM_ANIM_OFFSET);
BIND_ENUM_CONSTANT(PARAM_INITIAL_LINEAR_VELOCITY);
diff --git a/scene/3d/decal.cpp b/scene/3d/decal.cpp
index e9cc4e9479..e122adcc8c 100644
--- a/scene/3d/decal.cpp
+++ b/scene/3d/decal.cpp
@@ -30,14 +30,14 @@
#include "decal.h"
-void Decal::set_extents(const Vector3 &p_extents) {
- extents = p_extents;
- RS::get_singleton()->decal_set_extents(decal, p_extents);
+void Decal::set_size(const Vector3 &p_size) {
+ size = p_size;
+ RS::get_singleton()->decal_set_size(decal, p_size);
update_gizmos();
}
-Vector3 Decal::get_extents() const {
- return extents;
+Vector3 Decal::get_size() const {
+ return size;
}
void Decal::set_texture(DecalTexture p_type, const Ref<Texture2D> &p_texture) {
@@ -147,8 +147,8 @@ uint32_t Decal::get_cull_mask() const {
AABB Decal::get_aabb() const {
AABB aabb;
- aabb.position = -extents;
- aabb.size = extents * 2.0;
+ aabb.position = -size / 2;
+ aabb.size = size;
return aabb;
}
@@ -156,6 +156,10 @@ void Decal::_validate_property(PropertyInfo &p_property) const {
if (!distance_fade_enabled && (p_property.name == "distance_fade_begin" || p_property.name == "distance_fade_length")) {
p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
+
+ if (p_property.name == "sorting_offset") {
+ p_property.usage = PROPERTY_USAGE_DEFAULT;
+ }
}
PackedStringArray Decal::get_configuration_warnings() const {
@@ -177,8 +181,8 @@ PackedStringArray Decal::get_configuration_warnings() const {
}
void Decal::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_extents", "extents"), &Decal::set_extents);
- ClassDB::bind_method(D_METHOD("get_extents"), &Decal::get_extents);
+ ClassDB::bind_method(D_METHOD("set_size", "size"), &Decal::set_size);
+ ClassDB::bind_method(D_METHOD("get_size"), &Decal::get_size);
ClassDB::bind_method(D_METHOD("set_texture", "type", "texture"), &Decal::set_texture);
ClassDB::bind_method(D_METHOD("get_texture", "type"), &Decal::get_texture);
@@ -213,7 +217,7 @@ void Decal::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_cull_mask", "mask"), &Decal::set_cull_mask);
ClassDB::bind_method(D_METHOD("get_cull_mask"), &Decal::get_cull_mask);
- ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "extents", PROPERTY_HINT_RANGE, "0,1024,0.001,or_greater,suffix:m"), "set_extents", "get_extents");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "size", PROPERTY_HINT_RANGE, "0,1024,0.001,or_greater,suffix:m"), "set_size", "get_size");
ADD_GROUP("Textures", "texture_");
ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "texture_albedo", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture", TEXTURE_ALBEDO);
@@ -248,6 +252,24 @@ void Decal::_bind_methods() {
BIND_ENUM_CONSTANT(TEXTURE_MAX);
}
+#ifndef DISABLE_DEPRECATED
+bool Decal::_set(const StringName &p_name, const Variant &p_value) {
+ if (p_name == "extents") { // Compatibility with Godot 3.x.
+ set_size((Vector3)p_value * 2);
+ return true;
+ }
+ return false;
+}
+
+bool Decal::_get(const StringName &p_name, Variant &r_property) const {
+ if (p_name == "extents") { // Compatibility with Godot 3.x.
+ r_property = size / 2;
+ return true;
+ }
+ return false;
+}
+#endif // DISABLE_DEPRECATED
+
Decal::Decal() {
decal = RenderingServer::get_singleton()->decal_create();
RS::get_singleton()->instance_set_base(get_instance(), decal);
diff --git a/scene/3d/decal.h b/scene/3d/decal.h
index 5797a2f645..171b52815a 100644
--- a/scene/3d/decal.h
+++ b/scene/3d/decal.h
@@ -47,7 +47,7 @@ public:
private:
RID decal;
- Vector3 extents = Vector3(1, 1, 1);
+ Vector3 size = Vector3(2, 2, 2);
Ref<Texture2D> textures[TEXTURE_MAX];
real_t emission_energy = 1.0;
real_t albedo_mix = 1.0;
@@ -63,12 +63,16 @@ private:
protected:
static void _bind_methods();
void _validate_property(PropertyInfo &p_property) const;
+#ifndef DISABLE_DEPRECATED
+ bool _set(const StringName &p_name, const Variant &p_value);
+ bool _get(const StringName &p_name, Variant &r_property) const;
+#endif // DISABLE_DEPRECATED
public:
virtual PackedStringArray get_configuration_warnings() const override;
- void set_extents(const Vector3 &p_extents);
- Vector3 get_extents() const;
+ void set_size(const Vector3 &p_size);
+ Vector3 get_size() const;
void set_texture(DecalTexture p_type, const Ref<Texture2D> &p_texture);
Ref<Texture2D> get_texture(DecalTexture p_type) const;
diff --git a/scene/3d/fog_volume.cpp b/scene/3d/fog_volume.cpp
index 30dfb45836..9b0a7bb302 100644
--- a/scene/3d/fog_volume.cpp
+++ b/scene/3d/fog_volume.cpp
@@ -34,36 +34,54 @@
///////////////////////////
void FogVolume::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_extents", "extents"), &FogVolume::set_extents);
- ClassDB::bind_method(D_METHOD("get_extents"), &FogVolume::get_extents);
+ ClassDB::bind_method(D_METHOD("set_size", "size"), &FogVolume::set_size);
+ ClassDB::bind_method(D_METHOD("get_size"), &FogVolume::get_size);
ClassDB::bind_method(D_METHOD("set_shape", "shape"), &FogVolume::set_shape);
ClassDB::bind_method(D_METHOD("get_shape"), &FogVolume::get_shape);
ClassDB::bind_method(D_METHOD("set_material", "material"), &FogVolume::set_material);
ClassDB::bind_method(D_METHOD("get_material"), &FogVolume::get_material);
- ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "extents", PROPERTY_HINT_RANGE, "0.01,1024,0.01,or_greater,suffix:m"), "set_extents", "get_extents");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "size", PROPERTY_HINT_RANGE, "0.01,1024,0.01,or_greater,suffix:m"), "set_size", "get_size");
ADD_PROPERTY(PropertyInfo(Variant::INT, "shape", PROPERTY_HINT_ENUM, "Ellipsoid (Local),Cone (Local),Cylinder (Local),Box (Local),World (Global)"), "set_shape", "get_shape");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "material", PROPERTY_HINT_RESOURCE_TYPE, "FogMaterial,ShaderMaterial"), "set_material", "get_material");
}
void FogVolume::_validate_property(PropertyInfo &p_property) const {
- if (p_property.name == "extents" && shape == RS::FOG_VOLUME_SHAPE_WORLD) {
+ if (p_property.name == "size" && shape == RS::FOG_VOLUME_SHAPE_WORLD) {
p_property.usage = PROPERTY_USAGE_NONE;
return;
}
}
-void FogVolume::set_extents(const Vector3 &p_extents) {
- extents = p_extents;
- extents.x = MAX(0.0, extents.x);
- extents.y = MAX(0.0, extents.y);
- extents.z = MAX(0.0, extents.z);
- RS::get_singleton()->fog_volume_set_extents(_get_volume(), extents);
+#ifndef DISABLE_DEPRECATED
+bool FogVolume::_set(const StringName &p_name, const Variant &p_value) {
+ if (p_name == "extents") { // Compatibility with Godot 3.x.
+ set_size((Vector3)p_value * 2);
+ return true;
+ }
+ return false;
+}
+
+bool FogVolume::_get(const StringName &p_name, Variant &r_property) const {
+ if (p_name == "extents") { // Compatibility with Godot 3.x.
+ r_property = size / 2;
+ return true;
+ }
+ return false;
+}
+#endif // DISABLE_DEPRECATED
+
+void FogVolume::set_size(const Vector3 &p_size) {
+ size = p_size;
+ size.x = MAX(0.0, size.x);
+ size.y = MAX(0.0, size.y);
+ size.z = MAX(0.0, size.z);
+ RS::get_singleton()->fog_volume_set_size(_get_volume(), size);
update_gizmos();
}
-Vector3 FogVolume::get_extents() const {
- return extents;
+Vector3 FogVolume::get_size() const {
+ return size;
}
void FogVolume::set_shape(RS::FogVolumeShape p_type) {
@@ -94,7 +112,7 @@ Ref<Material> FogVolume::get_material() const {
AABB FogVolume::get_aabb() const {
if (shape != RS::FOG_VOLUME_SHAPE_WORLD) {
- return AABB(-extents, extents * 2);
+ return AABB(-size / 2, size);
}
return AABB();
}
diff --git a/scene/3d/fog_volume.h b/scene/3d/fog_volume.h
index fa02834762..f7e861e3d0 100644
--- a/scene/3d/fog_volume.h
+++ b/scene/3d/fog_volume.h
@@ -40,7 +40,7 @@
class FogVolume : public VisualInstance3D {
GDCLASS(FogVolume, VisualInstance3D);
- Vector3 extents = Vector3(1, 1, 1);
+ Vector3 size = Vector3(2, 2, 2);
Ref<Material> material;
RS::FogVolumeShape shape = RS::FOG_VOLUME_SHAPE_BOX;
@@ -50,10 +50,14 @@ protected:
_FORCE_INLINE_ RID _get_volume() { return volume; }
static void _bind_methods();
void _validate_property(PropertyInfo &p_property) const;
+#ifndef DISABLE_DEPRECATED
+ bool _set(const StringName &p_name, const Variant &p_value);
+ bool _get(const StringName &p_name, Variant &r_property) const;
+#endif // DISABLE_DEPRECATED
public:
- void set_extents(const Vector3 &p_extents);
- Vector3 get_extents() const;
+ void set_size(const Vector3 &p_size);
+ Vector3 get_size() const;
void set_shape(RS::FogVolumeShape p_type);
RS::FogVolumeShape get_shape() const;
diff --git a/scene/3d/gpu_particles_collision_3d.cpp b/scene/3d/gpu_particles_collision_3d.cpp
index d1f2dfb25f..137d578291 100644
--- a/scene/3d/gpu_particles_collision_3d.cpp
+++ b/scene/3d/gpu_particles_collision_3d.cpp
@@ -95,24 +95,42 @@ GPUParticlesCollisionSphere3D::~GPUParticlesCollisionSphere3D() {
///////////////////////////
void GPUParticlesCollisionBox3D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_extents", "extents"), &GPUParticlesCollisionBox3D::set_extents);
- ClassDB::bind_method(D_METHOD("get_extents"), &GPUParticlesCollisionBox3D::get_extents);
+ ClassDB::bind_method(D_METHOD("set_size", "size"), &GPUParticlesCollisionBox3D::set_size);
+ ClassDB::bind_method(D_METHOD("get_size"), &GPUParticlesCollisionBox3D::get_size);
- ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "extents", PROPERTY_HINT_RANGE, "0.01,1024,0.01,or_greater,suffix:m"), "set_extents", "get_extents");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "size", PROPERTY_HINT_RANGE, "0.01,1024,0.01,or_greater,suffix:m"), "set_size", "get_size");
}
-void GPUParticlesCollisionBox3D::set_extents(const Vector3 &p_extents) {
- extents = p_extents;
- RS::get_singleton()->particles_collision_set_box_extents(_get_collision(), extents);
+#ifndef DISABLE_DEPRECATED
+bool GPUParticlesCollisionBox3D::_set(const StringName &p_name, const Variant &p_value) {
+ if (p_name == "extents") { // Compatibility with Godot 3.x.
+ set_size((Vector3)p_value * 2);
+ return true;
+ }
+ return false;
+}
+
+bool GPUParticlesCollisionBox3D::_get(const StringName &p_name, Variant &r_property) const {
+ if (p_name == "extents") { // Compatibility with Godot 3.x.
+ r_property = size / 2;
+ return true;
+ }
+ return false;
+}
+#endif // DISABLE_DEPRECATED
+
+void GPUParticlesCollisionBox3D::set_size(const Vector3 &p_size) {
+ size = p_size;
+ RS::get_singleton()->particles_collision_set_box_extents(_get_collision(), size / 2);
update_gizmos();
}
-Vector3 GPUParticlesCollisionBox3D::get_extents() const {
- return extents;
+Vector3 GPUParticlesCollisionBox3D::get_size() const {
+ return size;
}
AABB GPUParticlesCollisionBox3D::get_aabb() const {
- return AABB(-extents, extents * 2);
+ return AABB(-size / 2, size);
}
GPUParticlesCollisionBox3D::GPUParticlesCollisionBox3D() :
@@ -359,7 +377,7 @@ Vector3i GPUParticlesCollisionSDF3D::get_estimated_cell_size() const {
static const int subdivs[RESOLUTION_MAX] = { 16, 32, 64, 128, 256, 512 };
int subdiv = subdivs[get_resolution()];
- AABB aabb(-extents, extents * 2);
+ AABB aabb(-size / 2, size);
float cell_size = aabb.get_longest_axis_size() / float(subdiv);
@@ -374,7 +392,7 @@ Ref<Image> GPUParticlesCollisionSDF3D::bake() {
static const int subdivs[RESOLUTION_MAX] = { 16, 32, 64, 128, 256, 512 };
int subdiv = subdivs[get_resolution()];
- AABB aabb(-extents, extents * 2);
+ AABB aabb(-size / 2, size);
float cell_size = aabb.get_longest_axis_size() / float(subdiv);
@@ -515,8 +533,8 @@ PackedStringArray GPUParticlesCollisionSDF3D::get_configuration_warnings() const
}
void GPUParticlesCollisionSDF3D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_extents", "extents"), &GPUParticlesCollisionSDF3D::set_extents);
- ClassDB::bind_method(D_METHOD("get_extents"), &GPUParticlesCollisionSDF3D::get_extents);
+ ClassDB::bind_method(D_METHOD("set_size", "size"), &GPUParticlesCollisionSDF3D::set_size);
+ ClassDB::bind_method(D_METHOD("get_size"), &GPUParticlesCollisionSDF3D::get_size);
ClassDB::bind_method(D_METHOD("set_resolution", "resolution"), &GPUParticlesCollisionSDF3D::set_resolution);
ClassDB::bind_method(D_METHOD("get_resolution"), &GPUParticlesCollisionSDF3D::get_resolution);
@@ -532,7 +550,7 @@ void GPUParticlesCollisionSDF3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_bake_mask_value", "layer_number", "value"), &GPUParticlesCollisionSDF3D::set_bake_mask_value);
ClassDB::bind_method(D_METHOD("get_bake_mask_value", "layer_number"), &GPUParticlesCollisionSDF3D::get_bake_mask_value);
- ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "extents", PROPERTY_HINT_RANGE, "0.01,1024,0.01,or_greater,suffix:m"), "set_extents", "get_extents");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "size", PROPERTY_HINT_RANGE, "0.01,1024,0.01,or_greater,suffix:m"), "set_size", "get_size");
ADD_PROPERTY(PropertyInfo(Variant::INT, "resolution", PROPERTY_HINT_ENUM, "16,32,64,128,256,512"), "set_resolution", "get_resolution");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "thickness", PROPERTY_HINT_RANGE, "0.0,2.0,0.01,suffix:m"), "set_thickness", "get_thickness");
ADD_PROPERTY(PropertyInfo(Variant::INT, "bake_mask", PROPERTY_HINT_LAYERS_3D_RENDER), "set_bake_mask", "get_bake_mask");
@@ -547,6 +565,24 @@ void GPUParticlesCollisionSDF3D::_bind_methods() {
BIND_ENUM_CONSTANT(RESOLUTION_MAX);
}
+#ifndef DISABLE_DEPRECATED
+bool GPUParticlesCollisionSDF3D::_set(const StringName &p_name, const Variant &p_value) {
+ if (p_name == "extents") { // Compatibility with Godot 3.x.
+ set_size((Vector3)p_value * 2);
+ return true;
+ }
+ return false;
+}
+
+bool GPUParticlesCollisionSDF3D::_get(const StringName &p_name, Variant &r_property) const {
+ if (p_name == "extents") { // Compatibility with Godot 3.x.
+ r_property = size / 2;
+ return true;
+ }
+ return false;
+}
+#endif // DISABLE_DEPRECATED
+
void GPUParticlesCollisionSDF3D::set_thickness(float p_thickness) {
thickness = p_thickness;
}
@@ -555,14 +591,14 @@ float GPUParticlesCollisionSDF3D::get_thickness() const {
return thickness;
}
-void GPUParticlesCollisionSDF3D::set_extents(const Vector3 &p_extents) {
- extents = p_extents;
- RS::get_singleton()->particles_collision_set_box_extents(_get_collision(), extents);
+void GPUParticlesCollisionSDF3D::set_size(const Vector3 &p_size) {
+ size = p_size;
+ RS::get_singleton()->particles_collision_set_box_extents(_get_collision(), size / 2);
update_gizmos();
}
-Vector3 GPUParticlesCollisionSDF3D::get_extents() const {
- return extents;
+Vector3 GPUParticlesCollisionSDF3D::get_size() const {
+ return size;
}
void GPUParticlesCollisionSDF3D::set_resolution(Resolution p_resolution) {
@@ -610,7 +646,7 @@ Ref<Texture3D> GPUParticlesCollisionSDF3D::get_texture() const {
}
AABB GPUParticlesCollisionSDF3D::get_aabb() const {
- return AABB(-extents, extents * 2);
+ return AABB(-size / 2, size);
}
GPUParticlesCollisionSDF3D::BakeBeginFunc GPUParticlesCollisionSDF3D::bake_begin_function = nullptr;
@@ -675,8 +711,8 @@ void GPUParticlesCollisionHeightField3D::_notification(int p_what) {
}
void GPUParticlesCollisionHeightField3D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_extents", "extents"), &GPUParticlesCollisionHeightField3D::set_extents);
- ClassDB::bind_method(D_METHOD("get_extents"), &GPUParticlesCollisionHeightField3D::get_extents);
+ ClassDB::bind_method(D_METHOD("set_size", "size"), &GPUParticlesCollisionHeightField3D::set_size);
+ ClassDB::bind_method(D_METHOD("get_size"), &GPUParticlesCollisionHeightField3D::get_size);
ClassDB::bind_method(D_METHOD("set_resolution", "resolution"), &GPUParticlesCollisionHeightField3D::set_resolution);
ClassDB::bind_method(D_METHOD("get_resolution"), &GPUParticlesCollisionHeightField3D::get_resolution);
@@ -687,7 +723,7 @@ void GPUParticlesCollisionHeightField3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_follow_camera_enabled", "enabled"), &GPUParticlesCollisionHeightField3D::set_follow_camera_enabled);
ClassDB::bind_method(D_METHOD("is_follow_camera_enabled"), &GPUParticlesCollisionHeightField3D::is_follow_camera_enabled);
- ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "extents", PROPERTY_HINT_RANGE, "0.01,1024,0.01,or_greater,suffix:m"), "set_extents", "get_extents");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "size", PROPERTY_HINT_RANGE, "0.01,1024,0.01,or_greater,suffix:m"), "set_size", "get_size");
ADD_PROPERTY(PropertyInfo(Variant::INT, "resolution", PROPERTY_HINT_ENUM, "256 (Fastest),512 (Fast),1024 (Average),2048 (Slow),4096 (Slower),8192 (Slowest)"), "set_resolution", "get_resolution");
ADD_PROPERTY(PropertyInfo(Variant::INT, "update_mode", PROPERTY_HINT_ENUM, "When Moved (Fast),Always (Slow)"), "set_update_mode", "get_update_mode");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "follow_camera_enabled"), "set_follow_camera_enabled", "is_follow_camera_enabled");
@@ -704,15 +740,33 @@ void GPUParticlesCollisionHeightField3D::_bind_methods() {
BIND_ENUM_CONSTANT(UPDATE_MODE_ALWAYS);
}
-void GPUParticlesCollisionHeightField3D::set_extents(const Vector3 &p_extents) {
- extents = p_extents;
- RS::get_singleton()->particles_collision_set_box_extents(_get_collision(), extents);
+#ifndef DISABLE_DEPRECATED
+bool GPUParticlesCollisionHeightField3D::_set(const StringName &p_name, const Variant &p_value) {
+ if (p_name == "extents") { // Compatibility with Godot 3.x.
+ set_size((Vector3)p_value * 2);
+ return true;
+ }
+ return false;
+}
+
+bool GPUParticlesCollisionHeightField3D::_get(const StringName &p_name, Variant &r_property) const {
+ if (p_name == "extents") { // Compatibility with Godot 3.x.
+ r_property = size / 2;
+ return true;
+ }
+ return false;
+}
+#endif // DISABLE_DEPRECATED
+
+void GPUParticlesCollisionHeightField3D::set_size(const Vector3 &p_size) {
+ size = p_size;
+ RS::get_singleton()->particles_collision_set_box_extents(_get_collision(), size / 2);
update_gizmos();
RS::get_singleton()->particles_collision_height_field_update(_get_collision());
}
-Vector3 GPUParticlesCollisionHeightField3D::get_extents() const {
- return extents;
+Vector3 GPUParticlesCollisionHeightField3D::get_size() const {
+ return size;
}
void GPUParticlesCollisionHeightField3D::set_resolution(Resolution p_resolution) {
@@ -745,7 +799,7 @@ bool GPUParticlesCollisionHeightField3D::is_follow_camera_enabled() const {
}
AABB GPUParticlesCollisionHeightField3D::get_aabb() const {
- return AABB(-extents, extents * 2);
+ return AABB(-size / 2, size);
}
GPUParticlesCollisionHeightField3D::GPUParticlesCollisionHeightField3D() :
@@ -857,24 +911,42 @@ GPUParticlesAttractorSphere3D::~GPUParticlesAttractorSphere3D() {
///////////////////////////
void GPUParticlesAttractorBox3D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_extents", "extents"), &GPUParticlesAttractorBox3D::set_extents);
- ClassDB::bind_method(D_METHOD("get_extents"), &GPUParticlesAttractorBox3D::get_extents);
+ ClassDB::bind_method(D_METHOD("set_size", "size"), &GPUParticlesAttractorBox3D::set_size);
+ ClassDB::bind_method(D_METHOD("get_size"), &GPUParticlesAttractorBox3D::get_size);
+
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "size", PROPERTY_HINT_RANGE, "0.01,1024,0.01,or_greater,suffix:m"), "set_size", "get_size");
+}
- ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "extents", PROPERTY_HINT_RANGE, "0.01,1024,0.01,or_greater,suffix:m"), "set_extents", "get_extents");
+#ifndef DISABLE_DEPRECATED
+bool GPUParticlesAttractorBox3D::_set(const StringName &p_name, const Variant &p_value) {
+ if (p_name == "extents") { // Compatibility with Godot 3.x.
+ set_size((Vector3)p_value * 2);
+ return true;
+ }
+ return false;
}
-void GPUParticlesAttractorBox3D::set_extents(const Vector3 &p_extents) {
- extents = p_extents;
- RS::get_singleton()->particles_collision_set_box_extents(_get_collision(), extents);
+bool GPUParticlesAttractorBox3D::_get(const StringName &p_name, Variant &r_property) const {
+ if (p_name == "extents") { // Compatibility with Godot 3.x.
+ r_property = size / 2;
+ return true;
+ }
+ return false;
+}
+#endif // DISABLE_DEPRECATED
+
+void GPUParticlesAttractorBox3D::set_size(const Vector3 &p_size) {
+ size = p_size;
+ RS::get_singleton()->particles_collision_set_box_extents(_get_collision(), size / 2);
update_gizmos();
}
-Vector3 GPUParticlesAttractorBox3D::get_extents() const {
- return extents;
+Vector3 GPUParticlesAttractorBox3D::get_size() const {
+ return size;
}
AABB GPUParticlesAttractorBox3D::get_aabb() const {
- return AABB(-extents, extents * 2);
+ return AABB(-size / 2, size);
}
GPUParticlesAttractorBox3D::GPUParticlesAttractorBox3D() :
@@ -887,24 +959,42 @@ GPUParticlesAttractorBox3D::~GPUParticlesAttractorBox3D() {
///////////////////////////
void GPUParticlesAttractorVectorField3D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_extents", "extents"), &GPUParticlesAttractorVectorField3D::set_extents);
- ClassDB::bind_method(D_METHOD("get_extents"), &GPUParticlesAttractorVectorField3D::get_extents);
+ ClassDB::bind_method(D_METHOD("set_size", "size"), &GPUParticlesAttractorVectorField3D::set_size);
+ ClassDB::bind_method(D_METHOD("get_size"), &GPUParticlesAttractorVectorField3D::get_size);
ClassDB::bind_method(D_METHOD("set_texture", "texture"), &GPUParticlesAttractorVectorField3D::set_texture);
ClassDB::bind_method(D_METHOD("get_texture"), &GPUParticlesAttractorVectorField3D::get_texture);
- ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "extents", PROPERTY_HINT_RANGE, "0.01,1024,0.01,or_greater,suffix:m"), "set_extents", "get_extents");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "size", PROPERTY_HINT_RANGE, "0.01,1024,0.01,or_greater,suffix:m"), "set_size", "get_size");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture3D"), "set_texture", "get_texture");
}
-void GPUParticlesAttractorVectorField3D::set_extents(const Vector3 &p_extents) {
- extents = p_extents;
- RS::get_singleton()->particles_collision_set_box_extents(_get_collision(), extents);
+#ifndef DISABLE_DEPRECATED
+bool GPUParticlesAttractorVectorField3D::_set(const StringName &p_name, const Variant &p_value) {
+ if (p_name == "extents") { // Compatibility with Godot 3.x.
+ set_size((Vector3)p_value * 2);
+ return true;
+ }
+ return false;
+}
+
+bool GPUParticlesAttractorVectorField3D::_get(const StringName &p_name, Variant &r_property) const {
+ if (p_name == "extents") { // Compatibility with Godot 3.x.
+ r_property = size / 2;
+ return true;
+ }
+ return false;
+}
+#endif // DISABLE_DEPRECATED
+
+void GPUParticlesAttractorVectorField3D::set_size(const Vector3 &p_size) {
+ size = p_size;
+ RS::get_singleton()->particles_collision_set_box_extents(_get_collision(), size / 2);
update_gizmos();
}
-Vector3 GPUParticlesAttractorVectorField3D::get_extents() const {
- return extents;
+Vector3 GPUParticlesAttractorVectorField3D::get_size() const {
+ return size;
}
void GPUParticlesAttractorVectorField3D::set_texture(const Ref<Texture3D> &p_texture) {
@@ -918,7 +1008,7 @@ Ref<Texture3D> GPUParticlesAttractorVectorField3D::get_texture() const {
}
AABB GPUParticlesAttractorVectorField3D::get_aabb() const {
- return AABB(-extents, extents * 2);
+ return AABB(-size / 2, size);
}
GPUParticlesAttractorVectorField3D::GPUParticlesAttractorVectorField3D() :
diff --git a/scene/3d/gpu_particles_collision_3d.h b/scene/3d/gpu_particles_collision_3d.h
index 3c569ac73d..1649320069 100644
--- a/scene/3d/gpu_particles_collision_3d.h
+++ b/scene/3d/gpu_particles_collision_3d.h
@@ -74,14 +74,18 @@ public:
class GPUParticlesCollisionBox3D : public GPUParticlesCollision3D {
GDCLASS(GPUParticlesCollisionBox3D, GPUParticlesCollision3D);
- Vector3 extents = Vector3(1, 1, 1);
+ Vector3 size = Vector3(2, 2, 2);
protected:
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_property) const;
+#endif // DISABLE_DEPRECATED
public:
- void set_extents(const Vector3 &p_extents);
- Vector3 get_extents() const;
+ void set_size(const Vector3 &p_size);
+ Vector3 get_size() const;
virtual AABB get_aabb() const override;
@@ -108,7 +112,7 @@ public:
typedef void (*BakeEndFunc)();
private:
- Vector3 extents = Vector3(1, 1, 1);
+ Vector3 size = Vector3(2, 2, 2);
Resolution resolution = RESOLUTION_64;
uint32_t bake_mask = 0xFFFFFFFF;
Ref<Texture3D> texture;
@@ -160,6 +164,10 @@ private:
protected:
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_property) const;
+#endif // DISABLE_DEPRECATED
public:
virtual PackedStringArray get_configuration_warnings() const override;
@@ -167,8 +175,8 @@ public:
void set_thickness(float p_thickness);
float get_thickness() const;
- void set_extents(const Vector3 &p_extents);
- Vector3 get_extents() const;
+ void set_size(const Vector3 &p_size);
+ Vector3 get_size() const;
void set_resolution(Resolution p_resolution);
Resolution get_resolution() const;
@@ -217,7 +225,7 @@ public:
};
private:
- Vector3 extents = Vector3(1, 1, 1);
+ Vector3 size = Vector3(2, 2, 2);
Resolution resolution = RESOLUTION_1024;
bool follow_camera_mode = false;
@@ -226,10 +234,14 @@ private:
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_property) const;
+#endif // DISABLE_DEPRECATED
public:
- void set_extents(const Vector3 &p_extents);
- Vector3 get_extents() const;
+ void set_size(const Vector3 &p_size);
+ Vector3 get_size() const;
void set_resolution(Resolution p_resolution);
Resolution get_resolution() const;
@@ -301,14 +313,18 @@ public:
class GPUParticlesAttractorBox3D : public GPUParticlesAttractor3D {
GDCLASS(GPUParticlesAttractorBox3D, GPUParticlesAttractor3D);
- Vector3 extents = Vector3(1, 1, 1);
+ Vector3 size = Vector3(2, 2, 2);
protected:
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_property) const;
+#endif // DISABLE_DEPRECATED
public:
- void set_extents(const Vector3 &p_extents);
- Vector3 get_extents() const;
+ void set_size(const Vector3 &p_size);
+ Vector3 get_size() const;
virtual AABB get_aabb() const override;
@@ -319,15 +335,19 @@ public:
class GPUParticlesAttractorVectorField3D : public GPUParticlesAttractor3D {
GDCLASS(GPUParticlesAttractorVectorField3D, GPUParticlesAttractor3D);
- Vector3 extents = Vector3(1, 1, 1);
+ Vector3 size = Vector3(2, 2, 2);
Ref<Texture3D> texture;
protected:
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_property) const;
+#endif // DISABLE_DEPRECATED
public:
- void set_extents(const Vector3 &p_extents);
- Vector3 get_extents() const;
+ void set_size(const Vector3 &p_size);
+ Vector3 get_size() const;
void set_texture(const Ref<Texture3D> &p_texture);
Ref<Texture3D> get_texture() const;
diff --git a/scene/3d/label_3d.cpp b/scene/3d/label_3d.cpp
index f8c54809da..b39ca43d2e 100644
--- a/scene/3d/label_3d.cpp
+++ b/scene/3d/label_3d.cpp
@@ -109,6 +109,15 @@ void Label3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_alpha_scissor_threshold", "threshold"), &Label3D::set_alpha_scissor_threshold);
ClassDB::bind_method(D_METHOD("get_alpha_scissor_threshold"), &Label3D::get_alpha_scissor_threshold);
+ ClassDB::bind_method(D_METHOD("set_alpha_hash_scale", "threshold"), &Label3D::set_alpha_hash_scale);
+ ClassDB::bind_method(D_METHOD("get_alpha_hash_scale"), &Label3D::get_alpha_hash_scale);
+
+ ClassDB::bind_method(D_METHOD("set_alpha_antialiasing", "alpha_aa"), &Label3D::set_alpha_antialiasing);
+ ClassDB::bind_method(D_METHOD("get_alpha_antialiasing"), &Label3D::get_alpha_antialiasing);
+
+ ClassDB::bind_method(D_METHOD("set_alpha_antialiasing_edge", "edge"), &Label3D::set_alpha_antialiasing_edge);
+ ClassDB::bind_method(D_METHOD("get_alpha_antialiasing_edge"), &Label3D::get_alpha_antialiasing_edge);
+
ClassDB::bind_method(D_METHOD("set_texture_filter", "mode"), &Label3D::set_texture_filter);
ClassDB::bind_method(D_METHOD("get_texture_filter"), &Label3D::get_texture_filter);
@@ -127,8 +136,11 @@ void Label3D::_bind_methods() {
ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "double_sided"), "set_draw_flag", "get_draw_flag", FLAG_DOUBLE_SIDED);
ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "no_depth_test"), "set_draw_flag", "get_draw_flag", FLAG_DISABLE_DEPTH_TEST);
ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "fixed_size"), "set_draw_flag", "get_draw_flag", FLAG_FIXED_SIZE);
- ADD_PROPERTY(PropertyInfo(Variant::INT, "alpha_cut", PROPERTY_HINT_ENUM, "Disabled,Discard,Opaque Pre-Pass"), "set_alpha_cut_mode", "get_alpha_cut_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "alpha_cut", PROPERTY_HINT_ENUM, "Disabled,Discard,Opaque Pre-Pass,Alpha Hash"), "set_alpha_cut_mode", "get_alpha_cut_mode");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "alpha_scissor_threshold", PROPERTY_HINT_RANGE, "0,1,0.001"), "set_alpha_scissor_threshold", "get_alpha_scissor_threshold");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "alpha_hash_scale", PROPERTY_HINT_RANGE, "0,2,0.01"), "set_alpha_hash_scale", "get_alpha_hash_scale");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "alpha_antialiasing_mode", PROPERTY_HINT_ENUM, "Disabled,Alpha Edge Blend,Alpha Edge Clip"), "set_alpha_antialiasing", "get_alpha_antialiasing");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "alpha_antialiasing_edge", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_alpha_antialiasing_edge", "get_alpha_antialiasing_edge");
ADD_PROPERTY(PropertyInfo(Variant::INT, "texture_filter", PROPERTY_HINT_ENUM, "Nearest,Linear,Nearest Mipmap,Linear Mipmap,Nearest Mipmap Anisotropic,Linear Mipmap Anisotropic"), "set_texture_filter", "get_texture_filter");
ADD_PROPERTY(PropertyInfo(Variant::INT, "render_priority", PROPERTY_HINT_RANGE, itos(RS::MATERIAL_RENDER_PRIORITY_MIN) + "," + itos(RS::MATERIAL_RENDER_PRIORITY_MAX) + ",1"), "set_render_priority", "get_render_priority");
ADD_PROPERTY(PropertyInfo(Variant::INT, "outline_render_priority", PROPERTY_HINT_RANGE, itos(RS::MATERIAL_RENDER_PRIORITY_MIN) + "," + itos(RS::MATERIAL_RENDER_PRIORITY_MAX) + ",1"), "set_outline_render_priority", "get_outline_render_priority");
@@ -162,6 +174,7 @@ void Label3D::_bind_methods() {
BIND_ENUM_CONSTANT(ALPHA_CUT_DISABLED);
BIND_ENUM_CONSTANT(ALPHA_CUT_DISCARD);
BIND_ENUM_CONSTANT(ALPHA_CUT_OPAQUE_PREPASS);
+ BIND_ENUM_CONSTANT(ALPHA_CUT_HASH);
}
void Label3D::_validate_property(PropertyInfo &p_property) const {
@@ -350,13 +363,24 @@ void Label3D::_generate_glyph_surfaces(const Glyph &p_glyph, Vector2 &r_offset,
RS::get_singleton()->material_set_param(surf.material, "uv2_offset", Vector3(0, 0, 0));
RS::get_singleton()->material_set_param(surf.material, "uv2_scale", Vector3(1, 1, 1));
RS::get_singleton()->material_set_param(surf.material, "alpha_scissor_threshold", alpha_scissor_threshold);
+ RS::get_singleton()->material_set_param(surf.material, "alpha_hash_scale", alpha_hash_scale);
+ RS::get_singleton()->material_set_param(surf.material, "alpha_antialiasing_edge", alpha_antialiasing_edge);
if (msdf) {
RS::get_singleton()->material_set_param(surf.material, "msdf_pixel_range", TS->font_get_msdf_pixel_range(p_glyph.font_rid));
RS::get_singleton()->material_set_param(surf.material, "msdf_outline_size", p_outline_size);
}
+ BaseMaterial3D::Transparency mat_transparency = BaseMaterial3D::Transparency::TRANSPARENCY_ALPHA;
+ if (get_alpha_cut_mode() == ALPHA_CUT_DISCARD) {
+ mat_transparency = BaseMaterial3D::Transparency::TRANSPARENCY_ALPHA_SCISSOR;
+ } else if (get_alpha_cut_mode() == ALPHA_CUT_OPAQUE_PREPASS) {
+ mat_transparency = BaseMaterial3D::Transparency::TRANSPARENCY_ALPHA_DEPTH_PRE_PASS;
+ } else if (get_alpha_cut_mode() == ALPHA_CUT_HASH) {
+ mat_transparency = BaseMaterial3D::Transparency::TRANSPARENCY_ALPHA_HASH;
+ }
+
RID shader_rid;
- StandardMaterial3D::get_material_for_2d(get_draw_flag(FLAG_SHADED), true, get_draw_flag(FLAG_DOUBLE_SIDED), get_alpha_cut_mode() == ALPHA_CUT_DISCARD, get_alpha_cut_mode() == ALPHA_CUT_OPAQUE_PREPASS, get_billboard_mode() == StandardMaterial3D::BILLBOARD_ENABLED, get_billboard_mode() == StandardMaterial3D::BILLBOARD_FIXED_Y, msdf, get_draw_flag(FLAG_DISABLE_DEPTH_TEST), get_draw_flag(FLAG_FIXED_SIZE), texture_filter, &shader_rid);
+ StandardMaterial3D::get_material_for_2d(get_draw_flag(FLAG_SHADED), mat_transparency, get_draw_flag(FLAG_DOUBLE_SIDED), get_billboard_mode() == StandardMaterial3D::BILLBOARD_ENABLED, get_billboard_mode() == StandardMaterial3D::BILLBOARD_FIXED_Y, msdf, get_draw_flag(FLAG_DISABLE_DEPTH_TEST), get_draw_flag(FLAG_FIXED_SIZE), texture_filter, alpha_antialiasing_mode, &shader_rid);
RS::get_singleton()->material_set_shader(surf.material, shader_rid);
RS::get_singleton()->material_set_param(surf.material, "texture_albedo", tex);
@@ -442,7 +466,7 @@ void Label3D::_shape() {
TS->shaped_text_set_spacing(text_rid, TextServer::SpacingType(i), font->get_spacing(TextServer::SpacingType(i)));
}
- TypedArray<Vector2i> stt;
+ TypedArray<Vector3i> stt;
if (st_parser == TextServer::STRUCTURED_TEXT_CUSTOM) {
GDVIRTUAL_CALL(_structured_text_parser, st_args, txt, stt);
} else {
@@ -906,7 +930,7 @@ StandardMaterial3D::BillboardMode Label3D::get_billboard_mode() const {
}
void Label3D::set_alpha_cut_mode(AlphaCutMode p_mode) {
- ERR_FAIL_INDEX(p_mode, 3);
+ ERR_FAIL_INDEX(p_mode, ALPHA_CUT_MAX);
if (alpha_cut != p_mode) {
alpha_cut = p_mode;
_queue_update();
@@ -929,6 +953,17 @@ Label3D::AlphaCutMode Label3D::get_alpha_cut_mode() const {
return alpha_cut;
}
+void Label3D::set_alpha_hash_scale(float p_hash_scale) {
+ if (alpha_hash_scale != p_hash_scale) {
+ alpha_hash_scale = p_hash_scale;
+ _queue_update();
+ }
+}
+
+float Label3D::get_alpha_hash_scale() const {
+ return alpha_hash_scale;
+}
+
void Label3D::set_alpha_scissor_threshold(float p_threshold) {
if (alpha_scissor_threshold != p_threshold) {
alpha_scissor_threshold = p_threshold;
@@ -940,6 +975,28 @@ float Label3D::get_alpha_scissor_threshold() const {
return alpha_scissor_threshold;
}
+void Label3D::set_alpha_antialiasing(BaseMaterial3D::AlphaAntiAliasing p_alpha_aa) {
+ if (alpha_antialiasing_mode != p_alpha_aa) {
+ alpha_antialiasing_mode = p_alpha_aa;
+ _queue_update();
+ }
+}
+
+BaseMaterial3D::AlphaAntiAliasing Label3D::get_alpha_antialiasing() const {
+ return alpha_antialiasing_mode;
+}
+
+void Label3D::set_alpha_antialiasing_edge(float p_edge) {
+ if (alpha_antialiasing_edge != p_edge) {
+ alpha_antialiasing_edge = p_edge;
+ _queue_update();
+ }
+}
+
+float Label3D::get_alpha_antialiasing_edge() const {
+ return alpha_antialiasing_edge;
+}
+
Label3D::Label3D() {
for (int i = 0; i < FLAG_MAX; i++) {
flags[i] = (i == FLAG_DOUBLE_SIDED);
diff --git a/scene/3d/label_3d.h b/scene/3d/label_3d.h
index 8fc772e4b0..912f485354 100644
--- a/scene/3d/label_3d.h
+++ b/scene/3d/label_3d.h
@@ -51,7 +51,9 @@ public:
enum AlphaCutMode {
ALPHA_CUT_DISABLED,
ALPHA_CUT_DISCARD,
- ALPHA_CUT_OPAQUE_PREPASS
+ ALPHA_CUT_OPAQUE_PREPASS,
+ ALPHA_CUT_HASH,
+ ALPHA_CUT_MAX
};
private:
@@ -59,6 +61,9 @@ private:
bool flags[FLAG_MAX] = {};
AlphaCutMode alpha_cut = ALPHA_CUT_DISABLED;
float alpha_scissor_threshold = 0.5;
+ float alpha_hash_scale = 1.0;
+ StandardMaterial3D::AlphaAntiAliasing alpha_antialiasing_mode = StandardMaterial3D::ALPHA_ANTIALIASING_OFF;
+ float alpha_antialiasing_edge = 0.0f;
AABB aabb;
@@ -143,7 +148,7 @@ private:
void _generate_glyph_surfaces(const Glyph &p_glyph, Vector2 &r_offset, const Color &p_modulate, int p_priority = 0, int p_outline_size = 0);
protected:
- GDVIRTUAL2RC(Array, _structured_text_parser, Array, String)
+ GDVIRTUAL2RC(TypedArray<Vector3i>, _structured_text_parser, Array, String)
void _notification(int p_what);
@@ -228,6 +233,15 @@ public:
void set_alpha_scissor_threshold(float p_threshold);
float get_alpha_scissor_threshold() const;
+ void set_alpha_hash_scale(float p_hash_scale);
+ float get_alpha_hash_scale() const;
+
+ void set_alpha_antialiasing(BaseMaterial3D::AlphaAntiAliasing p_alpha_aa);
+ BaseMaterial3D::AlphaAntiAliasing get_alpha_antialiasing() const;
+
+ void set_alpha_antialiasing_edge(float p_edge);
+ float get_alpha_antialiasing_edge() const;
+
void set_billboard_mode(StandardMaterial3D::BillboardMode p_mode);
StandardMaterial3D::BillboardMode get_billboard_mode() const;
diff --git a/scene/3d/light_3d.cpp b/scene/3d/light_3d.cpp
index 77073ff763..cca84c2b85 100644
--- a/scene/3d/light_3d.cpp
+++ b/scene/3d/light_3d.cpp
@@ -157,9 +157,16 @@ AABB Light3D::get_aabb() const {
return AABB(Vector3(-1, -1, -1) * param[PARAM_RANGE], Vector3(2, 2, 2) * param[PARAM_RANGE]);
} else if (type == RenderingServer::LIGHT_SPOT) {
- real_t len = param[PARAM_RANGE];
- real_t size = Math::tan(Math::deg_to_rad(param[PARAM_SPOT_ANGLE])) * len;
- return AABB(Vector3(-size, -size, -len), Vector3(size * 2, size * 2, len));
+ real_t cone_slant_height = param[PARAM_RANGE];
+ real_t cone_angle_rad = Math::deg_to_rad(param[PARAM_SPOT_ANGLE]);
+
+ if (cone_angle_rad > Math_PI / 2.0) {
+ // Just return the AABB of an omni light if the spot angle is above 90 degrees.
+ return AABB(Vector3(-1, -1, -1) * cone_slant_height, Vector3(2, 2, 2) * cone_slant_height);
+ }
+
+ real_t size = Math::sin(cone_angle_rad) * cone_slant_height;
+ return AABB(Vector3(-size, -size, -cone_slant_height), Vector3(2 * size, 2 * size, cone_slant_height));
}
return AABB();
diff --git a/scene/3d/lightmap_gi.cpp b/scene/3d/lightmap_gi.cpp
index a6d63619df..fb74cffc94 100644
--- a/scene/3d/lightmap_gi.cpp
+++ b/scene/3d/lightmap_gi.cpp
@@ -455,8 +455,8 @@ int32_t LightmapGI::_compute_bsp_tree(const Vector<Vector3> &p_points, const Loc
Plane best_plane;
float best_plane_score = -1.0;
- for (uint32_t i = 0; i < p_simplex_indices.size(); i++) {
- const BSPSimplex &s = p_simplices[p_simplex_indices[i]];
+ for (const int idx : p_simplex_indices) {
+ const BSPSimplex &s = p_simplices[idx];
for (int j = 0; j < 4; j++) {
uint32_t plane_index = s.planes[j];
if (planes_tested[plane_index] == node_index) {
@@ -484,8 +484,8 @@ int32_t LightmapGI::_compute_bsp_tree(const Vector<Vector3> &p_points, const Loc
int over_count = 0;
int under_count = 0;
- for (uint32_t k = 0; k < p_simplex_indices.size(); k++) {
- int side = _bsp_get_simplex_side(p_points, p_simplices, plane, p_simplex_indices[k]);
+ for (const int &index : p_simplex_indices) {
+ int side = _bsp_get_simplex_side(p_points, p_simplices, plane, index);
if (side == -2) {
continue; //this simplex is invalid, skip for now
} else if (side < 0) {
@@ -523,8 +523,7 @@ int32_t LightmapGI::_compute_bsp_tree(const Vector<Vector3> &p_points, const Loc
LocalVector<int32_t> indices_under;
//split again, but add to list
- for (uint32_t i = 0; i < p_simplex_indices.size(); i++) {
- uint32_t index = p_simplex_indices[i];
+ for (const uint32_t index : p_simplex_indices) {
int side = _bsp_get_simplex_side(p_points, p_simplices, best_plane, index);
if (side == -2) {
@@ -763,7 +762,15 @@ LightmapGI::BakeError LightmapGI::bake(Node *p_from_node, String p_image_data_pa
MeshesFound &mf = meshes_found.write[m_i];
- Size2i lightmap_size = mf.mesh->get_lightmap_size_hint() * mf.lightmap_scale;
+ Size2i lightmap_size = mf.mesh->get_lightmap_size_hint();
+
+ if (lightmap_size == Size2i(0, 0)) {
+ // TODO we should compute a size if no lightmap hint is set, as we did in 3.x.
+ // For now set to basic size to avoid crash.
+ lightmap_size = Size2i(64, 64);
+ }
+
+ lightmap_size *= mf.lightmap_scale;
TypedArray<RID> overrides;
overrides.resize(mf.overrides.size());
for (int i = 0; i < mf.overrides.size(); i++) {
@@ -969,8 +976,8 @@ LightmapGI::BakeError LightmapGI::bake(Node *p_from_node, String p_image_data_pa
}
}
- for (uint32_t i = 0; i < new_probe_positions.size(); i++) {
- probes_found.push_back(new_probe_positions[i]);
+ for (const Vector3 &position : new_probe_positions) {
+ probes_found.push_back(position);
}
}
@@ -1211,8 +1218,8 @@ LightmapGI::BakeError LightmapGI::bake(Node *p_from_node, String p_image_data_pa
LocalVector<BSPNode> bsp_nodes;
LocalVector<int32_t> planes_tested;
planes_tested.resize(bsp_planes.size());
- for (uint32_t i = 0; i < planes_tested.size(); i++) {
- planes_tested[i] = 0x7FFFFFFF;
+ for (int &index : planes_tested) {
+ index = 0x7FFFFFFF;
}
if (p_bake_step) {
@@ -1538,6 +1545,8 @@ void LightmapGI::_bind_methods() {
BIND_ENUM_CONSTANT(GENERATE_PROBES_SUBDIV_32);
BIND_ENUM_CONSTANT(BAKE_ERROR_OK);
+ BIND_ENUM_CONSTANT(BAKE_ERROR_NO_SCENE_ROOT);
+ BIND_ENUM_CONSTANT(BAKE_ERROR_FOREIGN_DATA);
BIND_ENUM_CONSTANT(BAKE_ERROR_NO_LIGHTMAPPER);
BIND_ENUM_CONSTANT(BAKE_ERROR_NO_SAVE_PATH);
BIND_ENUM_CONSTANT(BAKE_ERROR_NO_MESHES);
diff --git a/scene/3d/lightmap_gi.h b/scene/3d/lightmap_gi.h
index 1294571cc0..40ff9e4cad 100644
--- a/scene/3d/lightmap_gi.h
+++ b/scene/3d/lightmap_gi.h
@@ -124,6 +124,8 @@ public:
enum BakeError {
BAKE_ERROR_OK,
+ BAKE_ERROR_NO_SCENE_ROOT,
+ BAKE_ERROR_FOREIGN_DATA,
BAKE_ERROR_NO_LIGHTMAPPER,
BAKE_ERROR_NO_SAVE_PATH,
BAKE_ERROR_NO_MESHES,
diff --git a/scene/3d/navigation_agent_3d.cpp b/scene/3d/navigation_agent_3d.cpp
index 0034bf78b9..081e7505d0 100644
--- a/scene/3d/navigation_agent_3d.cpp
+++ b/scene/3d/navigation_agent_3d.cpp
@@ -80,10 +80,10 @@ void NavigationAgent3D::_bind_methods() {
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);
- ClassDB::bind_method(D_METHOD("set_target_location", "location"), &NavigationAgent3D::set_target_location);
- ClassDB::bind_method(D_METHOD("get_target_location"), &NavigationAgent3D::get_target_location);
+ ClassDB::bind_method(D_METHOD("set_target_position", "position"), &NavigationAgent3D::set_target_position);
+ ClassDB::bind_method(D_METHOD("get_target_position"), &NavigationAgent3D::get_target_position);
- ClassDB::bind_method(D_METHOD("get_next_location"), &NavigationAgent3D::get_next_location);
+ ClassDB::bind_method(D_METHOD("get_next_path_position"), &NavigationAgent3D::get_next_path_position);
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_current_navigation_result"), &NavigationAgent3D::get_current_navigation_result);
@@ -92,12 +92,12 @@ void NavigationAgent3D::_bind_methods() {
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);
- ClassDB::bind_method(D_METHOD("get_final_location"), &NavigationAgent3D::get_final_location);
+ ClassDB::bind_method(D_METHOD("get_final_position"), &NavigationAgent3D::get_final_position);
ClassDB::bind_method(D_METHOD("_avoidance_done", "new_velocity"), &NavigationAgent3D::_avoidance_done);
ADD_GROUP("Pathfinding", "");
- ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "target_location", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "set_target_location", "get_target_location");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "target_position", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "set_target_position", "get_target_position");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "path_desired_distance", PROPERTY_HINT_RANGE, "0.1,100,0.01,suffix:m"), "set_path_desired_distance", "get_path_desired_distance");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "target_desired_distance", PROPERTY_HINT_RANGE, "0.1,100,0.01,suffix:m"), "set_target_desired_distance", "get_target_desired_distance");
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");
@@ -120,15 +120,36 @@ void NavigationAgent3D::_bind_methods() {
ADD_SIGNAL(MethodInfo("link_reached", PropertyInfo(Variant::DICTIONARY, "details")));
ADD_SIGNAL(MethodInfo("navigation_finished"));
ADD_SIGNAL(MethodInfo("velocity_computed", PropertyInfo(Variant::VECTOR3, "safe_velocity")));
+
+ ClassDB::bind_method(D_METHOD("set_debug_enabled", "enabled"), &NavigationAgent3D::set_debug_enabled);
+ ClassDB::bind_method(D_METHOD("get_debug_enabled"), &NavigationAgent3D::get_debug_enabled);
+ ClassDB::bind_method(D_METHOD("set_debug_use_custom", "enabled"), &NavigationAgent3D::set_debug_use_custom);
+ ClassDB::bind_method(D_METHOD("get_debug_use_custom"), &NavigationAgent3D::get_debug_use_custom);
+ ClassDB::bind_method(D_METHOD("set_debug_path_custom_color", "color"), &NavigationAgent3D::set_debug_path_custom_color);
+ ClassDB::bind_method(D_METHOD("get_debug_path_custom_color"), &NavigationAgent3D::get_debug_path_custom_color);
+ ClassDB::bind_method(D_METHOD("set_debug_path_custom_point_size", "point_size"), &NavigationAgent3D::set_debug_path_custom_point_size);
+ ClassDB::bind_method(D_METHOD("get_debug_path_custom_point_size"), &NavigationAgent3D::get_debug_path_custom_point_size);
+
+ ADD_GROUP("Debug", "");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "debug_enabled"), "set_debug_enabled", "get_debug_enabled");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "debug_use_custom"), "set_debug_use_custom", "get_debug_use_custom");
+ ADD_PROPERTY(PropertyInfo(Variant::COLOR, "debug_path_custom_color"), "set_debug_path_custom_color", "get_debug_path_custom_color");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "debug_path_custom_point_size", PROPERTY_HINT_RANGE, "1,50,1,suffix:px"), "set_debug_path_custom_point_size", "get_debug_path_custom_point_size");
}
void NavigationAgent3D::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_POST_ENTER_TREE: {
// need to use POST_ENTER_TREE cause with normal ENTER_TREE not all required Nodes are ready.
- // cannot use READY as ready does not get called if Node is readded to SceneTree
+ // cannot use READY as ready does not get called if Node is re-added to SceneTree
set_agent_parent(get_parent());
set_physics_process_internal(true);
+
+#ifdef DEBUG_ENABLED
+ if (NavigationServer3D::get_singleton()->get_debug_enabled()) {
+ debug_path_dirty = true;
+ }
+#endif // DEBUG_ENABLED
} break;
case NOTIFICATION_PARENTED: {
@@ -151,6 +172,12 @@ void NavigationAgent3D::_notification(int p_what) {
case NOTIFICATION_EXIT_TREE: {
set_agent_parent(nullptr);
set_physics_process_internal(false);
+
+#ifdef DEBUG_ENABLED
+ if (debug_path_instance.is_valid()) {
+ RS::get_singleton()->instance_set_visible(debug_path_instance, false);
+ }
+#endif // DEBUG_ENABLED
} break;
case NOTIFICATION_PAUSED: {
@@ -178,22 +205,27 @@ void NavigationAgent3D::_notification(int p_what) {
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
- NavigationServer3D::get_singleton()->agent_set_position(agent, agent_parent->get_global_transform().origin);
+ NavigationServer3D::get_singleton()->agent_set_position(agent, agent_parent->get_global_position());
}
_check_distance_to_target();
}
+#ifdef DEBUG_ENABLED
+ if (debug_path_dirty) {
+ _update_debug_path();
+ }
+#endif // DEBUG_ENABLED
} break;
}
}
NavigationAgent3D::NavigationAgent3D() {
agent = NavigationServer3D::get_singleton()->agent_create();
- set_neighbor_distance(50.0);
- set_max_neighbors(10);
- set_time_horizon(5.0);
- set_radius(1.0);
- set_max_speed(10.0);
- set_ignore_y(true);
+ NavigationServer3D::get_singleton()->agent_set_neighbor_distance(agent, neighbor_distance);
+ NavigationServer3D::get_singleton()->agent_set_max_neighbors(agent, max_neighbors);
+ NavigationServer3D::get_singleton()->agent_set_time_horizon(agent, time_horizon);
+ NavigationServer3D::get_singleton()->agent_set_radius(agent, radius);
+ NavigationServer3D::get_singleton()->agent_set_max_speed(agent, max_speed);
+ NavigationServer3D::get_singleton()->agent_set_ignore_y(agent, ignore_y);
// Preallocate query and result objects to improve performance.
navigation_query = Ref<NavigationPathQueryParameters3D>();
@@ -201,20 +233,41 @@ NavigationAgent3D::NavigationAgent3D() {
navigation_result = Ref<NavigationPathQueryResult3D>();
navigation_result.instantiate();
+
+#ifdef DEBUG_ENABLED
+ NavigationServer3D::get_singleton()->connect(SNAME("navigation_debug_changed"), callable_mp(this, &NavigationAgent3D::_navigation_debug_changed));
+#endif // DEBUG_ENABLED
}
NavigationAgent3D::~NavigationAgent3D() {
ERR_FAIL_NULL(NavigationServer3D::get_singleton());
NavigationServer3D::get_singleton()->free(agent);
agent = RID(); // Pointless
+
+#ifdef DEBUG_ENABLED
+ NavigationServer3D::get_singleton()->disconnect(SNAME("navigation_debug_changed"), callable_mp(this, &NavigationAgent3D::_navigation_debug_changed));
+
+ ERR_FAIL_NULL(RenderingServer::get_singleton());
+ if (debug_path_instance.is_valid()) {
+ RenderingServer::get_singleton()->free(debug_path_instance);
+ }
+ if (debug_path_mesh.is_valid()) {
+ RenderingServer::get_singleton()->free(debug_path_mesh->get_rid());
+ }
+#endif // DEBUG_ENABLED
}
void NavigationAgent3D::set_avoidance_enabled(bool p_enabled) {
+ if (avoidance_enabled == p_enabled) {
+ return;
+ }
+
avoidance_enabled = p_enabled;
+
if (avoidance_enabled) {
- NavigationServer3D::get_singleton()->agent_set_callback(agent, get_instance_id(), "_avoidance_done");
+ NavigationServer3D::get_singleton()->agent_set_callback(agent, callable_mp(this, &NavigationAgent3D::_avoidance_done));
} else {
- NavigationServer3D::get_singleton()->agent_set_callback(agent, ObjectID(), "_avoidance_done");
+ NavigationServer3D::get_singleton()->agent_set_callback(agent, Callable());
}
}
@@ -223,8 +276,13 @@ bool NavigationAgent3D::get_avoidance_enabled() const {
}
void NavigationAgent3D::set_agent_parent(Node *p_agent_parent) {
+ if (agent_parent == p_agent_parent) {
+ return;
+ }
+
// 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, ObjectID(), "_avoidance_done");
+ NavigationServer3D::get_singleton()->agent_set_callback(agent, Callable());
+
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);
@@ -233,8 +291,11 @@ void NavigationAgent3D::set_agent_parent(Node *p_agent_parent) {
} else {
NavigationServer3D::get_singleton()->agent_set_map(get_rid(), agent_parent->get_world_3d()->get_navigation_map());
}
+
// create new avoidance callback if enabled
- set_avoidance_enabled(avoidance_enabled);
+ if (avoidance_enabled) {
+ NavigationServer3D::get_singleton()->agent_set_callback(agent, callable_mp(this, &NavigationAgent3D::_avoidance_done));
+ }
} else {
agent_parent = nullptr;
NavigationServer3D::get_singleton()->agent_set_map(get_rid(), RID());
@@ -242,11 +303,13 @@ void NavigationAgent3D::set_agent_parent(Node *p_agent_parent) {
}
void NavigationAgent3D::set_navigation_layers(uint32_t p_navigation_layers) {
- bool navigation_layers_changed = navigation_layers != p_navigation_layers;
- navigation_layers = p_navigation_layers;
- if (navigation_layers_changed) {
- _request_repath();
+ if (navigation_layers == p_navigation_layers) {
+ return;
}
+
+ navigation_layers = p_navigation_layers;
+
+ _request_repath();
}
uint32_t NavigationAgent3D::get_navigation_layers() const {
@@ -280,7 +343,12 @@ void NavigationAgent3D::set_path_metadata_flags(BitField<NavigationPathQueryPara
}
void NavigationAgent3D::set_navigation_map(RID p_navigation_map) {
+ if (map_override == p_navigation_map) {
+ return;
+ }
+
map_override = p_navigation_map;
+
NavigationServer3D::get_singleton()->agent_set_map(agent, map_override);
_request_repath();
}
@@ -294,73 +362,123 @@ RID NavigationAgent3D::get_navigation_map() const {
return RID();
}
-void NavigationAgent3D::set_path_desired_distance(real_t p_dd) {
- path_desired_distance = p_dd;
+void NavigationAgent3D::set_path_desired_distance(real_t p_path_desired_distance) {
+ if (Math::is_equal_approx(path_desired_distance, p_path_desired_distance)) {
+ return;
+ }
+
+ path_desired_distance = p_path_desired_distance;
}
-void NavigationAgent3D::set_target_desired_distance(real_t p_dd) {
- target_desired_distance = p_dd;
+void NavigationAgent3D::set_target_desired_distance(real_t p_target_desired_distance) {
+ if (Math::is_equal_approx(target_desired_distance, p_target_desired_distance)) {
+ return;
+ }
+
+ target_desired_distance = p_target_desired_distance;
}
void NavigationAgent3D::set_radius(real_t p_radius) {
+ if (Math::is_equal_approx(radius, p_radius)) {
+ return;
+ }
+
radius = p_radius;
+
NavigationServer3D::get_singleton()->agent_set_radius(agent, radius);
}
-void NavigationAgent3D::set_agent_height_offset(real_t p_hh) {
- navigation_height_offset = p_hh;
+void NavigationAgent3D::set_agent_height_offset(real_t p_agent_height_offset) {
+ if (Math::is_equal_approx(navigation_height_offset, p_agent_height_offset)) {
+ return;
+ }
+
+ navigation_height_offset = p_agent_height_offset;
}
void NavigationAgent3D::set_ignore_y(bool p_ignore_y) {
+ if (ignore_y == p_ignore_y) {
+ return;
+ }
+
ignore_y = p_ignore_y;
+
NavigationServer3D::get_singleton()->agent_set_ignore_y(agent, ignore_y);
}
void NavigationAgent3D::set_neighbor_distance(real_t p_distance) {
+ if (Math::is_equal_approx(neighbor_distance, p_distance)) {
+ return;
+ }
+
neighbor_distance = p_distance;
+
NavigationServer3D::get_singleton()->agent_set_neighbor_distance(agent, neighbor_distance);
}
void NavigationAgent3D::set_max_neighbors(int p_count) {
+ if (max_neighbors == p_count) {
+ return;
+ }
+
max_neighbors = p_count;
+
NavigationServer3D::get_singleton()->agent_set_max_neighbors(agent, max_neighbors);
}
void NavigationAgent3D::set_time_horizon(real_t p_time) {
+ if (Math::is_equal_approx(time_horizon, p_time)) {
+ return;
+ }
+
time_horizon = p_time;
+
NavigationServer3D::get_singleton()->agent_set_time_horizon(agent, time_horizon);
}
void NavigationAgent3D::set_max_speed(real_t p_max_speed) {
+ if (Math::is_equal_approx(max_speed, p_max_speed)) {
+ return;
+ }
+
max_speed = p_max_speed;
+
NavigationServer3D::get_singleton()->agent_set_max_speed(agent, max_speed);
}
-void NavigationAgent3D::set_path_max_distance(real_t p_pmd) {
- path_max_distance = p_pmd;
+void NavigationAgent3D::set_path_max_distance(real_t p_path_max_distance) {
+ if (Math::is_equal_approx(path_max_distance, p_path_max_distance)) {
+ return;
+ }
+
+ path_max_distance = p_path_max_distance;
}
real_t NavigationAgent3D::get_path_max_distance() {
return path_max_distance;
}
-void NavigationAgent3D::set_target_location(Vector3 p_location) {
- target_location = p_location;
+void NavigationAgent3D::set_target_position(Vector3 p_position) {
+ // Intentionally not checking for equality of the parameter, as we want to update the path even if the target position is the same in case the world changed.
+ // Revisit later when the navigation server can update the path without requesting a new path.
+
+ target_position = p_position;
target_position_submitted = true;
+
_request_repath();
}
-Vector3 NavigationAgent3D::get_target_location() const {
- return target_location;
+Vector3 NavigationAgent3D::get_target_position() const {
+ return target_position;
}
-Vector3 NavigationAgent3D::get_next_location() {
+Vector3 NavigationAgent3D::get_next_path_position() {
update_navigation();
const Vector<Vector3> &navigation_path = navigation_result->get_path();
if (navigation_path.size() == 0) {
ERR_FAIL_COND_V_MSG(agent_parent == nullptr, Vector3(), "The agent has no parent.");
- return agent_parent->get_global_transform().origin;
+ return agent_parent->get_global_position();
} else {
return navigation_path[navigation_path_index] - Vector3(0, navigation_height_offset, 0);
}
@@ -368,7 +486,7 @@ Vector3 NavigationAgent3D::get_next_location() {
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);
+ return agent_parent->get_global_position().distance_to(target_position);
}
bool NavigationAgent3D::is_target_reached() const {
@@ -376,7 +494,7 @@ bool NavigationAgent3D::is_target_reached() const {
}
bool NavigationAgent3D::is_target_reachable() {
- return target_desired_distance >= get_final_location().distance_to(target_location);
+ return target_desired_distance >= get_final_position().distance_to(target_position);
}
bool NavigationAgent3D::is_navigation_finished() {
@@ -384,7 +502,7 @@ bool NavigationAgent3D::is_navigation_finished() {
return navigation_finished;
}
-Vector3 NavigationAgent3D::get_final_location() {
+Vector3 NavigationAgent3D::get_final_position() {
update_navigation();
const Vector<Vector3> &navigation_path = navigation_result->get_path();
@@ -395,10 +513,15 @@ Vector3 NavigationAgent3D::get_final_location() {
}
void NavigationAgent3D::set_velocity(Vector3 p_velocity) {
+ // Intentionally not checking for equality of the parameter.
+ // We need to always submit the velocity to the navigation server, even when it is the same, in order to run avoidance every frame.
+ // Revisit later when the navigation server can update avoidance without users resubmitting the velocity.
+
target_velocity = p_velocity;
+ velocity_submitted = true;
+
NavigationServer3D::get_singleton()->agent_set_target_velocity(agent, target_velocity);
NavigationServer3D::get_singleton()->agent_set_velocity(agent, prev_safe_velocity);
- velocity_submitted = true;
}
void NavigationAgent3D::_avoidance_done(Vector3 p_new_velocity) {
@@ -439,7 +562,7 @@ void NavigationAgent3D::update_navigation() {
update_frame_id = Engine::get_singleton()->get_physics_frames();
- Vector3 origin = agent_parent->get_global_transform().origin;
+ Vector3 origin = agent_parent->get_global_position();
bool reload_path = false;
@@ -467,7 +590,7 @@ void NavigationAgent3D::update_navigation() {
if (reload_path) {
navigation_query->set_start_position(origin);
- navigation_query->set_target_position(target_location);
+ navigation_query->set_target_position(target_position);
navigation_query->set_navigation_layers(navigation_layers);
navigation_query->set_metadata_flags(path_metadata_flags);
@@ -478,6 +601,9 @@ void NavigationAgent3D::update_navigation() {
}
NavigationServer3D::get_singleton()->query_path(navigation_query, navigation_result);
+#ifdef DEBUG_ENABLED
+ debug_path_dirty = true;
+#endif // DEBUG_ENABLED
navigation_finished = false;
navigation_path_index = 0;
emit_signal(SNAME("path_changed"));
@@ -489,7 +615,7 @@ void NavigationAgent3D::update_navigation() {
// Check if we can advance the navigation path
if (navigation_finished == false) {
- // Advances to the next far away location.
+ // Advances to the next far away position.
const Vector<Vector3> &navigation_path = navigation_result->get_path();
const Vector<int32_t> &navigation_path_types = navigation_result->get_path_types();
const TypedArray<RID> &navigation_path_rids = navigation_result->get_path_rids();
@@ -499,7 +625,7 @@ void NavigationAgent3D::update_navigation() {
Dictionary details;
const Vector3 waypoint = navigation_path[navigation_path_index];
- details[SNAME("location")] = waypoint;
+ details[SNAME("position")] = waypoint;
int waypoint_type = -1;
if (path_metadata_flags.has_flag(NavigationPathQueryParameters3D::PathMetadataFlags::PATH_METADATA_INCLUDE_TYPES)) {
@@ -564,3 +690,154 @@ void NavigationAgent3D::_check_distance_to_target() {
}
}
}
+
+////////DEBUG////////////////////////////////////////////////////////////
+
+void NavigationAgent3D::set_debug_enabled(bool p_enabled) {
+#ifdef DEBUG_ENABLED
+ if (debug_enabled == p_enabled) {
+ return;
+ }
+
+ debug_enabled = p_enabled;
+ debug_path_dirty = true;
+#endif // DEBUG_ENABLED
+}
+
+bool NavigationAgent3D::get_debug_enabled() const {
+ return debug_enabled;
+}
+
+void NavigationAgent3D::set_debug_use_custom(bool p_enabled) {
+#ifdef DEBUG_ENABLED
+ if (debug_use_custom == p_enabled) {
+ return;
+ }
+
+ debug_use_custom = p_enabled;
+ debug_path_dirty = true;
+#endif // DEBUG_ENABLED
+}
+
+bool NavigationAgent3D::get_debug_use_custom() const {
+ return debug_use_custom;
+}
+
+void NavigationAgent3D::set_debug_path_custom_color(Color p_color) {
+#ifdef DEBUG_ENABLED
+ if (debug_path_custom_color == p_color) {
+ return;
+ }
+
+ debug_path_custom_color = p_color;
+ debug_path_dirty = true;
+#endif // DEBUG_ENABLED
+}
+
+Color NavigationAgent3D::get_debug_path_custom_color() const {
+ return debug_path_custom_color;
+}
+
+void NavigationAgent3D::set_debug_path_custom_point_size(float p_point_size) {
+#ifdef DEBUG_ENABLED
+ if (Math::is_equal_approx(debug_path_custom_point_size, p_point_size)) {
+ return;
+ }
+
+ debug_path_custom_point_size = p_point_size;
+ debug_path_dirty = true;
+#endif // DEBUG_ENABLED
+}
+
+float NavigationAgent3D::get_debug_path_custom_point_size() const {
+ return debug_path_custom_point_size;
+}
+
+#ifdef DEBUG_ENABLED
+void NavigationAgent3D::_navigation_debug_changed() {
+ debug_path_dirty = true;
+}
+
+void NavigationAgent3D::_update_debug_path() {
+ if (!debug_path_dirty) {
+ return;
+ }
+ debug_path_dirty = false;
+
+ if (!debug_path_instance.is_valid()) {
+ debug_path_instance = RenderingServer::get_singleton()->instance_create();
+ }
+
+ if (!debug_path_mesh.is_valid()) {
+ debug_path_mesh = Ref<ArrayMesh>(memnew(ArrayMesh));
+ }
+
+ debug_path_mesh->clear_surfaces();
+
+ if (!(debug_enabled && NavigationServer3D::get_singleton()->get_debug_navigation_enable_agent_paths())) {
+ return;
+ }
+
+ if (!(agent_parent && agent_parent->is_inside_tree())) {
+ return;
+ }
+
+ const Vector<Vector3> &navigation_path = navigation_result->get_path();
+
+ if (navigation_path.size() <= 1) {
+ return;
+ }
+
+ Vector<Vector3> debug_path_lines_vertex_array;
+
+ for (int i = 0; i < navigation_path.size() - 1; i++) {
+ debug_path_lines_vertex_array.push_back(navigation_path[i]);
+ debug_path_lines_vertex_array.push_back(navigation_path[i + 1]);
+ }
+
+ Array debug_path_lines_mesh_array;
+ debug_path_lines_mesh_array.resize(Mesh::ARRAY_MAX);
+ debug_path_lines_mesh_array[Mesh::ARRAY_VERTEX] = debug_path_lines_vertex_array;
+
+ debug_path_mesh->add_surface_from_arrays(Mesh::PRIMITIVE_LINES, debug_path_lines_mesh_array);
+
+ Ref<StandardMaterial3D> debug_agent_path_line_material = NavigationServer3D::get_singleton()->get_debug_navigation_agent_path_line_material();
+ if (debug_use_custom) {
+ if (!debug_agent_path_line_custom_material.is_valid()) {
+ debug_agent_path_line_custom_material = debug_agent_path_line_material->duplicate();
+ }
+ debug_agent_path_line_custom_material->set_albedo(debug_path_custom_color);
+ debug_path_mesh->surface_set_material(0, debug_agent_path_line_custom_material);
+ } else {
+ debug_path_mesh->surface_set_material(0, debug_agent_path_line_material);
+ }
+
+ Vector<Vector3> debug_path_points_vertex_array;
+
+ for (int i = 0; i < navigation_path.size(); i++) {
+ debug_path_points_vertex_array.push_back(navigation_path[i]);
+ }
+
+ Array debug_path_points_mesh_array;
+ debug_path_points_mesh_array.resize(Mesh::ARRAY_MAX);
+ debug_path_points_mesh_array[Mesh::ARRAY_VERTEX] = debug_path_lines_vertex_array;
+
+ debug_path_mesh->add_surface_from_arrays(Mesh::PRIMITIVE_POINTS, debug_path_points_mesh_array);
+
+ Ref<StandardMaterial3D> debug_agent_path_point_material = NavigationServer3D::get_singleton()->get_debug_navigation_agent_path_point_material();
+ if (debug_use_custom) {
+ if (!debug_agent_path_point_custom_material.is_valid()) {
+ debug_agent_path_point_custom_material = debug_agent_path_point_material->duplicate();
+ }
+ debug_agent_path_point_custom_material->set_albedo(debug_path_custom_color);
+ debug_agent_path_point_custom_material->set_point_size(debug_path_custom_point_size);
+ debug_path_mesh->surface_set_material(1, debug_agent_path_point_custom_material);
+ } else {
+ debug_path_mesh->surface_set_material(1, debug_agent_path_point_material);
+ }
+
+ RS::get_singleton()->instance_set_base(debug_path_instance, debug_path_mesh->get_rid());
+ RS::get_singleton()->instance_set_scenario(debug_path_instance, agent_parent->get_world_3d()->get_scenario());
+ RS::get_singleton()->instance_set_visible(debug_path_instance, agent_parent->is_visible_in_tree());
+}
+#endif // DEBUG_ENABLED
diff --git a/scene/3d/navigation_agent_3d.h b/scene/3d/navigation_agent_3d.h
index 91be068392..072ca1d3e8 100644
--- a/scene/3d/navigation_agent_3d.h
+++ b/scene/3d/navigation_agent_3d.h
@@ -52,17 +52,16 @@ class NavigationAgent3D : public Node {
real_t path_desired_distance = 1.0;
real_t target_desired_distance = 1.0;
- real_t radius = 0.0;
+ real_t radius = 1.0;
real_t navigation_height_offset = 0.0;
- bool ignore_y = false;
- real_t neighbor_distance = 0.0;
- int max_neighbors = 0;
- real_t time_horizon = 0.0;
- real_t max_speed = 0.0;
-
+ bool ignore_y = true;
+ real_t neighbor_distance = 50.0;
+ int max_neighbors = 10;
+ real_t time_horizon = 5.0;
+ real_t max_speed = 10.0;
real_t path_max_distance = 3.0;
- Vector3 target_location;
+ Vector3 target_position;
bool target_position_submitted = false;
Ref<NavigationPathQueryParameters3D> navigation_query;
Ref<NavigationPathQueryResult3D> navigation_result;
@@ -76,6 +75,24 @@ class NavigationAgent3D : public Node {
// No initialized on purpose
uint32_t update_frame_id = 0;
+ // Debug properties for exposed bindings
+ bool debug_enabled = false;
+ float debug_path_custom_point_size = 4.0;
+ bool debug_use_custom = false;
+ Color debug_path_custom_color = Color(1.0, 1.0, 1.0, 1.0);
+#ifdef DEBUG_ENABLED
+ // Debug properties internal only
+ bool debug_path_dirty = true;
+ RID debug_path_instance;
+ Ref<ArrayMesh> debug_path_mesh;
+ Ref<StandardMaterial3D> debug_agent_path_line_custom_material;
+ Ref<StandardMaterial3D> debug_agent_path_point_custom_material;
+
+private:
+ void _navigation_debug_changed();
+ void _update_debug_path();
+#endif // DEBUG_ENABLED
+
protected:
static void _bind_methods();
void _notification(int p_what);
@@ -155,10 +172,10 @@ public:
void set_path_max_distance(real_t p_pmd);
real_t get_path_max_distance();
- void set_target_location(Vector3 p_location);
- Vector3 get_target_location() const;
+ void set_target_position(Vector3 p_position);
+ Vector3 get_target_position() const;
- Vector3 get_next_location();
+ Vector3 get_next_path_position();
Ref<NavigationPathQueryResult3D> get_current_navigation_result() const {
return navigation_result;
@@ -174,13 +191,25 @@ public:
bool is_target_reached() const;
bool is_target_reachable();
bool is_navigation_finished();
- Vector3 get_final_location();
+ Vector3 get_final_position();
void set_velocity(Vector3 p_velocity);
void _avoidance_done(Vector3 p_new_velocity);
PackedStringArray get_configuration_warnings() const override;
+ void set_debug_enabled(bool p_enabled);
+ bool get_debug_enabled() const;
+
+ void set_debug_use_custom(bool p_enabled);
+ bool get_debug_use_custom() const;
+
+ void set_debug_path_custom_color(Color p_color);
+ Color get_debug_path_custom_color() const;
+
+ void set_debug_path_custom_point_size(float p_point_size);
+ float get_debug_path_custom_point_size() const;
+
private:
void update_navigation();
void _request_repath();
diff --git a/scene/3d/navigation_link_3d.cpp b/scene/3d/navigation_link_3d.cpp
index b64cf11c05..f47fcfaf51 100644
--- a/scene/3d/navigation_link_3d.cpp
+++ b/scene/3d/navigation_link_3d.cpp
@@ -70,10 +70,10 @@ void NavigationLink3D::_update_debug_mesh() {
Vector<Vector3> lines;
// Draw line between the points.
- lines.push_back(start_location);
- lines.push_back(end_location);
+ lines.push_back(start_position);
+ lines.push_back(end_position);
- // Draw start location search radius
+ // Draw start position search radius
for (int i = 0; i < 30; i++) {
// Create a circle
const float ra = Math::deg_to_rad((float)(i * 12));
@@ -84,21 +84,21 @@ void NavigationLink3D::_update_debug_mesh() {
// Draw axis-aligned circle
switch (up_axis) {
case Vector3::AXIS_X:
- lines.append(start_location + Vector3(0, a.x, a.y));
- lines.append(start_location + Vector3(0, b.x, b.y));
+ lines.append(start_position + Vector3(0, a.x, a.y));
+ lines.append(start_position + Vector3(0, b.x, b.y));
break;
case Vector3::AXIS_Y:
- lines.append(start_location + Vector3(a.x, 0, a.y));
- lines.append(start_location + Vector3(b.x, 0, b.y));
+ lines.append(start_position + Vector3(a.x, 0, a.y));
+ lines.append(start_position + Vector3(b.x, 0, b.y));
break;
case Vector3::AXIS_Z:
- lines.append(start_location + Vector3(a.x, a.y, 0));
- lines.append(start_location + Vector3(b.x, b.y, 0));
+ lines.append(start_position + Vector3(a.x, a.y, 0));
+ lines.append(start_position + Vector3(b.x, b.y, 0));
break;
}
}
- // Draw end location search radius
+ // Draw end position search radius
for (int i = 0; i < 30; i++) {
// Create a circle
const float ra = Math::deg_to_rad((float)(i * 12));
@@ -109,16 +109,16 @@ void NavigationLink3D::_update_debug_mesh() {
// Draw axis-aligned circle
switch (up_axis) {
case Vector3::AXIS_X:
- lines.append(end_location + Vector3(0, a.x, a.y));
- lines.append(end_location + Vector3(0, b.x, b.y));
+ lines.append(end_position + Vector3(0, a.x, a.y));
+ lines.append(end_position + Vector3(0, b.x, b.y));
break;
case Vector3::AXIS_Y:
- lines.append(end_location + Vector3(a.x, 0, a.y));
- lines.append(end_location + Vector3(b.x, 0, b.y));
+ lines.append(end_position + Vector3(a.x, 0, a.y));
+ lines.append(end_position + Vector3(b.x, 0, b.y));
break;
case Vector3::AXIS_Z:
- lines.append(end_location + Vector3(a.x, a.y, 0));
- lines.append(end_location + Vector3(b.x, b.y, 0));
+ lines.append(end_position + Vector3(a.x, a.y, 0));
+ lines.append(end_position + Vector3(b.x, b.y, 0));
break;
}
}
@@ -133,8 +133,8 @@ void NavigationLink3D::_update_debug_mesh() {
RS::get_singleton()->instance_set_scenario(debug_instance, get_world_3d()->get_scenario());
RS::get_singleton()->instance_set_visible(debug_instance, is_visible_in_tree());
- Ref<StandardMaterial3D> link_material = NavigationServer3D::get_singleton_mut()->get_debug_navigation_link_connections_material();
- Ref<StandardMaterial3D> disabled_link_material = NavigationServer3D::get_singleton_mut()->get_debug_navigation_link_connections_disabled_material();
+ Ref<StandardMaterial3D> link_material = NavigationServer3D::get_singleton()->get_debug_navigation_link_connections_material();
+ Ref<StandardMaterial3D> disabled_link_material = NavigationServer3D::get_singleton()->get_debug_navigation_link_connections_disabled_material();
if (enabled) {
RS::get_singleton()->instance_set_surface_override_material(debug_instance, 0, link_material->get_rid());
@@ -157,11 +157,11 @@ void NavigationLink3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_navigation_layer_value", "layer_number", "value"), &NavigationLink3D::set_navigation_layer_value);
ClassDB::bind_method(D_METHOD("get_navigation_layer_value", "layer_number"), &NavigationLink3D::get_navigation_layer_value);
- ClassDB::bind_method(D_METHOD("set_start_location", "location"), &NavigationLink3D::set_start_location);
- ClassDB::bind_method(D_METHOD("get_start_location"), &NavigationLink3D::get_start_location);
+ ClassDB::bind_method(D_METHOD("set_start_position", "position"), &NavigationLink3D::set_start_position);
+ ClassDB::bind_method(D_METHOD("get_start_position"), &NavigationLink3D::get_start_position);
- ClassDB::bind_method(D_METHOD("set_end_location", "location"), &NavigationLink3D::set_end_location);
- ClassDB::bind_method(D_METHOD("get_end_location"), &NavigationLink3D::get_end_location);
+ ClassDB::bind_method(D_METHOD("set_end_position", "position"), &NavigationLink3D::set_end_position);
+ ClassDB::bind_method(D_METHOD("get_end_position"), &NavigationLink3D::get_end_position);
ClassDB::bind_method(D_METHOD("set_enter_cost", "enter_cost"), &NavigationLink3D::set_enter_cost);
ClassDB::bind_method(D_METHOD("get_enter_cost"), &NavigationLink3D::get_enter_cost);
@@ -172,12 +172,38 @@ void NavigationLink3D::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "enabled"), "set_enabled", "is_enabled");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "bidirectional"), "set_bidirectional", "is_bidirectional");
ADD_PROPERTY(PropertyInfo(Variant::INT, "navigation_layers", PROPERTY_HINT_LAYERS_3D_NAVIGATION), "set_navigation_layers", "get_navigation_layers");
- ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "start_location"), "set_start_location", "get_start_location");
- ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "end_location"), "set_end_location", "get_end_location");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "start_position"), "set_start_position", "get_start_position");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "end_position"), "set_end_position", "get_end_position");
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
+bool NavigationLink3D::_set(const StringName &p_name, const Variant &p_value) {
+ if (p_name == "start_location") {
+ set_start_position(p_value);
+ return true;
+ }
+ if (p_name == "end_location") {
+ set_end_position(p_value);
+ return true;
+ }
+ return false;
+}
+
+bool NavigationLink3D::_get(const StringName &p_name, Variant &r_ret) const {
+ if (p_name == "start_location") {
+ r_ret = get_start_position();
+ return true;
+ }
+ if (p_name == "end_location") {
+ r_ret = get_end_position();
+ return true;
+ }
+ return false;
+}
+#endif // DISABLE_DEPRECATED
+
void NavigationLink3D::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
@@ -186,8 +212,8 @@ void NavigationLink3D::_notification(int p_what) {
// Update global positions for the link.
Transform3D gt = get_global_transform();
- NavigationServer3D::get_singleton()->link_set_start_location(link, gt.xform(start_location));
- NavigationServer3D::get_singleton()->link_set_end_location(link, gt.xform(end_location));
+ NavigationServer3D::get_singleton()->link_set_start_position(link, gt.xform(start_position));
+ NavigationServer3D::get_singleton()->link_set_end_position(link, gt.xform(end_position));
}
#ifdef DEBUG_ENABLED
@@ -197,8 +223,8 @@ void NavigationLink3D::_notification(int p_what) {
case NOTIFICATION_TRANSFORM_CHANGED: {
// Update global positions for the link.
Transform3D gt = get_global_transform();
- NavigationServer3D::get_singleton()->link_set_start_location(link, gt.xform(start_location));
- NavigationServer3D::get_singleton()->link_set_end_location(link, gt.xform(end_location));
+ NavigationServer3D::get_singleton()->link_set_start_position(link, gt.xform(start_position));
+ NavigationServer3D::get_singleton()->link_set_end_position(link, gt.xform(end_position));
#ifdef DEBUG_ENABLED
if (is_inside_tree() && debug_instance.is_valid()) {
@@ -262,10 +288,10 @@ void NavigationLink3D::set_enabled(bool p_enabled) {
#ifdef DEBUG_ENABLED
if (debug_instance.is_valid() && debug_mesh.is_valid()) {
if (enabled) {
- Ref<StandardMaterial3D> link_material = NavigationServer3D::get_singleton_mut()->get_debug_navigation_link_connections_material();
+ Ref<StandardMaterial3D> link_material = NavigationServer3D::get_singleton()->get_debug_navigation_link_connections_material();
RS::get_singleton()->instance_set_surface_override_material(debug_instance, 0, link_material->get_rid());
} else {
- Ref<StandardMaterial3D> disabled_link_material = NavigationServer3D::get_singleton_mut()->get_debug_navigation_link_connections_disabled_material();
+ Ref<StandardMaterial3D> disabled_link_material = NavigationServer3D::get_singleton()->get_debug_navigation_link_connections_disabled_material();
RS::get_singleton()->instance_set_surface_override_material(debug_instance, 0, disabled_link_material->get_rid());
}
}
@@ -316,19 +342,19 @@ bool NavigationLink3D::get_navigation_layer_value(int p_layer_number) const {
return get_navigation_layers() & (1 << (p_layer_number - 1));
}
-void NavigationLink3D::set_start_location(Vector3 p_location) {
- if (start_location.is_equal_approx(p_location)) {
+void NavigationLink3D::set_start_position(Vector3 p_position) {
+ if (start_position.is_equal_approx(p_position)) {
return;
}
- start_location = p_location;
+ start_position = p_position;
if (!is_inside_tree()) {
return;
}
Transform3D gt = get_global_transform();
- NavigationServer3D::get_singleton()->link_set_start_location(link, gt.xform(start_location));
+ NavigationServer3D::get_singleton()->link_set_start_position(link, gt.xform(start_position));
#ifdef DEBUG_ENABLED
_update_debug_mesh();
@@ -338,19 +364,19 @@ void NavigationLink3D::set_start_location(Vector3 p_location) {
update_configuration_warnings();
}
-void NavigationLink3D::set_end_location(Vector3 p_location) {
- if (end_location.is_equal_approx(p_location)) {
+void NavigationLink3D::set_end_position(Vector3 p_position) {
+ if (end_position.is_equal_approx(p_position)) {
return;
}
- end_location = p_location;
+ end_position = p_position;
if (!is_inside_tree()) {
return;
}
Transform3D gt = get_global_transform();
- NavigationServer3D::get_singleton()->link_set_end_location(link, gt.xform(end_location));
+ NavigationServer3D::get_singleton()->link_set_end_position(link, gt.xform(end_position));
#ifdef DEBUG_ENABLED
_update_debug_mesh();
@@ -385,8 +411,8 @@ void NavigationLink3D::set_travel_cost(real_t p_travel_cost) {
PackedStringArray NavigationLink3D::get_configuration_warnings() const {
PackedStringArray warnings = Node::get_configuration_warnings();
- if (start_location.is_equal_approx(end_location)) {
- warnings.push_back(RTR("NavigationLink3D start location should be different than the end location to be useful."));
+ if (start_position.is_equal_approx(end_position)) {
+ warnings.push_back(RTR("NavigationLink3D start position should be different than the end position to be useful."));
}
return warnings;
diff --git a/scene/3d/navigation_link_3d.h b/scene/3d/navigation_link_3d.h
index 175c5cdd5d..5c9ec36189 100644
--- a/scene/3d/navigation_link_3d.h
+++ b/scene/3d/navigation_link_3d.h
@@ -40,8 +40,8 @@ class NavigationLink3D : public Node3D {
RID link;
bool bidirectional = true;
uint32_t navigation_layers = 1;
- Vector3 end_location;
- Vector3 start_location;
+ Vector3 end_position;
+ Vector3 start_position;
real_t enter_cost = 0.0;
real_t travel_cost = 1.0;
@@ -56,6 +56,11 @@ protected:
static void _bind_methods();
void _notification(int p_what);
+#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:
NavigationLink3D();
~NavigationLink3D();
@@ -72,11 +77,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_start_location(Vector3 p_location);
- Vector3 get_start_location() const { return start_location; }
+ void set_start_position(Vector3 p_position);
+ Vector3 get_start_position() const { return start_position; }
- void set_end_location(Vector3 p_location);
- Vector3 get_end_location() const { return end_location; }
+ void set_end_position(Vector3 p_position);
+ Vector3 get_end_position() const { return end_position; }
void set_enter_cost(real_t p_enter_cost);
real_t get_enter_cost() const { return enter_cost; }
diff --git a/scene/3d/navigation_obstacle_3d.cpp b/scene/3d/navigation_obstacle_3d.cpp
index c706f55566..85b3c164cc 100644
--- a/scene/3d/navigation_obstacle_3d.cpp
+++ b/scene/3d/navigation_obstacle_3d.cpp
@@ -192,6 +192,10 @@ real_t NavigationObstacle3D::estimate_agent_radius() const {
}
void NavigationObstacle3D::set_agent_parent(Node *p_agent_parent) {
+ if (parent_node3d == p_agent_parent) {
+ return;
+ }
+
if (Object::cast_to<Node3D>(p_agent_parent) != nullptr) {
parent_node3d = Object::cast_to<Node3D>(p_agent_parent);
if (map_override.is_valid()) {
@@ -207,7 +211,12 @@ void NavigationObstacle3D::set_agent_parent(Node *p_agent_parent) {
}
void NavigationObstacle3D::set_navigation_map(RID p_navigation_map) {
+ if (map_override == p_navigation_map) {
+ return;
+ }
+
map_override = p_navigation_map;
+
NavigationServer3D::get_singleton()->agent_set_map(agent, map_override);
}
@@ -221,13 +230,23 @@ RID NavigationObstacle3D::get_navigation_map() const {
}
void NavigationObstacle3D::set_estimate_radius(bool p_estimate_radius) {
+ if (estimate_radius == p_estimate_radius) {
+ return;
+ }
+
estimate_radius = p_estimate_radius;
+
notify_property_list_changed();
reevaluate_agent_radius();
}
void NavigationObstacle3D::set_radius(real_t p_radius) {
ERR_FAIL_COND_MSG(p_radius <= 0.0, "Radius must be greater than 0.");
+ if (Math::is_equal_approx(radius, p_radius)) {
+ return;
+ }
+
radius = p_radius;
+
reevaluate_agent_radius();
}
diff --git a/scene/3d/navigation_region_3d.cpp b/scene/3d/navigation_region_3d.cpp
index d5b79690dd..22a6ec3517 100644
--- a/scene/3d/navigation_region_3d.cpp
+++ b/scene/3d/navigation_region_3d.cpp
@@ -55,10 +55,10 @@ void NavigationRegion3D::set_enabled(bool p_enabled) {
if (!is_enabled()) {
if (debug_mesh.is_valid()) {
if (debug_mesh->get_surface_count() > 0) {
- RS::get_singleton()->instance_set_surface_override_material(debug_instance, 0, NavigationServer3D::get_singleton_mut()->get_debug_navigation_geometry_face_disabled_material()->get_rid());
+ RS::get_singleton()->instance_set_surface_override_material(debug_instance, 0, NavigationServer3D::get_singleton()->get_debug_navigation_geometry_face_disabled_material()->get_rid());
}
if (debug_mesh->get_surface_count() > 1) {
- RS::get_singleton()->instance_set_surface_override_material(debug_instance, 1, NavigationServer3D::get_singleton_mut()->get_debug_navigation_geometry_edge_disabled_material()->get_rid());
+ RS::get_singleton()->instance_set_surface_override_material(debug_instance, 1, NavigationServer3D::get_singleton()->get_debug_navigation_geometry_edge_disabled_material()->get_rid());
}
}
} else {
@@ -365,9 +365,9 @@ NavigationRegion3D::NavigationRegion3D() {
NavigationServer3D::get_singleton()->region_set_travel_cost(region, get_travel_cost());
#ifdef DEBUG_ENABLED
- NavigationServer3D::get_singleton_mut()->connect("map_changed", callable_mp(this, &NavigationRegion3D::_navigation_map_changed));
- NavigationServer3D::get_singleton_mut()->connect("navigation_debug_changed", callable_mp(this, &NavigationRegion3D::_update_debug_mesh));
- NavigationServer3D::get_singleton_mut()->connect("navigation_debug_changed", callable_mp(this, &NavigationRegion3D::_update_debug_edge_connections_mesh));
+ NavigationServer3D::get_singleton()->connect("map_changed", callable_mp(this, &NavigationRegion3D::_navigation_map_changed));
+ NavigationServer3D::get_singleton()->connect("navigation_debug_changed", callable_mp(this, &NavigationRegion3D::_update_debug_mesh));
+ NavigationServer3D::get_singleton()->connect("navigation_debug_changed", callable_mp(this, &NavigationRegion3D::_update_debug_edge_connections_mesh));
#endif // DEBUG_ENABLED
}
@@ -379,9 +379,9 @@ NavigationRegion3D::~NavigationRegion3D() {
NavigationServer3D::get_singleton()->free(region);
#ifdef DEBUG_ENABLED
- NavigationServer3D::get_singleton_mut()->disconnect("map_changed", callable_mp(this, &NavigationRegion3D::_navigation_map_changed));
- NavigationServer3D::get_singleton_mut()->disconnect("navigation_debug_changed", callable_mp(this, &NavigationRegion3D::_update_debug_mesh));
- NavigationServer3D::get_singleton_mut()->disconnect("navigation_debug_changed", callable_mp(this, &NavigationRegion3D::_update_debug_edge_connections_mesh));
+ NavigationServer3D::get_singleton()->disconnect("map_changed", callable_mp(this, &NavigationRegion3D::_navigation_map_changed));
+ NavigationServer3D::get_singleton()->disconnect("navigation_debug_changed", callable_mp(this, &NavigationRegion3D::_update_debug_mesh));
+ NavigationServer3D::get_singleton()->disconnect("navigation_debug_changed", callable_mp(this, &NavigationRegion3D::_update_debug_edge_connections_mesh));
ERR_FAIL_NULL(RenderingServer::get_singleton());
if (debug_instance.is_valid()) {
@@ -459,8 +459,8 @@ void NavigationRegion3D::_update_debug_mesh() {
Color debug_navigation_geometry_face_color = NavigationServer3D::get_singleton()->get_debug_navigation_geometry_face_color();
- Ref<StandardMaterial3D> face_material = NavigationServer3D::get_singleton_mut()->get_debug_navigation_geometry_face_material();
- Ref<StandardMaterial3D> line_material = NavigationServer3D::get_singleton_mut()->get_debug_navigation_geometry_edge_material();
+ Ref<StandardMaterial3D> face_material = NavigationServer3D::get_singleton()->get_debug_navigation_geometry_face_material();
+ Ref<StandardMaterial3D> line_material = NavigationServer3D::get_singleton()->get_debug_navigation_geometry_edge_material();
RandomPCG rand;
Color polygon_color = debug_navigation_geometry_face_color;
@@ -518,10 +518,10 @@ void NavigationRegion3D::_update_debug_mesh() {
if (!is_enabled()) {
if (debug_mesh.is_valid()) {
if (debug_mesh->get_surface_count() > 0) {
- RS::get_singleton()->instance_set_surface_override_material(debug_instance, 0, NavigationServer3D::get_singleton_mut()->get_debug_navigation_geometry_face_disabled_material()->get_rid());
+ RS::get_singleton()->instance_set_surface_override_material(debug_instance, 0, NavigationServer3D::get_singleton()->get_debug_navigation_geometry_face_disabled_material()->get_rid());
}
if (debug_mesh->get_surface_count() > 1) {
- RS::get_singleton()->instance_set_surface_override_material(debug_instance, 1, NavigationServer3D::get_singleton_mut()->get_debug_navigation_geometry_edge_disabled_material()->get_rid());
+ RS::get_singleton()->instance_set_surface_override_material(debug_instance, 1, NavigationServer3D::get_singleton()->get_debug_navigation_geometry_edge_disabled_material()->get_rid());
}
}
} else {
@@ -610,7 +610,7 @@ void NavigationRegion3D::_update_debug_edge_connections_mesh() {
return;
}
- Ref<StandardMaterial3D> edge_connections_material = NavigationServer3D::get_singleton_mut()->get_debug_navigation_edge_connections_material();
+ Ref<StandardMaterial3D> edge_connections_material = NavigationServer3D::get_singleton()->get_debug_navigation_edge_connections_material();
Array mesh_array;
mesh_array.resize(Mesh::ARRAY_MAX);
diff --git a/scene/3d/node_3d.cpp b/scene/3d/node_3d.cpp
index a0382b73dc..66e8831d15 100644
--- a/scene/3d/node_3d.cpp
+++ b/scene/3d/node_3d.cpp
@@ -623,6 +623,14 @@ void Node3D::set_disable_gizmos(bool p_enabled) {
#endif
}
+void Node3D::reparent(Node *p_parent, bool p_keep_global_transform) {
+ Transform3D temp = get_global_transform();
+ Node::reparent(p_parent);
+ if (p_keep_global_transform) {
+ set_global_transform(temp);
+ }
+}
+
void Node3D::set_disable_scale(bool p_enabled) {
data.disable_scale = p_enabled;
}
diff --git a/scene/3d/node_3d.h b/scene/3d/node_3d.h
index 0901ab331b..98bcab5fd4 100644
--- a/scene/3d/node_3d.h
+++ b/scene/3d/node_3d.h
@@ -206,6 +206,7 @@ public:
virtual void set_transform_gizmo_visible(bool p_enabled) { data.transform_gizmo_visible = p_enabled; };
virtual bool is_transform_gizmo_visible() const { return data.transform_gizmo_visible; };
#endif
+ virtual void reparent(Node *p_parent, bool p_keep_global_transform = true) override;
void set_disable_gizmos(bool p_enabled);
void update_gizmos();
diff --git a/scene/3d/occluder_instance_3d.cpp b/scene/3d/occluder_instance_3d.cpp
index 632b27953f..594580a205 100644
--- a/scene/3d/occluder_instance_3d.cpp
+++ b/scene/3d/occluder_instance_3d.cpp
@@ -542,13 +542,14 @@ void OccluderInstance3D::_bake_surface(const Transform3D &p_transform, Array p_s
float error = -1.0f;
int target_index_count = MIN(indices.size(), 36);
+ const int simplify_options = SurfaceTool::SIMPLIFY_LOCK_BORDER;
+
uint32_t index_count = SurfaceTool::simplify_func(
(unsigned int *)indices.ptrw(),
(unsigned int *)indices.ptr(),
indices.size(),
vertices_f32.ptr(), vertices.size(), sizeof(float) * 3,
- target_index_count, target_error, &error);
-
+ target_index_count, target_error, simplify_options, &error);
indices.resize(index_count);
}
diff --git a/scene/3d/physics_body_3d.cpp b/scene/3d/physics_body_3d.cpp
index 46956b0a2e..c8cfcf7d7a 100644
--- a/scene/3d/physics_body_3d.cpp
+++ b/scene/3d/physics_body_3d.cpp
@@ -333,6 +333,11 @@ void AnimatableBody3D::_body_state_changed(PhysicsDirectBodyState3D *p_state) {
}
void AnimatableBody3D::_notification(int p_what) {
+#ifdef TOOLS_ENABLED
+ if (Engine::get_singleton()->is_editor_hint()) {
+ return;
+ }
+#endif
switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
last_valid_transform = get_global_transform();
@@ -484,6 +489,8 @@ struct _RigidBodyInOut {
};
void RigidBody3D::_body_state_changed(PhysicsDirectBodyState3D *p_state) {
+ lock_callback();
+
set_ignore_transform_notification(true);
set_global_transform(p_state->get_transform());
@@ -578,6 +585,8 @@ void RigidBody3D::_body_state_changed(PhysicsDirectBodyState3D *p_state) {
contact_monitor->locked = false;
}
+
+ unlock_callback();
}
void RigidBody3D::_notification(int p_what) {
@@ -973,12 +982,11 @@ TypedArray<Node3D> RigidBody3D::get_colliding_bodies() const {
}
PackedStringArray RigidBody3D::get_configuration_warnings() const {
- Transform3D t = get_transform();
-
- PackedStringArray warnings = Node::get_configuration_warnings();
+ PackedStringArray warnings = CollisionObject3D::get_configuration_warnings();
- if (ABS(t.basis.get_column(0).length() - 1.0) > 0.05 || ABS(t.basis.get_column(1).length() - 1.0) > 0.05 || ABS(t.basis.get_column(2).length() - 1.0) > 0.05) {
- warnings.push_back(RTR("Size changes to RigidBody will be overridden by the physics engine when running.\nChange the size in children collision shapes instead."));
+ Vector3 scale = get_transform().get_basis().get_scale();
+ if (ABS(scale.x - 1.0) > 0.05 || ABS(scale.y - 1.0) > 0.05 || ABS(scale.z - 1.0) > 0.05) {
+ warnings.push_back(RTR("Scale changes to RigidBody3D will be overridden by the physics engine when running.\nPlease change the size in children collision shapes instead."));
}
return warnings;
@@ -1343,7 +1351,7 @@ void CharacterBody3D::_move_and_slide_grounded(double p_delta, bool p_was_on_flo
motion = motion.slide(up_direction);
result.travel = Vector3();
} else {
- // Travel is too high to be safely cancelled, we take it into account.
+ // Travel is too high to be safely canceled, we take it into account.
result.travel = result.travel.slide(up_direction);
motion = motion.normalized() * result.travel.length();
}
@@ -1351,7 +1359,7 @@ void CharacterBody3D::_move_and_slide_grounded(double p_delta, bool p_was_on_flo
// Determines if you are on the ground, and limits the possibility of climbing on the walls because of the approximations.
_snap_on_floor(true, false);
} else {
- // If the movement is not cancelled we only keep the remaining.
+ // If the movement is not canceled we only keep the remaining.
motion = result.remainder;
}
diff --git a/scene/3d/reflection_probe.cpp b/scene/3d/reflection_probe.cpp
index 606f6140cb..62202c0b1b 100644
--- a/scene/3d/reflection_probe.cpp
+++ b/scene/3d/reflection_probe.cpp
@@ -85,38 +85,40 @@ float ReflectionProbe::get_mesh_lod_threshold() const {
return mesh_lod_threshold;
}
-void ReflectionProbe::set_extents(const Vector3 &p_extents) {
- extents = p_extents;
+void ReflectionProbe::set_size(const Vector3 &p_size) {
+ size = p_size;
for (int i = 0; i < 3; i++) {
- if (extents[i] < 0.01) {
- extents[i] = 0.01;
+ float half_size = size[i] / 2;
+ if (half_size < 0.01) {
+ half_size = 0.01;
}
- if (extents[i] - 0.01 < ABS(origin_offset[i])) {
- origin_offset[i] = SIGN(origin_offset[i]) * (extents[i] - 0.01);
+ if (half_size - 0.01 < ABS(origin_offset[i])) {
+ origin_offset[i] = SIGN(origin_offset[i]) * (half_size - 0.01);
}
}
- RS::get_singleton()->reflection_probe_set_extents(probe, extents);
+ RS::get_singleton()->reflection_probe_set_size(probe, size);
RS::get_singleton()->reflection_probe_set_origin_offset(probe, origin_offset);
update_gizmos();
}
-Vector3 ReflectionProbe::get_extents() const {
- return extents;
+Vector3 ReflectionProbe::get_size() const {
+ return size;
}
-void ReflectionProbe::set_origin_offset(const Vector3 &p_extents) {
- origin_offset = p_extents;
+void ReflectionProbe::set_origin_offset(const Vector3 &p_offset) {
+ origin_offset = p_offset;
for (int i = 0; i < 3; i++) {
- if (extents[i] - 0.01 < ABS(origin_offset[i])) {
- origin_offset[i] = SIGN(origin_offset[i]) * (extents[i] - 0.01);
+ float half_size = size[i] / 2;
+ if (half_size - 0.01 < ABS(origin_offset[i])) {
+ origin_offset[i] = SIGN(origin_offset[i]) * (half_size - 0.01);
}
}
- RS::get_singleton()->reflection_probe_set_extents(probe, extents);
+ RS::get_singleton()->reflection_probe_set_size(probe, size);
RS::get_singleton()->reflection_probe_set_origin_offset(probe, origin_offset);
update_gizmos();
@@ -174,7 +176,7 @@ ReflectionProbe::UpdateMode ReflectionProbe::get_update_mode() const {
AABB ReflectionProbe::get_aabb() const {
AABB aabb;
aabb.position = -origin_offset;
- aabb.size = origin_offset + extents;
+ aabb.size = origin_offset + size / 2;
return aabb;
}
@@ -205,8 +207,8 @@ void ReflectionProbe::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_mesh_lod_threshold", "ratio"), &ReflectionProbe::set_mesh_lod_threshold);
ClassDB::bind_method(D_METHOD("get_mesh_lod_threshold"), &ReflectionProbe::get_mesh_lod_threshold);
- ClassDB::bind_method(D_METHOD("set_extents", "extents"), &ReflectionProbe::set_extents);
- ClassDB::bind_method(D_METHOD("get_extents"), &ReflectionProbe::get_extents);
+ ClassDB::bind_method(D_METHOD("set_size", "size"), &ReflectionProbe::set_size);
+ ClassDB::bind_method(D_METHOD("get_size"), &ReflectionProbe::get_size);
ClassDB::bind_method(D_METHOD("set_origin_offset", "origin_offset"), &ReflectionProbe::set_origin_offset);
ClassDB::bind_method(D_METHOD("get_origin_offset"), &ReflectionProbe::get_origin_offset);
@@ -229,7 +231,7 @@ void ReflectionProbe::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::INT, "update_mode", PROPERTY_HINT_ENUM, "Once (Fast),Always (Slow)"), "set_update_mode", "get_update_mode");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "intensity", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_intensity", "get_intensity");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "max_distance", PROPERTY_HINT_RANGE, "0,16384,0.1,or_greater,exp,suffix:m"), "set_max_distance", "get_max_distance");
- ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "extents", PROPERTY_HINT_NONE, "suffix:m"), "set_extents", "get_extents");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "size", PROPERTY_HINT_NONE, "suffix:m"), "set_size", "get_size");
ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "origin_offset", PROPERTY_HINT_NONE, "suffix:m"), "set_origin_offset", "get_origin_offset");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "box_projection"), "set_enable_box_projection", "is_box_projection_enabled");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "interior"), "set_as_interior", "is_set_as_interior");
@@ -250,6 +252,24 @@ void ReflectionProbe::_bind_methods() {
BIND_ENUM_CONSTANT(AMBIENT_COLOR);
}
+#ifndef DISABLE_DEPRECATED
+bool ReflectionProbe::_set(const StringName &p_name, const Variant &p_value) {
+ if (p_name == "extents") { // Compatibility with Godot 3.x.
+ set_size((Vector3)p_value * 2);
+ return true;
+ }
+ return false;
+}
+
+bool ReflectionProbe::_get(const StringName &p_name, Variant &r_property) const {
+ if (p_name == "extents") { // Compatibility with Godot 3.x.
+ r_property = size / 2;
+ return true;
+ }
+ return false;
+}
+#endif // DISABLE_DEPRECATED
+
ReflectionProbe::ReflectionProbe() {
probe = RenderingServer::get_singleton()->reflection_probe_create();
RS::get_singleton()->instance_set_base(get_instance(), probe);
diff --git a/scene/3d/reflection_probe.h b/scene/3d/reflection_probe.h
index cb417c3eea..738277ad39 100644
--- a/scene/3d/reflection_probe.h
+++ b/scene/3d/reflection_probe.h
@@ -52,7 +52,7 @@ private:
RID probe;
float intensity = 1.0;
float max_distance = 0.0;
- Vector3 extents = Vector3(10, 10, 10);
+ Vector3 size = Vector3(20, 20, 20);
Vector3 origin_offset = Vector3(0, 0, 0);
bool box_projection = false;
bool enable_shadows = false;
@@ -68,6 +68,10 @@ private:
protected:
static void _bind_methods();
void _validate_property(PropertyInfo &p_property) const;
+#ifndef DISABLE_DEPRECATED
+ bool _set(const StringName &p_name, const Variant &p_value);
+ bool _get(const StringName &p_name, Variant &r_property) const;
+#endif // DISABLE_DEPRECATED
public:
void set_intensity(float p_intensity);
@@ -91,10 +95,10 @@ public:
void set_mesh_lod_threshold(float p_pixels);
float get_mesh_lod_threshold() const;
- void set_extents(const Vector3 &p_extents);
- Vector3 get_extents() const;
+ void set_size(const Vector3 &p_size);
+ Vector3 get_size() const;
- void set_origin_offset(const Vector3 &p_extents);
+ void set_origin_offset(const Vector3 &p_offset);
Vector3 get_origin_offset() const;
void set_as_interior(bool p_enable);
diff --git a/scene/3d/shape_cast_3d.cpp b/scene/3d/shape_cast_3d.cpp
index 358da2b6d0..87361d6b38 100644
--- a/scene/3d/shape_cast_3d.cpp
+++ b/scene/3d/shape_cast_3d.cpp
@@ -30,8 +30,9 @@
#include "shape_cast_3d.h"
-#include "collision_object_3d.h"
-#include "mesh_instance_3d.h"
+#include "core/core_string_names.h"
+#include "scene/3d/collision_object_3d.h"
+#include "scene/3d/mesh_instance_3d.h"
#include "scene/resources/concave_polygon_shape_3d.h"
void ShapeCast3D::_notification(int p_what) {
@@ -318,25 +319,35 @@ void ShapeCast3D::resource_changed(Ref<Resource> p_res) {
update_gizmos();
}
+void ShapeCast3D::_shape_changed() {
+ update_gizmos();
+ bool is_editor = Engine::get_singleton()->is_editor_hint();
+ if (is_inside_tree() && (is_editor || get_tree()->is_debugging_collisions_hint())) {
+ _update_debug_shape();
+ }
+}
+
void ShapeCast3D::set_shape(const Ref<Shape3D> &p_shape) {
if (p_shape == shape) {
return;
}
if (!shape.is_null()) {
+ shape->disconnect(CoreStringNames::get_singleton()->changed, callable_mp(this, &ShapeCast3D::_shape_changed));
shape->unregister_owner(this);
}
shape = p_shape;
if (!shape.is_null()) {
shape->register_owner(this);
+ shape->connect(CoreStringNames::get_singleton()->changed, callable_mp(this, &ShapeCast3D::_shape_changed));
}
if (p_shape.is_valid()) {
shape_rid = shape->get_rid();
}
- if (is_inside_tree() && get_tree()->is_debugging_collisions_hint()) {
+ bool is_editor = Engine::get_singleton()->is_editor_hint();
+ if (is_inside_tree() && (is_editor || get_tree()->is_debugging_collisions_hint())) {
_update_debug_shape();
}
-
update_gizmos();
update_configuration_warnings();
}
diff --git a/scene/3d/shape_cast_3d.h b/scene/3d/shape_cast_3d.h
index 483364472f..344f1d3b8a 100644
--- a/scene/3d/shape_cast_3d.h
+++ b/scene/3d/shape_cast_3d.h
@@ -77,6 +77,7 @@ class ShapeCast3D : public Node3D {
protected:
void _notification(int p_what);
void _update_shapecast_state();
+ void _shape_changed();
static void _bind_methods();
public:
diff --git a/scene/3d/skeleton_3d.cpp b/scene/3d/skeleton_3d.cpp
index 4eadaa603f..1b46879079 100644
--- a/scene/3d/skeleton_3d.cpp
+++ b/scene/3d/skeleton_3d.cpp
@@ -33,7 +33,6 @@
#include "core/object/message_queue.h"
#include "core/variant/type_info.h"
#include "scene/3d/physics_body_3d.h"
-#include "scene/resources/skeleton_modification_3d.h"
#include "scene/resources/surface_tool.h"
#include "scene/scene_string_names.h"
@@ -70,13 +69,6 @@ SkinReference::~SkinReference() {
bool Skeleton3D::_set(const StringName &p_path, const Variant &p_value) {
String path = p_path;
-#ifndef _3D_DISABLED
- if (path.begins_with("modification_stack")) {
- set_modification_stack(p_value);
- return true;
- }
-#endif //_3D_DISABLED
-
if (!path.begins_with("bones/")) {
return false;
}
@@ -113,13 +105,6 @@ bool Skeleton3D::_set(const StringName &p_path, const Variant &p_value) {
bool Skeleton3D::_get(const StringName &p_path, Variant &r_ret) const {
String path = p_path;
-#ifndef _3D_DISABLED
- if (path.begins_with("modification_stack")) {
- r_ret = modification_stack;
- return true;
- }
-#endif //_3D_DISABLED
-
if (!path.begins_with("bones/")) {
return false;
}
@@ -162,14 +147,6 @@ void Skeleton3D::_get_property_list(List<PropertyInfo> *p_list) const {
p_list->push_back(PropertyInfo(Variant::VECTOR3, prep + PNAME("scale"), PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR));
}
-#ifndef _3D_DISABLED
- p_list->push_back(
- PropertyInfo(Variant::OBJECT, "modification_stack",
- PROPERTY_HINT_RESOURCE_TYPE,
- "SkeletonModificationStack3D",
- PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_DEFERRED_SET_RESOURCE | PROPERTY_USAGE_DO_NOT_SHARE_ON_DUPLICATE));
-#endif //_3D_DISABLED
-
for (PropertyInfo &E : *p_list) {
_validate_property(E);
}
@@ -330,24 +307,10 @@ void Skeleton3D::_notification(int p_what) {
}
}
}
-
- if (modification_stack.is_valid()) {
- execute_modifications(get_physics_process_delta_time(), SkeletonModificationStack3D::EXECUTION_MODE::execution_mode_physics_process);
- }
- } break;
-
- case NOTIFICATION_INTERNAL_PROCESS: {
- if (modification_stack.is_valid()) {
- execute_modifications(get_process_delta_time(), SkeletonModificationStack3D::EXECUTION_MODE::execution_mode_process);
- }
} break;
-
case NOTIFICATION_READY: {
- set_physics_process_internal(true);
- set_process_internal(true);
-
- if (modification_stack.is_valid()) {
- set_modification_stack(modification_stack);
+ if (Engine::get_singleton()->is_editor_hint()) {
+ set_physics_process_internal(true);
}
} break;
#endif // _3D_DISABLED
@@ -395,99 +358,6 @@ Transform3D Skeleton3D::get_bone_global_pose_no_override(int p_bone) const {
return bones[p_bone].pose_global_no_override;
}
-void Skeleton3D::clear_bones_local_pose_override() {
- for (int i = 0; i < bones.size(); i += 1) {
- bones.write[i].local_pose_override_amount = 0;
- }
- _make_dirty();
-}
-
-void Skeleton3D::set_bone_local_pose_override(int p_bone, const Transform3D &p_pose, real_t p_amount, bool p_persistent) {
- const int bone_size = bones.size();
- ERR_FAIL_INDEX(p_bone, bone_size);
- bones.write[p_bone].local_pose_override_amount = p_amount;
- bones.write[p_bone].local_pose_override = p_pose;
- bones.write[p_bone].local_pose_override_reset = !p_persistent;
- _make_dirty();
-}
-
-Transform3D Skeleton3D::get_bone_local_pose_override(int p_bone) const {
- const int bone_size = bones.size();
- ERR_FAIL_INDEX_V(p_bone, bone_size, Transform3D());
- return bones[p_bone].local_pose_override;
-}
-
-void Skeleton3D::update_bone_rest_forward_vector(int p_bone, bool p_force_update) {
- const int bone_size = bones.size();
- ERR_FAIL_INDEX(p_bone, bone_size);
-
- if (bones[p_bone].rest_bone_forward_vector.length_squared() > 0 && p_force_update == false) {
- update_bone_rest_forward_axis(p_bone, p_force_update);
- }
-
- // If it is a child/leaf bone...
- if (get_bone_parent(p_bone) > 0) {
- bones.write[p_bone].rest_bone_forward_vector = bones[p_bone].rest.origin.normalized();
- } else {
- // If it has children...
- Vector<int> child_bones = get_bone_children(p_bone);
- if (child_bones.size() > 0) {
- Vector3 combined_child_dir = Vector3(0, 0, 0);
- for (int i = 0; i < child_bones.size(); i++) {
- combined_child_dir += bones[child_bones[i]].rest.origin.normalized();
- }
- combined_child_dir = combined_child_dir / child_bones.size();
- bones.write[p_bone].rest_bone_forward_vector = combined_child_dir.normalized();
- } else {
- WARN_PRINT_ONCE("Cannot calculate forward direction for bone " + itos(p_bone));
- WARN_PRINT_ONCE("Assuming direction of (0, 1, 0) for bone");
- bones.write[p_bone].rest_bone_forward_vector = Vector3(0, 1, 0);
- }
- }
- update_bone_rest_forward_axis(p_bone, p_force_update);
-}
-
-void Skeleton3D::update_bone_rest_forward_axis(int p_bone, bool p_force_update) {
- const int bone_size = bones.size();
- ERR_FAIL_INDEX(p_bone, bone_size);
- if (bones[p_bone].rest_bone_forward_axis > -1 && p_force_update == false) {
- return;
- }
-
- Vector3 forward_axis_absolute = bones[p_bone].rest_bone_forward_vector.abs();
- if (forward_axis_absolute.x > forward_axis_absolute.y && forward_axis_absolute.x > forward_axis_absolute.z) {
- if (bones[p_bone].rest_bone_forward_vector.x > 0) {
- bones.write[p_bone].rest_bone_forward_axis = BONE_AXIS_X_FORWARD;
- } else {
- bones.write[p_bone].rest_bone_forward_axis = BONE_AXIS_NEGATIVE_X_FORWARD;
- }
- } else if (forward_axis_absolute.y > forward_axis_absolute.x && forward_axis_absolute.y > forward_axis_absolute.z) {
- if (bones[p_bone].rest_bone_forward_vector.y > 0) {
- bones.write[p_bone].rest_bone_forward_axis = BONE_AXIS_Y_FORWARD;
- } else {
- bones.write[p_bone].rest_bone_forward_axis = BONE_AXIS_NEGATIVE_Y_FORWARD;
- }
- } else {
- if (bones[p_bone].rest_bone_forward_vector.z > 0) {
- bones.write[p_bone].rest_bone_forward_axis = BONE_AXIS_Z_FORWARD;
- } else {
- bones.write[p_bone].rest_bone_forward_axis = BONE_AXIS_NEGATIVE_Z_FORWARD;
- }
- }
-}
-
-Vector3 Skeleton3D::get_bone_axis_forward_vector(int p_bone) {
- const int bone_size = bones.size();
- ERR_FAIL_INDEX_V(p_bone, bone_size, Vector3(0, 0, 0));
- return bones[p_bone].rest_bone_forward_vector;
-}
-
-int Skeleton3D::get_bone_axis_forward_enum(int p_bone) {
- const int bone_size = bones.size();
- ERR_FAIL_INDEX_V(p_bone, bone_size, -1);
- return bones[p_bone].rest_bone_forward_axis;
-}
-
void Skeleton3D::set_motion_scale(float p_motion_scale) {
if (p_motion_scale <= 0) {
motion_scale = 1;
@@ -503,6 +373,10 @@ float Skeleton3D::get_motion_scale() const {
// Skeleton creation api
+uint64_t Skeleton3D::get_version() const {
+ return version;
+}
+
void Skeleton3D::add_bone(const String &p_name) {
ERR_FAIL_COND(p_name.is_empty() || p_name.contains(":") || p_name.contains("/"));
@@ -546,6 +420,7 @@ void Skeleton3D::set_bone_name(int p_bone, const String &p_name) {
}
bones.write[p_bone].name = p_name;
+ version++;
}
bool Skeleton3D::is_bone_parent_of(int p_bone, int p_parent_bone_id) const {
@@ -1068,23 +943,10 @@ void Skeleton3D::force_update_bone_children_transforms(int p_bone_idx) {
b.global_rest = b.parent >= 0 ? bonesptr[b.parent].global_rest * b.rest : b.rest;
}
- if (b.local_pose_override_amount >= CMP_EPSILON) {
- Transform3D override_local_pose;
- if (b.parent >= 0) {
- override_local_pose = bonesptr[b.parent].pose_global * b.local_pose_override;
- } else {
- override_local_pose = b.local_pose_override;
- }
- b.pose_global = b.pose_global.interpolate_with(override_local_pose, b.local_pose_override_amount);
- }
-
if (b.global_pose_override_amount >= CMP_EPSILON) {
b.pose_global = b.pose_global.interpolate_with(b.global_pose_override, b.global_pose_override_amount);
}
- if (b.local_pose_override_reset) {
- b.local_pose_override_amount = 0.0;
- }
if (b.global_pose_override_reset) {
b.global_pose_override_amount = 0.0;
}
@@ -1100,100 +962,6 @@ void Skeleton3D::force_update_bone_children_transforms(int p_bone_idx) {
rest_dirty = false;
}
-// Helper functions
-
-Transform3D Skeleton3D::global_pose_to_world_transform(Transform3D p_global_pose) {
- return get_global_transform() * p_global_pose;
-}
-
-Transform3D Skeleton3D::world_transform_to_global_pose(Transform3D p_world_transform) {
- return get_global_transform().affine_inverse() * p_world_transform;
-}
-
-Transform3D Skeleton3D::global_pose_to_local_pose(int p_bone_idx, Transform3D p_global_pose) {
- const int bone_size = bones.size();
- ERR_FAIL_INDEX_V(p_bone_idx, bone_size, Transform3D());
- if (bones[p_bone_idx].parent >= 0) {
- int parent_bone_idx = bones[p_bone_idx].parent;
- Transform3D conversion_transform = get_bone_global_pose(parent_bone_idx).affine_inverse();
- return conversion_transform * p_global_pose;
- } else {
- return p_global_pose;
- }
-}
-
-Transform3D Skeleton3D::local_pose_to_global_pose(int p_bone_idx, Transform3D p_local_pose) {
- const int bone_size = bones.size();
- ERR_FAIL_INDEX_V(p_bone_idx, bone_size, Transform3D());
- if (bones[p_bone_idx].parent >= 0) {
- int parent_bone_idx = bones[p_bone_idx].parent;
- return bones[parent_bone_idx].pose_global * p_local_pose;
- } else {
- return p_local_pose;
- }
-}
-
-Basis Skeleton3D::global_pose_z_forward_to_bone_forward(int p_bone_idx, Basis p_basis) {
- const int bone_size = bones.size();
- ERR_FAIL_INDEX_V(p_bone_idx, bone_size, Basis());
- Basis return_basis = p_basis;
-
- if (bones[p_bone_idx].rest_bone_forward_axis < 0) {
- update_bone_rest_forward_vector(p_bone_idx, true);
- }
-
- if (bones[p_bone_idx].rest_bone_forward_axis == BONE_AXIS_X_FORWARD) {
- return_basis.rotate_local(Vector3(0, 1, 0), (Math_PI / 2.0));
- } else if (bones[p_bone_idx].rest_bone_forward_axis == BONE_AXIS_NEGATIVE_X_FORWARD) {
- return_basis.rotate_local(Vector3(0, 1, 0), -(Math_PI / 2.0));
- } else if (bones[p_bone_idx].rest_bone_forward_axis == BONE_AXIS_Y_FORWARD) {
- return_basis.rotate_local(Vector3(1, 0, 0), -(Math_PI / 2.0));
- } else if (bones[p_bone_idx].rest_bone_forward_axis == BONE_AXIS_NEGATIVE_Y_FORWARD) {
- return_basis.rotate_local(Vector3(1, 0, 0), (Math_PI / 2.0));
- } else if (bones[p_bone_idx].rest_bone_forward_axis == BONE_AXIS_Z_FORWARD) {
- // Do nothing!
- } else if (bones[p_bone_idx].rest_bone_forward_axis == BONE_AXIS_NEGATIVE_Z_FORWARD) {
- return_basis.rotate_local(Vector3(0, 0, 1), Math_PI);
- }
-
- return return_basis;
-}
-
-// Modifications
-
-#ifndef _3D_DISABLED
-
-void Skeleton3D::set_modification_stack(Ref<SkeletonModificationStack3D> p_stack) {
- if (modification_stack.is_valid()) {
- modification_stack->is_setup = false;
- modification_stack->set_skeleton(nullptr);
- }
-
- modification_stack = p_stack;
- if (modification_stack.is_valid()) {
- modification_stack->set_skeleton(this);
- modification_stack->setup();
- }
-}
-Ref<SkeletonModificationStack3D> Skeleton3D::get_modification_stack() {
- return modification_stack;
-}
-
-void Skeleton3D::execute_modifications(real_t p_delta, int p_execution_mode) {
- if (!modification_stack.is_valid()) {
- return;
- }
-
- // Needed to avoid the issue where the stack looses reference to the skeleton when the scene is saved.
- if (modification_stack->skeleton != this) {
- modification_stack->set_skeleton(this);
- }
-
- modification_stack->execute(p_delta, p_execution_mode);
-}
-
-#endif // _3D_DISABLED
-
void Skeleton3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("add_bone", "name"), &Skeleton3D::add_bone);
ClassDB::bind_method(D_METHOD("find_bone", "name"), &Skeleton3D::find_bone);
@@ -1204,6 +972,7 @@ void Skeleton3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_bone_parent", "bone_idx", "parent_idx"), &Skeleton3D::set_bone_parent);
ClassDB::bind_method(D_METHOD("get_bone_count"), &Skeleton3D::get_bone_count);
+ ClassDB::bind_method(D_METHOD("get_version"), &Skeleton3D::get_version);
ClassDB::bind_method(D_METHOD("unparent_bone_and_rest", "bone_idx"), &Skeleton3D::unparent_bone_and_rest);
@@ -1243,23 +1012,12 @@ void Skeleton3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_bone_global_pose", "bone_idx"), &Skeleton3D::get_bone_global_pose);
ClassDB::bind_method(D_METHOD("get_bone_global_pose_no_override", "bone_idx"), &Skeleton3D::get_bone_global_pose_no_override);
- ClassDB::bind_method(D_METHOD("clear_bones_local_pose_override"), &Skeleton3D::clear_bones_local_pose_override);
- ClassDB::bind_method(D_METHOD("set_bone_local_pose_override", "bone_idx", "pose", "amount", "persistent"), &Skeleton3D::set_bone_local_pose_override, DEFVAL(false));
- ClassDB::bind_method(D_METHOD("get_bone_local_pose_override", "bone_idx"), &Skeleton3D::get_bone_local_pose_override);
-
ClassDB::bind_method(D_METHOD("force_update_all_bone_transforms"), &Skeleton3D::force_update_all_bone_transforms);
ClassDB::bind_method(D_METHOD("force_update_bone_child_transform", "bone_idx"), &Skeleton3D::force_update_bone_children_transforms);
ClassDB::bind_method(D_METHOD("set_motion_scale", "motion_scale"), &Skeleton3D::set_motion_scale);
ClassDB::bind_method(D_METHOD("get_motion_scale"), &Skeleton3D::get_motion_scale);
- // Helper functions
- ClassDB::bind_method(D_METHOD("global_pose_to_world_transform", "global_pose"), &Skeleton3D::global_pose_to_world_transform);
- ClassDB::bind_method(D_METHOD("world_transform_to_global_pose", "world_transform"), &Skeleton3D::world_transform_to_global_pose);
- ClassDB::bind_method(D_METHOD("global_pose_to_local_pose", "bone_idx", "global_pose"), &Skeleton3D::global_pose_to_local_pose);
- ClassDB::bind_method(D_METHOD("local_pose_to_global_pose", "bone_idx", "local_pose"), &Skeleton3D::local_pose_to_global_pose);
- ClassDB::bind_method(D_METHOD("global_pose_z_forward_to_bone_forward", "bone_idx", "basis"), &Skeleton3D::global_pose_z_forward_to_bone_forward);
-
ClassDB::bind_method(D_METHOD("set_show_rest_only", "enabled"), &Skeleton3D::set_show_rest_only);
ClassDB::bind_method(D_METHOD("is_show_rest_only"), &Skeleton3D::is_show_rest_only);
@@ -1271,11 +1029,6 @@ void Skeleton3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("physical_bones_add_collision_exception", "exception"), &Skeleton3D::physical_bones_add_collision_exception);
ClassDB::bind_method(D_METHOD("physical_bones_remove_collision_exception", "exception"), &Skeleton3D::physical_bones_remove_collision_exception);
- // Modifications
- ClassDB::bind_method(D_METHOD("set_modification_stack", "modification_stack"), &Skeleton3D::set_modification_stack);
- ClassDB::bind_method(D_METHOD("get_modification_stack"), &Skeleton3D::get_modification_stack);
- ClassDB::bind_method(D_METHOD("execute_modifications", "delta", "execution_mode"), &Skeleton3D::execute_modifications);
-
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "motion_scale", PROPERTY_HINT_RANGE, "0.001,10,0.001,or_greater"), "set_motion_scale", "get_motion_scale");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "show_rest_only"), "set_show_rest_only", "is_show_rest_only");
#ifndef _3D_DISABLED
diff --git a/scene/3d/skeleton_3d.h b/scene/3d/skeleton_3d.h
index f66cc2f9ed..3df909d936 100644
--- a/scene/3d/skeleton_3d.h
+++ b/scene/3d/skeleton_3d.h
@@ -32,7 +32,6 @@
#define SKELETON_3D_H
#include "scene/3d/node_3d.h"
-#include "scene/resources/skeleton_modification_3d.h"
#include "scene/resources/skin.h"
typedef int BoneId;
@@ -64,8 +63,6 @@ public:
~SkinReference();
};
-class SkeletonModificationStack3D;
-
class Skeleton3D : public Node3D {
GDCLASS(Skeleton3D, Node3D);
@@ -104,17 +101,8 @@ private:
PhysicalBone3D *physical_bone = nullptr;
PhysicalBone3D *cache_parent_physical_bone = nullptr;
- real_t local_pose_override_amount;
- bool local_pose_override_reset;
- Transform3D local_pose_override;
-
Vector<int> child_bones;
- // The forward direction vector and rest bone forward axis are cached because they do not change
- // 99% of the time, but recalculating them can be expensive on models with many bones.
- Vector3 rest_bone_forward_vector;
- int rest_bone_forward_axis = -1;
-
Bone() {
parent = -1;
enabled = true;
@@ -124,12 +112,7 @@ private:
physical_bone = nullptr;
cache_parent_physical_bone = nullptr;
#endif // _3D_DISABLED
- local_pose_override_amount = 0;
- local_pose_override_reset = false;
child_bones = Vector<int>();
-
- rest_bone_forward_vector = Vector3(0, 0, 0);
- rest_bone_forward_axis = -1;
}
};
@@ -162,25 +145,13 @@ protected:
void _notification(int p_what);
static void _bind_methods();
-#ifndef _3D_DISABLED
- Ref<SkeletonModificationStack3D> modification_stack;
-#endif // _3D_DISABLED
-
public:
- enum Bone_Forward_Axis {
- BONE_AXIS_X_FORWARD = 0,
- BONE_AXIS_Y_FORWARD = 1,
- BONE_AXIS_Z_FORWARD = 2,
- BONE_AXIS_NEGATIVE_X_FORWARD = 3,
- BONE_AXIS_NEGATIVE_Y_FORWARD = 4,
- BONE_AXIS_NEGATIVE_Z_FORWARD = 5,
- };
-
enum {
NOTIFICATION_UPDATE_SKELETON = 50
};
// skeleton creation api
+ uint64_t get_version() const;
void add_bone(const String &p_name);
int find_bone(const String &p_name) const;
String get_bone_name(int p_bone) const;
@@ -233,10 +204,6 @@ public:
Transform3D get_bone_global_pose_override(int p_bone) const;
void set_bone_global_pose_override(int p_bone, const Transform3D &p_pose, real_t p_amount, bool p_persistent = false);
- void clear_bones_local_pose_override();
- Transform3D get_bone_local_pose_override(int p_bone) const;
- void set_bone_local_pose_override(int p_bone, const Transform3D &p_pose, real_t p_amount, bool p_persistent = false);
-
void localize_rests(); // used for loaders and tools
Ref<Skin> create_skin_from_rest_transforms();
@@ -247,26 +214,6 @@ public:
void force_update_all_bone_transforms();
void force_update_bone_children_transforms(int bone_idx);
- void update_bone_rest_forward_vector(int p_bone, bool p_force_update = false);
- void update_bone_rest_forward_axis(int p_bone, bool p_force_update = false);
- Vector3 get_bone_axis_forward_vector(int p_bone);
- int get_bone_axis_forward_enum(int p_bone);
-
- // Helper functions
- Transform3D global_pose_to_world_transform(Transform3D p_global_pose);
- Transform3D world_transform_to_global_pose(Transform3D p_transform);
- Transform3D global_pose_to_local_pose(int p_bone_idx, Transform3D p_global_pose);
- Transform3D local_pose_to_global_pose(int p_bone_idx, Transform3D p_local_pose);
-
- Basis global_pose_z_forward_to_bone_forward(int p_bone_idx, Basis p_basis);
-
- // Modifications
-#ifndef _3D_DISABLED
- Ref<SkeletonModificationStack3D> get_modification_stack();
- void set_modification_stack(Ref<SkeletonModificationStack3D> p_stack);
- void execute_modifications(real_t p_delta, int p_execution_mode);
-#endif // _3D_DISABLED
-
// Physical bone API
void set_animate_physical_bones(bool p_enabled);
diff --git a/scene/3d/skeleton_ik_3d.cpp b/scene/3d/skeleton_ik_3d.cpp
index f35cd3fbc5..75f54a925b 100644
--- a/scene/3d/skeleton_ik_3d.cpp
+++ b/scene/3d/skeleton_ik_3d.cpp
@@ -249,6 +249,26 @@ void FabrikInverseKinematic::make_goal(Task *p_task, const Transform3D &p_invers
}
}
+static Vector3 get_bone_axis_forward_vector(Skeleton3D *skeleton, int p_bone) {
+ // If it is a child/leaf bone...
+ if (skeleton->get_bone_parent(p_bone) > 0) {
+ return skeleton->get_bone_rest(p_bone).origin.normalized();
+ }
+ // If it has children...
+ Vector<int> child_bones = skeleton->get_bone_children(p_bone);
+ if (child_bones.size() == 0) {
+ WARN_PRINT_ONCE("Cannot calculate forward direction for bone " + itos(p_bone));
+ WARN_PRINT_ONCE("Assuming direction of (0, 1, 0) for bone");
+ return Vector3(0, 1, 0);
+ }
+ Vector3 combined_child_dir = Vector3(0, 0, 0);
+ for (int i = 0; i < child_bones.size(); i++) {
+ combined_child_dir += skeleton->get_bone_rest(child_bones[i]).origin.normalized();
+ }
+ combined_child_dir = combined_child_dir / child_bones.size();
+ return combined_child_dir.normalized();
+}
+
void FabrikInverseKinematic::solve(Task *p_task, real_t blending_delta, bool override_tip_basis, bool p_use_magnet, const Vector3 &p_magnet_position) {
if (blending_delta <= 0.01f) {
// Before skipping, make sure we undo the global pose overrides
@@ -287,8 +307,7 @@ void FabrikInverseKinematic::solve(Task *p_task, real_t blending_delta, bool ove
new_bone_pose.origin = ci->current_pos;
if (!ci->children.is_empty()) {
- p_task->skeleton->update_bone_rest_forward_vector(ci->bone);
- Vector3 forward_vector = p_task->skeleton->get_bone_axis_forward_vector(ci->bone);
+ Vector3 forward_vector = get_bone_axis_forward_vector(p_task->skeleton, ci->bone);
// Rotate the bone towards the next bone in the chain:
new_bone_pose.basis.rotate_to_align(forward_vector, new_bone_pose.origin.direction_to(ci->children[0].current_pos));
diff --git a/scene/3d/soft_body_3d.cpp b/scene/3d/soft_body_3d.cpp
index e73bd460ed..e7e3084037 100644
--- a/scene/3d/soft_body_3d.cpp
+++ b/scene/3d/soft_body_3d.cpp
@@ -302,14 +302,6 @@ void SoftBody3D::_notification(int p_what) {
_prepare_physics_server();
}
} break;
-
-#ifdef TOOLS_ENABLED
- case NOTIFICATION_LOCAL_TRANSFORM_CHANGED: {
- if (Engine::get_singleton()->is_editor_hint()) {
- update_configuration_warnings();
- }
- } break;
-#endif
}
}
@@ -368,7 +360,7 @@ void SoftBody3D::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::INT, "collision_layer", PROPERTY_HINT_LAYERS_3D_PHYSICS), "set_collision_layer", "get_collision_layer");
ADD_PROPERTY(PropertyInfo(Variant::INT, "collision_mask", PROPERTY_HINT_LAYERS_3D_PHYSICS), "set_collision_mask", "get_collision_mask");
- ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "parent_collision_ignore", PROPERTY_HINT_PROPERTY_OF_VARIANT_TYPE, "Parent collision object"), "set_parent_collision_ignore", "get_parent_collision_ignore");
+ ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "parent_collision_ignore", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "CollisionObject3D"), "set_parent_collision_ignore", "get_parent_collision_ignore");
ADD_PROPERTY(PropertyInfo(Variant::INT, "simulation_precision", PROPERTY_HINT_RANGE, "1,100,1"), "set_simulation_precision", "get_simulation_precision");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "total_mass", PROPERTY_HINT_RANGE, "0.01,10000,1"), "set_total_mass", "get_total_mass");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "linear_stiffness", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_linear_stiffness", "get_linear_stiffness");
@@ -391,11 +383,6 @@ PackedStringArray SoftBody3D::get_configuration_warnings() const {
warnings.push_back(RTR("This body will be ignored until you set a mesh."));
}
- Transform3D t = get_transform();
- if ((ABS(t.basis.get_column(0).length() - 1.0) > 0.05 || ABS(t.basis.get_column(1).length() - 1.0) > 0.05 || ABS(t.basis.get_column(2).length() - 1.0) > 0.05)) {
- warnings.push_back(RTR("Size changes to SoftBody3D will be overridden by the physics engine when running.\nChange the size in children collision shapes instead."));
- }
-
return warnings;
}
diff --git a/scene/3d/sprite_3d.cpp b/scene/3d/sprite_3d.cpp
index 71d76c0d1c..59e4a0b718 100644
--- a/scene/3d/sprite_3d.cpp
+++ b/scene/3d/sprite_3d.cpp
@@ -245,8 +245,26 @@ void SpriteBase3D::draw_texture_rect(Ref<Texture2D> p_texture, Rect2 p_dst_rect,
RS::get_singleton()->mesh_set_custom_aabb(mesh_new, aabb_new);
set_aabb(aabb_new);
+ RS::get_singleton()->material_set_param(get_material(), "alpha_scissor_threshold", alpha_scissor_threshold);
+ RS::get_singleton()->material_set_param(get_material(), "alpha_hash_scale", alpha_hash_scale);
+ RS::get_singleton()->material_set_param(get_material(), "alpha_antialiasing_edge", alpha_antialiasing_edge);
+
+ BaseMaterial3D::Transparency mat_transparency = BaseMaterial3D::Transparency::TRANSPARENCY_DISABLED;
+ if (get_draw_flag(FLAG_TRANSPARENT)) {
+ if (get_alpha_cut_mode() == ALPHA_CUT_DISCARD) {
+ mat_transparency = BaseMaterial3D::Transparency::TRANSPARENCY_ALPHA_SCISSOR;
+ } else if (get_alpha_cut_mode() == ALPHA_CUT_OPAQUE_PREPASS) {
+ mat_transparency = BaseMaterial3D::Transparency::TRANSPARENCY_ALPHA_DEPTH_PRE_PASS;
+ } else if (get_alpha_cut_mode() == ALPHA_CUT_HASH) {
+ mat_transparency = BaseMaterial3D::Transparency::TRANSPARENCY_ALPHA_HASH;
+ } else {
+ mat_transparency = BaseMaterial3D::Transparency::TRANSPARENCY_ALPHA;
+ }
+ }
+
RID shader_rid;
- StandardMaterial3D::get_material_for_2d(get_draw_flag(FLAG_SHADED), get_draw_flag(FLAG_TRANSPARENT), get_draw_flag(FLAG_DOUBLE_SIDED), get_alpha_cut_mode() == ALPHA_CUT_DISCARD, get_alpha_cut_mode() == ALPHA_CUT_OPAQUE_PREPASS, get_billboard_mode() == StandardMaterial3D::BILLBOARD_ENABLED, get_billboard_mode() == StandardMaterial3D::BILLBOARD_FIXED_Y, false, get_draw_flag(FLAG_DISABLE_DEPTH_TEST), get_draw_flag(FLAG_FIXED_SIZE), get_texture_filter(), &shader_rid);
+ StandardMaterial3D::get_material_for_2d(get_draw_flag(FLAG_SHADED), mat_transparency, get_draw_flag(FLAG_DOUBLE_SIDED), get_billboard_mode() == StandardMaterial3D::BILLBOARD_ENABLED, get_billboard_mode() == StandardMaterial3D::BILLBOARD_FIXED_Y, false, get_draw_flag(FLAG_DISABLE_DEPTH_TEST), get_draw_flag(FLAG_FIXED_SIZE), get_texture_filter(), alpha_antialiasing_mode, &shader_rid);
+
if (last_shader != shader_rid) {
RS::get_singleton()->material_set_shader(get_material(), shader_rid);
last_shader = shader_rid;
@@ -433,7 +451,7 @@ bool SpriteBase3D::get_draw_flag(DrawFlags p_flag) const {
}
void SpriteBase3D::set_alpha_cut_mode(AlphaCutMode p_mode) {
- ERR_FAIL_INDEX(p_mode, 3);
+ ERR_FAIL_INDEX(p_mode, ALPHA_CUT_MAX);
alpha_cut = p_mode;
_queue_redraw();
}
@@ -442,6 +460,50 @@ SpriteBase3D::AlphaCutMode SpriteBase3D::get_alpha_cut_mode() const {
return alpha_cut;
}
+void SpriteBase3D::set_alpha_hash_scale(float p_hash_scale) {
+ if (alpha_hash_scale != p_hash_scale) {
+ alpha_hash_scale = p_hash_scale;
+ _queue_redraw();
+ }
+}
+
+float SpriteBase3D::get_alpha_hash_scale() const {
+ return alpha_hash_scale;
+}
+
+void SpriteBase3D::set_alpha_scissor_threshold(float p_threshold) {
+ if (alpha_scissor_threshold != p_threshold) {
+ alpha_scissor_threshold = p_threshold;
+ _queue_redraw();
+ }
+}
+
+float SpriteBase3D::get_alpha_scissor_threshold() const {
+ return alpha_scissor_threshold;
+}
+
+void SpriteBase3D::set_alpha_antialiasing(BaseMaterial3D::AlphaAntiAliasing p_alpha_aa) {
+ if (alpha_antialiasing_mode != p_alpha_aa) {
+ alpha_antialiasing_mode = p_alpha_aa;
+ _queue_redraw();
+ }
+}
+
+BaseMaterial3D::AlphaAntiAliasing SpriteBase3D::get_alpha_antialiasing() const {
+ return alpha_antialiasing_mode;
+}
+
+void SpriteBase3D::set_alpha_antialiasing_edge(float p_edge) {
+ if (alpha_antialiasing_edge != p_edge) {
+ alpha_antialiasing_edge = p_edge;
+ _queue_redraw();
+ }
+}
+
+float SpriteBase3D::get_alpha_antialiasing_edge() const {
+ return alpha_antialiasing_edge;
+}
+
void SpriteBase3D::set_billboard_mode(StandardMaterial3D::BillboardMode p_mode) {
ERR_FAIL_INDEX(p_mode, 3); // Cannot use BILLBOARD_PARTICLES.
billboard_mode = p_mode;
@@ -494,6 +556,18 @@ void SpriteBase3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_alpha_cut_mode", "mode"), &SpriteBase3D::set_alpha_cut_mode);
ClassDB::bind_method(D_METHOD("get_alpha_cut_mode"), &SpriteBase3D::get_alpha_cut_mode);
+ ClassDB::bind_method(D_METHOD("set_alpha_scissor_threshold", "threshold"), &SpriteBase3D::set_alpha_scissor_threshold);
+ ClassDB::bind_method(D_METHOD("get_alpha_scissor_threshold"), &SpriteBase3D::get_alpha_scissor_threshold);
+
+ ClassDB::bind_method(D_METHOD("set_alpha_hash_scale", "threshold"), &SpriteBase3D::set_alpha_hash_scale);
+ ClassDB::bind_method(D_METHOD("get_alpha_hash_scale"), &SpriteBase3D::get_alpha_hash_scale);
+
+ ClassDB::bind_method(D_METHOD("set_alpha_antialiasing", "alpha_aa"), &SpriteBase3D::set_alpha_antialiasing);
+ ClassDB::bind_method(D_METHOD("get_alpha_antialiasing"), &SpriteBase3D::get_alpha_antialiasing);
+
+ ClassDB::bind_method(D_METHOD("set_alpha_antialiasing_edge", "edge"), &SpriteBase3D::set_alpha_antialiasing_edge);
+ ClassDB::bind_method(D_METHOD("get_alpha_antialiasing_edge"), &SpriteBase3D::get_alpha_antialiasing_edge);
+
ClassDB::bind_method(D_METHOD("set_billboard_mode", "mode"), &SpriteBase3D::set_billboard_mode);
ClassDB::bind_method(D_METHOD("get_billboard_mode"), &SpriteBase3D::get_billboard_mode);
@@ -519,7 +593,11 @@ void SpriteBase3D::_bind_methods() {
ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "double_sided"), "set_draw_flag", "get_draw_flag", FLAG_DOUBLE_SIDED);
ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "no_depth_test"), "set_draw_flag", "get_draw_flag", FLAG_DISABLE_DEPTH_TEST);
ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "fixed_size"), "set_draw_flag", "get_draw_flag", FLAG_FIXED_SIZE);
- ADD_PROPERTY(PropertyInfo(Variant::INT, "alpha_cut", PROPERTY_HINT_ENUM, "Disabled,Discard,Opaque Pre-Pass"), "set_alpha_cut_mode", "get_alpha_cut_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "alpha_cut", PROPERTY_HINT_ENUM, "Disabled,Discard,Opaque Pre-Pass,Alpha Hash"), "set_alpha_cut_mode", "get_alpha_cut_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "alpha_scissor_threshold", PROPERTY_HINT_RANGE, "0,1,0.001"), "set_alpha_scissor_threshold", "get_alpha_scissor_threshold");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "alpha_hash_scale", PROPERTY_HINT_RANGE, "0,2,0.01"), "set_alpha_hash_scale", "get_alpha_hash_scale");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "alpha_antialiasing_mode", PROPERTY_HINT_ENUM, "Disabled,Alpha Edge Blend,Alpha Edge Clip"), "set_alpha_antialiasing", "get_alpha_antialiasing");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "alpha_antialiasing_edge", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_alpha_antialiasing_edge", "get_alpha_antialiasing_edge");
ADD_PROPERTY(PropertyInfo(Variant::INT, "texture_filter", PROPERTY_HINT_ENUM, "Nearest,Linear,Nearest Mipmap,Linear Mipmap,Nearest Mipmap Anisotropic,Linear Mipmap Anisotropic"), "set_texture_filter", "get_texture_filter");
ADD_PROPERTY(PropertyInfo(Variant::INT, "render_priority", PROPERTY_HINT_RANGE, itos(RS::MATERIAL_RENDER_PRIORITY_MIN) + "," + itos(RS::MATERIAL_RENDER_PRIORITY_MAX) + ",1"), "set_render_priority", "get_render_priority");
@@ -533,6 +611,7 @@ void SpriteBase3D::_bind_methods() {
BIND_ENUM_CONSTANT(ALPHA_CUT_DISABLED);
BIND_ENUM_CONSTANT(ALPHA_CUT_DISCARD);
BIND_ENUM_CONSTANT(ALPHA_CUT_OPAQUE_PREPASS);
+ BIND_ENUM_CONSTANT(ALPHA_CUT_HASH);
}
SpriteBase3D::SpriteBase3D() {
@@ -550,7 +629,6 @@ SpriteBase3D::SpriteBase3D() {
RS::get_singleton()->material_set_param(material, "uv1_scale", Vector3(1, 1, 1));
RS::get_singleton()->material_set_param(material, "uv2_offset", Vector3(0, 0, 0));
RS::get_singleton()->material_set_param(material, "uv2_scale", Vector3(1, 1, 1));
- RS::get_singleton()->material_set_param(material, "alpha_scissor_threshold", 0.5);
mesh = RenderingServer::get_singleton()->mesh_create();
@@ -866,7 +944,6 @@ void AnimatedSprite3D::_validate_property(PropertyInfo &p_property) const {
}
if (p_property.name == "animation") {
- p_property.hint = PROPERTY_HINT_ENUM;
List<StringName> names;
frames->get_animation_list(&names);
names.sort_custom<StringName::AlphCompare>();
@@ -916,6 +993,12 @@ void AnimatedSprite3D::_validate_property(PropertyInfo &p_property) const {
void AnimatedSprite3D::_notification(int p_what) {
switch (p_what) {
+ case NOTIFICATION_READY: {
+ if (!Engine::get_singleton()->is_editor_hint() && !frames.is_null() && frames->has_animation(autoplay)) {
+ play(autoplay);
+ }
+ } break;
+
case NOTIFICATION_INTERNAL_PROCESS: {
if (frames.is_null() || !frames->has_animation(animation)) {
return;
@@ -925,7 +1008,8 @@ void AnimatedSprite3D::_notification(int p_what) {
int i = 0;
while (remaining) {
// Animation speed may be changed by animation_finished or frame_changed signals.
- double speed = frames->get_animation_speed(animation) * Math::abs(speed_scale);
+ double speed = frames->get_animation_speed(animation) * speed_scale * custom_speed_scale * frame_speed_scale;
+ double abs_speed = Math::abs(speed);
if (speed == 0) {
return; // Do nothing.
@@ -934,53 +1018,57 @@ void AnimatedSprite3D::_notification(int p_what) {
// Frame count may be changed by animation_finished or frame_changed signals.
int fc = frames->get_frame_count(animation);
- if (timeout <= 0) {
- int last_frame = fc - 1;
- if (!playing_backwards) {
- // Forward.
+ int last_frame = fc - 1;
+ if (!signbit(speed)) {
+ // Forwards.
+ if (frame_progress >= 1.0) {
if (frame >= last_frame) {
if (frames->get_animation_loop(animation)) {
frame = 0;
- emit_signal(SceneStringNames::get_singleton()->animation_finished);
+ emit_signal("animation_looped");
} else {
frame = last_frame;
- if (!is_over) {
- is_over = true;
- emit_signal(SceneStringNames::get_singleton()->animation_finished);
- }
+ pause();
+ emit_signal(SceneStringNames::get_singleton()->animation_finished);
+ return;
}
} else {
frame++;
}
- } else {
- // Reversed.
+ _calc_frame_speed_scale();
+ frame_progress = 0.0;
+ _queue_redraw();
+ emit_signal(SceneStringNames::get_singleton()->frame_changed);
+ }
+ double to_process = MIN((1.0 - frame_progress) / abs_speed, remaining);
+ frame_progress += to_process * abs_speed;
+ remaining -= to_process;
+ } else {
+ // Backwards.
+ if (frame_progress <= 0) {
if (frame <= 0) {
if (frames->get_animation_loop(animation)) {
frame = last_frame;
- emit_signal(SceneStringNames::get_singleton()->animation_finished);
+ emit_signal("animation_looped");
} else {
frame = 0;
- if (!is_over) {
- is_over = true;
- emit_signal(SceneStringNames::get_singleton()->animation_finished);
- }
+ pause();
+ emit_signal(SceneStringNames::get_singleton()->animation_finished);
+ return;
}
} else {
frame--;
}
+ _calc_frame_speed_scale();
+ frame_progress = 1.0;
+ _queue_redraw();
+ emit_signal(SceneStringNames::get_singleton()->frame_changed);
}
-
- timeout = _get_frame_duration();
-
- _queue_redraw();
-
- emit_signal(SceneStringNames::get_singleton()->frame_changed);
+ double to_process = MIN(frame_progress / abs_speed, remaining);
+ frame_progress -= to_process * abs_speed;
+ remaining -= to_process;
}
- double to_process = MIN(timeout / speed, remaining);
- timeout -= to_process * speed;
- remaining -= to_process;
-
i++;
if (i > fc) {
return; // Prevents freezing if to_process is each time much less than remaining.
@@ -991,25 +1079,37 @@ void AnimatedSprite3D::_notification(int p_what) {
}
void AnimatedSprite3D::set_sprite_frames(const Ref<SpriteFrames> &p_frames) {
+ if (frames == p_frames) {
+ return;
+ }
+
if (frames.is_valid()) {
frames->disconnect(SceneStringNames::get_singleton()->changed, callable_mp(this, &AnimatedSprite3D::_res_changed));
}
-
+ stop();
frames = p_frames;
if (frames.is_valid()) {
frames->connect(SceneStringNames::get_singleton()->changed, callable_mp(this, &AnimatedSprite3D::_res_changed));
- }
- if (frames.is_null()) {
- frame = 0;
- } else {
- set_frame(frame);
+ List<StringName> al;
+ frames->get_animation_list(&al);
+ if (al.size() == 0) {
+ set_animation(StringName());
+ set_autoplay(String());
+ } else {
+ if (!frames->has_animation(animation)) {
+ set_animation(al[0]);
+ }
+ if (!frames->has_animation(autoplay)) {
+ set_autoplay(String());
+ }
+ }
}
notify_property_list_changed();
- _reset_timeout();
_queue_redraw();
update_configuration_warnings();
+ emit_signal("sprite_frames_changed");
}
Ref<SpriteFrames> AnimatedSprite3D::get_sprite_frames() const {
@@ -1017,44 +1117,63 @@ Ref<SpriteFrames> AnimatedSprite3D::get_sprite_frames() const {
}
void AnimatedSprite3D::set_frame(int p_frame) {
+ set_frame_and_progress(p_frame, signbit(get_playing_speed()) ? 1.0 : 0.0);
+}
+
+int AnimatedSprite3D::get_frame() const {
+ return frame;
+}
+
+void AnimatedSprite3D::set_frame_progress(real_t p_progress) {
+ frame_progress = p_progress;
+}
+
+real_t AnimatedSprite3D::get_frame_progress() const {
+ return frame_progress;
+}
+
+void AnimatedSprite3D::set_frame_and_progress(int p_frame, real_t p_progress) {
if (frames.is_null()) {
return;
}
- if (frames->has_animation(animation)) {
- int limit = frames->get_frame_count(animation);
- if (p_frame >= limit) {
- p_frame = limit - 1;
- }
- }
+ bool has_animation = frames->has_animation(animation);
+ int end_frame = has_animation ? MAX(0, frames->get_frame_count(animation) - 1) : 0;
+ bool is_changed = frame != p_frame;
if (p_frame < 0) {
- p_frame = 0;
+ frame = 0;
+ } else if (has_animation && p_frame > end_frame) {
+ frame = end_frame;
+ } else {
+ frame = p_frame;
}
- if (frame == p_frame) {
- return;
- }
+ _calc_frame_speed_scale();
+ frame_progress = p_progress;
- frame = p_frame;
- _reset_timeout();
+ if (!is_changed) {
+ return; // No change, don't redraw.
+ }
_queue_redraw();
emit_signal(SceneStringNames::get_singleton()->frame_changed);
}
-int AnimatedSprite3D::get_frame() const {
- return frame;
-}
-
void AnimatedSprite3D::set_speed_scale(float p_speed_scale) {
speed_scale = p_speed_scale;
- playing_backwards = signbit(speed_scale) != backwards;
}
float AnimatedSprite3D::get_speed_scale() const {
return speed_scale;
}
+float AnimatedSprite3D::get_playing_speed() const {
+ if (!playing) {
+ return 0;
+ }
+ return speed_scale * custom_speed_scale;
+}
+
Rect2 AnimatedSprite3D::get_item_rect() const {
if (frames.is_null() || !frames->has_animation(animation)) {
return Rect2(0, 0, 1, 1);
@@ -1085,69 +1204,131 @@ Rect2 AnimatedSprite3D::get_item_rect() const {
}
void AnimatedSprite3D::_res_changed() {
- set_frame(frame);
+ set_frame_and_progress(frame, frame_progress);
_queue_redraw();
notify_property_list_changed();
}
-void AnimatedSprite3D::set_playing(bool p_playing) {
- if (playing == p_playing) {
- return;
+bool AnimatedSprite3D::is_playing() const {
+ return playing;
+}
+
+void AnimatedSprite3D::set_autoplay(const String &p_name) {
+ if (is_inside_tree() && !Engine::get_singleton()->is_editor_hint()) {
+ WARN_PRINT("Setting autoplay after the node has been added to the scene has no effect.");
}
- playing = p_playing;
- playing_backwards = signbit(speed_scale) != backwards;
- set_process_internal(playing);
- notify_property_list_changed();
+
+ autoplay = p_name;
}
-bool AnimatedSprite3D::is_playing() const {
- return playing;
+String AnimatedSprite3D::get_autoplay() const {
+ return autoplay;
}
-void AnimatedSprite3D::play(const StringName &p_animation, bool p_backwards) {
- backwards = p_backwards;
- playing_backwards = signbit(speed_scale) != backwards;
+void AnimatedSprite3D::play(const StringName &p_name, float p_custom_scale, bool p_from_end) {
+ StringName name = p_name;
+
+ if (name == StringName()) {
+ name = animation;
+ }
+
+ ERR_FAIL_COND_MSG(frames == nullptr, vformat("There is no animation with name '%s'.", name));
+ ERR_FAIL_COND_MSG(!frames->get_animation_names().has(name), vformat("There is no animation with name '%s'.", name));
- if (p_animation) {
- set_animation(p_animation);
- if (frames.is_valid() && playing_backwards && get_frame() == 0) {
- set_frame(frames->get_frame_count(p_animation) - 1);
+ if (frames->get_frame_count(name) == 0) {
+ return;
+ }
+
+ playing = true;
+ custom_speed_scale = p_custom_scale;
+
+ int end_frame = MAX(0, frames->get_frame_count(animation) - 1);
+ if (name != animation) {
+ animation = name;
+ if (p_from_end) {
+ set_frame_and_progress(end_frame, 1.0);
+ } else {
+ set_frame_and_progress(0, 0.0);
+ }
+ emit_signal("animation_changed");
+ } else {
+ bool is_backward = signbit(speed_scale * custom_speed_scale);
+ if (p_from_end && is_backward && frame == 0 && frame_progress <= 0.0) {
+ set_frame_and_progress(end_frame, 1.0);
+ } else if (!p_from_end && !is_backward && frame == end_frame && frame_progress >= 1.0) {
+ set_frame_and_progress(0, 0.0);
}
}
- is_over = false;
- set_playing(true);
+ set_process_internal(true);
+ notify_property_list_changed();
+ _queue_redraw();
+}
+
+void AnimatedSprite3D::play_backwards(const StringName &p_name) {
+ play(p_name, -1, true);
+}
+
+void AnimatedSprite3D::_stop_internal(bool p_reset) {
+ playing = false;
+ if (p_reset) {
+ custom_speed_scale = 1.0;
+ set_frame_and_progress(0, 0.0);
+ }
+ notify_property_list_changed();
+ set_process_internal(false);
+}
+
+void AnimatedSprite3D::pause() {
+ _stop_internal(false);
}
void AnimatedSprite3D::stop() {
- set_playing(false);
- backwards = false;
- _reset_timeout();
+ _stop_internal(true);
}
double AnimatedSprite3D::_get_frame_duration() {
if (frames.is_valid() && frames->has_animation(animation)) {
return frames->get_frame_duration(animation, frame);
}
- return 0.0;
+ return 1.0;
}
-void AnimatedSprite3D::_reset_timeout() {
- timeout = _get_frame_duration();
- is_over = false;
+void AnimatedSprite3D::_calc_frame_speed_scale() {
+ frame_speed_scale = 1.0 / _get_frame_duration();
}
-void AnimatedSprite3D::set_animation(const StringName &p_animation) {
- ERR_FAIL_COND_MSG(frames == nullptr, vformat("There is no animation with name '%s'.", p_animation));
- ERR_FAIL_COND_MSG(!frames->get_animation_names().has(p_animation), vformat("There is no animation with name '%s'.", p_animation));
+void AnimatedSprite3D::set_animation(const StringName &p_name) {
+ if (animation == p_name) {
+ return;
+ }
+
+ animation = p_name;
- if (animation == p_animation) {
+ emit_signal("animation_changed");
+
+ if (frames == nullptr) {
+ animation = StringName();
+ stop();
+ ERR_FAIL_MSG(vformat("There is no animation with name '%s'.", p_name));
+ }
+
+ int frame_count = frames->get_frame_count(animation);
+ if (animation == StringName() || frame_count == 0) {
+ stop();
return;
+ } else if (!frames->get_animation_names().has(animation)) {
+ animation = StringName();
+ stop();
+ ERR_FAIL_MSG(vformat("There is no animation with name '%s'.", p_name));
+ }
+
+ if (signbit(get_playing_speed())) {
+ set_frame_and_progress(frame_count - 1, 1.0);
+ } else {
+ set_frame_and_progress(0, 0.0);
}
- animation = p_animation;
- set_frame(0);
- _reset_timeout();
notify_property_list_changed();
_queue_redraw();
}
@@ -1175,35 +1356,58 @@ void AnimatedSprite3D::get_argument_options(const StringName &p_function, int p_
Node::get_argument_options(p_function, p_idx, r_options);
}
+#ifndef DISABLE_DEPRECATED
+bool AnimatedSprite3D::_set(const StringName &p_name, const Variant &p_value) {
+ if ((p_name == SNAME("frames"))) {
+ set_sprite_frames(p_value);
+ return true;
+ }
+ return false;
+}
+#endif
void AnimatedSprite3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_sprite_frames", "sprite_frames"), &AnimatedSprite3D::set_sprite_frames);
ClassDB::bind_method(D_METHOD("get_sprite_frames"), &AnimatedSprite3D::get_sprite_frames);
- ClassDB::bind_method(D_METHOD("set_animation", "animation"), &AnimatedSprite3D::set_animation);
+ ClassDB::bind_method(D_METHOD("set_animation", "name"), &AnimatedSprite3D::set_animation);
ClassDB::bind_method(D_METHOD("get_animation"), &AnimatedSprite3D::get_animation);
- ClassDB::bind_method(D_METHOD("set_playing", "playing"), &AnimatedSprite3D::set_playing);
+ ClassDB::bind_method(D_METHOD("set_autoplay", "name"), &AnimatedSprite3D::set_autoplay);
+ ClassDB::bind_method(D_METHOD("get_autoplay"), &AnimatedSprite3D::get_autoplay);
+
ClassDB::bind_method(D_METHOD("is_playing"), &AnimatedSprite3D::is_playing);
- ClassDB::bind_method(D_METHOD("play", "anim", "backwards"), &AnimatedSprite3D::play, DEFVAL(StringName()), DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("play", "name", "custom_speed", "from_end"), &AnimatedSprite3D::play, DEFVAL(StringName()), DEFVAL(1.0), DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("play_backwards", "name"), &AnimatedSprite3D::play_backwards, DEFVAL(StringName()));
+ ClassDB::bind_method(D_METHOD("pause"), &AnimatedSprite3D::pause);
ClassDB::bind_method(D_METHOD("stop"), &AnimatedSprite3D::stop);
ClassDB::bind_method(D_METHOD("set_frame", "frame"), &AnimatedSprite3D::set_frame);
ClassDB::bind_method(D_METHOD("get_frame"), &AnimatedSprite3D::get_frame);
+ ClassDB::bind_method(D_METHOD("set_frame_progress", "progress"), &AnimatedSprite3D::set_frame_progress);
+ ClassDB::bind_method(D_METHOD("get_frame_progress"), &AnimatedSprite3D::get_frame_progress);
+
+ ClassDB::bind_method(D_METHOD("set_frame_and_progress", "frame", "progress"), &AnimatedSprite3D::set_frame_and_progress);
+
ClassDB::bind_method(D_METHOD("set_speed_scale", "speed_scale"), &AnimatedSprite3D::set_speed_scale);
ClassDB::bind_method(D_METHOD("get_speed_scale"), &AnimatedSprite3D::get_speed_scale);
+ ClassDB::bind_method(D_METHOD("get_playing_speed"), &AnimatedSprite3D::get_playing_speed);
ClassDB::bind_method(D_METHOD("_res_changed"), &AnimatedSprite3D::_res_changed);
+ ADD_SIGNAL(MethodInfo("sprite_frames_changed"));
+ ADD_SIGNAL(MethodInfo("animation_changed"));
ADD_SIGNAL(MethodInfo("frame_changed"));
+ ADD_SIGNAL(MethodInfo("animation_looped"));
ADD_SIGNAL(MethodInfo("animation_finished"));
- ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "frames", PROPERTY_HINT_RESOURCE_TYPE, "SpriteFrames"), "set_sprite_frames", "get_sprite_frames");
- ADD_PROPERTY(PropertyInfo(Variant::STRING, "animation"), "set_animation", "get_animation");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "sprite_frames", PROPERTY_HINT_RESOURCE_TYPE, "SpriteFrames"), "set_sprite_frames", "get_sprite_frames");
+ ADD_PROPERTY(PropertyInfo(Variant::STRING_NAME, "animation", PROPERTY_HINT_ENUM, ""), "set_animation", "get_animation");
+ ADD_PROPERTY(PropertyInfo(Variant::STRING_NAME, "autoplay", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "set_autoplay", "get_autoplay");
ADD_PROPERTY(PropertyInfo(Variant::INT, "frame"), "set_frame", "get_frame");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "frame_progress", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "set_frame_progress", "get_frame_progress");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "speed_scale"), "set_speed_scale", "get_speed_scale");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL, "playing"), "set_playing", "is_playing");
}
AnimatedSprite3D::AnimatedSprite3D() {
diff --git a/scene/3d/sprite_3d.h b/scene/3d/sprite_3d.h
index c5509aa723..1eb1211951 100644
--- a/scene/3d/sprite_3d.h
+++ b/scene/3d/sprite_3d.h
@@ -53,7 +53,9 @@ public:
enum AlphaCutMode {
ALPHA_CUT_DISABLED,
ALPHA_CUT_DISCARD,
- ALPHA_CUT_OPAQUE_PREPASS
+ ALPHA_CUT_OPAQUE_PREPASS,
+ ALPHA_CUT_HASH,
+ ALPHA_CUT_MAX
};
private:
@@ -85,6 +87,10 @@ private:
bool flags[FLAG_MAX] = {};
AlphaCutMode alpha_cut = ALPHA_CUT_DISABLED;
+ float alpha_scissor_threshold = 0.5;
+ float alpha_hash_scale = 1.0;
+ StandardMaterial3D::AlphaAntiAliasing alpha_antialiasing_mode = StandardMaterial3D::ALPHA_ANTIALIASING_OFF;
+ float alpha_antialiasing_edge = 0.0f;
StandardMaterial3D::BillboardMode billboard_mode = StandardMaterial3D::BILLBOARD_DISABLED;
StandardMaterial3D::TextureFilter texture_filter = StandardMaterial3D::TEXTURE_FILTER_LINEAR_WITH_MIPMAPS;
bool pending_update = false;
@@ -143,6 +149,18 @@ public:
void set_alpha_cut_mode(AlphaCutMode p_mode);
AlphaCutMode get_alpha_cut_mode() const;
+ void set_alpha_scissor_threshold(float p_threshold);
+ float get_alpha_scissor_threshold() const;
+
+ void set_alpha_hash_scale(float p_hash_scale);
+ float get_alpha_hash_scale() const;
+
+ void set_alpha_antialiasing(BaseMaterial3D::AlphaAntiAliasing p_alpha_aa);
+ BaseMaterial3D::AlphaAntiAliasing get_alpha_antialiasing() const;
+
+ void set_alpha_antialiasing_edge(float p_edge);
+ float get_alpha_antialiasing_edge() const;
+
void set_billboard_mode(StandardMaterial3D::BillboardMode p_mode);
StandardMaterial3D::BillboardMode get_billboard_mode() const;
@@ -209,24 +227,29 @@ class AnimatedSprite3D : public SpriteBase3D {
GDCLASS(AnimatedSprite3D, SpriteBase3D);
Ref<SpriteFrames> frames;
+ String autoplay;
+
bool playing = false;
- bool playing_backwards = false;
- bool backwards = false;
StringName animation = "default";
int frame = 0;
float speed_scale = 1.0;
+ float custom_speed_scale = 1.0;
bool centered = false;
- bool is_over = false;
- double timeout = 0.0;
+ real_t frame_speed_scale = 1.0;
+ real_t frame_progress = 0.0;
void _res_changed();
double _get_frame_duration();
- void _reset_timeout();
+ void _calc_frame_speed_scale();
+ void _stop_internal(bool p_reset);
protected:
+#ifndef DISABLE_DEPRECATED
+ bool _set(const StringName &p_name, const Variant &p_value);
+#endif
virtual void _draw() override;
static void _bind_methods();
void _notification(int p_what);
@@ -236,20 +259,30 @@ public:
void set_sprite_frames(const Ref<SpriteFrames> &p_frames);
Ref<SpriteFrames> get_sprite_frames() const;
- void play(const StringName &p_animation = StringName(), bool p_backwards = false);
+ void play(const StringName &p_name = StringName(), float p_custom_scale = 1.0, bool p_from_end = false);
+ void play_backwards(const StringName &p_name = StringName());
+ void pause();
void stop();
- void set_playing(bool p_playing);
bool is_playing() const;
- void set_animation(const StringName &p_animation);
+ void set_animation(const StringName &p_name);
StringName get_animation() const;
+ void set_autoplay(const String &p_name);
+ String get_autoplay() const;
+
void set_frame(int p_frame);
int get_frame() const;
+ void set_frame_progress(real_t p_progress);
+ real_t get_frame_progress() const;
+
+ void set_frame_and_progress(int p_frame, real_t p_progress);
+
void set_speed_scale(float p_speed_scale);
float get_speed_scale() const;
+ float get_playing_speed() const;
virtual Rect2 get_item_rect() const override;
diff --git a/scene/3d/visible_on_screen_notifier_3d.cpp b/scene/3d/visible_on_screen_notifier_3d.cpp
index 60a0b03c0d..afddfdb749 100644
--- a/scene/3d/visible_on_screen_notifier_3d.cpp
+++ b/scene/3d/visible_on_screen_notifier_3d.cpp
@@ -128,7 +128,7 @@ void VisibleOnScreenEnabler3D::set_enable_node_path(NodePath p_path) {
return;
}
enable_node_path = p_path;
- if (is_inside_tree()) {
+ if (is_inside_tree() && !Engine::get_singleton()->is_editor_hint()) {
node_id = ObjectID();
Node *node = get_node(enable_node_path);
if (node) {
diff --git a/scene/3d/visual_instance_3d.cpp b/scene/3d/visual_instance_3d.cpp
index 64fb0a7657..8026b12c2b 100644
--- a/scene/3d/visual_instance_3d.cpp
+++ b/scene/3d/visual_instance_3d.cpp
@@ -120,6 +120,12 @@ bool VisualInstance3D::is_sorting_use_aabb_center() const {
return sorting_use_aabb_center;
}
+void VisualInstance3D::_validate_property(PropertyInfo &p_property) const {
+ if (p_property.name == "sorting_offset" || p_property.name == "sorting_use_aabb_center") {
+ p_property.usage = PROPERTY_USAGE_NONE;
+ }
+}
+
void VisualInstance3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_base", "base"), &VisualInstance3D::set_base);
ClassDB::bind_method(D_METHOD("get_base"), &VisualInstance3D::get_base);
@@ -437,6 +443,12 @@ PackedStringArray GeometryInstance3D::get_configuration_warnings() const {
return warnings;
}
+void GeometryInstance3D::_validate_property(PropertyInfo &p_property) const {
+ if (p_property.name == "sorting_offset" || p_property.name == "sorting_use_aabb_center") {
+ p_property.usage = PROPERTY_USAGE_DEFAULT;
+ }
+}
+
void GeometryInstance3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_material_override", "material"), &GeometryInstance3D::set_material_override);
ClassDB::bind_method(D_METHOD("get_material_override"), &GeometryInstance3D::get_material_override);
diff --git a/scene/3d/visual_instance_3d.h b/scene/3d/visual_instance_3d.h
index 190ed17753..ef0f7966e2 100644
--- a/scene/3d/visual_instance_3d.h
+++ b/scene/3d/visual_instance_3d.h
@@ -47,6 +47,7 @@ protected:
void _notification(int p_what);
static void _bind_methods();
+ void _validate_property(PropertyInfo &p_property) const;
GDVIRTUAL0RC(AABB, _get_aabb)
public:
@@ -140,6 +141,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;
+ void _validate_property(PropertyInfo &p_property) const;
static void _bind_methods();
diff --git a/scene/3d/voxel_gi.cpp b/scene/3d/voxel_gi.cpp
index 4325152a7b..36a877246e 100644
--- a/scene/3d/voxel_gi.cpp
+++ b/scene/3d/voxel_gi.cpp
@@ -237,6 +237,24 @@ void VoxelGIData::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "interior"), "set_interior", "is_interior");
}
+#ifndef DISABLE_DEPRECATED
+bool VoxelGI::_set(const StringName &p_name, const Variant &p_value) {
+ if (p_name == "extents") { // Compatibility with Godot 3.x.
+ set_size((Vector3)p_value * 2);
+ return true;
+ }
+ return false;
+}
+
+bool VoxelGI::_get(const StringName &p_name, Variant &r_property) const {
+ if (p_name == "extents") { // Compatibility with Godot 3.x.
+ r_property = size / 2;
+ return true;
+ }
+ return false;
+}
+#endif // DISABLE_DEPRECATED
+
VoxelGIData::VoxelGIData() {
probe = RS::get_singleton()->voxel_gi_create();
}
@@ -273,14 +291,14 @@ VoxelGI::Subdiv VoxelGI::get_subdiv() const {
return subdiv;
}
-void VoxelGI::set_extents(const Vector3 &p_extents) {
- // Prevent very small extents as these break baking if other extents are set very high.
- extents = Vector3(MAX(1.0, p_extents.x), MAX(1.0, p_extents.y), MAX(1.0, p_extents.z));
+void VoxelGI::set_size(const Vector3 &p_size) {
+ // Prevent very small size dimensions as these breaks baking if other size dimensions are set very high.
+ size = Vector3(MAX(1.0, p_size.x), MAX(1.0, p_size.y), MAX(1.0, p_size.z));
update_gizmos();
}
-Vector3 VoxelGI::get_extents() const {
- return extents;
+Vector3 VoxelGI::get_size() const {
+ return size;
}
void VoxelGI::set_camera_attributes(const Ref<CameraAttributes> &p_camera_attributes) {
@@ -300,7 +318,7 @@ void VoxelGI::_find_meshes(Node *p_at_node, List<PlotMesh> &plot_meshes) {
Transform3D xf = get_global_transform().affine_inverse() * mi->get_global_transform();
- if (AABB(-extents, extents * 2).intersects(xf.xform(aabb))) {
+ if (AABB(-size / 2, size).intersects(xf.xform(aabb))) {
PlotMesh pm;
pm.local_xform = xf;
pm.mesh = mesh;
@@ -328,7 +346,7 @@ void VoxelGI::_find_meshes(Node *p_at_node, List<PlotMesh> &plot_meshes) {
Transform3D xf = get_global_transform().affine_inverse() * (s->get_global_transform() * mxf);
- if (AABB(-extents, extents * 2).intersects(xf.xform(aabb))) {
+ if (AABB(-size / 2, size).intersects(xf.xform(aabb))) {
PlotMesh pm;
pm.local_xform = xf;
pm.mesh = mesh;
@@ -352,7 +370,7 @@ Vector3i VoxelGI::get_estimated_cell_size() const {
static const int subdiv_value[SUBDIV_MAX] = { 6, 7, 8, 9 };
int cell_subdiv = subdiv_value[subdiv];
int axis_cell_size[3];
- AABB bounds = AABB(-extents, extents * 2.0);
+ AABB bounds = AABB(-size / 2, size);
int longest_axis = bounds.get_longest_axis_index();
axis_cell_size[longest_axis] = 1 << cell_subdiv;
@@ -390,7 +408,7 @@ void VoxelGI::bake(Node *p_from_node, bool p_create_visual_debug) {
Voxelizer baker;
- baker.begin_bake(subdiv_value[subdiv], AABB(-extents, extents * 2.0), exposure_normalization);
+ baker.begin_bake(subdiv_value[subdiv], AABB(-size / 2, size), exposure_normalization);
List<PlotMesh> mesh_list;
@@ -448,7 +466,7 @@ void VoxelGI::bake(Node *p_from_node, bool p_create_visual_debug) {
RS::get_singleton()->voxel_gi_set_baked_exposure_normalization(probe_data_new->get_rid(), exposure_normalization);
- probe_data_new->allocate(baker.get_to_cell_space_xform(), AABB(-extents, extents * 2.0), baker.get_voxel_gi_octree_size(), baker.get_voxel_gi_octree_cells(), baker.get_voxel_gi_data_cells(), df, baker.get_voxel_gi_level_cell_count());
+ probe_data_new->allocate(baker.get_to_cell_space_xform(), AABB(-size / 2, size), baker.get_voxel_gi_octree_size(), baker.get_voxel_gi_octree_cells(), baker.get_voxel_gi_data_cells(), df, baker.get_voxel_gi_level_cell_count());
set_probe_data(probe_data_new);
#ifdef TOOLS_ENABLED
@@ -468,7 +486,7 @@ void VoxelGI::_debug_bake() {
}
AABB VoxelGI::get_aabb() const {
- return AABB(-extents, extents * 2);
+ return AABB(-size / 2, size);
}
PackedStringArray VoxelGI::get_configuration_warnings() const {
@@ -489,8 +507,8 @@ void VoxelGI::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_subdiv", "subdiv"), &VoxelGI::set_subdiv);
ClassDB::bind_method(D_METHOD("get_subdiv"), &VoxelGI::get_subdiv);
- ClassDB::bind_method(D_METHOD("set_extents", "extents"), &VoxelGI::set_extents);
- ClassDB::bind_method(D_METHOD("get_extents"), &VoxelGI::get_extents);
+ ClassDB::bind_method(D_METHOD("set_size", "size"), &VoxelGI::set_size);
+ ClassDB::bind_method(D_METHOD("get_size"), &VoxelGI::get_size);
ClassDB::bind_method(D_METHOD("set_camera_attributes", "camera_attributes"), &VoxelGI::set_camera_attributes);
ClassDB::bind_method(D_METHOD("get_camera_attributes"), &VoxelGI::get_camera_attributes);
@@ -500,9 +518,9 @@ void VoxelGI::_bind_methods() {
ClassDB::set_method_flags(get_class_static(), _scs_create("debug_bake"), METHOD_FLAGS_DEFAULT | METHOD_FLAG_EDITOR);
ADD_PROPERTY(PropertyInfo(Variant::INT, "subdiv", PROPERTY_HINT_ENUM, "64,128,256,512"), "set_subdiv", "get_subdiv");
- ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "extents", PROPERTY_HINT_NONE, "suffix:m"), "set_extents", "get_extents");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "size", PROPERTY_HINT_NONE, "suffix:m"), "set_size", "get_size");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "camera_attributes", PROPERTY_HINT_RESOURCE_TYPE, "CameraAttributesPractical,CameraAttributesPhysical"), "set_camera_attributes", "get_camera_attributes");
- ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "data", PROPERTY_HINT_RESOURCE_TYPE, "VoxelGIData", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_DO_NOT_SHARE_ON_DUPLICATE), "set_probe_data", "get_probe_data");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "data", PROPERTY_HINT_RESOURCE_TYPE, "VoxelGIData", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_ALWAYS_DUPLICATE), "set_probe_data", "get_probe_data");
BIND_ENUM_CONSTANT(SUBDIV_64);
BIND_ENUM_CONSTANT(SUBDIV_128);
diff --git a/scene/3d/voxel_gi.h b/scene/3d/voxel_gi.h
index ae348daf9e..d276186dd1 100644
--- a/scene/3d/voxel_gi.h
+++ b/scene/3d/voxel_gi.h
@@ -118,7 +118,7 @@ private:
RID voxel_gi;
Subdiv subdiv = SUBDIV_128;
- Vector3 extents = Vector3(10, 10, 10);
+ Vector3 size = Vector3(20, 20, 20);
Ref<CameraAttributes> camera_attributes;
struct PlotMesh {
@@ -133,6 +133,10 @@ private:
protected:
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_property) const;
+#endif // DISABLE_DEPRECATED
public:
static BakeBeginFunc bake_begin_function;
@@ -145,8 +149,8 @@ public:
void set_subdiv(Subdiv p_subdiv);
Subdiv get_subdiv() const;
- void set_extents(const Vector3 &p_extents);
- Vector3 get_extents() const;
+ void set_size(const Vector3 &p_size);
+ Vector3 get_size() const;
void set_camera_attributes(const Ref<CameraAttributes> &p_camera_attributes);
Ref<CameraAttributes> get_camera_attributes() const;
diff --git a/scene/3d/xr_nodes.cpp b/scene/3d/xr_nodes.cpp
index a758cc5e5e..ac0a47d1a1 100644
--- a/scene/3d/xr_nodes.cpp
+++ b/scene/3d/xr_nodes.cpp
@@ -432,15 +432,16 @@ PackedStringArray XRNode3D::get_configuration_warnings() const {
void XRController3D::_bind_methods() {
// passthroughs to information about our related joystick
ClassDB::bind_method(D_METHOD("is_button_pressed", "name"), &XRController3D::is_button_pressed);
- ClassDB::bind_method(D_METHOD("get_value", "name"), &XRController3D::get_value);
- ClassDB::bind_method(D_METHOD("get_axis", "name"), &XRController3D::get_axis);
+ ClassDB::bind_method(D_METHOD("get_input", "name"), &XRController3D::get_input);
+ ClassDB::bind_method(D_METHOD("get_float", "name"), &XRController3D::get_float);
+ ClassDB::bind_method(D_METHOD("get_vector2", "name"), &XRController3D::get_vector2);
ClassDB::bind_method(D_METHOD("get_tracker_hand"), &XRController3D::get_tracker_hand);
ADD_SIGNAL(MethodInfo("button_pressed", PropertyInfo(Variant::STRING, "name")));
ADD_SIGNAL(MethodInfo("button_released", PropertyInfo(Variant::STRING, "name")));
- ADD_SIGNAL(MethodInfo("input_value_changed", PropertyInfo(Variant::STRING, "name"), PropertyInfo(Variant::FLOAT, "value")));
- ADD_SIGNAL(MethodInfo("input_axis_changed", PropertyInfo(Variant::STRING, "name"), PropertyInfo(Variant::VECTOR2, "value")));
+ ADD_SIGNAL(MethodInfo("input_float_changed", PropertyInfo(Variant::STRING, "name"), PropertyInfo(Variant::FLOAT, "value")));
+ ADD_SIGNAL(MethodInfo("input_vector2_changed", PropertyInfo(Variant::STRING, "name"), PropertyInfo(Variant::VECTOR2, "value")));
};
void XRController3D::_bind_tracker() {
@@ -449,8 +450,8 @@ void XRController3D::_bind_tracker() {
// bind to input signals
tracker->connect("button_pressed", callable_mp(this, &XRController3D::_button_pressed));
tracker->connect("button_released", callable_mp(this, &XRController3D::_button_released));
- tracker->connect("input_value_changed", callable_mp(this, &XRController3D::_input_value_changed));
- tracker->connect("input_axis_changed", callable_mp(this, &XRController3D::_input_axis_changed));
+ tracker->connect("input_float_changed", callable_mp(this, &XRController3D::_input_float_changed));
+ tracker->connect("input_vector2_changed", callable_mp(this, &XRController3D::_input_vector2_changed));
}
}
@@ -459,8 +460,8 @@ void XRController3D::_unbind_tracker() {
// unbind input signals
tracker->disconnect("button_pressed", callable_mp(this, &XRController3D::_button_pressed));
tracker->disconnect("button_released", callable_mp(this, &XRController3D::_button_released));
- tracker->disconnect("input_value_changed", callable_mp(this, &XRController3D::_input_value_changed));
- tracker->disconnect("input_axis_changed", callable_mp(this, &XRController3D::_input_axis_changed));
+ tracker->disconnect("input_float_changed", callable_mp(this, &XRController3D::_input_float_changed));
+ tracker->disconnect("input_vector2_changed", callable_mp(this, &XRController3D::_input_vector2_changed));
}
XRNode3D::_unbind_tracker();
@@ -476,14 +477,14 @@ void XRController3D::_button_released(const String &p_name) {
emit_signal(SNAME("button_released"), p_name);
}
-void XRController3D::_input_value_changed(const String &p_name, float p_value) {
+void XRController3D::_input_float_changed(const String &p_name, float p_value) {
// just pass it on...
- emit_signal(SNAME("input_value_changed"), p_name, p_value);
+ emit_signal(SNAME("input_float_changed"), p_name, p_value);
}
-void XRController3D::_input_axis_changed(const String &p_name, Vector2 p_value) {
+void XRController3D::_input_vector2_changed(const String &p_name, Vector2 p_value) {
// just pass it on...
- emit_signal(SNAME("input_axis_changed"), p_name, p_value);
+ emit_signal(SNAME("input_vector2_changed"), p_name, p_value);
}
bool XRController3D::is_button_pressed(const StringName &p_name) const {
@@ -496,7 +497,15 @@ bool XRController3D::is_button_pressed(const StringName &p_name) const {
}
}
-float XRController3D::get_value(const StringName &p_name) const {
+Variant XRController3D::get_input(const StringName &p_name) const {
+ if (tracker.is_valid()) {
+ return tracker->get_input(p_name);
+ } else {
+ return Variant();
+ }
+}
+
+float XRController3D::get_float(const StringName &p_name) const {
if (tracker.is_valid()) {
// Inputs should already be of the correct type, our XR runtime handles conversions between raw input and the desired type, but just in case we convert
Variant input = tracker->get_input(p_name);
@@ -517,7 +526,7 @@ float XRController3D::get_value(const StringName &p_name) const {
}
}
-Vector2 XRController3D::get_axis(const StringName &p_name) const {
+Vector2 XRController3D::get_vector2(const StringName &p_name) const {
if (tracker.is_valid()) {
// Inputs should already be of the correct type, our XR runtime handles conversions between raw input and the desired type, but just in case we convert
Variant input = tracker->get_input(p_name);
diff --git a/scene/3d/xr_nodes.h b/scene/3d/xr_nodes.h
index c93cb14d62..6e56aa28de 100644
--- a/scene/3d/xr_nodes.h
+++ b/scene/3d/xr_nodes.h
@@ -131,13 +131,14 @@ protected:
void _button_pressed(const String &p_name);
void _button_released(const String &p_name);
- void _input_value_changed(const String &p_name, float p_value);
- void _input_axis_changed(const String &p_name, Vector2 p_value);
+ void _input_float_changed(const String &p_name, float p_value);
+ void _input_vector2_changed(const String &p_name, Vector2 p_value);
public:
bool is_button_pressed(const StringName &p_name) const;
- float get_value(const StringName &p_name) const;
- Vector2 get_axis(const StringName &p_name) const;
+ Variant get_input(const StringName &p_name) const;
+ float get_float(const StringName &p_name) const;
+ Vector2 get_vector2(const StringName &p_name) const;
XRPositionalTracker::TrackerHand get_tracker_hand() const;
diff --git a/scene/animation/animation_blend_space_1d.cpp b/scene/animation/animation_blend_space_1d.cpp
index a2028b8de8..0e9e02f247 100644
--- a/scene/animation/animation_blend_space_1d.cpp
+++ b/scene/animation/animation_blend_space_1d.cpp
@@ -30,12 +30,20 @@
#include "animation_blend_space_1d.h"
+#include "animation_blend_tree.h"
+
void AnimationNodeBlendSpace1D::get_parameter_list(List<PropertyInfo> *r_list) const {
r_list->push_back(PropertyInfo(Variant::FLOAT, blend_position));
+ r_list->push_back(PropertyInfo(Variant::INT, closest, PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NONE));
+ r_list->push_back(PropertyInfo(Variant::FLOAT, length_internal, PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NONE));
}
Variant AnimationNodeBlendSpace1D::get_parameter_default_value(const StringName &p_parameter) const {
- return 0;
+ if (p_parameter == closest) {
+ return -1;
+ } else {
+ return 0;
+ }
}
Ref<AnimationNode> AnimationNodeBlendSpace1D::get_child_by_name(const StringName &p_name) {
@@ -53,7 +61,15 @@ void AnimationNodeBlendSpace1D::_validate_property(PropertyInfo &p_property) con
}
void AnimationNodeBlendSpace1D::_tree_changed() {
- emit_signal(SNAME("tree_changed"));
+ AnimationRootNode::_tree_changed();
+}
+
+void AnimationNodeBlendSpace1D::_animation_node_renamed(const ObjectID &p_oid, const String &p_old_name, const String &p_new_name) {
+ AnimationRootNode::_animation_node_renamed(p_oid, p_old_name, p_new_name);
+}
+
+void AnimationNodeBlendSpace1D::_animation_node_removed(const ObjectID &p_oid, const StringName &p_node) {
+ AnimationRootNode::_animation_node_removed(p_oid, p_node);
}
void AnimationNodeBlendSpace1D::_bind_methods() {
@@ -77,6 +93,9 @@ void AnimationNodeBlendSpace1D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_value_label", "text"), &AnimationNodeBlendSpace1D::set_value_label);
ClassDB::bind_method(D_METHOD("get_value_label"), &AnimationNodeBlendSpace1D::get_value_label);
+ ClassDB::bind_method(D_METHOD("set_blend_mode", "mode"), &AnimationNodeBlendSpace1D::set_blend_mode);
+ ClassDB::bind_method(D_METHOD("get_blend_mode"), &AnimationNodeBlendSpace1D::get_blend_mode);
+
ClassDB::bind_method(D_METHOD("set_use_sync", "enable"), &AnimationNodeBlendSpace1D::set_use_sync);
ClassDB::bind_method(D_METHOD("is_using_sync"), &AnimationNodeBlendSpace1D::is_using_sync);
@@ -91,7 +110,12 @@ void AnimationNodeBlendSpace1D::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "max_space", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "set_max_space", "get_max_space");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "snap", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "set_snap", "get_snap");
ADD_PROPERTY(PropertyInfo(Variant::STRING, "value_label", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "set_value_label", "get_value_label");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "blend_mode", PROPERTY_HINT_ENUM, "Interpolated,Discrete,Carry", PROPERTY_USAGE_NO_EDITOR), "set_blend_mode", "get_blend_mode");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "sync", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "set_use_sync", "is_using_sync");
+
+ BIND_ENUM_CONSTANT(BLEND_MODE_INTERPOLATED);
+ BIND_ENUM_CONSTANT(BLEND_MODE_DISCRETE);
+ BIND_ENUM_CONSTANT(BLEND_MODE_DISCRETE_CARRY);
}
void AnimationNodeBlendSpace1D::get_child_nodes(List<ChildNode> *r_child_nodes) {
@@ -121,6 +145,8 @@ void AnimationNodeBlendSpace1D::add_blend_point(const Ref<AnimationRootNode> &p_
blend_points[p_at_index].position = p_position;
blend_points[p_at_index].node->connect("tree_changed", callable_mp(this, &AnimationNodeBlendSpace1D::_tree_changed), CONNECT_REFERENCE_COUNTED);
+ blend_points[p_at_index].node->connect("animation_node_renamed", callable_mp(this, &AnimationNodeBlendSpace1D::_animation_node_renamed), CONNECT_REFERENCE_COUNTED);
+ blend_points[p_at_index].node->connect("animation_node_removed", callable_mp(this, &AnimationNodeBlendSpace1D::_animation_node_removed), CONNECT_REFERENCE_COUNTED);
blend_points_used++;
emit_signal(SNAME("tree_changed"));
@@ -138,10 +164,14 @@ void AnimationNodeBlendSpace1D::set_blend_point_node(int p_point, const Ref<Anim
if (blend_points[p_point].node.is_valid()) {
blend_points[p_point].node->disconnect("tree_changed", callable_mp(this, &AnimationNodeBlendSpace1D::_tree_changed));
+ blend_points[p_point].node->disconnect("animation_node_renamed", callable_mp(this, &AnimationNodeBlendSpace1D::_animation_node_renamed));
+ blend_points[p_point].node->disconnect("animation_node_removed", callable_mp(this, &AnimationNodeBlendSpace1D::_animation_node_removed));
}
blend_points[p_point].node = p_node;
blend_points[p_point].node->connect("tree_changed", callable_mp(this, &AnimationNodeBlendSpace1D::_tree_changed), CONNECT_REFERENCE_COUNTED);
+ blend_points[p_point].node->connect("animation_node_renamed", callable_mp(this, &AnimationNodeBlendSpace1D::_animation_node_renamed), CONNECT_REFERENCE_COUNTED);
+ blend_points[p_point].node->connect("animation_node_removed", callable_mp(this, &AnimationNodeBlendSpace1D::_animation_node_removed), CONNECT_REFERENCE_COUNTED);
emit_signal(SNAME("tree_changed"));
}
@@ -161,12 +191,16 @@ void AnimationNodeBlendSpace1D::remove_blend_point(int p_point) {
ERR_FAIL_COND(blend_points[p_point].node.is_null());
blend_points[p_point].node->disconnect("tree_changed", callable_mp(this, &AnimationNodeBlendSpace1D::_tree_changed));
+ blend_points[p_point].node->disconnect("animation_node_renamed", callable_mp(this, &AnimationNodeBlendSpace1D::_animation_node_renamed));
+ blend_points[p_point].node->disconnect("animation_node_removed", callable_mp(this, &AnimationNodeBlendSpace1D::_animation_node_removed));
for (int i = p_point; i < blend_points_used - 1; i++) {
blend_points[i] = blend_points[i + 1];
}
blend_points_used--;
+
+ emit_signal(SNAME("animation_node_removed"), get_instance_id(), itos(p_point));
emit_signal(SNAME("tree_changed"));
}
@@ -214,6 +248,14 @@ String AnimationNodeBlendSpace1D::get_value_label() const {
return value_label;
}
+void AnimationNodeBlendSpace1D::set_blend_mode(BlendMode p_blend_mode) {
+ blend_mode = p_blend_mode;
+}
+
+AnimationNodeBlendSpace1D::BlendMode AnimationNodeBlendSpace1D::get_blend_mode() const {
+ return blend_mode;
+}
+
void AnimationNodeBlendSpace1D::set_use_sync(bool p_sync) {
sync = p_sync;
}
@@ -241,79 +283,125 @@ double AnimationNodeBlendSpace1D::process(double p_time, bool p_seek, bool p_is_
}
double blend_pos = get_parameter(blend_position);
+ int cur_closest = get_parameter(closest);
+ double cur_length_internal = get_parameter(length_internal);
+ double max_time_remaining = 0.0;
- float weights[MAX_BLEND_POINTS] = {};
+ if (blend_mode == BLEND_MODE_INTERPOLATED) {
+ float weights[MAX_BLEND_POINTS] = {};
+
+ int point_lower = -1;
+ float pos_lower = 0.0;
+ int point_higher = -1;
+ float pos_higher = 0.0;
+
+ // find the closest two points to blend between
+ for (int i = 0; i < blend_points_used; i++) {
+ float pos = blend_points[i].position;
+
+ if (pos <= blend_pos) {
+ if (point_lower == -1) {
+ point_lower = i;
+ pos_lower = pos;
+ } else if ((blend_pos - pos) < (blend_pos - pos_lower)) {
+ point_lower = i;
+ pos_lower = pos;
+ }
+ } else {
+ if (point_higher == -1) {
+ point_higher = i;
+ pos_higher = pos;
+ } else if ((pos - blend_pos) < (pos_higher - blend_pos)) {
+ point_higher = i;
+ pos_higher = pos;
+ }
+ }
+ }
- int point_lower = -1;
- float pos_lower = 0.0;
- int point_higher = -1;
- float pos_higher = 0.0;
+ // fill in weights
- // find the closest two points to blend between
- for (int i = 0; i < blend_points_used; i++) {
- float pos = blend_points[i].position;
-
- if (pos <= blend_pos) {
- if (point_lower == -1) {
- point_lower = i;
- pos_lower = pos;
- } else if ((blend_pos - pos) < (blend_pos - pos_lower)) {
- point_lower = i;
- pos_lower = pos;
- }
+ if (point_lower == -1 && point_higher != -1) {
+ // we are on the left side, no other point to the left
+ // we just play the next point.
+
+ weights[point_higher] = 1.0;
+ } else if (point_higher == -1) {
+ // we are on the right side, no other point to the right
+ // we just play the previous point
+
+ weights[point_lower] = 1.0;
} else {
- if (point_higher == -1) {
- point_higher = i;
- pos_higher = pos;
- } else if ((pos - blend_pos) < (pos_higher - blend_pos)) {
- point_higher = i;
- pos_higher = pos;
- }
- }
- }
+ // we are between two points.
+ // figure out weights, then blend the animations
- // fill in weights
+ float distance_between_points = pos_higher - pos_lower;
- if (point_lower == -1 && point_higher != -1) {
- // we are on the left side, no other point to the left
- // we just play the next point.
+ float current_pos_inbetween = blend_pos - pos_lower;
- weights[point_higher] = 1.0;
- } else if (point_higher == -1) {
- // we are on the right side, no other point to the right
- // we just play the previous point
+ float blend_percentage = current_pos_inbetween / distance_between_points;
- weights[point_lower] = 1.0;
- } else {
- // we are between two points.
- // figure out weights, then blend the animations
+ float blend_lower = 1.0 - blend_percentage;
+ float blend_higher = blend_percentage;
- float distance_between_points = pos_higher - pos_lower;
+ weights[point_lower] = blend_lower;
+ weights[point_higher] = blend_higher;
+ }
- float current_pos_inbetween = blend_pos - pos_lower;
+ // actually blend the animations now
- float blend_percentage = current_pos_inbetween / distance_between_points;
+ 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_is_external_seeking, weights[i], FILTER_IGNORE, true);
+ max_time_remaining = MAX(max_time_remaining, remaining);
+ } 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);
+ }
+ }
+ } else {
+ int new_closest = -1;
+ double new_closest_dist = 1e20;
+
+ for (int i = 0; i < blend_points_used; i++) {
+ double d = abs(blend_points[i].position - blend_pos);
+ if (d < new_closest_dist) {
+ new_closest = i;
+ new_closest_dist = d;
+ }
+ }
- float blend_lower = 1.0 - blend_percentage;
- float blend_higher = blend_percentage;
+ if (new_closest != cur_closest && new_closest != -1) {
+ double from = 0.0;
+ if (blend_mode == BLEND_MODE_DISCRETE_CARRY && cur_closest != -1) {
+ //for ping-pong loop
+ Ref<AnimationNodeAnimation> na_c = static_cast<Ref<AnimationNodeAnimation>>(blend_points[cur_closest].node);
+ Ref<AnimationNodeAnimation> na_n = static_cast<Ref<AnimationNodeAnimation>>(blend_points[new_closest].node);
+ if (!na_c.is_null() && !na_n.is_null()) {
+ 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_is_external_seeking, 0.0, FILTER_IGNORE, true);
+ }
- weights[point_lower] = blend_lower;
- weights[point_higher] = blend_higher;
- }
+ max_time_remaining = 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 + max_time_remaining;
- // actually blend the animations now
+ cur_closest = new_closest;
- double max_time_remaining = 0.0;
+ } else {
+ max_time_remaining = 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 == point_lower || i == point_higher) {
- 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 if (sync) {
- blend_node(blend_points[i].name, blend_points[i].node, p_time, p_seek, p_is_external_seeking, 0, FILTER_IGNORE, true);
+ 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);
+ }
+ }
}
}
+ set_parameter(this->closest, cur_closest);
+ set_parameter(this->length_internal, cur_length_internal);
return max_time_remaining;
}
diff --git a/scene/animation/animation_blend_space_1d.h b/scene/animation/animation_blend_space_1d.h
index af93783c0d..4007df0ded 100644
--- a/scene/animation/animation_blend_space_1d.h
+++ b/scene/animation/animation_blend_space_1d.h
@@ -36,6 +36,14 @@
class AnimationNodeBlendSpace1D : public AnimationRootNode {
GDCLASS(AnimationNodeBlendSpace1D, AnimationRootNode);
+public:
+ enum BlendMode {
+ BLEND_MODE_INTERPOLATED,
+ BLEND_MODE_DISCRETE,
+ BLEND_MODE_DISCRETE_CARRY,
+ };
+
+protected:
enum {
MAX_BLEND_POINTS = 64
};
@@ -58,16 +66,21 @@ class AnimationNodeBlendSpace1D : public AnimationRootNode {
void _add_blend_point(int p_index, const Ref<AnimationRootNode> &p_node);
- void _tree_changed();
-
StringName blend_position = "blend_position";
+ StringName closest = "closest";
+ StringName length_internal = "length_internal";
+
+ BlendMode blend_mode = BLEND_MODE_INTERPOLATED;
-protected:
bool sync = false;
void _validate_property(PropertyInfo &p_property) const;
static void _bind_methods();
+ virtual void _tree_changed() override;
+ virtual void _animation_node_renamed(const ObjectID &p_oid, const String &p_old_name, const String &p_new_name) override;
+ virtual void _animation_node_removed(const ObjectID &p_oid, const StringName &p_node) override;
+
public:
virtual void get_parameter_list(List<PropertyInfo> *r_list) const override;
virtual Variant get_parameter_default_value(const StringName &p_parameter) const override;
@@ -95,6 +108,9 @@ public:
void set_value_label(const String &p_label);
String get_value_label() const;
+ void set_blend_mode(BlendMode p_blend_mode);
+ BlendMode get_blend_mode() const;
+
void set_use_sync(bool p_sync);
bool is_using_sync() const;
@@ -107,4 +123,6 @@ public:
~AnimationNodeBlendSpace1D();
};
+VARIANT_ENUM_CAST(AnimationNodeBlendSpace1D::BlendMode)
+
#endif // ANIMATION_BLEND_SPACE_1D_H
diff --git a/scene/animation/animation_blend_space_2d.cpp b/scene/animation/animation_blend_space_2d.cpp
index c37d54961e..ae5b0d5779 100644
--- a/scene/animation/animation_blend_space_2d.cpp
+++ b/scene/animation/animation_blend_space_2d.cpp
@@ -81,6 +81,8 @@ void AnimationNodeBlendSpace2D::add_blend_point(const Ref<AnimationRootNode> &p_
blend_points[p_at_index].position = p_position;
blend_points[p_at_index].node->connect("tree_changed", callable_mp(this, &AnimationNodeBlendSpace2D::_tree_changed), CONNECT_REFERENCE_COUNTED);
+ blend_points[p_at_index].node->connect("animation_node_renamed", callable_mp(this, &AnimationNodeBlendSpace2D::_animation_node_renamed), CONNECT_REFERENCE_COUNTED);
+ blend_points[p_at_index].node->connect("animation_node_removed", callable_mp(this, &AnimationNodeBlendSpace2D::_animation_node_removed), CONNECT_REFERENCE_COUNTED);
blend_points_used++;
_queue_auto_triangles();
@@ -100,9 +102,13 @@ void AnimationNodeBlendSpace2D::set_blend_point_node(int p_point, const Ref<Anim
if (blend_points[p_point].node.is_valid()) {
blend_points[p_point].node->disconnect("tree_changed", callable_mp(this, &AnimationNodeBlendSpace2D::_tree_changed));
+ blend_points[p_point].node->disconnect("animation_node_renamed", callable_mp(this, &AnimationNodeBlendSpace2D::_animation_node_renamed));
+ blend_points[p_point].node->disconnect("animation_node_removed", callable_mp(this, &AnimationNodeBlendSpace2D::_animation_node_removed));
}
blend_points[p_point].node = p_node;
blend_points[p_point].node->connect("tree_changed", callable_mp(this, &AnimationNodeBlendSpace2D::_tree_changed), CONNECT_REFERENCE_COUNTED);
+ blend_points[p_point].node->connect("animation_node_renamed", callable_mp(this, &AnimationNodeBlendSpace2D::_animation_node_renamed), CONNECT_REFERENCE_COUNTED);
+ blend_points[p_point].node->connect("animation_node_removed", callable_mp(this, &AnimationNodeBlendSpace2D::_animation_node_removed), CONNECT_REFERENCE_COUNTED);
emit_signal(SNAME("tree_changed"));
}
@@ -122,6 +128,8 @@ void AnimationNodeBlendSpace2D::remove_blend_point(int p_point) {
ERR_FAIL_COND(blend_points[p_point].node.is_null());
blend_points[p_point].node->disconnect("tree_changed", callable_mp(this, &AnimationNodeBlendSpace2D::_tree_changed));
+ blend_points[p_point].node->disconnect("animation_node_renamed", callable_mp(this, &AnimationNodeBlendSpace2D::_animation_node_renamed));
+ blend_points[p_point].node->disconnect("animation_node_removed", callable_mp(this, &AnimationNodeBlendSpace2D::_animation_node_removed));
for (int i = 0; i < triangles.size(); i++) {
bool erase = false;
@@ -144,6 +152,8 @@ void AnimationNodeBlendSpace2D::remove_blend_point(int p_point) {
blend_points[i] = blend_points[i + 1];
}
blend_points_used--;
+
+ emit_signal(SNAME("animation_node_removed"), get_instance_id(), itos(p_point));
emit_signal(SNAME("tree_changed"));
}
@@ -598,10 +608,6 @@ Ref<AnimationNode> AnimationNodeBlendSpace2D::get_child_by_name(const StringName
return get_blend_point_node(p_name.operator String().to_int());
}
-void AnimationNodeBlendSpace2D::_tree_changed() {
- emit_signal(SNAME("tree_changed"));
-}
-
void AnimationNodeBlendSpace2D::set_blend_mode(BlendMode p_blend_mode) {
blend_mode = p_blend_mode;
}
@@ -618,6 +624,18 @@ bool AnimationNodeBlendSpace2D::is_using_sync() const {
return sync;
}
+void AnimationNodeBlendSpace2D::_tree_changed() {
+ AnimationRootNode::_tree_changed();
+}
+
+void AnimationNodeBlendSpace2D::_animation_node_renamed(const ObjectID &p_oid, const String &p_old_name, const String &p_new_name) {
+ AnimationRootNode::_animation_node_renamed(p_oid, p_old_name, p_new_name);
+}
+
+void AnimationNodeBlendSpace2D::_animation_node_removed(const ObjectID &p_oid, const StringName &p_node) {
+ AnimationRootNode::_animation_node_removed(p_oid, p_node);
+}
+
void AnimationNodeBlendSpace2D::_bind_methods() {
ClassDB::bind_method(D_METHOD("add_blend_point", "node", "pos", "at_index"), &AnimationNodeBlendSpace2D::add_blend_point, DEFVAL(-1));
ClassDB::bind_method(D_METHOD("set_blend_point_position", "point", "pos"), &AnimationNodeBlendSpace2D::set_blend_point_position);
diff --git a/scene/animation/animation_blend_space_2d.h b/scene/animation/animation_blend_space_2d.h
index 044c93d9f6..a770bf01ee 100644
--- a/scene/animation/animation_blend_space_2d.h
+++ b/scene/animation/animation_blend_space_2d.h
@@ -85,14 +85,15 @@ protected:
void _update_triangles();
void _queue_auto_triangles();
- void _tree_changed();
-
-protected:
bool sync = false;
void _validate_property(PropertyInfo &p_property) const;
static void _bind_methods();
+ virtual void _tree_changed() override;
+ virtual void _animation_node_renamed(const ObjectID &p_oid, const String &p_old_name, const String &p_new_name) override;
+ virtual void _animation_node_removed(const ObjectID &p_oid, const StringName &p_node) override;
+
public:
virtual void get_parameter_list(List<PropertyInfo> *r_list) const override;
virtual Variant get_parameter_default_value(const StringName &p_parameter) const override;
diff --git a/scene/animation/animation_blend_tree.cpp b/scene/animation/animation_blend_tree.cpp
index 1ef0774828..3567738366 100644
--- a/scene/animation/animation_blend_tree.cpp
+++ b/scene/animation/animation_blend_tree.cpp
@@ -229,15 +229,17 @@ AnimationNodeSync::AnimationNodeSync() {
////////////////////////////////////////////////////////
void AnimationNodeOneShot::get_parameter_list(List<PropertyInfo> *r_list) const {
- r_list->push_back(PropertyInfo(Variant::BOOL, active));
- r_list->push_back(PropertyInfo(Variant::BOOL, prev_active, PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NONE));
+ r_list->push_back(PropertyInfo(Variant::BOOL, active, PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_READ_ONLY));
+ r_list->push_back(PropertyInfo(Variant::INT, request, PROPERTY_HINT_ENUM, ",Fire,Abort"));
r_list->push_back(PropertyInfo(Variant::FLOAT, time, PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NONE));
r_list->push_back(PropertyInfo(Variant::FLOAT, remaining, PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NONE));
r_list->push_back(PropertyInfo(Variant::FLOAT, time_to_restart, PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NONE));
}
Variant AnimationNodeOneShot::get_parameter_default_value(const StringName &p_parameter) const {
- if (p_parameter == active || p_parameter == prev_active) {
+ if (p_parameter == request) {
+ return ONE_SHOT_REQUEST_NONE;
+ } else if (p_parameter == active) {
return false;
} else if (p_parameter == time_to_restart) {
return -1;
@@ -246,6 +248,13 @@ Variant AnimationNodeOneShot::get_parameter_default_value(const StringName &p_pa
}
}
+bool AnimationNodeOneShot::is_parameter_read_only(const StringName &p_parameter) const {
+ if (p_parameter == active) {
+ return true;
+ }
+ return false;
+}
+
void AnimationNodeOneShot::set_fadein_time(double p_time) {
fade_in = p_time;
}
@@ -303,50 +312,51 @@ bool AnimationNodeOneShot::has_filter() const {
}
double AnimationNodeOneShot::process(double p_time, bool p_seek, bool p_is_external_seeking) {
+ OneShotRequest cur_request = static_cast<OneShotRequest>((int)get_parameter(request));
bool cur_active = get_parameter(active);
- bool cur_prev_active = get_parameter(prev_active);
double cur_time = get_parameter(time);
double cur_remaining = get_parameter(remaining);
double cur_time_to_restart = get_parameter(time_to_restart);
- if (!cur_active) {
- //make it as if this node doesn't exist, pass input 0 by.
- if (cur_prev_active) {
- set_parameter(prev_active, false);
- }
+ set_parameter(request, ONE_SHOT_REQUEST_NONE);
+
+ bool do_start = cur_request == ONE_SHOT_REQUEST_FIRE;
+ if (cur_request == ONE_SHOT_REQUEST_ABORT) {
+ set_parameter(active, false);
+ set_parameter(time_to_restart, -1);
+ return blend_input(0, p_time, p_seek, p_is_external_seeking, 1.0, FILTER_IGNORE, sync);
+ } else if (!do_start && !cur_active) {
if (cur_time_to_restart >= 0.0 && !p_seek) {
cur_time_to_restart -= p_time;
if (cur_time_to_restart < 0) {
- //restart
- set_parameter(active, true);
- cur_active = true;
+ do_start = true; // Restart.
}
set_parameter(time_to_restart, cur_time_to_restart);
}
-
- return blend_input(0, p_time, p_seek, p_is_external_seeking, 1.0, FILTER_IGNORE, sync);
+ if (!do_start) {
+ return blend_input(0, p_time, p_seek, p_is_external_seeking, 1.0, FILTER_IGNORE, sync);
+ }
}
bool os_seek = p_seek;
-
if (p_seek) {
cur_time = p_time;
}
- bool do_start = !cur_prev_active;
if (do_start) {
cur_time = 0;
os_seek = true;
- set_parameter(prev_active, true);
+ set_parameter(request, ONE_SHOT_REQUEST_NONE);
+ set_parameter(active, true);
}
real_t blend;
-
+ bool use_fade_in = fade_in > 0;
if (cur_time < fade_in) {
- if (fade_in > 0) {
+ if (use_fade_in) {
blend = cur_time / fade_in;
} else {
- blend = 0;
+ blend = 0; // Should not happen.
}
} else if (!do_start && cur_remaining <= fade_out) {
if (fade_out > 0) {
@@ -358,10 +368,10 @@ double AnimationNodeOneShot::process(double p_time, bool p_seek, bool p_is_exter
blend = 1.0;
}
- double main_rem;
+ double main_rem = 0.0;
if (mix == MIX_MODE_ADD) {
main_rem = blend_input(0, p_time, p_seek, p_is_external_seeking, 1.0, FILTER_IGNORE, sync);
- } else {
+ } else if (use_fade_in) {
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_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.
@@ -375,7 +385,6 @@ double AnimationNodeOneShot::process(double p_time, bool p_seek, bool p_is_exter
cur_remaining = os_rem;
if (cur_remaining <= 0) {
set_parameter(active, false);
- set_parameter(prev_active, false);
if (autorestart) {
double restart_sec = autorestart_delay + Math::randd() * autorestart_random_delay;
set_parameter(time_to_restart, restart_sec);
@@ -419,6 +428,10 @@ void AnimationNodeOneShot::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "autorestart_delay", PROPERTY_HINT_RANGE, "0,60,0.01,or_greater,suffix:s"), "set_autorestart_delay", "get_autorestart_delay");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "autorestart_random_delay", PROPERTY_HINT_RANGE, "0,60,0.01,or_greater,suffix:s"), "set_autorestart_random_delay", "get_autorestart_random_delay");
+ BIND_ENUM_CONSTANT(ONE_SHOT_REQUEST_NONE);
+ BIND_ENUM_CONSTANT(ONE_SHOT_REQUEST_FIRE);
+ BIND_ENUM_CONSTANT(ONE_SHOT_REQUEST_ABORT);
+
BIND_ENUM_CONSTANT(MIX_MODE_BLEND);
BIND_ENUM_CONSTANT(MIX_MODE_ADD);
}
@@ -505,7 +518,7 @@ void AnimationNodeBlend2::get_parameter_list(List<PropertyInfo> *r_list) const {
}
Variant AnimationNodeBlend2::get_parameter_default_value(const StringName &p_parameter) const {
- return 0; //for blend amount
+ return 0; // For blend amount.
}
String AnimationNodeBlend2::get_caption() const {
@@ -518,7 +531,7 @@ double AnimationNodeBlend2::process(double p_time, bool p_seek, bool p_is_extern
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
+ return amount > 0.5 ? rem1 : rem0; // Hacky but good enough.
}
bool AnimationNodeBlend2::has_filter() const {
@@ -540,7 +553,7 @@ void AnimationNodeBlend3::get_parameter_list(List<PropertyInfo> *r_list) const {
}
Variant AnimationNodeBlend3::get_parameter_default_value(const StringName &p_parameter) const {
- return 0; //for blend amount
+ return 0; // For blend amount.
}
String AnimationNodeBlend3::get_caption() const {
@@ -553,7 +566,7 @@ double AnimationNodeBlend3::process(double p_time, bool p_seek, bool p_is_extern
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
+ return amount > 0.5 ? rem2 : (amount < -0.5 ? rem0 : rem1); // Hacky but good enough.
}
void AnimationNodeBlend3::_bind_methods() {
@@ -572,7 +585,7 @@ void AnimationNodeTimeScale::get_parameter_list(List<PropertyInfo> *r_list) cons
}
Variant AnimationNodeTimeScale::get_parameter_default_value(const StringName &p_parameter) const {
- return 1.0; //initial timescale
+ return 1.0; // Initial timescale.
}
String AnimationNodeTimeScale::get_caption() const {
@@ -598,24 +611,24 @@ AnimationNodeTimeScale::AnimationNodeTimeScale() {
////////////////////////////////////
void AnimationNodeTimeSeek::get_parameter_list(List<PropertyInfo> *r_list) const {
- r_list->push_back(PropertyInfo(Variant::FLOAT, seek_pos, PROPERTY_HINT_RANGE, "-1,3600,0.01,or_greater"));
+ r_list->push_back(PropertyInfo(Variant::FLOAT, seek_pos_request, PROPERTY_HINT_RANGE, "-1,3600,0.01,or_greater")); // It will be reset to -1 after seeking the position immediately.
}
Variant AnimationNodeTimeSeek::get_parameter_default_value(const StringName &p_parameter) const {
- return 1.0; //initial timescale
+ return -1.0; // Initial seek request.
}
String AnimationNodeTimeSeek::get_caption() const {
- return "Seek";
+ return "TimeSeek";
}
double AnimationNodeTimeSeek::process(double p_time, bool p_seek, bool p_is_external_seeking) {
- double cur_seek_pos = get_parameter(seek_pos);
+ double cur_seek_pos = get_parameter(seek_pos_request);
if (p_seek) {
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
+ set_parameter(seek_pos_request, -1.0); // Reset.
return ret;
} else {
return blend_input(0, p_time, false, p_is_external_seeking, 1.0, FILTER_IGNORE, true);
@@ -631,18 +644,76 @@ AnimationNodeTimeSeek::AnimationNodeTimeSeek() {
/////////////////////////////////////////////////
+bool AnimationNodeTransition::_set(const StringName &p_path, const Variant &p_value) {
+ String path = p_path;
+
+ if (!path.begins_with("input_")) {
+ return false;
+ }
+
+ int which = path.get_slicec('/', 0).get_slicec('_', 1).to_int();
+ String what = path.get_slicec('/', 1);
+
+ if (which == get_input_count() && what == "name") {
+ if (add_input(p_value)) {
+ return true;
+ }
+ return false;
+ }
+
+ ERR_FAIL_INDEX_V(which, get_input_count(), false);
+
+ if (what == "name") {
+ set_input_name(which, p_value);
+ } else if (what == "auto_advance") {
+ set_input_as_auto_advance(which, p_value);
+ } else if (what == "reset") {
+ set_input_reset(which, p_value);
+ } else {
+ return false;
+ }
+
+ return true;
+}
+
+bool AnimationNodeTransition::_get(const StringName &p_path, Variant &r_ret) const {
+ String path = p_path;
+
+ if (!path.begins_with("input_")) {
+ return false;
+ }
+
+ int which = path.get_slicec('/', 0).get_slicec('_', 1).to_int();
+ String what = path.get_slicec('/', 1);
+
+ ERR_FAIL_INDEX_V(which, get_input_count(), false);
+
+ if (what == "name") {
+ r_ret = get_input_name(which);
+ } else if (what == "auto_advance") {
+ r_ret = is_input_set_as_auto_advance(which);
+ } else if (what == "reset") {
+ r_ret = is_input_reset(which);
+ } else {
+ return false;
+ }
+
+ return true;
+}
+
void AnimationNodeTransition::get_parameter_list(List<PropertyInfo> *r_list) const {
String anims;
- for (int i = 0; i < enabled_inputs; i++) {
+ for (int i = 0; i < get_input_count(); i++) {
if (i > 0) {
anims += ",";
}
anims += inputs[i].name;
}
- r_list->push_back(PropertyInfo(Variant::INT, current, PROPERTY_HINT_ENUM, anims));
- r_list->push_back(PropertyInfo(Variant::INT, prev_current, PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NONE));
- r_list->push_back(PropertyInfo(Variant::INT, prev, PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NONE));
+ r_list->push_back(PropertyInfo(Variant::STRING, current_state, PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_READ_ONLY)); // For interface.
+ r_list->push_back(PropertyInfo(Variant::STRING, transition_request, PROPERTY_HINT_ENUM, anims)); // For transition request. It will be cleared after setting the value immediately.
+ r_list->push_back(PropertyInfo(Variant::INT, current_index, PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_READ_ONLY)); // To avoid finding the index every frame, use this internally.
+ r_list->push_back(PropertyInfo(Variant::INT, prev_index, PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NONE));
r_list->push_back(PropertyInfo(Variant::FLOAT, time, PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NONE));
r_list->push_back(PropertyInfo(Variant::FLOAT, prev_xfading, PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NONE));
}
@@ -650,56 +721,74 @@ void AnimationNodeTransition::get_parameter_list(List<PropertyInfo> *r_list) con
Variant AnimationNodeTransition::get_parameter_default_value(const StringName &p_parameter) const {
if (p_parameter == time || p_parameter == prev_xfading) {
return 0.0;
- } else if (p_parameter == prev || p_parameter == prev_current) {
+ } else if (p_parameter == prev_index || p_parameter == current_index) {
return -1;
} else {
- return 0;
+ return String();
}
}
+bool AnimationNodeTransition::is_parameter_read_only(const StringName &p_parameter) const {
+ if (p_parameter == current_state || p_parameter == current_index) {
+ return true;
+ }
+ return false;
+}
+
String AnimationNodeTransition::get_caption() const {
return "Transition";
}
-void AnimationNodeTransition::_update_inputs() {
- while (get_input_count() < enabled_inputs) {
- add_input(inputs[get_input_count()].name);
+void AnimationNodeTransition::set_input_count(int p_inputs) {
+ for (int i = get_input_count(); i < p_inputs; i++) {
+ add_input("state_" + itos(i));
}
-
- while (get_input_count() > enabled_inputs) {
+ while (get_input_count() > p_inputs) {
remove_input(get_input_count() - 1);
}
+
+ pending_update = true;
+
+ emit_signal(SNAME("tree_changed")); // For updating connect activity map.
+ notify_property_list_changed();
+}
+
+bool AnimationNodeTransition::add_input(const String &p_name) {
+ if (AnimationNode::add_input(p_name)) {
+ input_data.push_back(InputData());
+ return true;
+ }
+ return false;
}
-void AnimationNodeTransition::set_enabled_inputs(int p_inputs) {
- ERR_FAIL_INDEX(p_inputs, MAX_INPUTS);
- enabled_inputs = p_inputs;
- _update_inputs();
+void AnimationNodeTransition::remove_input(int p_index) {
+ input_data.remove_at(p_index);
+ AnimationNode::remove_input(p_index);
}
-int AnimationNodeTransition::get_enabled_inputs() {
- return enabled_inputs;
+bool AnimationNodeTransition::set_input_name(int p_input, const String &p_name) {
+ pending_update = true;
+ return AnimationNode::set_input_name(p_input, p_name);
}
void AnimationNodeTransition::set_input_as_auto_advance(int p_input, bool p_enable) {
- ERR_FAIL_INDEX(p_input, MAX_INPUTS);
- inputs[p_input].auto_advance = p_enable;
+ ERR_FAIL_INDEX(p_input, get_input_count());
+ input_data.write[p_input].auto_advance = p_enable;
}
bool AnimationNodeTransition::is_input_set_as_auto_advance(int p_input) const {
- ERR_FAIL_INDEX_V(p_input, MAX_INPUTS, false);
- return inputs[p_input].auto_advance;
+ ERR_FAIL_INDEX_V(p_input, get_input_count(), false);
+ return input_data[p_input].auto_advance;
}
-void AnimationNodeTransition::set_input_caption(int p_input, const String &p_name) {
- ERR_FAIL_INDEX(p_input, MAX_INPUTS);
- inputs[p_input].name = p_name;
- set_input_name(p_input, p_name);
+void AnimationNodeTransition::set_input_reset(int p_input, bool p_enable) {
+ ERR_FAIL_INDEX(p_input, get_input_count());
+ input_data.write[p_input].reset = p_enable;
}
-String AnimationNodeTransition::get_input_caption(int p_input) const {
- ERR_FAIL_INDEX_V(p_input, MAX_INPUTS, String());
- return inputs[p_input].name;
+bool AnimationNodeTransition::is_input_reset(int p_input) const {
+ ERR_FAIL_INDEX_V(p_input, get_input_count(), true);
+ return input_data[p_input].reset;
}
void AnimationNodeTransition::set_xfade_time(double p_fade) {
@@ -718,51 +807,96 @@ Ref<Curve> AnimationNodeTransition::get_xfade_curve() const {
return xfade_curve;
}
-void AnimationNodeTransition::set_from_start(bool p_from_start) {
- from_start = p_from_start;
+void AnimationNodeTransition::set_allow_transition_to_self(bool p_enable) {
+ allow_transition_to_self = p_enable;
}
-bool AnimationNodeTransition::is_from_start() const {
- return from_start;
+bool AnimationNodeTransition::is_allow_transition_to_self() const {
+ return allow_transition_to_self;
}
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);
+ String cur_transition_request = get_parameter(transition_request);
+ int cur_current_index = get_parameter(current_index);
+ int cur_prev_index = get_parameter(prev_index);
double cur_time = get_parameter(time);
double cur_prev_xfading = get_parameter(prev_xfading);
- bool switched = cur_current != cur_prev_current;
+ bool switched = false;
+ bool restart = false;
- if (switched) {
- set_parameter(prev_current, cur_current);
- set_parameter(prev, cur_prev_current);
+ if (pending_update) {
+ if (cur_current_index < 0 || cur_current_index >= get_input_count()) {
+ set_parameter(prev_index, -1);
+ if (get_input_count() > 0) {
+ set_parameter(current_index, 0);
+ set_parameter(current_state, get_input_name(0));
+ } else {
+ set_parameter(current_index, -1);
+ set_parameter(current_state, StringName());
+ }
+ } else {
+ set_parameter(current_state, get_input_name(cur_current_index));
+ }
+ pending_update = false;
+ }
- cur_prev = cur_prev_current;
+ if (!cur_transition_request.is_empty()) {
+ int new_idx = find_input(cur_transition_request);
+ if (new_idx >= 0) {
+ if (cur_current_index == new_idx) {
+ if (allow_transition_to_self) {
+ // Transition to same state.
+ restart = input_data[cur_current_index].reset;
+ cur_prev_xfading = 0;
+ set_parameter(prev_xfading, 0);
+ cur_prev_index = -1;
+ set_parameter(prev_index, -1);
+ }
+ } else {
+ switched = true;
+ cur_prev_index = cur_current_index;
+ set_parameter(prev_index, cur_current_index);
+ cur_current_index = new_idx;
+ set_parameter(current_index, cur_current_index);
+ set_parameter(current_state, cur_transition_request);
+ }
+ } else {
+ ERR_PRINT("No such input: '" + cur_transition_request + "'");
+ }
+ cur_transition_request = String();
+ set_parameter(transition_request, cur_transition_request);
+ }
+
+ // Special case for restart.
+ if (restart) {
+ set_parameter(time, 0);
+ return blend_input(cur_current_index, 0, true, p_is_external_seeking, 1.0, FILTER_IGNORE, true);
+ }
+
+ if (switched) {
cur_prev_xfading = xfade_time;
cur_time = 0;
- switched = true;
}
- if (cur_current < 0 || cur_current >= enabled_inputs || cur_prev >= enabled_inputs) {
+ if (cur_current_index < 0 || cur_current_index >= get_input_count() || cur_prev_index >= get_input_count()) {
return 0;
}
double rem = 0.0;
if (sync) {
- for (int i = 0; i < enabled_inputs; i++) {
- if (i != cur_current && i != cur_prev) {
+ for (int i = 0; i < get_input_count(); i++) {
+ if (i != cur_current_index && i != cur_prev_index) {
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
+ if (cur_prev_index < 0) { // Process current animation, check for transition.
- rem = blend_input(cur_current, p_time, p_seek, p_is_external_seeking, 1.0, FILTER_IGNORE, true);
+ rem = blend_input(cur_current_index, p_time, p_seek, p_is_external_seeking, 1.0, FILTER_IGNORE, true);
if (p_seek) {
cur_time = p_time;
@@ -770,34 +904,39 @@ double AnimationNodeTransition::process(double p_time, bool p_seek, bool p_is_ex
cur_time += p_time;
}
- if (inputs[cur_current].auto_advance && rem <= xfade_time) {
- set_parameter(current, (cur_current + 1) % enabled_inputs);
+ if (input_data[cur_current_index].auto_advance && rem <= xfade_time) {
+ set_parameter(transition_request, get_input_name((cur_current_index + 1) % get_input_count()));
}
- } else { // cross-fading from prev to current
+ } else { // Cross-fading from prev to current.
- real_t blend = xfade_time == 0 ? 0 : (cur_prev_xfading / xfade_time);
+ bool use_blend = xfade_time > 0;
+ real_t blend = !use_blend ? 0 : (cur_prev_xfading / xfade_time);
if (xfade_curve.is_valid()) {
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_is_external_seeking, Math::is_zero_approx(blend_inv) ? CMP_EPSILON : blend_inv, FILTER_IGNORE, true);
+ if (input_data[cur_current_index].reset && !p_seek && switched) { // Just switched, seek to start of current.
+ rem = blend_input(cur_current_index, 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_is_external_seeking, Math::is_zero_approx(blend_inv) ? CMP_EPSILON : blend_inv, FILTER_IGNORE, true);
+ rem = blend_input(cur_current_index, 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_is_external_seeking, Math::is_zero_approx(blend) ? CMP_EPSILON : blend, FILTER_IGNORE, true);
+ if (use_blend) {
+ blend_input(cur_prev_index, 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_is_external_seeking, Math::is_zero_approx(blend) ? CMP_EPSILON : blend, FILTER_IGNORE, true);
+ if (use_blend) {
+ blend_input(cur_prev_index, 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) {
- set_parameter(prev, -1);
+ set_parameter(prev_index, -1);
}
}
}
@@ -808,27 +947,22 @@ double AnimationNodeTransition::process(double p_time, bool p_seek, bool p_is_ex
return rem;
}
-void AnimationNodeTransition::_validate_property(PropertyInfo &p_property) const {
- if (p_property.name.begins_with("input_")) {
- String n = p_property.name.get_slicec('/', 0).get_slicec('_', 1);
- if (n != "count") {
- int idx = n.to_int();
- if (idx >= enabled_inputs) {
- p_property.usage = PROPERTY_USAGE_NONE;
- }
- }
+void AnimationNodeTransition::_get_property_list(List<PropertyInfo> *p_list) const {
+ for (int i = 0; i < get_input_count(); i++) {
+ p_list->push_back(PropertyInfo(Variant::STRING, "input_" + itos(i) + "/name", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_INTERNAL));
+ p_list->push_back(PropertyInfo(Variant::BOOL, "input_" + itos(i) + "/auto_advance", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_INTERNAL));
+ p_list->push_back(PropertyInfo(Variant::BOOL, "input_" + itos(i) + "/reset", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_INTERNAL));
}
}
void AnimationNodeTransition::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_enabled_inputs", "amount"), &AnimationNodeTransition::set_enabled_inputs);
- ClassDB::bind_method(D_METHOD("get_enabled_inputs"), &AnimationNodeTransition::get_enabled_inputs);
+ ClassDB::bind_method(D_METHOD("set_input_count", "input_count"), &AnimationNodeTransition::set_input_count);
ClassDB::bind_method(D_METHOD("set_input_as_auto_advance", "input", "enable"), &AnimationNodeTransition::set_input_as_auto_advance);
ClassDB::bind_method(D_METHOD("is_input_set_as_auto_advance", "input"), &AnimationNodeTransition::is_input_set_as_auto_advance);
- ClassDB::bind_method(D_METHOD("set_input_caption", "input", "caption"), &AnimationNodeTransition::set_input_caption);
- ClassDB::bind_method(D_METHOD("get_input_caption", "input"), &AnimationNodeTransition::get_input_caption);
+ ClassDB::bind_method(D_METHOD("set_input_reset", "input", "enable"), &AnimationNodeTransition::set_input_reset);
+ ClassDB::bind_method(D_METHOD("is_input_reset", "input"), &AnimationNodeTransition::is_input_reset);
ClassDB::bind_method(D_METHOD("set_xfade_time", "time"), &AnimationNodeTransition::set_xfade_time);
ClassDB::bind_method(D_METHOD("get_xfade_time"), &AnimationNodeTransition::get_xfade_time);
@@ -836,24 +970,16 @@ void AnimationNodeTransition::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_xfade_curve", "curve"), &AnimationNodeTransition::set_xfade_curve);
ClassDB::bind_method(D_METHOD("get_xfade_curve"), &AnimationNodeTransition::get_xfade_curve);
- ClassDB::bind_method(D_METHOD("set_from_start", "from_start"), &AnimationNodeTransition::set_from_start);
- ClassDB::bind_method(D_METHOD("is_from_start"), &AnimationNodeTransition::is_from_start);
+ ClassDB::bind_method(D_METHOD("set_allow_transition_to_self", "enable"), &AnimationNodeTransition::set_allow_transition_to_self);
+ ClassDB::bind_method(D_METHOD("is_allow_transition_to_self"), &AnimationNodeTransition::is_allow_transition_to_self);
- ADD_PROPERTY(PropertyInfo(Variant::INT, "enabled_inputs", PROPERTY_HINT_RANGE, "0,64,1", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), "set_enabled_inputs", "get_enabled_inputs");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "xfade_time", PROPERTY_HINT_RANGE, "0,120,0.01,suffix:s"), "set_xfade_time", "get_xfade_time");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "xfade_curve", PROPERTY_HINT_RESOURCE_TYPE, "Curve"), "set_xfade_curve", "get_xfade_curve");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL, "from_start"), "set_from_start", "is_from_start");
-
- for (int i = 0; i < MAX_INPUTS; i++) {
- ADD_PROPERTYI(PropertyInfo(Variant::STRING, "input_" + itos(i) + "/name", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_INTERNAL), "set_input_caption", "get_input_caption", i);
- ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "input_" + itos(i) + "/auto_advance", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_INTERNAL), "set_input_as_auto_advance", "is_input_set_as_auto_advance", i);
- }
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "allow_transition_to_self"), "set_allow_transition_to_self", "is_allow_transition_to_self");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "input_count", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_ARRAY | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED, "Inputs,input_"), "set_input_count", "get_input_count");
}
AnimationNodeTransition::AnimationNodeTransition() {
- for (int i = 0; i < MAX_INPUTS; i++) {
- inputs[i].name = "state " + itos(i);
- }
}
/////////////////////
@@ -887,6 +1013,8 @@ void AnimationNodeBlendTree::add_node(const StringName &p_name, Ref<AnimationNod
emit_signal(SNAME("tree_changed"));
p_node->connect("tree_changed", callable_mp(this, &AnimationNodeBlendTree::_tree_changed), CONNECT_REFERENCE_COUNTED);
+ p_node->connect("animation_node_renamed", callable_mp(this, &AnimationNodeBlendTree::_animation_node_renamed), CONNECT_REFERENCE_COUNTED);
+ p_node->connect("animation_node_removed", callable_mp(this, &AnimationNodeBlendTree::_animation_node_removed), CONNECT_REFERENCE_COUNTED);
p_node->connect("changed", callable_mp(this, &AnimationNodeBlendTree::_node_changed).bind(p_name), CONNECT_REFERENCE_COUNTED);
}
@@ -949,12 +1077,14 @@ void AnimationNodeBlendTree::remove_node(const StringName &p_name) {
{
Ref<AnimationNode> node = nodes[p_name].node;
node->disconnect("tree_changed", callable_mp(this, &AnimationNodeBlendTree::_tree_changed));
+ node->disconnect("animation_node_renamed", callable_mp(this, &AnimationNodeBlendTree::_animation_node_renamed));
+ node->disconnect("animation_node_removed", callable_mp(this, &AnimationNodeBlendTree::_animation_node_removed));
node->disconnect("changed", callable_mp(this, &AnimationNodeBlendTree::_node_changed));
}
nodes.erase(p_name);
- //erase connections to name
+ // Erase connections to name.
for (KeyValue<StringName, Node> &E : nodes) {
for (int i = 0; i < E.value.connections.size(); i++) {
if (E.value.connections[i] == p_name) {
@@ -963,6 +1093,7 @@ void AnimationNodeBlendTree::remove_node(const StringName &p_name) {
}
}
+ emit_signal(SNAME("animation_node_removed"), get_instance_id(), p_name);
emit_changed();
emit_signal(SNAME("tree_changed"));
}
@@ -978,7 +1109,7 @@ void AnimationNodeBlendTree::rename_node(const StringName &p_name, const StringN
nodes[p_new_name] = nodes[p_name];
nodes.erase(p_name);
- //rename connections
+ // Rename connections.
for (KeyValue<StringName, Node> &E : nodes) {
for (int i = 0; i < E.value.connections.size(); i++) {
if (E.value.connections[i] == p_name) {
@@ -986,9 +1117,10 @@ void AnimationNodeBlendTree::rename_node(const StringName &p_name, const StringN
}
}
}
- //connection must be done with new name
+ // Connection must be done with new name.
nodes[p_new_name].node->connect("changed", callable_mp(this, &AnimationNodeBlendTree::_node_changed).bind(p_new_name), CONNECT_REFERENCE_COUNTED);
+ emit_signal(SNAME("animation_node_renamed"), get_instance_id(), p_name, p_new_name);
emit_signal(SNAME("tree_changed"));
}
@@ -1189,6 +1321,18 @@ void AnimationNodeBlendTree::_get_property_list(List<PropertyInfo> *p_list) cons
p_list->push_back(PropertyInfo(Variant::ARRAY, "node_connections", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR));
}
+void AnimationNodeBlendTree::_tree_changed() {
+ AnimationRootNode::_tree_changed();
+}
+
+void AnimationNodeBlendTree::_animation_node_renamed(const ObjectID &p_oid, const String &p_old_name, const String &p_new_name) {
+ AnimationRootNode::_animation_node_renamed(p_oid, p_old_name, p_new_name);
+}
+
+void AnimationNodeBlendTree::_animation_node_removed(const ObjectID &p_oid, const StringName &p_node) {
+ AnimationRootNode::_animation_node_removed(p_oid, p_node);
+}
+
void AnimationNodeBlendTree::reset_state() {
graph_offset = Vector2();
nodes.clear();
@@ -1197,10 +1341,6 @@ void AnimationNodeBlendTree::reset_state() {
emit_signal(SNAME("tree_changed"));
}
-void AnimationNodeBlendTree::_tree_changed() {
- emit_signal(SNAME("tree_changed"));
-}
-
void AnimationNodeBlendTree::_node_changed(const StringName &p_node) {
ERR_FAIL_COND(!nodes.has(p_node));
nodes[p_node].connections.resize(nodes[p_node].node->get_input_count());
diff --git a/scene/animation/animation_blend_tree.h b/scene/animation/animation_blend_tree.h
index e72471202e..d4827180bb 100644
--- a/scene/animation/animation_blend_tree.h
+++ b/scene/animation/animation_blend_tree.h
@@ -96,6 +96,12 @@ class AnimationNodeOneShot : public AnimationNodeSync {
GDCLASS(AnimationNodeOneShot, AnimationNodeSync);
public:
+ enum OneShotRequest {
+ ONE_SHOT_REQUEST_NONE,
+ ONE_SHOT_REQUEST_FIRE,
+ ONE_SHOT_REQUEST_ABORT,
+ };
+
enum MixMode {
MIX_MODE_BLEND,
MIX_MODE_ADD
@@ -110,13 +116,8 @@ private:
double autorestart_random_delay = 0.0;
MixMode mix = MIX_MODE_BLEND;
- /* bool active;
- bool do_start;
- double time;
- double remaining;*/
-
+ StringName request = PNAME("request");
StringName active = PNAME("active");
- StringName prev_active = "prev_active";
StringName time = "time";
StringName remaining = "remaining";
StringName time_to_restart = "time_to_restart";
@@ -127,6 +128,7 @@ protected:
public:
virtual void get_parameter_list(List<PropertyInfo> *r_list) const override;
virtual Variant get_parameter_default_value(const StringName &p_parameter) const override;
+ virtual bool is_parameter_read_only(const StringName &p_parameter) const override;
virtual String get_caption() const override;
@@ -153,6 +155,7 @@ public:
AnimationNodeOneShot();
};
+VARIANT_ENUM_CAST(AnimationNodeOneShot::OneShotRequest)
VARIANT_ENUM_CAST(AnimationNodeOneShot::MixMode)
class AnimationNodeAdd2 : public AnimationNodeSync {
@@ -254,7 +257,7 @@ public:
class AnimationNodeTimeSeek : public AnimationNode {
GDCLASS(AnimationNodeTimeSeek, AnimationNode);
- StringName seek_pos = PNAME("seek_position");
+ StringName seek_pos_request = PNAME("seek_request");
protected:
static void _bind_methods();
@@ -273,54 +276,52 @@ public:
class AnimationNodeTransition : public AnimationNodeSync {
GDCLASS(AnimationNodeTransition, AnimationNodeSync);
- enum {
- MAX_INPUTS = 32
- };
struct InputData {
- String name;
bool auto_advance = false;
+ bool reset = true;
};
+ Vector<InputData> input_data;
- InputData inputs[MAX_INPUTS];
- int enabled_inputs = 0;
-
- /*
- double prev_xfading;
- int prev;
- double time;
- int current;
- int prev_current; */
-
- StringName prev_xfading = "prev_xfading";
- StringName prev = "prev";
StringName time = "time";
- StringName current = PNAME("current");
- StringName prev_current = "prev_current";
+ StringName prev_xfading = "prev_xfading";
+ StringName prev_index = "prev_index";
+ StringName current_index = PNAME("current_index");
+ StringName current_state = PNAME("current_state");
+ StringName transition_request = PNAME("transition_request");
+
+ StringName prev_frame_current = "pf_current";
+ StringName prev_frame_current_idx = "pf_current_idx";
double xfade_time = 0.0;
Ref<Curve> xfade_curve;
- bool from_start = true;
+ bool allow_transition_to_self = false;
- void _update_inputs();
+ bool pending_update = false;
protected:
+ bool _get(const StringName &p_path, Variant &r_ret) const;
+ bool _set(const StringName &p_path, const Variant &p_value);
static void _bind_methods();
- void _validate_property(PropertyInfo &p_property) const;
+ void _get_property_list(List<PropertyInfo> *p_list) const;
public:
virtual void get_parameter_list(List<PropertyInfo> *r_list) const override;
virtual Variant get_parameter_default_value(const StringName &p_parameter) const override;
+ virtual bool is_parameter_read_only(const StringName &p_parameter) const override;
virtual String get_caption() const override;
- void set_enabled_inputs(int p_inputs);
- int get_enabled_inputs();
+ void set_input_count(int p_inputs);
+
+ virtual bool add_input(const String &p_name) override;
+ virtual void remove_input(int p_index) override;
+ virtual bool set_input_name(int p_input, const String &p_name) override;
void set_input_as_auto_advance(int p_input, bool p_enable);
bool is_input_set_as_auto_advance(int p_input) const;
- void set_input_caption(int p_input, const String &p_name);
- String get_input_caption(int p_input) const;
+ void set_input_reset(int p_input, bool p_enable);
+ bool is_input_reset(int p_input) const;
void set_xfade_time(double p_fade);
double get_xfade_time() const;
@@ -328,8 +329,8 @@ public:
void set_xfade_curve(const Ref<Curve> &p_curve);
Ref<Curve> get_xfade_curve() const;
- void set_from_start(bool p_from_start);
- bool is_from_start() const;
+ void set_allow_transition_to_self(bool p_enable);
+ bool is_allow_transition_to_self() const;
double process(double p_time, bool p_seek, bool p_is_external_seeking) override;
@@ -360,7 +361,6 @@ class AnimationNodeBlendTree : public AnimationRootNode {
Vector2 graph_offset;
- void _tree_changed();
void _node_changed(const StringName &p_node);
void _initialize_node_tree();
@@ -371,6 +371,10 @@ protected:
bool _get(const StringName &p_name, Variant &r_ret) const;
void _get_property_list(List<PropertyInfo> *p_list) const;
+ virtual void _tree_changed() override;
+ virtual void _animation_node_renamed(const ObjectID &p_oid, const String &p_old_name, const String &p_new_name) override;
+ virtual void _animation_node_removed(const ObjectID &p_oid, const StringName &p_node) override;
+
virtual void reset_state() override;
public:
diff --git a/scene/animation/animation_node_state_machine.cpp b/scene/animation/animation_node_state_machine.cpp
index f5df64dbdd..d19d3cc7a3 100644
--- a/scene/animation/animation_node_state_machine.cpp
+++ b/scene/animation/animation_node_state_machine.cpp
@@ -107,6 +107,15 @@ Ref<Curve> AnimationNodeStateMachineTransition::get_xfade_curve() const {
return xfade_curve;
}
+void AnimationNodeStateMachineTransition::set_reset(bool p_reset) {
+ reset = p_reset;
+ emit_changed();
+}
+
+bool AnimationNodeStateMachineTransition::is_reset() const {
+ return reset;
+}
+
void AnimationNodeStateMachineTransition::set_priority(int p_priority) {
priority = p_priority;
emit_changed();
@@ -132,6 +141,9 @@ 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_reset", "reset"), &AnimationNodeStateMachineTransition::set_reset);
+ ClassDB::bind_method(D_METHOD("is_reset"), &AnimationNodeStateMachineTransition::is_reset);
+
ClassDB::bind_method(D_METHOD("set_priority", "priority"), &AnimationNodeStateMachineTransition::set_priority);
ClassDB::bind_method(D_METHOD("get_priority"), &AnimationNodeStateMachineTransition::get_priority);
@@ -140,6 +152,9 @@ void AnimationNodeStateMachineTransition::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "xfade_time", PROPERTY_HINT_RANGE, "0,240,0.01,suffix:s"), "set_xfade_time", "get_xfade_time");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "xfade_curve", PROPERTY_HINT_RESOURCE_TYPE, "Curve"), "set_xfade_curve", "get_xfade_curve");
+
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "reset"), "set_reset", "is_reset");
+
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");
@@ -164,18 +179,27 @@ AnimationNodeStateMachineTransition::AnimationNodeStateMachineTransition() {
////////////////////////////////////////////////////////
-void AnimationNodeStateMachinePlayback::travel(const StringName &p_state) {
- start_request_travel = true;
- start_request = p_state;
+void AnimationNodeStateMachinePlayback::travel(const StringName &p_state, bool p_reset_on_teleport) {
+ travel_request = p_state;
+ reset_request_on_teleport = p_reset_on_teleport;
stop_request = false;
}
-void AnimationNodeStateMachinePlayback::start(const StringName &p_state) {
- start_request_travel = false;
+void AnimationNodeStateMachinePlayback::start(const StringName &p_state, bool p_reset) {
+ travel_request = StringName();
+ reset_request = p_reset;
+ _start(p_state);
+}
+
+void AnimationNodeStateMachinePlayback::_start(const StringName &p_state) {
start_request = p_state;
stop_request = false;
}
+void AnimationNodeStateMachinePlayback::next() {
+ next_request = true;
+}
+
void AnimationNodeStateMachinePlayback::stop() {
stop_request = true;
}
@@ -188,7 +212,7 @@ StringName AnimationNodeStateMachinePlayback::get_current_node() const {
return current;
}
-StringName AnimationNodeStateMachinePlayback::get_blend_from_node() const {
+StringName AnimationNodeStateMachinePlayback::get_fading_from_node() const {
return fading_from;
}
@@ -204,6 +228,22 @@ float AnimationNodeStateMachinePlayback::get_current_length() const {
return len_current;
}
+float AnimationNodeStateMachinePlayback::get_fade_from_play_pos() const {
+ return pos_fade_from;
+}
+
+float AnimationNodeStateMachinePlayback::get_fade_from_length() const {
+ return len_fade_from;
+}
+
+float AnimationNodeStateMachinePlayback::get_fading_time() const {
+ return fading_time;
+}
+
+float AnimationNodeStateMachinePlayback::get_fading_pos() const {
+ return fading_pos;
+}
+
bool AnimationNodeStateMachinePlayback::_travel(AnimationNodeStateMachine *p_state_machine, const StringName &p_travel) {
ERR_FAIL_COND_V(!playing, false);
ERR_FAIL_COND_V(!p_state_machine->states.has(p_travel), false);
@@ -212,7 +252,7 @@ bool AnimationNodeStateMachinePlayback::_travel(AnimationNodeStateMachine *p_sta
path.clear(); //a new one will be needed
if (current == p_travel) {
- return true; //nothing to do
+ return !p_state_machine->is_allow_transition_to_self();
}
Vector2 current_pos = p_state_machine->states[current].position;
@@ -323,6 +363,15 @@ bool AnimationNodeStateMachinePlayback::_travel(AnimationNodeStateMachine *p_sta
}
double AnimationNodeStateMachinePlayback::process(AnimationNodeStateMachine *p_state_machine, double p_time, bool p_seek, bool p_is_external_seeking) {
+ double rem = _process(p_state_machine, p_time, p_seek, p_is_external_seeking);
+ start_request = StringName();
+ next_request = false;
+ stop_request = false;
+ reset_request_on_teleport = false;
+ return rem;
+}
+
+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()) {
@@ -335,14 +384,13 @@ double AnimationNodeStateMachinePlayback::process(AnimationNodeStateMachine *p_s
//if not playing and it can restart, then restart
if (!playing && start_request == StringName()) {
if (!stop_request && p_state_machine->start_node) {
- start(p_state_machine->start_node);
+ _start(p_state_machine->start_node);
} else {
return 0;
}
}
if (playing && stop_request) {
- stop_request = false;
playing = false;
return 0;
}
@@ -350,42 +398,47 @@ double AnimationNodeStateMachinePlayback::process(AnimationNodeStateMachine *p_s
bool play_start = false;
if (start_request != StringName()) {
- if (start_request_travel) {
- if (!playing) {
- if (!stop_request && p_state_machine->start_node) {
- // can restart, just postpone traveling
- path.clear();
- current = p_state_machine->start_node;
- playing = true;
- play_start = true;
- } else {
- // stopped, invalid state
- String node_name = start_request;
- start_request = StringName(); //clear start request
- ERR_FAIL_V_MSG(0, "Can't travel to '" + node_name + "' if state machine is not playing. Maybe you need to enable Autoplay on Load for one of the nodes in your state machine or call .start() first?");
- }
- } else {
- if (!_travel(p_state_machine, start_request)) {
- // can't travel, then teleport
- path.clear();
- current = start_request;
- play_start = true;
- }
- start_request = StringName(); //clear start request
- }
+ // teleport to start
+ if (p_state_machine->states.has(start_request)) {
+ path.clear();
+ current = start_request;
+ playing = true;
+ play_start = true;
} else {
- // teleport to start
- if (p_state_machine->states.has(start_request)) {
+ StringName node = start_request;
+ ERR_FAIL_V_MSG(0, "No such node: '" + node + "'");
+ }
+ } else if (travel_request != StringName()) {
+ if (!playing) {
+ if (!stop_request && p_state_machine->start_node) {
+ // can restart, just postpone traveling
path.clear();
- current = start_request;
+ current = p_state_machine->start_node;
playing = true;
play_start = true;
- start_request = StringName(); //clear start request
} else {
- StringName node = start_request;
- start_request = StringName(); //clear start request
- ERR_FAIL_V_MSG(0, "No such node: '" + node + "'");
+ // stopped, invalid state
+ String node_name = travel_request;
+ travel_request = StringName();
+ ERR_FAIL_V_MSG(0, "Can't travel to '" + node_name + "' if state machine is not playing. Maybe you need to enable Autoplay on Load for one of the nodes in your state machine or call .start() first?");
+ }
+ } else {
+ if (!_travel(p_state_machine, travel_request)) {
+ // can't travel, then teleport
+ if (p_state_machine->states.has(travel_request)) {
+ path.clear();
+ if (current != travel_request || reset_request_on_teleport) {
+ current = travel_request;
+ play_start = true;
+ reset_request = reset_request_on_teleport;
+ }
+ } else {
+ StringName node = travel_request;
+ travel_request = StringName();
+ ERR_FAIL_V_MSG(0, "No such node: '" + node + "'");
+ }
}
+ travel_request = StringName();
}
}
@@ -396,8 +449,11 @@ 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_is_external_seeking, 1.0, AnimationNode::FILTER_IGNORE, true);
- pos_current = 0;
+ if (reset_request) {
+ 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;
+ reset_request = false;
+ }
}
if (!p_state_machine->states.has(current)) {
@@ -421,11 +477,22 @@ double AnimationNodeStateMachinePlayback::process(AnimationNodeStateMachine *p_s
if (current_curve.is_valid()) {
fade_blend = current_curve->sample(fade_blend);
}
- 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 rem = do_start ? len_current : 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.
if (fading_from != StringName()) {
double fade_blend_inv = 1.0 - fade_blend;
- 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.
+ float fading_from_rem = 0.0;
+ fading_from_rem = 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
+ if (fading_from_rem > len_fade_from) { // weird but ok
+ len_fade_from = fading_from_rem;
+ }
+
+ { //advance and loop check
+ float next_pos = len_fade_from - fading_from_rem;
+ pos_fade_from = next_pos; //looped
+ }
if (fade_blend >= 1.0) {
fading_from = StringName();
}
@@ -457,6 +524,7 @@ double AnimationNodeStateMachinePlayback::process(AnimationNodeStateMachine *p_s
next_xfade = p_state_machine->transitions[i].transition->get_xfade_time();
current_curve = p_state_machine->transitions[i].transition->get_xfade_curve();
switch_mode = p_state_machine->transitions[i].transition->get_switch_mode();
+ reset_request = p_state_machine->transitions[i].transition->is_reset();
next = path[0];
}
}
@@ -513,6 +581,7 @@ double AnimationNodeStateMachinePlayback::process(AnimationNodeStateMachine *p_s
current_curve = p_state_machine->transitions[auto_advance_to].transition->get_xfade_curve();
next_xfade = p_state_machine->transitions[auto_advance_to].transition->get_xfade_time();
switch_mode = p_state_machine->transitions[auto_advance_to].transition->get_switch_mode();
+ reset_request = p_state_machine->transitions[auto_advance_to].transition->is_reset();
}
}
@@ -567,7 +636,7 @@ double AnimationNodeStateMachinePlayback::process(AnimationNodeStateMachine *p_s
goto_next = fading_from == StringName();
}
- if (goto_next) { //end_loop should be used because fade time may be too small or zero and animation may have looped
+ if (next_request || goto_next) { //end_loop should be used because fade time may be too small or zero and animation may have looped
if (next_xfade) {
//time to fade, baby
fading_from = current;
@@ -590,8 +659,12 @@ double AnimationNodeStateMachinePlayback::process(AnimationNodeStateMachine *p_s
}
current = next;
+ pos_fade_from = pos_current;
+ len_fade_from = len_current;
- 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 (reset_request) {
+ 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) {
pos_current = MIN(pos_current, len_current);
p_state_machine->blend_node(current, p_state_machine->states[current].node, pos_current, true, p_is_external_seeking, 0, AnimationNode::FILTER_IGNORE, true);
@@ -652,13 +725,15 @@ bool AnimationNodeStateMachinePlayback::_check_advance_condition(const Ref<Anima
}
void AnimationNodeStateMachinePlayback::_bind_methods() {
- ClassDB::bind_method(D_METHOD("travel", "to_node"), &AnimationNodeStateMachinePlayback::travel);
- ClassDB::bind_method(D_METHOD("start", "node"), &AnimationNodeStateMachinePlayback::start);
+ ClassDB::bind_method(D_METHOD("travel", "to_node", "reset_on_teleport"), &AnimationNodeStateMachinePlayback::travel, DEFVAL(true));
+ ClassDB::bind_method(D_METHOD("start", "node", "reset"), &AnimationNodeStateMachinePlayback::start, DEFVAL(true));
+ ClassDB::bind_method(D_METHOD("next"), &AnimationNodeStateMachinePlayback::next);
ClassDB::bind_method(D_METHOD("stop"), &AnimationNodeStateMachinePlayback::stop);
ClassDB::bind_method(D_METHOD("is_playing"), &AnimationNodeStateMachinePlayback::is_playing);
ClassDB::bind_method(D_METHOD("get_current_node"), &AnimationNodeStateMachinePlayback::get_current_node);
ClassDB::bind_method(D_METHOD("get_current_play_position"), &AnimationNodeStateMachinePlayback::get_current_play_pos);
ClassDB::bind_method(D_METHOD("get_current_length"), &AnimationNodeStateMachinePlayback::get_current_length);
+ ClassDB::bind_method(D_METHOD("get_fading_from_node"), &AnimationNodeStateMachinePlayback::get_fading_from_node);
ClassDB::bind_method(D_METHOD("get_travel_path"), &AnimationNodeStateMachinePlayback::get_travel_path);
}
@@ -669,7 +744,7 @@ AnimationNodeStateMachinePlayback::AnimationNodeStateMachinePlayback() {
///////////////////////////////////////////////////////
void AnimationNodeStateMachine::get_parameter_list(List<PropertyInfo> *r_list) const {
- r_list->push_back(PropertyInfo(Variant::OBJECT, playback, PROPERTY_HINT_RESOURCE_TYPE, "AnimationNodeStateMachinePlayback", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_DO_NOT_SHARE_ON_DUPLICATE));
+ r_list->push_back(PropertyInfo(Variant::OBJECT, playback, PROPERTY_HINT_RESOURCE_TYPE, "AnimationNodeStateMachinePlayback", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_ALWAYS_DUPLICATE));
List<StringName> advance_conditions;
for (int i = 0; i < transitions.size(); i++) {
StringName ac = transitions[i].transition->get_advance_condition_name();
@@ -716,6 +791,8 @@ void AnimationNodeStateMachine::add_node(const StringName &p_name, Ref<Animation
emit_signal(SNAME("tree_changed"));
p_node->connect("tree_changed", callable_mp(this, &AnimationNodeStateMachine::_tree_changed), CONNECT_REFERENCE_COUNTED);
+ p_node->connect("animation_node_renamed", callable_mp(this, &AnimationNodeStateMachine::_animation_node_renamed), CONNECT_REFERENCE_COUNTED);
+ p_node->connect("animation_node_removed", callable_mp(this, &AnimationNodeStateMachine::_animation_node_removed), CONNECT_REFERENCE_COUNTED);
}
void AnimationNodeStateMachine::replace_node(const StringName &p_name, Ref<AnimationNode> p_node) {
@@ -727,6 +804,8 @@ void AnimationNodeStateMachine::replace_node(const StringName &p_name, Ref<Anima
Ref<AnimationNode> node = states[p_name].node;
if (node.is_valid()) {
node->disconnect("tree_changed", callable_mp(this, &AnimationNodeStateMachine::_tree_changed));
+ node->disconnect("animation_node_renamed", callable_mp(this, &AnimationNodeStateMachine::_animation_node_renamed));
+ node->disconnect("animation_node_removed", callable_mp(this, &AnimationNodeStateMachine::_animation_node_removed));
}
}
@@ -736,6 +815,16 @@ void AnimationNodeStateMachine::replace_node(const StringName &p_name, Ref<Anima
emit_signal(SNAME("tree_changed"));
p_node->connect("tree_changed", callable_mp(this, &AnimationNodeStateMachine::_tree_changed), CONNECT_REFERENCE_COUNTED);
+ p_node->connect("animation_node_renamed", callable_mp(this, &AnimationNodeStateMachine::_animation_node_renamed), CONNECT_REFERENCE_COUNTED);
+ p_node->connect("animation_node_removed", callable_mp(this, &AnimationNodeStateMachine::_animation_node_removed), CONNECT_REFERENCE_COUNTED);
+}
+
+void AnimationNodeStateMachine::set_allow_transition_to_self(bool p_enable) {
+ allow_transition_to_self = p_enable;
+}
+
+bool AnimationNodeStateMachine::is_allow_transition_to_self() const {
+ return allow_transition_to_self;
}
bool AnimationNodeStateMachine::can_edit_node(const StringName &p_name) const {
@@ -801,10 +890,13 @@ void AnimationNodeStateMachine::remove_node(const StringName &p_name) {
Ref<AnimationNode> node = states[p_name].node;
ERR_FAIL_COND(node.is_null());
node->disconnect("tree_changed", callable_mp(this, &AnimationNodeStateMachine::_tree_changed));
+ node->disconnect("animation_node_renamed", callable_mp(this, &AnimationNodeStateMachine::_animation_node_renamed));
+ node->disconnect("animation_node_removed", callable_mp(this, &AnimationNodeStateMachine::_animation_node_removed));
}
states.erase(p_name);
+ emit_signal(SNAME("animation_node_removed"), get_instance_id(), p_name);
emit_changed();
emit_signal(SNAME("tree_changed"));
}
@@ -824,6 +916,7 @@ void AnimationNodeStateMachine::rename_node(const StringName &p_name, const Stri
_rename_transitions(p_name, p_new_name);
+ emit_signal(SNAME("animation_node_renamed"), get_instance_id(), p_name, p_new_name);
emit_changed();
emit_signal(SNAME("tree_changed"));
}
@@ -1282,7 +1375,15 @@ Vector2 AnimationNodeStateMachine::get_node_position(const StringName &p_name) c
void AnimationNodeStateMachine::_tree_changed() {
emit_changed();
- emit_signal(SNAME("tree_changed"));
+ AnimationRootNode::_tree_changed();
+}
+
+void AnimationNodeStateMachine::_animation_node_renamed(const ObjectID &p_oid, const String &p_old_name, const String &p_new_name) {
+ AnimationRootNode::_animation_node_renamed(p_oid, p_old_name, p_new_name);
+}
+
+void AnimationNodeStateMachine::_animation_node_removed(const ObjectID &p_oid, const StringName &p_node) {
+ AnimationRootNode::_animation_node_removed(p_oid, p_node);
}
void AnimationNodeStateMachine::_bind_methods() {
@@ -1308,6 +1409,11 @@ void AnimationNodeStateMachine::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_graph_offset", "offset"), &AnimationNodeStateMachine::set_graph_offset);
ClassDB::bind_method(D_METHOD("get_graph_offset"), &AnimationNodeStateMachine::get_graph_offset);
+
+ ClassDB::bind_method(D_METHOD("set_allow_transition_to_self", "enable"), &AnimationNodeStateMachine::set_allow_transition_to_self);
+ ClassDB::bind_method(D_METHOD("is_allow_transition_to_self"), &AnimationNodeStateMachine::is_allow_transition_to_self);
+
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "allow_transition_to_self"), "set_allow_transition_to_self", "is_allow_transition_to_self");
}
AnimationNodeStateMachine::AnimationNodeStateMachine() {
diff --git a/scene/animation/animation_node_state_machine.h b/scene/animation/animation_node_state_machine.h
index 116589eb2f..5867b6c65a 100644
--- a/scene/animation/animation_node_state_machine.h
+++ b/scene/animation/animation_node_state_machine.h
@@ -57,6 +57,7 @@ private:
StringName advance_condition_name;
float xfade_time = 0.0;
Ref<Curve> xfade_curve;
+ bool reset = true;
int priority = 1;
String advance_expression;
@@ -84,6 +85,9 @@ public:
void set_xfade_time(float p_xfade);
float get_xfade_time() const;
+ void set_reset(bool p_reset);
+ bool is_reset() const;
+
void set_xfade_curve(const Ref<Curve> &p_curve);
Ref<Curve> get_xfade_curve() const;
@@ -114,6 +118,9 @@ class AnimationNodeStateMachinePlayback : public Resource {
StringName next;
};
+ double len_fade_from = 0.0;
+ double pos_fade_from = 0.0;
+
double len_current = 0.0;
double pos_current = 0.0;
bool end_loop = false;
@@ -131,10 +138,15 @@ class AnimationNodeStateMachinePlayback : public Resource {
bool playing = false;
StringName start_request;
- bool start_request_travel = false;
+ StringName travel_request;
+ bool reset_request = false;
+ bool reset_request_on_teleport = false;
+ bool next_request = false;
bool stop_request = false;
bool _travel(AnimationNodeStateMachine *p_state_machine, const StringName &p_travel);
+ void _start(const StringName &p_state);
+ double _process(AnimationNodeStateMachine *p_state_machine, double p_time, bool p_seek, bool p_is_external_seeking);
double process(AnimationNodeStateMachine *p_state_machine, double p_time, bool p_seek, bool p_is_external_seeking);
@@ -144,16 +156,23 @@ protected:
static void _bind_methods();
public:
- void travel(const StringName &p_state);
- void start(const StringName &p_state);
+ void travel(const StringName &p_state, bool p_reset_on_teleport = true);
+ void start(const StringName &p_state, bool p_reset = true);
+ void next();
void stop();
bool is_playing() const;
StringName get_current_node() const;
- StringName get_blend_from_node() const;
+ StringName get_fading_from_node() const;
Vector<StringName> get_travel_path() const;
float get_current_play_pos() const;
float get_current_length() const;
+ float get_fade_from_play_pos() const;
+ float get_fade_from_length() const;
+
+ float get_fading_time() const;
+ float get_fading_pos() const;
+
AnimationNodeStateMachinePlayback();
};
@@ -169,6 +188,7 @@ private:
};
HashMap<StringName, State> states;
+ bool allow_transition_to_self = false;
struct Transition {
StringName from;
@@ -187,7 +207,6 @@ private:
Vector2 graph_offset;
- void _tree_changed();
void _remove_transition(const Ref<AnimationNodeStateMachineTransition> p_transition);
void _rename_transitions(const StringName &p_name, const StringName &p_new_name);
bool _can_connect(const StringName &p_name, Vector<AnimationNodeStateMachine *> p_parents = Vector<AnimationNodeStateMachine *>());
@@ -201,6 +220,10 @@ protected:
void _get_property_list(List<PropertyInfo> *p_list) const;
bool _check_advance_condition(const Ref<AnimationNodeStateMachine> p_state_machine, const Ref<AnimationNodeStateMachineTransition> p_transition) const;
+ virtual void _tree_changed() override;
+ virtual void _animation_node_renamed(const ObjectID &p_oid, const String &p_old_name, const String &p_new_name) override;
+ virtual void _animation_node_removed(const ObjectID &p_oid, const StringName &p_node) override;
+
virtual void reset_state() override;
public:
@@ -235,6 +258,9 @@ public:
void remove_transition_by_index(const int p_transition);
void remove_transition(const StringName &p_from, const StringName &p_to);
+ void set_allow_transition_to_self(bool p_enable);
+ bool is_allow_transition_to_self() const;
+
bool can_edit_node(const StringName &p_name) const;
AnimationNodeStateMachine *get_prev_state_machine() const;
diff --git a/scene/animation/animation_player.cpp b/scene/animation/animation_player.cpp
index 7f42c8fac3..fc3a3d306f 100644
--- a/scene/animation/animation_player.cpp
+++ b/scene/animation/animation_player.cpp
@@ -143,8 +143,8 @@ bool AnimationPlayer::_get(const StringName &p_name, Variant &r_ret) const {
} else if (name.begins_with("libraries")) {
Dictionary d;
- for (uint32_t i = 0; i < animation_libraries.size(); i++) {
- d[animation_libraries[i].name] = animation_libraries[i].library;
+ for (const AnimationLibraryData &lib : animation_libraries) {
+ d[lib.name] = lib.library;
}
r_ret = d;
@@ -199,7 +199,7 @@ void AnimationPlayer::_validate_property(PropertyInfo &p_property) const {
void AnimationPlayer::_get_property_list(List<PropertyInfo> *p_list) const {
List<PropertyInfo> anim_names;
- anim_names.push_back(PropertyInfo(Variant::DICTIONARY, "libraries"));
+ anim_names.push_back(PropertyInfo(Variant::DICTIONARY, PNAME("libraries")));
for (const KeyValue<StringName, AnimationData> &E : animation_set) {
if (E.value.next != StringName()) {
@@ -431,6 +431,17 @@ void AnimationPlayer::_ensure_node_caches(AnimationData *p_anim, Node *p_root_ov
}
}
+ if (a->track_get_type(i) == Animation::TYPE_AUDIO) {
+ if (!node_cache->audio_anim.has(a->track_get_path(i).get_concatenated_names())) {
+ TrackNodeCache::AudioAnim aa;
+ aa.object = (Object *)child;
+ aa.audio_stream.instantiate();
+ aa.audio_stream->set_polyphony(audio_max_polyphony);
+
+ node_cache->audio_anim[a->track_get_path(i).get_concatenated_names()] = aa;
+ }
+ }
+
node_cache->last_setup_pass = setup_pass;
}
}
@@ -451,6 +462,15 @@ static void _call_object(Object *p_object, const StringName &p_method, const Vec
}
}
+Variant AnimationPlayer::post_process_key_value(const Ref<Animation> &p_anim, int p_track, Variant p_value, const Object *p_object, int p_object_idx) {
+ Variant res;
+ if (GDVIRTUAL_CALL(_post_process_key_value, p_anim, p_track, p_value, const_cast<Object *>(p_object), p_object_idx, res)) {
+ return res;
+ }
+
+ return _post_process_key_value(p_anim, p_track, p_value, p_object, p_object_idx);
+}
+
Variant AnimationPlayer::_post_process_key_value(const Ref<Animation> &p_anim, int p_track, Variant p_value, const Object *p_object, int p_object_idx) {
switch (p_anim->track_get_type(p_track)) {
#ifndef _3D_DISABLED
@@ -473,7 +493,9 @@ void AnimationPlayer::_animation_process_animation(AnimationData *p_anim, double
ERR_FAIL_COND(p_anim->node_cache.size() != p_anim->animation->get_track_count());
Animation *a = p_anim->animation.operator->();
+#ifdef TOOLS_ENABLED
bool can_call = is_inside_tree() && !Engine::get_singleton()->is_editor_hint();
+#endif // TOOLS_ENABLED
bool backward = signbit(p_delta);
for (int i = 0; i < a->get_track_count(); i++) {
@@ -512,7 +534,7 @@ void AnimationPlayer::_animation_process_animation(AnimationData *p_anim, double
if (err != OK) {
continue;
}
- loc = _post_process_key_value(a, i, loc, nc->node_3d, nc->bone_idx);
+ loc = post_process_key_value(a, i, loc, nc->node_3d, nc->bone_idx);
if (nc->accum_pass != accum_pass) {
ERR_CONTINUE(cache_update_size >= NODE_CACHE_UPDATE_MAX);
@@ -540,7 +562,7 @@ void AnimationPlayer::_animation_process_animation(AnimationData *p_anim, double
if (err != OK) {
continue;
}
- rot = _post_process_key_value(a, i, rot, nc->node_3d, nc->bone_idx);
+ rot = post_process_key_value(a, i, rot, nc->node_3d, nc->bone_idx);
if (nc->accum_pass != accum_pass) {
ERR_CONTINUE(cache_update_size >= NODE_CACHE_UPDATE_MAX);
@@ -568,7 +590,7 @@ void AnimationPlayer::_animation_process_animation(AnimationData *p_anim, double
if (err != OK) {
continue;
}
- scale = _post_process_key_value(a, i, scale, nc->node_3d, nc->bone_idx);
+ scale = post_process_key_value(a, i, scale, nc->node_3d, nc->bone_idx);
if (nc->accum_pass != accum_pass) {
ERR_CONTINUE(cache_update_size >= NODE_CACHE_UPDATE_MAX);
@@ -596,7 +618,7 @@ void AnimationPlayer::_animation_process_animation(AnimationData *p_anim, double
if (err != OK) {
continue;
}
- blend = _post_process_key_value(a, i, blend, nc->node_blend_shape, nc->blend_shape_idx);
+ blend = post_process_key_value(a, i, blend, nc->node_blend_shape, nc->blend_shape_idx);
if (nc->accum_pass != accum_pass) {
ERR_CONTINUE(cache_update_size >= NODE_CACHE_UPDATE_MAX);
@@ -649,7 +671,7 @@ void AnimationPlayer::_animation_process_animation(AnimationData *p_anim, double
if (p_time < first_key_time) {
double c = Math::ease(p_time / first_key_time, transition);
Variant first_value = a->track_get_key_value(i, first_key);
- first_value = _post_process_key_value(a, i, first_value, nc->node);
+ first_value = post_process_key_value(a, i, first_value, nc->node);
Variant interp_value = Animation::interpolate_variant(pa->capture, first_value, c);
if (pa->accum_pass != accum_pass) {
ERR_CONTINUE(cache_update_prop_size >= NODE_CACHE_UPDATE_MAX);
@@ -670,7 +692,7 @@ void AnimationPlayer::_animation_process_animation(AnimationData *p_anim, double
if (value == Variant()) {
continue;
}
- value = _post_process_key_value(a, i, value, nc->node);
+ value = post_process_key_value(a, i, value, nc->node);
if (pa->accum_pass != accum_pass) {
ERR_CONTINUE(cache_update_prop_size >= NODE_CACHE_UPDATE_MAX);
@@ -701,7 +723,7 @@ void AnimationPlayer::_animation_process_animation(AnimationData *p_anim, double
for (int &F : indices) {
Variant value = a->track_get_key_value(i, F);
- value = _post_process_key_value(a, i, value, nc->node);
+ value = post_process_key_value(a, i, value, nc->node);
switch (pa->special) {
case SP_NONE: {
bool valid;
@@ -745,11 +767,13 @@ void AnimationPlayer::_animation_process_animation(AnimationData *p_anim, double
} break;
case Animation::TYPE_METHOD: {
- if (!nc->node) {
+#ifdef TOOLS_ENABLED
+ if (!can_call) {
continue;
}
- if (!p_is_current) {
- break;
+#endif // TOOLS_ENABLED
+ if (!p_is_current || !nc->node || is_stopping) {
+ continue;
}
List<int> indices;
@@ -772,16 +796,12 @@ void AnimationPlayer::_animation_process_animation(AnimationData *p_anim, double
for (int &E : indices) {
StringName method = a->method_track_get_name(i, E);
Vector<Variant> params = a->method_track_get_params(i, E);
-
#ifdef DEBUG_ENABLED
if (!nc->node->has_method(method)) {
ERR_PRINT("Invalid method call '" + method + "'. '" + a->get_name() + "' at node '" + get_path() + "'.");
}
#endif
-
- if (can_call) {
- _call_object(nc->node, method, params, method_call_mode == ANIMATION_METHOD_CALL_DEFERRED);
- }
+ _call_object(nc->node, method, params, method_call_mode == ANIMATION_METHOD_CALL_DEFERRED);
}
} break;
@@ -796,7 +816,7 @@ void AnimationPlayer::_animation_process_animation(AnimationData *p_anim, double
TrackNodeCache::BezierAnim *ba = &E->value;
real_t bezier = a->bezier_track_interpolate(i, p_time);
- bezier = _post_process_key_value(a, i, bezier, nc->node);
+ bezier = post_process_key_value(a, i, bezier, nc->node);
if (ba->accum_pass != accum_pass) {
ERR_CONTINUE(cache_update_bezier_size >= NODE_CACHE_UPDATE_MAX);
cache_update_bezier[cache_update_bezier_size++] = ba;
@@ -808,113 +828,100 @@ void AnimationPlayer::_animation_process_animation(AnimationData *p_anim, double
} break;
case Animation::TYPE_AUDIO: {
- if (!nc->node) {
+ if (!nc->node || is_stopping) {
continue;
}
+#ifdef TOOLS_ENABLED
+ if (p_seeked && !can_call) {
+ continue; // To avoid spamming the preview in editor.
+ }
+#endif // TOOLS_ENABLED
+ HashMap<StringName, TrackNodeCache::AudioAnim>::Iterator E = nc->audio_anim.find(a->track_get_path(i).get_concatenated_names());
+ ERR_CONTINUE(!E); //should it continue, or create a new one?
- if (p_seeked) {
- //find whatever should be playing
- int idx = a->track_find_key(i, p_time);
- if (idx < 0) {
- continue;
- }
-
- Ref<AudioStream> stream = a->audio_track_get_key_stream(i, idx);
- if (!stream.is_valid()) {
- nc->node->call(SNAME("stop"));
- nc->audio_playing = false;
- playing_caches.erase(nc);
- } else {
- float start_ofs = a->audio_track_get_key_start_offset(i, idx);
- start_ofs += p_time - a->track_get_key_time(i, idx);
- float end_ofs = a->audio_track_get_key_end_offset(i, idx);
- float len = stream->get_length();
-
- if (start_ofs > len - end_ofs) {
- nc->node->call(SNAME("stop"));
- nc->audio_playing = false;
- playing_caches.erase(nc);
- continue;
- }
-
- nc->node->call(SNAME("set_stream"), stream);
- nc->node->call(SNAME("play"), start_ofs);
-
- nc->audio_playing = true;
- playing_caches.insert(nc);
- if (len && end_ofs > 0) { //force an end at a time
- nc->audio_len = len - start_ofs - end_ofs;
- } else {
- nc->audio_len = 0;
- }
+ TrackNodeCache::AudioAnim *aa = &E->value;
+ Node *asp = Object::cast_to<Node>(aa->object);
+ if (!asp) {
+ continue;
+ }
+ aa->length = a->get_length();
+ aa->time = p_time;
+ aa->loop = a->get_loop_mode() != Animation::LOOP_NONE;
+ aa->backward = backward;
+ if (aa->accum_pass != accum_pass) {
+ ERR_CONTINUE(cache_update_audio_size >= NODE_CACHE_UPDATE_MAX);
+ cache_update_audio[cache_update_audio_size++] = aa;
+ aa->accum_pass = accum_pass;
+ }
- nc->audio_start = p_time;
+ HashMap<int, TrackNodeCache::PlayingAudioStreamInfo> &map = aa->playing_streams;
+ // Find stream.
+ int idx = -1;
+ if (p_seeked || p_started) {
+ idx = a->track_find_key(i, p_time);
+ // Discard previous stream when seeking.
+ if (map.has(idx)) {
+ aa->audio_stream_playback->stop_stream(map[idx].index);
+ map.erase(idx);
}
-
} else {
- //find stuff to play
List<int> to_play;
- 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();
-
- Ref<AudioStream> stream = a->audio_track_get_key_stream(i, idx);
- if (!stream.is_valid()) {
- nc->node->call(SNAME("stop"));
- nc->audio_playing = false;
- playing_caches.erase(nc);
- } else {
- float start_ofs = a->audio_track_get_key_start_offset(i, idx);
- float end_ofs = a->audio_track_get_key_end_offset(i, idx);
- float len = stream->get_length();
-
- nc->node->call(SNAME("set_stream"), stream);
- nc->node->call(SNAME("play"), start_ofs);
-
- nc->audio_playing = true;
- playing_caches.insert(nc);
- if (len && end_ofs > 0) { //force an end at a time
- nc->audio_len = len - start_ofs - end_ofs;
- } else {
- nc->audio_len = 0;
- }
-
- nc->audio_start = p_time;
- }
- } else if (nc->audio_playing) {
- bool loop = a->get_loop_mode() != Animation::LOOP_NONE;
+ idx = to_play.back()->get();
+ }
+ }
+ if (idx < 0) {
+ continue;
+ }
- bool stop = false;
+ // Play stream.
+ Ref<AudioStream> stream = a->audio_track_get_key_stream(i, idx);
+ if (stream.is_valid()) {
+ double start_ofs = a->audio_track_get_key_start_offset(i, idx);
+ double end_ofs = a->audio_track_get_key_end_offset(i, idx);
+ double len = stream->get_length();
- if (!loop) {
- if ((p_time < nc->audio_start && !backward) || (p_time > nc->audio_start && backward)) {
- stop = true;
- }
- } else if (nc->audio_len > 0) {
- float len = nc->audio_start > p_time ? (a->get_length() - nc->audio_start) + p_time : p_time - nc->audio_start;
+ if (p_seeked || p_started) {
+ start_ofs += p_time - a->track_get_key_time(i, idx);
+ }
- if (len > nc->audio_len) {
- stop = true;
- }
+ if (aa->object->call(SNAME("get_stream")) != aa->audio_stream) {
+ aa->object->call(SNAME("set_stream"), aa->audio_stream);
+ aa->audio_stream_playback.unref();
+ if (!playing_audio_stream_players.has(asp)) {
+ playing_audio_stream_players.push_back(asp);
}
+ }
+ if (!aa->object->call(SNAME("is_playing"))) {
+ aa->object->call(SNAME("play"));
+ }
+ if (!aa->object->call(SNAME("has_stream_playback"))) {
+ aa->audio_stream_playback.unref();
+ continue;
+ }
+ if (aa->audio_stream_playback.is_null()) {
+ aa->audio_stream_playback = aa->object->call(SNAME("get_stream_playback"));
+ }
- if (stop) {
- //time to stop
- nc->node->call(SNAME("stop"));
- nc->audio_playing = false;
- playing_caches.erase(nc);
- }
+ TrackNodeCache::PlayingAudioStreamInfo pasi;
+ pasi.index = aa->audio_stream_playback->play_stream(stream, start_ofs);
+ pasi.start = p_time;
+ if (len && end_ofs > 0) { // Force an end at a time.
+ pasi.len = len - start_ofs - end_ofs;
+ } else {
+ pasi.len = 0;
}
+ map[idx] = pasi;
}
} break;
case Animation::TYPE_ANIMATION: {
+ if (is_stopping) {
+ continue;
+ }
+
AnimationPlayer *player = Object::cast_to<AnimationPlayer>(nc->node);
if (!player) {
continue;
@@ -1206,6 +1213,53 @@ void AnimationPlayer::_animation_update_transforms() {
ERR_CONTINUE(ba->accum_pass != accum_pass);
ba->object->set_indexed(ba->bezier_property, ba->bezier_accum);
}
+
+ for (int i = 0; i < cache_update_audio_size; i++) {
+ TrackNodeCache::AudioAnim *aa = cache_update_audio[i];
+
+ ERR_CONTINUE(aa->accum_pass != accum_pass);
+
+ // Audio ending process.
+ LocalVector<int> erase_list;
+ for (const KeyValue<int, TrackNodeCache::PlayingAudioStreamInfo> &K : aa->playing_streams) {
+ TrackNodeCache::PlayingAudioStreamInfo pasi = K.value;
+
+ bool stop = false;
+ if (!aa->audio_stream_playback->is_stream_playing(pasi.index)) {
+ stop = true;
+ }
+ if (!aa->loop) {
+ if (!aa->backward) {
+ if (aa->time < pasi.start) {
+ stop = true;
+ }
+ } else {
+ if (aa->time > pasi.start) {
+ stop = true;
+ }
+ }
+ }
+ if (pasi.len > 0) {
+ double len = 0.0;
+ if (!aa->backward) {
+ len = pasi.start > aa->time ? (aa->length - pasi.start) + aa->time : aa->time - pasi.start;
+ } else {
+ len = pasi.start < aa->time ? (aa->length - aa->time) + pasi.start : pasi.start - aa->time;
+ }
+ if (len > pasi.len) {
+ stop = true;
+ }
+ }
+ if (stop) {
+ // Time to stop.
+ aa->audio_stream_playback->stop_stream(pasi.index);
+ erase_list.push_back(K.key);
+ }
+ }
+ for (uint32_t erase_idx = 0; erase_idx < erase_list.size(); erase_idx++) {
+ aa->playing_streams.erase(erase_list[erase_idx]);
+ }
+ }
}
void AnimationPlayer::_animation_process(double p_delta) {
@@ -1221,6 +1275,7 @@ void AnimationPlayer::_animation_process(double p_delta) {
cache_update_size = 0;
cache_update_prop_size = 0;
cache_update_bezier_size = 0;
+ cache_update_audio_size = 0;
AnimationData *prev_from = playback.current.from;
_animation_process2(p_delta, started);
@@ -1230,6 +1285,8 @@ void AnimationPlayer::_animation_process(double p_delta) {
_animation_update_transforms();
if (end_reached) {
+ _clear_audio_streams();
+ _stop_playing_caches(false);
if (queued.size()) {
String old = playback.assigned;
play(queued.front()->get());
@@ -1265,13 +1322,13 @@ void AnimationPlayer::_animation_set_cache_update() {
bool clear_cache_needed = false;
// Update changed and add otherwise
- for (uint32_t i = 0; i < animation_libraries.size(); i++) {
- for (const KeyValue<StringName, Ref<Animation>> &K : animation_libraries[i].library->animations) {
- StringName key = animation_libraries[i].name == StringName() ? K.key : StringName(String(animation_libraries[i].name) + "/" + String(K.key));
+ for (const AnimationLibraryData &lib : animation_libraries) {
+ for (const KeyValue<StringName, Ref<Animation>> &K : lib.library->animations) {
+ StringName key = lib.name == StringName() ? K.key : StringName(String(lib.name) + "/" + String(K.key));
if (!animation_set.has(key)) {
AnimationData ad;
ad.animation = K.value;
- ad.animation_library = animation_libraries[i].name;
+ ad.animation_library = lib.name;
ad.name = key;
ad.last_update = animation_set_update_pass;
animation_set.insert(ad.name, ad);
@@ -1279,11 +1336,11 @@ void AnimationPlayer::_animation_set_cache_update() {
AnimationData &ad = animation_set[key];
if (ad.last_update != animation_set_update_pass) {
// Was not updated, update. If the animation is duplicated, the second one will be ignored.
- if (ad.animation != K.value || ad.animation_library != animation_libraries[i].name) {
+ if (ad.animation != K.value || ad.animation_library != lib.name) {
// Animation changed, update and clear caches.
clear_cache_needed = true;
ad.animation = K.value;
- ad.animation_library = animation_libraries[i].name;
+ ad.animation_library = lib.name;
}
ad.last_update = animation_set_update_pass;
@@ -1401,11 +1458,11 @@ Error AnimationPlayer::add_animation_library(const StringName &p_name, const Ref
int insert_pos = 0;
- for (uint32_t i = 0; i < animation_libraries.size(); i++) {
- ERR_FAIL_COND_V_MSG(animation_libraries[i].name == p_name, ERR_ALREADY_EXISTS, "Can't add animation library twice with name: " + String(p_name));
- ERR_FAIL_COND_V_MSG(animation_libraries[i].library == p_animation_library, ERR_ALREADY_EXISTS, "Can't add animation library twice (adding as '" + p_name.operator String() + "', exists as '" + animation_libraries[i].name.operator String() + "'.");
+ for (const AnimationLibraryData &lib : animation_libraries) {
+ ERR_FAIL_COND_V_MSG(lib.name == p_name, ERR_ALREADY_EXISTS, "Can't add animation library twice with name: " + String(p_name));
+ ERR_FAIL_COND_V_MSG(lib.library == p_animation_library, ERR_ALREADY_EXISTS, "Can't add animation library twice (adding as '" + p_name.operator String() + "', exists as '" + lib.name.operator String() + "'.");
- if (animation_libraries[i].name.operator String() >= p_name.operator String()) {
+ if (lib.name.operator String() >= p_name.operator String()) {
break;
}
@@ -1464,21 +1521,21 @@ void AnimationPlayer::rename_animation_library(const StringName &p_name, const S
#endif
bool found = false;
- for (uint32_t i = 0; i < animation_libraries.size(); i++) {
- ERR_FAIL_COND_MSG(animation_libraries[i].name == p_new_name, "Can't rename animation library to another existing name: " + String(p_new_name));
- if (animation_libraries[i].name == p_name) {
+ for (AnimationLibraryData &lib : animation_libraries) {
+ ERR_FAIL_COND_MSG(lib.name == p_new_name, "Can't rename animation library to another existing name: " + String(p_new_name));
+ if (lib.name == p_name) {
found = true;
- animation_libraries[i].name = p_new_name;
+ lib.name = p_new_name;
// rename connections
- animation_libraries[i].library->disconnect(SNAME("animation_added"), callable_mp(this, &AnimationPlayer::_animation_added));
- animation_libraries[i].library->disconnect(SNAME("animation_removed"), callable_mp(this, &AnimationPlayer::_animation_removed));
- animation_libraries[i].library->disconnect(SNAME("animation_renamed"), callable_mp(this, &AnimationPlayer::_animation_renamed));
+ lib.library->disconnect(SNAME("animation_added"), callable_mp(this, &AnimationPlayer::_animation_added));
+ lib.library->disconnect(SNAME("animation_removed"), callable_mp(this, &AnimationPlayer::_animation_removed));
+ lib.library->disconnect(SNAME("animation_renamed"), callable_mp(this, &AnimationPlayer::_animation_renamed));
- animation_libraries[i].library->connect(SNAME("animation_added"), callable_mp(this, &AnimationPlayer::_animation_added).bind(p_new_name));
- animation_libraries[i].library->connect(SNAME("animation_removed"), callable_mp(this, &AnimationPlayer::_animation_removed).bind(p_new_name));
- animation_libraries[i].library->connect(SNAME("animation_renamed"), callable_mp(this, &AnimationPlayer::_animation_renamed).bind(p_new_name));
+ lib.library->connect(SNAME("animation_added"), callable_mp(this, &AnimationPlayer::_animation_added).bind(p_new_name));
+ lib.library->connect(SNAME("animation_removed"), callable_mp(this, &AnimationPlayer::_animation_removed).bind(p_new_name));
+ lib.library->connect(SNAME("animation_renamed"), callable_mp(this, &AnimationPlayer::_animation_renamed).bind(p_new_name));
- for (const KeyValue<StringName, Ref<Animation>> &K : animation_libraries[i].library->animations) {
+ for (const KeyValue<StringName, Ref<Animation>> &K : lib.library->animations) {
StringName old_name = p_name == StringName() ? K.key : StringName(String(p_name) + "/" + String(K.key));
StringName new_name = p_new_name == StringName() ? K.key : StringName(String(p_new_name) + "/" + String(K.key));
_rename_animation(old_name, new_name);
@@ -1498,8 +1555,8 @@ void AnimationPlayer::rename_animation_library(const StringName &p_name, const S
}
bool AnimationPlayer::has_animation_library(const StringName &p_name) const {
- for (uint32_t i = 0; i < animation_libraries.size(); i++) {
- if (animation_libraries[i].name == p_name) {
+ for (const AnimationLibraryData &lib : animation_libraries) {
+ if (lib.name == p_name) {
return true;
}
}
@@ -1508,9 +1565,9 @@ bool AnimationPlayer::has_animation_library(const StringName &p_name) const {
}
Ref<AnimationLibrary> AnimationPlayer::get_animation_library(const StringName &p_name) const {
- for (uint32_t i = 0; i < animation_libraries.size(); i++) {
- if (animation_libraries[i].name == p_name) {
- return animation_libraries[i].library;
+ for (const AnimationLibraryData &lib : animation_libraries) {
+ if (lib.name == p_name) {
+ return lib.library;
}
}
ERR_FAIL_V(Ref<AnimationLibrary>());
@@ -1518,15 +1575,15 @@ Ref<AnimationLibrary> AnimationPlayer::get_animation_library(const StringName &p
TypedArray<StringName> AnimationPlayer::_get_animation_library_list() const {
TypedArray<StringName> ret;
- for (uint32_t i = 0; i < animation_libraries.size(); i++) {
- ret.push_back(animation_libraries[i].name);
+ for (const AnimationLibraryData &lib : animation_libraries) {
+ ret.push_back(lib.name);
}
return ret;
}
void AnimationPlayer::get_animation_library_list(List<StringName> *p_libraries) const {
- for (uint32_t i = 0; i < animation_libraries.size(); i++) {
- p_libraries->push_back(animation_libraries[i].name);
+ for (const AnimationLibraryData &lib : animation_libraries) {
+ p_libraries->push_back(lib.name);
}
}
@@ -1658,7 +1715,8 @@ void AnimationPlayer::play(const StringName &p_name, double p_custom_blend, floa
}
if (get_current_animation() != p_name) {
- _stop_playing_caches();
+ _clear_audio_streams();
+ _stop_playing_caches(false);
}
c.current.from = &animation_set[name];
@@ -1705,8 +1763,11 @@ bool AnimationPlayer::is_playing() const {
void AnimationPlayer::set_current_animation(const String &p_anim) {
if (p_anim == "[stop]" || p_anim.is_empty()) {
stop();
- } else if (!is_playing() || playback.assigned != p_anim) {
+ } else if (!is_playing()) {
play(p_anim);
+ } else if (playback.assigned != p_anim) {
+ float speed = get_playing_speed();
+ play(p_anim, -1.0, speed, signbit(speed));
} else {
// Same animation, do not replay from start
}
@@ -1718,7 +1779,8 @@ String AnimationPlayer::get_current_animation() const {
void AnimationPlayer::set_assigned_animation(const String &p_anim) {
if (is_playing()) {
- play(p_anim);
+ float speed = get_playing_speed();
+ play(p_anim, -1.0, speed, signbit(speed));
} else {
ERR_FAIL_COND_MSG(!animation_set.has(p_anim), vformat("Animation not found: %s.", p_anim));
playback.current.pos = 0;
@@ -1731,18 +1793,12 @@ String AnimationPlayer::get_assigned_animation() const {
return playback.assigned;
}
-void AnimationPlayer::stop(bool p_reset) {
- _stop_playing_caches();
- Playback &c = playback;
- c.blend.clear();
- if (p_reset) {
- c.current.from = nullptr;
- c.current.speed_scale = 1;
- c.current.pos = 0;
- }
- _set_process(false);
- queued.clear();
- playing = false;
+void AnimationPlayer::pause() {
+ _stop_internal(false, false);
+}
+
+void AnimationPlayer::stop(bool p_keep_state) {
+ _stop_internal(true, p_keep_state);
}
void AnimationPlayer::set_speed_scale(float p_speed) {
@@ -1761,15 +1817,18 @@ float AnimationPlayer::get_playing_speed() const {
}
void AnimationPlayer::seek(double p_time, bool p_update) {
+ playback.current.pos = p_time;
+
if (!playback.current.from) {
if (playback.assigned) {
ERR_FAIL_COND_MSG(!animation_set.has(playback.assigned), vformat("Animation not found: %s.", playback.assigned));
playback.current.from = &animation_set[playback.assigned];
}
- ERR_FAIL_COND(!playback.current.from);
+ if (!playback.current.from) {
+ return; // There is no animation.
+ }
}
- playback.current.pos = p_time;
playback.seeked = true;
if (p_update) {
_animation_process(0);
@@ -1777,20 +1836,22 @@ void AnimationPlayer::seek(double p_time, bool p_update) {
}
void AnimationPlayer::seek_delta(double p_time, double p_delta) {
+ playback.current.pos = p_time - p_delta;
+
if (!playback.current.from) {
if (playback.assigned) {
ERR_FAIL_COND_MSG(!animation_set.has(playback.assigned), vformat("Animation not found: %s.", playback.assigned));
playback.current.from = &animation_set[playback.assigned];
}
- ERR_FAIL_COND(!playback.current.from);
+ if (!playback.current.from) {
+ return; // There is no animation.
+ }
}
- playback.current.pos = p_time - p_delta;
if (speed_scale != 0.0) {
p_delta /= speed_scale;
}
_animation_process(p_delta);
- //playback.current.pos=p_time;
}
bool AnimationPlayer::is_valid() const {
@@ -1814,7 +1875,7 @@ void AnimationPlayer::_animation_changed(const StringName &p_name) {
}
}
-void AnimationPlayer::_stop_playing_caches() {
+void AnimationPlayer::_stop_playing_caches(bool p_reset) {
for (TrackNodeCache *E : playing_caches) {
if (E->node && E->audio_playing) {
E->node->call(SNAME("stop"));
@@ -1824,7 +1885,12 @@ void AnimationPlayer::_stop_playing_caches() {
if (!player) {
continue;
}
- player->stop();
+
+ if (p_reset) {
+ player->stop();
+ } else {
+ player->pause();
+ }
}
}
@@ -1836,7 +1902,8 @@ void AnimationPlayer::_node_removed(Node *p_node) {
}
void AnimationPlayer::clear_caches() {
- _stop_playing_caches();
+ _clear_audio_streams();
+ _stop_playing_caches(true);
node_cache_map.clear();
@@ -1847,10 +1914,19 @@ void AnimationPlayer::clear_caches() {
cache_update_size = 0;
cache_update_prop_size = 0;
cache_update_bezier_size = 0;
+ cache_update_audio_size = 0;
emit_signal(SNAME("caches_cleared"));
}
+void AnimationPlayer::_clear_audio_streams() {
+ for (int i = 0; i < playing_audio_stream_players.size(); i++) {
+ playing_audio_stream_players[i]->call(SNAME("stop"));
+ playing_audio_stream_players[i]->call(SNAME("set_stream"), Ref<AudioStream>());
+ }
+ playing_audio_stream_players.clear();
+}
+
void AnimationPlayer::set_active(bool p_active) {
if (active == p_active) {
return;
@@ -1930,6 +2006,15 @@ AnimationPlayer::AnimationMethodCallMode AnimationPlayer::get_method_call_mode()
return method_call_mode;
}
+void AnimationPlayer::set_audio_max_polyphony(int p_audio_max_polyphony) {
+ ERR_FAIL_COND(p_audio_max_polyphony < 0 || p_audio_max_polyphony > 128);
+ audio_max_polyphony = p_audio_max_polyphony;
+}
+
+int AnimationPlayer::get_audio_max_polyphony() const {
+ return audio_max_polyphony;
+}
+
void AnimationPlayer::set_movie_quit_on_finish_enabled(bool p_enabled) {
movie_quit_on_finish = p_enabled;
}
@@ -1957,6 +2042,27 @@ void AnimationPlayer::_set_process(bool p_process, bool p_force) {
processing = p_process;
}
+void AnimationPlayer::_stop_internal(bool p_reset, bool p_keep_state) {
+ _clear_audio_streams();
+ _stop_playing_caches(p_reset);
+ Playback &c = playback;
+ c.blend.clear();
+ if (p_reset) {
+ if (p_keep_state) {
+ c.current.pos = 0;
+ } else {
+ is_stopping = true;
+ seek(0, true);
+ is_stopping = false;
+ }
+ c.current.from = nullptr;
+ c.current.speed_scale = 1;
+ }
+ _set_process(false);
+ queued.clear();
+ playing = false;
+}
+
void AnimationPlayer::animation_set_next(const StringName &p_animation, const StringName &p_next) {
ERR_FAIL_COND_MSG(!animation_set.has(p_animation), vformat("Animation not found: %s.", p_animation));
animation_set[p_animation].next = p_next;
@@ -2081,7 +2187,7 @@ Ref<AnimatedValuesBackup> AnimationPlayer::apply_reset(bool p_user_initiated) {
Ref<AnimatedValuesBackup> new_values = aux_player->backup_animated_values();
old_values->restore();
- Ref<EditorUndoRedoManager> &ur = EditorNode::get_undo_redo();
+ EditorUndoRedoManager *ur = EditorUndoRedoManager::get_singleton();
ur->create_action(TTR("Animation Apply Reset"));
ur->add_do_method(new_values.ptr(), "restore");
ur->add_undo_method(old_values.ptr(), "restore");
@@ -2119,7 +2225,8 @@ void AnimationPlayer::_bind_methods() {
ClassDB::bind_method(D_METHOD("play", "name", "custom_blend", "custom_speed", "from_end"), &AnimationPlayer::play, DEFVAL(""), DEFVAL(-1), DEFVAL(1.0), DEFVAL(false));
ClassDB::bind_method(D_METHOD("play_backwards", "name", "custom_blend"), &AnimationPlayer::play_backwards, DEFVAL(""), DEFVAL(-1));
- ClassDB::bind_method(D_METHOD("stop", "reset"), &AnimationPlayer::stop, DEFVAL(true));
+ ClassDB::bind_method(D_METHOD("pause"), &AnimationPlayer::pause);
+ ClassDB::bind_method(D_METHOD("stop", "keep_state"), &AnimationPlayer::stop, DEFVAL(false));
ClassDB::bind_method(D_METHOD("is_playing"), &AnimationPlayer::is_playing);
ClassDB::bind_method(D_METHOD("set_current_animation", "anim"), &AnimationPlayer::set_current_animation);
@@ -2157,6 +2264,9 @@ void AnimationPlayer::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_method_call_mode", "mode"), &AnimationPlayer::set_method_call_mode);
ClassDB::bind_method(D_METHOD("get_method_call_mode"), &AnimationPlayer::get_method_call_mode);
+ ClassDB::bind_method(D_METHOD("set_audio_max_polyphony", "max_polyphony"), &AnimationPlayer::set_audio_max_polyphony);
+ ClassDB::bind_method(D_METHOD("get_audio_max_polyphony"), &AnimationPlayer::get_audio_max_polyphony);
+
ClassDB::bind_method(D_METHOD("set_movie_quit_on_finish_enabled", "enabled"), &AnimationPlayer::set_movie_quit_on_finish_enabled);
ClassDB::bind_method(D_METHOD("is_movie_quit_on_finish_enabled"), &AnimationPlayer::is_movie_quit_on_finish_enabled);
@@ -2166,6 +2276,8 @@ void AnimationPlayer::_bind_methods() {
ClassDB::bind_method(D_METHOD("seek", "seconds", "update"), &AnimationPlayer::seek, DEFVAL(false));
ClassDB::bind_method(D_METHOD("advance", "delta"), &AnimationPlayer::advance);
+ GDVIRTUAL_BIND(_post_process_key_value, "animation", "track", "value", "object", "object_idx");
+
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), "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");
@@ -2178,8 +2290,9 @@ void AnimationPlayer::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::INT, "playback_process_mode", PROPERTY_HINT_ENUM, "Physics,Idle,Manual"), "set_process_callback", "get_process_callback");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "playback_default_blend_time", PROPERTY_HINT_RANGE, "0,4096,0.01,suffix:s"), "set_default_blend_time", "get_default_blend_time");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "playback_active", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NONE), "set_active", "is_active");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "playback_speed", PROPERTY_HINT_RANGE, "-64,64,0.01"), "set_speed_scale", "get_speed_scale");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "speed_scale", PROPERTY_HINT_RANGE, "-64,64,0.01"), "set_speed_scale", "get_speed_scale");
ADD_PROPERTY(PropertyInfo(Variant::INT, "method_call_mode", PROPERTY_HINT_ENUM, "Deferred,Immediate"), "set_method_call_mode", "get_method_call_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "audio_max_polyphony", PROPERTY_HINT_RANGE, "1,127,1"), "set_audio_max_polyphony", "get_audio_max_polyphony");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "movie_quit_on_finish"), "set_movie_quit_on_finish_enabled", "is_movie_quit_on_finish_enabled");
diff --git a/scene/animation/animation_player.h b/scene/animation/animation_player.h
index f431253876..b0975fbead 100644
--- a/scene/animation/animation_player.h
+++ b/scene/animation/animation_player.h
@@ -37,6 +37,7 @@
#include "scene/3d/skeleton_3d.h"
#include "scene/resources/animation.h"
#include "scene/resources/animation_library.h"
+#include "scene/resources/audio_stream_polyphonic.h"
#ifdef TOOLS_ENABLED
class AnimatedValuesBackup : public RefCounted {
@@ -147,6 +148,26 @@ private:
HashMap<StringName, BezierAnim> bezier_anim;
+ struct PlayingAudioStreamInfo {
+ AudioStreamPlaybackPolyphonic::ID index = -1;
+ double start = 0.0;
+ double len = 0.0;
+ };
+
+ struct AudioAnim {
+ Ref<AudioStreamPolyphonic> audio_stream;
+ Ref<AudioStreamPlaybackPolyphonic> audio_stream_playback;
+ HashMap<int, PlayingAudioStreamInfo> playing_streams;
+ Object *object = nullptr;
+ uint64_t accum_pass = 0;
+ double length = 0.0;
+ double time = 0.0;
+ bool loop = false;
+ bool backward = false;
+ };
+
+ HashMap<StringName, AudioAnim> audio_anim;
+
uint32_t last_setup_pass = 0;
TrackNodeCache() {}
};
@@ -187,11 +208,15 @@ private:
int cache_update_prop_size = 0;
TrackNodeCache::BezierAnim *cache_update_bezier[NODE_CACHE_UPDATE_MAX];
int cache_update_bezier_size = 0;
+ TrackNodeCache::AudioAnim *cache_update_audio[NODE_CACHE_UPDATE_MAX];
+ int cache_update_audio_size = 0;
HashSet<TrackNodeCache *> playing_caches;
+ Vector<Node *> playing_audio_stream_players;
uint64_t accum_pass = 1;
float speed_scale = 1.0;
double default_blend_time = 0.0;
+ bool is_stopping = false;
struct AnimationData {
String name;
@@ -262,6 +287,7 @@ private:
bool reset_on_save = true;
AnimationProcessCallback process_callback = ANIMATION_PROCESS_IDLE;
AnimationMethodCallMode method_call_mode = ANIMATION_METHOD_CALL_DEFERRED;
+ int audio_max_polyphony = 32;
bool movie_quit_on_finish = false;
bool processing = false;
bool active = true;
@@ -277,7 +303,8 @@ private:
void _animation_process(double p_delta);
void _node_removed(Node *p_node);
- void _stop_playing_caches();
+ void _clear_audio_streams();
+ void _stop_playing_caches(bool p_reset);
// bind helpers
Vector<String> _get_animation_list() const {
@@ -294,6 +321,7 @@ private:
void _animation_changed(const StringName &p_name);
void _set_process(bool p_process, bool p_force = false);
+ void _stop_internal(bool p_reset, bool p_keep_state);
bool playing = false;
@@ -315,6 +343,8 @@ protected:
static void _bind_methods();
+ GDVIRTUAL5RC(Variant, _post_process_key_value, Ref<Animation>, int, Variant, Object *, int);
+ Variant post_process_key_value(const Ref<Animation> &p_anim, int p_track, Variant p_value, const Object *p_object, int p_object_idx = -1);
virtual Variant _post_process_key_value(const Ref<Animation> &p_anim, int p_track, Variant p_value, const Object *p_object, int p_object_idx = -1);
public:
@@ -346,7 +376,8 @@ public:
void queue(const StringName &p_name);
Vector<String> get_queue();
void clear_queue();
- void stop(bool p_reset = true);
+ void pause();
+ void stop(bool p_keep_state = false);
bool is_playing() const;
String get_current_animation() const;
void set_current_animation(const String &p_anim);
@@ -372,6 +403,9 @@ public:
void set_method_call_mode(AnimationMethodCallMode p_mode);
AnimationMethodCallMode get_method_call_mode() const;
+ void set_audio_max_polyphony(int p_audio_max_polyphony);
+ int get_audio_max_polyphony() const;
+
void set_movie_quit_on_finish_enabled(bool p_enabled);
bool is_movie_quit_on_finish_enabled() const;
diff --git a/scene/animation/animation_tree.cpp b/scene/animation/animation_tree.cpp
index ab341797c7..9f9916c1c6 100644
--- a/scene/animation/animation_tree.cpp
+++ b/scene/animation/animation_tree.cpp
@@ -54,13 +54,19 @@ Variant AnimationNode::get_parameter_default_value(const StringName &p_parameter
return ret;
}
+bool AnimationNode::is_parameter_read_only(const StringName &p_parameter) const {
+ bool ret = false;
+ GDVIRTUAL_CALL(_is_parameter_read_only, p_parameter, ret);
+ return ret;
+}
+
void AnimationNode::set_parameter(const StringName &p_name, const Variant &p_value) {
ERR_FAIL_COND(!state);
ERR_FAIL_COND(!state->tree->property_parent_map.has(base_path));
ERR_FAIL_COND(!state->tree->property_parent_map[base_path].has(p_name));
StringName path = state->tree->property_parent_map[base_path][p_name];
- state->tree->property_map[path] = p_value;
+ state->tree->property_map[path].first = p_value;
}
Variant AnimationNode::get_parameter(const StringName &p_name) const {
@@ -69,7 +75,7 @@ Variant AnimationNode::get_parameter(const StringName &p_name) const {
ERR_FAIL_COND_V(!state->tree->property_parent_map[base_path].has(p_name), Variant());
StringName path = state->tree->property_parent_map[base_path][p_name];
- return state->tree->property_map[path];
+ return state->tree->property_map[path].first;
}
void AnimationNode::get_child_nodes(List<ChildNode> *r_child_nodes) {
@@ -297,36 +303,21 @@ double AnimationNode::_blend_node(const StringName &p_subpath, const Vector<Stri
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 {
- return inputs.size();
-}
-
-String AnimationNode::get_input_name(int p_input) {
- ERR_FAIL_INDEX_V(p_input, inputs.size(), String());
- return inputs[p_input].name;
-}
-
String AnimationNode::get_caption() const {
String ret = "Node";
GDVIRTUAL_CALL(_get_caption, ret);
return ret;
}
-void AnimationNode::add_input(const String &p_name) {
+bool AnimationNode::add_input(const String &p_name) {
//root nodes can't add inputs
- ERR_FAIL_COND(Object::cast_to<AnimationRootNode>(this) != nullptr);
+ ERR_FAIL_COND_V(Object::cast_to<AnimationRootNode>(this) != nullptr, false);
Input input;
- ERR_FAIL_COND(p_name.contains(".") || p_name.contains("/"));
+ ERR_FAIL_COND_V(p_name.contains(".") || p_name.contains("/"), false);
input.name = p_name;
inputs.push_back(input);
emit_changed();
-}
-
-void AnimationNode::set_input_name(int p_input, const String &p_name) {
- ERR_FAIL_INDEX(p_input, inputs.size());
- ERR_FAIL_COND(p_name.contains(".") || p_name.contains("/"));
- inputs.write[p_input].name = p_name;
- emit_changed();
+ return true;
}
void AnimationNode::remove_input(int p_index) {
@@ -335,6 +326,34 @@ void AnimationNode::remove_input(int p_index) {
emit_changed();
}
+bool AnimationNode::set_input_name(int p_input, const String &p_name) {
+ ERR_FAIL_INDEX_V(p_input, inputs.size(), false);
+ ERR_FAIL_COND_V(p_name.contains(".") || p_name.contains("/"), false);
+ inputs.write[p_input].name = p_name;
+ emit_changed();
+ return true;
+}
+
+String AnimationNode::get_input_name(int p_input) const {
+ ERR_FAIL_INDEX_V(p_input, inputs.size(), String());
+ return inputs[p_input].name;
+}
+
+int AnimationNode::get_input_count() const {
+ return inputs.size();
+}
+
+int AnimationNode::find_input(const String &p_name) const {
+ int idx = -1;
+ for (int i = 0; i < inputs.size(); i++) {
+ if (inputs[i].name == p_name) {
+ idx = i;
+ break;
+ }
+ }
+ return idx;
+}
+
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_is_external_seeking, ret);
@@ -398,11 +417,12 @@ Ref<AnimationNode> AnimationNode::get_child_by_name(const StringName &p_name) {
}
void AnimationNode::_bind_methods() {
- ClassDB::bind_method(D_METHOD("get_input_count"), &AnimationNode::get_input_count);
- ClassDB::bind_method(D_METHOD("get_input_name", "input"), &AnimationNode::get_input_name);
-
ClassDB::bind_method(D_METHOD("add_input", "name"), &AnimationNode::add_input);
ClassDB::bind_method(D_METHOD("remove_input", "index"), &AnimationNode::remove_input);
+ ClassDB::bind_method(D_METHOD("set_input_name", "input", "name"), &AnimationNode::set_input_name);
+ ClassDB::bind_method(D_METHOD("get_input_name", "input"), &AnimationNode::get_input_name);
+ ClassDB::bind_method(D_METHOD("get_input_count"), &AnimationNode::get_input_count);
+ ClassDB::bind_method(D_METHOD("find_input", "name"), &AnimationNode::find_input);
ClassDB::bind_method(D_METHOD("set_filter_path", "path", "enable"), &AnimationNode::set_filter_path);
ClassDB::bind_method(D_METHOD("is_path_filtered", "path"), &AnimationNode::is_path_filtered);
@@ -427,11 +447,14 @@ 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(_is_parameter_read_only, "parameter");
GDVIRTUAL_BIND(_process, "time", "seek", "is_external_seeking");
GDVIRTUAL_BIND(_get_caption);
GDVIRTUAL_BIND(_has_filter);
ADD_SIGNAL(MethodInfo("tree_changed"));
+ ADD_SIGNAL(MethodInfo("animation_node_renamed", PropertyInfo(Variant::INT, "object_id"), PropertyInfo(Variant::STRING, "old_name"), PropertyInfo(Variant::STRING, "new_name")));
+ ADD_SIGNAL(MethodInfo("animation_node_removed", PropertyInfo(Variant::INT, "object_id"), PropertyInfo(Variant::STRING, "name")));
BIND_ENUM_CONSTANT(FILTER_IGNORE);
BIND_ENUM_CONSTANT(FILTER_PASS);
@@ -444,15 +467,33 @@ AnimationNode::AnimationNode() {
////////////////////
+void AnimationRootNode::_tree_changed() {
+ emit_signal(SNAME("tree_changed"));
+}
+
+void AnimationRootNode::_animation_node_renamed(const ObjectID &p_oid, const String &p_old_name, const String &p_new_name) {
+ emit_signal(SNAME("animation_node_renamed"), p_oid, p_old_name, p_new_name);
+}
+
+void AnimationRootNode::_animation_node_removed(const ObjectID &p_oid, const StringName &p_node) {
+ emit_signal(SNAME("animation_node_removed"), p_oid, p_node);
+}
+
+////////////////////
+
void AnimationTree::set_tree_root(const Ref<AnimationNode> &p_root) {
if (root.is_valid()) {
root->disconnect("tree_changed", callable_mp(this, &AnimationTree::_tree_changed));
+ root->disconnect("animation_node_renamed", callable_mp(this, &AnimationTree::_animation_node_renamed));
+ root->disconnect("animation_node_removed", callable_mp(this, &AnimationTree::_animation_node_removed));
}
root = p_root;
if (root.is_valid()) {
root->connect("tree_changed", callable_mp(this, &AnimationTree::_tree_changed));
+ root->connect("animation_node_renamed", callable_mp(this, &AnimationTree::_animation_node_renamed));
+ root->connect("animation_node_removed", callable_mp(this, &AnimationTree::_animation_node_removed));
}
properties_dirty = true;
@@ -479,13 +520,7 @@ void AnimationTree::set_active(bool p_active) {
}
if (!active && is_inside_tree()) {
- for (const TrackCache *E : playing_caches) {
- if (ObjectDB::get_instance(E->object_id)) {
- E->object->call(SNAME("stop"));
- }
- }
-
- playing_caches.clear();
+ _clear_caches();
}
}
@@ -524,6 +559,7 @@ bool AnimationTree::_update_caches(AnimationPlayer *player) {
if (!player->has_node(player->get_root())) {
ERR_PRINT("AnimationTree: AnimationPlayer root is invalid.");
set_active(false);
+ _clear_caches();
return false;
}
Node *parent = player->get_node(player->get_root());
@@ -531,6 +567,10 @@ bool AnimationTree::_update_caches(AnimationPlayer *player) {
List<StringName> sname;
player->get_animation_list(&sname);
+ root_motion_cache.loc = Vector3(0, 0, 0);
+ root_motion_cache.rot = Quaternion(0, 0, 0, 1);
+ root_motion_cache.scale = Vector3(1, 1, 1);
+
Ref<Animation> reset_anim;
bool has_reset_anim = player->has_animation(SceneStringNames::get_singleton()->RESET);
if (has_reset_anim) {
@@ -747,7 +787,7 @@ bool AnimationTree::_update_caches(AnimationPlayer *player) {
if (has_reset_anim) {
int rt = reset_anim->find_track(path, track_type);
if (rt >= 0 && reset_anim->track_get_key_count(rt) > 0) {
- track_bezier->init_value = reset_anim->track_get_key_value(rt, 0);
+ track_bezier->init_value = (reset_anim->track_get_key_value(rt, 0).operator Array())[0];
}
}
} break;
@@ -756,6 +796,8 @@ bool AnimationTree::_update_caches(AnimationPlayer *player) {
track_audio->object = child;
track_audio->object_id = track_audio->object->get_instance_id();
+ track_audio->audio_stream.instantiate();
+ track_audio->audio_stream->set_polyphony(audio_max_polyphony);
track = track_audio;
@@ -853,14 +895,32 @@ void AnimationTree::_animation_player_changed() {
}
void AnimationTree::_clear_caches() {
+ _clear_audio_streams();
+ _clear_playing_caches();
for (KeyValue<NodePath, TrackCache *> &K : track_cache) {
memdelete(K.value);
}
- playing_caches.clear();
track_cache.clear();
cache_valid = false;
}
+void AnimationTree::_clear_audio_streams() {
+ for (int i = 0; i < playing_audio_stream_players.size(); i++) {
+ playing_audio_stream_players[i]->call(SNAME("stop"));
+ playing_audio_stream_players[i]->call(SNAME("set_stream"), Ref<AudioStream>());
+ }
+ playing_audio_stream_players.clear();
+}
+
+void AnimationTree::_clear_playing_caches() {
+ for (const TrackCache *E : playing_caches) {
+ if (ObjectDB::get_instance(E->object_id)) {
+ E->object->call(SNAME("stop"));
+ }
+ }
+ playing_caches.clear();
+}
+
static void _call_object(Object *p_object, const StringName &p_method, const Vector<Variant> &p_params, bool p_deferred) {
// Separate function to use alloca() more efficiently
const Variant **argptrs = (const Variant **)alloca(sizeof(const Variant **) * p_params.size());
@@ -979,14 +1039,13 @@ void AnimationTree::_process_graph(double p_delta) {
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;
+ root_motion_cache.loc = Vector3(0, 0, 0);
+ root_motion_cache.rot = Quaternion(0, 0, 0, 1);
+ root_motion_cache.scale = Vector3(1, 1, 1);
}
+ 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);
@@ -1000,6 +1059,13 @@ void AnimationTree::_process_graph(double p_delta) {
TrackCacheBezier *t = static_cast<TrackCacheBezier *>(track);
t->value = t->init_value;
} break;
+ case Animation::TYPE_AUDIO: {
+ TrackCacheAudio *t = static_cast<TrackCacheAudio *>(track);
+ for (KeyValue<ObjectID, PlayingAudioTrackInfo> &L : t->playing_streams) {
+ PlayingAudioTrackInfo &track_info = L.value;
+ track_info.volume = 0.0;
+ }
+ } break;
default: {
} break;
}
@@ -1008,8 +1074,9 @@ void AnimationTree::_process_graph(double p_delta) {
// Apply value/transform/blend/bezier blends to track caches and execute method/audio/animation tracks.
{
+#ifdef TOOLS_ENABLED
bool can_call = is_inside_tree() && !Engine::get_singleton()->is_editor_hint();
-
+#endif // TOOLS_ENABLED
for (const AnimationNode::AnimationState &as : state.animation_states) {
Ref<Animation> a = as.animation;
double time = as.time;
@@ -1018,8 +1085,8 @@ void AnimationTree::_process_graph(double p_delta) {
bool seeked = as.seeked;
Animation::LoopedFlag looped_flag = as.looped_flag;
bool is_external_seeking = as.is_external_seeking;
+ bool backward = signbit(delta); // This flag is used by the root motion calculates or detecting the end of audio stream.
#ifndef _3D_DISABLED
- 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
@@ -1038,9 +1105,6 @@ void AnimationTree::_process_graph(double p_delta) {
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) {
@@ -1052,7 +1116,11 @@ void AnimationTree::_process_graph(double p_delta) {
switch (ttype) {
case Animation::TYPE_POSITION_3D: {
#ifndef _3D_DISABLED
+ if (Math::is_zero_approx(blend)) {
+ continue; // Nothing to blend.
+ }
TrackCacheTransform *t = static_cast<TrackCacheTransform *>(track);
+
if (track->root_motion && calc_root) {
double prev_time = time - delta;
if (!backward) {
@@ -1097,10 +1165,10 @@ void AnimationTree::_process_graph(double p_delta) {
if (err != OK) {
continue;
}
- loc[0] = _post_process_key_value(a, i, loc[0], t->object, t->bone_idx);
+ loc[0] = post_process_key_value(a, i, loc[0], t->object, t->bone_idx);
a->position_track_interpolate(i, (double)a->get_length(), &loc[1]);
- loc[1] = _post_process_key_value(a, i, loc[1], t->object, t->bone_idx);
- t->loc += (loc[1] - loc[0]) * blend;
+ loc[1] = post_process_key_value(a, i, loc[1], t->object, t->bone_idx);
+ root_motion_cache.loc += (loc[1] - loc[0]) * blend;
prev_time = 0;
}
} else {
@@ -1109,10 +1177,10 @@ void AnimationTree::_process_graph(double p_delta) {
if (err != OK) {
continue;
}
- loc[0] = _post_process_key_value(a, i, loc[0], t->object, t->bone_idx);
+ loc[0] = post_process_key_value(a, i, loc[0], t->object, t->bone_idx);
a->position_track_interpolate(i, 0, &loc[1]);
- loc[1] = _post_process_key_value(a, i, loc[1], t->object, t->bone_idx);
- t->loc += (loc[1] - loc[0]) * blend;
+ loc[1] = post_process_key_value(a, i, loc[1], t->object, t->bone_idx);
+ root_motion_cache.loc += (loc[1] - loc[0]) * blend;
prev_time = (double)a->get_length();
}
}
@@ -1121,21 +1189,21 @@ void AnimationTree::_process_graph(double p_delta) {
if (err != OK) {
continue;
}
- loc[0] = _post_process_key_value(a, i, loc[0], t->object, t->bone_idx);
-
+ loc[0] = post_process_key_value(a, i, loc[0], t->object, t->bone_idx);
a->position_track_interpolate(i, time, &loc[1]);
- loc[1] = _post_process_key_value(a, i, loc[1], t->object, t->bone_idx);
- t->loc += (loc[1] - loc[0]) * blend;
+ loc[1] = post_process_key_value(a, i, loc[1], t->object, t->bone_idx);
+ root_motion_cache.loc += (loc[1] - loc[0]) * blend;
prev_time = !backward ? 0 : (double)a->get_length();
+ }
- } else {
+ {
Vector3 loc;
Error err = a->position_track_interpolate(i, time, &loc);
if (err != OK) {
continue;
}
- loc = _post_process_key_value(a, i, loc, t->object, t->bone_idx);
+ loc = post_process_key_value(a, i, loc, t->object, t->bone_idx);
t->loc += (loc - t->init_loc) * blend;
}
@@ -1143,7 +1211,11 @@ void AnimationTree::_process_graph(double p_delta) {
} break;
case Animation::TYPE_ROTATION_3D: {
#ifndef _3D_DISABLED
+ if (Math::is_zero_approx(blend)) {
+ continue; // Nothing to blend.
+ }
TrackCacheTransform *t = static_cast<TrackCacheTransform *>(track);
+
if (track->root_motion && calc_root) {
double prev_time = time - delta;
if (!backward) {
@@ -1188,10 +1260,10 @@ void AnimationTree::_process_graph(double p_delta) {
if (err != OK) {
continue;
}
- rot[0] = _post_process_key_value(a, i, rot[0], t->object, t->bone_idx);
+ rot[0] = post_process_key_value(a, i, rot[0], t->object, t->bone_idx);
a->rotation_track_interpolate(i, (double)a->get_length(), &rot[1]);
- rot[1] = _post_process_key_value(a, i, rot[1], t->object, t->bone_idx);
- t->rot = (t->rot * Quaternion().slerp(rot[0].inverse() * rot[1], blend)).normalized();
+ rot[1] = post_process_key_value(a, i, rot[1], t->object, t->bone_idx);
+ root_motion_cache.rot = (root_motion_cache.rot * Quaternion().slerp(rot[0].inverse() * rot[1], blend)).normalized();
prev_time = 0;
}
} else {
@@ -1200,9 +1272,9 @@ void AnimationTree::_process_graph(double p_delta) {
if (err != OK) {
continue;
}
- rot[0] = _post_process_key_value(a, i, rot[0], t->object, t->bone_idx);
+ rot[0] = post_process_key_value(a, i, rot[0], t->object, t->bone_idx);
a->rotation_track_interpolate(i, 0, &rot[1]);
- t->rot = (t->rot * Quaternion().slerp(rot[0].inverse() * rot[1], blend)).normalized();
+ root_motion_cache.rot = (root_motion_cache.rot * Quaternion().slerp(rot[0].inverse() * rot[1], blend)).normalized();
prev_time = (double)a->get_length();
}
}
@@ -1211,21 +1283,22 @@ void AnimationTree::_process_graph(double p_delta) {
if (err != OK) {
continue;
}
- rot[0] = _post_process_key_value(a, i, rot[0], t->object, t->bone_idx);
+ rot[0] = post_process_key_value(a, i, rot[0], t->object, t->bone_idx);
a->rotation_track_interpolate(i, time, &rot[1]);
- rot[1] = _post_process_key_value(a, i, rot[1], t->object, t->bone_idx);
- t->rot = (t->rot * Quaternion().slerp(rot[0].inverse() * rot[1], blend)).normalized();
+ rot[1] = post_process_key_value(a, i, rot[1], t->object, t->bone_idx);
+ root_motion_cache.rot = (root_motion_cache.rot * Quaternion().slerp(rot[0].inverse() * rot[1], blend)).normalized();
prev_time = !backward ? 0 : (double)a->get_length();
+ }
- } else {
+ {
Quaternion rot;
Error err = a->rotation_track_interpolate(i, time, &rot);
if (err != OK) {
continue;
}
- rot = _post_process_key_value(a, i, rot, t->object, t->bone_idx);
+ rot = post_process_key_value(a, i, rot, t->object, t->bone_idx);
t->rot = (t->rot * Quaternion().slerp(t->init_rot.inverse() * rot, blend)).normalized();
}
@@ -1233,7 +1306,11 @@ void AnimationTree::_process_graph(double p_delta) {
} break;
case Animation::TYPE_SCALE_3D: {
#ifndef _3D_DISABLED
+ if (Math::is_zero_approx(blend)) {
+ continue; // Nothing to blend.
+ }
TrackCacheTransform *t = static_cast<TrackCacheTransform *>(track);
+
if (track->root_motion && calc_root) {
double prev_time = time - delta;
if (!backward) {
@@ -1278,10 +1355,10 @@ void AnimationTree::_process_graph(double p_delta) {
if (err != OK) {
continue;
}
- scale[0] = _post_process_key_value(a, i, scale[0], t->object, t->bone_idx);
+ scale[0] = post_process_key_value(a, i, scale[0], t->object, t->bone_idx);
a->scale_track_interpolate(i, (double)a->get_length(), &scale[1]);
- t->scale += (scale[1] - scale[0]) * blend;
- scale[1] = _post_process_key_value(a, i, scale[1], t->object, t->bone_idx);
+ root_motion_cache.scale += (scale[1] - scale[0]) * blend;
+ scale[1] = post_process_key_value(a, i, scale[1], t->object, t->bone_idx);
prev_time = 0;
}
} else {
@@ -1290,10 +1367,10 @@ void AnimationTree::_process_graph(double p_delta) {
if (err != OK) {
continue;
}
- scale[0] = _post_process_key_value(a, i, scale[0], t->object, t->bone_idx);
+ scale[0] = post_process_key_value(a, i, scale[0], t->object, t->bone_idx);
a->scale_track_interpolate(i, 0, &scale[1]);
- scale[1] = _post_process_key_value(a, i, scale[1], t->object, t->bone_idx);
- t->scale += (scale[1] - scale[0]) * blend;
+ scale[1] = post_process_key_value(a, i, scale[1], t->object, t->bone_idx);
+ root_motion_cache.scale += (scale[1] - scale[0]) * blend;
prev_time = (double)a->get_length();
}
}
@@ -1302,21 +1379,22 @@ void AnimationTree::_process_graph(double p_delta) {
if (err != OK) {
continue;
}
- scale[0] = _post_process_key_value(a, i, scale[0], t->object, t->bone_idx);
+ scale[0] = post_process_key_value(a, i, scale[0], t->object, t->bone_idx);
a->scale_track_interpolate(i, time, &scale[1]);
- scale[1] = _post_process_key_value(a, i, scale[1], t->object, t->bone_idx);
- t->scale += (scale[1] - scale[0]) * blend;
+ scale[1] = post_process_key_value(a, i, scale[1], t->object, t->bone_idx);
+ root_motion_cache.scale += (scale[1] - scale[0]) * blend;
prev_time = !backward ? 0 : (double)a->get_length();
+ }
- } else {
+ {
Vector3 scale;
Error err = a->scale_track_interpolate(i, time, &scale);
if (err != OK) {
continue;
}
- scale = _post_process_key_value(a, i, scale, t->object, t->bone_idx);
+ scale = post_process_key_value(a, i, scale, t->object, t->bone_idx);
t->scale += (scale - t->init_scale) * blend;
}
@@ -1324,6 +1402,9 @@ void AnimationTree::_process_graph(double p_delta) {
} break;
case Animation::TYPE_BLEND_SHAPE: {
#ifndef _3D_DISABLED
+ if (Math::is_zero_approx(blend)) {
+ continue; // Nothing to blend.
+ }
TrackCacheBlendShape *t = static_cast<TrackCacheBlendShape *>(track);
float value;
@@ -1334,19 +1415,22 @@ void AnimationTree::_process_graph(double p_delta) {
if (err != OK) {
continue;
}
- value = _post_process_key_value(a, i, value, t->object, t->shape_index);
+ value = post_process_key_value(a, i, value, t->object, t->shape_index);
t->value += (value - t->init_value) * blend;
#endif // _3D_DISABLED
} break;
case Animation::TYPE_VALUE: {
+ if (Math::is_zero_approx(blend)) {
+ continue; // Nothing to blend.
+ }
TrackCacheValue *t = static_cast<TrackCacheValue *>(track);
Animation::UpdateMode update_mode = a->value_track_get_update_mode(i);
if (update_mode == Animation::UPDATE_CONTINUOUS || update_mode == Animation::UPDATE_CAPTURE) {
Variant value = a->value_track_interpolate(i, time);
- value = _post_process_key_value(a, i, value, t->object);
+ value = post_process_key_value(a, i, value, t->object);
if (value == Variant()) {
continue;
@@ -1386,14 +1470,14 @@ void AnimationTree::_process_graph(double p_delta) {
continue;
}
Variant value = a->track_get_key_value(i, idx);
- value = _post_process_key_value(a, i, value, t->object);
+ value = post_process_key_value(a, i, value, t->object);
t->object->set_indexed(t->subpath, value);
} else {
List<int> indices;
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);
+ value = post_process_key_value(a, i, value, t->object);
t->object->set_indexed(t->subpath, value);
}
}
@@ -1401,6 +1485,14 @@ void AnimationTree::_process_graph(double p_delta) {
} break;
case Animation::TYPE_METHOD: {
+#ifdef TOOLS_ENABLED
+ if (!can_call) {
+ continue;
+ }
+#endif // TOOLS_ENABLED
+ if (Math::is_zero_approx(blend)) {
+ continue; // Nothing to blend.
+ }
TrackCacheMethod *t = static_cast<TrackCacheMethod *>(track);
if (seeked) {
@@ -1410,137 +1502,116 @@ void AnimationTree::_process_graph(double p_delta) {
}
StringName method = a->method_track_get_name(i, idx);
Vector<Variant> params = a->method_track_get_params(i, idx);
- if (can_call) {
- _call_object(t->object, method, params, false);
- }
+ _call_object(t->object, method, params, false);
} else {
List<int> indices;
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);
- if (can_call) {
- _call_object(t->object, method, params, true);
- }
+ _call_object(t->object, method, params, true);
}
}
} break;
case Animation::TYPE_BEZIER: {
+ if (Math::is_zero_approx(blend)) {
+ continue; // Nothing to blend.
+ }
TrackCacheBezier *t = static_cast<TrackCacheBezier *>(track);
real_t bezier = a->bezier_track_interpolate(i, time);
- bezier = _post_process_key_value(a, i, bezier, t->object);
+ bezier = post_process_key_value(a, i, bezier, t->object);
t->value += (bezier - t->init_value) * blend;
} break;
case Animation::TYPE_AUDIO: {
TrackCacheAudio *t = static_cast<TrackCacheAudio *>(track);
- if (seeked) {
- //find whatever should be playing
- int idx = a->track_find_key(i, time, is_external_seeking ? Animation::FIND_MODE_NEAREST : Animation::FIND_MODE_EXACT);
- if (idx < 0) {
- continue;
- }
-
- Ref<AudioStream> stream = a->audio_track_get_key_stream(i, idx);
- if (!stream.is_valid()) {
- t->object->call(SNAME("stop"));
- t->playing = false;
- playing_caches.erase(t);
- } else {
- double start_ofs = a->audio_track_get_key_start_offset(i, idx);
- start_ofs += time - a->track_get_key_time(i, idx);
- double end_ofs = a->audio_track_get_key_end_offset(i, idx);
- double len = stream->get_length();
-
- if (start_ofs > len - end_ofs) {
- t->object->call(SNAME("stop"));
- t->playing = false;
- playing_caches.erase(t);
- continue;
- }
-
- t->object->call(SNAME("set_stream"), stream);
- t->object->call(SNAME("play"), start_ofs);
-
- t->playing = true;
- playing_caches.insert(t);
- if (len && end_ofs > 0) { //force an end at a time
- t->len = len - start_ofs - end_ofs;
- } else {
- t->len = 0;
- }
+ Node *asp = Object::cast_to<Node>(t->object);
+ if (!asp) {
+ t->playing_streams.clear();
+ continue;
+ }
- t->start = time;
+ ObjectID oid = a->get_instance_id();
+ if (!t->playing_streams.has(oid)) {
+ t->playing_streams[oid] = PlayingAudioTrackInfo();
+ }
+ // The end of audio should be observed even if the blend value is 0, build up the information and store to the cache for that.
+ PlayingAudioTrackInfo &track_info = t->playing_streams[oid];
+ track_info.length = a->get_length();
+ track_info.time = time;
+ track_info.volume += blend;
+ track_info.loop = a->get_loop_mode() != Animation::LOOP_NONE;
+ track_info.backward = backward;
+ track_info.use_blend = a->audio_track_is_use_blend(i);
+
+ HashMap<int, PlayingAudioStreamInfo> &map = track_info.stream_info;
+ // Find stream.
+ int idx = -1;
+ if (seeked) {
+ idx = a->track_find_key(i, time, is_external_seeking ? Animation::FIND_MODE_NEAREST : Animation::FIND_MODE_EXACT);
+ // Discard previous stream when seeking.
+ if (map.has(idx)) {
+ t->audio_stream_playback->stop_stream(map[idx].index);
+ map.erase(idx);
}
-
} else {
- //find stuff to play
List<int> to_play;
a->track_get_key_indices_in_range(i, time, delta, &to_play, looped_flag);
if (to_play.size()) {
- int idx = to_play.back()->get();
-
- Ref<AudioStream> stream = a->audio_track_get_key_stream(i, idx);
- if (!stream.is_valid()) {
- t->object->call(SNAME("stop"));
- t->playing = false;
- playing_caches.erase(t);
- } else {
- double start_ofs = a->audio_track_get_key_start_offset(i, idx);
- double end_ofs = a->audio_track_get_key_end_offset(i, idx);
- double len = stream->get_length();
-
- t->object->call(SNAME("set_stream"), stream);
- t->object->call(SNAME("play"), start_ofs);
+ idx = to_play.back()->get();
+ }
+ }
+ if (idx < 0) {
+ continue;
+ }
- t->playing = true;
- playing_caches.insert(t);
- if (len && end_ofs > 0) { //force an end at a time
- t->len = len - start_ofs - end_ofs;
- } else {
- t->len = 0;
- }
+ // Play stream.
+ Ref<AudioStream> stream = a->audio_track_get_key_stream(i, idx);
+ if (stream.is_valid()) {
+ double start_ofs = a->audio_track_get_key_start_offset(i, idx);
+ double end_ofs = a->audio_track_get_key_end_offset(i, idx);
+ double len = stream->get_length();
- t->start = time;
- }
- } else if (t->playing) {
- bool loop = a->get_loop_mode() != Animation::LOOP_NONE;
-
- bool stop = false;
-
- if (!loop) {
- if (delta > 0) {
- if (time < t->start) {
- stop = true;
- }
- } else if (delta < 0) {
- if (time > t->start) {
- stop = true;
- }
- }
- } else if (t->len > 0) {
- double len = t->start > time ? (a->get_length() - t->start) + time : time - t->start;
+ if (seeked) {
+ start_ofs += time - a->track_get_key_time(i, idx);
+ }
- if (len > t->len) {
- stop = true;
- }
+ if (t->object->call(SNAME("get_stream")) != t->audio_stream) {
+ t->object->call(SNAME("set_stream"), t->audio_stream);
+ t->audio_stream_playback.unref();
+ if (!playing_audio_stream_players.has(asp)) {
+ playing_audio_stream_players.push_back(asp);
}
+ }
+ if (!t->object->call(SNAME("is_playing"))) {
+ t->object->call(SNAME("play"));
+ }
+ if (!t->object->call(SNAME("has_stream_playback"))) {
+ t->audio_stream_playback.unref();
+ continue;
+ }
+ if (t->audio_stream_playback.is_null()) {
+ t->audio_stream_playback = t->object->call(SNAME("get_stream_playback"));
+ }
- if (stop) {
- //time to stop
- t->object->call(SNAME("stop"));
- t->playing = false;
- playing_caches.erase(t);
- }
+ PlayingAudioStreamInfo pasi;
+ pasi.index = t->audio_stream_playback->play_stream(stream, start_ofs);
+ pasi.start = time;
+ if (len && end_ofs > 0) { // Force an end at a time.
+ pasi.len = len - start_ofs - end_ofs;
+ } else {
+ pasi.len = 0;
}
+ map[idx] = pasi;
}
- real_t db = Math::linear_to_db(MAX(blend, 0.00001));
- t->object->call(SNAME("set_volume_db"), db);
} break;
case Animation::TYPE_ANIMATION: {
+ if (Math::is_zero_approx(blend)) {
+ continue; // Nothing to blend.
+ }
TrackCacheAnimation *t = static_cast<TrackCacheAnimation *>(track);
AnimationPlayer *player2 = Object::cast_to<AnimationPlayer>(t->object);
@@ -1629,10 +1700,12 @@ void AnimationTree::_process_graph(double p_delta) {
TrackCacheTransform *t = static_cast<TrackCacheTransform *>(track);
if (t->root_motion) {
- root_motion_position = t->loc;
- root_motion_rotation = t->rot;
- root_motion_scale = t->scale - Vector3(1, 1, 1);
-
+ root_motion_position = root_motion_cache.loc;
+ root_motion_rotation = root_motion_cache.rot;
+ root_motion_scale = root_motion_cache.scale - Vector3(1, 1, 1);
+ root_motion_position_accumulator = t->loc;
+ root_motion_rotation_accumulator = t->rot;
+ root_motion_scale_accumulator = t->scale;
} else if (t->skeleton && t->bone_idx >= 0) {
if (t->loc_used) {
t->skeleton->set_bone_pose_position(t->bone_idx, t->loc);
@@ -1686,6 +1759,64 @@ void AnimationTree::_process_graph(double p_delta) {
t->object->set_indexed(t->subpath, t->value);
} break;
+ case Animation::TYPE_AUDIO: {
+ TrackCacheAudio *t = static_cast<TrackCacheAudio *>(track);
+
+ // Audio ending process.
+ LocalVector<ObjectID> erase_maps;
+ for (KeyValue<ObjectID, PlayingAudioTrackInfo> &L : t->playing_streams) {
+ PlayingAudioTrackInfo &track_info = L.value;
+ float db = Math::linear_to_db(track_info.use_blend ? track_info.volume : 1.0);
+ LocalVector<int> erase_streams;
+ HashMap<int, PlayingAudioStreamInfo> &map = track_info.stream_info;
+ for (const KeyValue<int, PlayingAudioStreamInfo> &M : map) {
+ PlayingAudioStreamInfo pasi = M.value;
+
+ bool stop = false;
+ if (!t->audio_stream_playback->is_stream_playing(pasi.index)) {
+ stop = true;
+ }
+ if (!track_info.loop) {
+ if (!track_info.backward) {
+ if (track_info.time < pasi.start) {
+ stop = true;
+ }
+ } else if (track_info.backward) {
+ if (track_info.time > pasi.start) {
+ stop = true;
+ }
+ }
+ }
+ if (pasi.len > 0) {
+ double len = 0.0;
+ if (!track_info.backward) {
+ len = pasi.start > track_info.time ? (track_info.length - pasi.start) + track_info.time : track_info.time - pasi.start;
+ } else {
+ len = pasi.start < track_info.time ? (track_info.length - track_info.time) + pasi.start : pasi.start - track_info.time;
+ }
+ if (len > pasi.len) {
+ stop = true;
+ }
+ }
+ if (stop) {
+ // Time to stop.
+ t->audio_stream_playback->stop_stream(pasi.index);
+ erase_streams.push_back(M.key);
+ } else {
+ t->audio_stream_playback->set_stream_volume(pasi.index, db);
+ }
+ }
+ for (uint32_t erase_idx = 0; erase_idx < erase_streams.size(); erase_idx++) {
+ map.erase(erase_streams[erase_idx]);
+ }
+ if (map.size() == 0) {
+ erase_maps.push_back(L.key);
+ }
+ }
+ for (uint32_t erase_idx = 0; erase_idx < erase_maps.size(); erase_idx++) {
+ t->playing_streams.erase(erase_maps[erase_idx]);
+ }
+ } break;
default: {
} //the rest don't matter
}
@@ -1693,6 +1824,15 @@ void AnimationTree::_process_graph(double p_delta) {
}
}
+Variant AnimationTree::post_process_key_value(const Ref<Animation> &p_anim, int p_track, Variant p_value, const Object *p_object, int p_object_idx) {
+ Variant res;
+ if (GDVIRTUAL_CALL(_post_process_key_value, p_anim, p_track, p_value, const_cast<Object *>(p_object), p_object_idx, res)) {
+ return res;
+ }
+
+ return _post_process_key_value(p_anim, p_track, p_value, p_object, p_object_idx);
+}
+
Variant AnimationTree::_post_process_key_value(const Ref<Animation> &p_anim, int p_track, Variant p_value, const Object *p_object, int p_object_idx) {
switch (p_anim->track_get_type(p_track)) {
#ifndef _3D_DISABLED
@@ -1755,6 +1895,8 @@ void AnimationTree::_setup_animation_player() {
return;
}
+ cache_valid = false;
+
AnimationPlayer *new_player = nullptr;
if (!animation_player.is_empty()) {
new_player = Object::cast_to<AnimationPlayer>(get_node_or_null(animation_player));
@@ -1802,6 +1944,15 @@ NodePath AnimationTree::get_advance_expression_base_node() const {
return advance_expression_base_node;
}
+void AnimationTree::set_audio_max_polyphony(int p_audio_max_polyphony) {
+ ERR_FAIL_COND(p_audio_max_polyphony < 0 || p_audio_max_polyphony > 128);
+ audio_max_polyphony = p_audio_max_polyphony;
+}
+
+int AnimationTree::get_audio_max_polyphony() const {
+ return audio_max_polyphony;
+}
+
bool AnimationTree::is_state_invalid() const {
return !state.valid;
}
@@ -1856,6 +2007,18 @@ Vector3 AnimationTree::get_root_motion_scale() const {
return root_motion_scale;
}
+Vector3 AnimationTree::get_root_motion_position_accumulator() const {
+ return root_motion_position_accumulator;
+}
+
+Quaternion AnimationTree::get_root_motion_rotation_accumulator() const {
+ return root_motion_rotation_accumulator;
+}
+
+Vector3 AnimationTree::get_root_motion_scale_accumulator() const {
+ return root_motion_scale_accumulator;
+}
+
void AnimationTree::_tree_changed() {
if (properties_dirty) {
return;
@@ -1865,11 +2028,46 @@ void AnimationTree::_tree_changed() {
properties_dirty = true;
}
+void AnimationTree::_animation_node_renamed(const ObjectID &p_oid, const String &p_old_name, const String &p_new_name) {
+ ERR_FAIL_COND(!property_reference_map.has(p_oid));
+ String base_path = property_reference_map[p_oid];
+ String old_base = base_path + p_old_name;
+ String new_base = base_path + p_new_name;
+ for (const PropertyInfo &E : properties) {
+ if (E.name.begins_with(old_base)) {
+ String new_name = E.name.replace_first(old_base, new_base);
+ property_map[new_name] = property_map[E.name];
+ property_map.erase(E.name);
+ }
+ }
+
+ //update tree second
+ properties_dirty = true;
+ _update_properties();
+}
+
+void AnimationTree::_animation_node_removed(const ObjectID &p_oid, const StringName &p_node) {
+ ERR_FAIL_COND(!property_reference_map.has(p_oid));
+ String base_path = String(property_reference_map[p_oid]) + String(p_node);
+ for (const PropertyInfo &E : properties) {
+ if (E.name.begins_with(base_path)) {
+ property_map.erase(E.name);
+ }
+ }
+
+ //update tree second
+ properties_dirty = true;
+ _update_properties();
+}
+
void AnimationTree::_update_properties_for_node(const String &p_base_path, Ref<AnimationNode> node) {
ERR_FAIL_COND(node.is_null());
if (!property_parent_map.has(p_base_path)) {
property_parent_map[p_base_path] = HashMap<StringName, StringName>();
}
+ if (!property_reference_map.has(node->get_instance_id())) {
+ property_reference_map[node->get_instance_id()] = p_base_path;
+ }
if (node->get_input_count() && !input_activity_map.has(p_base_path)) {
Vector<Activity> activity;
@@ -1889,7 +2087,10 @@ void AnimationTree::_update_properties_for_node(const String &p_base_path, Ref<A
StringName key = pinfo.name;
if (!property_map.has(p_base_path + key)) {
- property_map[p_base_path + key] = node->get_parameter_default_value(key);
+ Pair<Variant, bool> param;
+ param.first = node->get_parameter_default_value(key);
+ param.second = node->is_parameter_read_only(key);
+ property_map[p_base_path + key] = param;
}
property_parent_map[p_base_path][key] = p_base_path + key;
@@ -1912,6 +2113,7 @@ void AnimationTree::_update_properties() {
}
properties.clear();
+ property_reference_map.clear();
property_parent_map.clear();
input_activity_map.clear();
input_activity_map_get.clear();
@@ -1931,7 +2133,10 @@ bool AnimationTree::_set(const StringName &p_name, const Variant &p_value) {
}
if (property_map.has(p_name)) {
- property_map[p_name] = p_value;
+ if (is_inside_tree() && property_map[p_name].second) {
+ return false; // Prevent to set property by user.
+ }
+ property_map[p_name].first = p_value;
return true;
}
@@ -1944,7 +2149,7 @@ bool AnimationTree::_get(const StringName &p_name, Variant &r_ret) const {
}
if (property_map.has(p_name)) {
- r_ret = property_map[p_name];
+ r_ret = property_map[p_name].first;
return true;
}
@@ -1961,20 +2166,6 @@ void AnimationTree::_get_property_list(List<PropertyInfo> *p_list) const {
}
}
-void AnimationTree::rename_parameter(const String &p_base, const String &p_new_base) {
- //rename values first
- for (const PropertyInfo &E : properties) {
- if (E.name.begins_with(p_base)) {
- String new_name = E.name.replace_first(p_base, p_new_base);
- property_map[new_name] = property_map[E.name];
- }
- }
-
- //update tree second
- properties_dirty = true;
- _update_properties();
-}
-
real_t AnimationTree::get_connection_activity(const StringName &p_path, int p_connection) const {
if (!input_activity_map_get.has(p_path)) {
return 0;
@@ -2011,22 +2202,30 @@ 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("set_audio_max_polyphony", "max_polyphony"), &AnimationTree::set_audio_max_polyphony);
+ ClassDB::bind_method(D_METHOD("get_audio_max_polyphony"), &AnimationTree::get_audio_max_polyphony);
+
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("get_root_motion_position_accumulator"), &AnimationTree::get_root_motion_position_accumulator);
+ ClassDB::bind_method(D_METHOD("get_root_motion_rotation_accumulator"), &AnimationTree::get_root_motion_rotation_accumulator);
+ ClassDB::bind_method(D_METHOD("get_root_motion_scale_accumulator"), &AnimationTree::get_root_motion_scale_accumulator);
ClassDB::bind_method(D_METHOD("_update_properties"), &AnimationTree::_update_properties);
- ClassDB::bind_method(D_METHOD("rename_parameter", "old_name", "new_name"), &AnimationTree::rename_parameter);
-
ClassDB::bind_method(D_METHOD("advance", "delta"), &AnimationTree::advance);
+ GDVIRTUAL_BIND(_post_process_key_value, "animation", "track", "value", "object", "object_idx");
+
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "tree_root", PROPERTY_HINT_RESOURCE_TYPE, "AnimationRootNode"), "set_tree_root", "get_tree_root");
ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "anim_player", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "AnimationPlayer"), "set_animation_player", "get_animation_player");
ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "advance_expression_base_node", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Node"), "set_advance_expression_base_node", "get_advance_expression_base_node");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "active"), "set_active", "is_active");
ADD_PROPERTY(PropertyInfo(Variant::INT, "process_callback", PROPERTY_HINT_ENUM, "Physics,Idle,Manual"), "set_process_callback", "get_process_callback");
+ ADD_GROUP("Audio", "audio_");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "audio_max_polyphony", PROPERTY_HINT_RANGE, "1,127,1"), "set_audio_max_polyphony", "get_audio_max_polyphony");
ADD_GROUP("Root Motion", "root_motion_");
ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "root_motion_track"), "set_root_motion_track", "get_root_motion_track");
diff --git a/scene/animation/animation_tree.h b/scene/animation/animation_tree.h
index 2c1be6199c..c68cae56ea 100644
--- a/scene/animation/animation_tree.h
+++ b/scene/animation/animation_tree.h
@@ -35,6 +35,7 @@
#include "scene/3d/node_3d.h"
#include "scene/3d/skeleton_3d.h"
#include "scene/resources/animation.h"
+#include "scene/resources/audio_stream_polyphonic.h"
class AnimationNodeBlendTree;
class AnimationNodeStartState;
@@ -117,6 +118,7 @@ protected:
GDVIRTUAL0RC(Array, _get_parameter_list)
GDVIRTUAL1RC(Ref<AnimationNode>, _get_child_by_name, StringName)
GDVIRTUAL1RC(Variant, _get_parameter_default_value, StringName)
+ GDVIRTUAL1RC(bool, _is_parameter_read_only, StringName)
GDVIRTUAL3RC(double, _process, double, bool, bool)
GDVIRTUAL0RC(String, _get_caption)
GDVIRTUAL0RC(bool, _has_filter)
@@ -124,6 +126,7 @@ protected:
public:
virtual void get_parameter_list(List<PropertyInfo> *r_list) const;
virtual Variant get_parameter_default_value(const StringName &p_parameter) const;
+ virtual bool is_parameter_read_only(const StringName &p_parameter) const;
void set_parameter(const StringName &p_name, const Variant &p_value);
Variant get_parameter(const StringName &p_name) const;
@@ -138,12 +141,12 @@ public:
virtual double process(double p_time, bool p_seek, bool p_is_external_seeking);
virtual String get_caption() const;
+ virtual bool add_input(const String &p_name);
+ virtual void remove_input(int p_index);
+ virtual bool set_input_name(int p_input, const String &p_name);
+ virtual String get_input_name(int p_input) const;
int get_input_count() const;
- String get_input_name(int p_input);
-
- void add_input(const String &p_name);
- void set_input_name(int p_input, const String &p_name);
- void remove_input(int p_index);
+ int find_input(const String &p_name) const;
void set_filter_path(const NodePath &p_path, bool p_enable);
bool is_path_filtered(const NodePath &p_path) const;
@@ -164,6 +167,11 @@ VARIANT_ENUM_CAST(AnimationNode::FilterAction)
class AnimationRootNode : public AnimationNode {
GDCLASS(AnimationRootNode, AnimationNode);
+protected:
+ virtual void _tree_changed();
+ virtual void _animation_node_renamed(const ObjectID &p_oid, const String &p_old_name, const String &p_new_name);
+ virtual void _animation_node_removed(const ObjectID &p_oid, const StringName &p_node);
+
public:
AnimationRootNode() {}
};
@@ -220,6 +228,12 @@ private:
}
};
+ struct RootMotionCache {
+ Vector3 loc = Vector3(0, 0, 0);
+ Quaternion rot = Quaternion(0, 0, 0, 1);
+ Vector3 scale = Vector3(1, 1, 1);
+ };
+
struct TrackCacheBlendShape : public TrackCache {
MeshInstance3D *mesh_3d = nullptr;
float init_value = 0;
@@ -250,10 +264,28 @@ private:
}
};
- struct TrackCacheAudio : public TrackCache {
- bool playing = false;
+ // Audio stream information for each audio stream placed on the track.
+ struct PlayingAudioStreamInfo {
+ AudioStreamPlaybackPolyphonic::ID index = -1; // ID retrieved from AudioStreamPlaybackPolyphonic.
double start = 0.0;
double len = 0.0;
+ };
+
+ // Audio track information for mixng and ending.
+ struct PlayingAudioTrackInfo {
+ HashMap<int, PlayingAudioStreamInfo> stream_info;
+ double length = 0.0;
+ double time = 0.0;
+ real_t volume = 0.0;
+ bool loop = false;
+ bool backward = false;
+ bool use_blend = false;
+ };
+
+ struct TrackCacheAudio : public TrackCache {
+ Ref<AudioStreamPolyphonic> audio_stream;
+ Ref<AudioStreamPlaybackPolyphonic> audio_stream_playback;
+ HashMap<ObjectID, PlayingAudioTrackInfo> playing_streams; // Key is Animation resource ObjectID.
TrackCacheAudio() {
type = Animation::TYPE_AUDIO;
@@ -268,8 +300,10 @@ private:
}
};
+ RootMotionCache root_motion_cache;
HashMap<NodePath, TrackCache *> track_cache;
HashSet<TrackCache *> playing_caches;
+ Vector<Node *> playing_audio_stream_players;
Ref<AnimationNode> root;
NodePath advance_expression_base_node = NodePath(String("."));
@@ -277,6 +311,7 @@ private:
AnimationProcessCallback process_callback = ANIMATION_PROCESS_IDLE;
bool active = false;
NodePath animation_player;
+ int audio_max_polyphony = 32;
AnimationNode::State state;
bool cache_valid = false;
@@ -285,6 +320,8 @@ private:
void _setup_animation_player();
void _animation_player_changed();
void _clear_caches();
+ void _clear_playing_caches();
+ void _clear_audio_streams();
bool _update_caches(AnimationPlayer *player);
void _process_graph(double p_delta);
@@ -297,14 +334,20 @@ private:
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);
+ Vector3 root_motion_position_accumulator = Vector3(0, 0, 0);
+ Quaternion root_motion_rotation_accumulator = Quaternion(0, 0, 0, 1);
+ Vector3 root_motion_scale_accumulator = Vector3(1, 1, 1);
friend class AnimationNode;
bool properties_dirty = true;
void _tree_changed();
+ void _animation_node_renamed(const ObjectID &p_oid, const String &p_old_name, const String &p_new_name);
+ void _animation_node_removed(const ObjectID &p_oid, const StringName &p_node);
void _update_properties();
List<PropertyInfo> properties;
HashMap<StringName, HashMap<StringName, StringName>> property_parent_map;
- HashMap<StringName, Variant> property_map;
+ HashMap<ObjectID, StringName> property_reference_map;
+ HashMap<StringName, Pair<Variant, bool>> property_map; // Property value and read-only flag.
struct Activity {
uint64_t last_pass = 0;
@@ -326,6 +369,8 @@ protected:
void _notification(int p_what);
static void _bind_methods();
+ GDVIRTUAL5RC(Variant, _post_process_key_value, Ref<Animation>, int, Variant, Object *, int);
+ Variant post_process_key_value(const Ref<Animation> &p_anim, int p_track, Variant p_value, const Object *p_object, int p_object_idx = -1);
virtual Variant _post_process_key_value(const Ref<Animation> &p_anim, int p_track, Variant p_value, const Object *p_object, int p_object_idx = -1);
public:
@@ -344,6 +389,9 @@ public:
void set_advance_expression_base_node(const NodePath &p_advance_expression_base_node);
NodePath get_advance_expression_base_node() const;
+ void set_audio_max_polyphony(int p_audio_max_polyphony);
+ int get_audio_max_polyphony() const;
+
PackedStringArray get_configuration_warnings() const override;
bool is_state_invalid() const;
@@ -356,11 +404,13 @@ public:
Quaternion get_root_motion_rotation() const;
Vector3 get_root_motion_scale() const;
+ Vector3 get_root_motion_position_accumulator() const;
+ Quaternion get_root_motion_rotation_accumulator() const;
+ Vector3 get_root_motion_scale_accumulator() const;
+
real_t get_connection_activity(const StringName &p_path, int p_connection) const;
void advance(double p_time);
- void rename_parameter(const String &p_base, const String &p_new_base);
-
uint64_t get_last_process_pass() const;
AnimationTree();
~AnimationTree();
diff --git a/scene/animation/root_motion_view.cpp b/scene/animation/root_motion_view.cpp
index e6b258df3e..fc758b9456 100644
--- a/scene/animation/root_motion_view.cpp
+++ b/scene/animation/root_motion_view.cpp
@@ -80,13 +80,15 @@ bool RootMotionView::get_zero_y() const {
void RootMotionView::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
- immediate_material = StandardMaterial3D::get_material_for_2d(false, true, false, false, false);
+ immediate_material = StandardMaterial3D::get_material_for_2d(false, BaseMaterial3D::TRANSPARENCY_ALPHA, false);
+
first = true;
} break;
case NOTIFICATION_INTERNAL_PROCESS:
case NOTIFICATION_INTERNAL_PHYSICS_PROCESS: {
Transform3D transform;
+ Basis diff;
if (has_node(path)) {
Node *node = get_node(path);
@@ -102,9 +104,9 @@ void RootMotionView::_notification(int p_what) {
set_process_internal(true);
set_physics_process_internal(false);
}
-
transform.origin = tree->get_root_motion_position();
transform.basis = tree->get_root_motion_rotation(); // Scale is meaningless.
+ diff = tree->get_root_motion_rotation_accumulator();
}
}
@@ -114,8 +116,10 @@ void RootMotionView::_notification(int p_what) {
first = false;
- accumulated.origin += transform.origin;
accumulated.basis *= transform.basis;
+ transform.origin = (diff.inverse() * accumulated.basis).xform(transform.origin);
+ accumulated.origin += transform.origin;
+
accumulated.origin.x = Math::fposmod(accumulated.origin.x, cell_size);
if (zero_y) {
accumulated.origin.y = 0;
diff --git a/scene/animation/tween.cpp b/scene/animation/tween.cpp
index b88695427e..abc7814877 100644
--- a/scene/animation/tween.cpp
+++ b/scene/animation/tween.cpp
@@ -60,7 +60,7 @@ void Tweener::_bind_methods() {
ADD_SIGNAL(MethodInfo("finished"));
}
-void Tween::start_tweeners() {
+void Tween::_start_tweeners() {
if (tweeners.is_empty()) {
dead = true;
ERR_FAIL_MSG("Tween without commands, aborting.");
@@ -71,6 +71,15 @@ void Tween::start_tweeners() {
}
}
+void Tween::_stop_internal(bool p_reset) {
+ running = false;
+ if (p_reset) {
+ started = false;
+ dead = false;
+ total_time = 0;
+ }
+}
+
Ref<PropertyTweener> Tween::tween_property(Object *p_target, NodePath p_property, Variant p_to, double p_duration) {
ERR_FAIL_NULL_V(p_target, nullptr);
ERR_FAIL_COND_V_MSG(!valid, nullptr, "Tween invalid. Either finished or created outside scene tree.");
@@ -135,14 +144,11 @@ void Tween::append(Ref<Tweener> p_tweener) {
}
void Tween::stop() {
- started = false;
- running = false;
- dead = false;
- total_time = 0;
+ _stop_internal(true);
}
void Tween::pause() {
- running = false;
+ _stop_internal(false);
}
void Tween::play() {
@@ -274,11 +280,20 @@ bool Tween::step(double p_delta) {
}
if (!started) {
- ERR_FAIL_COND_V_MSG(tweeners.is_empty(), false, "Tween started, but has no Tweeners.");
+ if (tweeners.is_empty()) {
+ String tween_id;
+ Node *node = get_bound_node();
+ if (node) {
+ tween_id = vformat("Tween (bound to %s)", node->is_inside_tree() ? (String)node->get_path() : (String)node->get_name());
+ } else {
+ tween_id = to_string();
+ }
+ ERR_FAIL_V_MSG(false, tween_id + ": started with no Tweeners.");
+ }
current_step = 0;
loops_done = 0;
total_time = 0;
- start_tweeners();
+ _start_tweeners();
started = true;
}
@@ -319,7 +334,7 @@ bool Tween::step(double p_delta) {
} else {
emit_signal(SNAME("loop_finished"), loops_done);
current_step = 0;
- start_tweeners();
+ _start_tweeners();
#ifdef DEBUG_ENABLED
if (loops <= 0 && Math::is_equal_approx(rem_delta, initial_delta)) {
if (!potential_infinite) {
@@ -332,7 +347,7 @@ bool Tween::step(double p_delta) {
#endif
}
} else {
- start_tweeners();
+ _start_tweeners();
}
}
}
@@ -387,6 +402,15 @@ Variant Tween::interpolate_variant(Variant p_initial_val, Variant p_delta_val, d
return ret;
}
+String Tween::to_string() {
+ String ret = Object::to_string();
+ Node *node = get_bound_node();
+ if (node) {
+ ret += vformat(" (bound to %s)", node->get_name());
+ }
+ return ret;
+}
+
void Tween::_bind_methods() {
ClassDB::bind_method(D_METHOD("tween_property", "object", "property", "final_val", "duration"), &Tween::tween_property);
ClassDB::bind_method(D_METHOD("tween_interval", "time"), &Tween::tween_interval);
@@ -570,7 +594,7 @@ PropertyTweener::PropertyTweener(Object *p_target, NodePath p_property, Variant
}
PropertyTweener::PropertyTweener() {
- ERR_FAIL_MSG("Can't create empty PropertyTweener. Use get_tree().tween_property() or tween_property() instead.");
+ ERR_FAIL_MSG("PropertyTweener can't be created directly. Use the tween_property() method in Tween.");
}
void IntervalTweener::start() {
@@ -601,7 +625,7 @@ IntervalTweener::IntervalTweener(double p_time) {
}
IntervalTweener::IntervalTweener() {
- ERR_FAIL_MSG("Can't create empty IntervalTweener. Use get_tree().tween_interval() instead.");
+ ERR_FAIL_MSG("IntervalTweener can't be created directly. Use the tween_interval() method in Tween.");
}
Ref<CallbackTweener> CallbackTweener::set_delay(double p_delay) {
@@ -652,7 +676,7 @@ CallbackTweener::CallbackTweener(Callable p_callback) {
}
CallbackTweener::CallbackTweener() {
- ERR_FAIL_MSG("Can't create empty CallbackTweener. Use get_tree().tween_callback() instead.");
+ ERR_FAIL_MSG("CallbackTweener can't be created directly. Use the tween_callback() method in Tween.");
}
Ref<MethodTweener> MethodTweener::set_delay(double p_delay) {
@@ -745,5 +769,5 @@ MethodTweener::MethodTweener(Callable p_callback, Variant p_from, Variant p_to,
}
MethodTweener::MethodTweener() {
- ERR_FAIL_MSG("Can't create empty MethodTweener. Use get_tree().tween_method() instead.");
+ ERR_FAIL_MSG("MethodTweener can't be created directly. Use the tween_method() method in Tween.");
}
diff --git a/scene/animation/tween.h b/scene/animation/tween.h
index 8f65416e71..58217db535 100644
--- a/scene/animation/tween.h
+++ b/scene/animation/tween.h
@@ -123,12 +123,15 @@ private:
typedef real_t (*interpolater)(real_t t, real_t b, real_t c, real_t d);
static interpolater interpolaters[TRANS_MAX][EASE_MAX];
- void start_tweeners();
+ void _start_tweeners();
+ void _stop_internal(bool p_reset);
protected:
static void _bind_methods();
public:
+ virtual String to_string() override;
+
Ref<PropertyTweener> tween_property(Object *p_target, NodePath p_property, Variant p_to, double p_duration);
Ref<IntervalTweener> tween_interval(double p_time);
Ref<CallbackTweener> tween_callback(Callable p_callback);
diff --git a/scene/audio/audio_stream_player.cpp b/scene/audio/audio_stream_player.cpp
index 42f76068e7..7533a56b59 100644
--- a/scene/audio/audio_stream_player.cpp
+++ b/scene/audio/audio_stream_player.cpp
@@ -307,11 +307,13 @@ void AudioStreamPlayer::_bus_layout_changed() {
notify_property_list_changed();
}
+bool AudioStreamPlayer::has_stream_playback() {
+ return !stream_playbacks.is_empty();
+}
+
Ref<AudioStreamPlayback> AudioStreamPlayer::get_stream_playback() {
- if (!stream_playbacks.is_empty()) {
- return stream_playbacks[stream_playbacks.size() - 1];
- }
- return nullptr;
+ ERR_FAIL_COND_V_MSG(stream_playbacks.is_empty(), Ref<AudioStreamPlayback>(), "Player is inactive. Call play() before requesting get_stream_playback().");
+ return stream_playbacks[stream_playbacks.size() - 1];
}
void AudioStreamPlayer::_bind_methods() {
@@ -349,6 +351,7 @@ void AudioStreamPlayer::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_max_polyphony", "max_polyphony"), &AudioStreamPlayer::set_max_polyphony);
ClassDB::bind_method(D_METHOD("get_max_polyphony"), &AudioStreamPlayer::get_max_polyphony);
+ ClassDB::bind_method(D_METHOD("has_stream_playback"), &AudioStreamPlayer::has_stream_playback);
ClassDB::bind_method(D_METHOD("get_stream_playback"), &AudioStreamPlayer::get_stream_playback);
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "stream", PROPERTY_HINT_RESOURCE_TYPE, "AudioStream"), "set_stream", "get_stream");
diff --git a/scene/audio/audio_stream_player.h b/scene/audio/audio_stream_player.h
index 5368391073..d1f6fca2ee 100644
--- a/scene/audio/audio_stream_player.h
+++ b/scene/audio/audio_stream_player.h
@@ -107,6 +107,7 @@ public:
void set_stream_paused(bool p_pause);
bool get_stream_paused() const;
+ bool has_stream_playback();
Ref<AudioStreamPlayback> get_stream_playback();
AudioStreamPlayer();
diff --git a/scene/gui/base_button.cpp b/scene/gui/base_button.cpp
index 4c27cf4b21..c26a00221a 100644
--- a/scene/gui/base_button.cpp
+++ b/scene/gui/base_button.cpp
@@ -30,6 +30,7 @@
#include "base_button.h"
+#include "core/config/project_settings.h"
#include "core/os/keyboard.h"
#include "scene/main/window.h"
#include "scene/scene_string_names.h"
@@ -62,7 +63,7 @@ void BaseButton::gui_input(const Ref<InputEvent> &p_event) {
Ref<InputEventMouseButton> mouse_button = p_event;
bool ui_accept = p_event->is_action("ui_accept", true) && !p_event->is_echo();
- bool button_masked = mouse_button.is_valid() && (mouse_button_to_mask(mouse_button->get_button_index()) & button_mask) != MouseButton::NONE;
+ bool button_masked = mouse_button.is_valid() && button_mask.has_flag(mouse_button_to_mask(mouse_button->get_button_index()));
if (button_masked || ui_accept) {
was_mouse_pressed = button_masked;
on_action_event(p_event);
@@ -127,7 +128,6 @@ void BaseButton::_notification(int p_what) {
status.hovering = false;
status.press_attempt = false;
status.pressing_inside = false;
- status.shortcut_press = false;
} break;
}
}
@@ -154,14 +154,10 @@ void BaseButton::on_action_event(Ref<InputEvent> p_event) {
if (status.press_attempt && status.pressing_inside) {
if (toggle_mode) {
bool is_pressed = p_event->is_pressed();
- if (Object::cast_to<InputEventShortcut>(*p_event)) {
- is_pressed = false;
- }
if ((is_pressed && action_mode == ACTION_MODE_BUTTON_PRESS) || (!is_pressed && action_mode == ACTION_MODE_BUTTON_RELEASE)) {
if (action_mode == ACTION_MODE_BUTTON_PRESS) {
status.press_attempt = false;
status.pressing_inside = false;
- status.shortcut_press = false;
}
status.pressed = !status.pressed;
_unpress_group();
@@ -187,7 +183,6 @@ void BaseButton::on_action_event(Ref<InputEvent> p_event) {
}
status.press_attempt = false;
status.pressing_inside = false;
- status.shortcut_press = false;
emit_signal(SNAME("button_up"));
}
@@ -212,7 +207,6 @@ void BaseButton::set_disabled(bool p_disabled) {
}
status.press_attempt = false;
status.pressing_inside = false;
- status.shortcut_press = false;
}
queue_redraw();
}
@@ -267,6 +261,10 @@ BaseButton::DrawMode BaseButton::get_draw_mode() const {
return DRAW_DISABLED;
}
+ if (in_shortcut_feedback) {
+ return DRAW_HOVER_PRESSED;
+ }
+
if (!status.press_attempt && status.hovering) {
if (status.pressed) {
return DRAW_HOVER_PRESSED;
@@ -285,7 +283,7 @@ BaseButton::DrawMode BaseButton::get_draw_mode() const {
pressing = status.pressed;
}
- if ((shortcut_feedback || !status.shortcut_press) && pressing) {
+ if (pressing) {
return DRAW_PRESSED;
} else {
return DRAW_NORMAL;
@@ -323,11 +321,11 @@ BaseButton::ActionMode BaseButton::get_action_mode() const {
return action_mode;
}
-void BaseButton::set_button_mask(MouseButton p_mask) {
+void BaseButton::set_button_mask(BitField<MouseButtonMask> p_mask) {
button_mask = p_mask;
}
-MouseButton BaseButton::get_button_mask() const {
+BitField<MouseButtonMask> BaseButton::get_button_mask() const {
return button_mask;
}
@@ -339,6 +337,14 @@ bool BaseButton::is_keep_pressed_outside() const {
return keep_pressed_outside;
}
+void BaseButton::set_shortcut_feedback(bool p_enable) {
+ shortcut_feedback = p_enable;
+}
+
+bool BaseButton::is_shortcut_feedback() const {
+ return shortcut_feedback;
+}
+
void BaseButton::set_shortcut(const Ref<Shortcut> &p_shortcut) {
shortcut = p_shortcut;
set_process_shortcut_input(shortcut.is_valid());
@@ -348,13 +354,46 @@ Ref<Shortcut> BaseButton::get_shortcut() const {
return shortcut;
}
+void BaseButton::_shortcut_feedback_timeout() {
+ in_shortcut_feedback = false;
+ queue_redraw();
+}
+
void BaseButton::shortcut_input(const Ref<InputEvent> &p_event) {
ERR_FAIL_COND(p_event.is_null());
- if (!is_disabled() && is_visible_in_tree() && !p_event->is_echo() && shortcut.is_valid() && shortcut->matches_event(p_event)) {
- status.shortcut_press = true;
- on_action_event(p_event);
+ if (!is_disabled() && p_event->is_pressed() && is_visible_in_tree() && !p_event->is_echo() && shortcut.is_valid() && shortcut->matches_event(p_event)) {
+ if (toggle_mode) {
+ status.pressed = !status.pressed;
+
+ if (status.pressed) {
+ _unpress_group();
+ if (button_group.is_valid()) {
+ button_group->emit_signal(SNAME("pressed"), this);
+ }
+ }
+
+ _toggled(status.pressed);
+ _pressed();
+
+ } else {
+ _pressed();
+ }
+ queue_redraw();
accept_event();
+
+ if (shortcut_feedback) {
+ if (shortcut_feedback_timer == nullptr) {
+ shortcut_feedback_timer = memnew(Timer);
+ shortcut_feedback_timer->set_one_shot(true);
+ add_child(shortcut_feedback_timer);
+ shortcut_feedback_timer->set_wait_time(GLOBAL_GET("gui/timers/button_shortcut_feedback_highlight_time"));
+ shortcut_feedback_timer->connect("timeout", callable_mp(this, &BaseButton::_shortcut_feedback_timeout));
+ }
+
+ in_shortcut_feedback = true;
+ shortcut_feedback_timer->start();
+ }
}
}
@@ -393,14 +432,6 @@ bool BaseButton::_was_pressed_by_mouse() const {
return was_mouse_pressed;
}
-void BaseButton::set_shortcut_feedback(bool p_feedback) {
- shortcut_feedback = p_feedback;
-}
-
-bool BaseButton::is_shortcut_feedback() const {
- return shortcut_feedback;
-}
-
PackedStringArray BaseButton::get_configuration_warnings() const {
PackedStringArray warnings = Control::get_configuration_warnings();
@@ -429,6 +460,8 @@ void BaseButton::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_draw_mode"), &BaseButton::get_draw_mode);
ClassDB::bind_method(D_METHOD("set_keep_pressed_outside", "enabled"), &BaseButton::set_keep_pressed_outside);
ClassDB::bind_method(D_METHOD("is_keep_pressed_outside"), &BaseButton::is_keep_pressed_outside);
+ ClassDB::bind_method(D_METHOD("set_shortcut_feedback", "enabled"), &BaseButton::set_shortcut_feedback);
+ ClassDB::bind_method(D_METHOD("is_shortcut_feedback"), &BaseButton::is_shortcut_feedback);
ClassDB::bind_method(D_METHOD("set_shortcut", "shortcut"), &BaseButton::set_shortcut);
ClassDB::bind_method(D_METHOD("get_shortcut"), &BaseButton::get_shortcut);
@@ -436,9 +469,6 @@ void BaseButton::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_button_group", "button_group"), &BaseButton::set_button_group);
ClassDB::bind_method(D_METHOD("get_button_group"), &BaseButton::get_button_group);
- ClassDB::bind_method(D_METHOD("set_shortcut_feedback", "enabled"), &BaseButton::set_shortcut_feedback);
- ClassDB::bind_method(D_METHOD("is_shortcut_feedback"), &BaseButton::is_shortcut_feedback);
-
GDVIRTUAL_BIND(_pressed);
GDVIRTUAL_BIND(_toggled, "button_pressed");
@@ -449,14 +479,16 @@ void BaseButton::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "disabled"), "set_disabled", "is_disabled");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "toggle_mode"), "set_toggle_mode", "is_toggle_mode");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL, "shortcut_in_tooltip"), "set_shortcut_in_tooltip", "is_shortcut_in_tooltip_enabled");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "button_pressed"), "set_pressed", "is_pressed");
ADD_PROPERTY(PropertyInfo(Variant::INT, "action_mode", PROPERTY_HINT_ENUM, "Button Press,Button Release"), "set_action_mode", "get_action_mode");
ADD_PROPERTY(PropertyInfo(Variant::INT, "button_mask", PROPERTY_HINT_FLAGS, "Mouse Left, Mouse Right, Mouse Middle"), "set_button_mask", "get_button_mask");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "keep_pressed_outside"), "set_keep_pressed_outside", "is_keep_pressed_outside");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "button_group", PROPERTY_HINT_RESOURCE_TYPE, "ButtonGroup"), "set_button_group", "get_button_group");
+
+ ADD_GROUP("Shortcut", "");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "shortcut", PROPERTY_HINT_RESOURCE_TYPE, "Shortcut"), "set_shortcut", "get_shortcut");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "shortcut_feedback"), "set_shortcut_feedback", "is_shortcut_feedback");
- ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "button_group", PROPERTY_HINT_RESOURCE_TYPE, "ButtonGroup"), "set_button_group", "get_button_group");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "shortcut_in_tooltip"), "set_shortcut_in_tooltip", "is_shortcut_in_tooltip_enabled");
BIND_ENUM_CONSTANT(DRAW_NORMAL);
BIND_ENUM_CONSTANT(DRAW_PRESSED);
@@ -466,6 +498,8 @@ void BaseButton::_bind_methods() {
BIND_ENUM_CONSTANT(ACTION_MODE_BUTTON_PRESS);
BIND_ENUM_CONSTANT(ACTION_MODE_BUTTON_RELEASE);
+
+ GLOBAL_DEF(PropertyInfo(Variant::FLOAT, "gui/timers/button_shortcut_feedback_highlight_time", PROPERTY_HINT_RANGE, "0.01,10,0.01,suffix:s"), 0.2);
}
BaseButton::BaseButton() {
diff --git a/scene/gui/base_button.h b/scene/gui/base_button.h
index d7e6b68517..962a16c453 100644
--- a/scene/gui/base_button.h
+++ b/scene/gui/base_button.h
@@ -46,14 +46,14 @@ public:
};
private:
- MouseButton button_mask = MouseButton::MASK_LEFT;
+ BitField<MouseButtonMask> button_mask = MouseButtonMask::LEFT;
bool toggle_mode = false;
bool shortcut_in_tooltip = true;
bool was_mouse_pressed = false;
bool keep_pressed_outside = false;
+ bool shortcut_feedback = true;
Ref<Shortcut> shortcut;
ObjectID shortcut_context;
- bool shortcut_feedback = true;
ActionMode action_mode = ACTION_MODE_BUTTON_RELEASE;
struct Status {
@@ -61,7 +61,6 @@ private:
bool hovering = false;
bool press_attempt = false;
bool pressing_inside = false;
- bool shortcut_press = false;
bool disabled = false;
@@ -75,6 +74,10 @@ private:
void on_action_event(Ref<InputEvent> p_event);
+ Timer *shortcut_feedback_timer = nullptr;
+ bool in_shortcut_feedback = false;
+ void _shortcut_feedback_timeout();
+
protected:
virtual void pressed();
virtual void toggled(bool p_pressed);
@@ -122,8 +125,11 @@ public:
void set_keep_pressed_outside(bool p_on);
bool is_keep_pressed_outside() const;
- void set_button_mask(MouseButton p_mask);
- MouseButton get_button_mask() const;
+ void set_shortcut_feedback(bool p_enable);
+ bool is_shortcut_feedback() const;
+
+ void set_button_mask(BitField<MouseButtonMask> p_mask);
+ BitField<MouseButtonMask> get_button_mask() const;
void set_shortcut(const Ref<Shortcut> &p_shortcut);
Ref<Shortcut> get_shortcut() const;
@@ -133,9 +139,6 @@ public:
void set_button_group(const Ref<ButtonGroup> &p_group);
Ref<ButtonGroup> get_button_group() const;
- void set_shortcut_feedback(bool p_feedback);
- bool is_shortcut_feedback() const;
-
PackedStringArray get_configuration_warnings() const override;
BaseButton();
diff --git a/scene/gui/box_container.cpp b/scene/gui/box_container.cpp
index 1e75659a8c..97729b1ac5 100644
--- a/scene/gui/box_container.cpp
+++ b/scene/gui/box_container.cpp
@@ -68,12 +68,12 @@ void BoxContainer::_resort() {
if (vertical) { /* VERTICAL */
stretch_min += size.height;
msc.min_size = size.height;
- msc.will_stretch = c->get_v_size_flags() & SIZE_EXPAND;
+ msc.will_stretch = c->get_v_size_flags().has_flag(SIZE_EXPAND);
} else { /* HORIZONTAL */
stretch_min += size.width;
msc.min_size = size.width;
- msc.will_stretch = c->get_h_size_flags() & SIZE_EXPAND;
+ msc.will_stretch = c->get_h_size_flags().has_flag(SIZE_EXPAND);
}
if (msc.will_stretch) {
diff --git a/scene/gui/button.cpp b/scene/gui/button.cpp
index 46764b64b2..2a8b1cd8c4 100644
--- a/scene/gui/button.cpp
+++ b/scene/gui/button.cpp
@@ -572,12 +572,16 @@ void Button::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_expand_icon", "enabled"), &Button::set_expand_icon);
ClassDB::bind_method(D_METHOD("is_expand_icon"), &Button::is_expand_icon);
- ADD_PROPERTY(PropertyInfo(Variant::STRING, "text", PROPERTY_HINT_MULTILINE_TEXT, "", PROPERTY_USAGE_DEFAULT_INTL), "set_text", "get_text");
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "text", PROPERTY_HINT_MULTILINE_TEXT), "set_text", "get_text");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "icon", PROPERTY_HINT_RESOURCE_TYPE, "Texture2D"), "set_button_icon", "get_button_icon");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "flat"), "set_flat", "is_flat");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL, "clip_text"), "set_clip_text", "get_clip_text");
+
+ ADD_GROUP("Text Behavior", "");
ADD_PROPERTY(PropertyInfo(Variant::INT, "alignment", PROPERTY_HINT_ENUM, "Left,Center,Right"), "set_text_alignment", "get_text_alignment");
ADD_PROPERTY(PropertyInfo(Variant::INT, "text_overrun_behavior", PROPERTY_HINT_ENUM, "Trim Nothing,Trim Characters,Trim Words,Ellipsis,Word Ellipsis"), "set_text_overrun_behavior", "get_text_overrun_behavior");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "clip_text"), "set_clip_text", "get_clip_text");
+
+ ADD_GROUP("Icon Behavior", "");
ADD_PROPERTY(PropertyInfo(Variant::INT, "icon_alignment", PROPERTY_HINT_ENUM, "Left,Center,Right"), "set_icon_alignment", "get_icon_alignment");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "expand_icon"), "set_expand_icon", "is_expand_icon");
diff --git a/scene/gui/code_edit.cpp b/scene/gui/code_edit.cpp
index 274d4d981a..b084cb5bea 100644
--- a/scene/gui/code_edit.cpp
+++ b/scene/gui/code_edit.cpp
@@ -380,13 +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) {
+ if (mm->is_command_or_control_pressed() && mm->get_button_mask().is_empty()) {
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 if (!mm->is_command_or_control_pressed() || (mm->get_button_mask() != MouseButton::NONE && symbol_lookup_pos != get_line_column_at_pos(mpos))) {
+ } else if (!mm->is_command_or_control_pressed() || (!mm->get_button_mask().is_empty() && symbol_lookup_pos != get_line_column_at_pos(mpos))) {
set_symbol_lookup_word_as_valid(false);
}
}
@@ -548,7 +548,7 @@ void CodeEdit::gui_input(const Ref<InputEvent> &p_gui_input) {
}
if (k->is_action("ui_text_dedent", true)) {
- do_unindent();
+ unindent_lines();
accept_event();
return;
}
@@ -898,50 +898,6 @@ void CodeEdit::indent_lines() {
end_complex_operation();
}
-void CodeEdit::do_unindent() {
- if (!is_editable()) {
- return;
- }
-
- int cc = get_caret_column();
-
- if (has_selection() || cc <= 0) {
- unindent_lines();
- return;
- }
-
- begin_complex_operation();
- Vector<int> caret_edit_order = get_caret_index_edit_order();
- for (const int &c : caret_edit_order) {
- int cl = get_caret_line(c);
- const String &line = get_line(cl);
-
- if (line[cc - 1] == '\t') {
- remove_text(cl, cc - 1, cl, cc);
- set_caret_column(MAX(0, cc - 1), c == 0, c);
- adjust_carets_after_edit(c, cl, cc, cl, cc - 1);
- continue;
- }
-
- if (line[cc - 1] != ' ') {
- continue;
- }
-
- int spaces_to_remove = _calculate_spaces_till_next_left_indent(cc);
- if (spaces_to_remove > 0) {
- for (int i = 1; i <= spaces_to_remove; i++) {
- if (line[cc - i] != ' ') {
- spaces_to_remove = i - 1;
- break;
- }
- }
- remove_text(cl, cc - spaces_to_remove, cl, cc);
- set_caret_column(MAX(0, cc - spaces_to_remove), c == 0, c);
- }
- }
- end_complex_operation();
-}
-
void CodeEdit::unindent_lines() {
if (!is_editable()) {
return;
@@ -2086,9 +2042,11 @@ void CodeEdit::confirm_code_completion(bool p_replace) {
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;
// 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);
+ if (has_string_delimiter(String::chr(last_completion_char))) {
+ if (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 (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);
@@ -2202,7 +2160,6 @@ void CodeEdit::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_auto_indent_prefixes"), &CodeEdit::get_auto_indent_prefixes);
ClassDB::bind_method(D_METHOD("do_indent"), &CodeEdit::do_indent);
- ClassDB::bind_method(D_METHOD("do_unindent"), &CodeEdit::do_unindent);
ClassDB::bind_method(D_METHOD("indent_lines"), &CodeEdit::indent_lines);
ClassDB::bind_method(D_METHOD("unindent_lines"), &CodeEdit::unindent_lines);
@@ -2338,7 +2295,7 @@ void CodeEdit::_bind_methods() {
ClassDB::bind_method(D_METHOD("is_code_completion_enabled"), &CodeEdit::is_code_completion_enabled);
ClassDB::bind_method(D_METHOD("set_code_completion_prefixes", "prefixes"), &CodeEdit::set_code_completion_prefixes);
- ClassDB::bind_method(D_METHOD("get_code_comletion_prefixes"), &CodeEdit::get_code_completion_prefixes);
+ ClassDB::bind_method(D_METHOD("get_code_completion_prefixes"), &CodeEdit::get_code_completion_prefixes);
// Overridable
@@ -2382,7 +2339,7 @@ void CodeEdit::_bind_methods() {
ADD_GROUP("Code Completion", "code_completion_");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "code_completion_enabled"), "set_code_completion_enabled", "is_code_completion_enabled");
- ADD_PROPERTY(PropertyInfo(Variant::PACKED_STRING_ARRAY, "code_completion_prefixes"), "set_code_completion_prefixes", "get_code_comletion_prefixes");
+ ADD_PROPERTY(PropertyInfo(Variant::PACKED_STRING_ARRAY, "code_completion_prefixes"), "set_code_completion_prefixes", "get_code_completion_prefixes");
ADD_GROUP("Indentation", "indent_");
ADD_PROPERTY(PropertyInfo(Variant::INT, "indent_size"), "set_indent_size", "get_indent_size");
@@ -2899,6 +2856,7 @@ void CodeEdit::_filter_code_completion_candidates_impl() {
const int caret_line = get_caret_line();
const int caret_column = get_caret_column();
const String line = get_line(caret_line);
+ ERR_FAIL_INDEX_MSG(caret_column - 1, line.length(), "Caret column exceeds line length.");
if (caret_column > 0 && line[caret_column - 1] == '(' && !code_completion_forced) {
cancel_code_completion();
@@ -3130,6 +3088,8 @@ void CodeEdit::_filter_code_completion_candidates_impl() {
}
code_completion_options.append_array(completion_options_casei);
+ code_completion_options.append_array(completion_options_substr);
+ code_completion_options.append_array(completion_options_substr_casei);
code_completion_options.append_array(completion_options_subseq);
code_completion_options.append_array(completion_options_subseq_casei);
diff --git a/scene/gui/code_edit.h b/scene/gui/code_edit.h
index c050b2266f..55fc5aa2ae 100644
--- a/scene/gui/code_edit.h
+++ b/scene/gui/code_edit.h
@@ -289,7 +289,6 @@ public:
TypedArray<String> get_auto_indent_prefixes() const;
void do_indent();
- void do_unindent();
void indent_lines();
void unindent_lines();
diff --git a/scene/gui/color_picker.cpp b/scene/gui/color_picker.cpp
index 944363bcb0..da29bc823f 100644
--- a/scene/gui/color_picker.cpp
+++ b/scene/gui/color_picker.cpp
@@ -35,11 +35,6 @@
#include "core/os/keyboard.h"
#include "core/os/os.h"
#include "scene/gui/color_mode.h"
-
-#ifdef TOOLS_ENABLED
-#include "editor/editor_settings.h"
-#endif
-
#include "thirdparty/misc/ok_color.h"
#include "thirdparty/misc/ok_color_shader.h"
@@ -50,31 +45,6 @@ void ColorPicker::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
_update_color();
-#ifdef TOOLS_ENABLED
- if (Engine::get_singleton()->is_editor_hint()) {
- if (preset_cache.is_empty()) {
- PackedColorArray saved_presets = EditorSettings::get_singleton()->get_project_metadata("color_picker", "presets", PackedColorArray());
- for (int i = 0; i < saved_presets.size(); i++) {
- preset_cache.push_back(saved_presets[i]);
- }
- }
-
- for (int i = 0; i < preset_cache.size(); i++) {
- presets.push_back(preset_cache[i]);
- }
-
- if (recent_preset_cache.is_empty()) {
- PackedColorArray saved_recent_presets = EditorSettings::get_singleton()->get_project_metadata("color_picker", "recent_presets", PackedColorArray());
- for (int i = 0; i < saved_recent_presets.size(); i++) {
- recent_preset_cache.push_back(saved_recent_presets[i]);
- }
- }
-
- for (int i = 0; i < recent_preset_cache.size(); i++) {
- recent_presets.push_back(recent_preset_cache[i]);
- }
- }
-#endif
[[fallthrough]];
}
case NOTIFICATION_THEME_CHANGED: {
@@ -404,6 +374,40 @@ void ColorPicker::create_slider(GridContainer *gc, int idx) {
}
}
+#ifdef TOOLS_ENABLED
+void ColorPicker::set_editor_settings(Object *p_editor_settings) {
+ if (editor_settings) {
+ return;
+ }
+ editor_settings = p_editor_settings;
+
+ if (preset_cache.is_empty()) {
+ PackedColorArray saved_presets = editor_settings->call(SNAME("get_project_metadata"), "color_picker", "presets", PackedColorArray());
+ for (int i = 0; i < saved_presets.size(); i++) {
+ preset_cache.push_back(saved_presets[i]);
+ }
+ }
+
+ for (int i = 0; i < preset_cache.size(); i++) {
+ presets.push_back(preset_cache[i]);
+ }
+
+ if (recent_preset_cache.is_empty()) {
+ PackedColorArray saved_recent_presets = editor_settings->call(SNAME("get_project_metadata"), "color_picker", "recent_presets", PackedColorArray());
+ for (int i = 0; i < saved_recent_presets.size(); i++) {
+ recent_preset_cache.push_back(saved_recent_presets[i]);
+ }
+ }
+
+ for (int i = 0; i < recent_preset_cache.size(); i++) {
+ recent_presets.push_back(recent_preset_cache[i]);
+ }
+
+ _update_presets();
+ _update_recent_presets();
+}
+#endif
+
HSlider *ColorPicker::get_slider(int p_idx) {
if (p_idx < SLIDER_COUNT) {
return sliders[p_idx];
@@ -471,7 +475,7 @@ ColorPicker::PickerShapeType ColorPicker::_get_actual_shape() const {
void ColorPicker::_reset_theme() {
Ref<StyleBoxFlat> style_box_flat(memnew(StyleBoxFlat));
- style_box_flat->set_default_margin(SIDE_TOP, 16 * get_theme_default_base_scale());
+ style_box_flat->set_content_margin(SIDE_TOP, 16 * get_theme_default_base_scale());
style_box_flat->set_bg_color(Color(0.2, 0.23, 0.31).lerp(Color(0, 0, 0, 1), 0.3).clamp());
for (int i = 0; i < SLIDER_COUNT; i++) {
sliders[i]->add_theme_icon_override("grabber", get_theme_icon(SNAME("bar_arrow"), SNAME("ColorPicker")));
@@ -553,7 +557,7 @@ void ColorPicker::_update_presets() {
}
#ifdef TOOLS_ENABLED
- if (Engine::get_singleton()->is_editor_hint()) {
+ if (editor_settings) {
// Only load preset buttons when the only child is the add-preset button.
if (preset_container->get_child_count() == 1) {
for (int i = 0; i < preset_cache.size(); i++) {
@@ -567,7 +571,7 @@ void ColorPicker::_update_presets() {
void ColorPicker::_update_recent_presets() {
#ifdef TOOLS_ENABLED
- if (Engine::get_singleton()->is_editor_hint()) {
+ if (editor_settings) {
int recent_preset_count = recent_preset_hbc->get_child_count();
for (int i = 0; i < recent_preset_count; i++) {
memdelete(recent_preset_hbc->get_child(0));
@@ -642,7 +646,7 @@ inline int ColorPicker::_get_preset_size() {
void ColorPicker::_add_preset_button(int p_size, const Color &p_color) {
ColorPresetButton *btn_preset_new = memnew(ColorPresetButton(p_color, p_size));
btn_preset_new->set_tooltip_text(vformat(RTR("Color: #%s\nLMB: Apply color\nRMB: Remove preset"), p_color.to_html(p_color.a < 1)));
- btn_preset_new->set_drag_forwarding(this);
+ SET_DRAG_FORWARDING_GCDU(btn_preset_new, ColorPicker);
btn_preset_new->set_button_group(preset_group);
preset_container->add_child(btn_preset_new);
btn_preset_new->set_pressed(true);
@@ -743,9 +747,9 @@ void ColorPicker::add_preset(const Color &p_color) {
}
#ifdef TOOLS_ENABLED
- if (Engine::get_singleton()->is_editor_hint()) {
+ if (editor_settings) {
PackedColorArray arr_to_save = get_presets();
- EditorSettings::get_singleton()->set_project_metadata("color_picker", "presets", arr_to_save);
+ editor_settings->call(SNAME("set_project_metadata"), "color_picker", "presets", arr_to_save);
}
#endif
}
@@ -764,9 +768,9 @@ void ColorPicker::add_recent_preset(const Color &p_color) {
_select_from_preset_container(p_color);
#ifdef TOOLS_ENABLED
- if (Engine::get_singleton()->is_editor_hint()) {
+ if (editor_settings) {
PackedColorArray arr_to_save = get_recent_presets();
- EditorSettings::get_singleton()->set_project_metadata("color_picker", "recent_presets", arr_to_save);
+ editor_settings->call(SNAME("set_project_metadata"), "color_picker", "recent_presets", arr_to_save);
}
#endif
}
@@ -787,9 +791,9 @@ void ColorPicker::erase_preset(const Color &p_color) {
}
#ifdef TOOLS_ENABLED
- if (Engine::get_singleton()->is_editor_hint()) {
+ if (editor_settings) {
PackedColorArray arr_to_save = get_presets();
- EditorSettings::get_singleton()->set_project_metadata("color_picker", "presets", arr_to_save);
+ editor_settings->call(SNAME("set_project_metadata"), "color_picker", "presets", arr_to_save);
}
#endif
}
@@ -811,9 +815,9 @@ void ColorPicker::erase_recent_preset(const Color &p_color) {
}
#ifdef TOOLS_ENABLED
- if (Engine::get_singleton()->is_editor_hint()) {
+ if (editor_settings) {
PackedColorArray arr_to_save = get_recent_presets();
- EditorSettings::get_singleton()->set_project_metadata("color_picker", "recent_presets", arr_to_save);
+ editor_settings->call(SNAME("set_project_metadata"), "color_picker", "recent_presets", arr_to_save);
}
#endif
}
@@ -890,7 +894,7 @@ void ColorPicker::set_colorize_sliders(bool p_colorize_sliders) {
alpha_slider->add_theme_style_override("slider", style_box_empty);
} else {
Ref<StyleBoxFlat> style_box_flat(memnew(StyleBoxFlat));
- style_box_flat->set_default_margin(SIDE_TOP, 16 * get_theme_default_base_scale());
+ style_box_flat->set_content_margin(SIDE_TOP, 16 * get_theme_default_base_scale());
style_box_flat->set_bg_color(Color(0.2, 0.23, 0.31).lerp(Color(0, 0, 0, 1), 0.3).clamp());
if (!slider_theme_modified) {
@@ -1544,10 +1548,6 @@ void ColorPicker::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_picker_shape", "shape"), &ColorPicker::set_picker_shape);
ClassDB::bind_method(D_METHOD("get_picker_shape"), &ColorPicker::get_picker_shape);
- ClassDB::bind_method(D_METHOD("_get_drag_data_fw"), &ColorPicker::_get_drag_data_fw);
- ClassDB::bind_method(D_METHOD("_can_drop_data_fw"), &ColorPicker::_can_drop_data_fw);
- ClassDB::bind_method(D_METHOD("_drop_data_fw"), &ColorPicker::_drop_data_fw);
-
ADD_PROPERTY(PropertyInfo(Variant::COLOR, "color"), "set_pick_color", "get_pick_color");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "edit_alpha"), "set_edit_alpha", "is_editing_alpha");
ADD_PROPERTY(PropertyInfo(Variant::INT, "color_mode", PROPERTY_HINT_ENUM, "RGB,HSV,RAW,OKHSL"), "set_color_mode", "get_color_mode");
diff --git a/scene/gui/color_picker.h b/scene/gui/color_picker.h
index 5eaeecca2a..f7578612cd 100644
--- a/scene/gui/color_picker.h
+++ b/scene/gui/color_picker.h
@@ -100,6 +100,10 @@ private:
static List<Color> preset_cache;
static List<Color> recent_preset_cache;
+#ifdef TOOLS_ENABLED
+ Object *editor_settings = nullptr;
+#endif
+
int current_slider_count = SLIDER_COUNT;
static const int MODE_BUTTON_COUNT = 3;
@@ -231,6 +235,10 @@ protected:
static void _bind_methods();
public:
+#ifdef TOOLS_ENABLED
+ void set_editor_settings(Object *p_editor_settings);
+#endif
+
HSlider *get_slider(int idx);
Vector<float> get_active_slider_values();
diff --git a/scene/gui/container.cpp b/scene/gui/container.cpp
index 8d25195199..145074a626 100644
--- a/scene/gui/container.cpp
+++ b/scene/gui/container.cpp
@@ -104,22 +104,22 @@ void Container::fit_child_in_rect(Control *p_child, const Rect2 &p_rect) {
Size2 minsize = p_child->get_combined_minimum_size();
Rect2 r = p_rect;
- if (!(p_child->get_h_size_flags() & SIZE_FILL)) {
+ if (!(p_child->get_h_size_flags().has_flag(SIZE_FILL))) {
r.size.x = minsize.width;
- if (p_child->get_h_size_flags() & SIZE_SHRINK_END) {
+ if (p_child->get_h_size_flags().has_flag(SIZE_SHRINK_END)) {
r.position.x += rtl ? 0 : (p_rect.size.width - minsize.width);
- } else if (p_child->get_h_size_flags() & SIZE_SHRINK_CENTER) {
+ } else if (p_child->get_h_size_flags().has_flag(SIZE_SHRINK_CENTER)) {
r.position.x += Math::floor((p_rect.size.x - minsize.width) / 2);
} else {
r.position.x += rtl ? (p_rect.size.width - minsize.width) : 0;
}
}
- if (!(p_child->get_v_size_flags() & SIZE_FILL)) {
+ if (!(p_child->get_v_size_flags().has_flag(SIZE_FILL))) {
r.size.y = minsize.y;
- if (p_child->get_v_size_flags() & SIZE_SHRINK_END) {
+ if (p_child->get_v_size_flags().has_flag(SIZE_SHRINK_END)) {
r.position.y += p_rect.size.height - minsize.height;
- } else if (p_child->get_v_size_flags() & SIZE_SHRINK_CENTER) {
+ } else if (p_child->get_v_size_flags().has_flag(SIZE_SHRINK_CENTER)) {
r.position.y += Math::floor((p_rect.size.y - minsize.height) / 2);
} else {
r.position.y += 0;
diff --git a/scene/gui/control.cpp b/scene/gui/control.cpp
index 64d1d38abb..ec75fcb665 100644
--- a/scene/gui/control.cpp
+++ b/scene/gui/control.cpp
@@ -105,7 +105,7 @@ void Control::_edit_set_state(const Dictionary &p_state) {
}
_set_layout_mode(_layout);
- if (_layout == LayoutMode::LAYOUT_MODE_ANCHORS) {
+ if (_layout == LayoutMode::LAYOUT_MODE_ANCHORS || _layout == LayoutMode::LAYOUT_MODE_UNCONTROLLED) {
_set_anchors_layout_preset((int)state["anchors_layout_preset"]);
}
@@ -125,7 +125,7 @@ void Control::_edit_set_state(const Dictionary &p_state) {
void Control::_edit_set_position(const Point2 &p_position) {
ERR_FAIL_COND_MSG(!Engine::get_singleton()->is_editor_hint(), "This function can only be used from editor plugins.");
- set_position(p_position, ControlEditorToolbar::get_singleton()->is_anchors_mode_enabled() && Object::cast_to<Control>(data.parent));
+ set_position(p_position, ControlEditorToolbar::get_singleton()->is_anchors_mode_enabled() && get_parent_control());
};
Point2 Control::_edit_get_position() const {
@@ -186,6 +186,14 @@ Size2 Control::_edit_get_minimum_size() const {
}
#endif
+void Control::reparent(Node *p_parent, bool p_keep_global_transform) {
+ Transform2D temp = get_global_transform();
+ Node::reparent(p_parent);
+ if (p_keep_global_transform) {
+ set_global_position(temp.get_origin());
+ }
+}
+
// Editor integration.
void Control::get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const {
@@ -545,7 +553,8 @@ void Control::_validate_property(PropertyInfo &p_property) const {
}
// Use the layout mode to display or hide advanced anchoring properties.
- bool use_anchors = _get_layout_mode() == LayoutMode::LAYOUT_MODE_ANCHORS;
+ LayoutMode _layout = _get_layout_mode();
+ bool use_anchors = (_layout == LayoutMode::LAYOUT_MODE_ANCHORS || _layout == LayoutMode::LAYOUT_MODE_UNCONTROLLED);
if (!use_anchors && p_property.name == "anchors_preset") {
p_property.usage ^= PROPERTY_USAGE_EDITOR;
}
@@ -598,7 +607,7 @@ bool Control::is_top_level_control() const {
}
Control *Control::get_parent_control() const {
- return data.parent;
+ return data.parent_control;
}
Window *Control::get_parent_window() const {
@@ -635,8 +644,10 @@ Rect2 Control::get_parent_anchorable_rect() const {
parent_rect = data.parent_canvas_item->get_anchorable_rect();
} else {
#ifdef TOOLS_ENABLED
- Node *edited_root = get_tree()->get_edited_scene_root();
- if (edited_root && (this == edited_root || edited_root->is_ancestor_of(this))) {
+ Node *edited_scene_root = get_tree()->get_edited_scene_root();
+ Node *scene_root_parent = edited_scene_root ? edited_scene_root->get_parent() : nullptr;
+
+ if (scene_root_parent && get_viewport() == scene_root_parent->get_viewport()) {
parent_rect.size = Size2(GLOBAL_GET("display/window/size/viewport_width"), GLOBAL_GET("display/window/size/viewport_height"));
} else {
parent_rect = get_viewport()->get_visible_rect();
@@ -683,6 +694,12 @@ Transform2D Control::get_transform() const {
return xform;
}
+void Control::_top_level_changed_on_parent() {
+ // Update root control status.
+ _notification(NOTIFICATION_EXIT_CANVAS);
+ _notification(NOTIFICATION_ENTER_CANVAS);
+}
+
/// Anchors and offsets.
void Control::_set_anchor(Side p_side, real_t p_anchor) {
@@ -749,6 +766,7 @@ void Control::set_anchor_and_offset(Side p_side, real_t p_anchor, real_t p_pos,
}
void Control::set_begin(const Size2 &p_point) {
+ ERR_FAIL_COND(!isfinite(p_point.x) || !isfinite(p_point.y));
if (data.offset[0] == p_point.x && data.offset[1] == p_point.y) {
return;
}
@@ -855,6 +873,14 @@ void Control::_set_layout_mode(LayoutMode p_mode) {
}
}
+void Control::_update_layout_mode() {
+ LayoutMode computed_layout = _get_layout_mode();
+ if (data.stored_layout_mode != computed_layout) {
+ data.stored_layout_mode = computed_layout;
+ notify_property_list_changed();
+ }
+}
+
Control::LayoutMode Control::_get_layout_mode() const {
Node *parent_node = get_parent_control();
// In these modes the property is read-only.
@@ -887,11 +913,9 @@ Control::LayoutMode Control::_get_default_layout_mode() const {
}
void Control::_set_anchors_layout_preset(int p_preset) {
- bool list_changed = false;
-
- if (data.stored_layout_mode != LayoutMode::LAYOUT_MODE_ANCHORS) {
- list_changed = true;
- data.stored_layout_mode = LayoutMode::LAYOUT_MODE_ANCHORS;
+ if (data.stored_layout_mode != LayoutMode::LAYOUT_MODE_UNCONTROLLED && data.stored_layout_mode != LayoutMode::LAYOUT_MODE_ANCHORS) {
+ // In other modes the anchor preset is non-operational and shouldn't be set to anything.
+ return;
}
if (p_preset == -1) {
@@ -902,6 +926,8 @@ void Control::_set_anchors_layout_preset(int p_preset) {
return; // Keep settings as is.
}
+ bool list_changed = false;
+
if (data.stored_use_custom_anchors) {
list_changed = true;
data.stored_use_custom_anchors = false;
@@ -944,6 +970,11 @@ void Control::_set_anchors_layout_preset(int p_preset) {
}
int Control::_get_anchors_layout_preset() const {
+ // If this is a layout mode that doesn't rely on anchors, avoid excessive checks.
+ if (data.stored_layout_mode != LayoutMode::LAYOUT_MODE_UNCONTROLLED && data.stored_layout_mode != LayoutMode::LAYOUT_MODE_ANCHORS) {
+ return LayoutPreset::PRESET_TOP_LEFT;
+ }
+
// If the custom preset was selected by user, use it.
if (data.stored_use_custom_anchors) {
return -1;
@@ -1364,13 +1395,7 @@ Point2 Control::get_global_position() const {
Point2 Control::get_screen_position() const {
ERR_FAIL_COND_V(!is_inside_tree(), Point2());
- Point2 global_pos = get_global_transform_with_canvas().get_origin();
- Window *w = Object::cast_to<Window>(get_viewport());
- if (w && !w->is_embedding_subwindows()) {
- global_pos += w->get_position();
- }
-
- return global_pos;
+ return get_screen_transform().get_origin();
}
void Control::_set_size(const Size2 &p_size) {
@@ -1383,6 +1408,7 @@ void Control::_set_size(const Size2 &p_size) {
}
void Control::set_size(const Size2 &p_size, bool p_keep_offsets) {
+ ERR_FAIL_COND(!isfinite(p_size.x) || !isfinite(p_size.y));
Size2 new_size = p_size;
Size2 min = get_combined_minimum_size();
if (new_size.x < min.x) {
@@ -1420,24 +1446,20 @@ void Control::set_rect(const Rect2 &p_rect) {
}
Rect2 Control::get_rect() const {
- return Rect2(get_position(), get_size());
+ Transform2D xform = get_transform();
+ return Rect2(xform.get_origin(), xform.get_scale() * get_size());
}
Rect2 Control::get_global_rect() const {
- return Rect2(get_global_position(), get_size());
+ Transform2D xform = get_global_transform();
+ return Rect2(xform.get_origin(), xform.get_scale() * get_size());
}
Rect2 Control::get_screen_rect() const {
ERR_FAIL_COND_V(!is_inside_tree(), Rect2());
- Rect2 r(get_global_position(), get_size());
-
- Window *w = Object::cast_to<Window>(get_viewport());
- if (w && !w->is_embedding_subwindows()) {
- r.position += w->get_position();
- }
-
- return r;
+ Transform2D xform = get_screen_transform();
+ return Rect2(xform.get_origin(), xform.get_scale() * get_size());
}
Rect2 Control::get_anchorable_rect() const {
@@ -1525,19 +1547,20 @@ void Control::update_minimum_size() {
Control *invalidate = this;
- //invalidate cache upwards
+ // Invalidate cache upwards.
while (invalidate && invalidate->data.minimum_size_valid) {
invalidate->data.minimum_size_valid = false;
if (invalidate->is_set_as_top_level()) {
- break; // do not go further up
+ break; // Do not go further up.
}
- if (!invalidate->data.parent && get_parent()) {
- Window *parent_window = Object::cast_to<Window>(get_parent());
- if (parent_window && parent_window->is_wrapping_controls()) {
- parent_window->child_controls_changed();
- }
+
+ Window *parent_window = invalidate->get_parent_window();
+ if (parent_window && parent_window->is_wrapping_controls()) {
+ parent_window->child_controls_changed();
+ break; // Stop on a window as well.
}
- invalidate = invalidate->data.parent;
+
+ invalidate = invalidate->get_parent_control();
}
if (!is_visible_in_tree()) {
@@ -1557,10 +1580,6 @@ void Control::set_block_minimum_size_adjust(bool p_block) {
data.block_minimum_size_adjust = p_block;
}
-bool Control::is_minimum_size_adjust_blocked() const {
- return data.block_minimum_size_adjust;
-}
-
Size2 Control::get_minimum_size() const {
Vector2 ms;
GDVIRTUAL_CALL(_get_minimum_size, ms);
@@ -1572,7 +1591,7 @@ void Control::set_custom_minimum_size(const Size2 &p_custom) {
return;
}
- if (isnan(p_custom.x) || isnan(p_custom.y)) {
+ if (!isfinite(p_custom.x) || !isfinite(p_custom.y)) {
// Prevent infinite loop.
return;
}
@@ -1676,27 +1695,27 @@ void Control::_clear_size_warning() {
// Container sizing.
-void Control::set_h_size_flags(int p_flags) {
- if (data.h_size_flags == p_flags) {
+void Control::set_h_size_flags(BitField<SizeFlags> p_flags) {
+ if ((int)data.h_size_flags == (int)p_flags) {
return;
}
data.h_size_flags = p_flags;
emit_signal(SceneStringNames::get_singleton()->size_flags_changed);
}
-int Control::get_h_size_flags() const {
+BitField<Control::SizeFlags> Control::get_h_size_flags() const {
return data.h_size_flags;
}
-void Control::set_v_size_flags(int p_flags) {
- if (data.v_size_flags == p_flags) {
+void Control::set_v_size_flags(BitField<SizeFlags> p_flags) {
+ if ((int)data.v_size_flags == (int)p_flags) {
return;
}
data.v_size_flags = p_flags;
emit_signal(SceneStringNames::get_singleton()->size_flags_changed);
}
-int Control::get_v_size_flags() const {
+BitField<Control::SizeFlags> Control::get_v_size_flags() const {
return data.v_size_flags;
}
@@ -1798,33 +1817,40 @@ bool Control::is_focus_owner_in_shortcut_context() const {
// Drag and drop handling.
-void Control::set_drag_forwarding(Object *p_target) {
- if (p_target) {
- data.drag_owner = p_target->get_instance_id();
- } else {
- data.drag_owner = ObjectID();
- }
+void Control::set_drag_forwarding(const Callable &p_drag, const Callable &p_can_drop, const Callable &p_drop) {
+ data.forward_drag = p_drag;
+ data.forward_can_drop = p_can_drop;
+ data.forward_drop = p_drop;
}
Variant Control::get_drag_data(const Point2 &p_point) {
- if (data.drag_owner.is_valid()) {
- Object *obj = ObjectDB::get_instance(data.drag_owner);
- if (obj) {
- return obj->call("_get_drag_data_fw", p_point, this);
+ Variant ret;
+ if (data.forward_drag.is_valid()) {
+ Variant p = p_point;
+ const Variant *vp[1] = { &p };
+ Callable::CallError ce;
+ data.forward_drag.callp((const Variant **)vp, 1, ret, ce);
+ if (ce.error != Callable::CallError::CALL_OK) {
+ ERR_FAIL_V_MSG(Variant(), "Error calling forwarded method from 'get_drag_data': " + Variant::get_callable_error_text(data.forward_drag, (const Variant **)vp, 1, ce) + ".");
}
+ return ret;
}
- Variant dd;
- GDVIRTUAL_CALL(_get_drag_data, p_point, dd);
- return dd;
+ GDVIRTUAL_CALL(_get_drag_data, p_point, ret);
+ return ret;
}
bool Control::can_drop_data(const Point2 &p_point, const Variant &p_data) const {
- if (data.drag_owner.is_valid()) {
- Object *obj = ObjectDB::get_instance(data.drag_owner);
- if (obj) {
- return obj->call("_can_drop_data_fw", p_point, p_data, this);
+ if (data.forward_can_drop.is_valid()) {
+ Variant ret;
+ Variant p = p_point;
+ const Variant *vp[2] = { &p, &p_data };
+ Callable::CallError ce;
+ data.forward_can_drop.callp((const Variant **)vp, 2, ret, ce);
+ if (ce.error != Callable::CallError::CALL_OK) {
+ ERR_FAIL_V_MSG(Variant(), "Error calling forwarded method from 'can_drop_data': " + Variant::get_callable_error_text(data.forward_can_drop, (const Variant **)vp, 2, ce) + ".");
}
+ return ret;
}
bool ret = false;
@@ -1833,12 +1859,16 @@ bool Control::can_drop_data(const Point2 &p_point, const Variant &p_data) const
}
void Control::drop_data(const Point2 &p_point, const Variant &p_data) {
- if (data.drag_owner.is_valid()) {
- Object *obj = ObjectDB::get_instance(data.drag_owner);
- if (obj) {
- obj->call("_drop_data_fw", p_point, p_data, this);
- return;
+ if (data.forward_drop.is_valid()) {
+ Variant ret;
+ Variant p = p_point;
+ const Variant *vp[2] = { &p, &p_data };
+ Callable::CallError ce;
+ data.forward_drop.callp((const Variant **)vp, 2, ret, ce);
+ if (ce.error != Callable::CallError::CALL_OK) {
+ ERR_FAIL_MSG("Error calling forwarded method from 'drop_data': " + Variant::get_callable_error_text(data.forward_drop, (const Variant **)vp, 2, ce) + ".");
}
+ return;
}
GDVIRTUAL_CALL(_drop_data, p_point, p_data);
@@ -2733,9 +2763,9 @@ void Control::end_bulk_theme_override() {
// Internationalization.
-TypedArray<Vector2i> Control::structured_text_parser(TextServer::StructuredTextParser p_parser_type, const Array &p_args, const String &p_text) const {
+TypedArray<Vector3i> Control::structured_text_parser(TextServer::StructuredTextParser p_parser_type, const Array &p_args, const String &p_text) const {
if (p_parser_type == TextServer::STRUCTURED_TEXT_CUSTOM) {
- TypedArray<Vector2i> ret;
+ TypedArray<Vector3i> ret;
GDVIRTUAL_CALL(_structured_text_parser, p_args, p_text, ret);
return ret;
} else {
@@ -2850,10 +2880,19 @@ void Control::_notification(int p_notification) {
} break;
case NOTIFICATION_PARENTED: {
+ Node *parent_node = get_parent();
+ data.parent_control = Object::cast_to<Control>(parent_node);
+ data.parent_window = Object::cast_to<Window>(parent_node);
+
data.theme_owner->assign_theme_on_parented(this);
+
+ _update_layout_mode();
} break;
case NOTIFICATION_UNPARENTED: {
+ data.parent_control = nullptr;
+ data.parent_window = nullptr;
+
data.theme_owner->clear_theme_on_unparented(this);
} break;
@@ -2879,8 +2918,6 @@ void Control::_notification(int p_notification) {
} break;
case NOTIFICATION_ENTER_CANVAS: {
- data.parent = Object::cast_to<Control>(get_parent());
- data.parent_window = Object::cast_to<Window>(get_parent());
data.is_rtl_dirty = true;
CanvasItem *node = this;
@@ -2938,17 +2975,16 @@ void Control::_notification(int p_notification) {
data.RI = nullptr;
}
- data.parent = nullptr;
data.parent_canvas_item = nullptr;
- data.parent_window = nullptr;
data.is_rtl_dirty = true;
} break;
case NOTIFICATION_MOVED_IN_PARENT: {
- // some parents need to know the order of the children to draw (like TabContainer)
- // update if necessary
- if (data.parent) {
- data.parent->queue_redraw();
+ // Some parents need to know the order of the children to draw (like TabContainer),
+ // so we update them just in case.
+ Control *parent_control = get_parent_control();
+ if (parent_control) {
+ parent_control->queue_redraw();
}
queue_redraw();
@@ -3170,7 +3206,7 @@ void Control::_bind_methods() {
ClassDB::bind_method(D_METHOD("grab_click_focus"), &Control::grab_click_focus);
- ClassDB::bind_method(D_METHOD("set_drag_forwarding", "target"), &Control::set_drag_forwarding);
+ ClassDB::bind_method(D_METHOD("set_drag_forwarding", "drag_func", "can_drop_func", "drop_func"), &Control::set_drag_forwarding);
ClassDB::bind_method(D_METHOD("set_drag_preview", "control"), &Control::set_drag_preview);
ClassDB::bind_method(D_METHOD("is_drag_successful"), &Control::is_drag_successful);
@@ -3318,12 +3354,12 @@ void Control::_bind_methods() {
BIND_ENUM_CONSTANT(PRESET_MODE_KEEP_HEIGHT);
BIND_ENUM_CONSTANT(PRESET_MODE_KEEP_SIZE);
- BIND_ENUM_CONSTANT(SIZE_SHRINK_BEGIN);
- BIND_ENUM_CONSTANT(SIZE_FILL);
- BIND_ENUM_CONSTANT(SIZE_EXPAND);
- BIND_ENUM_CONSTANT(SIZE_EXPAND_FILL);
- BIND_ENUM_CONSTANT(SIZE_SHRINK_CENTER);
- BIND_ENUM_CONSTANT(SIZE_SHRINK_END);
+ BIND_BITFIELD_FLAG(SIZE_SHRINK_BEGIN);
+ BIND_BITFIELD_FLAG(SIZE_FILL);
+ BIND_BITFIELD_FLAG(SIZE_EXPAND);
+ BIND_BITFIELD_FLAG(SIZE_EXPAND_FILL);
+ BIND_BITFIELD_FLAG(SIZE_SHRINK_CENTER);
+ BIND_BITFIELD_FLAG(SIZE_SHRINK_END);
BIND_ENUM_CONSTANT(MOUSE_FILTER_STOP);
BIND_ENUM_CONSTANT(MOUSE_FILTER_PASS);
@@ -3356,7 +3392,7 @@ void Control::_bind_methods() {
ADD_SIGNAL(MethodInfo("minimum_size_changed"));
ADD_SIGNAL(MethodInfo("theme_changed"));
- GDVIRTUAL_BIND(_has_point, "position");
+ GDVIRTUAL_BIND(_has_point, "point");
GDVIRTUAL_BIND(_structured_text_parser, "args", "text");
GDVIRTUAL_BIND(_get_minimum_size);
diff --git a/scene/gui/control.h b/scene/gui/control.h
index 288de7c9e7..2fb5d559b6 100644
--- a/scene/gui/control.h
+++ b/scene/gui/control.h
@@ -145,7 +145,7 @@ public:
TEXT_DIRECTION_AUTO = TextServer::DIRECTION_AUTO,
TEXT_DIRECTION_LTR = TextServer::DIRECTION_LTR,
TEXT_DIRECTION_RTL = TextServer::DIRECTION_RTL,
- TEXT_DIRECTION_INHERITED,
+ TEXT_DIRECTION_INHERITED = TextServer::DIRECTION_INHERITED,
};
private:
@@ -165,10 +165,12 @@ private:
List<Control *>::Element *RI = nullptr;
- Control *parent = nullptr;
+ Control *parent_control = nullptr;
Window *parent_window = nullptr;
CanvasItem *parent_canvas_item = nullptr;
- ObjectID drag_owner;
+ Callable forward_drag;
+ Callable forward_can_drop;
+ Callable forward_drop;
// Positioning and sizing.
@@ -198,8 +200,8 @@ private:
// Container sizing.
- int h_size_flags = SIZE_FILL;
- int v_size_flags = SIZE_FILL;
+ BitField<SizeFlags> h_size_flags = SIZE_FILL;
+ BitField<SizeFlags> v_size_flags = SIZE_FILL;
real_t expand = 1.0;
Point2 custom_minimum_size;
@@ -280,6 +282,7 @@ private:
void _compute_anchors(Rect2 p_rect, const real_t p_offsets[4], real_t (&r_anchors)[4]);
void _set_layout_mode(LayoutMode p_mode);
+ void _update_layout_mode();
LayoutMode _get_layout_mode() const;
LayoutMode _get_default_layout_mode() const;
void _set_anchors_layout_preset(int p_preset);
@@ -289,6 +292,9 @@ private:
void _update_minimum_size();
void _size_changed();
+ void _top_level_changed() override {} // Controls don't need to do anything, only other CanvasItems.
+ void _top_level_changed_on_parent() override;
+
void _clear_size_warning();
// Input events.
@@ -327,7 +333,7 @@ protected:
// Internationalization.
- virtual TypedArray<Vector2i> structured_text_parser(TextServer::StructuredTextParser p_parser_type, const Array &p_args, const String &p_text) const;
+ virtual TypedArray<Vector3i> structured_text_parser(TextServer::StructuredTextParser p_parser_type, const Array &p_args, const String &p_text) const;
// Base object overrides.
@@ -337,7 +343,7 @@ protected:
// Exposed virtual methods.
GDVIRTUAL1RC(bool, _has_point, Vector2)
- GDVIRTUAL2RC(TypedArray<Vector2i>, _structured_text_parser, Array, String)
+ GDVIRTUAL2RC(TypedArray<Vector3i>, _structured_text_parser, Array, String)
GDVIRTUAL0RC(Vector2, _get_minimum_size)
GDVIRTUAL1RC(Variant, _get_drag_data, Vector2)
@@ -387,6 +393,7 @@ public:
virtual Size2 _edit_get_minimum_size() const override;
#endif
+ virtual void reparent(Node *p_parent, bool p_keep_global_transform = true) override;
// Editor integration.
@@ -460,7 +467,6 @@ public:
void update_minimum_size();
void set_block_minimum_size_adjust(bool p_block);
- bool is_minimum_size_adjust_blocked() const;
virtual Size2 get_minimum_size() const;
virtual Size2 get_combined_minimum_size() const;
@@ -470,10 +476,10 @@ public:
// Container sizing.
- void set_h_size_flags(int p_flags);
- int get_h_size_flags() const;
- void set_v_size_flags(int p_flags);
- int get_v_size_flags() const;
+ void set_h_size_flags(BitField<SizeFlags> p_flags);
+ BitField<SizeFlags> get_h_size_flags() const;
+ void set_v_size_flags(BitField<SizeFlags> p_flags);
+ BitField<SizeFlags> get_v_size_flags() const;
void set_stretch_ratio(real_t p_ratio);
real_t get_stretch_ratio() const;
@@ -498,7 +504,7 @@ public:
// Drag and drop handling.
- virtual void set_drag_forwarding(Object *p_target);
+ virtual void set_drag_forwarding(const Callable &p_drag, const Callable &p_can_drop, const Callable &p_drop);
virtual Variant get_drag_data(const Point2 &p_point);
virtual bool can_drop_data(const Point2 &p_point, const Variant &p_data) const;
virtual void drop_data(const Point2 &p_point, const Variant &p_data);
@@ -618,7 +624,7 @@ public:
};
VARIANT_ENUM_CAST(Control::FocusMode);
-VARIANT_ENUM_CAST(Control::SizeFlags);
+VARIANT_BITFIELD_CAST(Control::SizeFlags);
VARIANT_ENUM_CAST(Control::CursorShape);
VARIANT_ENUM_CAST(Control::LayoutPreset);
VARIANT_ENUM_CAST(Control::LayoutPresetMode);
@@ -629,4 +635,10 @@ VARIANT_ENUM_CAST(Control::LayoutMode);
VARIANT_ENUM_CAST(Control::LayoutDirection);
VARIANT_ENUM_CAST(Control::TextDirection);
+// G = get_drag_data_fw, C = can_drop_data_fw, D = drop_data_fw, U = underscore
+#define SET_DRAG_FORWARDING_CD(from, to) from->set_drag_forwarding(Callable(), callable_mp(this, &to::can_drop_data_fw).bind(from), callable_mp(this, &to::drop_data_fw).bind(from));
+#define SET_DRAG_FORWARDING_CDU(from, to) from->set_drag_forwarding(Callable(), callable_mp(this, &to::_can_drop_data_fw).bind(from), callable_mp(this, &to::_drop_data_fw).bind(from));
+#define SET_DRAG_FORWARDING_GCD(from, to) from->set_drag_forwarding(callable_mp(this, &to::get_drag_data_fw).bind(from), callable_mp(this, &to::can_drop_data_fw).bind(from), callable_mp(this, &to::drop_data_fw).bind(from));
+#define SET_DRAG_FORWARDING_GCDU(from, to) from->set_drag_forwarding(callable_mp(this, &to::_get_drag_data_fw).bind(from), callable_mp(this, &to::_can_drop_data_fw).bind(from), callable_mp(this, &to::_drop_data_fw).bind(from));
+
#endif // CONTROL_H
diff --git a/scene/gui/dialogs.cpp b/scene/gui/dialogs.cpp
index 1d5e6320dd..760c86b2cc 100644
--- a/scene/gui/dialogs.cpp
+++ b/scene/gui/dialogs.cpp
@@ -136,7 +136,7 @@ void AcceptDialog::_cancel_pressed() {
call_deferred(SNAME("hide"));
- emit_signal(SNAME("cancelled"));
+ emit_signal(SNAME("canceled"));
cancel_pressed();
@@ -276,10 +276,6 @@ Size2 AcceptDialog::_get_contents_minimum_size() const {
// Plus there is a separation size added on top.
content_minsize.y += theme_cache.buttons_separation;
- // Last, we make sure that we aren't below the minimum window size.
- Size2 window_minsize = get_min_size();
- content_minsize.x = MAX(window_minsize.x, content_minsize.x);
- content_minsize.y = MAX(window_minsize.y, content_minsize.y);
return content_minsize;
}
@@ -372,13 +368,13 @@ void AcceptDialog::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_ok_button_text"), &AcceptDialog::get_ok_button_text);
ADD_SIGNAL(MethodInfo("confirmed"));
- ADD_SIGNAL(MethodInfo("cancelled"));
+ ADD_SIGNAL(MethodInfo("canceled"));
ADD_SIGNAL(MethodInfo("custom_action", PropertyInfo(Variant::STRING_NAME, "action")));
ADD_PROPERTY(PropertyInfo(Variant::STRING, "ok_button_text"), "set_ok_button_text", "get_ok_button_text");
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::STRING, "dialog_text", PROPERTY_HINT_MULTILINE_TEXT), "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");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "dialog_autowrap"), "set_autowrap", "has_autowrap");
diff --git a/scene/gui/flow_container.cpp b/scene/gui/flow_container.cpp
index e0a303651a..12ce6e17cb 100644
--- a/scene/gui/flow_container.cpp
+++ b/scene/gui/flow_container.cpp
@@ -86,7 +86,7 @@ void FlowContainer::_resort() {
}
line_height = MAX(line_height, child_msc.x);
- if (child->get_v_size_flags() & SIZE_EXPAND) {
+ if (child->get_v_size_flags().has_flag(SIZE_EXPAND)) {
line_stretch_ratio_total += child->get_stretch_ratio();
}
ofs.y += child_msc.y;
@@ -108,7 +108,7 @@ void FlowContainer::_resort() {
}
line_height = MAX(line_height, child_msc.y);
- if (child->get_h_size_flags() & SIZE_EXPAND) {
+ if (child->get_h_size_flags().has_flag(SIZE_EXPAND)) {
line_stretch_ratio_total += child->get_stretch_ratio();
}
ofs.x += child_msc.x;
@@ -175,21 +175,21 @@ void FlowContainer::_resort() {
}
if (vertical) { /* VERTICAL */
- if (child->get_h_size_flags() & (SIZE_FILL | SIZE_SHRINK_CENTER | SIZE_SHRINK_END)) {
+ if (child->get_h_size_flags().has_flag(SIZE_FILL) || child->get_h_size_flags().has_flag(SIZE_SHRINK_CENTER) || child->get_h_size_flags().has_flag(SIZE_SHRINK_END)) {
child_size.width = line_data.min_line_height;
}
- if (child->get_v_size_flags() & SIZE_EXPAND) {
+ if (child->get_v_size_flags().has_flag(SIZE_EXPAND)) {
int stretch = line_data.stretch_avail * child->get_stretch_ratio() / line_data.stretch_ratio_total;
child_size.height += stretch;
}
} else { /* HORIZONTAL */
- if (child->get_v_size_flags() & (SIZE_FILL | SIZE_SHRINK_CENTER | SIZE_SHRINK_END)) {
+ if (child->get_v_size_flags().has_flag(SIZE_FILL) || child->get_v_size_flags().has_flag(SIZE_SHRINK_CENTER) || child->get_v_size_flags().has_flag(SIZE_SHRINK_END)) {
child_size.height = line_data.min_line_height;
}
- if (child->get_h_size_flags() & SIZE_EXPAND) {
+ if (child->get_h_size_flags().has_flag(SIZE_EXPAND)) {
int stretch = line_data.stretch_avail * child->get_stretch_ratio() / line_data.stretch_ratio_total;
child_size.width += stretch;
}
diff --git a/scene/gui/graph_edit.cpp b/scene/gui/graph_edit.cpp
index a7b01e00ae..a6a2fb8d7c 100644
--- a/scene/gui/graph_edit.cpp
+++ b/scene/gui/graph_edit.cpp
@@ -193,7 +193,7 @@ void GraphEditMinimap::_adjust_graph_scroll(const Vector2 &p_offset) {
PackedStringArray GraphEdit::get_configuration_warnings() const {
PackedStringArray warnings = Control::get_configuration_warnings();
- warnings.push_back(RTR("Please be aware that GraphEdit and GraphNode will undergo extensive refactoring in a future beta version involving compatibility-breaking API changes."));
+ warnings.push_back(RTR("Please be aware that GraphEdit and GraphNode will undergo extensive refactoring in a future 4.x version involving compatibility-breaking API changes."));
return warnings;
}
@@ -264,10 +264,6 @@ void GraphEdit::_scroll_moved(double) {
top_layer->queue_redraw();
minimap->queue_redraw();
queue_redraw();
-
- if (!setting_scroll_ofs) { //in godot, signals on change value are avoided as a convention
- emit_signal(SNAME("scroll_offset_changed"), get_scroll_ofs());
- }
}
void GraphEdit::_update_scroll_offset() {
@@ -290,6 +286,10 @@ void GraphEdit::_update_scroll_offset() {
connections_layer->set_position(-Point2(h_scroll->get_value(), v_scroll->get_value()));
set_block_minimum_size_adjust(false);
awaiting_scroll_offset_update = false;
+
+ if (!setting_scroll_ofs) { //in godot, signals on change value are avoided as a convention
+ emit_signal(SNAME("scroll_offset_changed"), get_scroll_ofs());
+ }
}
void GraphEdit::_update_scroll() {
@@ -404,8 +404,8 @@ void GraphEdit::add_child_notify(Node *p_child) {
if (gn) {
gn->set_scale(Vector2(zoom, zoom));
gn->connect("position_offset_changed", callable_mp(this, &GraphEdit::_graph_node_moved).bind(gn));
- gn->connect("selected", callable_mp(this, &GraphEdit::_graph_node_selected).bind(gn));
- gn->connect("deselected", callable_mp(this, &GraphEdit::_graph_node_deselected).bind(gn));
+ gn->connect("node_selected", callable_mp(this, &GraphEdit::_graph_node_selected).bind(gn));
+ gn->connect("node_deselected", callable_mp(this, &GraphEdit::_graph_node_deselected).bind(gn));
gn->connect("slot_updated", callable_mp(this, &GraphEdit::_graph_node_slot_updated).bind(gn));
gn->connect("raise_request", callable_mp(this, &GraphEdit::_graph_node_raised).bind(gn));
gn->connect("item_rect_changed", callable_mp((CanvasItem *)connections_layer, &CanvasItem::queue_redraw));
@@ -432,8 +432,8 @@ void GraphEdit::remove_child_notify(Node *p_child) {
GraphNode *gn = Object::cast_to<GraphNode>(p_child);
if (gn) {
gn->disconnect("position_offset_changed", callable_mp(this, &GraphEdit::_graph_node_moved));
- gn->disconnect("selected", callable_mp(this, &GraphEdit::_graph_node_selected));
- gn->disconnect("deselected", callable_mp(this, &GraphEdit::_graph_node_deselected));
+ gn->disconnect("node_selected", callable_mp(this, &GraphEdit::_graph_node_selected));
+ gn->disconnect("node_deselected", callable_mp(this, &GraphEdit::_graph_node_deselected));
gn->disconnect("slot_updated", callable_mp(this, &GraphEdit::_graph_node_slot_updated));
gn->disconnect("raise_request", callable_mp(this, &GraphEdit::_graph_node_raised));
@@ -920,7 +920,8 @@ void GraphEdit::_draw_connection_line(CanvasItem *p_where, const Vector2 &p_from
scaled_points.push_back(points[i] * p_zoom);
}
- p_where->draw_polyline_colors(scaled_points, colors, Math::floor(p_width * get_theme_default_base_scale()), lines_antialiased);
+ // Thickness below 0.5 doesn't look good on the graph or its minimap.
+ p_where->draw_polyline_colors(scaled_points, colors, MAX(0.5, Math::floor(p_width * get_theme_default_base_scale())), lines_antialiased);
}
void GraphEdit::_connections_layer_draw() {
@@ -1088,7 +1089,7 @@ void GraphEdit::_minimap_draw() {
from_color = from_color.lerp(activity_color, E.activity);
to_color = to_color.lerp(activity_color, E.activity);
}
- _draw_connection_line(minimap, from_position, to_position, from_color, to_color, 0.1, minimap->_convert_from_graph_position(Vector2(zoom, zoom)).length());
+ _draw_connection_line(minimap, from_position, to_position, from_color, to_color, 0.5, minimap->_convert_from_graph_position(Vector2(zoom, zoom)).length());
}
// Draw the "camera" viewport.
@@ -1380,34 +1381,15 @@ void GraphEdit::gui_input(const Ref<InputEvent> &p_ev) {
accept_event();
}
}
-
- Ref<InputEventMagnifyGesture> magnify_gesture = p_ev;
- if (magnify_gesture.is_valid()) {
- set_zoom_custom(zoom * magnify_gesture->get_factor(), magnify_gesture->get_position());
- }
-
- Ref<InputEventPanGesture> pan_gesture = p_ev;
- if (pan_gesture.is_valid()) {
- h_scroll->set_value(h_scroll->get_value() + h_scroll->get_page() * pan_gesture->get_delta().x / 8);
- v_scroll->set_value(v_scroll->get_value() + v_scroll->get_page() * pan_gesture->get_delta().y / 8);
- }
-}
-
-void GraphEdit::_scroll_callback(Vector2 p_scroll_vec, bool p_alt) {
- if (p_scroll_vec.x != 0) {
- h_scroll->set_value(h_scroll->get_value() + (h_scroll->get_page() * Math::abs(p_scroll_vec.x) / 8) * SIGN(p_scroll_vec.x));
- } else {
- v_scroll->set_value(v_scroll->get_value() + (v_scroll->get_page() * Math::abs(p_scroll_vec.y) / 8) * SIGN(p_scroll_vec.y));
- }
}
-void GraphEdit::_pan_callback(Vector2 p_scroll_vec) {
+void GraphEdit::_pan_callback(Vector2 p_scroll_vec, Ref<InputEvent> p_event) {
h_scroll->set_value(h_scroll->get_value() - p_scroll_vec.x);
v_scroll->set_value(v_scroll->get_value() - p_scroll_vec.y);
}
-void GraphEdit::_zoom_callback(Vector2 p_scroll_vec, Vector2 p_origin, bool p_alt) {
- set_zoom_custom(p_scroll_vec.y < 0 ? zoom * zoom_step : zoom / zoom_step, p_origin);
+void GraphEdit::_zoom_callback(float p_zoom_factor, Vector2 p_origin, Ref<InputEvent> p_event) {
+ set_zoom_custom(zoom * p_zoom_factor, p_origin);
}
void GraphEdit::set_connection_activity(const StringName &p_from, int p_from_port, const StringName &p_to, int p_to_port, float p_activity) {
@@ -1496,11 +1478,13 @@ float GraphEdit::get_zoom() const {
void GraphEdit::set_zoom_step(float p_zoom_step) {
p_zoom_step = abs(p_zoom_step);
+ ERR_FAIL_COND(!isfinite(p_zoom_step));
if (zoom_step == p_zoom_step) {
return;
}
zoom_step = p_zoom_step;
+ panner->set_scroll_zoom_factor(zoom_step);
}
float GraphEdit::get_zoom_step() const {
@@ -2420,7 +2404,7 @@ GraphEdit::GraphEdit() {
zoom_max = (1 * Math::pow(zoom_step, 4));
panner.instantiate();
- panner->set_callbacks(callable_mp(this, &GraphEdit::_scroll_callback), callable_mp(this, &GraphEdit::_pan_callback), callable_mp(this, &GraphEdit::_zoom_callback));
+ panner->set_callbacks(callable_mp(this, &GraphEdit::_pan_callback), callable_mp(this, &GraphEdit::_zoom_callback));
top_layer = memnew(GraphEditFilter(this));
add_child(top_layer, false, INTERNAL_MODE_BACK);
diff --git a/scene/gui/graph_edit.h b/scene/gui/graph_edit.h
index 030f40e370..dfe6b94906 100644
--- a/scene/gui/graph_edit.h
+++ b/scene/gui/graph_edit.h
@@ -129,9 +129,8 @@ private:
Ref<ViewPanner> panner;
bool warped_panning = true;
- void _scroll_callback(Vector2 p_scroll_vec, bool p_alt);
- void _pan_callback(Vector2 p_scroll_vec);
- void _zoom_callback(Vector2 p_scroll_vec, Vector2 p_origin, bool p_alt);
+ void _pan_callback(Vector2 p_scroll_vec, Ref<InputEvent> p_event);
+ void _zoom_callback(float p_zoom_factor, Vector2 p_origin, Ref<InputEvent> p_event);
bool arrange_nodes_button_hidden = false;
diff --git a/scene/gui/graph_node.cpp b/scene/gui/graph_node.cpp
index b0318b3e8f..f8d2ff0d2c 100644
--- a/scene/gui/graph_node.cpp
+++ b/scene/gui/graph_node.cpp
@@ -174,7 +174,7 @@ void GraphNode::_resort() {
stretch_min += size.height;
msc.min_size = size.height;
- msc.will_stretch = c->get_v_size_flags() & SIZE_EXPAND;
+ msc.will_stretch = c->get_v_size_flags().has_flag(SIZE_EXPAND);
if (msc.will_stretch) {
stretch_avail += msc.min_size;
@@ -749,7 +749,7 @@ void GraphNode::set_selected(bool p_selected) {
}
selected = p_selected;
- emit_signal(p_selected ? SNAME("selected") : SNAME("deselected"));
+ emit_signal(p_selected ? SNAME("node_selected") : SNAME("node_deselected"));
queue_redraw();
}
@@ -1161,8 +1161,8 @@ void GraphNode::_bind_methods() {
ADD_GROUP("", "");
ADD_SIGNAL(MethodInfo("position_offset_changed"));
- ADD_SIGNAL(MethodInfo("selected"));
- ADD_SIGNAL(MethodInfo("deselected"));
+ ADD_SIGNAL(MethodInfo("node_selected"));
+ ADD_SIGNAL(MethodInfo("node_deselected"));
ADD_SIGNAL(MethodInfo("slot_updated", PropertyInfo(Variant::INT, "idx")));
ADD_SIGNAL(MethodInfo("dragged", PropertyInfo(Variant::VECTOR2, "from"), PropertyInfo(Variant::VECTOR2, "to")));
ADD_SIGNAL(MethodInfo("raise_request"));
diff --git a/scene/gui/grid_container.cpp b/scene/gui/grid_container.cpp
index e11afdf00d..28f86369a2 100644
--- a/scene/gui/grid_container.cpp
+++ b/scene/gui/grid_container.cpp
@@ -73,10 +73,10 @@ void GridContainer::_notification(int p_what) {
row_minh[row] = ms.height;
}
- if (c->get_h_size_flags() & SIZE_EXPAND) {
+ if (c->get_h_size_flags().has_flag(SIZE_EXPAND)) {
col_expanded.insert(col);
}
- if (c->get_v_size_flags() & SIZE_EXPAND) {
+ if (c->get_v_size_flags().has_flag(SIZE_EXPAND)) {
row_expanded.insert(row);
}
}
diff --git a/scene/gui/item_list.cpp b/scene/gui/item_list.cpp
index 372baeadae..25a27d5e1a 100644
--- a/scene/gui/item_list.cpp
+++ b/scene/gui/item_list.cpp
@@ -309,12 +309,6 @@ void ItemList::set_item_tag_icon(int p_idx, const Ref<Texture2D> &p_tag_icon) {
shape_changed = true;
}
-Ref<Texture2D> ItemList::get_item_tag_icon(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx, items.size(), Ref<Texture2D>());
-
- return items[p_idx].tag_icon;
-}
-
void ItemList::set_item_selectable(int p_idx, bool p_selectable) {
if (p_idx < 0) {
p_idx += get_item_count();
diff --git a/scene/gui/item_list.h b/scene/gui/item_list.h
index 848f9a2ba9..934318dbb4 100644
--- a/scene/gui/item_list.h
+++ b/scene/gui/item_list.h
@@ -191,7 +191,6 @@ public:
Variant get_item_metadata(int p_idx) const;
void set_item_tag_icon(int p_idx, const Ref<Texture2D> &p_tag_icon);
- Ref<Texture2D> get_item_tag_icon(int p_idx) const;
void set_item_tooltip_enabled(int p_idx, const bool p_enabled);
bool is_item_tooltip_enabled(int p_idx) const;
diff --git a/scene/gui/label.cpp b/scene/gui/label.cpp
index 81e5de1886..f59702835c 100644
--- a/scene/gui/label.cpp
+++ b/scene/gui/label.cpp
@@ -222,6 +222,7 @@ void Label::_shape() {
}
}
lines_dirty = false;
+ lines_shaped_last_width = get_size().width;
}
_update_visible();
@@ -596,7 +597,13 @@ void Label::_notification(int p_what) {
} break;
case NOTIFICATION_RESIZED: {
- lines_dirty = true;
+ // It may happen that the reshaping due to this size change triggers a cascade of re-layout
+ // across the hierarchy where this label belongs to in a way that its size changes multiple
+ // times, but ending up with the original size it was already shaped for.
+ // This check prevents the catastrophic, freezing infinite cascade of re-layout.
+ if (lines_shaped_last_width != get_size().width) {
+ lines_dirty = true;
+ }
} break;
}
}
@@ -949,7 +956,7 @@ void Label::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_structured_text_bidi_override_options", "args"), &Label::set_structured_text_bidi_override_options);
ClassDB::bind_method(D_METHOD("get_structured_text_bidi_override_options"), &Label::get_structured_text_bidi_override_options);
- ADD_PROPERTY(PropertyInfo(Variant::STRING, "text", PROPERTY_HINT_MULTILINE_TEXT, "", PROPERTY_USAGE_DEFAULT_INTL), "set_text", "get_text");
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "text", PROPERTY_HINT_MULTILINE_TEXT), "set_text", "get_text");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "label_settings", PROPERTY_HINT_RESOURCE_TYPE, "LabelSettings"), "set_label_settings", "get_label_settings");
ADD_PROPERTY(PropertyInfo(Variant::INT, "horizontal_alignment", PROPERTY_HINT_ENUM, "Left,Center,Right,Fill"), "set_horizontal_alignment", "get_horizontal_alignment");
ADD_PROPERTY(PropertyInfo(Variant::INT, "vertical_alignment", PROPERTY_HINT_ENUM, "Top,Center,Bottom,Fill"), "set_vertical_alignment", "get_vertical_alignment");
diff --git a/scene/gui/label.h b/scene/gui/label.h
index 2350525236..b80646810b 100644
--- a/scene/gui/label.h
+++ b/scene/gui/label.h
@@ -49,6 +49,8 @@ private:
bool uppercase = false;
bool lines_dirty = true;
+ int lines_shaped_last_width = -1;
+
bool dirty = true;
bool font_dirty = true;
RID text_rid;
diff --git a/scene/gui/line_edit.cpp b/scene/gui/line_edit.cpp
index ab96e2c557..a57dccd5c8 100644
--- a/scene/gui/line_edit.cpp
+++ b/scene/gui/line_edit.cpp
@@ -84,6 +84,7 @@ void LineEdit::_move_caret_left(bool p_select, bool p_move_by_word) {
}
shift_selection_check_post(p_select);
+ _reset_caret_blink_timer();
}
void LineEdit::_move_caret_right(bool p_select, bool p_move_by_word) {
@@ -116,6 +117,7 @@ void LineEdit::_move_caret_right(bool p_select, bool p_move_by_word) {
}
shift_selection_check_post(p_select);
+ _reset_caret_blink_timer();
}
void LineEdit::_move_caret_start(bool p_select) {
@@ -247,7 +249,7 @@ void LineEdit::gui_input(const Ref<InputEvent> &p_event) {
return;
}
if (b->is_pressed() && b->get_button_index() == MouseButton::RIGHT && context_menu_enabled) {
- _ensure_menu();
+ _update_context_menu();
menu->set_position(get_screen_position() + get_local_mouse_position());
menu->reset_size();
menu->popup();
@@ -272,6 +274,7 @@ void LineEdit::gui_input(const Ref<InputEvent> &p_event) {
}
}
grab_focus();
+ accept_event();
return;
}
@@ -381,6 +384,7 @@ void LineEdit::gui_input(const Ref<InputEvent> &p_event) {
}
queue_redraw();
+ return;
}
Ref<InputEventMouseMotion> m = p_event;
@@ -394,7 +398,7 @@ void LineEdit::gui_input(const Ref<InputEvent> &p_event) {
}
}
- if ((m->get_button_mask() & MouseButton::MASK_LEFT) != MouseButton::NONE) {
+ if (m->get_button_mask().has_flag(MouseButtonMask::LEFT)) {
if (selection.creating) {
set_caret_at_pixel_pos(m->get_position().x);
selection_fill_at_caret();
@@ -405,6 +409,8 @@ void LineEdit::gui_input(const Ref<InputEvent> &p_event) {
drag_caret_force_displayed = true;
set_caret_at_pixel_pos(m->get_position().x);
}
+
+ return;
}
Ref<InputEventKey> k = p_event;
@@ -452,12 +458,15 @@ void LineEdit::gui_input(const Ref<InputEvent> &p_event) {
if (context_menu_enabled) {
if (k->is_action("ui_menu", true)) {
- _ensure_menu();
+ _update_context_menu();
Point2 pos = Point2(get_caret_pixel_pos().x, (get_size().y + theme_cache.font->get_height(theme_cache.font_size)) / 2);
menu->set_position(get_screen_position() + pos);
menu->reset_size();
menu->popup();
menu->grab_focus();
+
+ accept_event();
+ return;
}
}
@@ -467,6 +476,8 @@ void LineEdit::gui_input(const Ref<InputEvent> &p_event) {
if (DisplayServer::get_singleton()->has_feature(DisplayServer::FEATURE_VIRTUAL_KEYBOARD) && virtual_keyboard_enabled) {
DisplayServer::get_singleton()->virtual_keyboard_hide();
}
+ accept_event();
+ return;
}
if (is_shortcut_keys_enabled()) {
@@ -606,6 +617,7 @@ void LineEdit::gui_input(const Ref<InputEvent> &p_event) {
_text_changed();
}
accept_event();
+ return;
}
}
}
@@ -952,9 +964,9 @@ void LineEdit::_notification(int p_what) {
// 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) {
+ if (ime_text.is_empty() || ime_selection.y == 0) {
// Normal caret.
- CaretInfo caret = TS->shaped_text_get_carets(text_rid, caret_column);
+ CaretInfo caret = TS->shaped_text_get_carets(text_rid, ime_text.is_empty() ? caret_column : caret_column + ime_selection.x);
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);
@@ -980,6 +992,7 @@ void LineEdit::_notification(int p_what) {
}
} break;
}
+
RenderingServer::get_singleton()->canvas_item_add_rect(ci, caret.l_caret, caret_color);
} else {
if (caret.l_caret != Rect2() && caret.l_dir == TextServer::DIRECTION_AUTO) {
@@ -1009,7 +1022,8 @@ void LineEdit::_notification(int p_what) {
RenderingServer::get_singleton()->canvas_item_add_rect(ci, caret.t_caret, caret_color);
}
- } else {
+ }
+ if (!ime_text.is_empty()) {
{
// IME intermediate text range.
Vector<Vector2> sel = TS->shaped_text_get_selection(text_rid, caret_column, caret_column + ime_text.length());
@@ -1030,20 +1044,22 @@ void LineEdit::_notification(int p_what) {
}
{
// IME caret.
- Vector<Vector2> sel = TS->shaped_text_get_selection(text_rid, caret_column + ime_selection.x, caret_column + ime_selection.x + ime_selection.y);
- for (int i = 0; i < sel.size(); i++) {
- Rect2 rect = Rect2(sel[i].x + ofs.x, ofs.y, sel[i].y - sel[i].x, text_height);
- if (rect.position.x + rect.size.x <= x_ofs || rect.position.x > ofs_max) {
- continue;
- }
- if (rect.position.x < x_ofs) {
- rect.size.x -= (x_ofs - rect.position.x);
- rect.position.x = x_ofs;
- } else if (rect.position.x + rect.size.x > ofs_max) {
- rect.size.x = ofs_max - rect.position.x;
+ if (ime_selection.y > 0) {
+ Vector<Vector2> sel = TS->shaped_text_get_selection(text_rid, caret_column + ime_selection.x, caret_column + ime_selection.x + ime_selection.y);
+ for (int i = 0; i < sel.size(); i++) {
+ Rect2 rect = Rect2(sel[i].x + ofs.x, ofs.y, sel[i].y - sel[i].x, text_height);
+ if (rect.position.x + rect.size.x <= x_ofs || rect.position.x > ofs_max) {
+ continue;
+ }
+ if (rect.position.x < x_ofs) {
+ rect.size.x -= (x_ofs - rect.position.x);
+ rect.position.x = x_ofs;
+ } else if (rect.position.x + rect.size.x > ofs_max) {
+ rect.size.x = ofs_max - rect.position.x;
+ }
+ rect.size.y = caret_width * 3;
+ RenderingServer::get_singleton()->canvas_item_add_rect(ci, rect, caret_color);
}
- rect.size.y = caret_width * 3;
- RenderingServer::get_singleton()->canvas_item_add_rect(ci, rect, caret_color);
}
}
}
@@ -1052,7 +1068,8 @@ void LineEdit::_notification(int p_what) {
if (has_focus()) {
if (get_viewport()->get_window_id() != DisplayServer::INVALID_WINDOW_ID && DisplayServer::get_singleton()->has_feature(DisplayServer::FEATURE_IME)) {
DisplayServer::get_singleton()->window_set_ime_active(true, get_viewport()->get_window_id());
- DisplayServer::get_singleton()->window_set_ime_position(get_global_position() + Point2(using_placeholder ? 0 : x_ofs, y_ofs + TS->shaped_text_get_size(text_rid).y), get_viewport()->get_window_id());
+ Point2 pos = Point2(get_caret_pixel_pos().x, (get_size().y + theme_cache.font->get_height(theme_cache.font_size)) / 2);
+ DisplayServer::get_singleton()->window_set_ime_position(get_global_position() + pos, get_viewport()->get_window_id());
}
}
} break;
@@ -1071,8 +1088,8 @@ void LineEdit::_notification(int p_what) {
if (get_viewport()->get_window_id() != DisplayServer::INVALID_WINDOW_ID && DisplayServer::get_singleton()->has_feature(DisplayServer::FEATURE_IME)) {
DisplayServer::get_singleton()->window_set_ime_active(true, get_viewport()->get_window_id());
- Point2 column = Point2(get_caret_column(), 1) * get_minimum_size().height;
- DisplayServer::get_singleton()->window_set_ime_position(get_global_position() + column, get_viewport()->get_window_id());
+ Point2 pos = Point2(get_caret_pixel_pos().x, (get_size().y + theme_cache.font->get_height(theme_cache.font_size)) / 2);
+ DisplayServer::get_singleton()->window_set_ime_position(get_global_position() + pos, get_viewport()->get_window_id());
}
show_virtual_keyboard();
@@ -1103,6 +1120,11 @@ void LineEdit::_notification(int p_what) {
if (has_focus()) {
ime_text = DisplayServer::get_singleton()->ime_get_text();
ime_selection = DisplayServer::get_singleton()->ime_get_selection();
+
+ if (!ime_text.is_empty()) {
+ selection_delete();
+ }
+
_shape();
set_caret_column(caret_column); // Update scroll_offset
@@ -1714,6 +1736,10 @@ void LineEdit::insert_text_at_caret(String p_text) {
input_direction = (TextDirection)dir;
}
set_caret_column(caret_column + p_text.length());
+
+ if (!ime_text.is_empty()) {
+ _shape();
+ }
}
void LineEdit::clear_internal() {
@@ -2063,7 +2089,9 @@ bool LineEdit::is_menu_visible() const {
}
PopupMenu *LineEdit::get_menu() const {
- const_cast<LineEdit *>(this)->_ensure_menu();
+ if (!menu) {
+ const_cast<LineEdit *>(this)->_generate_context_menu();
+ }
return menu;
}
@@ -2321,6 +2349,115 @@ Key LineEdit::_get_menu_action_accelerator(const String &p_action) {
}
}
+void LineEdit::_generate_context_menu() {
+ menu = memnew(PopupMenu);
+ add_child(menu, false, INTERNAL_MODE_FRONT);
+
+ menu_dir = memnew(PopupMenu);
+ menu_dir->set_name("DirMenu");
+ menu_dir->add_radio_check_item(RTR("Same as Layout Direction"), MENU_DIR_INHERITED);
+ menu_dir->add_radio_check_item(RTR("Auto-Detect Direction"), MENU_DIR_AUTO);
+ menu_dir->add_radio_check_item(RTR("Left-to-Right"), MENU_DIR_LTR);
+ menu_dir->add_radio_check_item(RTR("Right-to-Left"), MENU_DIR_RTL);
+ menu->add_child(menu_dir, false, INTERNAL_MODE_FRONT);
+
+ menu_ctl = memnew(PopupMenu);
+ menu_ctl->set_name("CTLMenu");
+ menu_ctl->add_item(RTR("Left-to-Right Mark (LRM)"), MENU_INSERT_LRM);
+ menu_ctl->add_item(RTR("Right-to-Left Mark (RLM)"), MENU_INSERT_RLM);
+ menu_ctl->add_item(RTR("Start of Left-to-Right Embedding (LRE)"), MENU_INSERT_LRE);
+ menu_ctl->add_item(RTR("Start of Right-to-Left Embedding (RLE)"), MENU_INSERT_RLE);
+ menu_ctl->add_item(RTR("Start of Left-to-Right Override (LRO)"), MENU_INSERT_LRO);
+ menu_ctl->add_item(RTR("Start of Right-to-Left Override (RLO)"), MENU_INSERT_RLO);
+ menu_ctl->add_item(RTR("Pop Direction Formatting (PDF)"), MENU_INSERT_PDF);
+ menu_ctl->add_separator();
+ menu_ctl->add_item(RTR("Arabic Letter Mark (ALM)"), MENU_INSERT_ALM);
+ menu_ctl->add_item(RTR("Left-to-Right Isolate (LRI)"), MENU_INSERT_LRI);
+ menu_ctl->add_item(RTR("Right-to-Left Isolate (RLI)"), MENU_INSERT_RLI);
+ menu_ctl->add_item(RTR("First Strong Isolate (FSI)"), MENU_INSERT_FSI);
+ menu_ctl->add_item(RTR("Pop Direction Isolate (PDI)"), MENU_INSERT_PDI);
+ menu_ctl->add_separator();
+ menu_ctl->add_item(RTR("Zero-Width Joiner (ZWJ)"), MENU_INSERT_ZWJ);
+ menu_ctl->add_item(RTR("Zero-Width Non-Joiner (ZWNJ)"), MENU_INSERT_ZWNJ);
+ menu_ctl->add_item(RTR("Word Joiner (WJ)"), MENU_INSERT_WJ);
+ menu_ctl->add_item(RTR("Soft Hyphen (SHY)"), MENU_INSERT_SHY);
+ menu->add_child(menu_ctl, false, INTERNAL_MODE_FRONT);
+
+ menu->add_item(RTR("Cut"), MENU_CUT);
+ menu->add_item(RTR("Copy"), MENU_COPY);
+ menu->add_item(RTR("Paste"), MENU_PASTE);
+ menu->add_separator();
+ menu->add_item(RTR("Select All"), MENU_SELECT_ALL);
+ menu->add_item(RTR("Clear"), MENU_CLEAR);
+ menu->add_separator();
+ menu->add_item(RTR("Undo"), MENU_UNDO);
+ menu->add_item(RTR("Redo"), MENU_REDO);
+ menu->add_separator();
+ menu->add_submenu_item(RTR("Text Writing Direction"), "DirMenu", MENU_SUBMENU_TEXT_DIR);
+ menu->add_separator();
+ menu->add_check_item(RTR("Display Control Characters"), MENU_DISPLAY_UCC);
+ menu->add_submenu_item(RTR("Insert Control Character"), "CTLMenu", MENU_SUBMENU_INSERT_UCC);
+
+ menu->connect("id_pressed", callable_mp(this, &LineEdit::menu_option));
+ menu_dir->connect("id_pressed", callable_mp(this, &LineEdit::menu_option));
+ menu_ctl->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));
+}
+
+void LineEdit::_update_context_menu() {
+ if (!menu) {
+ _generate_context_menu();
+ }
+
+ int idx = -1;
+
+#define MENU_ITEM_ACTION_DISABLED(m_menu, m_id, m_action, m_disabled) \
+ idx = m_menu->get_item_index(m_id); \
+ if (idx >= 0) { \
+ m_menu->set_item_accelerator(idx, shortcut_keys_enabled ? _get_menu_action_accelerator(m_action) : Key::NONE); \
+ m_menu->set_item_disabled(idx, m_disabled); \
+ }
+
+#define MENU_ITEM_ACTION(m_menu, m_id, m_action) \
+ idx = m_menu->get_item_index(m_id); \
+ if (idx >= 0) { \
+ m_menu->set_item_accelerator(idx, shortcut_keys_enabled ? _get_menu_action_accelerator(m_action) : Key::NONE); \
+ }
+
+#define MENU_ITEM_DISABLED(m_menu, m_id, m_disabled) \
+ idx = m_menu->get_item_index(m_id); \
+ if (idx >= 0) { \
+ m_menu->set_item_disabled(idx, m_disabled); \
+ }
+
+#define MENU_ITEM_CHECKED(m_menu, m_id, m_checked) \
+ idx = m_menu->get_item_index(m_id); \
+ if (idx >= 0) { \
+ m_menu->set_item_checked(idx, m_checked); \
+ }
+
+ MENU_ITEM_ACTION_DISABLED(menu, MENU_CUT, "ui_cut", !editable)
+ MENU_ITEM_ACTION(menu, MENU_COPY, "ui_copy")
+ MENU_ITEM_ACTION_DISABLED(menu, MENU_PASTE, "ui_paste", !editable)
+ MENU_ITEM_ACTION_DISABLED(menu, MENU_SELECT_ALL, "ui_text_select_all", !selecting_enabled)
+ MENU_ITEM_DISABLED(menu, MENU_CLEAR, !editable)
+ MENU_ITEM_ACTION_DISABLED(menu, MENU_UNDO, "ui_undo", !editable || !has_undo())
+ MENU_ITEM_ACTION_DISABLED(menu, MENU_REDO, "ui_redo", !editable || !has_redo())
+ MENU_ITEM_CHECKED(menu_dir, MENU_DIR_INHERITED, text_direction == TEXT_DIRECTION_INHERITED)
+ MENU_ITEM_CHECKED(menu_dir, MENU_DIR_AUTO, text_direction == TEXT_DIRECTION_AUTO)
+ MENU_ITEM_CHECKED(menu_dir, MENU_DIR_LTR, text_direction == TEXT_DIRECTION_LTR)
+ MENU_ITEM_CHECKED(menu_dir, MENU_DIR_RTL, text_direction == TEXT_DIRECTION_RTL)
+ MENU_ITEM_CHECKED(menu, MENU_DISPLAY_UCC, draw_control_chars)
+ MENU_ITEM_DISABLED(menu, MENU_SUBMENU_INSERT_UCC, !editable)
+
+#undef MENU_ITEM_ACTION_DISABLED
+#undef MENU_ITEM_ACTION
+#undef MENU_ITEM_DISABLED
+#undef MENU_ITEM_CHECKED
+}
+
void LineEdit::_validate_property(PropertyInfo &p_property) const {
if (!caret_blink_enabled && p_property.name == "caret_blink_interval") {
p_property.usage = PROPERTY_USAGE_NO_EDITOR;
@@ -2415,11 +2552,13 @@ void LineEdit::_bind_methods() {
BIND_ENUM_CONSTANT(MENU_SELECT_ALL);
BIND_ENUM_CONSTANT(MENU_UNDO);
BIND_ENUM_CONSTANT(MENU_REDO);
+ BIND_ENUM_CONSTANT(MENU_SUBMENU_TEXT_DIR);
BIND_ENUM_CONSTANT(MENU_DIR_INHERITED);
BIND_ENUM_CONSTANT(MENU_DIR_AUTO);
BIND_ENUM_CONSTANT(MENU_DIR_LTR);
BIND_ENUM_CONSTANT(MENU_DIR_RTL);
BIND_ENUM_CONSTANT(MENU_DISPLAY_UCC);
+ BIND_ENUM_CONSTANT(MENU_SUBMENU_INSERT_UCC);
BIND_ENUM_CONSTANT(MENU_INSERT_LRM);
BIND_ENUM_CONSTANT(MENU_INSERT_RLM);
BIND_ENUM_CONSTANT(MENU_INSERT_LRE);
@@ -2482,86 +2621,6 @@ void LineEdit::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "structured_text_bidi_override_options"), "set_structured_text_bidi_override_options", "get_structured_text_bidi_override_options");
}
-void LineEdit::_ensure_menu() {
- if (!menu) {
- menu = memnew(PopupMenu);
- add_child(menu, false, INTERNAL_MODE_FRONT);
-
- menu_dir = memnew(PopupMenu);
- menu_dir->set_name("DirMenu");
- menu_dir->add_radio_check_item(RTR("Same as Layout Direction"), MENU_DIR_INHERITED);
- menu_dir->add_radio_check_item(RTR("Auto-Detect Direction"), MENU_DIR_AUTO);
- menu_dir->add_radio_check_item(RTR("Left-to-Right"), MENU_DIR_LTR);
- menu_dir->add_radio_check_item(RTR("Right-to-Left"), MENU_DIR_RTL);
- menu->add_child(menu_dir, false, INTERNAL_MODE_FRONT);
-
- menu_ctl = memnew(PopupMenu);
- menu_ctl->set_name("CTLMenu");
- menu_ctl->add_item(RTR("Left-to-Right Mark (LRM)"), MENU_INSERT_LRM);
- menu_ctl->add_item(RTR("Right-to-Left Mark (RLM)"), MENU_INSERT_RLM);
- menu_ctl->add_item(RTR("Start of Left-to-Right Embedding (LRE)"), MENU_INSERT_LRE);
- menu_ctl->add_item(RTR("Start of Right-to-Left Embedding (RLE)"), MENU_INSERT_RLE);
- menu_ctl->add_item(RTR("Start of Left-to-Right Override (LRO)"), MENU_INSERT_LRO);
- menu_ctl->add_item(RTR("Start of Right-to-Left Override (RLO)"), MENU_INSERT_RLO);
- menu_ctl->add_item(RTR("Pop Direction Formatting (PDF)"), MENU_INSERT_PDF);
- menu_ctl->add_separator();
- menu_ctl->add_item(RTR("Arabic Letter Mark (ALM)"), MENU_INSERT_ALM);
- menu_ctl->add_item(RTR("Left-to-Right Isolate (LRI)"), MENU_INSERT_LRI);
- menu_ctl->add_item(RTR("Right-to-Left Isolate (RLI)"), MENU_INSERT_RLI);
- menu_ctl->add_item(RTR("First Strong Isolate (FSI)"), MENU_INSERT_FSI);
- menu_ctl->add_item(RTR("Pop Direction Isolate (PDI)"), MENU_INSERT_PDI);
- menu_ctl->add_separator();
- menu_ctl->add_item(RTR("Zero-Width Joiner (ZWJ)"), MENU_INSERT_ZWJ);
- menu_ctl->add_item(RTR("Zero-Width Non-Joiner (ZWNJ)"), MENU_INSERT_ZWNJ);
- menu_ctl->add_item(RTR("Word Joiner (WJ)"), MENU_INSERT_WJ);
- menu_ctl->add_item(RTR("Soft Hyphen (SHY)"), MENU_INSERT_SHY);
- 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));
- }
-
- // Reorganize context menu.
- menu->clear();
- if (editable) {
- menu->add_item(RTR("Cut"), MENU_CUT, is_shortcut_keys_enabled() ? _get_menu_action_accelerator("ui_cut") : Key::NONE);
- }
- menu->add_item(RTR("Copy"), MENU_COPY, is_shortcut_keys_enabled() ? _get_menu_action_accelerator("ui_copy") : Key::NONE);
- if (editable) {
- menu->add_item(RTR("Paste"), MENU_PASTE, is_shortcut_keys_enabled() ? _get_menu_action_accelerator("ui_paste") : Key::NONE);
- }
- menu->add_separator();
- if (is_selecting_enabled()) {
- menu->add_item(RTR("Select All"), MENU_SELECT_ALL, is_shortcut_keys_enabled() ? _get_menu_action_accelerator("ui_text_select_all") : Key::NONE);
- }
- if (editable) {
- menu->add_item(RTR("Clear"), MENU_CLEAR);
- menu->add_separator();
- menu->add_item(RTR("Undo"), MENU_UNDO, is_shortcut_keys_enabled() ? _get_menu_action_accelerator("ui_undo") : Key::NONE);
- menu->add_item(RTR("Redo"), MENU_REDO, is_shortcut_keys_enabled() ? _get_menu_action_accelerator("ui_redo") : Key::NONE);
- }
- menu->add_separator();
- menu->add_submenu_item(RTR("Text Writing Direction"), "DirMenu");
- menu->add_separator();
- menu->add_check_item(RTR("Display Control Characters"), MENU_DISPLAY_UCC);
- menu->set_item_checked(menu->get_item_index(MENU_DISPLAY_UCC), draw_control_chars);
- if (editable) {
- menu->add_submenu_item(RTR("Insert Control Character"), "CTLMenu");
- }
- menu_dir->set_item_checked(menu_dir->get_item_index(MENU_DIR_INHERITED), text_direction == TEXT_DIRECTION_INHERITED);
- menu_dir->set_item_checked(menu_dir->get_item_index(MENU_DIR_AUTO), text_direction == TEXT_DIRECTION_AUTO);
- menu_dir->set_item_checked(menu_dir->get_item_index(MENU_DIR_LTR), text_direction == TEXT_DIRECTION_LTR);
- menu_dir->set_item_checked(menu_dir->get_item_index(MENU_DIR_RTL), text_direction == TEXT_DIRECTION_RTL);
-
- if (editable) {
- menu->set_item_disabled(menu->get_item_index(MENU_UNDO), !has_undo());
- menu->set_item_disabled(menu->get_item_index(MENU_REDO), !has_redo());
- }
-}
-
LineEdit::LineEdit(const String &p_placeholder) {
text_rid = TS->create_shaped_text();
_create_undo_state();
@@ -2576,7 +2635,7 @@ LineEdit::LineEdit(const String &p_placeholder) {
set_placeholder(p_placeholder);
- set_editable(true); // Initialise to opposite first, so we get past the early-out in set_editable.
+ set_editable(true); // Initialize to opposite first, so we get past the early-out in set_editable.
}
LineEdit::~LineEdit() {
diff --git a/scene/gui/line_edit.h b/scene/gui/line_edit.h
index 5107845a5e..81c506069a 100644
--- a/scene/gui/line_edit.h
+++ b/scene/gui/line_edit.h
@@ -46,11 +46,13 @@ public:
MENU_SELECT_ALL,
MENU_UNDO,
MENU_REDO,
+ MENU_SUBMENU_TEXT_DIR,
MENU_DIR_INHERITED,
MENU_DIR_AUTO,
MENU_DIR_LTR,
MENU_DIR_RTL,
MENU_DISPLAY_UCC,
+ MENU_SUBMENU_INSERT_UCC,
MENU_INSERT_LRM,
MENU_INSERT_RLM,
MENU_INSERT_LRE,
@@ -207,6 +209,8 @@ private:
void _create_undo_state();
Key _get_menu_action_accelerator(const String &p_action);
+ void _generate_context_menu();
+ void _update_context_menu();
void _shape();
void _fit_to_width();
@@ -239,8 +243,6 @@ private:
void _backspace(bool p_word = false, bool p_all_to_left = false);
void _delete(bool p_word = false, bool p_all_to_right = false);
- void _ensure_menu();
-
protected:
bool _is_over_clear_button(const Point2 &p_pos) const;
virtual void _update_theme_item_cache() override;
diff --git a/scene/gui/menu_bar.cpp b/scene/gui/menu_bar.cpp
index d262959e8a..5b27983851 100644
--- a/scene/gui/menu_bar.cpp
+++ b/scene/gui/menu_bar.cpp
@@ -214,10 +214,10 @@ void MenuBar::_update_submenu(const String &p_menu_name, PopupMenu *p_child) {
PopupMenu *pm = Object::cast_to<PopupMenu>(n);
ERR_FAIL_COND_MSG(!pm, "Item subnode is not a PopupMenu: " + p_child->get_item_submenu(i) + ".");
- DisplayServer::get_singleton()->global_menu_add_submenu_item(p_menu_name, p_child->get_item_text(i), p_menu_name + "/" + itos(i));
+ DisplayServer::get_singleton()->global_menu_add_submenu_item(p_menu_name, atr(p_child->get_item_text(i)), p_menu_name + "/" + itos(i));
_update_submenu(p_menu_name + "/" + itos(i), pm);
} else {
- int index = DisplayServer::get_singleton()->global_menu_add_item(p_menu_name, p_child->get_item_text(i), callable_mp(p_child, &PopupMenu::activate_item), Callable(), i);
+ int index = DisplayServer::get_singleton()->global_menu_add_item(p_menu_name, atr(p_child->get_item_text(i)), callable_mp(p_child, &PopupMenu::activate_item), Callable(), i);
if (p_child->is_item_checkable(i)) {
DisplayServer::get_singleton()->global_menu_set_item_checkable(p_menu_name, index, true);
@@ -290,7 +290,7 @@ void MenuBar::_update_menu() {
if (menu_cache[i].hidden) {
continue;
}
- String menu_name = String(popups[i]->get_meta("_menu_name", popups[i]->get_name()));
+ String menu_name = atr(String(popups[i]->get_meta("_menu_name", popups[i]->get_name())));
index = DisplayServer::get_singleton()->global_menu_add_submenu_item("_main", menu_name, root_name + "/" + itos(i), index);
if (menu_cache[i].disabled) {
@@ -525,7 +525,7 @@ void MenuBar::shape(Menu &p_menu) {
} else {
p_menu.text_buf->set_direction((TextServer::Direction)text_direction);
}
- p_menu.text_buf->add_string(p_menu.name, theme_cache.font, theme_cache.font_size, language);
+ p_menu.text_buf->add_string(atr(p_menu.name), theme_cache.font, theme_cache.font_size, language);
}
void MenuBar::_refresh_menu_names() {
@@ -842,27 +842,6 @@ String MenuBar::get_tooltip(const Point2 &p_pos) const {
}
}
-void MenuBar::get_translatable_strings(List<String> *p_strings) const {
- Vector<PopupMenu *> popups = _get_popups();
- for (int i = 0; i < popups.size(); i++) {
- PopupMenu *pm = popups[i];
-
- if (!pm->has_meta("_menu_name") && !pm->has_meta("_menu_tooltip")) {
- continue;
- }
-
- String name = pm->get_meta("_menu_name");
- if (!name.is_empty()) {
- p_strings->push_back(name);
- }
-
- String tooltip = pm->get_meta("_menu_tooltip");
- if (!tooltip.is_empty()) {
- p_strings->push_back(tooltip);
- }
- }
-}
-
MenuBar::MenuBar() {
set_process_shortcut_input(true);
}
diff --git a/scene/gui/menu_bar.h b/scene/gui/menu_bar.h
index 306fcc01ab..3436978a0e 100644
--- a/scene/gui/menu_bar.h
+++ b/scene/gui/menu_bar.h
@@ -170,7 +170,6 @@ public:
PopupMenu *get_menu_popup(int p_menu) const;
- virtual void get_translatable_strings(List<String> *p_strings) const override;
virtual String get_tooltip(const Point2 &p_pos) const override;
MenuBar();
diff --git a/scene/gui/option_button.cpp b/scene/gui/option_button.cpp
index f21b5f43c6..dc1d6cc73e 100644
--- a/scene/gui/option_button.cpp
+++ b/scene/gui/option_button.cpp
@@ -491,9 +491,11 @@ void OptionButton::show_popup() {
return;
}
- 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));
+ Rect2 rect = get_screen_rect();
+ rect.position.y += rect.size.height;
+ rect.size.height = 0;
+ popup->set_position(rect.position);
+ popup->set_size(rect.size);
// 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)) {
@@ -519,10 +521,6 @@ void OptionButton::show_popup() {
popup->popup();
}
-void OptionButton::get_translatable_strings(List<String> *p_strings) const {
- popup->get_translatable_strings(p_strings);
-}
-
void OptionButton::_validate_property(PropertyInfo &p_property) const {
if (p_property.name == "text" || p_property.name == "icon") {
p_property.usage = PROPERTY_USAGE_NONE;
diff --git a/scene/gui/option_button.h b/scene/gui/option_button.h
index 9e409356e2..d8e2f3209d 100644
--- a/scene/gui/option_button.h
+++ b/scene/gui/option_button.h
@@ -125,8 +125,6 @@ public:
PopupMenu *get_popup() const;
void show_popup();
- virtual void get_translatable_strings(List<String> *p_strings) const override;
-
OptionButton(const String &p_text = String());
~OptionButton();
};
diff --git a/scene/gui/popup.cpp b/scene/gui/popup.cpp
index c939e7a48a..2ea1b93810 100644
--- a/scene/gui/popup.cpp
+++ b/scene/gui/popup.cpp
@@ -59,9 +59,9 @@ void Popup::_initialize_visible_parents() {
void Popup::_deinitialize_visible_parents() {
if (is_embedded()) {
- for (uint32_t i = 0; i < visible_parents.size(); ++i) {
- visible_parents[i]->disconnect("focus_entered", callable_mp(this, &Popup::_parent_focused));
- visible_parents[i]->disconnect("tree_exited", callable_mp(this, &Popup::_deinitialize_visible_parents));
+ for (Window *parent_window : visible_parents) {
+ parent_window->disconnect("focus_entered", callable_mp(this, &Popup::_parent_focused));
+ parent_window->disconnect("tree_exited", callable_mp(this, &Popup::_deinitialize_visible_parents));
}
visible_parents.clear();
diff --git a/scene/gui/popup_menu.cpp b/scene/gui/popup_menu.cpp
index 942e6fac7f..0eeac2f285 100644
--- a/scene/gui/popup_menu.cpp
+++ b/scene/gui/popup_menu.cpp
@@ -395,10 +395,10 @@ void PopupMenu::gui_input(const Ref<InputEvent> &p_event) {
// Activate the item on release of either the left mouse button or
// any mouse button held down when the popup was opened.
// This allows for opening the popup and triggering an action in a single mouse click.
- if (button_idx == MouseButton::LEFT || (initial_button_mask & mouse_button_to_mask(button_idx)) != MouseButton::NONE) {
+ if (button_idx == MouseButton::LEFT || initial_button_mask.has_flag(mouse_button_to_mask(button_idx))) {
bool was_during_grabbed_click = during_grabbed_click;
during_grabbed_click = false;
- initial_button_mask = MouseButton::NONE;
+ initial_button_mask.clear();
// Disable clicks under a time threshold to avoid selection right when opening the popup.
uint64_t now = OS::get_singleton()->get_ticks_msec();
@@ -594,17 +594,17 @@ void PopupMenu::_draw_items() {
int content_left = content_center - content_size / 2;
int content_right = content_center + content_size / 2;
if (content_left > item_ofs.x) {
- int sep_h = theme_cache.labeled_separator_left->get_center_size().height + theme_cache.labeled_separator_left->get_minimum_size().height;
+ int sep_h = theme_cache.labeled_separator_left->get_minimum_size().height;
int sep_ofs = Math::floor((h - sep_h) / 2.0);
theme_cache.labeled_separator_left->draw(ci, Rect2(item_ofs + Point2(0, sep_ofs), Size2(MAX(0, content_left - item_ofs.x), sep_h)));
}
if (content_right < display_width) {
- int sep_h = theme_cache.labeled_separator_right->get_center_size().height + theme_cache.labeled_separator_right->get_minimum_size().height;
+ int sep_h = theme_cache.labeled_separator_right->get_minimum_size().height;
int sep_ofs = Math::floor((h - sep_h) / 2.0);
theme_cache.labeled_separator_right->draw(ci, Rect2(Point2(content_right, item_ofs.y + sep_ofs), Size2(MAX(0, display_width - content_right), sep_h)));
}
} else {
- int sep_h = theme_cache.separator_style->get_center_size().height + theme_cache.separator_style->get_minimum_size().height;
+ int sep_h = theme_cache.separator_style->get_minimum_size().height;
int sep_ofs = Math::floor((h - sep_h) / 2.0);
theme_cache.separator_style->draw(ci, Rect2(item_ofs + Point2(0, sep_ofs), Size2(display_width, sep_h)));
}
@@ -840,6 +840,9 @@ void PopupMenu::_notification(int p_what) {
float pm_delay = pm->get_submenu_popup_delay();
set_submenu_popup_delay(pm_delay);
}
+ if (!is_embedded()) {
+ set_flag(FLAG_NO_FOCUS, true);
+ }
} break;
case NOTIFICATION_THEME_CHANGED:
@@ -1841,14 +1844,6 @@ void PopupMenu::set_parent_rect(const Rect2 &p_rect) {
parent_rect = p_rect;
}
-void PopupMenu::get_translatable_strings(List<String> *p_strings) const {
- for (int i = 0; i < items.size(); i++) {
- if (!items[i].xl_text.is_empty()) {
- p_strings->push_back(items[i].xl_text);
- }
- }
-}
-
void PopupMenu::add_autohide_area(const Rect2 &p_area) {
autohide_areas.push_back(p_area);
}
diff --git a/scene/gui/popup_menu.h b/scene/gui/popup_menu.h
index 1e56f8c192..bcc02a890f 100644
--- a/scene/gui/popup_menu.h
+++ b/scene/gui/popup_menu.h
@@ -92,7 +92,7 @@ class PopupMenu : public Popup {
Timer *submenu_timer = nullptr;
List<Rect2> autohide_areas;
Vector<Item> items;
- MouseButton initial_button_mask = MouseButton::NONE;
+ BitField<MouseButtonMask> initial_button_mask;
bool during_grabbed_click = false;
int mouse_over = -1;
int submenu_over = -1;
@@ -284,8 +284,6 @@ public:
virtual String get_tooltip(const Point2 &p_pos) const;
- virtual void get_translatable_strings(List<String> *p_strings) const override;
-
void add_autohide_area(const Rect2 &p_area);
void clear_autohide_areas();
diff --git a/scene/gui/rich_text_label.cpp b/scene/gui/rich_text_label.cpp
index dea61fcf66..f9c9906efa 100644
--- a/scene/gui/rich_text_label.cpp
+++ b/scene/gui/rich_text_label.cpp
@@ -1797,7 +1797,9 @@ void RichTextLabel::_notification(int p_what) {
} break;
case NOTIFICATION_INTERNAL_PHYSICS_PROCESS: {
- queue_redraw();
+ if (is_visible_in_tree()) {
+ queue_redraw();
+ }
} break;
case NOTIFICATION_DRAW: {
@@ -2029,7 +2031,7 @@ void RichTextLabel::gui_input(const Ref<InputEvent> &p_event) {
}
}
if (b->get_button_index() == MouseButton::RIGHT && context_menu_enabled) {
- _generate_context_menu();
+ _update_context_menu();
menu->set_position(get_screen_position() + b->get_position());
menu->reset_size();
menu->popup();
@@ -2088,7 +2090,7 @@ void RichTextLabel::gui_input(const Ref<InputEvent> &p_event) {
}
if (k->is_action("ui_menu", true)) {
if (context_menu_enabled) {
- _generate_context_menu();
+ _update_context_menu();
menu->set_position(get_screen_position());
menu->reset_size();
menu->popup();
@@ -2665,19 +2667,26 @@ bool RichTextLabel::_find_layout_subitem(Item *from, Item *to) {
return false;
}
-void RichTextLabel::_thread_function(void *self) {
- RichTextLabel *rtl = reinterpret_cast<RichTextLabel *>(self);
- rtl->set_physics_process_internal(true);
- rtl->_process_line_caches();
- rtl->set_physics_process_internal(false);
- rtl->updating.store(false);
- rtl->call_deferred(SNAME("queue_redraw"));
+void RichTextLabel::_thread_function(void *p_userdata) {
+ _process_line_caches();
+ updating.store(false);
+ call_deferred(SNAME("thread_end"));
+}
+
+void RichTextLabel::_thread_end() {
+ set_physics_process_internal(false);
+ if (is_visible_in_tree()) {
+ queue_redraw();
+ }
}
void RichTextLabel::_stop_thread() {
if (threaded) {
stop_thread.store(true);
- thread.wait_to_finish();
+ if (task != WorkerThreadPool::INVALID_TASK_ID) {
+ WorkerThreadPool::get_singleton()->wait_for_task_completion(task);
+ task = WorkerThreadPool::INVALID_TASK_ID;
+ }
}
}
@@ -2778,7 +2787,7 @@ bool RichTextLabel::_validate_line_caches() {
main->first_resized_line.store(main->lines.size());
- if (fit_content_height) {
+ if (fit_content) {
update_minimum_size();
}
return true;
@@ -2787,7 +2796,8 @@ bool RichTextLabel::_validate_line_caches() {
if (threaded) {
updating.store(true);
loaded.store(true);
- thread.start(RichTextLabel::_thread_function, reinterpret_cast<void *>(this));
+ task = WorkerThreadPool::get_singleton()->add_template_task(this, &RichTextLabel::_thread_function, nullptr, true, vformat("RichTextLabelShape:%x", (int64_t)get_instance_id()));
+ set_physics_process_internal(true);
loading_started = OS::get_singleton()->get_ticks_msec();
return false;
} else {
@@ -2808,7 +2818,7 @@ void RichTextLabel::_process_line_caches() {
int ctrl_height = get_size().height;
int fi = main->first_invalid_line.load();
- int total_chars = (fi == 0) ? 0 : (main->lines[fi].char_offset + main->lines[fi].char_count);
+ int total_chars = main->lines[fi].char_offset;
float total_height = (fi == 0) ? 0 : _calculate_line_vertical_offset(main->lines[fi - 1]);
for (int i = fi; i < (int)main->lines.size(); i++) {
@@ -2862,7 +2872,7 @@ void RichTextLabel::_process_line_caches() {
main->first_resized_line.store(main->lines.size());
main->first_invalid_font_line.store(main->lines.size());
- if (fit_content_height) {
+ if (fit_content) {
update_minimum_size();
}
emit_signal(SNAME("finished"));
@@ -2963,7 +2973,7 @@ void RichTextLabel::_add_item(Item *p_item, bool p_enter, bool p_ensure_newline)
_invalidate_current_line(current_frame);
- if (fixed_width != -1) {
+ if (fit_content) {
update_minimum_size();
}
queue_redraw();
@@ -3336,6 +3346,7 @@ void RichTextLabel::push_table(int p_columns, InlineAlignment p_alignment, int p
_stop_thread();
MutexLock data_lock(data_mutex);
+ ERR_FAIL_COND(current->type == ITEM_TABLE);
ERR_FAIL_COND(p_columns < 1);
ItemTable *item = memnew(ItemTable);
@@ -3434,6 +3445,8 @@ void RichTextLabel::push_customfx(Ref<RichTextEffect> p_custom_effect, Dictionar
item->custom_effect = p_custom_effect;
item->char_fx_transform->environment = p_environment;
_add_item(item, true);
+
+ set_process_internal(true);
}
void RichTextLabel::set_table_column_expand(int p_column, bool p_expand, int p_ratio) {
@@ -3550,7 +3563,7 @@ void RichTextLabel::clear() {
scroll_following = true;
}
- if (fixed_width != -1) {
+ if (fit_content) {
update_minimum_size();
}
}
@@ -3571,15 +3584,17 @@ int RichTextLabel::get_tab_size() const {
return tab_size;
}
-void RichTextLabel::set_fit_content_height(bool p_enabled) {
- if (p_enabled != fit_content_height) {
- fit_content_height = p_enabled;
- update_minimum_size();
+void RichTextLabel::set_fit_content(bool p_enabled) {
+ if (p_enabled == fit_content) {
+ return;
}
+
+ fit_content = p_enabled;
+ update_minimum_size();
}
-bool RichTextLabel::is_fit_content_height_enabled() const {
- return fit_content_height;
+bool RichTextLabel::is_fit_content_enabled() const {
+ return fit_content;
}
void RichTextLabel::set_meta_underline(bool p_underline) {
@@ -4073,8 +4088,8 @@ void RichTextLabel::append_text(const String &p_bbcode) {
st_parser_type = TextServer::STRUCTURED_TEXT_EMAIL;
} else if (subtag_a[1] == "l" || subtag_a[1] == "list") {
st_parser_type = TextServer::STRUCTURED_TEXT_LIST;
- } else if (subtag_a[1] == "n" || subtag_a[1] == "none") {
- st_parser_type = TextServer::STRUCTURED_TEXT_NONE;
+ } else if (subtag_a[1] == "n" || subtag_a[1] == "gdscript") {
+ st_parser_type = TextServer::STRUCTURED_TEXT_GDSCRIPT;
} else if (subtag_a[1] == "c" || subtag_a[1] == "custom") {
st_parser_type = TextServer::STRUCTURED_TEXT_CUSTOM;
}
@@ -4549,7 +4564,6 @@ void RichTextLabel::append_text(const String &p_bbcode) {
push_customfx(effect, properties);
pos = brk_end + 1;
tag_stack.push_front(identifier);
- set_process_internal(true);
} else {
add_text("["); //ignore
pos = brk_pos + 1;
@@ -4978,7 +4992,9 @@ bool RichTextLabel::is_shortcut_keys_enabled() const {
// Context menu.
PopupMenu *RichTextLabel::get_menu() const {
- const_cast<RichTextLabel *>(this)->_generate_context_menu();
+ if (!menu) {
+ const_cast<RichTextLabel *>(this)->_generate_context_menu();
+ }
return menu;
}
@@ -5343,6 +5359,7 @@ void RichTextLabel::_bind_methods() {
ClassDB::bind_method(D_METHOD("push_cell"), &RichTextLabel::push_cell);
ClassDB::bind_method(D_METHOD("push_fgcolor", "fgcolor"), &RichTextLabel::push_fgcolor);
ClassDB::bind_method(D_METHOD("push_bgcolor", "bgcolor"), &RichTextLabel::push_bgcolor);
+ ClassDB::bind_method(D_METHOD("push_customfx", "effect", "env"), &RichTextLabel::push_customfx);
ClassDB::bind_method(D_METHOD("pop"), &RichTextLabel::pop);
ClassDB::bind_method(D_METHOD("clear"), &RichTextLabel::clear);
@@ -5380,8 +5397,8 @@ void RichTextLabel::_bind_methods() {
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);
- ClassDB::bind_method(D_METHOD("set_fit_content_height", "enabled"), &RichTextLabel::set_fit_content_height);
- ClassDB::bind_method(D_METHOD("is_fit_content_height_enabled"), &RichTextLabel::is_fit_content_height_enabled);
+ ClassDB::bind_method(D_METHOD("set_fit_content", "enabled"), &RichTextLabel::set_fit_content);
+ ClassDB::bind_method(D_METHOD("is_fit_content_enabled"), &RichTextLabel::is_fit_content_enabled);
ClassDB::bind_method(D_METHOD("set_selection_enabled", "enabled"), &RichTextLabel::set_selection_enabled);
ClassDB::bind_method(D_METHOD("is_selection_enabled"), &RichTextLabel::is_selection_enabled);
@@ -5451,12 +5468,15 @@ void RichTextLabel::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_menu"), &RichTextLabel::get_menu);
ClassDB::bind_method(D_METHOD("is_menu_visible"), &RichTextLabel::is_menu_visible);
+ ClassDB::bind_method(D_METHOD("menu_option", "option"), &RichTextLabel::menu_option);
+
+ ClassDB::bind_method(D_METHOD("_thread_end"), &RichTextLabel::_thread_end);
// Note: set "bbcode_enabled" first, to avoid unnecessary "text" resets.
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "bbcode_enabled"), "set_use_bbcode", "is_using_bbcode");
ADD_PROPERTY(PropertyInfo(Variant::STRING, "text", PROPERTY_HINT_MULTILINE_TEXT), "set_text", "get_text");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL, "fit_content_height"), "set_fit_content_height", "is_fit_content_height_enabled");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "fit_content"), "set_fit_content", "is_fit_content_enabled");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "scroll_active"), "set_scroll_active", "is_scroll_active");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "scroll_following"), "set_scroll_follow", "is_scroll_following");
ADD_PROPERTY(PropertyInfo(Variant::INT, "autowrap_mode", PROPERTY_HINT_ENUM, "Off,Arbitrary,Word,Word (Smart)"), "set_autowrap_mode", "get_autowrap_mode");
@@ -5527,6 +5547,10 @@ void RichTextLabel::_bind_methods() {
BIND_ENUM_CONSTANT(ITEM_HINT);
BIND_ENUM_CONSTANT(ITEM_DROPCAP);
BIND_ENUM_CONSTANT(ITEM_CUSTOMFX);
+
+ BIND_ENUM_CONSTANT(MENU_COPY);
+ BIND_ENUM_CONSTANT(MENU_SELECT_ALL);
+ BIND_ENUM_CONSTANT(MENU_MAX);
}
TextServer::VisibleCharactersBehavior RichTextLabel::get_visible_characters_behavior() const {
@@ -5643,44 +5667,47 @@ int RichTextLabel::get_total_glyph_count() const {
return tg;
}
-void RichTextLabel::set_fixed_size_to_width(int p_width) {
- if (fixed_width == p_width) {
- return;
- }
-
- fixed_width = p_width;
- update_minimum_size();
-}
-
Size2 RichTextLabel::get_minimum_size() const {
- Size2 size = theme_cache.normal_style->get_minimum_size();
+ Size2 sb_min_size = theme_cache.normal_style->get_minimum_size();
+ Size2 min_size;
- if (fixed_width != -1) {
- size.x += fixed_width;
+ if (fit_content) {
+ min_size.x = get_content_width();
+ min_size.y = get_content_height();
}
- if (fit_content_height) {
- size.y += get_content_height();
- }
-
- return size;
+ return sb_min_size +
+ ((autowrap_mode != TextServer::AUTOWRAP_OFF) ? Size2(1, min_size.height) : min_size);
}
// Context menu.
void RichTextLabel::_generate_context_menu() {
- if (!menu) {
- menu = memnew(PopupMenu);
- add_child(menu, false, INTERNAL_MODE_FRONT);
+ menu = memnew(PopupMenu);
+ add_child(menu, false, INTERNAL_MODE_FRONT);
+ menu->connect("id_pressed", callable_mp(this, &RichTextLabel::menu_option));
+
+ menu->add_item(RTR("Copy"), MENU_COPY);
+ menu->add_item(RTR("Select All"), MENU_SELECT_ALL);
+}
- menu->connect("id_pressed", callable_mp(this, &RichTextLabel::_menu_option));
+void RichTextLabel::_update_context_menu() {
+ if (!menu) {
+ _generate_context_menu();
}
- // Reorganize context menu.
- menu->clear();
- if (selection.enabled) {
- menu->add_item(RTR("Copy"), MENU_COPY, is_shortcut_keys_enabled() ? _get_menu_action_accelerator("ui_copy") : Key::NONE);
- menu->add_item(RTR("Select All"), MENU_SELECT_ALL, is_shortcut_keys_enabled() ? _get_menu_action_accelerator("ui_text_select_all") : Key::NONE);
+ int idx = -1;
+
+#define MENU_ITEM_ACTION_DISABLED(m_menu, m_id, m_action, m_disabled) \
+ idx = m_menu->get_item_index(m_id); \
+ if (idx >= 0) { \
+ m_menu->set_item_accelerator(idx, shortcut_keys_enabled ? _get_menu_action_accelerator(m_action) : Key::NONE); \
+ m_menu->set_item_disabled(idx, m_disabled); \
}
+
+ MENU_ITEM_ACTION_DISABLED(menu, MENU_COPY, "ui_copy", !selection.enabled)
+ MENU_ITEM_ACTION_DISABLED(menu, MENU_SELECT_ALL, "ui_text_select_all", !selection.enabled)
+
+#undef MENU_ITEM_ACTION_DISABLED
}
Key RichTextLabel::_get_menu_action_accelerator(const String &p_action) {
@@ -5708,7 +5735,7 @@ Key RichTextLabel::_get_menu_action_accelerator(const String &p_action) {
}
}
-void RichTextLabel::_menu_option(int p_option) {
+void RichTextLabel::menu_option(int p_option) {
switch (p_option) {
case MENU_COPY: {
selection_copy();
diff --git a/scene/gui/rich_text_label.h b/scene/gui/rich_text_label.h
index 8ac77d5b47..b01fccf14c 100644
--- a/scene/gui/rich_text_label.h
+++ b/scene/gui/rich_text_label.h
@@ -31,6 +31,7 @@
#ifndef RICH_TEXT_LABEL_H
#define RICH_TEXT_LABEL_H
+#include "core/object/worker_thread_pool.h"
#include "rich_text_effect.h"
#include "scene/gui/popup_menu.h"
#include "scene/gui/scroll_bar.h"
@@ -80,6 +81,7 @@ public:
enum MenuItems {
MENU_COPY,
MENU_SELECT_ALL,
+ MENU_MAX
};
enum DefaultFont {
@@ -369,7 +371,7 @@ private:
Item *current = nullptr;
ItemFrame *current_frame = nullptr;
- Thread thread;
+ WorkerThreadPool::TaskID task = WorkerThreadPool::INVALID_TASK_ID;
Mutex data_mutex;
bool threaded = false;
std::atomic<bool> stop_thread;
@@ -409,7 +411,8 @@ private:
void _invalidate_current_line(ItemFrame *p_frame);
- static void _thread_function(void *self);
+ void _thread_function(void *p_userdata);
+ void _thread_end();
void _stop_thread();
bool _validate_line_caches();
void _process_line_caches();
@@ -452,8 +455,8 @@ private:
// Context menu.
PopupMenu *menu = nullptr;
void _generate_context_menu();
+ void _update_context_menu();
Key _get_menu_action_accelerator(const String &p_action);
- void _menu_option(int p_option);
int visible_characters = -1;
float visible_ratio = 1.0;
@@ -524,9 +527,7 @@ private:
bool use_bbcode = false;
String text;
- int fixed_width = -1;
-
- bool fit_content_height = false;
+ bool fit_content = false;
struct ThemeCache {
Ref<StyleBox> normal_style;
@@ -640,8 +641,8 @@ public:
void set_shortcut_keys_enabled(bool p_enabled);
bool is_shortcut_keys_enabled() const;
- void set_fit_content_height(bool p_enabled);
- bool is_fit_content_height_enabled() const;
+ void set_fit_content(bool p_enabled);
+ bool is_fit_content_enabled() const;
bool search(const String &p_string, bool p_from_selection = false, bool p_search_previous = false);
@@ -688,6 +689,7 @@ public:
// Context menu.
PopupMenu *get_menu() const;
bool is_menu_visible() const;
+ void menu_option(int p_option);
void parse_bbcode(const String &p_bbcode);
void append_text(const String &p_bbcode);
@@ -731,7 +733,6 @@ public:
void install_effect(const Variant effect);
- void set_fixed_size_to_width(int p_width);
virtual Size2 get_minimum_size() const override;
RichTextLabel(const String &p_text = String());
@@ -740,5 +741,6 @@ public:
VARIANT_ENUM_CAST(RichTextLabel::ListType);
VARIANT_ENUM_CAST(RichTextLabel::ItemType);
+VARIANT_ENUM_CAST(RichTextLabel::MenuItems);
#endif // RICH_TEXT_LABEL_H
diff --git a/scene/gui/scroll_bar.cpp b/scene/gui/scroll_bar.cpp
index e617b2ca77..b8faf22a59 100644
--- a/scene/gui/scroll_bar.cpp
+++ b/scene/gui/scroll_bar.cpp
@@ -433,7 +433,7 @@ void ScrollBar::_notification(int p_what) {
double ScrollBar::get_grabber_min_size() const {
Ref<StyleBox> grabber = theme_cache.grabber_style;
- Size2 gminsize = grabber->get_minimum_size() + grabber->get_center_size();
+ Size2 gminsize = grabber->get_minimum_size();
return (orientation == VERTICAL) ? gminsize.height : gminsize.width;
}
@@ -500,7 +500,7 @@ Size2 ScrollBar::get_minimum_size() const {
Size2 minsize;
if (orientation == VERTICAL) {
- minsize.width = MAX(incr->get_size().width, (bg->get_minimum_size() + bg->get_center_size()).width);
+ minsize.width = MAX(incr->get_size().width, bg->get_minimum_size().width);
minsize.height += incr->get_size().height;
minsize.height += decr->get_size().height;
minsize.height += bg->get_minimum_size().height;
@@ -508,7 +508,7 @@ Size2 ScrollBar::get_minimum_size() const {
}
if (orientation == HORIZONTAL) {
- minsize.height = MAX(incr->get_size().height, (bg->get_center_size() + bg->get_minimum_size()).height);
+ minsize.height = MAX(incr->get_size().height, bg->get_minimum_size().height);
minsize.width += incr->get_size().width;
minsize.width += decr->get_size().width;
minsize.width += bg->get_minimum_size().width;
diff --git a/scene/gui/scroll_container.cpp b/scene/gui/scroll_container.cpp
index ed24f30197..b678f46091 100644
--- a/scene/gui/scroll_container.cpp
+++ b/scene/gui/scroll_container.cpp
@@ -327,10 +327,10 @@ void ScrollContainer::_reposition_children() {
Size2 minsize = c->get_combined_minimum_size();
Rect2 r = Rect2(-Size2(get_h_scroll(), get_v_scroll()), minsize);
- if (c->get_h_size_flags() & SIZE_EXPAND) {
+ if (c->get_h_size_flags().has_flag(SIZE_EXPAND)) {
r.size.width = MAX(size.width, minsize.width);
}
- if (c->get_v_size_flags() & SIZE_EXPAND) {
+ if (c->get_v_size_flags().has_flag(SIZE_EXPAND)) {
r.size.height = MAX(size.height, minsize.height);
}
r.position += ofs;
diff --git a/scene/gui/separator.cpp b/scene/gui/separator.cpp
index 45185de698..b0879c1931 100644
--- a/scene/gui/separator.cpp
+++ b/scene/gui/separator.cpp
@@ -51,7 +51,7 @@ void Separator::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_DRAW: {
Size2i size = get_size();
- Size2i ssize = theme_cache.separator_style->get_minimum_size() + theme_cache.separator_style->get_center_size();
+ Size2i ssize = theme_cache.separator_style->get_minimum_size();
if (orientation == VERTICAL) {
theme_cache.separator_style->draw(get_canvas_item(), Rect2((size.x - ssize.x) / 2, 0, ssize.x, size.y));
diff --git a/scene/gui/slider.cpp b/scene/gui/slider.cpp
index 040559dab8..292a4cfea2 100644
--- a/scene/gui/slider.cpp
+++ b/scene/gui/slider.cpp
@@ -33,7 +33,7 @@
#include "core/os/keyboard.h"
Size2 Slider::get_minimum_size() const {
- Size2i ss = theme_cache.slider_style->get_minimum_size() + theme_cache.slider_style->get_center_size();
+ Size2i ss = theme_cache.slider_style->get_minimum_size();
Size2i rs = theme_cache.grabber_icon->get_size();
if (orientation == HORIZONTAL) {
@@ -212,7 +212,7 @@ void Slider::_notification(int p_what) {
}
if (orientation == VERTICAL) {
- int widget_width = style->get_minimum_size().width + style->get_center_size().width;
+ int widget_width = style->get_minimum_size().width;
double areasize = size.height - grabber->get_size().height;
style->draw(ci, Rect2i(Point2i(size.width / 2 - widget_width / 2, 0), Size2i(widget_width, size.height)));
grabber_area->draw(ci, Rect2i(Point2i((size.width - widget_width) / 2, size.height - areasize * ratio - grabber->get_size().height / 2), Size2i(widget_width, areasize * ratio + grabber->get_size().height / 2)));
@@ -229,7 +229,7 @@ void Slider::_notification(int p_what) {
}
grabber->draw(ci, Point2i(size.width / 2 - grabber->get_size().width / 2 + get_theme_constant(SNAME("grabber_offset")), size.height - ratio * areasize - grabber->get_size().height));
} else {
- int widget_height = style->get_minimum_size().height + style->get_center_size().height;
+ int widget_height = style->get_minimum_size().height;
double areasize = size.width - grabber->get_size().width;
style->draw(ci, Rect2i(Point2i(0, (size.height - widget_height) / 2), Size2i(size.width, widget_height)));
diff --git a/scene/gui/spin_box.cpp b/scene/gui/spin_box.cpp
index 29458ea16c..f99b2edd54 100644
--- a/scene/gui/spin_box.cpp
+++ b/scene/gui/spin_box.cpp
@@ -176,7 +176,7 @@ void SpinBox::gui_input(const Ref<InputEvent> &p_event) {
Ref<InputEventMouseMotion> mm = p_event;
- if (mm.is_valid() && (mm->get_button_mask() & MouseButton::MASK_LEFT) != MouseButton::NONE) {
+ if (mm.is_valid() && (mm->get_button_mask().has_flag(MouseButtonMask::LEFT))) {
if (drag.enabled) {
drag.diff_y += mm->get_relative().y;
double diff_y = -0.01 * Math::pow(ABS(drag.diff_y), 1.8) * SIGN(drag.diff_y);
@@ -368,7 +368,7 @@ void SpinBox::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "update_on_text_changed"), "set_update_on_text_changed", "get_update_on_text_changed");
ADD_PROPERTY(PropertyInfo(Variant::STRING, "prefix"), "set_prefix", "get_prefix");
ADD_PROPERTY(PropertyInfo(Variant::STRING, "suffix"), "set_suffix", "get_suffix");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "custom_arrow_step"), "set_custom_arrow_step", "get_custom_arrow_step");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "custom_arrow_step", PROPERTY_HINT_RANGE, "0,10000,0.0001,or_greater"), "set_custom_arrow_step", "get_custom_arrow_step");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "select_all_on_focus"), "set_select_all_on_focus", "is_select_all_on_focus");
}
diff --git a/scene/gui/split_container.cpp b/scene/gui/split_container.cpp
index ead9550b93..0c0125df76 100644
--- a/scene/gui/split_container.cpp
+++ b/scene/gui/split_container.cpp
@@ -115,7 +115,7 @@ void SplitContainerDragger::_notification(int p_what) {
return;
}
- Ref<Texture2D> tex = sc->get_theme_icon(SNAME("grabber"));
+ Ref<Texture2D> tex = sc->_get_grabber_icon();
draw_texture(tex, (get_size() - tex->get_size()) / 2);
} break;
}
diff --git a/scene/gui/subviewport_container.cpp b/scene/gui/subviewport_container.cpp
index 440597c24a..f10e1c2cd1 100644
--- a/scene/gui/subviewport_container.cpp
+++ b/scene/gui/subviewport_container.cpp
@@ -85,7 +85,7 @@ void SubViewportContainer::set_stretch_shrink(int p_shrink) {
continue;
}
- c->set_size(get_size() / shrink);
+ c->set_size_force(get_size() / shrink);
}
queue_redraw();
@@ -116,7 +116,7 @@ void SubViewportContainer::_notification(int p_what) {
continue;
}
- c->set_size(get_size() / shrink);
+ c->set_size_force(get_size() / shrink);
}
} break;
@@ -180,24 +180,51 @@ void SubViewportContainer::input(const Ref<InputEvent> &p_event) {
return;
}
- Transform2D xform = get_global_transform_with_canvas();
+ if (_is_propagated_in_gui_input(p_event)) {
+ return;
+ }
- if (stretch) {
- Transform2D scale_xf;
- scale_xf.scale(Vector2(shrink, shrink));
- xform *= scale_xf;
+ _send_event_to_viewports(p_event);
+}
+
+void SubViewportContainer::gui_input(const Ref<InputEvent> &p_event) {
+ ERR_FAIL_COND(p_event.is_null());
+
+ if (Engine::get_singleton()->is_editor_hint()) {
+ return;
}
- Ref<InputEvent> ev = p_event->xformed_by(xform.affine_inverse());
+ if (!_is_propagated_in_gui_input(p_event)) {
+ return;
+ }
+ if (stretch && shrink > 1) {
+ Transform2D xform;
+ xform.scale(Vector2(1, 1) / shrink);
+ _send_event_to_viewports(p_event->xformed_by(xform));
+ } else {
+ _send_event_to_viewports(p_event);
+ }
+}
+
+void SubViewportContainer::_send_event_to_viewports(const Ref<InputEvent> &p_event) {
for (int i = 0; i < get_child_count(); i++) {
SubViewport *c = Object::cast_to<SubViewport>(get_child(i));
if (!c || c->is_input_disabled()) {
continue;
}
- c->push_input(ev);
+ c->push_input(p_event);
+ }
+}
+
+bool SubViewportContainer::_is_propagated_in_gui_input(const Ref<InputEvent> &p_event) {
+ // Propagation of events with a position property happen in gui_input
+ // Propagation of other events happen in input
+ if (Object::cast_to<InputEventMouse>(*p_event) || Object::cast_to<InputEventScreenDrag>(*p_event) || Object::cast_to<InputEventScreenTouch>(*p_event) || Object::cast_to<InputEventGesture>(*p_event)) {
+ return true;
}
+ return false;
}
void SubViewportContainer::unhandled_input(const Ref<InputEvent> &p_event) {
diff --git a/scene/gui/subviewport_container.h b/scene/gui/subviewport_container.h
index d918c4a615..d3236b0c4e 100644
--- a/scene/gui/subviewport_container.h
+++ b/scene/gui/subviewport_container.h
@@ -39,6 +39,8 @@ class SubViewportContainer : public Container {
bool stretch = false;
int shrink = 1;
void _notify_viewports(int p_notification);
+ bool _is_propagated_in_gui_input(const Ref<InputEvent> &p_event);
+ void _send_event_to_viewports(const Ref<InputEvent> &p_event);
protected:
void _notification(int p_what);
@@ -52,6 +54,7 @@ public:
bool is_stretch_enabled() const;
virtual void input(const Ref<InputEvent> &p_event) override;
+ virtual void gui_input(const Ref<InputEvent> &p_event) override;
virtual void unhandled_input(const Ref<InputEvent> &p_event) override;
void set_stretch_shrink(int p_shrink);
int get_stretch_shrink() const;
diff --git a/scene/gui/tab_bar.cpp b/scene/gui/tab_bar.cpp
index ce6ccc3fa4..eca6cb3eef 100644
--- a/scene/gui/tab_bar.cpp
+++ b/scene/gui/tab_bar.cpp
@@ -1577,6 +1577,7 @@ void TabBar::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_scroll_to_selected"), &TabBar::get_scroll_to_selected);
ClassDB::bind_method(D_METHOD("set_select_with_rmb", "enabled"), &TabBar::set_select_with_rmb);
ClassDB::bind_method(D_METHOD("get_select_with_rmb"), &TabBar::get_select_with_rmb);
+ ClassDB::bind_method(D_METHOD("clear_tabs"), &TabBar::clear_tabs);
ADD_SIGNAL(MethodInfo("tab_selected", PropertyInfo(Variant::INT, "tab")));
ADD_SIGNAL(MethodInfo("tab_changed", PropertyInfo(Variant::INT, "tab")));
diff --git a/scene/gui/tab_container.cpp b/scene/gui/tab_container.cpp
index 0d7b055ce8..208cb29772 100644
--- a/scene/gui/tab_container.cpp
+++ b/scene/gui/tab_container.cpp
@@ -803,22 +803,6 @@ Ref<Texture2D> TabContainer::get_tab_button_icon(int p_tab) const {
return tab_bar->get_tab_button_icon(p_tab);
}
-void TabContainer::get_translatable_strings(List<String> *p_strings) const {
- Vector<Control *> controls = _get_tab_controls();
- for (int i = 0; i < controls.size(); i++) {
- Control *c = controls[i];
-
- if (!c->has_meta("_tab_name")) {
- continue;
- }
-
- String name = c->get_meta("_tab_name");
- if (!name.is_empty()) {
- p_strings->push_back(name);
- }
- }
-}
-
Size2 TabContainer::get_minimum_size() const {
Size2 ms;
@@ -970,9 +954,6 @@ void TabContainer::_bind_methods() {
ClassDB::bind_method(D_METHOD("_repaint"), &TabContainer::_repaint);
ClassDB::bind_method(D_METHOD("_on_theme_changed"), &TabContainer::_on_theme_changed);
- ClassDB::bind_method(D_METHOD("_get_drag_data_fw"), &TabContainer::_get_drag_data_fw);
- ClassDB::bind_method(D_METHOD("_can_drop_data_fw"), &TabContainer::_can_drop_data_fw);
- ClassDB::bind_method(D_METHOD("_drop_data_fw"), &TabContainer::_drop_data_fw);
ADD_SIGNAL(MethodInfo("tab_changed", PropertyInfo(Variant::INT, "tab")));
ADD_SIGNAL(MethodInfo("tab_selected", PropertyInfo(Variant::INT, "tab")));
@@ -991,7 +972,7 @@ void TabContainer::_bind_methods() {
TabContainer::TabContainer() {
tab_bar = memnew(TabBar);
- tab_bar->set_drag_forwarding(this);
+ SET_DRAG_FORWARDING_GCDU(tab_bar, TabContainer);
add_child(tab_bar, false, INTERNAL_MODE_FRONT);
tab_bar->set_anchors_and_offsets_preset(Control::PRESET_TOP_WIDE);
tab_bar->connect("tab_changed", callable_mp(this, &TabContainer::_on_tab_changed));
diff --git a/scene/gui/tab_container.h b/scene/gui/tab_container.h
index 4a0205c2f4..3020e1fada 100644
--- a/scene/gui/tab_container.h
+++ b/scene/gui/tab_container.h
@@ -147,8 +147,6 @@ public:
virtual Size2 get_minimum_size() const override;
- virtual void get_translatable_strings(List<String> *p_strings) const override;
-
void set_popup(Node *p_popup);
Popup *get_popup() const;
diff --git a/scene/gui/text_edit.cpp b/scene/gui/text_edit.cpp
index 99d3df249e..d785280701 100644
--- a/scene/gui/text_edit.cpp
+++ b/scene/gui/text_edit.cpp
@@ -1208,7 +1208,15 @@ void TextEdit::_notification(int p_what) {
char_ofs = 0;
}
for (int j = 0; j < gl_size; j++) {
- const Variant *color_data = color_map.getptr(glyphs[j].start);
+ int64_t color_start = -1;
+ for (const Variant *key = color_map.next(nullptr); key; key = color_map.next(key)) {
+ if (int64_t(*key) <= glyphs[j].start) {
+ color_start = *key;
+ } else {
+ break;
+ }
+ }
+ const Variant *color_data = (color_start >= 0) ? color_map.getptr(color_start) : nullptr;
if (color_data != nullptr) {
current_color = (color_data->operator Dictionary()).get("color", font_color);
if (!editable && current_color.a > font_readonly_color.a) {
@@ -1311,11 +1319,12 @@ void TextEdit::_notification(int p_what) {
if (!clipped && get_caret_line(c) == line && carets_wrap_index[c] == line_wrap_index) {
carets.write[c].draw_pos.y = ofs_y + ldata->get_line_descent(line_wrap_index);
- if (ime_text.length() == 0) {
+ if (ime_text.is_empty() || ime_selection.y == 0) {
+ // Normal caret.
CaretInfo ts_caret;
- if (str.length() != 0) {
+ if (!str.is_empty() || !ime_text.is_empty()) {
// Get carets.
- ts_caret = TS->shaped_text_get_carets(rid, get_caret_column(c));
+ ts_caret = TS->shaped_text_get_carets(rid, ime_text.is_empty() ? get_caret_column(c) : get_caret_column(c) + ime_selection.x);
} else {
// No carets, add one at the start.
int h = font->get_height(font_size);
@@ -1418,7 +1427,8 @@ void TextEdit::_notification(int p_what) {
}
}
}
- } else {
+ }
+ if (!ime_text.is_empty()) {
{
// IME Intermediate text range.
Vector<Vector2> sel = TS->shaped_text_get_selection(rid, get_caret_column(c), get_caret_column(c) + ime_text.length());
@@ -1538,6 +1548,10 @@ void TextEdit::_notification(int p_what) {
ime_text = DisplayServer::get_singleton()->ime_get_text();
ime_selection = DisplayServer::get_singleton()->ime_get_selection();
+ if (!ime_text.is_empty()) {
+ delete_selection();
+ }
+
for (int i = 0; i < carets.size(); i++) {
String t;
if (get_caret_column(i) >= 0) {
@@ -1847,7 +1861,7 @@ void TextEdit::gui_input(const Ref<InputEvent> &p_gui_input) {
}
if (context_menu_enabled) {
- _generate_context_menu();
+ _update_context_menu();
menu->set_position(get_screen_position() + mpos);
menu->reset_size();
menu->popup();
@@ -1906,7 +1920,7 @@ void TextEdit::gui_input(const Ref<InputEvent> &p_gui_input) {
mpos.x = get_size().x - mpos.x;
}
- if ((mm->get_button_mask() & MouseButton::MASK_LEFT) != MouseButton::NONE && get_viewport()->gui_get_drag_data() == Variant()) { // Ignore if dragging.
+ if (mm->get_button_mask().has_flag(MouseButtonMask::LEFT) && get_viewport()->gui_get_drag_data() == Variant()) { // Ignore if dragging.
_reset_caret_blink_timer();
if (draw_minimap && !dragging_selection) {
@@ -2127,7 +2141,7 @@ void TextEdit::gui_input(const Ref<InputEvent> &p_gui_input) {
// MISC.
if (k->is_action("ui_menu", true)) {
if (context_menu_enabled) {
- _generate_context_menu();
+ _update_context_menu();
adjust_viewport_to_caret();
menu->set_position(get_screen_position() + get_caret_draw_pos());
menu->reset_size();
@@ -3530,6 +3544,19 @@ void TextEdit::insert_text_at_caret(const String &p_text, int p_caret) {
adjust_carets_after_edit(i, new_line, new_column, from_line, from_col);
}
+
+ if (!ime_text.is_empty()) {
+ for (int i = 0; i < carets.size(); i++) {
+ String t;
+ if (get_caret_column(i) >= 0) {
+ t = text[get_caret_line(i)].substr(0, get_caret_column(i)) + ime_text + text[get_caret_line(i)].substr(get_caret_column(i), text[get_caret_line(i)].length());
+ } else {
+ t = ime_text;
+ }
+ text.invalidate_cache(get_caret_line(i), get_caret_column(i), true, t, structured_text_parser(st_parser, st_args, t));
+ }
+ }
+
end_complex_operation();
queue_redraw();
}
@@ -3699,7 +3726,9 @@ void TextEdit::paste_primary_clipboard(int p_caret) {
// Context menu.
PopupMenu *TextEdit::get_menu() const {
- const_cast<TextEdit *>(this)->_generate_context_menu();
+ if (!menu) {
+ const_cast<TextEdit *>(this)->_generate_context_menu();
+ }
return menu;
}
@@ -6048,11 +6077,13 @@ void TextEdit::_bind_methods() {
BIND_ENUM_CONSTANT(MENU_SELECT_ALL);
BIND_ENUM_CONSTANT(MENU_UNDO);
BIND_ENUM_CONSTANT(MENU_REDO);
+ BIND_ENUM_CONSTANT(MENU_SUBMENU_TEXT_DIR);
BIND_ENUM_CONSTANT(MENU_DIR_INHERITED);
BIND_ENUM_CONSTANT(MENU_DIR_AUTO);
BIND_ENUM_CONSTANT(MENU_DIR_LTR);
BIND_ENUM_CONSTANT(MENU_DIR_RTL);
BIND_ENUM_CONSTANT(MENU_DISPLAY_UCC);
+ BIND_ENUM_CONSTANT(MENU_SUBMENU_INSERT_UCC);
BIND_ENUM_CONSTANT(MENU_INSERT_LRM);
BIND_ENUM_CONSTANT(MENU_INSERT_RLM);
BIND_ENUM_CONSTANT(MENU_INSERT_LRE);
@@ -6360,7 +6391,7 @@ void TextEdit::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "draw_tabs"), "set_draw_tabs", "is_drawing_tabs");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "draw_spaces"), "set_draw_spaces", "is_drawing_spaces");
- ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "syntax_highlighter", PROPERTY_HINT_RESOURCE_TYPE, "SyntaxHighlighter", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_DO_NOT_SHARE_ON_DUPLICATE), "set_syntax_highlighter", "get_syntax_highlighter");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "syntax_highlighter", PROPERTY_HINT_RESOURCE_TYPE, "SyntaxHighlighter", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_ALWAYS_DUPLICATE), "set_syntax_highlighter", "get_syntax_highlighter");
ADD_GROUP("Scroll", "scroll_");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "scroll_smooth"), "set_smooth_scroll_enabled", "is_smooth_scroll_enabled");
@@ -6403,10 +6434,8 @@ void TextEdit::_bind_methods() {
ADD_SIGNAL(MethodInfo("gutter_removed"));
/* Settings. */
- GLOBAL_DEF("gui/timers/text_edit_idle_detect_sec", 3);
- ProjectSettings::get_singleton()->set_custom_property_info("gui/timers/text_edit_idle_detect_sec", PropertyInfo(Variant::FLOAT, "gui/timers/text_edit_idle_detect_sec", PROPERTY_HINT_RANGE, "0,10,0.01,or_greater")); // No negative numbers.
- GLOBAL_DEF("gui/common/text_edit_undo_stack_max_size", 1024);
- ProjectSettings::get_singleton()->set_custom_property_info("gui/common/text_edit_undo_stack_max_size", PropertyInfo(Variant::INT, "gui/common/text_edit_undo_stack_max_size", PROPERTY_HINT_RANGE, "0,10000,1,or_greater")); // No negative numbers.
+ GLOBAL_DEF(PropertyInfo(Variant::FLOAT, "gui/timers/text_edit_idle_detect_sec", PROPERTY_HINT_RANGE, "0,10,0.01,or_greater"), 3);
+ GLOBAL_DEF(PropertyInfo(Variant::INT, "gui/common/text_edit_undo_stack_max_size", PROPERTY_HINT_RANGE, "0,10000,1,or_greater"), 1024);
}
/* Internal API for CodeEdit. */
@@ -6705,87 +6734,7 @@ void TextEdit::_paste_primary_clipboard_internal(int p_caret) {
grab_focus();
}
-/* Text. */
// Context menu.
-void TextEdit::_generate_context_menu() {
- if (!menu) {
- menu = memnew(PopupMenu);
- add_child(menu, false, INTERNAL_MODE_FRONT);
-
- menu_dir = memnew(PopupMenu);
- menu_dir->set_name("DirMenu");
- menu_dir->add_radio_check_item(RTR("Same as Layout Direction"), MENU_DIR_INHERITED);
- menu_dir->add_radio_check_item(RTR("Auto-Detect Direction"), MENU_DIR_AUTO);
- menu_dir->add_radio_check_item(RTR("Left-to-Right"), MENU_DIR_LTR);
- menu_dir->add_radio_check_item(RTR("Right-to-Left"), MENU_DIR_RTL);
- menu->add_child(menu_dir, false, INTERNAL_MODE_FRONT);
-
- menu_ctl = memnew(PopupMenu);
- menu_ctl->set_name("CTLMenu");
- menu_ctl->add_item(RTR("Left-to-Right Mark (LRM)"), MENU_INSERT_LRM);
- menu_ctl->add_item(RTR("Right-to-Left Mark (RLM)"), MENU_INSERT_RLM);
- menu_ctl->add_item(RTR("Start of Left-to-Right Embedding (LRE)"), MENU_INSERT_LRE);
- menu_ctl->add_item(RTR("Start of Right-to-Left Embedding (RLE)"), MENU_INSERT_RLE);
- menu_ctl->add_item(RTR("Start of Left-to-Right Override (LRO)"), MENU_INSERT_LRO);
- menu_ctl->add_item(RTR("Start of Right-to-Left Override (RLO)"), MENU_INSERT_RLO);
- menu_ctl->add_item(RTR("Pop Direction Formatting (PDF)"), MENU_INSERT_PDF);
- menu_ctl->add_separator();
- menu_ctl->add_item(RTR("Arabic Letter Mark (ALM)"), MENU_INSERT_ALM);
- menu_ctl->add_item(RTR("Left-to-Right Isolate (LRI)"), MENU_INSERT_LRI);
- menu_ctl->add_item(RTR("Right-to-Left Isolate (RLI)"), MENU_INSERT_RLI);
- menu_ctl->add_item(RTR("First Strong Isolate (FSI)"), MENU_INSERT_FSI);
- menu_ctl->add_item(RTR("Pop Direction Isolate (PDI)"), MENU_INSERT_PDI);
- menu_ctl->add_separator();
- menu_ctl->add_item(RTR("Zero-Width Joiner (ZWJ)"), MENU_INSERT_ZWJ);
- menu_ctl->add_item(RTR("Zero-Width Non-Joiner (ZWNJ)"), MENU_INSERT_ZWNJ);
- menu_ctl->add_item(RTR("Word Joiner (WJ)"), MENU_INSERT_WJ);
- menu_ctl->add_item(RTR("Soft Hyphen (SHY)"), MENU_INSERT_SHY);
- menu->add_child(menu_ctl, false, INTERNAL_MODE_FRONT);
-
- menu->connect("id_pressed", callable_mp(this, &TextEdit::menu_option));
- menu_dir->connect("id_pressed", callable_mp(this, &TextEdit::menu_option));
- menu_ctl->connect("id_pressed", callable_mp(this, &TextEdit::menu_option));
- }
-
- // Reorganize context menu.
- menu->clear();
- if (editable) {
- menu->add_item(RTR("Cut"), MENU_CUT, is_shortcut_keys_enabled() ? _get_menu_action_accelerator("ui_cut") : Key::NONE);
- }
- menu->add_item(RTR("Copy"), MENU_COPY, is_shortcut_keys_enabled() ? _get_menu_action_accelerator("ui_copy") : Key::NONE);
- if (editable) {
- menu->add_item(RTR("Paste"), MENU_PASTE, is_shortcut_keys_enabled() ? _get_menu_action_accelerator("ui_paste") : Key::NONE);
- }
- if (selecting_enabled || editable) {
- menu->add_separator();
- }
- if (selecting_enabled) {
- menu->add_item(RTR("Select All"), MENU_SELECT_ALL, is_shortcut_keys_enabled() ? _get_menu_action_accelerator("ui_text_select_all") : Key::NONE);
- }
- if (editable) {
- menu->add_item(RTR("Clear"), MENU_CLEAR);
- menu->add_separator();
- menu->add_item(RTR("Undo"), MENU_UNDO, is_shortcut_keys_enabled() ? _get_menu_action_accelerator("ui_undo") : Key::NONE);
- menu->add_item(RTR("Redo"), MENU_REDO, is_shortcut_keys_enabled() ? _get_menu_action_accelerator("ui_redo") : Key::NONE);
- }
- menu->add_separator();
- menu->add_submenu_item(RTR("Text Writing Direction"), "DirMenu");
- menu->add_separator();
- menu->add_check_item(RTR("Display Control Characters"), MENU_DISPLAY_UCC);
- menu->set_item_checked(menu->get_item_index(MENU_DISPLAY_UCC), draw_control_chars);
- if (editable) {
- menu->add_submenu_item(RTR("Insert Control Character"), "CTLMenu");
- }
- menu_dir->set_item_checked(menu_dir->get_item_index(MENU_DIR_INHERITED), text_direction == TEXT_DIRECTION_INHERITED);
- menu_dir->set_item_checked(menu_dir->get_item_index(MENU_DIR_AUTO), text_direction == TEXT_DIRECTION_AUTO);
- menu_dir->set_item_checked(menu_dir->get_item_index(MENU_DIR_LTR), text_direction == TEXT_DIRECTION_LTR);
- menu_dir->set_item_checked(menu_dir->get_item_index(MENU_DIR_RTL), text_direction == TEXT_DIRECTION_RTL);
-
- if (editable) {
- menu->set_item_disabled(menu->get_item_index(MENU_UNDO), !has_undo());
- menu->set_item_disabled(menu->get_item_index(MENU_REDO), !has_redo());
- }
-}
Key TextEdit::_get_menu_action_accelerator(const String &p_action) {
const List<Ref<InputEvent>> *events = InputMap::get_singleton()->action_get_events(p_action);
@@ -6812,6 +6761,112 @@ Key TextEdit::_get_menu_action_accelerator(const String &p_action) {
}
}
+void TextEdit::_generate_context_menu() {
+ menu = memnew(PopupMenu);
+ add_child(menu, false, INTERNAL_MODE_FRONT);
+
+ menu_dir = memnew(PopupMenu);
+ menu_dir->set_name("DirMenu");
+ menu_dir->add_radio_check_item(RTR("Same as Layout Direction"), MENU_DIR_INHERITED);
+ menu_dir->add_radio_check_item(RTR("Auto-Detect Direction"), MENU_DIR_AUTO);
+ menu_dir->add_radio_check_item(RTR("Left-to-Right"), MENU_DIR_LTR);
+ menu_dir->add_radio_check_item(RTR("Right-to-Left"), MENU_DIR_RTL);
+ menu->add_child(menu_dir, false, INTERNAL_MODE_FRONT);
+
+ menu_ctl = memnew(PopupMenu);
+ menu_ctl->set_name("CTLMenu");
+ menu_ctl->add_item(RTR("Left-to-Right Mark (LRM)"), MENU_INSERT_LRM);
+ menu_ctl->add_item(RTR("Right-to-Left Mark (RLM)"), MENU_INSERT_RLM);
+ menu_ctl->add_item(RTR("Start of Left-to-Right Embedding (LRE)"), MENU_INSERT_LRE);
+ menu_ctl->add_item(RTR("Start of Right-to-Left Embedding (RLE)"), MENU_INSERT_RLE);
+ menu_ctl->add_item(RTR("Start of Left-to-Right Override (LRO)"), MENU_INSERT_LRO);
+ menu_ctl->add_item(RTR("Start of Right-to-Left Override (RLO)"), MENU_INSERT_RLO);
+ menu_ctl->add_item(RTR("Pop Direction Formatting (PDF)"), MENU_INSERT_PDF);
+ menu_ctl->add_separator();
+ menu_ctl->add_item(RTR("Arabic Letter Mark (ALM)"), MENU_INSERT_ALM);
+ menu_ctl->add_item(RTR("Left-to-Right Isolate (LRI)"), MENU_INSERT_LRI);
+ menu_ctl->add_item(RTR("Right-to-Left Isolate (RLI)"), MENU_INSERT_RLI);
+ menu_ctl->add_item(RTR("First Strong Isolate (FSI)"), MENU_INSERT_FSI);
+ menu_ctl->add_item(RTR("Pop Direction Isolate (PDI)"), MENU_INSERT_PDI);
+ menu_ctl->add_separator();
+ menu_ctl->add_item(RTR("Zero-Width Joiner (ZWJ)"), MENU_INSERT_ZWJ);
+ menu_ctl->add_item(RTR("Zero-Width Non-Joiner (ZWNJ)"), MENU_INSERT_ZWNJ);
+ menu_ctl->add_item(RTR("Word Joiner (WJ)"), MENU_INSERT_WJ);
+ menu_ctl->add_item(RTR("Soft Hyphen (SHY)"), MENU_INSERT_SHY);
+ menu->add_child(menu_ctl, false, INTERNAL_MODE_FRONT);
+
+ menu->add_item(RTR("Cut"), MENU_CUT);
+ menu->add_item(RTR("Copy"), MENU_COPY);
+ menu->add_item(RTR("Paste"), MENU_PASTE);
+ menu->add_separator();
+ menu->add_item(RTR("Select All"), MENU_SELECT_ALL);
+ menu->add_item(RTR("Clear"), MENU_CLEAR);
+ menu->add_separator();
+ menu->add_item(RTR("Undo"), MENU_UNDO);
+ menu->add_item(RTR("Redo"), MENU_REDO);
+ menu->add_separator();
+ menu->add_submenu_item(RTR("Text Writing Direction"), "DirMenu", MENU_SUBMENU_TEXT_DIR);
+ menu->add_separator();
+ menu->add_check_item(RTR("Display Control Characters"), MENU_DISPLAY_UCC);
+ menu->add_submenu_item(RTR("Insert Control Character"), "CTLMenu", MENU_SUBMENU_INSERT_UCC);
+
+ menu->connect("id_pressed", callable_mp(this, &TextEdit::menu_option));
+ menu_dir->connect("id_pressed", callable_mp(this, &TextEdit::menu_option));
+ menu_ctl->connect("id_pressed", callable_mp(this, &TextEdit::menu_option));
+}
+
+void TextEdit::_update_context_menu() {
+ if (!menu) {
+ _generate_context_menu();
+ }
+
+ int idx = -1;
+
+#define MENU_ITEM_ACTION_DISABLED(m_menu, m_id, m_action, m_disabled) \
+ idx = m_menu->get_item_index(m_id); \
+ if (idx >= 0) { \
+ m_menu->set_item_accelerator(idx, shortcut_keys_enabled ? _get_menu_action_accelerator(m_action) : Key::NONE); \
+ m_menu->set_item_disabled(idx, m_disabled); \
+ }
+
+#define MENU_ITEM_ACTION(m_menu, m_id, m_action) \
+ idx = m_menu->get_item_index(m_id); \
+ if (idx >= 0) { \
+ m_menu->set_item_accelerator(idx, shortcut_keys_enabled ? _get_menu_action_accelerator(m_action) : Key::NONE); \
+ }
+
+#define MENU_ITEM_DISABLED(m_menu, m_id, m_disabled) \
+ idx = m_menu->get_item_index(m_id); \
+ if (idx >= 0) { \
+ m_menu->set_item_disabled(idx, m_disabled); \
+ }
+
+#define MENU_ITEM_CHECKED(m_menu, m_id, m_checked) \
+ idx = m_menu->get_item_index(m_id); \
+ if (idx >= 0) { \
+ m_menu->set_item_checked(idx, m_checked); \
+ }
+
+ MENU_ITEM_ACTION_DISABLED(menu, MENU_CUT, "ui_cut", !editable)
+ MENU_ITEM_ACTION(menu, MENU_COPY, "ui_copy")
+ MENU_ITEM_ACTION_DISABLED(menu, MENU_PASTE, "ui_paste", !editable)
+ MENU_ITEM_ACTION_DISABLED(menu, MENU_SELECT_ALL, "ui_text_select_all", !selecting_enabled)
+ MENU_ITEM_DISABLED(menu, MENU_CLEAR, !editable)
+ MENU_ITEM_ACTION_DISABLED(menu, MENU_UNDO, "ui_undo", !editable || !has_undo())
+ MENU_ITEM_ACTION_DISABLED(menu, MENU_REDO, "ui_redo", !editable || !has_redo())
+ MENU_ITEM_CHECKED(menu_dir, MENU_DIR_INHERITED, text_direction == TEXT_DIRECTION_INHERITED)
+ MENU_ITEM_CHECKED(menu_dir, MENU_DIR_AUTO, text_direction == TEXT_DIRECTION_AUTO)
+ MENU_ITEM_CHECKED(menu_dir, MENU_DIR_LTR, text_direction == TEXT_DIRECTION_LTR)
+ MENU_ITEM_CHECKED(menu_dir, MENU_DIR_RTL, text_direction == TEXT_DIRECTION_RTL)
+ MENU_ITEM_CHECKED(menu, MENU_DISPLAY_UCC, draw_control_chars)
+ MENU_ITEM_DISABLED(menu, MENU_SUBMENU_INSERT_UCC, !editable)
+
+#undef MENU_ITEM_ACTION_DISABLED
+#undef MENU_ITEM_ACTION
+#undef MENU_ITEM_DISABLED
+#undef MENU_ITEM_CHECKED
+}
+
/* Versioning */
void TextEdit::_push_current_op() {
if (pending_action_end) {
diff --git a/scene/gui/text_edit.h b/scene/gui/text_edit.h
index 426acc4996..a084fa3833 100644
--- a/scene/gui/text_edit.h
+++ b/scene/gui/text_edit.h
@@ -87,11 +87,13 @@ public:
MENU_SELECT_ALL,
MENU_UNDO,
MENU_REDO,
+ MENU_SUBMENU_TEXT_DIR,
MENU_DIR_INHERITED,
MENU_DIR_AUTO,
MENU_DIR_LTR,
MENU_DIR_RTL,
MENU_DISPLAY_UCC,
+ MENU_SUBMENU_INSERT_UCC,
MENU_INSERT_LRM,
MENU_INSERT_RLM,
MENU_INSERT_LRE,
@@ -274,7 +276,7 @@ private:
void _update_placeholder();
- /* Initialise to opposite first, so we get past the early-out in set_editable. */
+ /* Initialize to opposite first, so we get past the early-out in set_editable. */
bool editable = false;
TextDirection text_direction = TEXT_DIRECTION_AUTO;
@@ -303,8 +305,9 @@ private:
PopupMenu *menu_dir = nullptr;
PopupMenu *menu_ctl = nullptr;
- void _generate_context_menu();
Key _get_menu_action_accelerator(const String &p_action);
+ void _generate_context_menu();
+ void _update_context_menu();
/* Versioning */
struct Caret;
diff --git a/scene/gui/texture_rect.cpp b/scene/gui/texture_rect.cpp
index ac6d0cd453..20472ab46e 100644
--- a/scene/gui/texture_rect.cpp
+++ b/scene/gui/texture_rect.cpp
@@ -110,22 +110,45 @@ void TextureRect::_notification(int p_what) {
draw_texture_rect(texture, Rect2(offset, size), tile);
}
} break;
+ case NOTIFICATION_RESIZED: {
+ update_minimum_size();
+ } break;
}
}
Size2 TextureRect::get_minimum_size() const {
- if (!ignore_texture_size && !texture.is_null()) {
- return texture->get_size();
- } else {
- return Size2();
+ if (!texture.is_null()) {
+ switch (expand_mode) {
+ case EXPAND_KEEP_SIZE: {
+ return texture->get_size();
+ } break;
+ case EXPAND_IGNORE_SIZE: {
+ return Size2();
+ } break;
+ case EXPAND_FIT_WIDTH: {
+ return Size2(get_size().y, 0);
+ } break;
+ case EXPAND_FIT_WIDTH_PROPORTIONAL: {
+ real_t ratio = real_t(texture->get_width()) / texture->get_height();
+ return Size2(get_size().y * ratio, 0);
+ } break;
+ case EXPAND_FIT_HEIGHT: {
+ return Size2(0, get_size().x);
+ } break;
+ case EXPAND_FIT_HEIGHT_PROPORTIONAL: {
+ real_t ratio = real_t(texture->get_height()) / texture->get_width();
+ return Size2(0, get_size().x * ratio);
+ } break;
+ }
}
+ return Size2();
}
void TextureRect::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_texture", "texture"), &TextureRect::set_texture);
ClassDB::bind_method(D_METHOD("get_texture"), &TextureRect::get_texture);
- ClassDB::bind_method(D_METHOD("set_ignore_texture_size", "ignore"), &TextureRect::set_ignore_texture_size);
- ClassDB::bind_method(D_METHOD("get_ignore_texture_size"), &TextureRect::get_ignore_texture_size);
+ ClassDB::bind_method(D_METHOD("set_expand_mode", "expand_mode"), &TextureRect::set_expand_mode);
+ ClassDB::bind_method(D_METHOD("get_expand_mode"), &TextureRect::get_expand_mode);
ClassDB::bind_method(D_METHOD("set_flip_h", "enable"), &TextureRect::set_flip_h);
ClassDB::bind_method(D_METHOD("is_flipped_h"), &TextureRect::is_flipped_h);
ClassDB::bind_method(D_METHOD("set_flip_v", "enable"), &TextureRect::set_flip_v);
@@ -134,11 +157,18 @@ void TextureRect::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_stretch_mode"), &TextureRect::get_stretch_mode);
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture2D"), "set_texture", "get_texture");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL, "ignore_texture_size"), "set_ignore_texture_size", "get_ignore_texture_size");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "expand_mode", PROPERTY_HINT_ENUM, "Keep Size,Ignore Size,Fit Width,Fit Width Proportional,Fit Height,Fit Height Proportional"), "set_expand_mode", "get_expand_mode");
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");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "flip_h"), "set_flip_h", "is_flipped_h");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "flip_v"), "set_flip_v", "is_flipped_v");
+ BIND_ENUM_CONSTANT(EXPAND_KEEP_SIZE);
+ BIND_ENUM_CONSTANT(EXPAND_IGNORE_SIZE);
+ BIND_ENUM_CONSTANT(EXPAND_FIT_WIDTH);
+ BIND_ENUM_CONSTANT(EXPAND_FIT_WIDTH_PROPORTIONAL);
+ BIND_ENUM_CONSTANT(EXPAND_FIT_HEIGHT);
+ BIND_ENUM_CONSTANT(EXPAND_FIT_HEIGHT_PROPORTIONAL);
+
BIND_ENUM_CONSTANT(STRETCH_SCALE);
BIND_ENUM_CONSTANT(STRETCH_TILE);
BIND_ENUM_CONSTANT(STRETCH_KEEP);
@@ -148,6 +178,16 @@ void TextureRect::_bind_methods() {
BIND_ENUM_CONSTANT(STRETCH_KEEP_ASPECT_COVERED);
}
+#ifndef DISABLE_DEPRECATED
+bool TextureRect::_set(const StringName &p_name, const Variant &p_value) {
+ if ((p_name == SNAME("expand") || p_name == SNAME("ignore_texture_size")) && p_value.operator bool()) {
+ expand_mode = EXPAND_IGNORE_SIZE;
+ return true;
+ }
+ return false;
+}
+#endif
+
void TextureRect::_texture_changed() {
if (texture.is_valid()) {
queue_redraw();
@@ -178,18 +218,18 @@ Ref<Texture2D> TextureRect::get_texture() const {
return texture;
}
-void TextureRect::set_ignore_texture_size(bool p_ignore) {
- if (ignore_texture_size == p_ignore) {
+void TextureRect::set_expand_mode(ExpandMode p_mode) {
+ if (expand_mode == p_mode) {
return;
}
- ignore_texture_size = p_ignore;
+ expand_mode = p_mode;
queue_redraw();
update_minimum_size();
}
-bool TextureRect::get_ignore_texture_size() const {
- return ignore_texture_size;
+TextureRect::ExpandMode TextureRect::get_expand_mode() const {
+ return expand_mode;
}
void TextureRect::set_stretch_mode(StretchMode p_mode) {
diff --git a/scene/gui/texture_rect.h b/scene/gui/texture_rect.h
index c56fee91e1..2425c6094b 100644
--- a/scene/gui/texture_rect.h
+++ b/scene/gui/texture_rect.h
@@ -37,6 +37,15 @@ class TextureRect : public Control {
GDCLASS(TextureRect, Control);
public:
+ enum ExpandMode {
+ EXPAND_KEEP_SIZE,
+ EXPAND_IGNORE_SIZE,
+ EXPAND_FIT_WIDTH,
+ EXPAND_FIT_WIDTH_PROPORTIONAL,
+ EXPAND_FIT_HEIGHT,
+ EXPAND_FIT_HEIGHT_PROPORTIONAL,
+ };
+
enum StretchMode {
STRETCH_SCALE,
STRETCH_TILE,
@@ -48,10 +57,10 @@ public:
};
private:
- bool ignore_texture_size = false;
bool hflip = false;
bool vflip = false;
Ref<Texture2D> texture;
+ ExpandMode expand_mode = EXPAND_KEEP_SIZE;
StretchMode stretch_mode = STRETCH_SCALE;
void _texture_changed();
@@ -60,13 +69,16 @@ protected:
void _notification(int p_what);
virtual Size2 get_minimum_size() const override;
static void _bind_methods();
+#ifndef DISABLE_DEPRECATED
+ bool _set(const StringName &p_name, const Variant &p_value);
+#endif
public:
void set_texture(const Ref<Texture2D> &p_tex);
Ref<Texture2D> get_texture() const;
- void set_ignore_texture_size(bool p_ignore);
- bool get_ignore_texture_size() const;
+ void set_expand_mode(ExpandMode p_mode);
+ ExpandMode get_expand_mode() const;
void set_stretch_mode(StretchMode p_mode);
StretchMode get_stretch_mode() const;
@@ -81,6 +93,7 @@ public:
~TextureRect();
};
+VARIANT_ENUM_CAST(TextureRect::ExpandMode);
VARIANT_ENUM_CAST(TextureRect::StretchMode);
#endif // TEXTURE_RECT_H
diff --git a/scene/gui/tree.cpp b/scene/gui/tree.cpp
index ace3edfcb0..f8c2e9f4ad 100644
--- a/scene/gui/tree.cpp
+++ b/scene/gui/tree.cpp
@@ -332,7 +332,7 @@ void TreeItem::set_structured_text_bidi_override(int p_column, TextServer::Struc
}
TextServer::StructuredTextParser TreeItem::get_structured_text_bidi_override(int p_column) const {
- ERR_FAIL_INDEX_V(p_column, cells.size(), TextServer::STRUCTURED_TEXT_NONE);
+ ERR_FAIL_INDEX_V(p_column, cells.size(), TextServer::STRUCTURED_TEXT_DEFAULT);
return cells[p_column].st_parser;
}
@@ -657,7 +657,7 @@ int TreeItem::get_custom_minimum_height() const {
/* Item manipulation */
-TreeItem *TreeItem::create_child(int p_idx) {
+TreeItem *TreeItem::create_child(int p_index) {
TreeItem *ti = memnew(TreeItem(tree));
if (tree) {
ti->cells.resize(tree->columns.size());
@@ -669,7 +669,7 @@ TreeItem *TreeItem::create_child(int p_idx) {
int idx = 0;
while (c) {
- if (idx++ == p_idx) {
+ if (idx++ == p_index) {
c->prev = ti;
ti->next = c;
break;
@@ -683,7 +683,7 @@ TreeItem *TreeItem::create_child(int p_idx) {
ti->prev = l_prev;
if (!children_cache.is_empty()) {
if (ti->next) {
- children_cache.insert(p_idx, ti);
+ children_cache.insert(p_index, ti);
} else {
children_cache.append(ti);
}
@@ -826,15 +826,15 @@ TreeItem *TreeItem::get_next_visible(bool p_wrap) {
return next_item;
}
-TreeItem *TreeItem::get_child(int p_idx) {
+TreeItem *TreeItem::get_child(int p_index) {
_create_children_cache();
- if (p_idx < 0) {
- p_idx += children_cache.size();
+ if (p_index < 0) {
+ p_index += children_cache.size();
}
- ERR_FAIL_INDEX_V(p_idx, children_cache.size(), nullptr);
+ ERR_FAIL_INDEX_V(p_index, children_cache.size(), nullptr);
- return children_cache.get(p_idx);
+ return children_cache.get(p_index);
}
int TreeItem::get_visible_child_count() {
@@ -1058,28 +1058,28 @@ int TreeItem::get_button_count(int p_column) const {
return cells[p_column].buttons.size();
}
-Ref<Texture2D> TreeItem::get_button(int p_column, int p_idx) const {
+Ref<Texture2D> TreeItem::get_button(int p_column, int p_index) const {
ERR_FAIL_INDEX_V(p_column, cells.size(), Ref<Texture2D>());
- ERR_FAIL_INDEX_V(p_idx, cells[p_column].buttons.size(), Ref<Texture2D>());
- return cells[p_column].buttons[p_idx].texture;
+ ERR_FAIL_INDEX_V(p_index, cells[p_column].buttons.size(), Ref<Texture2D>());
+ return cells[p_column].buttons[p_index].texture;
}
-String TreeItem::get_button_tooltip_text(int p_column, int p_idx) const {
+String TreeItem::get_button_tooltip_text(int p_column, int p_index) const {
ERR_FAIL_INDEX_V(p_column, cells.size(), String());
- ERR_FAIL_INDEX_V(p_idx, cells[p_column].buttons.size(), String());
- return cells[p_column].buttons[p_idx].tooltip;
+ ERR_FAIL_INDEX_V(p_index, cells[p_column].buttons.size(), String());
+ return cells[p_column].buttons[p_index].tooltip;
}
-int TreeItem::get_button_id(int p_column, int p_idx) const {
+int TreeItem::get_button_id(int p_column, int p_index) const {
ERR_FAIL_INDEX_V(p_column, cells.size(), -1);
- ERR_FAIL_INDEX_V(p_idx, cells[p_column].buttons.size(), -1);
- return cells[p_column].buttons[p_idx].id;
+ ERR_FAIL_INDEX_V(p_index, cells[p_column].buttons.size(), -1);
+ return cells[p_column].buttons[p_index].id;
}
-void TreeItem::erase_button(int p_column, int p_idx) {
+void TreeItem::erase_button(int p_column, int p_index) {
ERR_FAIL_INDEX(p_column, cells.size());
- ERR_FAIL_INDEX(p_idx, cells[p_column].buttons.size());
- cells.write[p_column].buttons.remove_at(p_idx);
+ ERR_FAIL_INDEX(p_index, cells[p_column].buttons.size());
+ cells.write[p_column].buttons.remove_at(p_index);
_changed_notify(p_column);
}
@@ -1094,52 +1094,52 @@ int TreeItem::get_button_by_id(int p_column, int p_id) const {
return -1;
}
-void TreeItem::set_button(int p_column, int p_idx, const Ref<Texture2D> &p_button) {
+void TreeItem::set_button(int p_column, int p_index, const Ref<Texture2D> &p_button) {
ERR_FAIL_COND(p_button.is_null());
ERR_FAIL_INDEX(p_column, cells.size());
- ERR_FAIL_INDEX(p_idx, cells[p_column].buttons.size());
+ ERR_FAIL_INDEX(p_index, cells[p_column].buttons.size());
- if (cells[p_column].buttons[p_idx].texture == p_button) {
+ if (cells[p_column].buttons[p_index].texture == p_button) {
return;
}
- cells.write[p_column].buttons.write[p_idx].texture = p_button;
+ cells.write[p_column].buttons.write[p_index].texture = p_button;
cells.write[p_column].cached_minimum_size_dirty = true;
_changed_notify(p_column);
}
-void TreeItem::set_button_color(int p_column, int p_idx, const Color &p_color) {
+void TreeItem::set_button_color(int p_column, int p_index, const Color &p_color) {
ERR_FAIL_INDEX(p_column, cells.size());
- ERR_FAIL_INDEX(p_idx, cells[p_column].buttons.size());
+ ERR_FAIL_INDEX(p_index, cells[p_column].buttons.size());
- if (cells[p_column].buttons[p_idx].color == p_color) {
+ if (cells[p_column].buttons[p_index].color == p_color) {
return;
}
- cells.write[p_column].buttons.write[p_idx].color = p_color;
+ cells.write[p_column].buttons.write[p_index].color = p_color;
_changed_notify(p_column);
}
-void TreeItem::set_button_disabled(int p_column, int p_idx, bool p_disabled) {
+void TreeItem::set_button_disabled(int p_column, int p_index, bool p_disabled) {
ERR_FAIL_INDEX(p_column, cells.size());
- ERR_FAIL_INDEX(p_idx, cells[p_column].buttons.size());
+ ERR_FAIL_INDEX(p_index, cells[p_column].buttons.size());
- if (cells[p_column].buttons[p_idx].disabled == p_disabled) {
+ if (cells[p_column].buttons[p_index].disabled == p_disabled) {
return;
}
- cells.write[p_column].buttons.write[p_idx].disabled = p_disabled;
+ cells.write[p_column].buttons.write[p_index].disabled = p_disabled;
cells.write[p_column].cached_minimum_size_dirty = true;
_changed_notify(p_column);
}
-bool TreeItem::is_button_disabled(int p_column, int p_idx) const {
+bool TreeItem::is_button_disabled(int p_column, int p_index) const {
ERR_FAIL_INDEX_V(p_column, cells.size(), false);
- ERR_FAIL_INDEX_V(p_idx, cells[p_column].buttons.size(), false);
+ ERR_FAIL_INDEX_V(p_index, cells[p_column].buttons.size(), false);
- return cells[p_column].buttons[p_idx].disabled;
+ return cells[p_column].buttons[p_index].disabled;
}
void TreeItem::set_editable(int p_column, bool p_editable) {
@@ -1497,15 +1497,15 @@ void TreeItem::_bind_methods() {
ClassDB::bind_method(D_METHOD("add_button", "column", "button", "id", "disabled", "tooltip_text"), &TreeItem::add_button, DEFVAL(-1), DEFVAL(false), DEFVAL(""));
ClassDB::bind_method(D_METHOD("get_button_count", "column"), &TreeItem::get_button_count);
- ClassDB::bind_method(D_METHOD("get_button_tooltip_text", "column", "button_idx"), &TreeItem::get_button_tooltip_text);
- ClassDB::bind_method(D_METHOD("get_button_id", "column", "button_idx"), &TreeItem::get_button_id);
+ ClassDB::bind_method(D_METHOD("get_button_tooltip_text", "column", "button_index"), &TreeItem::get_button_tooltip_text);
+ ClassDB::bind_method(D_METHOD("get_button_id", "column", "button_index"), &TreeItem::get_button_id);
ClassDB::bind_method(D_METHOD("get_button_by_id", "column", "id"), &TreeItem::get_button_by_id);
- ClassDB::bind_method(D_METHOD("get_button", "column", "button_idx"), &TreeItem::get_button);
- ClassDB::bind_method(D_METHOD("set_button", "column", "button_idx", "button"), &TreeItem::set_button);
- ClassDB::bind_method(D_METHOD("erase_button", "column", "button_idx"), &TreeItem::erase_button);
- ClassDB::bind_method(D_METHOD("set_button_disabled", "column", "button_idx", "disabled"), &TreeItem::set_button_disabled);
- ClassDB::bind_method(D_METHOD("set_button_color", "column", "button_idx", "color"), &TreeItem::set_button_color);
- ClassDB::bind_method(D_METHOD("is_button_disabled", "column", "button_idx"), &TreeItem::is_button_disabled);
+ ClassDB::bind_method(D_METHOD("get_button", "column", "button_index"), &TreeItem::get_button);
+ ClassDB::bind_method(D_METHOD("set_button", "column", "button_index", "button"), &TreeItem::set_button);
+ ClassDB::bind_method(D_METHOD("erase_button", "column", "button_index"), &TreeItem::erase_button);
+ ClassDB::bind_method(D_METHOD("set_button_disabled", "column", "button_index", "disabled"), &TreeItem::set_button_disabled);
+ ClassDB::bind_method(D_METHOD("set_button_color", "column", "button_index", "color"), &TreeItem::set_button_color);
+ ClassDB::bind_method(D_METHOD("is_button_disabled", "column", "button_index"), &TreeItem::is_button_disabled);
ClassDB::bind_method(D_METHOD("set_tooltip_text", "column", "tooltip"), &TreeItem::set_tooltip_text);
ClassDB::bind_method(D_METHOD("get_tooltip_text", "column"), &TreeItem::get_tooltip_text);
@@ -1518,7 +1518,7 @@ void TreeItem::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_disable_folding", "disable"), &TreeItem::set_disable_folding);
ClassDB::bind_method(D_METHOD("is_folding_disabled"), &TreeItem::is_folding_disabled);
- ClassDB::bind_method(D_METHOD("create_child", "idx"), &TreeItem::create_child, DEFVAL(-1));
+ ClassDB::bind_method(D_METHOD("create_child", "index"), &TreeItem::create_child, DEFVAL(-1));
ClassDB::bind_method(D_METHOD("get_tree"), &TreeItem::get_tree);
ClassDB::bind_method(D_METHOD("get_next"), &TreeItem::get_next);
@@ -1529,7 +1529,7 @@ void TreeItem::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_next_visible", "wrap"), &TreeItem::get_next_visible, DEFVAL(false));
ClassDB::bind_method(D_METHOD("get_prev_visible", "wrap"), &TreeItem::get_prev_visible, DEFVAL(false));
- ClassDB::bind_method(D_METHOD("get_child", "idx"), &TreeItem::get_child);
+ ClassDB::bind_method(D_METHOD("get_child", "index"), &TreeItem::get_child);
ClassDB::bind_method(D_METHOD("get_child_count"), &TreeItem::get_child_count);
ClassDB::bind_method(D_METHOD("get_children"), &TreeItem::get_children);
ClassDB::bind_method(D_METHOD("get_index"), &TreeItem::get_index);
@@ -1775,10 +1775,10 @@ void Tree::draw_item_rect(TreeItem::Cell &p_cell, const Rect2i &p_rect, const Co
RID ci = get_canvas_item();
- if (rtl) {
+ if (rtl && rect.size.width > 0) {
Point2 draw_pos = rect.position;
draw_pos.y += Math::floor((rect.size.y - p_cell.text_buf->get_size().y) / 2.0);
- p_cell.text_buf->set_width(MAX(0, rect.size.width));
+ p_cell.text_buf->set_width(rect.size.width);
if (p_ol_size > 0 && p_ol_color.a > 0) {
p_cell.text_buf->draw_outline(ci, draw_pos, p_ol_size, p_ol_color);
}
@@ -1800,10 +1800,10 @@ void Tree::draw_item_rect(TreeItem::Cell &p_cell, const Rect2i &p_rect, const Co
rect.size.x -= bmsize.x + theme_cache.h_separation;
}
- if (!rtl) {
+ if (!rtl && rect.size.width > 0) {
Point2 draw_pos = rect.position;
draw_pos.y += Math::floor((rect.size.y - p_cell.text_buf->get_size().y) / 2.0);
- p_cell.text_buf->set_width(MAX(0, rect.size.width));
+ p_cell.text_buf->set_width(rect.size.width);
if (p_ol_size > 0 && p_ol_color.a > 0) {
p_cell.text_buf->draw_outline(ci, draw_pos, p_ol_size, p_ol_color);
}
@@ -3554,7 +3554,7 @@ void Tree::gui_input(const Ref<InputEvent> &p_event) {
icon_size_x = icon_region.size.width;
}
}
- // Icon is treated as if it is outside of the rect so that double clicking on it will emit the item_double_clicked signal.
+ // Icon is treated as if it is outside of the rect so that double clicking on it will emit the item_icon_double_clicked signal.
if (rtl) {
mpos.x = get_size().width - (mpos.x + icon_size_x);
} else {
@@ -3562,10 +3562,10 @@ void Tree::gui_input(const Ref<InputEvent> &p_event) {
}
if (rect.has_point(mpos)) {
if (!edit_selected()) {
- emit_signal(SNAME("item_double_clicked"));
+ emit_signal(SNAME("item_icon_double_clicked"));
}
} else {
- emit_signal(SNAME("item_double_clicked"));
+ emit_signal(SNAME("item_icon_double_clicked"));
}
}
pressing_for_editor = false;
@@ -4108,14 +4108,14 @@ Size2 Tree::get_minimum_size() const {
}
}
-TreeItem *Tree::create_item(TreeItem *p_parent, int p_idx) {
+TreeItem *Tree::create_item(TreeItem *p_parent, int p_index) {
ERR_FAIL_COND_V(blocked > 0, nullptr);
TreeItem *ti = nullptr;
if (p_parent) {
ERR_FAIL_COND_V_MSG(p_parent->tree != this, nullptr, "A different tree owns the given parent");
- ti = p_parent->create_child(p_idx);
+ ti = p_parent->create_child(p_index);
} else {
if (!root) {
// No root exists, make the given item the new root.
@@ -4126,7 +4126,7 @@ TreeItem *Tree::create_item(TreeItem *p_parent, int p_idx) {
root = ti;
} else {
// Root exists, append or insert to root.
- ti = create_item(root, p_idx);
+ ti = create_item(root, p_index);
}
}
@@ -4850,7 +4850,11 @@ void Tree::_do_incr_search(const String &p_add) {
return;
}
- item->select(col);
+ if (select_mode == SELECT_MULTI) {
+ item->set_as_cursor(col);
+ } else {
+ item->select(col);
+ }
ensure_cursor_is_visible();
}
@@ -5158,7 +5162,7 @@ bool Tree::get_allow_reselect() const {
void Tree::_bind_methods() {
ClassDB::bind_method(D_METHOD("clear"), &Tree::clear);
- ClassDB::bind_method(D_METHOD("create_item", "parent", "idx"), &Tree::create_item, DEFVAL(Variant()), DEFVAL(-1));
+ ClassDB::bind_method(D_METHOD("create_item", "parent", "index"), &Tree::create_item, DEFVAL(Variant()), DEFVAL(-1));
ClassDB::bind_method(D_METHOD("get_root"), &Tree::get_root);
ClassDB::bind_method(D_METHOD("set_column_custom_minimum_width", "column", "min_width"), &Tree::set_column_custom_minimum_width);
@@ -5180,6 +5184,7 @@ void Tree::_bind_methods() {
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);
ClassDB::bind_method(D_METHOD("get_select_mode"), &Tree::get_select_mode);
+ ClassDB::bind_method(D_METHOD("deselect_all"), &Tree::deselect_all);
ClassDB::bind_method(D_METHOD("set_columns", "amount"), &Tree::set_columns);
ClassDB::bind_method(D_METHOD("get_columns"), &Tree::get_columns);
@@ -5251,8 +5256,7 @@ void Tree::_bind_methods() {
ADD_SIGNAL(MethodInfo("empty_clicked", PropertyInfo(Variant::VECTOR2, "position"), PropertyInfo(Variant::INT, "mouse_button_index")));
ADD_SIGNAL(MethodInfo("item_edited"));
ADD_SIGNAL(MethodInfo("custom_item_clicked", PropertyInfo(Variant::INT, "mouse_button_index")));
- ADD_SIGNAL(MethodInfo("item_custom_button_pressed"));
- ADD_SIGNAL(MethodInfo("item_double_clicked"));
+ ADD_SIGNAL(MethodInfo("item_icon_double_clicked"));
ADD_SIGNAL(MethodInfo("item_collapsed", PropertyInfo(Variant::OBJECT, "item", PROPERTY_HINT_RESOURCE_TYPE, "TreeItem")));
ADD_SIGNAL(MethodInfo("check_propagated_to_item", PropertyInfo(Variant::OBJECT, "item", PROPERTY_HINT_RESOURCE_TYPE, "TreeItem"), PropertyInfo(Variant::INT, "column")));
ADD_SIGNAL(MethodInfo("button_clicked", PropertyInfo(Variant::OBJECT, "item", PROPERTY_HINT_RESOURCE_TYPE, "TreeItem"), PropertyInfo(Variant::INT, "column"), PropertyInfo(Variant::INT, "id"), PropertyInfo(Variant::INT, "mouse_button_index")));
diff --git a/scene/gui/tree.h b/scene/gui/tree.h
index e0ed5fdfb5..ec639ce439 100644
--- a/scene/gui/tree.h
+++ b/scene/gui/tree.h
@@ -247,15 +247,15 @@ public:
void add_button(int p_column, const Ref<Texture2D> &p_button, int p_id = -1, bool p_disabled = false, const String &p_tooltip = "");
int get_button_count(int p_column) const;
- String get_button_tooltip_text(int p_column, int p_idx) const;
- Ref<Texture2D> get_button(int p_column, int p_idx) const;
- int get_button_id(int p_column, int p_idx) const;
- void erase_button(int p_column, int p_idx);
+ String get_button_tooltip_text(int p_column, int p_index) const;
+ Ref<Texture2D> get_button(int p_column, int p_index) const;
+ int get_button_id(int p_column, int p_index) const;
+ void erase_button(int p_column, int p_index);
int get_button_by_id(int p_column, int p_id) const;
- void set_button(int p_column, int p_idx, const Ref<Texture2D> &p_button);
- void set_button_color(int p_column, int p_idx, const Color &p_color);
- void set_button_disabled(int p_column, int p_idx, bool p_disabled);
- bool is_button_disabled(int p_column, int p_idx) const;
+ void set_button(int p_column, int p_index, const Ref<Texture2D> &p_button);
+ void set_button_color(int p_column, int p_index, const Color &p_color);
+ void set_button_disabled(int p_column, int p_index, bool p_disabled);
+ bool is_button_disabled(int p_column, int p_index) const;
/* range works for mode number or mode combo */
@@ -329,7 +329,7 @@ public:
/* Item manipulation */
- TreeItem *create_child(int p_idx = -1);
+ TreeItem *create_child(int p_index = -1);
Tree *get_tree() const;
@@ -341,7 +341,7 @@ public:
TreeItem *get_prev_visible(bool p_wrap = false);
TreeItem *get_next_visible(bool p_wrap = false);
- TreeItem *get_child(int p_idx);
+ TreeItem *get_child(int p_index);
int get_visible_child_count();
int get_child_count();
TypedArray<TreeItem> get_children();
@@ -647,7 +647,7 @@ public:
void clear();
- TreeItem *create_item(TreeItem *p_parent = nullptr, int p_idx = -1);
+ TreeItem *create_item(TreeItem *p_parent = nullptr, int p_index = -1);
TreeItem *get_root() const;
TreeItem *get_last_item() const;
diff --git a/scene/gui/video_stream_player.cpp b/scene/gui/video_stream_player.cpp
index 6eb25bf852..1f3bbff779 100644
--- a/scene/gui/video_stream_player.cpp
+++ b/scene/gui/video_stream_player.cpp
@@ -236,7 +236,6 @@ void VideoStreamPlayer::set_stream(const Ref<VideoStream> &p_stream) {
AudioServer::get_singleton()->unlock();
if (!playback.is_null()) {
- playback->set_loop(loops);
playback->set_paused(paused);
texture = playback->get_texture();
@@ -344,6 +343,12 @@ int VideoStreamPlayer::get_buffering_msec() const {
void VideoStreamPlayer::set_audio_track(int p_track) {
audio_track = p_track;
+ if (stream.is_valid()) {
+ stream->set_audio_track(audio_track);
+ }
+ if (playback.is_valid()) {
+ playback->set_audio_track(audio_track);
+ }
}
int VideoStreamPlayer::get_audio_track() const {
diff --git a/scene/gui/video_stream_player.h b/scene/gui/video_stream_player.h
index 09ef272a9a..1fd599a9e1 100644
--- a/scene/gui/video_stream_player.h
+++ b/scene/gui/video_stream_player.h
@@ -65,7 +65,6 @@ class VideoStreamPlayer : public Control {
float volume = 1.0;
double last_audio_time = 0.0;
bool expand = false;
- bool loops = false;
int buffering_ms = 500;
int audio_track = 0;
int bus_index = 0;
diff --git a/scene/gui/view_panner.cpp b/scene/gui/view_panner.cpp
index 9a0c93a1df..51af886709 100644
--- a/scene/gui/view_panner.cpp
+++ b/scene/gui/view_panner.cpp
@@ -43,36 +43,42 @@ bool ViewPanner::gui_input(const Ref<InputEvent> &p_event, Rect2 p_canvas_rect)
if (scroll_vec != Vector2() && mb->is_pressed()) {
if (control_scheme == SCROLL_PANS) {
if (mb->is_ctrl_pressed()) {
- scroll_vec.y *= mb->get_factor();
- callback_helper(zoom_callback, varray(scroll_vec, mb->get_position(), mb->is_alt_pressed()));
+ // Compute the zoom factor.
+ float zoom_factor = mb->get_factor() <= 0 ? 1.0 : mb->get_factor();
+ zoom_factor = ((scroll_zoom_factor - 1.0) * zoom_factor) + 1.0;
+ float zoom = (scroll_vec.x + scroll_vec.y) > 0 ? 1.0 / scroll_zoom_factor : scroll_zoom_factor;
+ callback_helper(zoom_callback, varray(zoom, mb->get_position(), p_event));
return true;
} else {
- Vector2 panning;
- if (mb->is_shift_pressed()) {
- panning.x += mb->get_factor() * scroll_vec.y;
- panning.y += mb->get_factor() * scroll_vec.x;
- } else {
- panning.y += mb->get_factor() * scroll_vec.y;
- panning.x += mb->get_factor() * scroll_vec.x;
+ Vector2 panning = scroll_vec * mb->get_factor();
+ if (pan_axis == PAN_AXIS_HORIZONTAL) {
+ panning = Vector2(panning.x + panning.y, 0);
+ } else if (pan_axis == PAN_AXIS_VERTICAL) {
+ panning = Vector2(0, panning.x + panning.y);
+ } else if (mb->is_shift_pressed()) {
+ panning = Vector2(panning.y, panning.x);
}
- callback_helper(scroll_callback, varray(panning, mb->is_alt_pressed()));
+ callback_helper(pan_callback, varray(-panning * scroll_speed, p_event));
return true;
}
} else {
if (mb->is_ctrl_pressed()) {
- Vector2 panning;
- if (mb->is_shift_pressed()) {
- panning.x += mb->get_factor() * scroll_vec.y;
- panning.y += mb->get_factor() * scroll_vec.x;
- } else {
- panning.y += mb->get_factor() * scroll_vec.y;
- panning.x += mb->get_factor() * scroll_vec.x;
+ Vector2 panning = scroll_vec * mb->get_factor();
+ if (pan_axis == PAN_AXIS_HORIZONTAL) {
+ panning = Vector2(panning.x + panning.y, 0);
+ } else if (pan_axis == PAN_AXIS_VERTICAL) {
+ panning = Vector2(0, panning.x + panning.y);
+ } else if (mb->is_shift_pressed()) {
+ panning = Vector2(panning.y, panning.x);
}
- callback_helper(scroll_callback, varray(panning, mb->is_alt_pressed()));
+ callback_helper(pan_callback, varray(-panning * scroll_speed, p_event));
return true;
} else if (!mb->is_shift_pressed()) {
- scroll_vec.y *= mb->get_factor();
- callback_helper(zoom_callback, varray(scroll_vec, mb->get_position(), mb->is_alt_pressed()));
+ // Compute the zoom factor.
+ float zoom_factor = mb->get_factor() <= 0 ? 1.0 : mb->get_factor();
+ zoom_factor = ((scroll_zoom_factor - 1.0) * zoom_factor) + 1.0;
+ float zoom = (scroll_vec.x + scroll_vec.y) > 0 ? 1.0 / scroll_zoom_factor : scroll_zoom_factor;
+ callback_helper(zoom_callback, varray(zoom, mb->get_position(), p_event));
return true;
}
}
@@ -102,19 +108,36 @@ bool ViewPanner::gui_input(const Ref<InputEvent> &p_event, Rect2 p_canvas_rect)
if (mm.is_valid()) {
if (is_dragging) {
if (p_canvas_rect != Rect2()) {
- callback_helper(pan_callback, varray(Input::get_singleton()->warp_mouse_motion(mm, p_canvas_rect)));
+ callback_helper(pan_callback, varray(Input::get_singleton()->warp_mouse_motion(mm, p_canvas_rect), p_event));
} else {
- callback_helper(pan_callback, varray(mm->get_relative()));
+ callback_helper(pan_callback, varray(mm->get_relative(), p_event));
}
return true;
}
}
+ Ref<InputEventMagnifyGesture> magnify_gesture = p_event;
+ if (magnify_gesture.is_valid()) {
+ // Zoom gesture
+ callback_helper(zoom_callback, varray(magnify_gesture->get_factor(), magnify_gesture->get_position(), p_event));
+ return true;
+ }
+
+ Ref<InputEventPanGesture> pan_gesture = p_event;
+ if (pan_gesture.is_valid()) {
+ callback_helper(pan_callback, varray(-pan_gesture->get_delta() * scroll_speed, p_event));
+ }
+
+ Ref<InputEventScreenDrag> screen_drag = p_event;
+ if (screen_drag.is_valid()) {
+ callback_helper(pan_callback, varray(screen_drag->get_relative(), p_event));
+ }
+
Ref<InputEventKey> k = p_event;
if (k.is_valid()) {
if (pan_view_shortcut.is_valid() && pan_view_shortcut->matches_event(k)) {
pan_key_pressed = k->is_pressed();
- if (simple_panning_enabled || (Input::get_singleton()->get_mouse_button_mask() & MouseButton::LEFT) != MouseButton::NONE) {
+ if (simple_panning_enabled || Input::get_singleton()->get_mouse_button_mask().has_flag(MouseButtonMask::LEFT)) {
is_dragging = pan_key_pressed;
}
return true;
@@ -140,8 +163,7 @@ void ViewPanner::callback_helper(Callable p_callback, Vector<Variant> p_args) {
p_callback.callp(argptr, p_args.size(), result, ce);
}
-void ViewPanner::set_callbacks(Callable p_scroll_callback, Callable p_pan_callback, Callable p_zoom_callback) {
- scroll_callback = p_scroll_callback;
+void ViewPanner::set_callbacks(Callable p_pan_callback, Callable p_zoom_callback) {
pan_callback = p_pan_callback;
zoom_callback = p_zoom_callback;
}
@@ -163,6 +185,20 @@ void ViewPanner::set_simple_panning_enabled(bool p_enabled) {
simple_panning_enabled = p_enabled;
}
+void ViewPanner::set_scroll_speed(int p_scroll_speed) {
+ ERR_FAIL_COND(p_scroll_speed <= 0);
+ scroll_speed = p_scroll_speed;
+}
+
+void ViewPanner::set_scroll_zoom_factor(float p_scroll_zoom_factor) {
+ ERR_FAIL_COND(p_scroll_zoom_factor <= 1.0);
+ scroll_zoom_factor = p_scroll_zoom_factor;
+}
+
+void ViewPanner::set_pan_axis(PanAxis p_pan_axis) {
+ pan_axis = p_pan_axis;
+}
+
void ViewPanner::setup(ControlScheme p_scheme, Ref<Shortcut> p_shortcut, bool p_simple_panning) {
set_control_scheme(p_scheme);
set_pan_shortcut(p_shortcut);
diff --git a/scene/gui/view_panner.h b/scene/gui/view_panner.h
index 861574a80c..60d36ca04c 100644
--- a/scene/gui/view_panner.h
+++ b/scene/gui/view_panner.h
@@ -45,7 +45,17 @@ public:
SCROLL_PANS,
};
+ enum PanAxis {
+ PAN_AXIS_BOTH,
+ PAN_AXIS_HORIZONTAL,
+ PAN_AXIS_VERTICAL,
+ };
+
private:
+ int scroll_speed = 32;
+ float scroll_zoom_factor = 1.1;
+ PanAxis pan_axis = PAN_AXIS_BOTH;
+
bool is_dragging = false;
bool pan_key_pressed = false;
bool force_drag = false;
@@ -55,7 +65,6 @@ private:
Ref<Shortcut> pan_view_shortcut;
- Callable scroll_callback;
Callable pan_callback;
Callable zoom_callback;
@@ -63,11 +72,14 @@ private:
ControlScheme control_scheme = SCROLL_ZOOMS;
public:
- void set_callbacks(Callable p_scroll_callback, Callable p_pan_callback, Callable p_zoom_callback);
+ void set_callbacks(Callable p_pan_callback, Callable p_zoom_callback);
void set_control_scheme(ControlScheme p_scheme);
void set_enable_rmb(bool p_enable);
void set_pan_shortcut(Ref<Shortcut> p_shortcut);
void set_simple_panning_enabled(bool p_enabled);
+ void set_scroll_speed(int p_scroll_speed);
+ void set_scroll_zoom_factor(float p_scroll_zoom_factor);
+ void set_pan_axis(PanAxis p_pan_axis);
void setup(ControlScheme p_scheme, Ref<Shortcut> p_shortcut, bool p_simple_panning);
diff --git a/scene/main/canvas_item.cpp b/scene/main/canvas_item.cpp
index a04c299705..e5dcdd2afd 100644
--- a/scene/main/canvas_item.cpp
+++ b/scene/main/canvas_item.cpp
@@ -154,17 +154,7 @@ Transform2D CanvasItem::get_global_transform_with_canvas() const {
Transform2D CanvasItem::get_screen_transform() const {
ERR_FAIL_COND_V(!is_inside_tree(), Transform2D());
- Transform2D xform = get_global_transform_with_canvas();
-
- Window *w = Object::cast_to<Window>(get_viewport());
- if (w && !w->is_embedding_subwindows()) {
- Transform2D s;
- s.set_origin(w->get_position());
-
- xform = s * xform;
- }
-
- return xform;
+ return get_viewport()->get_popup_base_transform() * get_global_transform_with_canvas();
}
Transform2D CanvasItem::get_global_transform() const {
@@ -195,7 +185,15 @@ void CanvasItem::_top_level_raise_self() {
}
void CanvasItem::_enter_canvas() {
- if ((!Object::cast_to<CanvasItem>(get_parent())) || top_level) {
+ // Resolves to nullptr if the node is top_level.
+ CanvasItem *parent_item = get_parent_item();
+
+ if (parent_item) {
+ canvas_layer = parent_item->canvas_layer;
+ RenderingServer::get_singleton()->canvas_item_set_parent(canvas_item, parent_item->get_canvas_item());
+ RenderingServer::get_singleton()->canvas_item_set_draw_index(canvas_item, get_index());
+ RenderingServer::get_singleton()->canvas_item_set_visibility_layer(canvas_item, visibility_layer);
+ } else {
Node *n = this;
canvas_layer = nullptr;
@@ -231,13 +229,6 @@ void CanvasItem::_enter_canvas() {
}
get_tree()->call_group_flags(SceneTree::GROUP_CALL_UNIQUE | SceneTree::GROUP_CALL_DEFERRED, canvas_group, SNAME("_top_level_raise_self"));
-
- } else {
- CanvasItem *parent = get_parent_item();
- canvas_layer = parent->canvas_layer;
- RenderingServer::get_singleton()->canvas_item_set_parent(canvas_item, parent->get_canvas_item());
- RenderingServer::get_singleton()->canvas_item_set_draw_index(canvas_item, get_index());
- RenderingServer::get_singleton()->canvas_item_set_visibility_layer(canvas_item, visibility_layer);
}
pending_update = false;
@@ -320,8 +311,7 @@ void CanvasItem::_notification(int p_what) {
if (canvas_group != StringName()) {
get_tree()->call_group_flags(SceneTree::GROUP_CALL_UNIQUE | SceneTree::GROUP_CALL_DEFERRED, canvas_group, "_top_level_raise_self");
} else {
- CanvasItem *p = get_parent_item();
- ERR_FAIL_COND(!p);
+ ERR_FAIL_COND_MSG(!get_parent_item(), "Moved child is in incorrect state (no canvas group, no canvas item parent).");
RenderingServer::get_singleton()->canvas_item_set_draw_index(canvas_item, get_index());
}
} break;
@@ -388,6 +378,16 @@ Color CanvasItem::get_modulate() const {
return modulate;
}
+Color CanvasItem::get_modulate_in_tree() const {
+ Color final_modulate = modulate;
+ CanvasItem *parent_item = get_parent_item();
+ while (parent_item) {
+ final_modulate *= parent_item->get_modulate();
+ parent_item = parent_item->get_parent_item();
+ }
+ return final_modulate;
+}
+
void CanvasItem::set_as_top_level(bool p_top_level) {
if (top_level == p_top_level) {
return;
@@ -400,11 +400,28 @@ void CanvasItem::set_as_top_level(bool p_top_level) {
_exit_canvas();
top_level = p_top_level;
+ _top_level_changed();
_enter_canvas();
_notify_transform();
}
+void CanvasItem::_top_level_changed() {
+ // Inform children that top_level status has changed on a parent.
+ int children = get_child_count();
+ for (int i = 0; i < children; i++) {
+ CanvasItem *child = Object::cast_to<CanvasItem>(get_child(i));
+ if (child) {
+ child->_top_level_changed_on_parent();
+ }
+ }
+}
+
+void CanvasItem::_top_level_changed_on_parent() {
+ // Inform children that top_level status has changed on a parent.
+ _top_level_changed();
+}
+
bool CanvasItem::is_set_as_top_level() const {
return top_level;
}
@@ -474,6 +491,17 @@ int CanvasItem::get_z_index() const {
return z_index;
}
+int CanvasItem::get_effective_z_index() const {
+ int effective_z_index = z_index;
+ if (is_z_relative()) {
+ CanvasItem *p = get_parent_item();
+ if (p) {
+ effective_z_index += p->get_effective_z_index();
+ }
+ }
+ return effective_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);
@@ -483,7 +511,7 @@ 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) {
+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, bool p_aligned) {
ERR_FAIL_COND_MSG(!drawing, "Drawing is only allowed inside NOTIFICATION_DRAW, _draw() function or 'draw' signal.");
float length = (p_to - p_from).length();
@@ -492,14 +520,28 @@ void CanvasItem::draw_dashed_line(const Point2 &p_from, const Point2 &p_to, cons
return;
}
- Point2 off = p_from;
Vector2 step = p_dash * (p_to - p_from).normalized();
- int steps = length / p_dash / 2;
- for (int i = 0; i < steps; i++) {
- RenderingServer::get_singleton()->canvas_item_add_line(canvas_item, off, (off + step), p_color, p_width);
- off += 2 * step;
+ int steps = (p_aligned) ? Math::ceil(length / p_dash) : Math::floor(length / p_dash);
+ if (steps % 2 == 0) {
+ steps--;
+ }
+
+ Point2 off = p_from;
+ if (p_aligned) {
+ off += (p_to - p_from).normalized() * (length - steps * p_dash) / 2.0;
+ }
+
+ Vector<Vector2> points;
+ points.resize(steps + 1);
+ for (int i = 0; i < steps; i += 2) {
+ points.write[i] = (i == 0) ? p_from : off;
+ points.write[i + 1] = (p_aligned && i == steps - 1) ? p_to : (off + step);
+ off += step * 2;
}
- RenderingServer::get_singleton()->canvas_item_add_line(canvas_item, off, p_to, p_color, p_width);
+
+ Vector<Color> colors = { p_color };
+
+ RenderingServer::get_singleton()->canvas_item_add_multiline(canvas_item, points, colors, p_width);
}
void CanvasItem::draw_line(const Point2 &p_from, const Point2 &p_to, const Color &p_color, real_t p_width, bool p_antialiased) {
@@ -525,10 +567,13 @@ void CanvasItem::draw_polyline_colors(const Vector<Point2> &p_points, const Vect
void CanvasItem::draw_arc(const Vector2 &p_center, real_t p_radius, real_t p_start_angle, real_t p_end_angle, int p_point_count, const Color &p_color, real_t p_width, bool p_antialiased) {
Vector<Point2> points;
points.resize(p_point_count);
- const real_t delta_angle = p_end_angle - p_start_angle;
+ Point2 *points_ptr = points.ptrw();
+
+ // Clamp angle difference to full circle so arc won't overlap itself.
+ const real_t delta_angle = CLAMP(p_end_angle - p_start_angle, -Math_TAU, Math_TAU);
for (int i = 0; i < p_point_count; i++) {
real_t theta = (i / (p_point_count - 1.0f)) * delta_angle + p_start_angle;
- points.set(i, p_center + Vector2(Math::cos(theta), Math::sin(theta)) * p_radius);
+ points_ptr[i] = p_center + Vector2(Math::cos(theta), Math::sin(theta)) * p_radius;
}
draw_polyline(points, p_color, p_width, p_antialiased);
@@ -551,46 +596,28 @@ void CanvasItem::draw_multiline_colors(const Vector<Point2> &p_points, const Vec
void CanvasItem::draw_rect(const Rect2 &p_rect, const Color &p_color, bool p_filled, real_t p_width) {
ERR_FAIL_COND_MSG(!drawing, "Drawing is only allowed inside NOTIFICATION_DRAW, _draw() function or 'draw' signal.");
+ Rect2 rect = p_rect.abs();
+
if (p_filled) {
- if (p_width != 1.0) {
+ if (p_width != -1.0) {
WARN_PRINT("The draw_rect() \"width\" argument has no effect when \"filled\" is \"true\".");
}
- RenderingServer::get_singleton()->canvas_item_add_rect(canvas_item, p_rect, p_color);
+ RenderingServer::get_singleton()->canvas_item_add_rect(canvas_item, rect, p_color);
+ } else if (p_width >= rect.size.width || p_width >= rect.size.height) {
+ RenderingServer::get_singleton()->canvas_item_add_rect(canvas_item, rect.grow(0.5f * p_width), p_color);
} else {
- // Thick lines are offset depending on their width to avoid partial overlapping.
- // Thin lines don't require an offset, so don't apply one in this case
- real_t offset;
- if (p_width >= 2) {
- offset = p_width / 2.0;
- } else {
- offset = 0.0;
- }
+ Vector<Vector2> points;
+ points.resize(5);
+ points.write[0] = rect.position;
+ points.write[1] = rect.position + Vector2(rect.size.x, 0);
+ points.write[2] = rect.position + rect.size;
+ points.write[3] = rect.position + Vector2(0, rect.size.y);
+ points.write[4] = rect.position;
+
+ Vector<Color> colors = { p_color };
- RenderingServer::get_singleton()->canvas_item_add_line(
- canvas_item,
- p_rect.position + Size2(-offset, 0),
- p_rect.position + Size2(p_rect.size.width + offset, 0),
- p_color,
- p_width);
- RenderingServer::get_singleton()->canvas_item_add_line(
- canvas_item,
- p_rect.position + Size2(p_rect.size.width, offset),
- p_rect.position + Size2(p_rect.size.width, p_rect.size.height - offset),
- p_color,
- p_width);
- RenderingServer::get_singleton()->canvas_item_add_line(
- canvas_item,
- p_rect.position + Size2(p_rect.size.width + offset, p_rect.size.height),
- p_rect.position + Size2(-offset, p_rect.size.height),
- p_color,
- p_width);
- RenderingServer::get_singleton()->canvas_item_add_line(
- canvas_item,
- p_rect.position + Size2(0, p_rect.size.height - offset),
- p_rect.position + Size2(0, offset),
- p_color,
- p_width);
+ RenderingServer::get_singleton()->canvas_item_add_polyline(canvas_item, points, colors, p_width);
}
}
@@ -641,11 +668,11 @@ void CanvasItem::draw_style_box(const Ref<StyleBox> &p_style_box, const Rect2 &p
p_style_box->draw(canvas_item, p_rect);
}
-void CanvasItem::draw_primitive(const Vector<Point2> &p_points, const Vector<Color> &p_colors, const Vector<Point2> &p_uvs, Ref<Texture2D> p_texture, real_t p_width) {
+void CanvasItem::draw_primitive(const Vector<Point2> &p_points, const Vector<Color> &p_colors, const Vector<Point2> &p_uvs, Ref<Texture2D> p_texture) {
ERR_FAIL_COND_MSG(!drawing, "Drawing is only allowed inside NOTIFICATION_DRAW, _draw() function or 'draw' signal.");
RID rid = p_texture.is_valid() ? p_texture->get_rid() : RID();
- RenderingServer::get_singleton()->canvas_item_add_primitive(canvas_item, p_points, p_colors, p_uvs, rid, p_width);
+ RenderingServer::get_singleton()->canvas_item_add_primitive(canvas_item, p_points, p_colors, p_uvs, rid);
}
void CanvasItem::draw_set_transform(const Point2 &p_offset, real_t p_rot, const Size2 &p_scale) {
@@ -905,6 +932,12 @@ void CanvasItem::force_update_transform() {
notification(NOTIFICATION_TRANSFORM_CHANGED);
}
+void CanvasItem::_validate_property(PropertyInfo &p_property) const {
+ if (hide_clip_children && p_property.name == "clip_children") {
+ p_property.usage = PROPERTY_USAGE_NONE;
+ }
+}
+
void CanvasItem::_bind_methods() {
ClassDB::bind_method(D_METHOD("_top_level_raise_self"), &CanvasItem::_top_level_raise_self);
@@ -962,14 +995,14 @@ void CanvasItem::_bind_methods() {
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);
- ClassDB::bind_method(D_METHOD("draw_line", "from", "to", "color", "width", "antialiased"), &CanvasItem::draw_line, DEFVAL(1.0), DEFVAL(false));
- ClassDB::bind_method(D_METHOD("draw_dashed_line", "from", "to", "color", "width", "dash"), &CanvasItem::draw_dashed_line, DEFVAL(1.0), DEFVAL(2.0));
- ClassDB::bind_method(D_METHOD("draw_polyline", "points", "color", "width", "antialiased"), &CanvasItem::draw_polyline, DEFVAL(1.0), DEFVAL(false));
- ClassDB::bind_method(D_METHOD("draw_polyline_colors", "points", "colors", "width", "antialiased"), &CanvasItem::draw_polyline_colors, DEFVAL(1.0), DEFVAL(false));
- ClassDB::bind_method(D_METHOD("draw_arc", "center", "radius", "start_angle", "end_angle", "point_count", "color", "width", "antialiased"), &CanvasItem::draw_arc, DEFVAL(1.0), DEFVAL(false));
- ClassDB::bind_method(D_METHOD("draw_multiline", "points", "color", "width"), &CanvasItem::draw_multiline, DEFVAL(1.0));
- ClassDB::bind_method(D_METHOD("draw_multiline_colors", "points", "colors", "width"), &CanvasItem::draw_multiline_colors, DEFVAL(1.0));
- ClassDB::bind_method(D_METHOD("draw_rect", "rect", "color", "filled", "width"), &CanvasItem::draw_rect, DEFVAL(true), DEFVAL(1.0));
+ ClassDB::bind_method(D_METHOD("draw_line", "from", "to", "color", "width", "antialiased"), &CanvasItem::draw_line, DEFVAL(-1.0), DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("draw_dashed_line", "from", "to", "color", "width", "dash", "aligned"), &CanvasItem::draw_dashed_line, DEFVAL(-1.0), DEFVAL(2.0), DEFVAL(true));
+ ClassDB::bind_method(D_METHOD("draw_polyline", "points", "color", "width", "antialiased"), &CanvasItem::draw_polyline, DEFVAL(-1.0), DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("draw_polyline_colors", "points", "colors", "width", "antialiased"), &CanvasItem::draw_polyline_colors, DEFVAL(-1.0), DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("draw_arc", "center", "radius", "start_angle", "end_angle", "point_count", "color", "width", "antialiased"), &CanvasItem::draw_arc, DEFVAL(-1.0), DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("draw_multiline", "points", "color", "width"), &CanvasItem::draw_multiline, DEFVAL(-1.0));
+ ClassDB::bind_method(D_METHOD("draw_multiline_colors", "points", "colors", "width"), &CanvasItem::draw_multiline_colors, DEFVAL(-1.0));
+ ClassDB::bind_method(D_METHOD("draw_rect", "rect", "color", "filled", "width"), &CanvasItem::draw_rect, DEFVAL(true), DEFVAL(-1.0));
ClassDB::bind_method(D_METHOD("draw_circle", "position", "radius", "color"), &CanvasItem::draw_circle);
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));
@@ -977,7 +1010,7 @@ void CanvasItem::_bind_methods() {
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));
+ ClassDB::bind_method(D_METHOD("draw_primitive", "points", "colors", "uvs", "texture"), &CanvasItem::draw_primitive, DEFVAL(Ref<Texture2D>()));
ClassDB::bind_method(D_METHOD("draw_polygon", "points", "colors", "uvs", "texture"), &CanvasItem::draw_polygon, DEFVAL(PackedVector2Array()), DEFVAL(Ref<Texture2D>()));
ClassDB::bind_method(D_METHOD("draw_colored_polygon", "points", "color", "uvs", "texture"), &CanvasItem::draw_colored_polygon, DEFVAL(PackedVector2Array()), DEFVAL(Ref<Texture2D>()));
ClassDB::bind_method(D_METHOD("draw_string", "font", "pos", "text", "alignment", "width", "font_size", "modulate", "jst_flags", "direction", "orientation"), &CanvasItem::draw_string, DEFVAL(HORIZONTAL_ALIGNMENT_LEFT), DEFVAL(-1), DEFVAL(Font::DEFAULT_FONT_SIZE), DEFVAL(Color(1.0, 1.0, 1.0)), DEFVAL(TextServer::JUSTIFICATION_KASHIDA | TextServer::JUSTIFICATION_WORD_BOUND), DEFVAL(TextServer::DIRECTION_AUTO), DEFVAL(TextServer::ORIENTATION_HORIZONTAL));
diff --git a/scene/main/canvas_item.h b/scene/main/canvas_item.h
index 47b40c9b46..5fbf043159 100644
--- a/scene/main/canvas_item.h
+++ b/scene/main/canvas_item.h
@@ -106,6 +106,7 @@ private:
bool use_parent_material = false;
bool notify_local_transform = false;
bool notify_transform = false;
+ bool hide_clip_children = false;
ClipChildrenMode clip_children_mode = CLIP_CHILDREN_DISABLED;
@@ -124,6 +125,9 @@ private:
void _propagate_visibility_changed(bool p_parent_visible_in_tree);
void _handle_visibility_change(bool p_visible);
+ virtual void _top_level_changed();
+ virtual void _top_level_changed_on_parent();
+
void _redraw_callback();
void _enter_canvas();
@@ -155,6 +159,9 @@ protected:
void _notification(int p_what);
static void _bind_methods();
+ void _validate_property(PropertyInfo &p_property) const;
+
+ _FORCE_INLINE_ void set_hide_clip_children(bool p_value) { hide_clip_children = p_value; }
GDVIRTUAL0(_draw)
public:
@@ -224,6 +231,7 @@ public:
void set_modulate(const Color &p_modulate);
Color get_modulate() const;
+ Color get_modulate_in_tree() const;
void set_self_modulate(const Color &p_self_modulate);
Color get_self_modulate() const;
@@ -238,6 +246,7 @@ public:
void set_z_index(int p_z);
int get_z_index() const;
+ int get_effective_z_index() const;
void set_z_as_relative(bool p_enabled);
bool is_z_relative() const;
@@ -247,14 +256,14 @@ public:
/* 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);
- void draw_line(const Point2 &p_from, const Point2 &p_to, const Color &p_color, real_t p_width = 1.0, bool p_antialiased = false);
- void draw_polyline(const Vector<Point2> &p_points, const Color &p_color, real_t p_width = 1.0, bool p_antialiased = false);
- void draw_polyline_colors(const Vector<Point2> &p_points, const Vector<Color> &p_colors, real_t p_width = 1.0, bool p_antialiased = false);
- void draw_arc(const Vector2 &p_center, real_t p_radius, real_t p_start_angle, real_t p_end_angle, int p_point_count, const Color &p_color, real_t p_width = 1.0, bool p_antialiased = false);
- void draw_multiline(const Vector<Point2> &p_points, const Color &p_color, real_t p_width = 1.0);
- void draw_multiline_colors(const Vector<Point2> &p_points, const Vector<Color> &p_colors, real_t p_width = 1.0);
- void draw_rect(const Rect2 &p_rect, const Color &p_color, bool p_filled = true, real_t p_width = 1.0);
+ 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, bool p_aligned = true);
+ void draw_line(const Point2 &p_from, const Point2 &p_to, const Color &p_color, real_t p_width = -1.0, bool p_antialiased = false);
+ void draw_polyline(const Vector<Point2> &p_points, const Color &p_color, real_t p_width = -1.0, bool p_antialiased = false);
+ void draw_polyline_colors(const Vector<Point2> &p_points, const Vector<Color> &p_colors, real_t p_width = -1.0, bool p_antialiased = false);
+ void draw_arc(const Vector2 &p_center, real_t p_radius, real_t p_start_angle, real_t p_end_angle, int p_point_count, const Color &p_color, real_t p_width = -1.0, bool p_antialiased = false);
+ void draw_multiline(const Vector<Point2> &p_points, const Color &p_color, real_t p_width = -1.0);
+ void draw_multiline_colors(const Vector<Point2> &p_points, const Vector<Color> &p_colors, real_t p_width = -1.0);
+ void draw_rect(const Rect2 &p_rect, const Color &p_color, bool p_filled = true, real_t p_width = -1.0);
void draw_circle(const Point2 &p_pos, real_t p_radius, const Color &p_color);
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);
@@ -262,7 +271,7 @@ public:
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);
+ void draw_primitive(const Vector<Point2> &p_points, const Vector<Color> &p_colors, const Vector<Point2> &p_uvs, Ref<Texture2D> p_texture = Ref<Texture2D>());
void draw_polygon(const Vector<Point2> &p_points, const Vector<Color> &p_colors, const Vector<Point2> &p_uvs = Vector<Point2>(), Ref<Texture2D> p_texture = Ref<Texture2D>());
void draw_colored_polygon(const Vector<Point2> &p_points, const Color &p_color, const Vector<Point2> &p_uvs = Vector<Point2>(), Ref<Texture2D> p_texture = Ref<Texture2D>());
diff --git a/scene/main/http_request.cpp b/scene/main/http_request.cpp
index 46ba7e67eb..0d53f740db 100644
--- a/scene/main/http_request.cpp
+++ b/scene/main/http_request.cpp
@@ -33,7 +33,7 @@
#include "scene/main/timer.h"
Error HTTPRequest::_request() {
- return client->connect_to_host(url, port, use_tls, validate_tls);
+ return client->connect_to_host(url, port, use_tls ? tls_options : nullptr);
}
Error HTTPRequest::_parse_url(const String &p_url) {
@@ -96,7 +96,7 @@ String HTTPRequest::get_header_value(const PackedStringArray &p_headers, const S
return value;
}
-Error HTTPRequest::request(const String &p_url, const Vector<String> &p_custom_headers, bool p_tls_validate_domain, HTTPClient::Method p_method, const String &p_request_data) {
+Error HTTPRequest::request(const String &p_url, const Vector<String> &p_custom_headers, HTTPClient::Method p_method, const String &p_request_data) {
// Copy the string into a raw buffer.
Vector<uint8_t> raw_data;
@@ -108,10 +108,10 @@ Error HTTPRequest::request(const String &p_url, const Vector<String> &p_custom_h
memcpy(w, charstr.ptr(), len);
}
- return request_raw(p_url, p_custom_headers, p_tls_validate_domain, p_method, raw_data);
+ return request_raw(p_url, p_custom_headers, p_method, raw_data);
}
-Error HTTPRequest::request_raw(const String &p_url, const Vector<String> &p_custom_headers, bool p_tls_validate_domain, HTTPClient::Method p_method, const Vector<uint8_t> &p_request_data_raw) {
+Error HTTPRequest::request_raw(const String &p_url, const Vector<String> &p_custom_headers, HTTPClient::Method p_method, const Vector<uint8_t> &p_request_data_raw) {
ERR_FAIL_COND_V(!is_inside_tree(), ERR_UNCONFIGURED);
ERR_FAIL_COND_V_MSG(requesting, ERR_BUSY, "HTTPRequest is processing a request. Wait for completion or cancel it before attempting a new one.");
@@ -127,8 +127,6 @@ Error HTTPRequest::request_raw(const String &p_url, const Vector<String> &p_cust
return err;
}
- validate_tls = p_tls_validate_domain;
-
headers = p_custom_headers;
if (accept_gzip) {
@@ -590,10 +588,16 @@ void HTTPRequest::_timeout() {
_defer_done(RESULT_TIMEOUT, 0, PackedStringArray(), PackedByteArray());
}
+void HTTPRequest::set_tls_options(const Ref<TLSOptions> &p_options) {
+ ERR_FAIL_COND(p_options.is_null() || p_options->is_server());
+ tls_options = p_options;
+}
+
void HTTPRequest::_bind_methods() {
- ClassDB::bind_method(D_METHOD("request", "url", "custom_headers", "tls_validate_domain", "method", "request_data"), &HTTPRequest::request, DEFVAL(PackedStringArray()), DEFVAL(true), DEFVAL(HTTPClient::METHOD_GET), DEFVAL(String()));
- ClassDB::bind_method(D_METHOD("request_raw", "url", "custom_headers", "tls_validate_domain", "method", "request_data_raw"), &HTTPRequest::request_raw, DEFVAL(PackedStringArray()), DEFVAL(true), DEFVAL(HTTPClient::METHOD_GET), DEFVAL(PackedByteArray()));
+ ClassDB::bind_method(D_METHOD("request", "url", "custom_headers", "method", "request_data"), &HTTPRequest::request, DEFVAL(PackedStringArray()), DEFVAL(HTTPClient::METHOD_GET), DEFVAL(String()));
+ ClassDB::bind_method(D_METHOD("request_raw", "url", "custom_headers", "method", "request_data_raw"), &HTTPRequest::request_raw, DEFVAL(PackedStringArray()), DEFVAL(HTTPClient::METHOD_GET), DEFVAL(PackedByteArray()));
ClassDB::bind_method(D_METHOD("cancel_request"), &HTTPRequest::cancel_request);
+ ClassDB::bind_method(D_METHOD("set_tls_options", "client_options"), &HTTPRequest::set_tls_options);
ClassDB::bind_method(D_METHOD("get_http_client_status"), &HTTPRequest::get_http_client_status);
@@ -654,6 +658,7 @@ void HTTPRequest::_bind_methods() {
HTTPRequest::HTTPRequest() {
client = Ref<HTTPClient>(HTTPClient::create());
+ tls_options = TLSOptions::client();
timer = memnew(Timer);
timer->set_one_shot(true);
timer->connect("timeout", callable_mp(this, &HTTPRequest::_timeout));
diff --git a/scene/main/http_request.h b/scene/main/http_request.h
index add4e9538d..9a91171eaf 100644
--- a/scene/main/http_request.h
+++ b/scene/main/http_request.h
@@ -68,8 +68,8 @@ private:
String url;
int port = 80;
Vector<String> headers;
- bool validate_tls = false;
bool use_tls = false;
+ Ref<TLSOptions> tls_options;
HTTPClient::Method method;
Vector<uint8_t> request_data;
@@ -125,8 +125,8 @@ protected:
static void _bind_methods();
public:
- Error request(const String &p_url, const Vector<String> &p_custom_headers = Vector<String>(), bool p_tls_validate_domain = true, HTTPClient::Method p_method = HTTPClient::METHOD_GET, const String &p_request_data = ""); //connects to a full url and perform request
- Error request_raw(const String &p_url, const Vector<String> &p_custom_headers = Vector<String>(), bool p_tls_validate_domain = true, HTTPClient::Method p_method = HTTPClient::METHOD_GET, const Vector<uint8_t> &p_request_data_raw = Vector<uint8_t>()); //connects to a full url and perform request
+ Error request(const String &p_url, const Vector<String> &p_custom_headers = Vector<String>(), HTTPClient::Method p_method = HTTPClient::METHOD_GET, const String &p_request_data = ""); //connects to a full url and perform request
+ Error request_raw(const String &p_url, const Vector<String> &p_custom_headers = Vector<String>(), HTTPClient::Method p_method = HTTPClient::METHOD_GET, const Vector<uint8_t> &p_request_data_raw = Vector<uint8_t>()); //connects to a full url and perform request
void cancel_request();
HTTPClient::Status get_http_client_status() const;
@@ -161,6 +161,8 @@ public:
void set_http_proxy(const String &p_host, int p_port);
void set_https_proxy(const String &p_host, int p_port);
+ void set_tls_options(const Ref<TLSOptions> &p_options);
+
HTTPRequest();
};
diff --git a/scene/main/multiplayer_api.cpp b/scene/main/multiplayer_api.cpp
index e36cbc4414..950eb2809c 100644
--- a/scene/main/multiplayer_api.cpp
+++ b/scene/main/multiplayer_api.cpp
@@ -135,7 +135,7 @@ Error MultiplayerAPI::encode_and_compress_variant(const Variant &p_variant, uint
return err;
}
if (r_buffer) {
- // The first byte is not used by the marshalling, so store the type
+ // The first byte is not used by the marshaling, so store the type
// so we know how to decompress and decode this variant.
r_buffer[0] = p_variant.get_type();
}
@@ -329,9 +329,9 @@ void MultiplayerAPI::_bind_methods() {
/// MultiplayerAPIExtension
Error MultiplayerAPIExtension::poll() {
- int err = OK;
+ Error err = OK;
GDVIRTUAL_CALL(_poll, err);
- return (Error)err;
+ return err;
}
void MultiplayerAPIExtension::set_multiplayer_peer(const Ref<MultiplayerPeer> &p_peer) {
@@ -364,9 +364,9 @@ Error MultiplayerAPIExtension::rpcp(Object *p_obj, int p_peer_id, const StringNa
for (int i = 0; i < p_argcount; i++) {
args.push_back(*p_arg[i]);
}
- int ret = FAILED;
+ Error ret = FAILED;
GDVIRTUAL_CALL(_rpc, p_peer_id, p_obj, p_method, args, ret);
- return (Error)ret;
+ return ret;
}
int MultiplayerAPIExtension::get_remote_sender_id() {
@@ -376,15 +376,15 @@ int MultiplayerAPIExtension::get_remote_sender_id() {
}
Error MultiplayerAPIExtension::object_configuration_add(Object *p_object, Variant p_config) {
- int err = ERR_UNAVAILABLE;
+ Error err = ERR_UNAVAILABLE;
GDVIRTUAL_CALL(_object_configuration_add, p_object, p_config, err);
- return (Error)err;
+ return err;
}
Error MultiplayerAPIExtension::object_configuration_remove(Object *p_object, Variant p_config) {
- int err = ERR_UNAVAILABLE;
+ Error err = ERR_UNAVAILABLE;
GDVIRTUAL_CALL(_object_configuration_remove, p_object, p_config, err);
- return (Error)err;
+ return err;
}
void MultiplayerAPIExtension::_bind_methods() {
diff --git a/scene/main/multiplayer_api.h b/scene/main/multiplayer_api.h
index 0b107ee50b..a578e6f2f1 100644
--- a/scene/main/multiplayer_api.h
+++ b/scene/main/multiplayer_api.h
@@ -101,15 +101,15 @@ public:
virtual Error object_configuration_remove(Object *p_object, Variant p_config) override;
// Extensions
- GDVIRTUAL0R(int, _poll);
+ GDVIRTUAL0R(Error, _poll);
GDVIRTUAL1(_set_multiplayer_peer, Ref<MultiplayerPeer>);
GDVIRTUAL0R(Ref<MultiplayerPeer>, _get_multiplayer_peer);
GDVIRTUAL0RC(int, _get_unique_id);
GDVIRTUAL0RC(PackedInt32Array, _get_peer_ids);
- GDVIRTUAL4R(int, _rpc, int, Object *, StringName, Array);
+ GDVIRTUAL4R(Error, _rpc, int, Object *, StringName, Array);
GDVIRTUAL0RC(int, _get_remote_sender_id);
- GDVIRTUAL2R(int, _object_configuration_add, Object *, Variant);
- GDVIRTUAL2R(int, _object_configuration_remove, Object *, Variant);
+ GDVIRTUAL2R(Error, _object_configuration_add, Object *, Variant);
+ GDVIRTUAL2R(Error, _object_configuration_remove, Object *, Variant);
};
#endif // MULTIPLAYER_API_H
diff --git a/scene/main/multiplayer_peer.cpp b/scene/main/multiplayer_peer.cpp
index 83555966d7..f3e56a1455 100644
--- a/scene/main/multiplayer_peer.cpp
+++ b/scene/main/multiplayer_peer.cpp
@@ -163,7 +163,7 @@ Error MultiplayerPeerExtension::put_packet(const uint8_t *p_buffer, int p_buffer
if (!GDVIRTUAL_CALL(_put_packet_script, a, err)) {
return FAILED;
}
- return (Error)err;
+ return err;
}
WARN_PRINT_ONCE("MultiplayerPeerExtension::_put_packet_native is unimplemented!");
return FAILED;
diff --git a/scene/main/node.cpp b/scene/main/node.cpp
index 0670b97d55..52c1df8110 100644
--- a/scene/main/node.cpp
+++ b/scene/main/node.cpp
@@ -39,6 +39,7 @@
#include "scene/animation/tween.h"
#include "scene/debugger/scene_debugger.h"
#include "scene/main/multiplayer_api.h"
+#include "scene/main/window.h"
#include "scene/resources/packed_scene.h"
#include "scene/scene_string_names.h"
#include "viewport.h"
@@ -278,7 +279,10 @@ void Node::_propagate_exit_tree() {
//block while removing children
#ifdef DEBUG_ENABLED
- SceneDebugger::remove_from_cache(data.scene_file_path, this);
+ if (!data.scene_file_path.is_empty()) {
+ // Only remove if file path is set (optimization).
+ SceneDebugger::remove_from_cache(data.scene_file_path, this);
+ }
#endif
data.blocked++;
@@ -304,7 +308,6 @@ void Node::_propagate_exit_tree() {
}
// exit groups
-
for (KeyValue<StringName, GroupData> &E : data.grouped) {
data.tree->remove_from_group(E.key, this);
E.value.group = nullptr;
@@ -943,7 +946,7 @@ String Node::validate_child_name(Node *p_child) {
#endif
String Node::adjust_name_casing(const String &p_name) {
- switch (GLOBAL_GET("editor/node_naming/name_casing").operator int()) {
+ switch (GLOBAL_GET("editor/naming/node_name_casing").operator int()) {
case NAME_CASING_PASCAL_CASE:
return p_name.to_pascal_case();
case NAME_CASING_CAMEL_CASE:
@@ -1165,7 +1168,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_child()` failed. Consider using `remove_child.call_deferred(child)` instead.");
+ ERR_FAIL_COND_MSG(data.blocked > 0, "Parent node is busy adding/removing children, `remove_child()` can't be called at this time. Consider using `remove_child.call_deferred(child)` instead.");
int child_count = data.children.size();
Node **children = data.children.ptrw();
@@ -1196,11 +1199,13 @@ void Node::remove_child(Node *p_child) {
data.internal_children_back--;
}
+ data.blocked++;
p_child->_set_tree(nullptr);
//}
remove_child_notify(p_child);
p_child->notification(NOTIFICATION_UNPARENTED);
+ data.blocked--;
data.children.remove_at(idx);
@@ -1439,6 +1444,18 @@ TypedArray<Node> Node::find_children(const String &p_pattern, const String &p_ty
return ret;
}
+void Node::reparent(Node *p_parent, bool p_keep_global_transform) {
+ ERR_FAIL_NULL(p_parent);
+ ERR_FAIL_NULL_MSG(data.parent, "Node needs a parent to be reparented.");
+
+ if (p_parent == data.parent) {
+ return;
+ }
+
+ data.parent->remove_child(this);
+ p_parent->add_child(this);
+}
+
Node *Node::get_parent() const {
return data.parent;
}
@@ -1455,6 +1472,14 @@ Node *Node::find_parent(const String &p_pattern) const {
return nullptr;
}
+Window *Node::get_window() const {
+ Viewport *vp = get_viewport();
+ if (vp) {
+ return vp->get_base_window();
+ }
+ return nullptr;
+}
+
bool Node::is_ancestor_of(const Node *p_node) const {
ERR_FAIL_NULL_V(p_node, false);
Node *p = p_node->data.parent;
@@ -1962,7 +1987,16 @@ String Node::get_scene_file_path() const {
}
void Node::set_editor_description(const String &p_editor_description) {
+ if (data.editor_description == p_editor_description) {
+ return;
+ }
+
data.editor_description = p_editor_description;
+
+ if (Engine::get_singleton()->is_editor_hint() && is_inside_tree()) {
+ // Update tree so the tooltip in the Scene tree dock is also updated in the editor.
+ get_tree()->tree_changed();
+ }
}
String Node::get_editor_description() const {
@@ -2101,13 +2135,13 @@ Node *Node::_duplicate(int p_flags, HashMap<const Node *, Node *> *r_duplimap) c
} 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;
+ PackedScene::GenEditState edit_state = PackedScene::GEN_EDIT_STATE_DISABLED;
#ifdef TOOLS_ENABLED
if (p_flags & DUPLICATE_FROM_EDITOR) {
- ges = PackedScene::GEN_EDIT_STATE_INSTANCE;
+ edit_state = PackedScene::GEN_EDIT_STATE_INSTANCE;
}
#endif
- node = res->instantiate(ges);
+ node = res->instantiate(edit_state);
ERR_FAIL_COND_V(!node, nullptr);
node->set_scene_instance_load_placeholder(get_scene_instance_load_placeholder());
@@ -2188,7 +2222,7 @@ Node *Node::_duplicate(int p_flags, HashMap<const Node *, Node *> *r_duplimap) c
Variant value = N->get()->get(name).duplicate(true);
- if (E.usage & PROPERTY_USAGE_DO_NOT_SHARE_ON_DUPLICATE) {
+ if (E.usage & PROPERTY_USAGE_ALWAYS_DUPLICATE) {
Resource *res = Object::cast_to<Resource>(value);
if (res) { // Duplicate only if it's a resource
current_node->set(name, res->duplicate());
@@ -2774,10 +2808,8 @@ void Node::unhandled_key_input(const Ref<InputEvent> &p_key_event) {
}
void Node::_bind_methods() {
- GLOBAL_DEF("editor/node_naming/name_num_separator", 0);
- ProjectSettings::get_singleton()->set_custom_property_info("editor/node_naming/name_num_separator", PropertyInfo(Variant::INT, "editor/node_naming/name_num_separator", PROPERTY_HINT_ENUM, "None,Space,Underscore,Dash"));
- 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"));
+ GLOBAL_DEF(PropertyInfo(Variant::INT, "editor/naming/node_name_num_separator", PROPERTY_HINT_ENUM, "None,Space,Underscore,Dash"), 0);
+ GLOBAL_DEF(PropertyInfo(Variant::INT, "editor/naming/node_name_casing", PROPERTY_HINT_ENUM, "PascalCase,camelCase,snake_case"), NAME_CASING_PASCAL_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));
@@ -2786,6 +2818,7 @@ void Node::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_name"), &Node::get_name);
ClassDB::bind_method(D_METHOD("add_child", "node", "force_readable_name", "internal"), &Node::add_child, DEFVAL(false), DEFVAL(0));
ClassDB::bind_method(D_METHOD("remove_child", "node"), &Node::remove_child);
+ ClassDB::bind_method(D_METHOD("reparent", "new_parent", "keep_global_transform"), &Node::reparent, DEFVAL(true));
ClassDB::bind_method(D_METHOD("get_child_count", "include_internal"), &Node::get_child_count, DEFVAL(false)); // Note that the default value bound for include_internal is false, while the method is declared with true. This is because internal nodes are irrelevant for GDSCript.
ClassDB::bind_method(D_METHOD("get_children", "include_internal"), &Node::_get_children, DEFVAL(false));
ClassDB::bind_method(D_METHOD("get_child", "idx", "include_internal"), &Node::get_child, DEFVAL(false));
@@ -2847,6 +2880,7 @@ void Node::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_physics_process_internal", "enable"), &Node::set_physics_process_internal);
ClassDB::bind_method(D_METHOD("is_physics_processing_internal"), &Node::is_physics_processing_internal);
+ ClassDB::bind_method(D_METHOD("get_window"), &Node::get_window);
ClassDB::bind_method(D_METHOD("get_tree"), &Node::get_tree);
ClassDB::bind_method(D_METHOD("create_tween"), &Node::create_tween);
@@ -2922,6 +2956,7 @@ void Node::_bind_methods() {
BIND_CONSTANT(NOTIFICATION_POST_ENTER_TREE);
BIND_CONSTANT(NOTIFICATION_DISABLED);
BIND_CONSTANT(NOTIFICATION_ENABLED);
+ BIND_CONSTANT(NOTIFICATION_NODE_RECACHE_REQUESTED);
BIND_CONSTANT(NOTIFICATION_EDITOR_PRE_SAVE);
BIND_CONSTANT(NOTIFICATION_EDITOR_POST_SAVE);
@@ -2996,7 +3031,7 @@ void Node::_bind_methods() {
}
String Node::_get_name_num_separator() {
- switch (GLOBAL_GET("editor/node_naming/name_num_separator").operator int()) {
+ switch (GLOBAL_GET("editor/naming/node_name_num_separator").operator int()) {
case 0:
return "";
case 1:
diff --git a/scene/main/node.h b/scene/main/node.h
index 611f48c400..493578bc5b 100644
--- a/scene/main/node.h
+++ b/scene/main/node.h
@@ -37,6 +37,7 @@
#include "scene/main/scene_tree.h"
class Viewport;
+class Window;
class SceneState;
class Tween;
class PropertyTweener;
@@ -269,6 +270,7 @@ public:
NOTIFICATION_POST_ENTER_TREE = 27,
NOTIFICATION_DISABLED = 28,
NOTIFICATION_ENABLED = 29,
+ NOTIFICATION_NODE_RECACHE_REQUESTED = 30,
//keep these linked to node
NOTIFICATION_WM_MOUSE_ENTER = 1002,
@@ -317,9 +319,12 @@ public:
bool has_node_and_resource(const NodePath &p_path) const;
Node *get_node_and_resource(const NodePath &p_path, Ref<Resource> &r_res, Vector<StringName> &r_leftover_subpath, bool p_last_is_property = true) const;
+ virtual void reparent(Node *p_parent, bool p_keep_global_transform = true);
Node *get_parent() const;
Node *find_parent(const String &p_pattern) const;
+ Window *get_window() const;
+
_FORCE_INLINE_ SceneTree *get_tree() const {
ERR_FAIL_COND_V(!data.tree, nullptr);
return data.tree;
diff --git a/scene/main/scene_tree.cpp b/scene/main/scene_tree.cpp
index 18253c6094..fbe11c94d1 100644
--- a/scene/main/scene_tree.cpp
+++ b/scene/main/scene_tree.cpp
@@ -1131,11 +1131,10 @@ Error SceneTree::change_scene_to_file(const String &p_path) {
}
Error SceneTree::change_scene_to_packed(const Ref<PackedScene> &p_scene) {
- Node *new_scene = nullptr;
- if (p_scene.is_valid()) {
- new_scene = p_scene->instantiate();
- ERR_FAIL_COND_V(!new_scene, ERR_CANT_CREATE);
- }
+ ERR_FAIL_COND_V_MSG(p_scene.is_null(), ERR_INVALID_PARAMETER, "Can't change to a null scene. Use unload_current_scene() if you wish to unload it.");
+
+ Node *new_scene = p_scene->instantiate();
+ ERR_FAIL_COND_V(!new_scene, ERR_CANT_CREATE);
call_deferred(SNAME("_change_scene"), new_scene);
return OK;
@@ -1147,6 +1146,13 @@ Error SceneTree::reload_current_scene() {
return change_scene_to_file(fname);
}
+void SceneTree::unload_current_scene() {
+ if (current_scene) {
+ memdelete(current_scene);
+ current_scene = nullptr;
+ }
+}
+
void SceneTree::add_current_scene(Node *p_current) {
current_scene = p_current;
root->add_child(p_current);
@@ -1297,6 +1303,7 @@ void SceneTree::_bind_methods() {
ClassDB::bind_method(D_METHOD("change_scene_to_packed", "packed_scene"), &SceneTree::change_scene_to_packed);
ClassDB::bind_method(D_METHOD("reload_current_scene"), &SceneTree::reload_current_scene);
+ ClassDB::bind_method(D_METHOD("unload_current_scene"), &SceneTree::unload_current_scene);
ClassDB::bind_method(D_METHOD("_change_scene"), &SceneTree::_change_scene);
@@ -1387,8 +1394,7 @@ SceneTree::SceneTree() {
debug_collision_contact_color = GLOBAL_DEF("debug/shapes/collision/contact_color", Color(1.0, 0.2, 0.1, 0.8));
debug_paths_color = GLOBAL_DEF("debug/shapes/paths/geometry_color", Color(0.1, 1.0, 0.7, 0.4));
debug_paths_width = GLOBAL_DEF("debug/shapes/paths/geometry_width", 2.0);
- collision_debug_contacts = GLOBAL_DEF("debug/shapes/collision/max_contacts_displayed", 10000);
- ProjectSettings::get_singleton()->set_custom_property_info("debug/shapes/collision/max_contacts_displayed", PropertyInfo(Variant::INT, "debug/shapes/collision/max_contacts_displayed", PROPERTY_HINT_RANGE, "0,20000,1")); // No negative
+ collision_debug_contacts = GLOBAL_DEF(PropertyInfo(Variant::INT, "debug/shapes/collision/max_contacts_displayed", PROPERTY_HINT_RANGE, "0,20000,1"), 10000);
GLOBAL_DEF("debug/shapes/collision/draw_2d_outlines", true);
@@ -1397,6 +1403,7 @@ SceneTree::SceneTree() {
// Create with mainloop.
root = memnew(Window);
+ root->set_min_size(Size2i(64, 64)); // Define a very small minimum window size to prevent bugs such as GH-37242.
root->set_process_mode(Node::PROCESS_MODE_PAUSABLE);
root->set_name("root");
root->set_title(GLOBAL_GET("application/config/name"));
@@ -1414,19 +1421,16 @@ SceneTree::SceneTree() {
root->set_as_audio_listener_2d(true);
current_scene = nullptr;
- const int msaa_mode_2d = GLOBAL_DEF_BASIC("rendering/anti_aliasing/quality/msaa_2d", 0);
- ProjectSettings::get_singleton()->set_custom_property_info("rendering/anti_aliasing/quality/msaa_2d", PropertyInfo(Variant::INT, "rendering/anti_aliasing/quality/msaa_2d", PROPERTY_HINT_ENUM, String::utf8("Disabled (Fastest),2× (Average),4× (Slow),8× (Slowest)")));
+ const int msaa_mode_2d = GLOBAL_DEF_BASIC(PropertyInfo(Variant::INT, "rendering/anti_aliasing/quality/msaa_2d", PROPERTY_HINT_ENUM, String::utf8("Disabled (Fastest),2× (Average),4× (Slow),8× (Slowest)")), 0);
root->set_msaa_2d(Viewport::MSAA(msaa_mode_2d));
- const int msaa_mode_3d = GLOBAL_DEF_BASIC("rendering/anti_aliasing/quality/msaa_3d", 0);
- 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)")));
+ const int msaa_mode_3d = GLOBAL_DEF_BASIC(PropertyInfo(Variant::INT, "rendering/anti_aliasing/quality/msaa_3d", PROPERTY_HINT_ENUM, String::utf8("Disabled (Fastest),2× (Average),4× (Slow),8× (Slowest)")), 0);
root->set_msaa_3d(Viewport::MSAA(msaa_mode_3d));
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);
- ProjectSettings::get_singleton()->set_custom_property_info("rendering/anti_aliasing/quality/screen_space_aa", PropertyInfo(Variant::INT, "rendering/anti_aliasing/quality/screen_space_aa", PROPERTY_HINT_ENUM, "Disabled (Fastest),FXAA (Fast)"));
+ const int ssaa_mode = GLOBAL_DEF_BASIC(PropertyInfo(Variant::INT, "rendering/anti_aliasing/quality/screen_space_aa", PROPERTY_HINT_ENUM, "Disabled (Fastest),FXAA (Fast)"), 0);
root->set_screen_space_aa(Viewport::ScreenSpaceAA(ssaa_mode));
const bool use_taa = GLOBAL_DEF_BASIC("rendering/anti_aliasing/quality/use_taa", false);
@@ -1438,8 +1442,7 @@ SceneTree::SceneTree() {
const bool use_occlusion_culling = GLOBAL_DEF("rendering/occlusion_culling/use_occlusion_culling", false);
root->set_use_occlusion_culling(use_occlusion_culling);
- float mesh_lod_threshold = GLOBAL_DEF("rendering/mesh_lod/lod_change/threshold_pixels", 1.0);
- ProjectSettings::get_singleton()->set_custom_property_info("rendering/mesh_lod/lod_change/threshold_pixels", PropertyInfo(Variant::FLOAT, "rendering/mesh_lod/lod_change/threshold_pixels", PROPERTY_HINT_RANGE, "0,1024,0.1"));
+ float mesh_lod_threshold = GLOBAL_DEF(PropertyInfo(Variant::FLOAT, "rendering/mesh_lod/lod_change/threshold_pixels", PROPERTY_HINT_RANGE, "0,1024,0.1"), 1.0);
root->set_mesh_lod_threshold(mesh_lod_threshold);
bool snap_2d_transforms = GLOBAL_DEF("rendering/2d/snap/snap_2d_transforms_to_pixel", false);
@@ -1449,14 +1452,9 @@ SceneTree::SceneTree() {
root->set_snap_2d_vertices_to_pixel(snap_2d_vertices);
// We setup VRS for the main viewport here, in the editor this will have little effect.
- const int vrs_mode = GLOBAL_DEF("rendering/vrs/mode", 0);
- ProjectSettings::get_singleton()->set_custom_property_info("rendering/vrs/mode", PropertyInfo(Variant::INT, "rendering/vrs/mode", PROPERTY_HINT_ENUM, String::utf8("Disabled,Texture,XR")));
+ const int vrs_mode = GLOBAL_DEF(PropertyInfo(Variant::INT, "rendering/vrs/mode", PROPERTY_HINT_ENUM, String::utf8("Disabled,Texture,XR")), 0);
root->set_vrs_mode(Viewport::VRSMode(vrs_mode));
- const String vrs_texture_path = String(GLOBAL_DEF("rendering/vrs/texture", String())).strip_edges();
- ProjectSettings::get_singleton()->set_custom_property_info("rendering/vrs/texture",
- PropertyInfo(Variant::STRING,
- "rendering/vrs/texture",
- PROPERTY_HINT_FILE, "*.bmp,*.png,*.tga,*.webp"));
+ const String vrs_texture_path = String(GLOBAL_DEF(PropertyInfo(Variant::STRING, "rendering/vrs/texture", PROPERTY_HINT_FILE, "*.bmp,*.png,*.tga,*.webp"), String())).strip_edges();
if (vrs_mode == 1 && !vrs_texture_path.is_empty()) {
Ref<Image> vrs_image;
vrs_image.instantiate();
@@ -1471,18 +1469,13 @@ SceneTree::SceneTree() {
}
}
- int shadowmap_size = GLOBAL_DEF("rendering/lights_and_shadows/positional_shadow/atlas_size", 4096);
- ProjectSettings::get_singleton()->set_custom_property_info("rendering/lights_and_shadows/positional_shadow/atlas_size", PropertyInfo(Variant::INT, "rendering/lights_and_shadows/positional_shadow/atlas_size", PROPERTY_HINT_RANGE, "256,16384"));
+ int shadowmap_size = GLOBAL_DEF(PropertyInfo(Variant::INT, "rendering/lights_and_shadows/positional_shadow/atlas_size", PROPERTY_HINT_RANGE, "256,16384"), 4096);
GLOBAL_DEF("rendering/lights_and_shadows/positional_shadow/atlas_size.mobile", 2048);
bool shadowmap_16_bits = GLOBAL_DEF("rendering/lights_and_shadows/positional_shadow/atlas_16_bits", true);
- int atlas_q0 = GLOBAL_DEF("rendering/lights_and_shadows/positional_shadow/atlas_quadrant_0_subdiv", 2);
- int atlas_q1 = GLOBAL_DEF("rendering/lights_and_shadows/positional_shadow/atlas_quadrant_1_subdiv", 2);
- int atlas_q2 = GLOBAL_DEF("rendering/lights_and_shadows/positional_shadow/atlas_quadrant_2_subdiv", 3);
- int atlas_q3 = GLOBAL_DEF("rendering/lights_and_shadows/positional_shadow/atlas_quadrant_3_subdiv", 4);
- ProjectSettings::get_singleton()->set_custom_property_info("rendering/lights_and_shadows/positional_shadow/atlas_quadrant_0_subdiv", PropertyInfo(Variant::INT, "rendering/lights_and_shadows/positional_shadow/atlas_quadrant_0_subdiv", PROPERTY_HINT_ENUM, "Disabled,1 Shadow,4 Shadows,16 Shadows,64 Shadows,256 Shadows,1024 Shadows"));
- ProjectSettings::get_singleton()->set_custom_property_info("rendering/lights_and_shadows/positional_shadow/atlas_quadrant_1_subdiv", PropertyInfo(Variant::INT, "rendering/lights_and_shadows/positional_shadow/atlas_quadrant_1_subdiv", PROPERTY_HINT_ENUM, "Disabled,1 Shadow,4 Shadows,16 Shadows,64 Shadows,256 Shadows,1024 Shadows"));
- ProjectSettings::get_singleton()->set_custom_property_info("rendering/lights_and_shadows/positional_shadow/atlas_quadrant_2_subdiv", PropertyInfo(Variant::INT, "rendering/lights_and_shadows/positional_shadow/atlas_quadrant_2_subdiv", PROPERTY_HINT_ENUM, "Disabled,1 Shadow,4 Shadows,16 Shadows,64 Shadows,256 Shadows,1024 Shadows"));
- ProjectSettings::get_singleton()->set_custom_property_info("rendering/lights_and_shadows/positional_shadow/atlas_quadrant_3_subdiv", PropertyInfo(Variant::INT, "rendering/lights_and_shadows/positional_shadow/atlas_quadrant_3_subdiv", PROPERTY_HINT_ENUM, "Disabled,1 Shadow,4 Shadows,16 Shadows,64 Shadows,256 Shadows,1024 Shadows"));
+ int atlas_q0 = GLOBAL_DEF(PropertyInfo(Variant::INT, "rendering/lights_and_shadows/positional_shadow/atlas_quadrant_0_subdiv", PROPERTY_HINT_ENUM, "Disabled,1 Shadow,4 Shadows,16 Shadows,64 Shadows,256 Shadows,1024 Shadows"), 2);
+ int atlas_q1 = GLOBAL_DEF(PropertyInfo(Variant::INT, "rendering/lights_and_shadows/positional_shadow/atlas_quadrant_1_subdiv", PROPERTY_HINT_ENUM, "Disabled,1 Shadow,4 Shadows,16 Shadows,64 Shadows,256 Shadows,1024 Shadows"), 2);
+ int atlas_q2 = GLOBAL_DEF(PropertyInfo(Variant::INT, "rendering/lights_and_shadows/positional_shadow/atlas_quadrant_2_subdiv", PROPERTY_HINT_ENUM, "Disabled,1 Shadow,4 Shadows,16 Shadows,64 Shadows,256 Shadows,1024 Shadows"), 3);
+ int atlas_q3 = GLOBAL_DEF(PropertyInfo(Variant::INT, "rendering/lights_and_shadows/positional_shadow/atlas_quadrant_3_subdiv", PROPERTY_HINT_ENUM, "Disabled,1 Shadow,4 Shadows,16 Shadows,64 Shadows,256 Shadows,1024 Shadows"), 4);
root->set_positional_shadow_atlas_size(shadowmap_size);
root->set_positional_shadow_atlas_16_bits(shadowmap_16_bits);
@@ -1491,14 +1484,11 @@ SceneTree::SceneTree() {
root->set_positional_shadow_atlas_quadrant_subdiv(2, Viewport::PositionalShadowAtlasQuadrantSubdiv(atlas_q2));
root->set_positional_shadow_atlas_quadrant_subdiv(3, Viewport::PositionalShadowAtlasQuadrantSubdiv(atlas_q3));
- Viewport::SDFOversize sdf_oversize = Viewport::SDFOversize(int(GLOBAL_DEF("rendering/2d/sdf/oversize", 1)));
+ Viewport::SDFOversize sdf_oversize = Viewport::SDFOversize(int(GLOBAL_DEF(PropertyInfo(Variant::INT, "rendering/2d/sdf/oversize", PROPERTY_HINT_ENUM, "100%,120%,150%,200%"), 1)));
root->set_sdf_oversize(sdf_oversize);
- Viewport::SDFScale sdf_scale = Viewport::SDFScale(int(GLOBAL_DEF("rendering/2d/sdf/scale", 1)));
+ Viewport::SDFScale sdf_scale = Viewport::SDFScale(int(GLOBAL_DEF(PropertyInfo(Variant::INT, "rendering/2d/sdf/scale", PROPERTY_HINT_ENUM, "100%,50%,25%"), 1)));
root->set_sdf_scale(sdf_scale);
- ProjectSettings::get_singleton()->set_custom_property_info("rendering/2d/sdf/oversize", PropertyInfo(Variant::INT, "rendering/2d/sdf/oversize", PROPERTY_HINT_ENUM, "100%,120%,150%,200%"));
- ProjectSettings::get_singleton()->set_custom_property_info("rendering/2d/sdf/scale", PropertyInfo(Variant::INT, "rendering/2d/sdf/scale", PROPERTY_HINT_ENUM, "100%,50%,25%"));
-
#ifndef _3D_DISABLED
{ // Load default fallback environment.
// Get possible extensions.
@@ -1512,9 +1502,8 @@ SceneTree::SceneTree() {
ext_hint += "*." + E;
}
// Get path.
- String env_path = GLOBAL_DEF("rendering/environment/defaults/default_environment", "");
+ String env_path = GLOBAL_DEF(PropertyInfo(Variant::STRING, "rendering/environment/defaults/default_environment", PROPERTY_HINT_FILE, ext_hint), "");
// Setup property.
- ProjectSettings::get_singleton()->set_custom_property_info("rendering/environment/defaults/default_environment", PropertyInfo(Variant::STRING, "rendering/viewport/default_environment", PROPERTY_HINT_FILE, ext_hint));
env_path = env_path.strip_edges();
if (!env_path.is_empty()) {
Ref<Environment> env = ResourceLoader::load(env_path);
diff --git a/scene/main/scene_tree.h b/scene/main/scene_tree.h
index 77cfe0a04a..fc185b4f37 100644
--- a/scene/main/scene_tree.h
+++ b/scene/main/scene_tree.h
@@ -361,6 +361,7 @@ public:
Error change_scene_to_file(const String &p_path);
Error change_scene_to_packed(const Ref<PackedScene> &p_scene);
Error reload_current_scene();
+ void unload_current_scene();
Ref<SceneTreeTimer> create_timer(double p_delay_sec, bool p_process_always = true, bool p_process_in_physics = false, bool p_ignore_time_scale = false);
Ref<Tween> create_tween();
diff --git a/scene/main/viewport.cpp b/scene/main/viewport.cpp
index 43f9863d14..23b7c072be 100644
--- a/scene/main/viewport.cpp
+++ b/scene/main/viewport.cpp
@@ -36,6 +36,7 @@
#include "core/object/message_queue.h"
#include "core/string/translation.h"
#include "core/templates/pair.h"
+#include "core/templates/sort_array.h"
#include "scene/2d/audio_listener_2d.h"
#include "scene/2d/camera_2d.h"
#include "scene/2d/collision_object_2d.h"
@@ -379,7 +380,7 @@ void Viewport::_notification(int p_what) {
if (get_tree()->is_debugging_collisions_hint()) {
PhysicsServer2D::get_singleton()->space_set_debug_contacts(find_world_2d()->get_space(), get_tree()->get_collision_debug_contact_count());
contact_2d_debug = RenderingServer::get_singleton()->canvas_item_create();
- RenderingServer::get_singleton()->canvas_item_set_parent(contact_2d_debug, find_world_2d()->get_canvas());
+ RenderingServer::get_singleton()->canvas_item_set_parent(contact_2d_debug, current_canvas);
#ifndef _3D_DISABLED
PhysicsServer3D::get_singleton()->space_set_debug_contacts(find_world_3d()->get_space(), get_tree()->get_collision_debug_contact_count());
contact_3d_debug_multimesh = RenderingServer::get_singleton()->multimesh_create();
@@ -524,7 +525,12 @@ void Viewport::_process_picking() {
if (!physics_object_picking) {
return;
}
- if (to_screen_rect != Rect2i() && Input::get_singleton()->get_mouse_mode() == Input::MOUSE_MODE_CAPTURED) {
+ if (Object::cast_to<Window>(this) && Input::get_singleton()->get_mouse_mode() == Input::MOUSE_MODE_CAPTURED) {
+ return;
+ }
+ if (!gui.mouse_in_viewport) {
+ // Clear picking events if mouse has left viewport.
+ physics_picking_events.clear();
return;
}
@@ -603,12 +609,12 @@ void Viewport::_process_picking() {
physics_last_mouse_state.meta = mb->is_meta_pressed();
if (mb->is_pressed()) {
- physics_last_mouse_state.mouse_mask |= mouse_button_to_mask(mb->get_button_index());
+ physics_last_mouse_state.mouse_mask.set_flag(mouse_button_to_mask(mb->get_button_index()));
} else {
- physics_last_mouse_state.mouse_mask &= ~mouse_button_to_mask(mb->get_button_index());
+ physics_last_mouse_state.mouse_mask.clear_flag(mouse_button_to_mask(mb->get_button_index()));
// If touch mouse raised, assume we don't know last mouse pos until new events come
- if (mb->get_device() == InputEvent::DEVICE_ID_TOUCH_MOUSE) {
+ if (mb->get_device() == InputEvent::DEVICE_ID_EMULATION) {
physics_has_last_mousepos = false;
}
}
@@ -664,6 +670,25 @@ void Viewport::_process_picking() {
point_params.pick_point = true;
int rc = ss2d->intersect_point(point_params, res, 64);
+ if (physics_object_picking_sort) {
+ struct ComparatorCollisionObjects {
+ bool operator()(const PhysicsDirectSpaceState2D::ShapeResult &p_a, const PhysicsDirectSpaceState2D::ShapeResult &p_b) const {
+ CollisionObject2D *a = Object::cast_to<CollisionObject2D>(p_a.collider);
+ CollisionObject2D *b = Object::cast_to<CollisionObject2D>(p_b.collider);
+ if (!a || !b) {
+ return false;
+ }
+ int za = a->get_effective_z_index();
+ int zb = b->get_effective_z_index();
+ if (za != zb) {
+ return zb < za;
+ }
+ return a->is_greater_than(b);
+ }
+ };
+ SortArray<PhysicsDirectSpaceState2D::ShapeResult, ComparatorCollisionObjects> sorter;
+ sorter.sort(res, rc);
+ }
for (int i = 0; i < rc; i++) {
if (res[i].collider_id.is_valid() && res[i].collider) {
CollisionObject2D *co = Object::cast_to<CollisionObject2D>(res[i].collider);
@@ -704,25 +729,15 @@ void Viewport::_process_picking() {
}
#ifndef _3D_DISABLED
- bool captured = false;
-
+ CollisionObject3D *capture_object = nullptr;
if (physics_object_capture.is_valid()) {
- CollisionObject3D *co = Object::cast_to<CollisionObject3D>(ObjectDB::get_instance(physics_object_capture));
- if (co && camera_3d) {
- _collision_object_3d_input_event(co, camera_3d, ev, Vector3(), Vector3(), 0);
- captured = true;
- if (mb.is_valid() && mb->get_button_index() == MouseButton::LEFT && !mb->is_pressed()) {
- physics_object_capture = ObjectID();
- }
-
- } else {
+ capture_object = Object::cast_to<CollisionObject3D>(ObjectDB::get_instance(physics_object_capture));
+ if (!capture_object || !camera_3d || (mb.is_valid() && mb->get_button_index() == MouseButton::LEFT && !mb->is_pressed())) {
physics_object_capture = ObjectID();
}
}
- if (captured) {
- // None.
- } else if (pos == last_pos) {
+ if (pos == last_pos) {
if (last_id.is_valid()) {
if (ObjectDB::get_instance(last_id) && last_object) {
// Good, exists.
@@ -748,13 +763,12 @@ void Viewport::_process_picking() {
bool col = space->intersect_ray(ray_params, result);
ObjectID new_collider;
- if (col) {
- CollisionObject3D *co = Object::cast_to<CollisionObject3D>(result.collider);
- if (co && co->can_process()) {
- _collision_object_3d_input_event(co, camera_3d, ev, result.position, result.normal, result.shape);
+ CollisionObject3D *co = col ? Object::cast_to<CollisionObject3D>(result.collider) : nullptr;
+ if (co && co->can_process()) {
+ new_collider = result.collider_id;
+ if (!capture_object) {
last_object = co;
last_id = result.collider_id;
- new_collider = last_id;
if (co->get_capture_input_on_drag() && mb.is_valid() && mb->get_button_index() == MouseButton::LEFT && mb->is_pressed()) {
physics_object_capture = last_id;
}
@@ -763,21 +777,24 @@ void Viewport::_process_picking() {
if (is_mouse && new_collider != physics_object_over) {
if (physics_object_over.is_valid()) {
- CollisionObject3D *co = Object::cast_to<CollisionObject3D>(ObjectDB::get_instance(physics_object_over));
- if (co) {
- co->_mouse_exit();
+ CollisionObject3D *previous_co = Object::cast_to<CollisionObject3D>(ObjectDB::get_instance(physics_object_over));
+ if (previous_co) {
+ previous_co->_mouse_exit();
}
}
if (new_collider.is_valid()) {
- CollisionObject3D *co = Object::cast_to<CollisionObject3D>(ObjectDB::get_instance(new_collider));
- if (co) {
- co->_mouse_enter();
- }
+ DEV_ASSERT(co);
+ co->_mouse_enter();
}
physics_object_over = new_collider;
}
+ if (capture_object) {
+ _collision_object_3d_input_event(capture_object, camera_3d, ev, result.position, result.normal, result.shape);
+ } else if (new_collider.is_valid()) {
+ _collision_object_3d_input_event(co, camera_3d, ev, result.position, result.normal, result.shape);
+ }
}
last_pos = pos;
@@ -799,16 +816,22 @@ void Viewport::update_canvas_items() {
_update_canvas_items(this);
}
-void Viewport::_set_size(const Size2i &p_size, const Size2i &p_size_2d_override, const Rect2i &p_to_screen_rect, const Transform2D &p_stretch_transform, bool p_allocated) {
- if (size == p_size && size_allocated == p_allocated && stretch_transform == p_stretch_transform && p_size_2d_override == size_2d_override && to_screen_rect == p_to_screen_rect) {
+void Viewport::_set_size(const Size2i &p_size, const Size2i &p_size_2d_override, bool p_allocated) {
+ Transform2D stretch_transform_new = Transform2D();
+ if (is_size_2d_override_stretch_enabled() && p_size_2d_override.width > 0 && p_size_2d_override.height > 0) {
+ Size2 scale = Size2(p_size) / Size2(p_size_2d_override);
+ stretch_transform_new.scale(scale);
+ }
+
+ Size2i new_size = p_size.max(Size2i(2, 2));
+ if (size == new_size && size_allocated == p_allocated && stretch_transform == stretch_transform_new && p_size_2d_override == size_2d_override) {
return;
}
- size = p_size;
+ size = new_size;
size_allocated = p_allocated;
size_2d_override = p_size_2d_override;
- stretch_transform = p_stretch_transform;
- to_screen_rect = p_to_screen_rect;
+ stretch_transform = stretch_transform_new;
#ifndef _3D_DISABLED
if (!use_xr) {
@@ -1053,6 +1076,29 @@ Transform2D Viewport::get_final_transform() const {
return stretch_transform * global_canvas_transform;
}
+void Viewport::assign_next_enabled_camera_2d(const StringName &p_camera_group) {
+ List<Node *> camera_list;
+ get_tree()->get_nodes_in_group(p_camera_group, &camera_list);
+
+ Camera2D *new_camera = nullptr;
+ for (Node *E : camera_list) {
+ Camera2D *cam = Object::cast_to<Camera2D>(E);
+ if (!cam) {
+ continue; // Non-camera node (e.g. ParallaxBackground).
+ }
+
+ if (cam->is_enabled()) {
+ new_camera = cam;
+ break;
+ }
+ }
+
+ _camera_2d_set(new_camera);
+ if (!camera_2d) {
+ set_canvas_transform(Transform2D());
+ }
+}
+
void Viewport::_update_canvas_items(Node *p_node) {
if (p_node != this) {
Window *w = Object::cast_to<Window>(p_node);
@@ -1117,32 +1163,26 @@ Viewport::PositionalShadowAtlasQuadrantSubdiv Viewport::get_positional_shadow_at
return positional_shadow_atlas_quadrant_subdiv[p_quadrant];
}
-Transform2D Viewport::_get_input_pre_xform() const {
- Transform2D pre_xf;
-
- if (to_screen_rect.size.x != 0 && to_screen_rect.size.y != 0) {
- pre_xf.columns[2] = -to_screen_rect.position;
- pre_xf.scale(Vector2(size) / to_screen_rect.size);
- }
-
- return pre_xf;
-}
-
Ref<InputEvent> Viewport::_make_input_local(const Ref<InputEvent> &ev) {
if (ev.is_null()) {
return ev; // No transformation defined for null event
}
- Transform2D ai = get_final_transform().affine_inverse() * _get_input_pre_xform();
+ Transform2D ai = get_final_transform().affine_inverse();
return ev->xformed_by(ai);
}
Vector2 Viewport::get_mouse_position() const {
- return gui.last_mouse_pos;
+ if (DisplayServer::get_singleton()->has_feature(DisplayServer::FEATURE_MOUSE)) {
+ return get_screen_transform_internal(true).affine_inverse().xform(DisplayServer::get_singleton()->mouse_get_position());
+ } else {
+ // Fallback to Input for getting mouse position in case of emulated mouse.
+ return get_screen_transform_internal().affine_inverse().xform(Input::get_singleton()->get_mouse_position());
+ }
}
void Viewport::warp_mouse(const Vector2 &p_position) {
- Transform2D xform = get_screen_transform();
+ Transform2D xform = get_screen_transform_internal();
Vector2 gpos = xform.xform(p_position);
Input::get_singleton()->warp_mouse(gpos);
}
@@ -1256,6 +1296,7 @@ void Viewport::_gui_show_tooltip() {
panel->set_transient(true);
panel->set_flag(Window::FLAG_NO_FOCUS, true);
panel->set_flag(Window::FLAG_POPUP, false);
+ panel->set_flag(Window::FLAG_MOUSE_PASSTHROUGH, true);
panel->set_wrap_controls(true);
panel->add_child(base_tooltip);
panel->gui_parent = this;
@@ -1298,7 +1339,6 @@ void Viewport::_gui_show_tooltip() {
r.position.y = vr.position.y;
}
- gui.tooltip_popup->set_current_screen(window->get_current_screen());
gui.tooltip_popup->set_position(r.position);
gui.tooltip_popup->set_size(r.size);
@@ -1314,7 +1354,7 @@ bool Viewport::_gui_call_input(Control *p_control, const Ref<InputEvent> &p_inpu
Ref<InputEvent> ev = p_input;
// Returns true if an event should be impacted by a control's mouse filter.
- bool is_mouse_event = Ref<InputEventMouse>(p_input).is_valid();
+ bool is_pointer_event = Ref<InputEventMouse>(p_input).is_valid() || Ref<InputEventScreenDrag>(p_input).is_valid() || Ref<InputEventScreenTouch>(p_input).is_valid();
Ref<InputEventMouseButton> mb = p_input;
bool is_scroll_event = mb.is_valid() &&
@@ -1338,8 +1378,8 @@ bool Viewport::_gui_call_input(Control *p_control, const Ref<InputEvent> &p_inpu
stopped = true;
break;
}
- if (control->data.mouse_filter == Control::MOUSE_FILTER_STOP && is_mouse_event && !(is_scroll_event && control->data.force_pass_scroll_events)) {
- // Mouse events are stopped by default with MOUSE_FILTER_STOP, unless we have a scroll event and force_pass_scroll_events set to true
+ if (control->data.mouse_filter == Control::MOUSE_FILTER_STOP && is_pointer_event && !(is_scroll_event && control->data.force_pass_scroll_events)) {
+ // Mouse, ScreenDrag and ScreenTouch events are stopped by default with MOUSE_FILTER_STOP, unless we have a scroll event and force_pass_scroll_events set to true
stopped = true;
break;
}
@@ -1402,7 +1442,7 @@ Control *Viewport::gui_find_control(const Point2 &p_global) {
xform = sw->get_canvas_transform();
}
- Control *ret = _gui_find_control_at_pos(sw, p_global, xform, gui.focus_inv_xform);
+ Control *ret = _gui_find_control_at_pos(sw, p_global, xform);
if (ret) {
return ret;
}
@@ -1411,7 +1451,7 @@ Control *Viewport::gui_find_control(const Point2 &p_global) {
return nullptr;
}
-Control *Viewport::_gui_find_control_at_pos(CanvasItem *p_node, const Point2 &p_global, const Transform2D &p_xform, Transform2D &r_inv_xform) {
+Control *Viewport::_gui_find_control_at_pos(CanvasItem *p_node, const Point2 &p_global, const Transform2D &p_xform) {
if (!p_node->is_visible()) {
return nullptr; // Canvas item hidden, discard.
}
@@ -1431,7 +1471,7 @@ Control *Viewport::_gui_find_control_at_pos(CanvasItem *p_node, const Point2 &p_
continue;
}
- Control *ret = _gui_find_control_at_pos(ci, p_global, matrix, r_inv_xform);
+ Control *ret = _gui_find_control_at_pos(ci, p_global, matrix);
if (ret) {
return ret;
}
@@ -1449,7 +1489,6 @@ Control *Viewport::_gui_find_control_at_pos(CanvasItem *p_node, const Point2 &p_
Control *drag_preview = _gui_get_drag_preview();
if (!drag_preview || (c != drag_preview && !drag_preview->is_ancestor_of(c))) {
- r_inv_xform = matrix;
return c;
}
@@ -1496,20 +1535,20 @@ void Viewport::_gui_input_event(Ref<InputEvent> p_event) {
Point2 mpos = mb->get_position();
if (mb->is_pressed()) {
- Size2 pos = mpos;
- if (gui.mouse_focus_mask != MouseButton::NONE) {
+ if (!gui.mouse_focus_mask.is_empty()) {
// Do not steal mouse focus and stuff while a focus mask exists.
- gui.mouse_focus_mask |= mouse_button_to_mask(mb->get_button_index());
+ gui.mouse_focus_mask.set_flag(mouse_button_to_mask(mb->get_button_index()));
} else {
- gui.mouse_focus = gui_find_control(pos);
+ gui.mouse_focus = gui_find_control(mpos);
gui.last_mouse_focus = gui.mouse_focus;
if (!gui.mouse_focus) {
- gui.mouse_focus_mask = MouseButton::NONE;
+ gui.mouse_focus_mask.clear();
return;
}
- gui.mouse_focus_mask = mouse_button_to_mask(mb->get_button_index());
+ gui.mouse_focus_mask.clear();
+ gui.mouse_focus_mask.set_flag(mouse_button_to_mask(mb->get_button_index()));
if (mb->get_button_index() == MouseButton::LEFT) {
gui.drag_accum = Vector2();
@@ -1519,10 +1558,7 @@ void Viewport::_gui_input_event(Ref<InputEvent> p_event) {
mb = mb->xformed_by(Transform2D()); // Make a copy of the event.
- mb->set_global_position(pos);
-
- pos = gui.focus_inv_xform.xform(pos);
-
+ Point2 pos = gui.mouse_focus->get_global_transform_with_canvas().affine_inverse().xform(mpos);
mb->set_position(pos);
#ifdef DEBUG_ENABLED
@@ -1579,18 +1615,15 @@ void Viewport::_gui_input_event(Ref<InputEvent> p_event) {
_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.
+ gui.mouse_focus_mask.clear_flag(mouse_button_to_mask(mb->get_button_index())); // Remove from mask.
if (!gui.mouse_focus) {
// Release event is only sent if a mouse focus (previously pressed button) exists.
return;
}
- Size2 pos = mpos;
-
mb = mb->xformed_by(Transform2D()); // Make a copy.
- mb->set_global_position(pos);
- pos = gui.focus_inv_xform.xform(pos);
+ Point2 pos = gui.mouse_focus->get_global_transform_with_canvas().affine_inverse().xform(mpos);
mb->set_position(pos);
Control *mouse_focus = gui.mouse_focus;
@@ -1598,7 +1631,7 @@ void Viewport::_gui_input_event(Ref<InputEvent> p_event) {
// Disable mouse focus if needed before calling input,
// this makes popups on mouse press event work better,
// as the release will never be received otherwise.
- if (gui.mouse_focus_mask == MouseButton::NONE) {
+ if (gui.mouse_focus_mask.is_empty()) {
gui.mouse_focus = nullptr;
gui.forced_mouse_focus = false;
}
@@ -1620,7 +1653,7 @@ void Viewport::_gui_input_event(Ref<InputEvent> p_event) {
Point2 mpos = mm->get_position();
// Drag & drop.
- if (!gui.drag_attempted && gui.mouse_focus && (mm->get_button_mask() & MouseButton::MASK_LEFT) != MouseButton::NONE) {
+ if (!gui.drag_attempted && gui.mouse_focus && (mm->get_button_mask().has_flag(MouseButtonMask::LEFT))) {
gui.drag_accum += mm->get_relative();
float len = gui.drag_accum.length();
if (len > 10) {
@@ -1634,7 +1667,7 @@ void Viewport::_gui_input_event(Ref<InputEvent> p_event) {
if (gui.drag_data.get_type() != Variant::NIL) {
gui.mouse_focus = nullptr;
gui.forced_mouse_focus = false;
- gui.mouse_focus_mask = MouseButton::NONE;
+ gui.mouse_focus_mask.clear();
break;
} else {
Control *drag_preview = _gui_get_drag_preview();
@@ -1702,7 +1735,7 @@ void Viewport::_gui_input_event(Ref<InputEvent> p_event) {
mm->set_velocity(velocity);
mm->set_relative(rel);
- if (mm->get_button_mask() == MouseButton::NONE) {
+ if (mm->get_button_mask().is_empty()) {
// Nothing pressed.
bool is_tooltip_shown = false;
@@ -1745,7 +1778,7 @@ void Viewport::_gui_input_event(Ref<InputEvent> p_event) {
Control *c = over;
Vector2 cpos = pos;
while (c) {
- if (gui.mouse_focus_mask != MouseButton::NONE || c->has_point(cpos)) {
+ if (!gui.mouse_focus_mask.is_empty() || c->has_point(cpos)) {
cursor_shape = c->get_cursor_shape(cpos);
} else {
cursor_shape = Control::CURSOR_ARROW;
@@ -1802,9 +1835,7 @@ void Viewport::_gui_input_event(Ref<InputEvent> p_event) {
if (w->is_embedded()) {
embedder = w->_get_embedder();
- Transform2D ai = (get_final_transform().affine_inverse() * _get_input_pre_xform()).affine_inverse();
-
- viewport_pos = ai.xform(mpos) + w->get_position(); // To parent coords.
+ viewport_pos = get_final_transform().xform(mpos) + w->get_position(); // To parent coords.
}
}
}
@@ -1854,7 +1885,7 @@ void Viewport::_gui_input_event(Ref<InputEvent> p_event) {
if (viewport_under) {
if (viewport_under != this) {
- Transform2D ai = (viewport_under->get_final_transform().affine_inverse() * viewport_under->_get_input_pre_xform());
+ Transform2D ai = viewport_under->get_final_transform().affine_inverse();
viewport_pos = ai.xform(viewport_pos);
}
// Find control under at position.
@@ -1893,11 +1924,7 @@ void Viewport::_gui_input_event(Ref<InputEvent> p_event) {
bool stopped = false;
if (over->can_process()) {
touch_event = touch_event->xformed_by(Transform2D()); // Make a copy.
- if (over == gui.mouse_focus) {
- pos = gui.focus_inv_xform.xform(pos);
- } else {
- pos = over->get_global_transform_with_canvas().affine_inverse().xform(pos);
- }
+ pos = over->get_global_transform_with_canvas().affine_inverse().xform(pos);
touch_event->set_position(pos);
stopped = _gui_call_input(over, touch_event);
}
@@ -1912,11 +1939,7 @@ void Viewport::_gui_input_event(Ref<InputEvent> p_event) {
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.
- 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);
- }
+ pos = over->get_global_transform_with_canvas().affine_inverse().xform(pos);
touch_event->set_position(pos);
stopped = _gui_call_input(over, touch_event);
@@ -1942,11 +1965,7 @@ void Viewport::_gui_input_event(Ref<InputEvent> p_event) {
bool stopped = false;
if (over->can_process()) {
gesture_event = gesture_event->xformed_by(Transform2D()); // Make a copy.
- if (over == gui.mouse_focus) {
- pos = gui.focus_inv_xform.xform(pos);
- } else {
- pos = over->get_global_transform_with_canvas().affine_inverse().xform(pos);
- }
+ pos = over->get_global_transform_with_canvas().affine_inverse().xform(pos);
gesture_event->set_position(pos);
stopped = _gui_call_input(over, gesture_event);
}
@@ -2104,7 +2123,7 @@ void Viewport::_gui_cleanup_internal_state(Ref<InputEvent> p_event) {
Ref<InputEventMouseButton> mb = p_event;
if (mb.is_valid()) {
if (!mb->is_pressed()) {
- gui.mouse_focus_mask &= ~mouse_button_to_mask(mb->get_button_index()); // Remove from mask.
+ gui.mouse_focus_mask.clear_flag(mouse_button_to_mask(mb->get_button_index())); // Remove from mask.
}
}
}
@@ -2195,7 +2214,7 @@ void Viewport::_gui_remove_control(Control *p_control) {
if (gui.mouse_focus == p_control) {
gui.mouse_focus = nullptr;
gui.forced_mouse_focus = false;
- gui.mouse_focus_mask = MouseButton::NONE;
+ gui.mouse_focus_mask.clear();
}
if (gui.last_mouse_focus == p_control) {
gui.last_mouse_focus = nullptr;
@@ -2264,10 +2283,10 @@ void Viewport::_drop_mouse_over() {
void Viewport::_drop_mouse_focus() {
Control *c = gui.mouse_focus;
- MouseButton mask = gui.mouse_focus_mask;
+ BitField<MouseButtonMask> mask = gui.mouse_focus_mask;
gui.mouse_focus = nullptr;
gui.forced_mouse_focus = false;
- gui.mouse_focus_mask = MouseButton::NONE;
+ gui.mouse_focus_mask.clear();
for (int i = 0; i < 3; i++) {
if ((int)mask & (1 << i)) {
@@ -2277,6 +2296,7 @@ void Viewport::_drop_mouse_focus() {
mb->set_global_position(c->get_local_mouse_position());
mb->set_button_index(MouseButton(i + 1));
mb->set_pressed(false);
+ mb->set_device(InputEvent::DEVICE_ID_INTERNAL);
c->_call_gui_input(mb);
}
}
@@ -2375,7 +2395,7 @@ void Viewport::_post_gui_grab_click_focus() {
return;
}
- MouseButton mask = gui.mouse_focus_mask;
+ BitField<MouseButtonMask> mask = gui.mouse_focus_mask;
Point2 click = gui.mouse_focus->get_global_transform_with_canvas().affine_inverse().xform(gui.last_mouse_pos);
for (int i = 0; i < 3; i++) {
@@ -2388,12 +2408,12 @@ void Viewport::_post_gui_grab_click_focus() {
mb->set_position(click);
mb->set_button_index(MouseButton(i + 1));
mb->set_pressed(false);
+ mb->set_device(InputEvent::DEVICE_ID_INTERNAL);
gui.mouse_focus->_call_gui_input(mb);
}
}
gui.mouse_focus = focus_grabber;
- gui.focus_inv_xform = gui.mouse_focus->get_global_transform_with_canvas().affine_inverse();
click = gui.mouse_focus->get_global_transform_with_canvas().affine_inverse().xform(gui.last_mouse_pos);
for (int i = 0; i < 3; i++) {
@@ -2406,6 +2426,7 @@ void Viewport::_post_gui_grab_click_focus() {
mb->set_position(click);
mb->set_button_index(MouseButton(i + 1));
mb->set_pressed(true);
+ mb->set_device(InputEvent::DEVICE_ID_INTERNAL);
MessageQueue::get_singleton()->push_callable(callable_mp(gui.mouse_focus, &Control::_call_gui_input), mb);
}
}
@@ -2541,20 +2562,14 @@ bool Viewport::_sub_windows_forward_input(const Ref<InputEvent> &p_event) {
if (gui.subwindow_drag == SUB_WINDOW_DRAG_RESIZE) {
Vector2i diff = mm->get_position() - gui.subwindow_drag_from;
Size2i min_size = gui.subwindow_focused->get_min_size();
+ Size2i min_size_clamped = gui.subwindow_focused->get_clamped_minimum_size();
- Size2i min_size_adjusted = min_size;
- if (gui.subwindow_focused->is_wrapping_controls()) {
- Size2i cms = gui.subwindow_focused->get_contents_minimum_size();
- min_size_adjusted.x = MAX(cms.x, min_size.x);
- min_size_adjusted.y = MAX(cms.y, min_size.y);
- }
-
- min_size_adjusted.x = MAX(min_size_adjusted.x, 1);
- min_size_adjusted.y = MAX(min_size_adjusted.y, 1);
+ min_size_clamped.x = MAX(min_size_clamped.x, 1);
+ min_size_clamped.y = MAX(min_size_clamped.y, 1);
Rect2i r = gui.subwindow_resize_from_rect;
- Size2i limit = r.size - min_size_adjusted;
+ Size2i limit = r.size - min_size_clamped;
switch (gui.subwindow_resize_mode) {
case SUB_WINDOW_RESIZE_TOP_LEFT: {
@@ -2872,8 +2887,16 @@ bool Viewport::get_physics_object_picking() {
return physics_object_picking;
}
+void Viewport::set_physics_object_picking_sort(bool p_enable) {
+ physics_object_picking_sort = p_enable;
+}
+
+bool Viewport::get_physics_object_picking_sort() {
+ return physics_object_picking_sort;
+}
+
Vector2 Viewport::get_camera_coords(const Vector2 &p_viewport_coords) const {
- Transform2D xf = get_final_transform();
+ Transform2D xf = stretch_transform * global_canvas_transform;
return xf.xform(p_viewport_coords);
}
@@ -3240,7 +3263,7 @@ void Viewport::pass_mouse_focus_to(Viewport *p_viewport, Control *p_control) {
gui.mouse_focus = nullptr;
gui.forced_mouse_focus = false;
- gui.mouse_focus_mask = MouseButton::NONE;
+ gui.mouse_focus_mask.clear();
}
}
@@ -3265,7 +3288,11 @@ Viewport::SDFScale Viewport::get_sdf_scale() const {
}
Transform2D Viewport::get_screen_transform() const {
- return _get_input_pre_xform().affine_inverse() * get_final_transform();
+ return get_screen_transform_internal();
+}
+
+Transform2D Viewport::get_screen_transform_internal(bool p_absolute_position) const {
+ return get_final_transform();
}
void Viewport::set_canvas_cull_mask(uint32_t p_canvas_cull_mask) {
@@ -3806,6 +3833,8 @@ void Viewport::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_physics_object_picking", "enable"), &Viewport::set_physics_object_picking);
ClassDB::bind_method(D_METHOD("get_physics_object_picking"), &Viewport::get_physics_object_picking);
+ ClassDB::bind_method(D_METHOD("set_physics_object_picking_sort", "enable"), &Viewport::set_physics_object_picking_sort);
+ ClassDB::bind_method(D_METHOD("get_physics_object_picking_sort"), &Viewport::get_physics_object_picking_sort);
ClassDB::bind_method(D_METHOD("get_viewport_rid"), &Viewport::get_viewport_rid);
ClassDB::bind_method(D_METHOD("push_text_input", "text"), &Viewport::push_text_input);
@@ -3936,7 +3965,7 @@ void Viewport::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_debanding"), "set_use_debanding", "is_using_debanding");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_occlusion_culling"), "set_use_occlusion_culling", "is_using_occlusion_culling");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "mesh_lod_threshold", PROPERTY_HINT_RANGE, "0,1024,0.1"), "set_mesh_lod_threshold", "get_mesh_lod_threshold");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "debug_draw", PROPERTY_HINT_ENUM, "Disabled,Unshaded,Overdraw,Wireframe"), "set_debug_draw", "get_debug_draw");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "debug_draw", PROPERTY_HINT_ENUM, "Disabled,Unshaded,Lighting,Overdraw,Wireframe"), "set_debug_draw", "get_debug_draw");
#ifndef _3D_DISABLED
ADD_GROUP("Scaling 3D", "");
ADD_PROPERTY(PropertyInfo(Variant::INT, "scaling_3d_mode", PROPERTY_HINT_ENUM, "Bilinear (Fastest),FSR 1.0 (Fast)"), "set_scaling_3d_mode", "get_scaling_3d_mode");
@@ -3957,6 +3986,7 @@ void Viewport::_bind_methods() {
#endif
ADD_GROUP("Physics", "physics_");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "physics_object_picking"), "set_physics_object_picking", "get_physics_object_picking");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "physics_object_picking_sort"), "set_physics_object_picking_sort", "get_physics_object_picking_sort");
ADD_GROUP("GUI", "gui_");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "gui_disable_input"), "set_disable_input", "is_input_disabled");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "gui_snap_controls_to_pixels"), "set_snap_controls_to_pixels", "is_snap_controls_to_pixels_enabled");
@@ -4104,8 +4134,7 @@ Viewport::Viewport() {
unhandled_key_input_group = "_vp_unhandled_key_input" + id;
// Window tooltip.
- gui.tooltip_delay = GLOBAL_DEF("gui/timers/tooltip_delay_sec", 0.5);
- ProjectSettings::get_singleton()->set_custom_property_info("gui/timers/tooltip_delay_sec", PropertyInfo(Variant::FLOAT, "gui/timers/tooltip_delay_sec", PROPERTY_HINT_RANGE, "0,5,0.01,or_greater")); // No negative numbers
+ gui.tooltip_delay = GLOBAL_DEF(PropertyInfo(Variant::FLOAT, "gui/timers/tooltip_delay_sec", PROPERTY_HINT_RANGE, "0,5,0.01,or_greater"), 0.5);
#ifndef _3D_DISABLED
set_scaling_3d_mode((Viewport::Scaling3DMode)(int)GLOBAL_GET("rendering/scaling_3d/mode"));
@@ -4129,9 +4158,26 @@ Viewport::~Viewport() {
/////////////////////////////////
void SubViewport::set_size(const Size2i &p_size) {
- _set_size(p_size, _get_size_2d_override(), Rect2i(), _stretch_transform(), true);
+ _internal_set_size(p_size);
+}
+void SubViewport::set_size_force(const Size2i &p_size) {
+ // Use only for setting the size from the parent SubViewportContainer with enabled stretch mode.
+ // Don't expose function to scripting.
+ _internal_set_size(p_size, true);
+}
+
+void SubViewport::_internal_set_size(const Size2i &p_size, bool p_force) {
SubViewportContainer *c = Object::cast_to<SubViewportContainer>(get_parent());
+ if (!p_force && c && c->is_stretch_enabled()) {
+#ifdef DEBUG_ENABLED
+ WARN_PRINT("Can't change the size of a `SubViewport` with a `SubViewportContainer` parent that has `stretch` enabled. Set `SubViewportContainer.stretch` to `false` to allow changing the size manually.");
+#endif // DEBUG_ENABLED
+ return;
+ }
+
+ _set_size(p_size, _get_size_2d_override(), true);
+
if (c) {
c->update_minimum_size();
}
@@ -4142,7 +4188,7 @@ Size2i SubViewport::get_size() const {
}
void SubViewport::set_size_2d_override(const Size2i &p_size) {
- _set_size(_get_size(), p_size, Rect2i(), _stretch_transform(), true);
+ _set_size(_get_size(), p_size, true);
}
Size2i SubViewport::get_size_2d_override() const {
@@ -4155,7 +4201,7 @@ void SubViewport::set_size_2d_override_stretch(bool p_enable) {
}
size_2d_override_stretch = p_enable;
- _set_size(_get_size(), _get_size_2d_override(), Rect2i(), _stretch_transform(), true);
+ _set_size(_get_size(), _get_size_2d_override(), true);
}
bool SubViewport::is_size_2d_override_stretch_enabled() const {
@@ -4184,29 +4230,33 @@ DisplayServer::WindowID SubViewport::get_window_id() const {
return DisplayServer::INVALID_WINDOW_ID;
}
-Transform2D SubViewport::_stretch_transform() {
- 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);
- transform.scale(scale);
- }
-
- return transform;
-}
-
-Transform2D SubViewport::get_screen_transform() const {
+Transform2D SubViewport::get_screen_transform_internal(bool p_absolute_position) const {
Transform2D container_transform;
SubViewportContainer *c = Object::cast_to<SubViewportContainer>(get_parent());
if (c) {
if (c->is_stretch_enabled()) {
container_transform.scale(Vector2(c->get_stretch_shrink(), c->get_stretch_shrink()));
}
- container_transform = c->get_viewport()->get_screen_transform() * c->get_global_transform_with_canvas() * container_transform;
+ container_transform = c->get_viewport()->get_screen_transform_internal(p_absolute_position) * c->get_global_transform_with_canvas() * container_transform;
} else {
WARN_PRINT_ONCE("SubViewport is not a child of a SubViewportContainer. get_screen_transform doesn't return the actual screen position.");
}
- return container_transform * Viewport::get_screen_transform();
+ return container_transform * get_final_transform();
+}
+
+Transform2D SubViewport::get_popup_base_transform() const {
+ if (is_embedding_subwindows()) {
+ return Transform2D();
+ }
+ SubViewportContainer *c = Object::cast_to<SubViewportContainer>(get_parent());
+ if (!c) {
+ return get_final_transform();
+ }
+ Transform2D container_transform;
+ if (c->is_stretch_enabled()) {
+ container_transform.scale(Vector2(c->get_stretch_shrink(), c->get_stretch_shrink()));
+ }
+ return c->get_screen_transform() * container_transform * get_final_transform();
}
void SubViewport::_notification(int p_what) {
diff --git a/scene/main/viewport.h b/scene/main/viewport.h
index ca6f3163df..055fad5369 100644
--- a/scene/main/viewport.h
+++ b/scene/main/viewport.h
@@ -246,6 +246,7 @@ private:
bool snap_2d_vertices_to_pixel = false;
bool physics_object_picking = false;
+ bool physics_object_picking_sort = false;
List<Ref<InputEvent>> physics_picking_events;
ObjectID physics_object_capture;
ObjectID physics_object_over;
@@ -259,7 +260,7 @@ private:
bool control = false;
bool shift = false;
bool meta = false;
- MouseButton mouse_mask = MouseButton::NONE;
+ BitField<MouseButtonMask> mouse_mask;
} physics_last_mouse_state;
@@ -275,7 +276,6 @@ private:
Ref<World2D> world_2d;
- Rect2i to_screen_rect;
StringName input_group;
StringName gui_input_group;
StringName shortcut_input_group;
@@ -358,7 +358,7 @@ private:
Control *mouse_focus = nullptr;
Control *last_mouse_focus = nullptr;
Control *mouse_click_grabber = nullptr;
- MouseButton mouse_focus_mask = MouseButton::NONE;
+ BitField<MouseButtonMask> mouse_focus_mask;
Control *key_focus = nullptr;
Control *mouse_over = nullptr;
Control *drag_mouse_over = nullptr;
@@ -374,7 +374,6 @@ private:
ObjectID drag_preview_id;
Ref<SceneTreeTimer> tooltip_timer;
double tooltip_delay = 0.0;
- Transform2D focus_inv_xform;
bool roots_order_dirty = false;
List<Control *> roots;
int canvas_sort_index = 0; //for sorting items with canvas as root
@@ -403,14 +402,12 @@ private:
void _gui_call_notification(Control *p_control, int p_what);
void _gui_sort_roots();
- Control *_gui_find_control_at_pos(CanvasItem *p_node, const Point2 &p_global, const Transform2D &p_xform, Transform2D &r_inv_xform);
+ Control *_gui_find_control_at_pos(CanvasItem *p_node, const Point2 &p_global, const Transform2D &p_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;
-
Ref<InputEvent> _make_input_local(const Ref<InputEvent> &ev);
friend class Control;
@@ -472,7 +469,7 @@ private:
uint64_t event_count = 0;
protected:
- void _set_size(const Size2i &p_size, const Size2i &p_size_2d_override, const Rect2i &p_to_screen_rect, const Transform2D &p_stretch_transform, bool p_allocated);
+ void _set_size(const Size2i &p_size, const Size2i &p_size_2d_override, bool p_allocated);
Size2i _get_size() const;
Size2i _get_size_2d_override() const;
@@ -511,7 +508,8 @@ public:
void set_global_canvas_transform(const Transform2D &p_transform);
Transform2D get_global_canvas_transform() const;
- Transform2D get_final_transform() const;
+ virtual Transform2D get_final_transform() const;
+ void assign_next_enabled_camera_2d(const StringName &p_camera_group);
void gui_set_root_order_dirty();
@@ -577,6 +575,8 @@ public:
void set_physics_object_picking(bool p_enable);
bool get_physics_object_picking();
+ void set_physics_object_picking_sort(bool p_enable);
+ bool get_physics_object_picking_sort();
Variant gui_get_drag_data() const;
@@ -649,7 +649,11 @@ public:
void set_canvas_cull_mask_bit(uint32_t p_layer, bool p_enable);
bool get_canvas_cull_mask_bit(uint32_t p_layer) const;
- virtual Transform2D get_screen_transform() const;
+ virtual bool is_size_2d_override_stretch_enabled() const { return true; }
+
+ Transform2D get_screen_transform() const;
+ virtual Transform2D get_screen_transform_internal(bool p_absolute_position = false) const;
+ virtual Transform2D get_popup_base_transform() const { return Transform2D(); }
#ifndef _3D_DISABLED
bool use_xr = false;
@@ -753,21 +757,23 @@ private:
ClearMode clear_mode = CLEAR_MODE_ALWAYS;
bool size_2d_override_stretch = false;
+ void _internal_set_size(const Size2i &p_size, bool p_force = false);
+
protected:
static void _bind_methods();
virtual DisplayServer::WindowID get_window_id() const override;
- Transform2D _stretch_transform();
void _notification(int p_what);
public:
void set_size(const Size2i &p_size);
Size2i get_size() const;
+ void set_size_force(const Size2i &p_size);
void set_size_2d_override(const Size2i &p_size);
Size2i get_size_2d_override() const;
void set_size_2d_override_stretch(bool p_enable);
- bool is_size_2d_override_stretch_enabled() const;
+ bool is_size_2d_override_stretch_enabled() const override;
void set_update_mode(UpdateMode p_mode);
UpdateMode get_update_mode() const;
@@ -775,7 +781,8 @@ public:
void set_clear_mode(ClearMode p_mode);
ClearMode get_clear_mode() const;
- virtual Transform2D get_screen_transform() const override;
+ virtual Transform2D get_screen_transform_internal(bool p_absolute_position = false) const override;
+ virtual Transform2D get_popup_base_transform() const override;
SubViewport();
~SubViewport();
diff --git a/scene/main/window.cpp b/scene/main/window.cpp
index d3fcf29927..771e074d48 100644
--- a/scene/main/window.cpp
+++ b/scene/main/window.cpp
@@ -223,6 +223,14 @@ void Window::_get_property_list(List<PropertyInfo> *p_list) const {
}
void Window::_validate_property(PropertyInfo &p_property) const {
+ if (p_property.name == "position" && initial_position != WINDOW_INITIAL_POSITION_ABSOLUTE) {
+ p_property.usage = PROPERTY_USAGE_NONE;
+ }
+
+ if (p_property.name == "current_screen" && initial_position != WINDOW_INITIAL_POSITION_CENTER_OTHER_SCREEN) {
+ p_property.usage = PROPERTY_USAGE_NONE;
+ }
+
if (p_property.name == "theme_type_variation") {
List<StringName> names;
@@ -275,6 +283,15 @@ String Window::get_title() const {
return title;
}
+void Window::set_initial_position(Window::WindowInitialPosition p_initial_position) {
+ initial_position = p_initial_position;
+ notify_property_list_changed();
+}
+
+Window::WindowInitialPosition Window::get_initial_position() const {
+ return initial_position;
+}
+
void Window::set_current_screen(int p_screen) {
current_screen = p_screen;
if (window_id == DisplayServer::INVALID_WINDOW_ID) {
@@ -332,8 +349,30 @@ Size2i Window::get_size_with_decorations() const {
return size;
}
+Size2i Window::_clamp_limit_size(const Size2i &p_limit_size) {
+ // Force window limits to respect size limitations of rendering server.
+ Size2i max_window_size = RS::get_singleton()->get_maximum_viewport_size();
+ if (max_window_size != Size2i()) {
+ return p_limit_size.clamp(Vector2i(), max_window_size);
+ } else {
+ return p_limit_size.max(Vector2i());
+ }
+}
+
+void Window::_validate_limit_size() {
+ // When max_size is invalid, max_size_used falls back to respect size limitations of rendering server.
+ bool max_size_valid = (max_size.x > 0 || max_size.y > 0) && max_size.x >= min_size.x && max_size.y >= min_size.y;
+ max_size_used = max_size_valid ? max_size : RS::get_singleton()->get_maximum_viewport_size();
+}
+
void Window::set_max_size(const Size2i &p_max_size) {
- max_size = p_max_size;
+ Size2i max_size_clamped = _clamp_limit_size(p_max_size);
+ if (max_size == max_size_clamped) {
+ return;
+ }
+ max_size = max_size_clamped;
+
+ _validate_limit_size();
_update_window_size();
}
@@ -342,7 +381,13 @@ Size2i Window::get_max_size() const {
}
void Window::set_min_size(const Size2i &p_min_size) {
- min_size = p_min_size;
+ Size2i min_size_clamped = _clamp_limit_size(p_min_size);
+ if (min_size == min_size_clamped) {
+ return;
+ }
+ min_size = min_size_clamped;
+
+ _validate_limit_size();
_update_window_size();
}
@@ -462,10 +507,21 @@ void Window::_make_window() {
}
DisplayServer::VSyncMode vsync_mode = DisplayServer::get_singleton()->window_get_vsync_mode(DisplayServer::MAIN_WINDOW_ID);
- window_id = DisplayServer::get_singleton()->create_sub_window(DisplayServer::WindowMode(mode), vsync_mode, f, Rect2i(position, size), current_screen);
+ Rect2i window_rect;
+ if (initial_position == WINDOW_INITIAL_POSITION_ABSOLUTE) {
+ window_rect = Rect2i(position, size);
+ } else if (initial_position == WINDOW_INITIAL_POSITION_CENTER_PRIMARY_SCREEN) {
+ window_rect = Rect2i(DisplayServer::get_singleton()->screen_get_position(DisplayServer::SCREEN_PRIMARY) + (DisplayServer::get_singleton()->screen_get_size(DisplayServer::SCREEN_PRIMARY) - size) / 2, size);
+ } else if (initial_position == WINDOW_INITIAL_POSITION_CENTER_MAIN_WINDOW_SCREEN) {
+ window_rect = Rect2i(DisplayServer::get_singleton()->screen_get_position(DisplayServer::SCREEN_OF_MAIN_WINDOW) + (DisplayServer::get_singleton()->screen_get_size(DisplayServer::SCREEN_OF_MAIN_WINDOW) - size) / 2, size);
+ } else if (initial_position == WINDOW_INITIAL_POSITION_CENTER_OTHER_SCREEN) {
+ window_rect = Rect2i(DisplayServer::get_singleton()->screen_get_position(current_screen) + (DisplayServer::get_singleton()->screen_get_size(current_screen) - size) / 2, size);
+ }
+ window_id = DisplayServer::get_singleton()->create_sub_window(DisplayServer::WindowMode(mode), vsync_mode, f, window_rect);
ERR_FAIL_COND(window_id == DisplayServer::INVALID_WINDOW_ID);
DisplayServer::get_singleton()->window_set_max_size(Size2i(), window_id);
DisplayServer::get_singleton()->window_set_min_size(Size2i(), window_id);
+ DisplayServer::get_singleton()->window_set_mouse_passthrough(mpath, window_id);
String tr_title = atr(title);
#ifdef DEBUG_ENABLED
if (window_id == DisplayServer::MAIN_WINDOW_ID) {
@@ -619,6 +675,7 @@ void Window::update_mouse_cursor_shape() {
mm.instantiate();
mm->set_position(pos);
mm->set_global_position(xform.xform(pos));
+ mm->set_device(InputEvent::DEVICE_ID_INTERNAL);
push_input(mm);
}
@@ -635,18 +692,18 @@ void Window::set_visible(bool p_visible) {
return;
}
- visible = p_visible;
-
if (!is_inside_tree()) {
+ visible = p_visible;
return;
}
- if (updating_child_controls) {
- _update_child_controls();
- }
-
ERR_FAIL_COND_MSG(get_parent() == nullptr, "Can't change visibility of main window.");
+ visible = p_visible;
+
+ // Stop any queued resizing, as the window will be resized right now.
+ updating_child_controls = false;
+
Viewport *embedder_vp = _get_embedder();
if (!embedder_vp) {
@@ -804,49 +861,35 @@ bool Window::is_visible() const {
return visible;
}
-void Window::_update_window_size() {
- // Force window to respect size limitations of rendering server
- RenderingServer *rendering_server = RenderingServer::get_singleton();
- if (rendering_server) {
- Size2i max_window_size = rendering_server->get_maximum_viewport_size();
+Size2i Window::_clamp_window_size(const Size2i &p_size) {
+ Size2i window_size_clamped = p_size;
+ Size2 minsize = get_clamped_minimum_size();
+ window_size_clamped = window_size_clamped.max(minsize);
- if (max_window_size != Size2i()) {
- size = size.min(max_window_size);
- min_size = min_size.min(max_window_size);
- max_size = max_size.min(max_window_size);
- }
+ if (max_size_used != Size2i()) {
+ window_size_clamped = window_size_clamped.min(max_size_used);
}
- Size2i size_limit;
- if (wrap_controls) {
- size_limit = get_contents_minimum_size();
- }
+ return window_size_clamped;
+}
- size_limit.x = MAX(size_limit.x, min_size.x);
- size_limit.y = MAX(size_limit.y, min_size.y);
+void Window::_update_window_size() {
+ Size2i size_limit = get_clamped_minimum_size();
- size.x = MAX(size_limit.x, size.x);
- size.y = MAX(size_limit.y, size.y);
+ size = size.max(size_limit);
bool reset_min_first = false;
- bool max_size_valid = false;
- if ((max_size.x > 0 || max_size.y > 0) && (max_size.x >= min_size.x && max_size.y >= min_size.y)) {
- max_size_valid = true;
+ if (max_size_used != Size2i()) {
+ // Force window size to respect size limitations of max_size_used.
+ size = size.min(max_size_used);
- if (size.x > max_size.x) {
- size.x = max_size.x;
- }
- if (size_limit.x > max_size.x) {
- size_limit.x = max_size.x;
+ if (size_limit.x > max_size_used.x) {
+ size_limit.x = max_size_used.x;
reset_min_first = true;
}
-
- if (size.y > max_size.y) {
- size.y = max_size.y;
- }
- if (size_limit.y > max_size.y) {
- size_limit.y = max_size.y;
+ if (size_limit.y > max_size_used.y) {
+ size_limit.y = max_size_used.y;
reset_min_first = true;
}
}
@@ -862,7 +905,7 @@ void Window::_update_window_size() {
DisplayServer::get_singleton()->window_set_min_size(Size2i(), window_id);
}
- DisplayServer::get_singleton()->window_set_max_size(max_size_valid ? max_size : Size2i(), window_id);
+ DisplayServer::get_singleton()->window_set_max_size(max_size_used, window_id);
DisplayServer::get_singleton()->window_set_min_size(size_limit, window_id);
DisplayServer::get_singleton()->window_set_size(size, window_id);
}
@@ -877,16 +920,13 @@ void Window::_update_viewport_size() {
Size2i final_size;
Size2i final_size_override;
Rect2i attach_to_screen_rect(Point2i(), size);
- Transform2D stretch_transform_new;
float font_oversampling = 1.0;
+ window_transform = Transform2D();
if (content_scale_mode == CONTENT_SCALE_MODE_DISABLED || content_scale_size.x == 0 || content_scale_size.y == 0) {
font_oversampling = content_scale_factor;
final_size = size;
final_size_override = Size2(size) / content_scale_factor;
-
- stretch_transform_new = Transform2D();
- stretch_transform_new.scale(Size2(content_scale_factor, content_scale_factor));
} else {
//actual screen video mode
Size2 video_mode = size;
@@ -962,20 +1002,24 @@ void Window::_update_viewport_size() {
attach_to_screen_rect = Rect2(margin, screen_size);
font_oversampling = (screen_size.x / viewport_size.x) * content_scale_factor;
- Size2 scale = Vector2(screen_size) / Vector2(final_size_override);
- stretch_transform_new.scale(scale);
-
+ window_transform.translate_local(margin);
} break;
case CONTENT_SCALE_MODE_VIEWPORT: {
final_size = (viewport_size / content_scale_factor).floor();
attach_to_screen_rect = Rect2(margin, screen_size);
+ window_transform.translate_local(margin);
+ if (final_size.x != 0 && final_size.y != 0) {
+ Transform2D scale_transform;
+ scale_transform.scale(Vector2(attach_to_screen_rect.size) / Vector2(final_size));
+ window_transform *= scale_transform;
+ }
} break;
}
}
bool allocate = is_inside_tree() && visible && (window_id != DisplayServer::INVALID_WINDOW_ID || embedder != nullptr);
- _set_size(final_size, final_size_override, attach_to_screen_rect, stretch_transform_new, allocate);
+ _set_size(final_size, final_size_override, allocate);
if (window_id != DisplayServer::INVALID_WINDOW_ID) {
RenderingServer::get_singleton()->viewport_attach_to_screen(get_viewport_rid(), attach_to_screen_rect, window_id);
@@ -1102,6 +1146,7 @@ void Window::_notification(int p_what) {
case NOTIFICATION_READY: {
if (wrap_controls) {
+ // Finish any resizing immediately so it doesn't interfere on stuff overriding _ready().
_update_child_controls();
}
} break;
@@ -1110,9 +1155,7 @@ void Window::_notification(int p_what) {
_invalidate_theme_cache();
_update_theme_item_cache();
- if (embedder) {
- embedder->_sub_window_update(this);
- } else if (window_id != DisplayServer::INVALID_WINDOW_ID) {
+ if (!embedder && window_id != DisplayServer::INVALID_WINDOW_ID) {
String tr_title = atr(title);
#ifdef DEBUG_ENABLED
if (window_id == DisplayServer::MAIN_WINDOW_ID) {
@@ -1124,8 +1167,6 @@ void Window::_notification(int p_what) {
#endif
DisplayServer::get_singleton()->window_set_title(tr_title, window_id);
}
-
- child_controls_changed();
} break;
case NOTIFICATION_EXIT_TREE: {
@@ -1212,10 +1253,27 @@ DisplayServer::WindowID Window::get_window_id() const {
return window_id;
}
+void Window::set_mouse_passthrough_polygon(const Vector<Vector2> &p_region) {
+ mpath = p_region;
+ if (window_id == DisplayServer::INVALID_WINDOW_ID) {
+ return;
+ }
+ DisplayServer::get_singleton()->window_set_mouse_passthrough(mpath, window_id);
+}
+
+Vector<Vector2> Window::get_mouse_passthrough_polygon() const {
+ return mpath;
+}
+
void Window::set_wrap_controls(bool p_enable) {
wrap_controls = p_enable;
- if (wrap_controls) {
- child_controls_changed();
+
+ if (!is_inside_tree()) {
+ return;
+ }
+
+ if (updating_child_controls) {
+ _update_child_controls();
} else {
_update_window_size();
}
@@ -1242,23 +1300,23 @@ Size2 Window::_get_contents_minimum_size() const {
return max;
}
-void Window::_update_child_controls() {
- if (!updating_child_controls) {
+void Window::child_controls_changed() {
+ if (!is_inside_tree() || !visible || updating_child_controls) {
return;
}
- _update_window_size();
-
- updating_child_controls = false;
+ updating_child_controls = true;
+ call_deferred(SNAME("_update_child_controls"));
}
-void Window::child_controls_changed() {
- if (!is_inside_tree() || !visible || updating_child_controls) {
+void Window::_update_child_controls() {
+ if (!updating_child_controls) {
return;
}
- updating_child_controls = true;
- call_deferred(SNAME("_update_child_controls"));
+ _update_window_size();
+
+ updating_child_controls = false;
}
bool Window::_can_consume_input_events() const {
@@ -1379,6 +1437,8 @@ void Window::popup_centered_clamped(const Size2i &p_size, float p_fallback_ratio
Rect2i popup_rect;
popup_rect.size = Vector2i(MIN(size_ratio.x, p_size.x), MIN(size_ratio.y, p_size.y));
+ popup_rect.size = _clamp_window_size(popup_rect.size);
+
if (parent_rect != Rect2()) {
popup_rect.position = parent_rect.position + (parent_rect.size - popup_rect.size) / 2;
}
@@ -1402,9 +1462,7 @@ void Window::popup_centered(const Size2i &p_minsize) {
}
Rect2i popup_rect;
- Size2 contents_minsize = _get_contents_minimum_size();
- popup_rect.size.x = MAX(p_minsize.x, contents_minsize.x);
- popup_rect.size.y = MAX(p_minsize.y, contents_minsize.y);
+ popup_rect.size = _clamp_window_size(get_size().max(p_minsize));
if (parent_rect != Rect2()) {
popup_rect.position = parent_rect.position + (parent_rect.size - popup_rect.size) / 2;
@@ -1432,6 +1490,7 @@ void Window::popup_centered_ratio(float p_ratio) {
Rect2i popup_rect;
if (parent_rect != Rect2()) {
popup_rect.size = parent_rect.size * p_ratio;
+ popup_rect.size = _clamp_window_size(popup_rect.size);
popup_rect.position = parent_rect.position + (parent_rect.size - popup_rect.size) / 2;
}
@@ -1495,6 +1554,14 @@ Size2 Window::get_contents_minimum_size() const {
return _get_contents_minimum_size();
}
+Size2 Window::get_clamped_minimum_size() const {
+ if (!wrap_controls) {
+ return min_size;
+ }
+
+ return min_size.max(get_contents_minimum_size());
+}
+
void Window::grab_focus() {
if (embedder) {
embedder->_sub_window_grab_focus(this);
@@ -1607,7 +1674,24 @@ 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();
+ if (!wrap_controls) {
+ updating_embedded_window = true;
+ call_deferred(SNAME("_update_embedded_window"));
+ } else {
+ child_controls_changed();
+ }
+}
+
+void Window::_update_embedded_window() {
+ if (!updating_embedded_window) {
+ return;
+ }
+
+ if (embedder) {
+ embedder->_sub_window_update(this);
+ };
+
+ updating_embedded_window = false;
}
void Window::set_theme_type_variation(const StringName &p_theme_type) {
@@ -2055,19 +2139,41 @@ bool Window::is_auto_translating() const {
return auto_translate;
}
-Transform2D Window::get_screen_transform() const {
+Transform2D Window::get_final_transform() const {
+ return window_transform * stretch_transform * global_canvas_transform;
+}
+
+Transform2D Window::get_screen_transform_internal(bool p_absolute_position) const {
Transform2D embedder_transform;
if (_get_embedder()) {
embedder_transform.translate_local(get_position());
- embedder_transform = _get_embedder()->get_screen_transform() * embedder_transform;
+ embedder_transform = _get_embedder()->get_screen_transform_internal(p_absolute_position) * embedder_transform;
+ } else if (p_absolute_position) {
+ embedder_transform.translate_local(get_position());
}
- return embedder_transform * Viewport::get_screen_transform();
+ return embedder_transform * get_final_transform();
+}
+
+Transform2D Window::get_popup_base_transform() const {
+ if (is_embedding_subwindows()) {
+ return Transform2D();
+ }
+ Transform2D popup_base_transform;
+ popup_base_transform.set_origin(get_position());
+ popup_base_transform *= get_final_transform();
+ if (_get_embedder()) {
+ return _get_embedder()->get_popup_base_transform() * popup_base_transform;
+ }
+ return popup_base_transform;
}
void Window::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_title", "title"), &Window::set_title);
ClassDB::bind_method(D_METHOD("get_title"), &Window::get_title);
+ ClassDB::bind_method(D_METHOD("set_initial_position", "initial_position"), &Window::set_initial_position);
+ ClassDB::bind_method(D_METHOD("get_initial_position"), &Window::get_initial_position);
+
ClassDB::bind_method(D_METHOD("set_current_screen", "index"), &Window::set_current_screen);
ClassDB::bind_method(D_METHOD("get_current_screen"), &Window::get_current_screen);
@@ -2137,11 +2243,15 @@ void Window::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_use_font_oversampling", "enable"), &Window::set_use_font_oversampling);
ClassDB::bind_method(D_METHOD("is_using_font_oversampling"), &Window::is_using_font_oversampling);
+ ClassDB::bind_method(D_METHOD("set_mouse_passthrough_polygon", "polygon"), &Window::set_mouse_passthrough_polygon);
+ ClassDB::bind_method(D_METHOD("get_mouse_passthrough_polygon"), &Window::get_mouse_passthrough_polygon);
+
ClassDB::bind_method(D_METHOD("set_wrap_controls", "enable"), &Window::set_wrap_controls);
ClassDB::bind_method(D_METHOD("is_wrapping_controls"), &Window::is_wrapping_controls);
ClassDB::bind_method(D_METHOD("child_controls_changed"), &Window::child_controls_changed);
ClassDB::bind_method(D_METHOD("_update_child_controls"), &Window::_update_child_controls);
+ ClassDB::bind_method(D_METHOD("_update_embedded_window"), &Window::_update_embedded_window);
ClassDB::bind_method(D_METHOD("set_theme", "theme"), &Window::set_theme);
ClassDB::bind_method(D_METHOD("get_theme"), &Window::get_theme);
@@ -2204,11 +2314,16 @@ void Window::_bind_methods() {
ClassDB::bind_method(D_METHOD("popup_centered", "minsize"), &Window::popup_centered, DEFVAL(Size2i()));
ClassDB::bind_method(D_METHOD("popup_centered_clamped", "minsize", "fallback_ratio"), &Window::popup_centered_clamped, DEFVAL(Size2i()), DEFVAL(0.75));
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "initial_position", PROPERTY_HINT_ENUM, "Absolute,Primary Screen Center,Main Window Screen Center,Other Screen Center"), "set_initial_position", "get_initial_position");
ADD_PROPERTY(PropertyInfo(Variant::STRING, "title"), "set_title", "get_title");
ADD_PROPERTY(PropertyInfo(Variant::VECTOR2I, "position", PROPERTY_HINT_NONE, "suffix:px"), "set_position", "get_position");
ADD_PROPERTY(PropertyInfo(Variant::VECTOR2I, "size", PROPERTY_HINT_NONE, "suffix:px"), "set_size", "get_size");
ADD_PROPERTY(PropertyInfo(Variant::INT, "mode", PROPERTY_HINT_ENUM, "Windowed,Minimized,Maximized,Fullscreen"), "set_mode", "get_mode");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "current_screen"), "set_current_screen", "get_current_screen");
+
+ // Keep the enum values in sync with the `DisplayServer::SCREEN_` enum.
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "current_screen", PROPERTY_HINT_RANGE, "0,64,1,or_greater"), "set_current_screen", "get_current_screen");
+
+ ADD_PROPERTY(PropertyInfo(Variant::PACKED_VECTOR2_ARRAY, "mouse_passthrough_polygon"), "set_mouse_passthrough_polygon", "get_mouse_passthrough_polygon");
ADD_GROUP("Flags", "");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "visible"), "set_visible", "is_visible");
@@ -2222,6 +2337,7 @@ void Window::_bind_methods() {
ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "unfocusable"), "set_flag", "get_flag", FLAG_NO_FOCUS);
ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "popup_window"), "set_flag", "get_flag", FLAG_POPUP);
ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "extend_to_title"), "set_flag", "get_flag", FLAG_EXTEND_TO_TITLE);
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "mouse_passthrough"), "set_flag", "get_flag", FLAG_MOUSE_PASSTHROUGH);
ADD_GROUP("Limits", "");
ADD_PROPERTY(PropertyInfo(Variant::VECTOR2I, "min_size", PROPERTY_HINT_NONE, "suffix:px"), "set_min_size", "get_min_size");
@@ -2251,6 +2367,7 @@ void Window::_bind_methods() {
ADD_SIGNAL(MethodInfo("visibility_changed"));
ADD_SIGNAL(MethodInfo("about_to_popup"));
ADD_SIGNAL(MethodInfo("theme_changed"));
+ ADD_SIGNAL(MethodInfo("dpi_changed"));
ADD_SIGNAL(MethodInfo("titlebar_changed"));
BIND_CONSTANT(NOTIFICATION_VISIBILITY_CHANGED);
@@ -2269,6 +2386,7 @@ void Window::_bind_methods() {
BIND_ENUM_CONSTANT(FLAG_NO_FOCUS);
BIND_ENUM_CONSTANT(FLAG_POPUP);
BIND_ENUM_CONSTANT(FLAG_EXTEND_TO_TITLE);
+ BIND_ENUM_CONSTANT(FLAG_MOUSE_PASSTHROUGH);
BIND_ENUM_CONSTANT(FLAG_MAX);
BIND_ENUM_CONSTANT(CONTENT_SCALE_MODE_DISABLED);
@@ -2285,12 +2403,18 @@ void Window::_bind_methods() {
BIND_ENUM_CONSTANT(LAYOUT_DIRECTION_LOCALE);
BIND_ENUM_CONSTANT(LAYOUT_DIRECTION_LTR);
BIND_ENUM_CONSTANT(LAYOUT_DIRECTION_RTL);
+
+ BIND_ENUM_CONSTANT(WINDOW_INITIAL_POSITION_ABSOLUTE);
+ BIND_ENUM_CONSTANT(WINDOW_INITIAL_POSITION_CENTER_PRIMARY_SCREEN);
+ BIND_ENUM_CONSTANT(WINDOW_INITIAL_POSITION_CENTER_MAIN_WINDOW_SCREEN);
+ BIND_ENUM_CONSTANT(WINDOW_INITIAL_POSITION_CENTER_OTHER_SCREEN);
}
Window::Window() {
RenderingServer *rendering_server = RenderingServer::get_singleton();
if (rendering_server) {
max_size = rendering_server->get_maximum_viewport_size();
+ max_size_used = max_size; // Update max_size_used.
}
theme_owner = memnew(ThemeOwner);
diff --git a/scene/main/window.h b/scene/main/window.h
index 9a16a24e57..5359c37e9a 100644
--- a/scene/main/window.h
+++ b/scene/main/window.h
@@ -59,6 +59,7 @@ public:
FLAG_NO_FOCUS = DisplayServer::WINDOW_FLAG_NO_FOCUS,
FLAG_POPUP = DisplayServer::WINDOW_FLAG_POPUP,
FLAG_EXTEND_TO_TITLE = DisplayServer::WINDOW_FLAG_EXTEND_TO_TITLE,
+ FLAG_MOUSE_PASSTHROUGH = DisplayServer::WINDOW_FLAG_MOUSE_PASSTHROUGH,
FLAG_MAX = DisplayServer::WINDOW_FLAG_MAX,
};
@@ -87,6 +88,13 @@ public:
DEFAULT_WINDOW_SIZE = 100,
};
+ enum WindowInitialPosition {
+ WINDOW_INITIAL_POSITION_ABSOLUTE,
+ WINDOW_INITIAL_POSITION_CENTER_PRIMARY_SCREEN,
+ WINDOW_INITIAL_POSITION_CENTER_MAIN_WINDOW_SCREEN,
+ WINDOW_INITIAL_POSITION_CENTER_OTHER_SCREEN,
+ };
+
private:
DisplayServer::WindowID window_id = DisplayServer::INVALID_WINDOW_ID;
@@ -96,16 +104,19 @@ private:
mutable Size2i size = Size2i(DEFAULT_WINDOW_SIZE, DEFAULT_WINDOW_SIZE);
mutable Size2i min_size;
mutable Size2i max_size;
+ mutable Vector<Vector2> mpath;
mutable Mode mode = MODE_WINDOWED;
mutable bool flags[FLAG_MAX] = {};
bool visible = true;
bool focused = false;
+ WindowInitialPosition initial_position = WINDOW_INITIAL_POSITION_ABSOLUTE;
bool use_font_oversampling = false;
bool transient = false;
bool exclusive = false;
bool wrap_controls = false;
bool updating_child_controls = false;
+ bool updating_embedded_window = false;
bool clamp_to_embedder = false;
LayoutDirection layout_dir = LAYOUT_DIRECTION_INHERITED;
@@ -113,6 +124,7 @@ private:
bool auto_translate = true;
void _update_child_controls();
+ void _update_embedded_window();
Size2i content_scale_size;
ContentScaleMode content_scale_mode = CONTENT_SCALE_MODE_DISABLED;
@@ -123,6 +135,11 @@ private:
void _clear_window();
void _update_from_window();
+ Size2i max_size_used;
+
+ Size2i _clamp_limit_size(const Size2i &p_limit_size);
+ Size2i _clamp_window_size(const Size2i &p_size);
+ void _validate_limit_size();
void _update_viewport_size();
void _update_window_size();
@@ -161,6 +178,8 @@ private:
Viewport *embedder = nullptr;
+ Transform2D window_transform;
+
friend class Viewport; //friend back, can call the methods below
void _window_input(const Ref<InputEvent> &p_ev);
@@ -201,6 +220,9 @@ public:
void set_title(const String &p_title);
String get_title() const;
+ void set_initial_position(WindowInitialPosition p_initial_position);
+ WindowInitialPosition get_initial_position() const;
+
void set_current_screen(int p_screen);
int get_current_screen() const;
@@ -272,10 +294,14 @@ public:
void set_use_font_oversampling(bool p_oversampling);
bool is_using_font_oversampling() const;
+ void set_mouse_passthrough_polygon(const Vector<Vector2> &p_region);
+ Vector<Vector2> get_mouse_passthrough_polygon() const;
+
void set_wrap_controls(bool p_enable);
bool is_wrapping_controls() const;
void child_controls_changed();
+ Window *get_exclusive_child() const { return exclusive_child; };
Window *get_parent_visible_window() const;
Viewport *get_parent_viewport() const;
void popup(const Rect2i &p_rect = Rect2i());
@@ -285,6 +311,7 @@ public:
void popup_centered_clamped(const Size2i &p_size = Size2i(), float p_fallback_ratio = 0.75);
Size2 get_contents_minimum_size() const;
+ Size2 get_clamped_minimum_size() const;
void grab_focus();
bool has_focus() const;
@@ -355,7 +382,9 @@ public:
//
- virtual Transform2D get_screen_transform() const override;
+ virtual Transform2D get_final_transform() const override;
+ virtual Transform2D get_screen_transform_internal(bool p_absolute_position = false) const override;
+ virtual Transform2D get_popup_base_transform() const override;
Rect2i get_parent_rect() const;
virtual DisplayServer::WindowID get_window_id() const override;
@@ -369,5 +398,6 @@ VARIANT_ENUM_CAST(Window::Flags);
VARIANT_ENUM_CAST(Window::ContentScaleMode);
VARIANT_ENUM_CAST(Window::ContentScaleAspect);
VARIANT_ENUM_CAST(Window::LayoutDirection);
+VARIANT_ENUM_CAST(Window::WindowInitialPosition);
#endif // WINDOW_H
diff --git a/scene/register_scene_types.cpp b/scene/register_scene_types.cpp
index b2d1f06da1..39fc03f9f1 100644
--- a/scene/register_scene_types.cpp
+++ b/scene/register_scene_types.cpp
@@ -140,6 +140,7 @@
#include "scene/main/viewport.h"
#include "scene/main/window.h"
#include "scene/resources/animation_library.h"
+#include "scene/resources/audio_stream_polyphonic.h"
#include "scene/resources/audio_stream_wav.h"
#include "scene/resources/bit_map.h"
#include "scene/resources/bone_map.h"
@@ -184,15 +185,7 @@
#include "scene/resources/skeleton_modification_2d_physicalbones.h"
#include "scene/resources/skeleton_modification_2d_stackholder.h"
#include "scene/resources/skeleton_modification_2d_twoboneik.h"
-#include "scene/resources/skeleton_modification_3d.h"
-#include "scene/resources/skeleton_modification_3d_ccdik.h"
-#include "scene/resources/skeleton_modification_3d_fabrik.h"
-#include "scene/resources/skeleton_modification_3d_jiggle.h"
-#include "scene/resources/skeleton_modification_3d_lookat.h"
-#include "scene/resources/skeleton_modification_3d_stackholder.h"
-#include "scene/resources/skeleton_modification_3d_twoboneik.h"
#include "scene/resources/skeleton_modification_stack_2d.h"
-#include "scene/resources/skeleton_modification_stack_3d.h"
#include "scene/resources/skeleton_profile.h"
#include "scene/resources/sky.h"
#include "scene/resources/sky_material.h"
@@ -400,6 +393,8 @@ void register_scene_types() {
GDREGISTER_CLASS(LineEdit);
GDREGISTER_CLASS(VideoStreamPlayer);
+ GDREGISTER_VIRTUAL_CLASS(VideoStreamPlayback);
+ GDREGISTER_VIRTUAL_CLASS(VideoStream);
#ifndef ADVANCED_GUI_DISABLED
GDREGISTER_CLASS(FileDialog);
@@ -602,6 +597,7 @@ void register_scene_types() {
GDREGISTER_CLASS(VisualShaderNodeComment);
GDREGISTER_CLASS(VisualShaderNodeFloatConstant);
GDREGISTER_CLASS(VisualShaderNodeIntConstant);
+ GDREGISTER_CLASS(VisualShaderNodeUIntConstant);
GDREGISTER_CLASS(VisualShaderNodeBooleanConstant);
GDREGISTER_CLASS(VisualShaderNodeColorConstant);
GDREGISTER_CLASS(VisualShaderNodeVec2Constant);
@@ -610,12 +606,14 @@ void register_scene_types() {
GDREGISTER_CLASS(VisualShaderNodeTransformConstant);
GDREGISTER_CLASS(VisualShaderNodeFloatOp);
GDREGISTER_CLASS(VisualShaderNodeIntOp);
+ GDREGISTER_CLASS(VisualShaderNodeUIntOp);
GDREGISTER_CLASS(VisualShaderNodeVectorOp);
GDREGISTER_CLASS(VisualShaderNodeColorOp);
GDREGISTER_CLASS(VisualShaderNodeTransformOp);
GDREGISTER_CLASS(VisualShaderNodeTransformVecMult);
GDREGISTER_CLASS(VisualShaderNodeFloatFunc);
GDREGISTER_CLASS(VisualShaderNodeIntFunc);
+ GDREGISTER_CLASS(VisualShaderNodeUIntFunc);
GDREGISTER_CLASS(VisualShaderNodeVectorFunc);
GDREGISTER_CLASS(VisualShaderNodeColorFunc);
GDREGISTER_CLASS(VisualShaderNodeTransformFunc);
@@ -648,6 +646,7 @@ void register_scene_types() {
GDREGISTER_CLASS(VisualShaderNodeParameterRef);
GDREGISTER_CLASS(VisualShaderNodeFloatParameter);
GDREGISTER_CLASS(VisualShaderNodeIntParameter);
+ GDREGISTER_CLASS(VisualShaderNodeUIntParameter);
GDREGISTER_CLASS(VisualShaderNodeBooleanParameter);
GDREGISTER_CLASS(VisualShaderNodeColorParameter);
GDREGISTER_CLASS(VisualShaderNodeVec2Parameter);
@@ -829,15 +828,6 @@ void register_scene_types() {
GDREGISTER_CLASS(ConvexPolygonShape3D);
GDREGISTER_CLASS(ConcavePolygonShape3D);
- 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
@@ -918,8 +908,9 @@ void register_scene_types() {
#ifndef _3D_DISABLED
GDREGISTER_CLASS(AudioStreamPlayer3D);
#endif
- GDREGISTER_ABSTRACT_CLASS(VideoStream);
GDREGISTER_CLASS(AudioStreamWAV);
+ GDREGISTER_CLASS(AudioStreamPolyphonic);
+ GDREGISTER_ABSTRACT_CLASS(AudioStreamPlaybackPolyphonic);
OS::get_singleton()->yield(); // may take time to init
diff --git a/scene/resources/animation.cpp b/scene/resources/animation.cpp
index b371266c83..bfbc92a8d4 100644
--- a/scene/resources/animation.cpp
+++ b/scene/resources/animation.cpp
@@ -127,6 +127,10 @@ bool Animation::_set(const StringName &p_name, const Variant &p_value) {
}
}
return true;
+ } else if (what == "use_blend") {
+ if (track_get_type(track) == TYPE_AUDIO) {
+ audio_track_set_use_blend(track, p_value);
+ }
} else if (what == "interp") {
track_set_interpolation_type(track, InterpolationType(p_value.operator int()));
} else if (what == "loop_wrap") {
@@ -528,7 +532,10 @@ bool Animation::_get(const StringName &p_name, Variant &r_ret) const {
}
return true;
-
+ } else if (what == "use_blend") {
+ if (track_get_type(track) == TYPE_AUDIO) {
+ r_ret = audio_track_is_use_blend(track);
+ }
} else if (what == "interp") {
r_ret = track_get_interpolation_type(track);
} else if (what == "loop_wrap") {
@@ -834,6 +841,9 @@ void Animation::_get_property_list(List<PropertyInfo> *p_list) const {
p_list->push_back(PropertyInfo(Variant::BOOL, "tracks/" + itos(i) + "/loop_wrap", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL));
p_list->push_back(PropertyInfo(Variant::ARRAY, "tracks/" + itos(i) + "/keys", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL));
}
+ if (track_get_type(i) == TYPE_AUDIO) {
+ p_list->push_back(PropertyInfo(Variant::BOOL, "tracks/" + itos(i) + "/use_blend", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL));
+ }
}
}
@@ -3581,6 +3591,27 @@ real_t Animation::audio_track_get_key_end_offset(int p_track, int p_key) const {
return at->values[p_key].value.end_offset;
}
+void Animation::audio_track_set_use_blend(int p_track, bool p_enable) {
+ ERR_FAIL_INDEX(p_track, tracks.size());
+ Track *t = tracks[p_track];
+ ERR_FAIL_COND(t->type != TYPE_AUDIO);
+
+ AudioTrack *at = static_cast<AudioTrack *>(t);
+
+ at->use_blend = p_enable;
+ emit_changed();
+}
+
+bool Animation::audio_track_is_use_blend(int p_track) const {
+ ERR_FAIL_INDEX_V(p_track, tracks.size(), false);
+ Track *t = tracks[p_track];
+ ERR_FAIL_COND_V(t->type != TYPE_AUDIO, false);
+
+ AudioTrack *at = static_cast<AudioTrack *>(t);
+
+ return at->use_blend;
+}
+
//
int Animation::animation_track_insert_key(int p_track, double p_time, const StringName &p_animation) {
@@ -3813,6 +3844,8 @@ void Animation::_bind_methods() {
ClassDB::bind_method(D_METHOD("audio_track_get_key_stream", "track_idx", "key_idx"), &Animation::audio_track_get_key_stream);
ClassDB::bind_method(D_METHOD("audio_track_get_key_start_offset", "track_idx", "key_idx"), &Animation::audio_track_get_key_start_offset);
ClassDB::bind_method(D_METHOD("audio_track_get_key_end_offset", "track_idx", "key_idx"), &Animation::audio_track_get_key_end_offset);
+ ClassDB::bind_method(D_METHOD("audio_track_set_use_blend", "track_idx", "enable"), &Animation::audio_track_set_use_blend);
+ ClassDB::bind_method(D_METHOD("audio_track_is_use_blend", "track_idx"), &Animation::audio_track_is_use_blend);
ClassDB::bind_method(D_METHOD("animation_track_insert_key", "track_idx", "time", "animation"), &Animation::animation_track_insert_key);
ClassDB::bind_method(D_METHOD("animation_track_set_key_animation", "track_idx", "key_idx", "animation"), &Animation::animation_track_set_key_animation);
@@ -4691,6 +4724,7 @@ void Animation::compress(uint32_t p_page_size, uint32_t p_fps, float p_split_tol
data_tracks.resize(tracks_to_compress.size());
time_tracks.resize(tracks_to_compress.size());
+ uint32_t needed_min_page_size = base_page_size;
for (uint32_t i = 0; i < data_tracks.size(); i++) {
data_tracks[i].split_tolerance = p_split_tolerance;
if (track_get_type(tracks_to_compress[i]) == TYPE_BLEND_SHAPE) {
@@ -4698,7 +4732,12 @@ void Animation::compress(uint32_t p_page_size, uint32_t p_fps, float p_split_tol
} else {
data_tracks[i].components = 3;
}
+ needed_min_page_size += data_tracks[i].data.size() + data_tracks[i].get_temp_packet_size();
}
+ for (uint32_t i = 0; i < time_tracks.size(); i++) {
+ needed_min_page_size += time_tracks[i].packets.size() * 4; // time packet is 32 bits
+ }
+ ERR_FAIL_COND_MSG(p_page_size < needed_min_page_size, "Cannot compress with the given page size");
while (true) {
// Begin by finding the keyframe in all tracks with the time closest to the current time
@@ -4754,17 +4793,17 @@ void Animation::compress(uint32_t p_page_size, uint32_t p_fps, float p_split_tol
// The frame has advanced, time to validate the previous frame
uint32_t current_page_size = base_page_size;
- for (uint32_t i = 0; i < data_tracks.size(); i++) {
- uint32_t track_size = data_tracks[i].data.size(); // track size
- track_size += data_tracks[i].get_temp_packet_size(); // Add the temporary data
+ for (const AnimationCompressionDataState &state : data_tracks) {
+ uint32_t track_size = state.data.size(); // track size
+ track_size += state.get_temp_packet_size(); // Add the temporary data
if (track_size > Compression::MAX_DATA_TRACK_SIZE) {
rollback = true; //track to large, time track can't point to keys any longer, because key offset is 12 bits
break;
}
current_page_size += track_size;
}
- for (uint32_t i = 0; i < time_tracks.size(); i++) {
- current_page_size += time_tracks[i].packets.size() * 4; // time packet is 32 bits
+ for (const AnimationCompressionTimeState &state : time_tracks) {
+ current_page_size += state.packets.size() * 4; // time packet is 32 bits
}
if (!rollback && current_page_size > p_page_size) {
@@ -4776,22 +4815,22 @@ void Animation::compress(uint32_t p_page_size, uint32_t p_fps, float p_split_tol
if (rollback) {
// Not valid any longer, so rollback and commit page
- for (uint32_t i = 0; i < data_tracks.size(); i++) {
- data_tracks[i].temp_packets.resize(data_tracks[i].validated_packet_count);
+ for (AnimationCompressionDataState &state : data_tracks) {
+ state.temp_packets.resize(state.validated_packet_count);
}
- for (uint32_t i = 0; i < time_tracks.size(); i++) {
- time_tracks[i].key_index = time_tracks[i].validated_key_index; //rollback key
- time_tracks[i].packets.resize(time_tracks[i].validated_packet_count);
+ for (AnimationCompressionTimeState &state : time_tracks) {
+ state.key_index = state.validated_key_index; //rollback key
+ state.packets.resize(state.validated_packet_count);
}
} else {
// All valid, so save rollback information
- for (uint32_t i = 0; i < data_tracks.size(); i++) {
- data_tracks[i].validated_packet_count = data_tracks[i].temp_packets.size();
+ for (AnimationCompressionDataState &state : data_tracks) {
+ state.validated_packet_count = state.temp_packets.size();
}
- for (uint32_t i = 0; i < time_tracks.size(); i++) {
- time_tracks[i].validated_key_index = time_tracks[i].key_index;
- time_tracks[i].validated_packet_count = time_tracks[i].packets.size();
+ for (AnimationCompressionTimeState &state : time_tracks) {
+ state.validated_key_index = state.key_index;
+ state.validated_packet_count = state.packets.size();
}
// Accept this frame as the frame being processed (as long as it exists)
@@ -4976,8 +5015,8 @@ void Animation::compress(uint32_t p_page_size, uint32_t p_fps, float p_split_tol
}
uint32_t new_size = 0;
- for (uint32_t i = 0; i < compression.pages.size(); i++) {
- new_size += compression.pages[i].data.size();
+ for (const Compression::Page &page : compression.pages) {
+ new_size += page.data.size();
}
print_line("Original size: " + itos(orig_size) + " - Compressed size: " + itos(new_size) + " " + String::num(float(new_size) / float(orig_size) * 100, 2) + "% pages: " + itos(compression.pages.size()));
@@ -5289,8 +5328,8 @@ int Animation::_get_compressed_key_count(uint32_t p_compressed_track) const {
int key_count = 0;
- for (uint32_t i = 0; i < compression.pages.size(); i++) {
- const uint8_t *page_data = compression.pages[i].data.ptr();
+ for (const Compression::Page &page : compression.pages) {
+ const uint8_t *page_data = page.data.ptr();
// Little endian assumed. No major big endian hardware exists any longer, but in case it does it will need to be supported.
const uint32_t *indices = (const uint32_t *)page_data;
const uint16_t *time_keys = (const uint16_t *)&page_data[indices[p_compressed_track * 3 + 0]];
@@ -5323,8 +5362,8 @@ bool Animation::_fetch_compressed_by_index(uint32_t p_compressed_track, int p_in
ERR_FAIL_COND_V(!compression.enabled, false);
ERR_FAIL_UNSIGNED_INDEX_V(p_compressed_track, compression.bounds.size(), false);
- for (uint32_t i = 0; i < compression.pages.size(); i++) {
- const uint8_t *page_data = compression.pages[i].data.ptr();
+ for (const Compression::Page &page : compression.pages) {
+ const uint8_t *page_data = page.data.ptr();
// Little endian assumed. No major big endian hardware exists any longer, but in case it does it will need to be supported.
const uint32_t *indices = (const uint32_t *)page_data;
const uint16_t *time_keys = (const uint16_t *)&page_data[indices[p_compressed_track * 3 + 0]];
@@ -5374,7 +5413,7 @@ bool Animation::_fetch_compressed_by_index(uint32_t p_compressed_track, int p_in
}
}
- r_time = compression.pages[i].time_offset + double(frame) / double(compression.fps);
+ r_time = page.time_offset + double(frame) / double(compression.fps);
for (uint32_t l = 0; l < COMPONENTS; l++) {
r_value[l] = decode[l];
}
diff --git a/scene/resources/animation.h b/scene/resources/animation.h
index 00a0761e0a..2c2ddb7095 100644
--- a/scene/resources/animation.h
+++ b/scene/resources/animation.h
@@ -213,6 +213,7 @@ private:
struct AudioTrack : public Track {
Vector<TKey<AudioKey>> values;
+ bool use_blend = true;
AudioTrack() {
type = TYPE_AUDIO;
@@ -447,6 +448,8 @@ public:
Ref<Resource> audio_track_get_key_stream(int p_track, int p_key) const;
real_t audio_track_get_key_start_offset(int p_track, int p_key) const;
real_t audio_track_get_key_end_offset(int p_track, int p_key) const;
+ void audio_track_set_use_blend(int p_track, bool p_enable);
+ bool audio_track_is_use_blend(int p_track) const;
int animation_track_insert_key(int p_track, double p_time, const StringName &p_animation);
void animation_track_set_key_animation(int p_track, int p_key, const StringName &p_animation);
diff --git a/scene/resources/audio_stream_polyphonic.cpp b/scene/resources/audio_stream_polyphonic.cpp
new file mode 100644
index 0000000000..f7299b0789
--- /dev/null
+++ b/scene/resources/audio_stream_polyphonic.cpp
@@ -0,0 +1,274 @@
+/**************************************************************************/
+/* audio_stream_polyphonic.cpp */
+/**************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/**************************************************************************/
+/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
+/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
+/* */
+/* 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 "audio_stream_polyphonic.h"
+#include "scene/main/scene_tree.h"
+
+Ref<AudioStreamPlayback> AudioStreamPolyphonic::instantiate_playback() {
+ Ref<AudioStreamPlaybackPolyphonic> playback;
+ playback.instantiate();
+ playback->streams.resize(polyphony);
+ return playback;
+}
+
+String AudioStreamPolyphonic::get_stream_name() const {
+ return "AudioStreamPolyphonic";
+}
+
+bool AudioStreamPolyphonic::is_monophonic() const {
+ return true; // This avoids stream players to instantiate more than one of these.
+}
+
+void AudioStreamPolyphonic::set_polyphony(int p_voices) {
+ ERR_FAIL_COND(p_voices < 0 || p_voices > 128);
+ polyphony = p_voices;
+}
+int AudioStreamPolyphonic::get_polyphony() const {
+ return polyphony;
+}
+
+void AudioStreamPolyphonic::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("set_polyphony", "voices"), &AudioStreamPolyphonic::set_polyphony);
+ ClassDB::bind_method(D_METHOD("get_polyphony"), &AudioStreamPolyphonic::get_polyphony);
+
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "polyphony", PROPERTY_HINT_RANGE, "1,128,1"), "set_polyphony", "get_polyphony");
+}
+
+AudioStreamPolyphonic::AudioStreamPolyphonic() {
+}
+
+////////////////////////
+
+void AudioStreamPlaybackPolyphonic::start(double p_from_pos) {
+ if (active) {
+ stop();
+ }
+
+ active = true;
+}
+
+void AudioStreamPlaybackPolyphonic::stop() {
+ if (!active) {
+ return;
+ }
+
+ bool locked = false;
+ for (Stream &s : streams) {
+ if (s.active.is_set()) {
+ // Need locking because something may still be mixing.
+ locked = true;
+ AudioServer::get_singleton()->lock();
+ }
+ s.active.clear();
+ s.finish_request.clear();
+ s.stream_playback.unref();
+ s.stream.unref();
+ }
+ if (locked) {
+ AudioServer::get_singleton()->unlock();
+ }
+
+ active = false;
+}
+
+bool AudioStreamPlaybackPolyphonic::is_playing() const {
+ return active;
+}
+
+int AudioStreamPlaybackPolyphonic::get_loop_count() const {
+ return 0;
+}
+
+double AudioStreamPlaybackPolyphonic::get_playback_position() const {
+ return 0;
+}
+void AudioStreamPlaybackPolyphonic::seek(double p_time) {
+ // Ignored.
+}
+
+void AudioStreamPlaybackPolyphonic::tag_used_streams() {
+ for (Stream &s : streams) {
+ if (s.active.is_set()) {
+ s.stream_playback->tag_used_streams();
+ }
+ }
+}
+
+int AudioStreamPlaybackPolyphonic::mix(AudioFrame *p_buffer, float p_rate_scale, int p_frames) {
+ if (!active) {
+ return 0;
+ }
+
+ // Pre-clear buffer.
+ for (int i = 0; i < p_frames; i++) {
+ p_buffer[i] = AudioFrame(0, 0);
+ }
+
+ for (Stream &s : streams) {
+ if (!s.active.is_set()) {
+ continue;
+ }
+
+ float volume_db = s.volume_db; // Copy because it can be overridden at any time.
+ float next_volume = Math::db_to_linear(volume_db);
+ s.prev_volume_db = volume_db;
+
+ if (s.finish_request.is_set()) {
+ if (s.pending_play.is_set()) {
+ // Did not get the chance to play, was finalized too soon.
+ s.active.clear();
+ continue;
+ }
+ next_volume = 0;
+ }
+
+ if (s.pending_play.is_set()) {
+ s.stream_playback->start(s.play_offset);
+ s.pending_play.clear();
+ }
+ float prev_volume = Math::db_to_linear(s.prev_volume_db);
+
+ float volume_inc = (next_volume - prev_volume) / float(p_frames);
+
+ int todo = p_frames;
+ int offset = 0;
+ float volume = prev_volume;
+
+ bool stream_done = false;
+
+ while (todo) {
+ int to_mix = MIN(todo, int(INTERNAL_BUFFER_LEN));
+ int mixed = s.stream_playback->mix(internal_buffer, s.pitch_scale, to_mix);
+
+ for (int i = 0; i < to_mix; i++) {
+ p_buffer[offset + i] += internal_buffer[i] * volume;
+ volume += volume_inc;
+ }
+
+ if (mixed < to_mix) {
+ // Stream is done.
+ s.active.clear();
+ stream_done = true;
+ break;
+ }
+
+ todo -= to_mix;
+ offset += to_mix;
+ }
+
+ if (stream_done) {
+ continue;
+ }
+
+ if (s.finish_request.is_set()) {
+ s.active.clear();
+ }
+ }
+
+ return p_frames;
+}
+
+AudioStreamPlaybackPolyphonic::ID AudioStreamPlaybackPolyphonic::play_stream(const Ref<AudioStream> &p_stream, float p_from_offset, float p_volume_db, float p_pitch_scale) {
+ ERR_FAIL_COND_V(p_stream.is_null(), INVALID_ID);
+ for (uint32_t i = 0; i < streams.size(); i++) {
+ if (!streams[i].active.is_set()) {
+ // Can use this stream, as it's not active.
+ streams[i].stream = p_stream;
+ streams[i].stream_playback = streams[i].stream->instantiate_playback();
+ streams[i].play_offset = p_from_offset;
+ streams[i].volume_db = p_volume_db;
+ streams[i].prev_volume_db = p_volume_db;
+ streams[i].pitch_scale = p_pitch_scale;
+ streams[i].id = id_counter++;
+ streams[i].finish_request.clear();
+ streams[i].pending_play.set();
+ streams[i].active.set();
+ return (ID(i) << INDEX_SHIFT) | ID(streams[i].id);
+ }
+ }
+
+ return INVALID_ID;
+}
+
+AudioStreamPlaybackPolyphonic::Stream *AudioStreamPlaybackPolyphonic::_find_stream(int64_t p_id) {
+ uint32_t index = p_id >> INDEX_SHIFT;
+ if (index >= streams.size()) {
+ return nullptr;
+ }
+ if (!streams[index].active.is_set()) {
+ return nullptr; // Not active, no longer exists.
+ }
+ int64_t id = p_id & ID_MASK;
+ if (streams[index].id != id) {
+ return nullptr;
+ }
+ return &streams[index];
+}
+
+void AudioStreamPlaybackPolyphonic::set_stream_volume(ID p_stream_id, float p_volume_db) {
+ Stream *s = _find_stream(p_stream_id);
+ if (!s) {
+ return;
+ }
+ s->volume_db = p_volume_db;
+}
+
+void AudioStreamPlaybackPolyphonic::set_stream_pitch_scale(ID p_stream_id, float p_pitch_scale) {
+ Stream *s = _find_stream(p_stream_id);
+ if (!s) {
+ return;
+ }
+ s->pitch_scale = p_pitch_scale;
+}
+
+bool AudioStreamPlaybackPolyphonic::is_stream_playing(ID p_stream_id) const {
+ return const_cast<AudioStreamPlaybackPolyphonic *>(this)->_find_stream(p_stream_id) != nullptr;
+}
+
+void AudioStreamPlaybackPolyphonic::stop_stream(ID p_stream_id) {
+ Stream *s = _find_stream(p_stream_id);
+ if (!s) {
+ return;
+ }
+ s->finish_request.set();
+}
+
+void AudioStreamPlaybackPolyphonic::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("play_stream", "stream", "from_offset", "volume_db", "pitch_scale"), &AudioStreamPlaybackPolyphonic::play_stream, DEFVAL(0), DEFVAL(0), DEFVAL(1.0));
+ ClassDB::bind_method(D_METHOD("set_stream_volume", "stream", "volume_db"), &AudioStreamPlaybackPolyphonic::set_stream_volume);
+ ClassDB::bind_method(D_METHOD("set_stream_pitch_scale", "stream", "pitch_scale"), &AudioStreamPlaybackPolyphonic::set_stream_pitch_scale);
+ ClassDB::bind_method(D_METHOD("is_stream_playing", "stream"), &AudioStreamPlaybackPolyphonic::is_stream_playing);
+ ClassDB::bind_method(D_METHOD("stop_stream", "stream"), &AudioStreamPlaybackPolyphonic::stop_stream);
+
+ BIND_CONSTANT(INVALID_ID);
+}
+
+AudioStreamPlaybackPolyphonic::AudioStreamPlaybackPolyphonic() {
+}
diff --git a/scene/resources/skeleton_modification_stack_3d.h b/scene/resources/audio_stream_polyphonic.h
index fd490c49e9..e414401b6f 100644
--- a/scene/resources/skeleton_modification_stack_3d.h
+++ b/scene/resources/audio_stream_polyphonic.h
@@ -1,5 +1,5 @@
/**************************************************************************/
-/* skeleton_modification_stack_3d.h */
+/* audio_stream_polyphonic.h */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
@@ -28,64 +28,92 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
-#ifndef SKELETON_MODIFICATION_STACK_3D_H
-#define SKELETON_MODIFICATION_STACK_3D_H
+#ifndef AUDIO_STREAM_POLYPHONIC_H
+#define AUDIO_STREAM_POLYPHONIC_H
#include "core/templates/local_vector.h"
-#include "scene/3d/skeleton_3d.h"
+#include "servers/audio/audio_stream.h"
-class Skeleton3D;
-class SkeletonModification3D;
+class AudioStreamPolyphonic : public AudioStream {
+ GDCLASS(AudioStreamPolyphonic, AudioStream)
+ int polyphony = 32;
-class SkeletonModificationStack3D : public Resource {
- GDCLASS(SkeletonModificationStack3D, Resource);
- friend class Skeleton3D;
- friend class SkeletonModification3D;
-
-protected:
static void _bind_methods();
- virtual void _get_property_list(List<PropertyInfo> *p_list) const;
- virtual bool _set(const StringName &p_path, const Variant &p_value);
- virtual bool _get(const StringName &p_path, Variant &r_ret) const;
public:
- Skeleton3D *skeleton = nullptr;
- bool is_setup = false;
- bool enabled = false;
- real_t strength = 1.0;
-
- enum EXECUTION_MODE {
- execution_mode_process,
- execution_mode_physics_process,
+ virtual Ref<AudioStreamPlayback> instantiate_playback() override;
+ virtual String get_stream_name() const override;
+ virtual bool is_monophonic() const override;
+
+ void set_polyphony(int p_voices);
+ int get_polyphony() const;
+
+ AudioStreamPolyphonic();
+};
+
+class AudioStreamPlaybackPolyphonic : public AudioStreamPlayback {
+ GDCLASS(AudioStreamPlaybackPolyphonic, AudioStreamPlayback)
+
+ enum {
+ INTERNAL_BUFFER_LEN = 128,
+ ID_MASK = 0xFFFFFFFF,
+ INDEX_SHIFT = 32
+ };
+ struct Stream {
+ SafeFlag active;
+ SafeFlag pending_play;
+ SafeFlag finish_request;
+ float play_offset = 0;
+ float pitch_scale = 1.0;
+ Ref<AudioStream> stream;
+ Ref<AudioStreamPlayback> stream_playback;
+ float prev_volume_db = 0;
+ float volume_db = 0;
+ uint32_t id = 0;
+
+ Stream() :
+ active(false), pending_play(false), finish_request(false) {}
};
- LocalVector<Ref<SkeletonModification3D>> modifications = LocalVector<Ref<SkeletonModification3D>>();
- int modifications_count = 0;
+ LocalVector<Stream> streams;
+ AudioFrame internal_buffer[INTERNAL_BUFFER_LEN];
- virtual void setup();
- virtual void execute(real_t p_delta, int p_execution_mode);
+ bool active = false;
+ uint32_t id_counter = 1;
+
+ _FORCE_INLINE_ Stream *_find_stream(int64_t p_id);
+
+ friend class AudioStreamPolyphonic;
+
+protected:
+ static void _bind_methods();
+
+public:
+ typedef int64_t ID;
+ enum {
+ INVALID_ID = -1
+ };
- void enable_all_modifications(bool p_enable);
- Ref<SkeletonModification3D> get_modification(int p_mod_idx) const;
- void add_modification(Ref<SkeletonModification3D> p_mod);
- void delete_modification(int p_mod_idx);
- void set_modification(int p_mod_idx, Ref<SkeletonModification3D> p_mod);
+ virtual void start(double p_from_pos = 0.0) override;
+ virtual void stop() override;
+ virtual bool is_playing() const override;
- void set_modification_count(int p_count);
- int get_modification_count() const;
+ virtual int get_loop_count() const override; //times it looped
- void set_skeleton(Skeleton3D *p_skeleton);
- Skeleton3D *get_skeleton() const;
+ virtual double get_playback_position() const override;
+ virtual void seek(double p_time) override;
- bool get_is_setup() const;
+ virtual void tag_used_streams() override;
- void set_enabled(bool p_enabled);
- bool get_enabled() const;
+ virtual int mix(AudioFrame *p_buffer, float p_rate_scale, int p_frames) override;
- void set_strength(real_t p_strength);
- real_t get_strength() const;
+ ID play_stream(const Ref<AudioStream> &p_stream, float p_from_offset = 0, float p_volume_db = 0, float p_pitch_scale = 1.0);
+ void set_stream_volume(ID p_stream_id, float p_volume_db);
+ void set_stream_pitch_scale(ID p_stream_id, float p_pitch_scale);
+ bool is_stream_playing(ID p_stream_id) const;
+ void stop_stream(ID p_stream_id);
- SkeletonModificationStack3D();
+ AudioStreamPlaybackPolyphonic();
};
-#endif // SKELETON_MODIFICATION_STACK_3D_H
+#endif // AUDIO_STREAM_POLYPHONIC_H
diff --git a/scene/resources/bone_map.cpp b/scene/resources/bone_map.cpp
index c73f8ca0b0..759d189bfa 100644
--- a/scene/resources/bone_map.cpp
+++ b/scene/resources/bone_map.cpp
@@ -152,7 +152,6 @@ void BoneMap::_validate_bone_map() {
} else {
bone_map.clear();
}
- emit_signal("retarget_option_updated");
}
void BoneMap::_bind_methods() {
diff --git a/scene/resources/camera_attributes.cpp b/scene/resources/camera_attributes.cpp
index b5e302cce5..61df56523d 100644
--- a/scene/resources/camera_attributes.cpp
+++ b/scene/resources/camera_attributes.cpp
@@ -286,10 +286,10 @@ void CameraAttributesPractical::_bind_methods() {
ADD_GROUP("DOF Blur", "dof_blur_");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "dof_blur_far_enabled"), "set_dof_blur_far_enabled", "is_dof_blur_far_enabled");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "dof_blur_far_distance", PROPERTY_HINT_RANGE, "0.01,8192,0.01,exp,suffix:m"), "set_dof_blur_far_distance", "get_dof_blur_far_distance");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "dof_blur_far_transition", PROPERTY_HINT_RANGE, "0.01,8192,0.01,exp"), "set_dof_blur_far_transition", "get_dof_blur_far_transition");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "dof_blur_far_transition", PROPERTY_HINT_RANGE, "-1,8192,0.01,exp"), "set_dof_blur_far_transition", "get_dof_blur_far_transition");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "dof_blur_near_enabled"), "set_dof_blur_near_enabled", "is_dof_blur_near_enabled");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "dof_blur_near_distance", PROPERTY_HINT_RANGE, "0.01,8192,0.01,exp,suffix:m"), "set_dof_blur_near_distance", "get_dof_blur_near_distance");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "dof_blur_near_transition", PROPERTY_HINT_RANGE, "0.01,8192,0.01,exp"), "set_dof_blur_near_transition", "get_dof_blur_near_transition");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "dof_blur_near_transition", PROPERTY_HINT_RANGE, "-1,8192,0.01,exp"), "set_dof_blur_near_transition", "get_dof_blur_near_transition");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "dof_blur_amount", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_dof_blur_amount", "get_dof_blur_amount");
ADD_GROUP("Auto Exposure", "auto_exposure_");
diff --git a/scene/resources/capsule_shape_2d.cpp b/scene/resources/capsule_shape_2d.cpp
index 5dc4e64c2e..5309e54846 100644
--- a/scene/resources/capsule_shape_2d.cpp
+++ b/scene/resources/capsule_shape_2d.cpp
@@ -88,8 +88,10 @@ void CapsuleShape2D::draw(const RID &p_to_rid, const Color &p_color) {
Vector<Vector2> points = _get_points();
Vector<Color> col = { p_color };
RenderingServer::get_singleton()->canvas_item_add_polygon(p_to_rid, points, col);
+
if (is_collision_outline_enabled()) {
points.push_back(points[0]);
+ col = { Color(p_color, 1.0) };
RenderingServer::get_singleton()->canvas_item_add_polyline(p_to_rid, points, col);
}
}
diff --git a/scene/resources/circle_shape_2d.cpp b/scene/resources/circle_shape_2d.cpp
index a15dfc0a54..0b207c33ca 100644
--- a/scene/resources/circle_shape_2d.cpp
+++ b/scene/resources/circle_shape_2d.cpp
@@ -84,6 +84,7 @@ void CircleShape2D::draw(const RID &p_to_rid, const Color &p_color) {
if (is_collision_outline_enabled()) {
points.push_back(points[0]);
+ col = { Color(p_color, 1.0) };
RenderingServer::get_singleton()->canvas_item_add_polyline(p_to_rid, points, col);
}
}
diff --git a/scene/resources/convex_polygon_shape_2d.cpp b/scene/resources/convex_polygon_shape_2d.cpp
index d92d4fa4a4..7f19dd63e6 100644
--- a/scene/resources/convex_polygon_shape_2d.cpp
+++ b/scene/resources/convex_polygon_shape_2d.cpp
@@ -76,13 +76,14 @@ void ConvexPolygonShape2D::draw(const RID &p_to_rid, const Color &p_color) {
return;
}
- Vector<Color> col;
- col.push_back(p_color);
+ Vector<Color> col = { p_color };
RenderingServer::get_singleton()->canvas_item_add_polygon(p_to_rid, points, col);
+
if (is_collision_outline_enabled()) {
+ col = { Color(p_color, 1.0) };
RenderingServer::get_singleton()->canvas_item_add_polyline(p_to_rid, points, col);
- // Draw the last segment as it's not drawn by `canvas_item_add_polyline()`.
- RenderingServer::get_singleton()->canvas_item_add_line(p_to_rid, points[points.size() - 1], points[0], p_color, 1.0, true);
+ // Draw the last segment.
+ RenderingServer::get_singleton()->canvas_item_add_line(p_to_rid, points[points.size() - 1], points[0], Color(p_color, 1.0));
}
}
diff --git a/scene/resources/default_theme/default_theme.cpp b/scene/resources/default_theme/default_theme.cpp
index 4d3eec6333..7a865691d9 100644
--- a/scene/resources/default_theme/default_theme.cpp
+++ b/scene/resources/default_theme/default_theme.cpp
@@ -53,7 +53,7 @@ static const int default_corner_radius = 3;
static Ref<StyleBoxFlat> make_flat_stylebox(Color p_color, float p_margin_left = default_margin, float p_margin_top = default_margin, float p_margin_right = default_margin, float p_margin_bottom = default_margin, int p_corner_radius = default_corner_radius, bool p_draw_center = true, int p_border_width = 0) {
Ref<StyleBoxFlat> style(memnew(StyleBoxFlat));
style->set_bg_color(p_color);
- style->set_default_margin_individual(p_margin_left * scale, p_margin_top * scale, p_margin_right * scale, p_margin_bottom * scale);
+ style->set_content_margin_individual(p_margin_left * scale, p_margin_top * scale, p_margin_right * scale, p_margin_bottom * scale);
style->set_corner_radius_all(p_corner_radius);
style->set_anti_aliased(true);
@@ -67,10 +67,10 @@ static Ref<StyleBoxFlat> make_flat_stylebox(Color p_color, float p_margin_left =
}
static Ref<StyleBoxFlat> sb_expand(Ref<StyleBoxFlat> p_sbox, float p_left, float p_top, float p_right, float p_bottom) {
- p_sbox->set_expand_margin_size(SIDE_LEFT, p_left * scale);
- p_sbox->set_expand_margin_size(SIDE_TOP, p_top * scale);
- p_sbox->set_expand_margin_size(SIDE_RIGHT, p_right * scale);
- p_sbox->set_expand_margin_size(SIDE_BOTTOM, p_bottom * scale);
+ p_sbox->set_expand_margin(SIDE_LEFT, p_left * scale);
+ p_sbox->set_expand_margin(SIDE_TOP, p_top * scale);
+ p_sbox->set_expand_margin(SIDE_RIGHT, p_right * scale);
+ p_sbox->set_expand_margin(SIDE_BOTTOM, p_bottom * scale);
return p_sbox;
}
@@ -93,7 +93,7 @@ static Ref<ImageTexture> generate_icon(int p_index) {
static Ref<StyleBox> make_empty_stylebox(float p_margin_left = -1, float p_margin_top = -1, float p_margin_right = -1, float p_margin_bottom = -1) {
Ref<StyleBox> style(memnew(StyleBoxEmpty));
- style->set_default_margin_individual(p_margin_left * scale, p_margin_top * scale, p_margin_right * scale, p_margin_bottom * scale);
+ style->set_content_margin_individual(p_margin_left * scale, p_margin_top * scale, p_margin_right * scale, p_margin_bottom * scale);
return style;
}
@@ -148,7 +148,7 @@ void fill_default_theme(Ref<Theme> &theme, const Ref<Font> &default_font, const
const Ref<StyleBoxFlat> button_disabled = make_flat_stylebox(style_disabled_color);
Ref<StyleBoxFlat> focus = make_flat_stylebox(style_focus_color, default_margin, default_margin, default_margin, default_margin, default_corner_radius, false, 2);
// Make the focus outline appear to be flush with the buttons it's focusing.
- focus->set_expand_margin_size_all(2 * scale);
+ focus->set_expand_margin_all(2 * scale);
theme->set_stylebox("normal", "Button", button_normal);
theme->set_stylebox("hover", "Button", button_hover);
@@ -279,9 +279,9 @@ void fill_default_theme(Ref<Theme> &theme, const Ref<Font> &default_font, const
// CheckBox
Ref<StyleBox> cbx_empty = memnew(StyleBoxEmpty);
- cbx_empty->set_default_margin_all(4 * scale);
+ cbx_empty->set_content_margin_all(4 * scale);
Ref<StyleBox> cbx_focus = focus;
- cbx_focus->set_default_margin_all(4 * scale);
+ cbx_focus->set_content_margin_all(4 * scale);
theme->set_stylebox("normal", "CheckBox", cbx_empty);
theme->set_stylebox("pressed", "CheckBox", cbx_empty);
@@ -317,7 +317,7 @@ void fill_default_theme(Ref<Theme> &theme, const Ref<Font> &default_font, const
// CheckButton
Ref<StyleBox> cb_empty = memnew(StyleBoxEmpty);
- cb_empty->set_default_margin_individual(6 * scale, 4 * scale, 6 * scale, 4 * scale);
+ cb_empty->set_content_margin_individual(6 * scale, 4 * scale, 6 * scale, 4 * scale);
theme->set_stylebox("normal", "CheckButton", cb_empty);
theme->set_stylebox("pressed", "CheckButton", cb_empty);
@@ -634,10 +634,10 @@ void fill_default_theme(Ref<Theme> &theme, const Ref<Font> &default_font, const
Ref<StyleBoxLine> separator_horizontal = memnew(StyleBoxLine);
separator_horizontal->set_thickness(Math::round(scale));
separator_horizontal->set_color(style_separator_color);
- separator_horizontal->set_default_margin_individual(default_margin, 0, default_margin, 0);
+ separator_horizontal->set_content_margin_individual(default_margin, 0, default_margin, 0);
Ref<StyleBoxLine> separator_vertical = separator_horizontal->duplicate();
separator_vertical->set_vertical(true);
- separator_vertical->set_default_margin_individual(0, default_margin, 0, default_margin);
+ separator_vertical->set_content_margin_individual(0, default_margin, 0, default_margin);
// Always display a border for PopupMenus so they can be distinguished from their background.
Ref<StyleBoxFlat> style_popup_panel = make_flat_stylebox(style_popup_color);
diff --git a/scene/resources/environment.cpp b/scene/resources/environment.cpp
index 746f2f8f9b..8b4656414d 100644
--- a/scene/resources/environment.cpp
+++ b/scene/resources/environment.cpp
@@ -1043,6 +1043,18 @@ void Environment::_validate_property(PropertyInfo &p_property) const {
}
}
+ if (p_property.name == "ambient_light_color" || p_property.name == "ambient_light_energy") {
+ if (ambient_source == AMBIENT_SOURCE_DISABLED) {
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
+ }
+ }
+
+ if (p_property.name == "ambient_light_sky_contribution") {
+ if (ambient_source == AMBIENT_SOURCE_DISABLED || ambient_source == AMBIENT_SOURCE_COLOR) {
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
+ }
+ }
+
if (p_property.name == "fog_aerial_perspective") {
if (bg_mode != BG_SKY) {
p_property.usage = PROPERTY_USAGE_NO_EDITOR;
diff --git a/scene/resources/fog_material.cpp b/scene/resources/fog_material.cpp
index 4e51bbaa73..aabaa54505 100644
--- a/scene/resources/fog_material.cpp
+++ b/scene/resources/fog_material.cpp
@@ -159,7 +159,7 @@ uniform sampler3D density_texture: hint_default_white;
void fog() {
DENSITY = density * clamp(exp2(-height_falloff * (WORLD_POSITION.y - OBJECT_POSITION.y)), 0.0, 1.0);
DENSITY *= texture(density_texture, UVW).r;
- DENSITY *= pow(clamp(-SDF / min(min(EXTENTS.x, EXTENTS.y), EXTENTS.z), 0.0, 1.0), edge_fade);
+ DENSITY *= pow(clamp(-2.0 * SDF / min(min(SIZE.x, SIZE.y), SIZE.z), 0.0, 1.0), edge_fade);
ALBEDO = albedo.rgb;
EMISSION = emission.rgb;
}
diff --git a/scene/resources/font.cpp b/scene/resources/font.cpp
index deee187e8e..0f7985bee6 100644
--- a/scene/resources/font.cpp
+++ b/scene/resources/font.cpp
@@ -2712,6 +2712,9 @@ Ref<Font> FontVariation::_get_base_font_or_default() const {
for (const StringName &E : theme_types) {
if (ThemeDB::get_singleton()->get_project_theme()->has_theme_item(Theme::DATA_TYPE_FONT, "font", E)) {
Ref<Font> f = ThemeDB::get_singleton()->get_project_theme()->get_theme_item(Theme::DATA_TYPE_FONT, "font", E);
+ if (f == this) {
+ continue;
+ }
if (f.is_valid()) {
theme_font = f;
theme_font->connect(CoreStringNames::get_singleton()->changed, callable_mp(reinterpret_cast<Font *>(const_cast<FontVariation *>(this)), &Font::_invalidate_rids), CONNECT_REFERENCE_COUNTED);
@@ -2729,6 +2732,9 @@ Ref<Font> FontVariation::_get_base_font_or_default() const {
for (const StringName &E : theme_types) {
if (ThemeDB::get_singleton()->get_default_theme()->has_theme_item(Theme::DATA_TYPE_FONT, "font", E)) {
Ref<Font> f = ThemeDB::get_singleton()->get_default_theme()->get_theme_item(Theme::DATA_TYPE_FONT, "font", E);
+ if (f == this) {
+ continue;
+ }
if (f.is_valid()) {
theme_font = f;
theme_font->connect(CoreStringNames::get_singleton()->changed, callable_mp(reinterpret_cast<Font *>(const_cast<FontVariation *>(this)), &Font::_invalidate_rids), CONNECT_REFERENCE_COUNTED);
@@ -2739,11 +2745,13 @@ Ref<Font> FontVariation::_get_base_font_or_default() const {
// If they don't exist, use any type to return the default/empty value.
Ref<Font> f = ThemeDB::get_singleton()->get_default_theme()->get_theme_item(Theme::DATA_TYPE_FONT, "font", StringName());
- if (f.is_valid()) {
- theme_font = f;
- theme_font->connect(CoreStringNames::get_singleton()->changed, callable_mp(reinterpret_cast<Font *>(const_cast<FontVariation *>(this)), &Font::_invalidate_rids), CONNECT_REFERENCE_COUNTED);
+ if (f != this) {
+ if (f.is_valid()) {
+ theme_font = f;
+ theme_font->connect(CoreStringNames::get_singleton()->changed, callable_mp(reinterpret_cast<Font *>(const_cast<FontVariation *>(this)), &Font::_invalidate_rids), CONNECT_REFERENCE_COUNTED);
+ }
+ return f;
}
- return f;
}
return Ref<Font>();
@@ -2868,6 +2876,12 @@ void SystemFont::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_multichannel_signed_distance_field", "msdf"), &SystemFont::set_multichannel_signed_distance_field);
ClassDB::bind_method(D_METHOD("is_multichannel_signed_distance_field"), &SystemFont::is_multichannel_signed_distance_field);
+ ClassDB::bind_method(D_METHOD("set_msdf_pixel_range", "msdf_pixel_range"), &SystemFont::set_msdf_pixel_range);
+ ClassDB::bind_method(D_METHOD("get_msdf_pixel_range"), &SystemFont::get_msdf_pixel_range);
+
+ ClassDB::bind_method(D_METHOD("set_msdf_size", "msdf_size"), &SystemFont::set_msdf_size);
+ ClassDB::bind_method(D_METHOD("get_msdf_size"), &SystemFont::get_msdf_size);
+
ClassDB::bind_method(D_METHOD("set_oversampling", "oversampling"), &SystemFont::set_oversampling);
ClassDB::bind_method(D_METHOD("get_oversampling"), &SystemFont::get_oversampling);
@@ -2890,6 +2904,8 @@ void SystemFont::_bind_methods() {
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::INT, "msdf_pixel_range"), "set_msdf_pixel_range", "get_msdf_pixel_range");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "msdf_size"), "set_msdf_size", "get_msdf_size");
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, MAKE_RESOURCE_TYPE_HINT("Font")), "set_fallbacks", "get_fallbacks");
}
@@ -2987,6 +3003,8 @@ void SystemFont::_update_base_font() {
file->set_hinting(hinting);
file->set_subpixel_positioning(subpixel_positioning);
file->set_multichannel_signed_distance_field(msdf);
+ file->set_msdf_pixel_range(msdf_pixel_range);
+ file->set_msdf_size(msdf_size);
file->set_oversampling(oversampling);
base_font = file;
@@ -3051,6 +3069,9 @@ Ref<Font> SystemFont::_get_base_font_or_default() const {
for (const StringName &E : theme_types) {
if (ThemeDB::get_singleton()->get_project_theme()->has_theme_item(Theme::DATA_TYPE_FONT, "font", E)) {
Ref<Font> f = ThemeDB::get_singleton()->get_project_theme()->get_theme_item(Theme::DATA_TYPE_FONT, "font", E);
+ if (f == this) {
+ continue;
+ }
if (f.is_valid()) {
theme_font = f;
theme_font->connect(CoreStringNames::get_singleton()->changed, callable_mp(reinterpret_cast<Font *>(const_cast<SystemFont *>(this)), &Font::_invalidate_rids), CONNECT_REFERENCE_COUNTED);
@@ -3068,6 +3089,9 @@ Ref<Font> SystemFont::_get_base_font_or_default() const {
for (const StringName &E : theme_types) {
if (ThemeDB::get_singleton()->get_default_theme()->has_theme_item(Theme::DATA_TYPE_FONT, "font", E)) {
Ref<Font> f = ThemeDB::get_singleton()->get_default_theme()->get_theme_item(Theme::DATA_TYPE_FONT, "font", E);
+ if (f == this) {
+ continue;
+ }
if (f.is_valid()) {
theme_font = f;
theme_font->connect(CoreStringNames::get_singleton()->changed, callable_mp(reinterpret_cast<Font *>(const_cast<SystemFont *>(this)), &Font::_invalidate_rids), CONNECT_REFERENCE_COUNTED);
@@ -3078,11 +3102,13 @@ Ref<Font> SystemFont::_get_base_font_or_default() const {
// If they don't exist, use any type to return the default/empty value.
Ref<Font> f = ThemeDB::get_singleton()->get_default_theme()->get_theme_item(Theme::DATA_TYPE_FONT, "font", StringName());
- if (f.is_valid()) {
- theme_font = f;
- theme_font->connect(CoreStringNames::get_singleton()->changed, callable_mp(reinterpret_cast<Font *>(const_cast<SystemFont *>(this)), &Font::_invalidate_rids), CONNECT_REFERENCE_COUNTED);
+ if (f != this) {
+ if (f.is_valid()) {
+ theme_font = f;
+ theme_font->connect(CoreStringNames::get_singleton()->changed, callable_mp(reinterpret_cast<Font *>(const_cast<SystemFont *>(this)), &Font::_invalidate_rids), CONNECT_REFERENCE_COUNTED);
+ }
+ return f;
}
- return f;
}
return Ref<Font>();
@@ -3186,6 +3212,34 @@ bool SystemFont::is_multichannel_signed_distance_field() const {
return msdf;
}
+void SystemFont::set_msdf_pixel_range(int p_msdf_pixel_range) {
+ if (msdf_pixel_range != p_msdf_pixel_range) {
+ msdf_pixel_range = p_msdf_pixel_range;
+ if (base_font.is_valid()) {
+ base_font->set_msdf_pixel_range(msdf_pixel_range);
+ }
+ emit_changed();
+ }
+}
+
+int SystemFont::get_msdf_pixel_range() const {
+ return msdf_pixel_range;
+}
+
+void SystemFont::set_msdf_size(int p_msdf_size) {
+ if (msdf_size != p_msdf_size) {
+ msdf_size = p_msdf_size;
+ if (base_font.is_valid()) {
+ base_font->set_msdf_size(msdf_size);
+ }
+ emit_changed();
+ }
+}
+
+int SystemFont::get_msdf_size() const {
+ return msdf_size;
+}
+
void SystemFont::set_oversampling(real_t p_oversampling) {
if (oversampling != p_oversampling) {
oversampling = p_oversampling;
diff --git a/scene/resources/font.h b/scene/resources/font.h
index 4d468a8841..ef79f8bd02 100644
--- a/scene/resources/font.h
+++ b/scene/resources/font.h
@@ -452,6 +452,8 @@ class SystemFont : public Font {
TextServer::SubpixelPositioning subpixel_positioning = TextServer::SUBPIXEL_POSITIONING_AUTO;
real_t oversampling = 0.f;
bool msdf = false;
+ int msdf_pixel_range = 16;
+ int msdf_size = 48;
protected:
static void _bind_methods();
@@ -488,6 +490,12 @@ public:
virtual void set_multichannel_signed_distance_field(bool p_msdf);
virtual bool is_multichannel_signed_distance_field() const;
+ virtual void set_msdf_pixel_range(int p_msdf_pixel_range);
+ virtual int get_msdf_pixel_range() const;
+
+ virtual void set_msdf_size(int p_msdf_size);
+ virtual int get_msdf_size() const;
+
virtual void set_font_names(const PackedStringArray &p_names);
virtual PackedStringArray get_font_names() const;
diff --git a/scene/resources/immediate_mesh.cpp b/scene/resources/immediate_mesh.cpp
index 2254c19327..48d609da97 100644
--- a/scene/resources/immediate_mesh.cpp
+++ b/scene/resources/immediate_mesh.cpp
@@ -41,8 +41,8 @@ void ImmediateMesh::surface_set_color(const Color &p_color) {
if (!uses_colors) {
colors.resize(vertices.size());
- for (uint32_t i = 0; i < colors.size(); i++) {
- colors[i] = p_color;
+ for (Color &color : colors) {
+ color = p_color;
}
uses_colors = true;
}
@@ -54,8 +54,8 @@ void ImmediateMesh::surface_set_normal(const Vector3 &p_normal) {
if (!uses_normals) {
normals.resize(vertices.size());
- for (uint32_t i = 0; i < normals.size(); i++) {
- normals[i] = p_normal;
+ for (Vector3 &normal : normals) {
+ normal = p_normal;
}
uses_normals = true;
}
@@ -66,8 +66,8 @@ void ImmediateMesh::surface_set_tangent(const Plane &p_tangent) {
ERR_FAIL_COND_MSG(!surface_active, "Not creating any surface. Use surface_begin() to do it.");
if (!uses_tangents) {
tangents.resize(vertices.size());
- for (uint32_t i = 0; i < tangents.size(); i++) {
- tangents[i] = p_tangent;
+ for (Plane &tangent : tangents) {
+ tangent = p_tangent;
}
uses_tangents = true;
}
@@ -78,8 +78,8 @@ void ImmediateMesh::surface_set_uv(const Vector2 &p_uv) {
ERR_FAIL_COND_MSG(!surface_active, "Not creating any surface. Use surface_begin() to do it.");
if (!uses_uvs) {
uvs.resize(vertices.size());
- for (uint32_t i = 0; i < uvs.size(); i++) {
- uvs[i] = p_uv;
+ for (Vector2 &uv : uvs) {
+ uv = p_uv;
}
uses_uvs = true;
}
@@ -90,8 +90,8 @@ void ImmediateMesh::surface_set_uv2(const Vector2 &p_uv2) {
ERR_FAIL_COND_MSG(!surface_active, "Not creating any surface. Use surface_begin() to do it.");
if (!uses_uv2s) {
uv2s.resize(vertices.size());
- for (uint32_t i = 0; i < uv2s.size(); i++) {
- uv2s[i] = p_uv2;
+ for (Vector2 &uv : uv2s) {
+ uv = p_uv2;
}
uses_uv2s = true;
}
@@ -194,25 +194,20 @@ void ImmediateMesh::surface_end() {
if (uses_normals) {
uint32_t *normal = (uint32_t *)&surface_vertex_ptr[i * vertex_stride + normal_offset];
- Vector3 n = normals[i] * Vector3(0.5, 0.5, 0.5) + Vector3(0.5, 0.5, 0.5);
+ Vector2 n = normals[i].octahedron_encode();
uint32_t value = 0;
- value |= CLAMP(int(n.x * 1023.0), 0, 1023);
- value |= CLAMP(int(n.y * 1023.0), 0, 1023) << 10;
- value |= CLAMP(int(n.z * 1023.0), 0, 1023) << 20;
+ value |= (uint16_t)CLAMP(n.x * 65535, 0, 65535);
+ value |= (uint16_t)CLAMP(n.y * 65535, 0, 65535) << 16;
*normal = value;
}
if (uses_tangents) {
uint32_t *tangent = (uint32_t *)&surface_vertex_ptr[i * vertex_stride + tangent_offset];
- Plane t = tangents[i];
+ Vector2 t = tangents[i].normal.octahedron_tangent_encode(tangents[i].d);
uint32_t value = 0;
- value |= CLAMP(int((t.normal.x * 0.5 + 0.5) * 1023.0), 0, 1023);
- value |= CLAMP(int((t.normal.y * 0.5 + 0.5) * 1023.0), 0, 1023) << 10;
- value |= CLAMP(int((t.normal.z * 0.5 + 0.5) * 1023.0), 0, 1023) << 20;
- if (t.d > 0) {
- value |= 3UL << 30;
- }
+ value |= (uint16_t)CLAMP(t.x * 65535, 0, 65535);
+ value |= (uint16_t)CLAMP(t.y * 65535, 0, 65535) << 16;
*tangent = value;
}
@@ -346,7 +341,7 @@ TypedArray<Array> ImmediateMesh::surface_get_blend_shape_arrays(int p_surface) c
Dictionary ImmediateMesh::surface_get_lods(int p_surface) const {
return Dictionary();
}
-uint32_t ImmediateMesh::surface_get_format(int p_idx) const {
+BitField<Mesh::ArrayFormat> ImmediateMesh::surface_get_format(int p_idx) const {
ERR_FAIL_INDEX_V(p_idx, int(surfaces.size()), 0);
return surfaces[p_idx].format;
}
diff --git a/scene/resources/immediate_mesh.h b/scene/resources/immediate_mesh.h
index 9407ecd98c..bf07c82a0c 100644
--- a/scene/resources/immediate_mesh.h
+++ b/scene/resources/immediate_mesh.h
@@ -99,7 +99,7 @@ public:
virtual Array surface_get_arrays(int p_surface) const override;
virtual TypedArray<Array> surface_get_blend_shape_arrays(int p_surface) const override;
virtual Dictionary surface_get_lods(int p_surface) const override;
- virtual uint32_t surface_get_format(int p_idx) const override;
+ virtual BitField<ArrayFormat> surface_get_format(int p_idx) const override;
virtual PrimitiveType surface_get_primitive_type(int p_idx) const override;
virtual void surface_set_material(int p_idx, const Ref<Material> &p_material) override;
virtual Ref<Material> surface_get_material(int p_idx) const override;
diff --git a/scene/resources/importer_mesh.cpp b/scene/resources/importer_mesh.cpp
index eefa5aa14a..672581bbe2 100644
--- a/scene/resources/importer_mesh.cpp
+++ b/scene/resources/importer_mesh.cpp
@@ -364,9 +364,7 @@ void ImporterMesh::generate_lods(float p_normal_merge_angle, float p_normal_spli
const LocalVector<Pair<int, int>> &close_verts = E->value;
bool found = false;
- for (unsigned int k = 0; k < close_verts.size(); k++) {
- const Pair<int, int> &idx = close_verts[k];
-
+ for (const Pair<int, int> &idx : close_verts) {
bool is_uvs_close = (!uvs_ptr || uvs_ptr[j].distance_squared_to(uvs_ptr[idx.second]) < CMP_EPSILON2);
bool is_uv2s_close = (!uv2s_ptr || uv2s_ptr[j].distance_squared_to(uv2s_ptr[idx.second]) < CMP_EPSILON2);
ERR_FAIL_INDEX(idx.second, normals.size());
@@ -454,6 +452,7 @@ void ImporterMesh::generate_lods(float p_normal_merge_angle, float p_normal_spli
new_indices.resize(index_count);
Vector<float> merged_normals_f32 = vector3_to_float32_array(merged_normals.ptr(), merged_normals.size());
+ const int simplify_options = SurfaceTool::SIMPLIFY_LOCK_BORDER;
size_t new_index_count = SurfaceTool::simplify_with_attrib_func(
(unsigned int *)new_indices.ptrw(),
@@ -462,6 +461,7 @@ void ImporterMesh::generate_lods(float p_normal_merge_angle, float p_normal_spli
sizeof(float) * 3, // Vertex stride
index_target,
max_mesh_error,
+ simplify_options,
&mesh_error,
merged_normals_f32.ptr(),
normal_weights.ptr(), 3);
@@ -599,8 +599,7 @@ void ImporterMesh::generate_lods(float p_normal_merge_angle, float p_normal_spli
const LocalVector<int> &corners = vertex_corners[j];
const Vector3 &vertex_normal = normals_ptr[j];
- for (unsigned int k = 0; k < corners.size(); k++) {
- const int &corner_idx = corners[k];
+ for (const int &corner_idx : corners) {
const Vector3 &ray_normal = ray_normals[corner_idx];
if (ray_normal.length_squared() < CMP_EPSILON2) {
@@ -635,8 +634,8 @@ void ImporterMesh::generate_lods(float p_normal_merge_angle, float p_normal_spli
split_vertex_indices.push_back(j);
split_vertex_normals.push_back(n);
int new_idx = split_vertex_count++;
- for (unsigned int l = 0; l < group_indices.size(); l++) {
- new_indices_ptr[group_indices[l]] = new_idx;
+ for (const int &index : group_indices) {
+ new_indices_ptr[index] = new_idx;
}
}
}
@@ -1061,6 +1060,8 @@ struct EditorSceneFormatImporterMeshLightmapSurface {
String name;
};
+static const uint32_t custom_shift[RS::ARRAY_CUSTOM_COUNT] = { Mesh::ARRAY_FORMAT_CUSTOM0_SHIFT, Mesh::ARRAY_FORMAT_CUSTOM1_SHIFT, Mesh::ARRAY_FORMAT_CUSTOM2_SHIFT, Mesh::ARRAY_FORMAT_CUSTOM3_SHIFT };
+
Error ImporterMesh::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) {
ERR_FAIL_COND_V(!array_mesh_lightmap_unwrap_callback, ERR_UNCONFIGURED);
ERR_FAIL_COND_V_MSG(blend_shapes.size() != 0, ERR_UNAVAILABLE, "Can't unwrap mesh with blend shapes.");
@@ -1181,9 +1182,6 @@ Error ImporterMesh::lightmap_unwrap_cached(const Transform3D &p_base_transform,
return ERR_CANT_CREATE;
}
- //remove surfaces
- clear();
-
//create surfacetools for each surface..
LocalVector<Ref<SurfaceTool>> surfaces_tools;
@@ -1193,9 +1191,16 @@ Error ImporterMesh::lightmap_unwrap_cached(const Transform3D &p_base_transform,
st->begin(Mesh::PRIMITIVE_TRIANGLES);
st->set_material(lightmap_surfaces[i].material);
st->set_meta("name", lightmap_surfaces[i].name);
+
+ for (int custom_i = 0; custom_i < RS::ARRAY_CUSTOM_COUNT; custom_i++) {
+ st->set_custom_format(custom_i, (SurfaceTool::CustomFormat)((lightmap_surfaces[i].format >> custom_shift[custom_i]) & RS::ARRAY_FORMAT_CUSTOM_MASK));
+ }
surfaces_tools.push_back(st); //stay there
}
+ //remove surfaces
+ clear();
+
print_verbose("Mesh: Gen indices: " + itos(gen_index_count));
//go through all indices
@@ -1232,6 +1237,11 @@ Error ImporterMesh::lightmap_unwrap_cached(const Transform3D &p_base_transform,
if (lightmap_surfaces[surface].format & Mesh::ARRAY_FORMAT_WEIGHTS) {
surfaces_tools[surface]->set_weights(v.weights);
}
+ for (int custom_i = 0; custom_i < RS::ARRAY_CUSTOM_COUNT; custom_i++) {
+ if ((lightmap_surfaces[surface].format >> custom_shift[custom_i]) & RS::ARRAY_FORMAT_CUSTOM_MASK) {
+ surfaces_tools[surface]->set_custom(custom_i, v.custom[custom_i]);
+ }
+ }
Vector2 uv2(gen_uvs[gen_indices[i + j] * 2 + 0], gen_uvs[gen_indices[i + j] * 2 + 1]);
surfaces_tools[surface]->set_uv2(uv2);
@@ -1241,10 +1251,11 @@ Error ImporterMesh::lightmap_unwrap_cached(const Transform3D &p_base_transform,
}
//generate surfaces
- for (unsigned int i = 0; i < surfaces_tools.size(); i++) {
- surfaces_tools[i]->index();
- Array arrays = surfaces_tools[i]->commit_to_arrays();
- add_surface(surfaces_tools[i]->get_primitive_type(), arrays, Array(), Dictionary(), surfaces_tools[i]->get_material(), surfaces_tools[i]->get_meta("name"));
+ for (int i = 0; i < lightmap_surfaces.size(); i++) {
+ Ref<SurfaceTool> &tool = surfaces_tools[i];
+ tool->index();
+ Array arrays = tool->commit_to_arrays();
+ add_surface(tool->get_primitive_type(), arrays, Array(), Dictionary(), tool->get_material(), tool->get_meta("name"), lightmap_surfaces[i].format);
}
set_lightmap_size_hint(Size2(size_x, size_y));
diff --git a/scene/resources/material.cpp b/scene/resources/material.cpp
index d5c3f7730b..7e84814ab3 100644
--- a/scene/resources/material.cpp
+++ b/scene/resources/material.cpp
@@ -113,6 +113,12 @@ bool Material::_can_use_render_priority() const {
return ret;
}
+Ref<Resource> Material::create_placeholder() const {
+ Ref<PlaceholderMaterial> placeholder;
+ placeholder.instantiate();
+ return placeholder;
+}
+
void Material::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_next_pass", "next_pass"), &Material::set_next_pass);
ClassDB::bind_method(D_METHOD("get_next_pass"), &Material::get_next_pass);
@@ -123,6 +129,8 @@ void Material::_bind_methods() {
ClassDB::bind_method(D_METHOD("inspect_native_shader_code"), &Material::inspect_native_shader_code);
ClassDB::set_method_flags(get_class_static(), _scs_create("inspect_native_shader_code"), METHOD_FLAGS_DEFAULT | METHOD_FLAG_EDITOR);
+ ClassDB::bind_method(D_METHOD("create_placeholder"), &Material::create_placeholder);
+
ADD_PROPERTY(PropertyInfo(Variant::INT, "render_priority", PROPERTY_HINT_RANGE, itos(RENDER_PRIORITY_MIN) + "," + itos(RENDER_PRIORITY_MAX) + ",1"), "set_render_priority", "get_render_priority");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "next_pass", PROPERTY_HINT_RESOURCE_TYPE, "Material"), "set_next_pass", "get_next_pass");
@@ -149,11 +157,36 @@ Material::~Material() {
bool ShaderMaterial::_set(const StringName &p_name, const Variant &p_value) {
if (shader.is_valid()) {
- StringName pr = shader->remap_parameter(p_name);
- if (pr) {
- set_shader_parameter(pr, p_value);
+ const StringName *sn = remap_cache.getptr(p_name);
+ if (sn) {
+ set_shader_parameter(*sn, p_value);
return true;
}
+ String s = p_name;
+ if (s.begins_with("shader_parameter/")) {
+ String param = s.replace_first("shader_parameter/", "");
+ remap_cache[s] = param;
+ set_shader_parameter(param, p_value);
+ return true;
+ }
+#ifndef DISABLE_DEPRECATED
+ // Compatibility remaps are only needed here.
+ if (s.begins_with("param/")) {
+ s = s.replace_first("param/", "shader_parameter/");
+ } else if (s.begins_with("shader_param/")) {
+ s = s.replace_first("shader_param/", "shader_parameter/");
+ } else if (s.begins_with("shader_uniform/")) {
+ s = s.replace_first("shader_uniform/", "shader_parameter/");
+ } else {
+ return false; // Not a shader parameter.
+ }
+
+ WARN_PRINT("This material (containing shader with path: '" + shader->get_path() + "') uses an old deprecated parameter names. Consider re-saving this resource (or scene which contains it) in order for it to continue working in future versions.");
+ String param = s.replace_first("shader_parameter/", "");
+ remap_cache[s] = param;
+ set_shader_parameter(param, p_value);
+ return true;
+#endif
}
return false;
@@ -161,9 +194,10 @@ bool ShaderMaterial::_set(const StringName &p_name, const Variant &p_value) {
bool ShaderMaterial::_get(const StringName &p_name, Variant &r_ret) const {
if (shader.is_valid()) {
- StringName pr = shader->remap_parameter(p_name);
- if (pr) {
- r_ret = get_shader_parameter(pr);
+ const StringName *sn = remap_cache.getptr(p_name);
+ if (sn) {
+ // Only return a parameter if it was previously set.
+ r_ret = get_shader_parameter(*sn);
return true;
}
}
@@ -247,6 +281,12 @@ void ShaderMaterial::_get_property_list(List<PropertyInfo> *p_list) const {
PropertyInfo info = E->get();
info.name = "shader_parameter/" + info.name;
+ if (!param_cache.has(E->get().name)) {
+ // Property has never been edited, retrieve with default value.
+ Variant default_value = RenderingServer::get_singleton()->shader_get_parameter_default(shader->get_rid(), E->get().name);
+ param_cache.insert(E->get().name, default_value);
+ remap_cache.insert(info.name, E->get().name);
+ }
groups[last_group][last_subgroup].push_back(info);
}
@@ -275,11 +315,10 @@ void ShaderMaterial::_get_property_list(List<PropertyInfo> *p_list) const {
bool ShaderMaterial::_property_can_revert(const StringName &p_name) const {
if (shader.is_valid()) {
- StringName pr = shader->remap_parameter(p_name);
+ const StringName *pr = remap_cache.getptr(p_name);
if (pr) {
- Variant default_value = RenderingServer::get_singleton()->shader_get_parameter_default(shader->get_rid(), pr);
- Variant current_value;
- _get(p_name, current_value);
+ Variant default_value = RenderingServer::get_singleton()->shader_get_parameter_default(shader->get_rid(), *pr);
+ Variant current_value = get_shader_parameter(*pr);
return default_value.get_type() != Variant::NIL && default_value != current_value;
}
}
@@ -288,9 +327,9 @@ bool ShaderMaterial::_property_can_revert(const StringName &p_name) const {
bool ShaderMaterial::_property_get_revert(const StringName &p_name, Variant &r_property) const {
if (shader.is_valid()) {
- StringName pr = shader->remap_parameter(p_name);
- if (pr) {
- r_property = RenderingServer::get_singleton()->shader_get_parameter_default(shader->get_rid(), pr);
+ const StringName *pr = remap_cache.getptr(p_name);
+ if (*pr) {
+ r_property = RenderingServer::get_singleton()->shader_get_parameter_default(shader->get_rid(), *pr);
return true;
}
}
@@ -791,6 +830,14 @@ void BaseMaterial3D::_update_shader() {
code += "uniform vec4 refraction_texture_channel;\n";
}
+ if (features[FEATURE_REFRACTION]) {
+ code += "uniform sampler2D screen_texture : hint_screen_texture, repeat_disable, filter_linear_mipmap;";
+ }
+
+ if (proximity_fade_enabled) {
+ code += "uniform sampler2D depth_texture : hint_depth_texture, repeat_disable, filter_nearest;";
+ }
+
if (features[FEATURE_NORMAL_MAPPING]) {
code += "uniform sampler2D texture_normal : hint_roughness_normal," + texfilter_str + ";\n";
code += "uniform float normal_scale : hint_range(-16,16);\n";
@@ -1228,7 +1275,7 @@ void BaseMaterial3D::_update_shader() {
code += " vec2 ref_ofs = SCREEN_UV - ref_normal.xy * dot(texture(texture_refraction,base_uv),refraction_texture_channel) * refraction;\n";
}
code += " float ref_amount = 1.0 - albedo.a * albedo_tex.a;\n";
- code += " EMISSION += textureLod(SCREEN_TEXTURE,ref_ofs,ROUGHNESS * 8.0).rgb * ref_amount;\n";
+ code += " EMISSION += textureLod(screen_texture,ref_ofs,ROUGHNESS * 8.0).rgb * ref_amount;\n";
code += " ALBEDO *= 1.0 - ref_amount;\n";
code += " ALPHA = 1.0;\n";
@@ -1246,7 +1293,7 @@ void BaseMaterial3D::_update_shader() {
}
if (proximity_fade_enabled) {
- code += " float depth_tex = textureLod(DEPTH_TEXTURE,SCREEN_UV,0.0).r;\n";
+ code += " float depth_tex = textureLod(depth_texture,SCREEN_UV,0.0).r;\n";
code += " vec4 world_pos = INV_PROJECTION_MATRIX * vec4(SCREEN_UV*2.0-1.0,depth_tex,1.0);\n";
code += " world_pos.xyz/=world_pos.w;\n";
code += " ALPHA*=clamp(1.0-smoothstep(world_pos.z+proximity_fade_distance,world_pos.z,VERTEX.z),0.0,1.0);\n";
@@ -2269,71 +2316,51 @@ BaseMaterial3D::TextureChannel BaseMaterial3D::get_refraction_texture_channel()
return refraction_texture_channel;
}
-Ref<Material> BaseMaterial3D::get_material_for_2d(bool p_shaded, bool p_transparent, bool p_double_sided, bool p_cut_alpha, bool p_opaque_prepass, bool p_billboard, bool p_billboard_y, bool p_msdf, bool p_no_depth, bool p_fixed_size, TextureFilter p_filter, RID *r_shader_rid) {
- int64_t hash = 0;
- if (p_shaded) {
- hash |= 1 << 0;
- }
- if (p_transparent) {
- hash |= 1 << 1;
- }
- if (p_cut_alpha) {
- hash |= 1 << 2;
- }
- if (p_opaque_prepass) {
- hash |= 1 << 3;
- }
- if (p_double_sided) {
- hash |= 1 << 4;
- }
- if (p_billboard) {
- hash |= 1 << 5;
- }
- if (p_billboard_y) {
- hash |= 1 << 6;
- }
- if (p_msdf) {
- hash |= 1 << 7;
- }
- if (p_no_depth) {
- hash |= 1 << 8;
- }
- if (p_fixed_size) {
- hash |= 1 << 9;
- }
- hash = hash_murmur3_one_64(p_filter, hash);
-
- if (materials_for_2d.has(hash)) {
+Ref<Material> BaseMaterial3D::get_material_for_2d(bool p_shaded, Transparency p_transparency, bool p_double_sided, bool p_billboard, bool p_billboard_y, bool p_msdf, bool p_no_depth, bool p_fixed_size, TextureFilter p_filter, AlphaAntiAliasing p_alpha_antialiasing_mode, RID *r_shader_rid) {
+ uint64_t key = 0;
+ key |= ((int8_t)p_shaded & 0x01) << 0;
+ key |= ((int8_t)p_transparency & 0x07) << 1; // Bits 1-3.
+ key |= ((int8_t)p_double_sided & 0x01) << 4;
+ key |= ((int8_t)p_billboard & 0x01) << 5;
+ key |= ((int8_t)p_billboard_y & 0x01) << 6;
+ key |= ((int8_t)p_msdf & 0x01) << 7;
+ key |= ((int8_t)p_no_depth & 0x01) << 8;
+ key |= ((int8_t)p_fixed_size & 0x01) << 9;
+ key |= ((int8_t)p_filter & 0x07) << 10; // Bits 10-12.
+ key |= ((int8_t)p_alpha_antialiasing_mode & 0x07) << 13; // Bits 13-15.
+
+ if (materials_for_2d.has(key)) {
if (r_shader_rid) {
- *r_shader_rid = materials_for_2d[hash]->get_shader_rid();
+ *r_shader_rid = materials_for_2d[key]->get_shader_rid();
}
- return materials_for_2d[hash];
+ return materials_for_2d[key];
}
Ref<StandardMaterial3D> material;
material.instantiate();
material->set_shading_mode(p_shaded ? SHADING_MODE_PER_PIXEL : SHADING_MODE_UNSHADED);
- material->set_transparency(p_transparent ? (p_opaque_prepass ? TRANSPARENCY_ALPHA_DEPTH_PRE_PASS : (p_cut_alpha ? TRANSPARENCY_ALPHA_SCISSOR : TRANSPARENCY_ALPHA)) : TRANSPARENCY_DISABLED);
+ material->set_transparency(p_transparency);
material->set_cull_mode(p_double_sided ? CULL_DISABLED : CULL_BACK);
material->set_flag(FLAG_SRGB_VERTEX_COLOR, true);
material->set_flag(FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
material->set_flag(FLAG_ALBEDO_TEXTURE_MSDF, p_msdf);
material->set_flag(FLAG_DISABLE_DEPTH_TEST, p_no_depth);
material->set_flag(FLAG_FIXED_SIZE, p_fixed_size);
+ material->set_alpha_antialiasing(p_alpha_antialiasing_mode);
material->set_texture_filter(p_filter);
if (p_billboard || p_billboard_y) {
material->set_flag(FLAG_BILLBOARD_KEEP_SCALE, true);
material->set_billboard_mode(p_billboard_y ? BILLBOARD_FIXED_Y : BILLBOARD_ENABLED);
}
- materials_for_2d[hash] = material;
+ materials_for_2d[key] = material;
if (r_shader_rid) {
- *r_shader_rid = materials_for_2d[hash]->get_shader_rid();
+ *r_shader_rid = materials_for_2d[key]->get_shader_rid();
}
- return materials_for_2d[hash];
+ return materials_for_2d[key];
}
void BaseMaterial3D::set_on_top_of_alpha() {
diff --git a/scene/resources/material.h b/scene/resources/material.h
index f1777d31f4..5ea9a807d4 100644
--- a/scene/resources/material.h
+++ b/scene/resources/material.h
@@ -74,6 +74,9 @@ public:
virtual RID get_rid() const override;
virtual RID get_shader_rid() const;
virtual Shader::Mode get_shader_mode() const;
+
+ virtual Ref<Resource> create_placeholder() const;
+
Material();
virtual ~Material();
};
@@ -82,7 +85,8 @@ class ShaderMaterial : public Material {
GDCLASS(ShaderMaterial, Material);
Ref<Shader> shader;
- HashMap<StringName, Variant> param_cache;
+ mutable HashMap<StringName, StringName> remap_cache;
+ mutable HashMap<StringName, Variant> param_cache;
protected:
bool _set(const StringName &p_name, const Variant &p_value);
@@ -756,7 +760,7 @@ public:
static void finish_shaders();
static void flush_changes();
- static Ref<Material> get_material_for_2d(bool p_shaded, bool p_transparent, bool p_double_sided, bool p_cut_alpha, bool p_opaque_prepass, bool p_billboard = false, bool p_billboard_y = false, bool p_msdf = false, bool p_no_depth = false, bool p_fixed_size = false, TextureFilter p_filter = TEXTURE_FILTER_LINEAR_WITH_MIPMAPS, RID *r_shader_rid = nullptr);
+ static Ref<Material> get_material_for_2d(bool p_shaded, Transparency p_transparency, bool p_double_sided, bool p_billboard = false, bool p_billboard_y = false, bool p_msdf = false, bool p_no_depth = false, bool p_fixed_size = false, TextureFilter p_filter = TEXTURE_FILTER_LINEAR_WITH_MIPMAPS, AlphaAntiAliasing p_alpha_antialiasing_mode = ALPHA_ANTIALIASING_OFF, RID *r_shader_rid = nullptr);
virtual RID get_shader_rid() const override;
diff --git a/scene/resources/mesh.cpp b/scene/resources/mesh.cpp
index 07baa0ad96..cf9baa2907 100644
--- a/scene/resources/mesh.cpp
+++ b/scene/resources/mesh.cpp
@@ -75,7 +75,7 @@ Dictionary Mesh::surface_get_lods(int p_surface) const {
return ret;
}
-uint32_t Mesh::surface_get_format(int p_idx) const {
+BitField<Mesh::ArrayFormat> Mesh::surface_get_format(int p_idx) const {
uint32_t ret = 0;
GDVIRTUAL_REQUIRED_CALL(_surface_get_format, p_idx, ret);
return ret;
@@ -189,6 +189,7 @@ Ref<TriangleMesh> Mesh::generate_triangle_mesh() const {
if (primitive == PRIMITIVE_TRIANGLES) {
for (int j = 0; j < ic; j++) {
int index = ir[j];
+ ERR_FAIL_COND_V(index >= vc, Ref<TriangleMesh>());
facesw[widx++] = vr[index];
}
} else { // PRIMITIVE_TRIANGLE_STRIP
@@ -614,6 +615,13 @@ Size2i Mesh::get_lightmap_size_hint() const {
return lightmap_size_hint;
}
+Ref<Resource> Mesh::create_placeholder() const {
+ Ref<PlaceholderMesh> placeholder;
+ placeholder.instantiate();
+ placeholder->set_aabb(get_aabb());
+ return placeholder;
+}
+
void Mesh::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_lightmap_size_hint", "size"), &Mesh::set_lightmap_size_hint);
ClassDB::bind_method(D_METHOD("get_lightmap_size_hint"), &Mesh::get_lightmap_size_hint);
@@ -626,6 +634,7 @@ void Mesh::_bind_methods() {
ClassDB::bind_method(D_METHOD("surface_get_blend_shape_arrays", "surf_idx"), &Mesh::surface_get_blend_shape_arrays);
ClassDB::bind_method(D_METHOD("surface_set_material", "surf_idx", "material"), &Mesh::surface_set_material);
ClassDB::bind_method(D_METHOD("surface_get_material", "surf_idx"), &Mesh::surface_get_material);
+ ClassDB::bind_method(D_METHOD("create_placeholder"), &Mesh::create_placeholder);
BIND_ENUM_CONSTANT(PRIMITIVE_POINTS);
BIND_ENUM_CONSTANT(PRIMITIVE_LINES);
@@ -658,35 +667,36 @@ void Mesh::_bind_methods() {
BIND_ENUM_CONSTANT(ARRAY_CUSTOM_RGBA_FLOAT);
BIND_ENUM_CONSTANT(ARRAY_CUSTOM_MAX);
- BIND_ENUM_CONSTANT(ARRAY_FORMAT_VERTEX);
- BIND_ENUM_CONSTANT(ARRAY_FORMAT_NORMAL);
- BIND_ENUM_CONSTANT(ARRAY_FORMAT_TANGENT);
- BIND_ENUM_CONSTANT(ARRAY_FORMAT_COLOR);
- BIND_ENUM_CONSTANT(ARRAY_FORMAT_TEX_UV);
- BIND_ENUM_CONSTANT(ARRAY_FORMAT_TEX_UV2);
- BIND_ENUM_CONSTANT(ARRAY_FORMAT_CUSTOM0);
- BIND_ENUM_CONSTANT(ARRAY_FORMAT_CUSTOM1);
- BIND_ENUM_CONSTANT(ARRAY_FORMAT_CUSTOM2);
- BIND_ENUM_CONSTANT(ARRAY_FORMAT_CUSTOM3);
- BIND_ENUM_CONSTANT(ARRAY_FORMAT_BONES);
- BIND_ENUM_CONSTANT(ARRAY_FORMAT_WEIGHTS);
- BIND_ENUM_CONSTANT(ARRAY_FORMAT_INDEX);
-
- BIND_ENUM_CONSTANT(ARRAY_FORMAT_BLEND_SHAPE_MASK);
-
- BIND_ENUM_CONSTANT(ARRAY_FORMAT_CUSTOM_BASE);
- BIND_ENUM_CONSTANT(ARRAY_FORMAT_CUSTOM_BITS);
- BIND_ENUM_CONSTANT(ARRAY_FORMAT_CUSTOM0_SHIFT);
- BIND_ENUM_CONSTANT(ARRAY_FORMAT_CUSTOM1_SHIFT);
- BIND_ENUM_CONSTANT(ARRAY_FORMAT_CUSTOM2_SHIFT);
- BIND_ENUM_CONSTANT(ARRAY_FORMAT_CUSTOM3_SHIFT);
-
- BIND_ENUM_CONSTANT(ARRAY_FORMAT_CUSTOM_MASK);
- BIND_ENUM_CONSTANT(ARRAY_COMPRESS_FLAGS_BASE);
-
- BIND_ENUM_CONSTANT(ARRAY_FLAG_USE_2D_VERTICES);
- BIND_ENUM_CONSTANT(ARRAY_FLAG_USE_DYNAMIC_UPDATE);
- BIND_ENUM_CONSTANT(ARRAY_FLAG_USE_8_BONE_WEIGHTS);
+ BIND_BITFIELD_FLAG(ARRAY_FORMAT_VERTEX);
+ BIND_BITFIELD_FLAG(ARRAY_FORMAT_NORMAL);
+ BIND_BITFIELD_FLAG(ARRAY_FORMAT_TANGENT);
+ BIND_BITFIELD_FLAG(ARRAY_FORMAT_COLOR);
+ BIND_BITFIELD_FLAG(ARRAY_FORMAT_TEX_UV);
+ BIND_BITFIELD_FLAG(ARRAY_FORMAT_TEX_UV2);
+ BIND_BITFIELD_FLAG(ARRAY_FORMAT_CUSTOM0);
+ BIND_BITFIELD_FLAG(ARRAY_FORMAT_CUSTOM1);
+ BIND_BITFIELD_FLAG(ARRAY_FORMAT_CUSTOM2);
+ BIND_BITFIELD_FLAG(ARRAY_FORMAT_CUSTOM3);
+ BIND_BITFIELD_FLAG(ARRAY_FORMAT_BONES);
+ BIND_BITFIELD_FLAG(ARRAY_FORMAT_WEIGHTS);
+ BIND_BITFIELD_FLAG(ARRAY_FORMAT_INDEX);
+
+ BIND_BITFIELD_FLAG(ARRAY_FORMAT_BLEND_SHAPE_MASK);
+
+ BIND_BITFIELD_FLAG(ARRAY_FORMAT_CUSTOM_BASE);
+ BIND_BITFIELD_FLAG(ARRAY_FORMAT_CUSTOM_BITS);
+ BIND_BITFIELD_FLAG(ARRAY_FORMAT_CUSTOM0_SHIFT);
+ BIND_BITFIELD_FLAG(ARRAY_FORMAT_CUSTOM1_SHIFT);
+ BIND_BITFIELD_FLAG(ARRAY_FORMAT_CUSTOM2_SHIFT);
+ BIND_BITFIELD_FLAG(ARRAY_FORMAT_CUSTOM3_SHIFT);
+
+ BIND_BITFIELD_FLAG(ARRAY_FORMAT_CUSTOM_MASK);
+ BIND_BITFIELD_FLAG(ARRAY_COMPRESS_FLAGS_BASE);
+
+ BIND_BITFIELD_FLAG(ARRAY_FLAG_USE_2D_VERTICES);
+ BIND_BITFIELD_FLAG(ARRAY_FLAG_USE_DYNAMIC_UPDATE);
+ BIND_BITFIELD_FLAG(ARRAY_FLAG_USE_8_BONE_WEIGHTS);
+ BIND_BITFIELD_FLAG(ARRAY_FLAG_USES_EMPTY_VERTEX_ARRAY);
BIND_ENUM_CONSTANT(BLEND_SHAPE_MODE_NORMALIZED);
BIND_ENUM_CONSTANT(BLEND_SHAPE_MODE_RELATIVE);
@@ -1120,17 +1130,6 @@ bool ArrayMesh::_set(const StringName &p_name, const Variant &p_value) {
}
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);
@@ -1554,7 +1553,8 @@ void ArrayMesh::_recompute_aabb() {
}
// TODO: Need to add binding to add_surface using future MeshSurfaceData object.
-void ArrayMesh::add_surface(uint32_t p_format, PrimitiveType p_primitive, const Vector<uint8_t> &p_array, const Vector<uint8_t> &p_attribute_array, const Vector<uint8_t> &p_skin_array, int p_vertex_count, const Vector<uint8_t> &p_index_array, int p_index_count, const AABB &p_aabb, const Vector<uint8_t> &p_blend_shape_data, const Vector<AABB> &p_bone_aabbs, const Vector<RS::SurfaceData::LOD> &p_lods) {
+void ArrayMesh::add_surface(BitField<ArrayFormat> p_format, PrimitiveType p_primitive, const Vector<uint8_t> &p_array, const Vector<uint8_t> &p_attribute_array, const Vector<uint8_t> &p_skin_array, int p_vertex_count, const Vector<uint8_t> &p_index_array, int p_index_count, const AABB &p_aabb, const Vector<uint8_t> &p_blend_shape_data, const Vector<AABB> &p_bone_aabbs, const Vector<RS::SurfaceData::LOD> &p_lods) {
+ ERR_FAIL_COND(surfaces.size() == RS::MAX_MESH_SURFACES);
_create_if_empty();
Surface s;
@@ -1589,7 +1589,8 @@ void ArrayMesh::add_surface(uint32_t p_format, PrimitiveType p_primitive, const
emit_changed();
}
-void ArrayMesh::add_surface_from_arrays(PrimitiveType p_primitive, const Array &p_arrays, const TypedArray<Array> &p_blend_shapes, const Dictionary &p_lods, uint32_t p_flags) {
+void ArrayMesh::add_surface_from_arrays(PrimitiveType p_primitive, const Array &p_arrays, const TypedArray<Array> &p_blend_shapes, const Dictionary &p_lods, BitField<ArrayFormat> p_flags) {
+ ERR_FAIL_COND(p_blend_shapes.size() != blend_shapes.size());
ERR_FAIL_COND(p_arrays.size() != ARRAY_MAX);
RS::SurfaceData surface;
@@ -1705,7 +1706,7 @@ int ArrayMesh::surface_get_array_index_len(int p_idx) const {
return surfaces[p_idx].index_array_length;
}
-uint32_t ArrayMesh::surface_get_format(int p_idx) const {
+BitField<Mesh::ArrayFormat> ArrayMesh::surface_get_format(int p_idx) const {
ERR_FAIL_INDEX_V(p_idx, surfaces.size(), 0);
return surfaces[p_idx].format;
}
@@ -2058,7 +2059,7 @@ void ArrayMesh::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_blend_shape_mode", "mode"), &ArrayMesh::set_blend_shape_mode);
ClassDB::bind_method(D_METHOD("get_blend_shape_mode"), &ArrayMesh::get_blend_shape_mode);
- ClassDB::bind_method(D_METHOD("add_surface_from_arrays", "primitive", "arrays", "blend_shapes", "lods", "compress_flags"), &ArrayMesh::add_surface_from_arrays, DEFVAL(Array()), DEFVAL(Dictionary()), DEFVAL(0));
+ ClassDB::bind_method(D_METHOD("add_surface_from_arrays", "primitive", "arrays", "blend_shapes", "lods", "flags"), &ArrayMesh::add_surface_from_arrays, DEFVAL(Array()), DEFVAL(Dictionary()), DEFVAL(0));
ClassDB::bind_method(D_METHOD("clear_surfaces"), &ArrayMesh::clear_surfaces);
ClassDB::bind_method(D_METHOD("surface_update_vertex_region", "surf_idx", "offset", "data"), &ArrayMesh::surface_update_vertex_region);
ClassDB::bind_method(D_METHOD("surface_update_attribute_region", "surf_idx", "offset", "data"), &ArrayMesh::surface_update_attribute_region);
diff --git a/scene/resources/mesh.h b/scene/resources/mesh.h
index f62f060682..1b870d996a 100644
--- a/scene/resources/mesh.h
+++ b/scene/resources/mesh.h
@@ -156,7 +156,7 @@ public:
virtual Array surface_get_arrays(int p_surface) const;
virtual TypedArray<Array> surface_get_blend_shape_arrays(int p_surface) const;
virtual Dictionary surface_get_lods(int p_surface) const;
- virtual uint32_t surface_get_format(int p_idx) const;
+ virtual BitField<ArrayFormat> surface_get_format(int p_idx) const;
virtual PrimitiveType surface_get_primitive_type(int p_idx) const;
virtual void surface_set_material(int p_idx, const Ref<Material> &p_material);
virtual Ref<Material> surface_get_material(int p_idx) const;
@@ -220,6 +220,8 @@ public:
virtual int get_builtin_bind_pose_count() const;
virtual Transform3D get_builtin_bind_pose(int p_index) const;
+ virtual Ref<Resource> create_placeholder() const;
+
Mesh();
};
@@ -269,9 +271,9 @@ protected:
static void _bind_methods();
public:
- void add_surface_from_arrays(PrimitiveType p_primitive, const Array &p_arrays, const TypedArray<Array> &p_blend_shapes = TypedArray<Array>(), const Dictionary &p_lods = Dictionary(), uint32_t p_flags = 0);
+ void add_surface_from_arrays(PrimitiveType p_primitive, const Array &p_arrays, const TypedArray<Array> &p_blend_shapes = TypedArray<Array>(), const Dictionary &p_lods = Dictionary(), BitField<ArrayFormat> p_flags = 0);
- void add_surface(uint32_t p_format, PrimitiveType p_primitive, const Vector<uint8_t> &p_array, const Vector<uint8_t> &p_attribute_array, const Vector<uint8_t> &p_skin_array, int p_vertex_count, const Vector<uint8_t> &p_index_array, int p_index_count, const AABB &p_aabb, const Vector<uint8_t> &p_blend_shape_data = Vector<uint8_t>(), const Vector<AABB> &p_bone_aabbs = Vector<AABB>(), const Vector<RS::SurfaceData::LOD> &p_lods = Vector<RS::SurfaceData::LOD>());
+ void add_surface(BitField<ArrayFormat> p_format, PrimitiveType p_primitive, const Vector<uint8_t> &p_array, const Vector<uint8_t> &p_attribute_array, const Vector<uint8_t> &p_skin_array, int p_vertex_count, const Vector<uint8_t> &p_index_array, int p_index_count, const AABB &p_aabb, const Vector<uint8_t> &p_blend_shape_data = Vector<uint8_t>(), const Vector<AABB> &p_bone_aabbs = Vector<AABB>(), const Vector<RS::SurfaceData::LOD> &p_lods = Vector<RS::SurfaceData::LOD>());
Array surface_get_arrays(int p_surface) const override;
TypedArray<Array> surface_get_blend_shape_arrays(int p_surface) const override;
@@ -298,7 +300,7 @@ public:
int surface_get_array_len(int p_idx) const override;
int surface_get_array_index_len(int p_idx) const override;
- uint32_t surface_get_format(int p_idx) const override;
+ BitField<ArrayFormat> surface_get_format(int p_idx) const override;
PrimitiveType surface_get_primitive_type(int p_idx) const override;
virtual void surface_set_material(int p_idx, const Ref<Material> &p_material) override;
@@ -330,7 +332,7 @@ public:
};
VARIANT_ENUM_CAST(Mesh::ArrayType);
-VARIANT_ENUM_CAST(Mesh::ArrayFormat);
+VARIANT_BITFIELD_CAST(Mesh::ArrayFormat);
VARIANT_ENUM_CAST(Mesh::ArrayCustomFormat);
VARIANT_ENUM_CAST(Mesh::PrimitiveType);
VARIANT_ENUM_CAST(Mesh::BlendShapeMode);
@@ -351,7 +353,7 @@ public:
virtual Array surface_get_arrays(int p_surface) const override { return Array(); }
virtual TypedArray<Array> surface_get_blend_shape_arrays(int p_surface) const override { return TypedArray<Array>(); }
virtual Dictionary surface_get_lods(int p_surface) const override { return Dictionary(); }
- virtual uint32_t surface_get_format(int p_idx) const override { return 0; }
+ virtual BitField<ArrayFormat> surface_get_format(int p_idx) const override { return 0; }
virtual PrimitiveType surface_get_primitive_type(int p_idx) const override { return PRIMITIVE_TRIANGLES; }
virtual void surface_set_material(int p_idx, const Ref<Material> &p_material) override {}
virtual Ref<Material> surface_get_material(int p_idx) const override { return Ref<Material>(); }
diff --git a/scene/resources/mesh_library.cpp b/scene/resources/mesh_library.cpp
index d45b8a9295..015eb0fa45 100644
--- a/scene/resources/mesh_library.cpp
+++ b/scene/resources/mesh_library.cpp
@@ -139,7 +139,6 @@ void MeshLibrary::set_item_name(int p_item, const String &p_name) {
ERR_FAIL_COND_MSG(!item_map.has(p_item), "Requested for nonexistent MeshLibrary item '" + itos(p_item) + "'.");
item_map[p_item].name = p_name;
emit_changed();
- notify_property_list_changed();
}
void MeshLibrary::set_item_mesh(int p_item, const Ref<Mesh> &p_mesh) {
@@ -155,7 +154,6 @@ void MeshLibrary::set_item_mesh_transform(int p_item, const Transform3D &p_trans
item_map[p_item].mesh_transform = p_transform;
notify_change_to_owners();
emit_changed();
- notify_property_list_changed();
}
void MeshLibrary::set_item_shapes(int p_item, const Vector<ShapeData> &p_shapes) {
@@ -190,7 +188,6 @@ void MeshLibrary::set_item_navigation_layers(int p_item, uint32_t p_navigation_l
notify_property_list_changed();
notify_change_to_owners();
emit_changed();
- notify_property_list_changed();
}
void MeshLibrary::set_item_preview(int p_item, const Ref<Texture2D> &p_preview) {
diff --git a/scene/resources/navigation_mesh.cpp b/scene/resources/navigation_mesh.cpp
index 287597de32..1d13f07b12 100644
--- a/scene/resources/navigation_mesh.cpp
+++ b/scene/resources/navigation_mesh.cpp
@@ -278,7 +278,7 @@ bool NavigationMesh::get_filter_walkable_low_height_spans() const {
void NavigationMesh::set_filter_baking_aabb(const AABB &p_aabb) {
filter_baking_aabb = p_aabb;
- notify_property_list_changed();
+ emit_changed();
}
AABB NavigationMesh::get_filter_baking_aabb() const {
@@ -287,7 +287,7 @@ AABB NavigationMesh::get_filter_baking_aabb() const {
void NavigationMesh::set_filter_baking_aabb_offset(const Vector3 &p_aabb_offset) {
filter_baking_aabb_offset = p_aabb_offset;
- notify_property_list_changed();
+ emit_changed();
}
Vector3 NavigationMesh::get_filter_baking_aabb_offset() const {
@@ -401,7 +401,7 @@ Ref<ArrayMesh> NavigationMesh::get_debug_mesh() {
}
debug_mesh->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, face_mesh_array);
- Ref<StandardMaterial3D> debug_geometry_face_material = NavigationServer3D::get_singleton_mut()->get_debug_navigation_geometry_face_material();
+ Ref<StandardMaterial3D> debug_geometry_face_material = NavigationServer3D::get_singleton()->get_debug_navigation_geometry_face_material();
debug_mesh->surface_set_material(0, debug_geometry_face_material);
// if enabled build geometry edge line surface
@@ -426,7 +426,7 @@ Ref<ArrayMesh> NavigationMesh::get_debug_mesh() {
line_mesh_array.resize(Mesh::ARRAY_MAX);
line_mesh_array[Mesh::ARRAY_VERTEX] = line_vertex_array;
debug_mesh->add_surface_from_arrays(Mesh::PRIMITIVE_LINES, line_mesh_array);
- Ref<StandardMaterial3D> debug_geometry_edge_material = NavigationServer3D::get_singleton_mut()->get_debug_navigation_geometry_edge_material();
+ Ref<StandardMaterial3D> debug_geometry_edge_material = NavigationServer3D::get_singleton()->get_debug_navigation_geometry_edge_material();
debug_mesh->surface_set_material(1, debug_geometry_edge_material);
}
diff --git a/scene/resources/packed_scene.cpp b/scene/resources/packed_scene.cpp
index 514e7eb260..1e9038139e 100644
--- a/scene/resources/packed_scene.cpp
+++ b/scene/resources/packed_scene.cpp
@@ -43,7 +43,7 @@
#include "scene/main/missing_node.h"
#include "scene/property_utils.h"
-#define PACKED_SCENE_VERSION 2
+#define PACKED_SCENE_VERSION 3
#define META_POINTER_PROPERTY_BASE "metadata/_editor_prop_ptr_"
bool SceneState::can_instantiate() const {
return nodes.size() > 0;
@@ -314,7 +314,19 @@ Node *SceneState::instantiate(GenEditState p_edit_state) const {
//must make a copy, because this res is local to scene
}
}
- } else if (p_edit_state == GEN_EDIT_STATE_INSTANCE) {
+ }
+ if (value.get_type() == Variant::ARRAY) {
+ Array set_array = value;
+ bool is_get_valid = false;
+ Variant get_value = node->get(snames[nprops[j].name], &is_get_valid);
+ if (is_get_valid && get_value.get_type() == Variant::ARRAY) {
+ Array get_array = get_value;
+ if (!set_array.is_same_typed(get_array)) {
+ value = Array(set_array, get_array.get_typed_builtin(), get_array.get_typed_class_name(), get_array.get_typed_script());
+ }
+ }
+ }
+ if (p_edit_state == GEN_EDIT_STATE_INSTANCE && value.get_type() != Variant::OBJECT) {
value = value.duplicate(true); // Duplicate arrays and dictionaries for the editor
}
@@ -402,8 +414,7 @@ Node *SceneState::instantiate(GenEditState p_edit_state) const {
}
}
- for (uint32_t i = 0; i < deferred_node_paths.size(); i++) {
- const DeferredNodePathProperties &dnp = deferred_node_paths[i];
+ for (const DeferredNodePathProperties &dnp : deferred_node_paths) {
Node *other = dnp.base->get_node_or_null(dnp.path);
dnp.base->set(dnp.property, other);
}
@@ -1047,6 +1058,25 @@ Ref<SceneState> SceneState::get_base_scene_state() const {
return Ref<SceneState>();
}
+void SceneState::update_instance_resource(String p_path, Ref<PackedScene> p_packed_scene) {
+ ERR_FAIL_COND(p_packed_scene.is_null());
+
+ for (const NodeData &nd : nodes) {
+ if (nd.instance >= 0) {
+ if (!(nd.instance & FLAG_INSTANCE_IS_PLACEHOLDER)) {
+ int instance_id = nd.instance & FLAG_MASK;
+ Ref<PackedScene> original_packed_scene = variants[instance_id];
+ if (original_packed_scene.is_valid()) {
+ if (original_packed_scene->get_path() == p_path) {
+ variants.remove_at(instance_id);
+ variants.insert(instance_id, p_packed_scene);
+ }
+ }
+ }
+ }
+ }
+}
+
int SceneState::find_node_by_path(const NodePath &p_node) const {
ERR_FAIL_COND_V_MSG(node_path_cache.size() == 0, -1, "This operation requires the node cache to have been built.");
@@ -1264,6 +1294,9 @@ void SceneState::set_bundled_scene(const Dictionary &p_dictionary) {
for (int j = 0; j < cd.binds.size(); j++) {
cd.binds.write[j] = r[idx++];
}
+ if (version >= 3) {
+ cd.unbinds = r[idx++];
+ }
}
}
@@ -1350,6 +1383,7 @@ Dictionary SceneState::get_bundled_scene() const {
for (int j = 0; j < cd.binds.size(); j++) {
rconns.push_back(cd.binds[j]);
}
+ rconns.push_back(cd.unbinds);
}
d["conns"] = rconns;
diff --git a/scene/resources/packed_scene.h b/scene/resources/packed_scene.h
index ef7363dd44..5c53ffdb45 100644
--- a/scene/resources/packed_scene.h
+++ b/scene/resources/packed_scene.h
@@ -150,6 +150,8 @@ public:
Ref<SceneState> get_base_scene_state() const;
+ void update_instance_resource(String p_path, Ref<PackedScene> p_packed_scene);
+
//unbuild API
int get_node_count() const;
diff --git a/scene/resources/particle_process_material.cpp b/scene/resources/particle_process_material.cpp
index a7f48b92fe..7ae154ea1d 100644
--- a/scene/resources/particle_process_material.cpp
+++ b/scene/resources/particle_process_material.cpp
@@ -1756,8 +1756,8 @@ void ParticleProcessMaterial::_bind_methods() {
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "anim_speed_min", PROPERTY_HINT_RANGE, "0,16,0.01,or_less,or_greater"), "set_param_min", "get_param_min", PARAM_ANIM_SPEED);
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "anim_speed_max", PROPERTY_HINT_RANGE, "0,16,0.01,or_less,or_greater"), "set_param_max", "get_param_max", PARAM_ANIM_SPEED);
ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "anim_speed_curve", PROPERTY_HINT_RESOURCE_TYPE, "CurveTexture"), "set_param_texture", "get_param_texture", PARAM_ANIM_SPEED);
- ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "anim_offset_min", PROPERTY_HINT_RANGE, "0,16,0.01,or_less,or_greater"), "set_param_min", "get_param_min", PARAM_ANIM_OFFSET);
- ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "anim_offset_max", PROPERTY_HINT_RANGE, "0,16,0.01,or_less,or_greater"), "set_param_max", "get_param_max", PARAM_ANIM_OFFSET);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "anim_offset_min", PROPERTY_HINT_RANGE, "0,1,0.0001"), "set_param_min", "get_param_min", PARAM_ANIM_OFFSET);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "anim_offset_max", PROPERTY_HINT_RANGE, "0,1,0.0001"), "set_param_max", "get_param_max", PARAM_ANIM_OFFSET);
ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "anim_offset_curve", PROPERTY_HINT_RESOURCE_TYPE, "CurveTexture"), "set_param_texture", "get_param_texture", PARAM_ANIM_OFFSET);
ADD_GROUP("Sub Emitter", "sub_emitter_");
diff --git a/scene/resources/polygon_path_finder.cpp b/scene/resources/polygon_path_finder.cpp
index 85106883f9..3bbd0a0b5e 100644
--- a/scene/resources/polygon_path_finder.cpp
+++ b/scene/resources/polygon_path_finder.cpp
@@ -325,7 +325,7 @@ Vector<Vector2> PolygonPathFinder::find_path(const Vector2 &p_from, const Vector
}
const Point &np = points[least_cost_point];
- //open the neighbours for search
+ //open the neighbors for search
for (const int &E : np.connections) {
Point &p = points.write[E];
@@ -339,7 +339,7 @@ Vector<Vector2> PolygonPathFinder::find_path(const Vector2 &p_from, const Vector
p.distance = distance;
}
} else {
- //add to open neighbours
+ //add to open neighbors
p.prev = least_cost_point;
p.distance = distance;
diff --git a/scene/resources/primitive_meshes.cpp b/scene/resources/primitive_meshes.cpp
index b6e953dd56..ef1f6459e9 100644
--- a/scene/resources/primitive_meshes.cpp
+++ b/scene/resources/primitive_meshes.cpp
@@ -180,7 +180,7 @@ TypedArray<Array> PrimitiveMesh::surface_get_blend_shape_arrays(int p_surface) c
return TypedArray<Array>(); //not really supported
}
-uint32_t PrimitiveMesh::surface_get_format(int p_idx) const {
+BitField<Mesh::ArrayFormat> PrimitiveMesh::surface_get_format(int p_idx) const {
ERR_FAIL_INDEX_V(p_idx, 1, 0);
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;
@@ -257,7 +257,7 @@ void PrimitiveMesh::_bind_methods() {
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");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "uv2_padding", PROPERTY_HINT_RANGE, "0,10,0.01,or_greater"), "set_uv2_padding", "get_uv2_padding");
GDVIRTUAL_BIND(_create_mesh_array);
}
@@ -2901,7 +2901,7 @@ void TextMesh::_create_mesh_array(Array &p_arr) const {
TS->shaped_text_set_spacing(text_rid, TextServer::SpacingType(i), font->get_spacing(TextServer::SpacingType(i)));
}
- Array stt;
+ TypedArray<Vector3i> stt;
if (st_parser == TextServer::STRUCTURED_TEXT_CUSTOM) {
GDVIRTUAL_CALL(_structured_text_parser, st_args, txt, stt);
} else {
diff --git a/scene/resources/primitive_meshes.h b/scene/resources/primitive_meshes.h
index c1c51b350b..e62f26b17c 100644
--- a/scene/resources/primitive_meshes.h
+++ b/scene/resources/primitive_meshes.h
@@ -84,7 +84,7 @@ public:
virtual Array surface_get_arrays(int p_surface) const override;
virtual TypedArray<Array> surface_get_blend_shape_arrays(int p_surface) const override;
virtual Dictionary surface_get_lods(int p_surface) const override;
- virtual uint32_t surface_get_format(int p_idx) const override;
+ virtual BitField<ArrayFormat> surface_get_format(int p_idx) const override;
virtual Mesh::PrimitiveType surface_get_primitive_type(int p_idx) const override;
virtual void surface_set_material(int p_idx, const Ref<Material> &p_material) override;
virtual Ref<Material> surface_get_material(int p_idx) const override;
@@ -622,7 +622,7 @@ protected:
virtual void _create_mesh_array(Array &p_arr) const override;
public:
- GDVIRTUAL2RC(Array, _structured_text_parser, Array, String)
+ GDVIRTUAL2RC(TypedArray<Vector3i>, _structured_text_parser, Array, String)
TextMesh();
~TextMesh();
diff --git a/scene/resources/rectangle_shape_2d.cpp b/scene/resources/rectangle_shape_2d.cpp
index 84c147b4b4..65b1653293 100644
--- a/scene/resources/rectangle_shape_2d.cpp
+++ b/scene/resources/rectangle_shape_2d.cpp
@@ -79,11 +79,7 @@ void RectangleShape2D::draw(const RID &p_to_rid, const Color &p_color) {
stroke_points.write[3] = Vector2(-size.x, size.y) * 0.5;
stroke_points.write[4] = -size * 0.5;
- Vector<Color> stroke_colors;
- stroke_colors.resize(5);
- for (int i = 0; i < 5; i++) {
- stroke_colors.write[i] = (p_color);
- }
+ Vector<Color> stroke_colors = { Color(p_color, 1.0) };
RenderingServer::get_singleton()->canvas_item_add_polyline(p_to_rid, stroke_points, stroke_colors);
}
diff --git a/scene/resources/resource_format_text.cpp b/scene/resources/resource_format_text.cpp
index ade8875935..448e800900 100644
--- a/scene/resources/resource_format_text.cpp
+++ b/scene/resources/resource_format_text.cpp
@@ -49,10 +49,6 @@
///
-void ResourceLoaderText::set_local_path(const String &p_local_path) {
- res_path = p_local_path;
-}
-
Ref<Resource> ResourceLoaderText::get_resource() {
return resource;
}
@@ -449,10 +445,10 @@ Error ResourceLoaderText::load() {
#ifdef TOOLS_ENABLED
// Silence a warning that can happen during the initial filesystem scan due to cache being regenerated.
if (ResourceLoader::get_resource_uid(path) != uid) {
- WARN_PRINT(String(res_path + ":" + itos(lines) + " - ext_resource, invalid UUID: " + uidt + " - using text path instead: " + path).utf8().get_data());
+ WARN_PRINT(String(res_path + ":" + itos(lines) + " - ext_resource, invalid UID: " + uidt + " - using text path instead: " + path).utf8().get_data());
}
#else
- WARN_PRINT(String(res_path + ":" + itos(lines) + " - ext_resource, invalid UUID: " + uidt + " - using text path instead: " + path).utf8().get_data());
+ WARN_PRINT(String(res_path + ":" + itos(lines) + " - ext_resource, invalid UID: " + uidt + " - using text path instead: " + path).utf8().get_data());
#endif
}
}
@@ -601,14 +597,16 @@ Error ResourceLoaderText::load() {
resource_current++;
- int_resources[id] = res; //always assign int resources
+ if (progress && resources_total > 0) {
+ *progress = resource_current / float(resources_total);
+ }
+
+ int_resources[id] = res; // Always assign int resources.
if (do_assign) {
- if (cache_mode == ResourceFormatLoader::CACHE_MODE_IGNORE) {
- res->set_path(path);
- } else {
+ if (cache_mode != ResourceFormatLoader::CACHE_MODE_IGNORE) {
res->set_path(path, cache_mode == ResourceFormatLoader::CACHE_MODE_REPLACE);
- res->set_scene_unique_id(id);
}
+ res->set_scene_unique_id(id);
}
Dictionary missing_resource_properties;
@@ -640,6 +638,18 @@ Error ResourceLoaderText::load() {
}
}
+ if (value.get_type() == Variant::ARRAY) {
+ Array set_array = value;
+ bool is_get_valid = false;
+ Variant get_value = res->get(assign, &is_get_valid);
+ if (is_get_valid && get_value.get_type() == Variant::ARRAY) {
+ Array get_array = get_value;
+ if (!set_array.is_same_typed(get_array)) {
+ value = Array(set_array, get_array.get_typed_builtin(), get_array.get_typed_class_name(), get_array.get_typed_script());
+ }
+ }
+ }
+
if (set_valid) {
res->set(assign, value);
}
@@ -663,10 +673,6 @@ Error ResourceLoaderText::load() {
if (!missing_resource_properties.is_empty()) {
res->set_meta(META_MISSING_RESOURCES, missing_resource_properties);
}
-
- if (progress && resources_total > 0) {
- *progress = resource_current / float(resources_total);
- }
}
while (true) {
@@ -716,8 +722,6 @@ Error ResourceLoaderText::load() {
resource = Ref<Resource>(r);
}
- resource_current++;
-
Dictionary missing_resource_properties;
while (true) {
@@ -756,6 +760,18 @@ Error ResourceLoaderText::load() {
}
}
+ if (value.get_type() == Variant::ARRAY) {
+ Array set_array = value;
+ bool is_get_valid = false;
+ Variant get_value = resource->get(assign, &is_get_valid);
+ if (is_get_valid && get_value.get_type() == Variant::ARRAY) {
+ Array get_array = get_value;
+ if (!set_array.is_same_typed(get_array)) {
+ value = Array(set_array, get_array.get_typed_builtin(), get_array.get_typed_class_name(), get_array.get_typed_script());
+ }
+ }
+ }
+
if (set_valid) {
resource->set(assign, value);
}
@@ -770,6 +786,12 @@ Error ResourceLoaderText::load() {
}
}
+ resource_current++;
+
+ if (progress && resources_total > 0) {
+ *progress = resource_current / float(resources_total);
+ }
+
if (missing_resource) {
missing_resource->set_recording_properties(false);
}
@@ -779,9 +801,6 @@ Error ResourceLoaderText::load() {
}
error = OK;
- if (progress && resources_total > 0) {
- *progress = resource_current / float(resources_total);
- }
return error;
}
@@ -930,7 +949,11 @@ Error ResourceLoaderText::rename_dependencies(Ref<FileAccess> p_f, const String
if (is_scene) {
fw->store_line("[gd_scene load_steps=" + itos(resources_total) + " format=" + itos(FORMAT_VERSION) + "]\n");
} else {
- fw->store_line("[gd_resource type=\"" + res_type + "\" load_steps=" + itos(resources_total) + " format=" + itos(FORMAT_VERSION) + "]\n");
+ String script_res_text;
+ if (!script_class.is_empty()) {
+ script_res_text = "script_class=\"" + script_class + "\" ";
+ }
+ fw->store_line("[gd_resource type=\"" + res_type + "\" " + script_res_text + "load_steps=" + itos(resources_total) + " format=" + itos(FORMAT_VERSION) + "]\n");
}
}
@@ -1054,6 +1077,10 @@ void ResourceLoaderText::open(Ref<FileAccess> p_f, bool p_skip_first_tag) {
return;
}
+ if (tag.fields.has("script_class")) {
+ script_class = tag.fields["script_class"];
+ }
+
res_type = tag.fields["type"];
} else {
@@ -1500,6 +1527,44 @@ Error ResourceLoaderText::get_classes_used(HashSet<StringName> *r_classes) {
return OK;
}
+String ResourceLoaderText::recognize_script_class(Ref<FileAccess> p_f) {
+ error = OK;
+
+ lines = 1;
+ f = p_f;
+
+ stream.f = f;
+
+ ignore_resource_parsing = true;
+
+ VariantParser::Tag tag;
+ Error err = VariantParser::parse_tag(&stream, lines, error_text, tag);
+
+ if (err) {
+ _printerr();
+ return "";
+ }
+
+ if (tag.fields.has("format")) {
+ int fmt = tag.fields["format"];
+ if (fmt > FORMAT_VERSION) {
+ error_text = "Saved with newer format version";
+ _printerr();
+ return "";
+ }
+ }
+
+ if (tag.name != "gd_resource") {
+ return "";
+ }
+
+ if (tag.fields.has("script_class")) {
+ return tag.fields["script_class"];
+ }
+
+ return "";
+}
+
String ResourceLoaderText::recognize(Ref<FileAccess> p_f) {
error = OK;
@@ -1669,6 +1734,25 @@ String ResourceFormatLoaderText::get_resource_type(const String &p_path) const {
return ClassDB::get_compatibility_remapped_class(r);
}
+String ResourceFormatLoaderText::get_resource_script_class(const String &p_path) const {
+ String ext = p_path.get_extension().to_lower();
+ if (ext != "tres") {
+ return String();
+ }
+
+ // ...for anything else must test...
+
+ Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ);
+ if (f.is_null()) {
+ return ""; //could not read
+ }
+
+ ResourceLoaderText loader;
+ loader.local_path = ProjectSettings::get_singleton()->localize_path(p_path);
+ loader.res_path = loader.local_path;
+ return loader.recognize_script_class(f);
+}
+
ResourceUID::ID ResourceFormatLoaderText::get_resource_uid(const String &p_path) const {
String ext = p_path.get_extension().to_lower();
@@ -1849,6 +1933,9 @@ void ResourceFormatSaverTextInstance::_find_resources(const Variant &p_variant,
List<Variant> keys;
d.get_key_list(&keys);
for (const Variant &E : keys) {
+ // Of course keys should also be cached, after all we can't prevent users from using resources as keys, right?
+ // See also ResourceFormatSaverBinaryInstance::_find_resources (when p_variant is of type Variant::DICTIONARY)
+ _find_resources(E);
Variant v = d[E];
_find_resources(v);
}
@@ -1909,7 +1996,12 @@ Error ResourceFormatSaverTextInstance::save(const String &p_path, const Ref<Reso
String title = packed_scene.is_valid() ? "[gd_scene " : "[gd_resource ";
if (packed_scene.is_null()) {
title += "type=\"" + _resource_get_class(p_resource) + "\" ";
+ Ref<Script> script = p_resource->get_script();
+ if (script.is_valid() && script->get_global_name()) {
+ title += "script_class=\"" + String(script->get_global_name()) + "\" ";
+ }
}
+
int load_steps = saved_resources.size() + external_resources.size();
if (load_steps > 1) {
@@ -2237,6 +2329,40 @@ Error ResourceFormatSaverTextInstance::save(const String &p_path, const Ref<Reso
return OK;
}
+Error ResourceLoaderText::set_uid(Ref<FileAccess> p_f, ResourceUID::ID p_uid) {
+ open(p_f, true);
+ ERR_FAIL_COND_V(error != OK, error);
+ ignore_resource_parsing = true;
+
+ Ref<FileAccess> fw;
+
+ fw = FileAccess::open(local_path + ".uidren", FileAccess::WRITE);
+ if (is_scene) {
+ fw->store_string("[gd_scene load_steps=" + itos(resources_total) + " format=" + itos(FORMAT_VERSION) + " uid=\"" + ResourceUID::get_singleton()->id_to_text(p_uid) + "\"]");
+ } else {
+ String script_res_text;
+ if (!script_class.is_empty()) {
+ script_res_text = "script_class=\"" + script_class + "\" ";
+ }
+
+ fw->store_string("[gd_resource type=\"" + res_type + "\" " + script_res_text + "load_steps=" + itos(resources_total) + " format=" + itos(FORMAT_VERSION) + " uid=\"" + ResourceUID::get_singleton()->id_to_text(p_uid) + "\"]");
+ }
+
+ uint8_t c = f->get_8();
+ while (!f->eof_reached()) {
+ fw->store_8(c);
+ c = f->get_8();
+ }
+
+ bool all_ok = fw->get_error() == OK;
+
+ if (!all_ok) {
+ return ERR_CANT_CREATE;
+ }
+
+ return OK;
+}
+
Error ResourceFormatSaverText::save(const Ref<Resource> &p_resource, const String &p_path, uint32_t p_flags) {
if (p_path.ends_with(".tscn") && !Ref<PackedScene>(p_resource).is_valid()) {
return ERR_FILE_UNRECOGNIZED;
@@ -2246,6 +2372,35 @@ Error ResourceFormatSaverText::save(const Ref<Resource> &p_resource, const Strin
return saver.save(p_path, p_resource, p_flags);
}
+Error ResourceFormatSaverText::set_uid(const String &p_path, ResourceUID::ID p_uid) {
+ String lc = p_path.to_lower();
+ if (!lc.ends_with(".tscn") && !lc.ends_with(".tres")) {
+ return ERR_FILE_UNRECOGNIZED;
+ }
+
+ String local_path = ProjectSettings::get_singleton()->localize_path(p_path);
+ Error err = OK;
+ {
+ Ref<FileAccess> file = FileAccess::open(p_path, FileAccess::READ);
+ if (file.is_null()) {
+ ERR_FAIL_V(ERR_CANT_OPEN);
+ }
+
+ ResourceLoaderText loader;
+ loader.local_path = local_path;
+ loader.res_path = loader.local_path;
+ err = loader.set_uid(file, p_uid);
+ }
+
+ if (err == OK) {
+ Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
+ da->remove(local_path);
+ da->rename(local_path + ".uidren", local_path);
+ }
+
+ return err;
+}
+
bool ResourceFormatSaverText::recognize(const Ref<Resource> &p_resource) const {
return true; // All resources recognized!
}
diff --git a/scene/resources/resource_format_text.h b/scene/resources/resource_format_text.h
index f96511fb74..25001d8023 100644
--- a/scene/resources/resource_format_text.h
+++ b/scene/resources/resource_format_text.h
@@ -64,6 +64,7 @@ class ResourceLoaderText {
int resources_total = 0;
int resource_current = 0;
String resource_type;
+ String script_class;
VariantParser::Tag next_tag;
@@ -106,6 +107,7 @@ class ResourceLoaderText {
VariantParser::ResourceParser rp;
friend class ResourceFormatLoaderText;
+ friend class ResourceFormatSaverText;
Error error = OK;
@@ -114,15 +116,16 @@ class ResourceLoaderText {
Ref<PackedScene> _parse_node_tag(VariantParser::ResourceParser &parser);
public:
- void set_local_path(const String &p_local_path);
Ref<Resource> get_resource();
Error load();
+ Error set_uid(Ref<FileAccess> p_f, ResourceUID::ID p_uid);
int get_stage() const;
int get_stage_count() const;
void set_translation_remapped(bool p_remapped);
void open(Ref<FileAccess> p_f, bool p_skip_first_tag = false);
String recognize(Ref<FileAccess> p_f);
+ String recognize_script_class(Ref<FileAccess> p_f);
ResourceUID::ID get_uid(Ref<FileAccess> p_f);
void get_dependencies(Ref<FileAccess> p_f, List<String> *p_dependencies, bool p_add_types);
Error rename_dependencies(Ref<FileAccess> p_f, const String &p_path, const HashMap<String, String> &p_map);
@@ -142,6 +145,7 @@ public:
virtual void get_classes_used(const String &p_path, HashSet<StringName> *r_classes);
virtual String get_resource_type(const String &p_path) const;
+ virtual String get_resource_script_class(const String &p_path) const;
virtual ResourceUID::ID get_resource_uid(const String &p_path) const;
virtual void get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types = false);
virtual Error rename_dependencies(const String &p_path, const HashMap<String, String> &p_map);
@@ -195,6 +199,7 @@ class ResourceFormatSaverText : public ResourceFormatSaver {
public:
static ResourceFormatSaverText *singleton;
virtual Error save(const Ref<Resource> &p_resource, const String &p_path, uint32_t p_flags = 0);
+ virtual Error set_uid(const String &p_path, ResourceUID::ID p_uid);
virtual bool recognize(const Ref<Resource> &p_resource) const;
virtual void get_recognized_extensions(const Ref<Resource> &p_resource, List<String> *p_extensions) const;
diff --git a/scene/resources/shader.cpp b/scene/resources/shader.cpp
index 9bb2db17ab..fd2be9ba22 100644
--- a/scene/resources/shader.cpp
+++ b/scene/resources/shader.cpp
@@ -42,10 +42,12 @@ Shader::Mode Shader::get_mode() const {
}
void Shader::_dependency_changed() {
- RenderingServer::get_singleton()->shader_set_code(shader, RenderingServer::get_singleton()->shader_get_code(shader));
- params_cache_dirty = true;
+ // Preprocess and compile the code again because a dependency has changed. It also calls emit_changed() for us.
+ _recompile();
+}
- emit_changed();
+void Shader::_recompile() {
+ set_code(get_code());
}
void Shader::set_path(const String &p_path, bool p_take_over) {
@@ -53,6 +55,12 @@ void Shader::set_path(const String &p_path, bool p_take_over) {
RS::get_singleton()->shader_set_path_hint(shader, p_path);
}
+void Shader::set_include_path(const String &p_path) {
+ // Used only if the shader does not have a resource path set,
+ // for example during loading stage or when created by code.
+ include_path = p_path;
+}
+
void Shader::set_code(const String &p_code) {
for (Ref<ShaderInclude> E : include_dependencies) {
E->disconnect(SNAME("changed"), callable_mp(this, &Shader::_dependency_changed));
@@ -78,11 +86,15 @@ void Shader::set_code(const String &p_code) {
HashSet<Ref<ShaderInclude>> new_include_dependencies;
{
+ String path = get_path();
+ if (path.is_empty()) {
+ path = include_path;
+ }
// Preprocessor must run here and not in the server because:
// 1) Need to keep track of include dependencies at resource level
// 2) Server does not do interaction with Resource filetypes, this is a scene level feature.
ShaderPreprocessor preprocessor;
- preprocessor.preprocess(p_code, "", pp_code, nullptr, nullptr, nullptr, &new_include_dependencies);
+ preprocessor.preprocess(p_code, path, pp_code, nullptr, nullptr, nullptr, &new_include_dependencies);
}
// This ensures previous include resources are not freed and then re-loaded during parse (which would make compiling slower)
@@ -93,7 +105,6 @@ void Shader::set_code(const String &p_code) {
}
RenderingServer::get_singleton()->shader_set_code(shader, pp_code);
- params_cache_dirty = true;
emit_changed();
}
@@ -108,8 +119,6 @@ void Shader::get_shader_uniform_list(List<PropertyInfo> *p_params, bool p_get_gr
List<PropertyInfo> local;
RenderingServer::get_singleton()->get_shader_parameter_list(shader, &local);
- params_cache.clear();
- params_cache_dirty = false;
for (PropertyInfo &pi : local) {
bool is_group = pi.usage == PROPERTY_USAGE_GROUP || pi.usage == PROPERTY_USAGE_SUBGROUP;
@@ -120,7 +129,6 @@ void Shader::get_shader_uniform_list(List<PropertyInfo> *p_params, bool p_get_gr
if (default_textures.has(pi.name)) { //do not show default textures
continue;
}
- params_cache[pi.name] = pi.name;
}
if (p_params) {
//small little hack
@@ -176,11 +184,17 @@ bool Shader::is_text_shader() const {
return true;
}
-bool Shader::has_parameter(const StringName &p_name) const {
- return params_cache.has(p_name);
+void Shader::_update_shader() const {
}
-void Shader::_update_shader() const {
+Array Shader::_get_shader_uniform_list(bool p_get_groups) {
+ List<PropertyInfo> uniform_list;
+ get_shader_uniform_list(&uniform_list, p_get_groups);
+ Array ret;
+ for (const PropertyInfo &pi : uniform_list) {
+ ret.push_back(pi.operator Dictionary());
+ }
+ return ret;
}
void Shader::_bind_methods() {
@@ -192,7 +206,7 @@ void Shader::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_default_texture_parameter", "name", "texture", "index"), &Shader::set_default_texture_parameter, DEFVAL(0));
ClassDB::bind_method(D_METHOD("get_default_texture_parameter", "name", "index"), &Shader::get_default_texture_parameter, DEFVAL(0));
- ClassDB::bind_method(D_METHOD("has_parameter", "name"), &Shader::has_parameter);
+ ClassDB::bind_method(D_METHOD("get_shader_uniform_list", "get_groups"), &Shader::_get_shader_uniform_list, DEFVAL(false));
ADD_PROPERTY(PropertyInfo(Variant::STRING, "code", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "set_code", "get_code");
@@ -227,6 +241,7 @@ Ref<Resource> ResourceFormatLoaderShader::load(const String &p_path, const Strin
String str;
str.parse_utf8((const char *)buffer.ptr(), buffer.size());
+ shader->set_include_path(p_path);
shader->set_code(str);
if (r_error) {
diff --git a/scene/resources/shader.h b/scene/resources/shader.h
index e579c2fca1..ca889940ef 100644
--- a/scene/resources/shader.h
+++ b/scene/resources/shader.h
@@ -56,16 +56,15 @@ private:
Mode mode = MODE_SPATIAL;
HashSet<Ref<ShaderInclude>> include_dependencies;
String code;
+ String include_path;
- // hack the name of performance
- // shaders keep a list of ShaderMaterial -> RenderingServer name translations, to make
- // conversion fast and save memory.
- mutable bool params_cache_dirty = true;
- mutable HashMap<StringName, StringName> params_cache; //map a shader param to a material param..
HashMap<StringName, HashMap<int, Ref<Texture2D>>> default_textures;
void _dependency_changed();
+ void _recompile();
virtual void _update_shader() const; //used for visual shader
+ Array _get_shader_uniform_list(bool p_get_groups = false);
+
protected:
static void _bind_methods();
@@ -74,12 +73,12 @@ public:
virtual Mode get_mode() const;
virtual void set_path(const String &p_path, bool p_take_over = false) override;
+ void set_include_path(const String &p_path);
void set_code(const String &p_code);
String get_code() const;
void get_shader_uniform_list(List<PropertyInfo> *p_params, bool p_get_groups = false) const;
- bool has_parameter(const StringName &p_name) const;
void set_default_texture_parameter(const StringName &p_name, const Ref<Texture2D> &p_texture, int p_index = 0);
Ref<Texture2D> get_default_texture_parameter(const StringName &p_name, int p_index = 0) const;
@@ -87,47 +86,6 @@ public:
virtual bool is_text_shader() const;
- // Finds the shader parameter name for the given property name, which should start with "shader_parameter/".
- _FORCE_INLINE_ StringName remap_parameter(const StringName &p_property) const {
- if (params_cache_dirty) {
- get_shader_uniform_list(nullptr);
- }
-
- String n = p_property;
-
- // Backwards compatibility with old shader parameter names.
- // Note: The if statements are important to make sure we are only replacing text exactly at index 0.
- if (n.find("param/") == 0) {
- n = n.replace_first("param/", "shader_parameter/");
- }
- if (n.find("shader_param/") == 0) {
- n = n.replace_first("shader_param/", "shader_parameter/");
- }
- if (n.find("shader_uniform/") == 0) {
- n = n.replace_first("shader_uniform/", "shader_parameter/");
- }
-
- {
- // Additional backwards compatibility for projects between #62972 and #64092 (about a month of v4.0 development).
- // These projects did not have any prefix for shader uniforms due to a bug.
- // This code should be removed during beta or rc of 4.0.
- const HashMap<StringName, StringName>::Iterator E = params_cache.find(n);
- if (E) {
- return E->value;
- }
- }
-
- if (n.begins_with("shader_parameter/")) {
- n = n.replace_first("shader_parameter/", "");
- const HashMap<StringName, StringName>::Iterator E = params_cache.find(n);
- if (E) {
- return E->value;
- }
- }
-
- return StringName();
- }
-
virtual RID get_rid() const override;
Shader();
diff --git a/scene/resources/shader_include.cpp b/scene/resources/shader_include.cpp
index cd5e9861f7..68137cbec0 100644
--- a/scene/resources/shader_include.cpp
+++ b/scene/resources/shader_include.cpp
@@ -45,9 +45,14 @@ void ShaderInclude::set_code(const String &p_code) {
}
{
+ String path = get_path();
+ if (path.is_empty()) {
+ path = include_path;
+ }
+
String pp_code;
ShaderPreprocessor preprocessor;
- preprocessor.preprocess(p_code, "", pp_code, nullptr, nullptr, nullptr, &new_dependencies);
+ preprocessor.preprocess(p_code, path, pp_code, nullptr, nullptr, nullptr, &new_dependencies);
}
// This ensures previous include resources are not freed and then re-loaded during parse (which would make compiling slower)
@@ -64,6 +69,10 @@ String ShaderInclude::get_code() const {
return code;
}
+void ShaderInclude::set_include_path(const String &p_path) {
+ include_path = p_path;
+}
+
void ShaderInclude::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_code", "code"), &ShaderInclude::set_code);
ClassDB::bind_method(D_METHOD("get_code"), &ShaderInclude::get_code);
@@ -86,6 +95,7 @@ Ref<Resource> ResourceFormatLoaderShaderInclude::load(const String &p_path, cons
String str;
str.parse_utf8((const char *)buffer.ptr(), buffer.size());
+ shader_inc->set_include_path(p_path);
shader_inc->set_code(str);
if (r_error) {
diff --git a/scene/resources/shader_include.h b/scene/resources/shader_include.h
index 04f4f5cf84..a8949b327e 100644
--- a/scene/resources/shader_include.h
+++ b/scene/resources/shader_include.h
@@ -42,6 +42,7 @@ class ShaderInclude : public Resource {
private:
String code;
+ String include_path;
HashSet<Ref<ShaderInclude>> dependencies;
void _dependency_changed();
@@ -51,6 +52,8 @@ protected:
public:
void set_code(const String &p_text);
String get_code() const;
+
+ void set_include_path(const String &p_path);
};
class ResourceFormatLoaderShaderInclude : public ResourceFormatLoader {
diff --git a/scene/resources/skeleton_modification_2d_stackholder.cpp b/scene/resources/skeleton_modification_2d_stackholder.cpp
index 121108965b..34d31bac8a 100644
--- a/scene/resources/skeleton_modification_2d_stackholder.cpp
+++ b/scene/resources/skeleton_modification_2d_stackholder.cpp
@@ -64,7 +64,7 @@ bool SkeletonModification2DStackHolder::_get(const StringName &p_path, Variant &
}
void SkeletonModification2DStackHolder::_get_property_list(List<PropertyInfo> *p_list) const {
- p_list->push_back(PropertyInfo(Variant::OBJECT, "held_modification_stack", PROPERTY_HINT_RESOURCE_TYPE, "SkeletonModificationStack2D", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_DO_NOT_SHARE_ON_DUPLICATE));
+ p_list->push_back(PropertyInfo(Variant::OBJECT, "held_modification_stack", PROPERTY_HINT_RESOURCE_TYPE, "SkeletonModificationStack2D", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_ALWAYS_DUPLICATE));
#ifdef TOOLS_ENABLED
if (Engine::get_singleton()->is_editor_hint()) {
diff --git a/scene/resources/skeleton_modification_3d.cpp b/scene/resources/skeleton_modification_3d.cpp
deleted file mode 100644
index 92fb4bfd78..0000000000
--- a/scene/resources/skeleton_modification_3d.cpp
+++ /dev/null
@@ -1,151 +0,0 @@
-/**************************************************************************/
-/* skeleton_modification_3d.cpp */
-/**************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/**************************************************************************/
-/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
-/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
-/* */
-/* 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 "skeleton_modification_3d.h"
-#include "scene/3d/skeleton_3d.h"
-
-void SkeletonModification3D::_execute(real_t p_delta) {
- GDVIRTUAL_CALL(_execute, p_delta);
-
- if (!enabled) {
- return;
- }
-}
-
-void SkeletonModification3D::_setup_modification(SkeletonModificationStack3D *p_stack) {
- stack = p_stack;
- if (stack) {
- is_setup = true;
- } else {
- WARN_PRINT("Could not setup modification with name " + this->get_name());
- }
-
- GDVIRTUAL_CALL(_setup_modification, Ref<SkeletonModificationStack3D>(p_stack));
-}
-
-void SkeletonModification3D::set_enabled(bool p_enabled) {
- enabled = p_enabled;
-}
-
-bool SkeletonModification3D::get_enabled() {
- return enabled;
-}
-
-// Helper function. Needed for CCDIK.
-real_t SkeletonModification3D::clamp_angle(real_t p_angle, real_t p_min_bound, real_t p_max_bound, bool p_invert) {
- // Map to the 0 to 360 range (in radians though) instead of the -180 to 180 range.
- if (p_angle < 0) {
- p_angle = Math_TAU + p_angle;
- }
-
- // Make min and max in the range of 0 to 360 (in radians), and make sure they are in the right order
- if (p_min_bound < 0) {
- p_min_bound = Math_TAU + p_min_bound;
- }
- if (p_max_bound < 0) {
- p_max_bound = Math_TAU + p_max_bound;
- }
- if (p_min_bound > p_max_bound) {
- SWAP(p_min_bound, p_max_bound);
- }
-
- bool is_beyond_bounds = (p_angle < p_min_bound || p_angle > p_max_bound);
- bool is_within_bounds = (p_angle > p_min_bound && p_angle < p_max_bound);
-
- // Note: May not be the most optimal way to clamp, but it always constraints to the nearest angle.
- if ((!p_invert && is_beyond_bounds) || (p_invert && is_within_bounds)) {
- Vector2 min_bound_vec = Vector2(Math::cos(p_min_bound), Math::sin(p_min_bound));
- Vector2 max_bound_vec = Vector2(Math::cos(p_max_bound), Math::sin(p_max_bound));
- Vector2 angle_vec = Vector2(Math::cos(p_angle), Math::sin(p_angle));
-
- if (angle_vec.distance_squared_to(min_bound_vec) <= angle_vec.distance_squared_to(max_bound_vec)) {
- p_angle = p_min_bound;
- } else {
- p_angle = p_max_bound;
- }
- }
-
- return p_angle;
-}
-
-bool SkeletonModification3D::_print_execution_error(bool p_condition, String p_message) {
- // If the modification is not setup, don't bother printing the error
- if (!is_setup) {
- return p_condition;
- }
-
- if (p_condition && !execution_error_found) {
- ERR_PRINT(p_message);
- execution_error_found = true;
- }
- return p_condition;
-}
-
-Ref<SkeletonModificationStack3D> SkeletonModification3D::get_modification_stack() {
- return stack;
-}
-
-void SkeletonModification3D::set_is_setup(bool p_is_setup) {
- is_setup = p_is_setup;
-}
-
-bool SkeletonModification3D::get_is_setup() const {
- return is_setup;
-}
-
-void SkeletonModification3D::set_execution_mode(int p_mode) {
- execution_mode = p_mode;
-}
-
-int SkeletonModification3D::get_execution_mode() const {
- return execution_mode;
-}
-
-void SkeletonModification3D::_bind_methods() {
- GDVIRTUAL_BIND(_execute, "delta");
- GDVIRTUAL_BIND(_setup_modification, "modification_stack")
-
- ClassDB::bind_method(D_METHOD("set_enabled", "enabled"), &SkeletonModification3D::set_enabled);
- ClassDB::bind_method(D_METHOD("get_enabled"), &SkeletonModification3D::get_enabled);
- ClassDB::bind_method(D_METHOD("get_modification_stack"), &SkeletonModification3D::get_modification_stack);
- ClassDB::bind_method(D_METHOD("set_is_setup", "is_setup"), &SkeletonModification3D::set_is_setup);
- ClassDB::bind_method(D_METHOD("get_is_setup"), &SkeletonModification3D::get_is_setup);
- ClassDB::bind_method(D_METHOD("set_execution_mode", "execution_mode"), &SkeletonModification3D::set_execution_mode);
- ClassDB::bind_method(D_METHOD("get_execution_mode"), &SkeletonModification3D::get_execution_mode);
- ClassDB::bind_method(D_METHOD("clamp_angle", "angle", "min", "max", "invert"), &SkeletonModification3D::clamp_angle);
-
- ADD_PROPERTY(PropertyInfo(Variant::BOOL, "enabled"), "set_enabled", "get_enabled");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "execution_mode", PROPERTY_HINT_ENUM, "process,physics_process"), "set_execution_mode", "get_execution_mode");
-}
-
-SkeletonModification3D::SkeletonModification3D() {
- stack = nullptr;
- is_setup = false;
-}
diff --git a/scene/resources/skeleton_modification_3d.h b/scene/resources/skeleton_modification_3d.h
deleted file mode 100644
index 367adbd977..0000000000
--- a/scene/resources/skeleton_modification_3d.h
+++ /dev/null
@@ -1,79 +0,0 @@
-/**************************************************************************/
-/* skeleton_modification_3d.h */
-/**************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/**************************************************************************/
-/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
-/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
-/* */
-/* 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 SKELETON_MODIFICATION_3D_H
-#define SKELETON_MODIFICATION_3D_H
-
-#include "scene/3d/skeleton_3d.h"
-#include "scene/resources/skeleton_modification_stack_3d.h"
-
-class SkeletonModificationStack3D;
-
-class SkeletonModification3D : public Resource {
- GDCLASS(SkeletonModification3D, Resource);
- friend class Skeleton3D;
- friend class SkeletonModificationStack3D;
-
-protected:
- static void _bind_methods();
-
- SkeletonModificationStack3D *stack = nullptr;
- int execution_mode = 0; // 0 = process
-
- bool enabled = true;
- bool is_setup = false;
- bool execution_error_found = false;
-
- bool _print_execution_error(bool p_condition, String p_message);
-
- GDVIRTUAL1(_execute, double)
- GDVIRTUAL1(_setup_modification, Ref<SkeletonModificationStack3D>)
-
-public:
- virtual void _execute(real_t p_delta);
- virtual void _setup_modification(SkeletonModificationStack3D *p_stack);
-
- real_t clamp_angle(real_t p_angle, real_t p_min_bound, real_t p_max_bound, bool p_invert);
-
- void set_enabled(bool p_enabled);
- bool get_enabled();
-
- void set_execution_mode(int p_mode);
- int get_execution_mode() const;
-
- Ref<SkeletonModificationStack3D> get_modification_stack();
-
- void set_is_setup(bool p_setup);
- bool get_is_setup() const;
-
- SkeletonModification3D();
-};
-
-#endif // SKELETON_MODIFICATION_3D_H
diff --git a/scene/resources/skeleton_modification_3d_ccdik.cpp b/scene/resources/skeleton_modification_3d_ccdik.cpp
deleted file mode 100644
index b5c930f970..0000000000
--- a/scene/resources/skeleton_modification_3d_ccdik.cpp
+++ /dev/null
@@ -1,474 +0,0 @@
-/**************************************************************************/
-/* skeleton_modification_3d_ccdik.cpp */
-/**************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/**************************************************************************/
-/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
-/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
-/* */
-/* 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 "scene/resources/skeleton_modification_3d_ccdik.h"
-#include "scene/3d/skeleton_3d.h"
-#include "scene/resources/skeleton_modification_3d.h"
-
-bool SkeletonModification3DCCDIK::_set(const StringName &p_path, const Variant &p_value) {
- String path = p_path;
-
- if (path.begins_with("joint_data/")) {
- int ccdik_data_size = ccdik_data_chain.size();
- int which = path.get_slicec('/', 1).to_int();
- String what = path.get_slicec('/', 2);
- ERR_FAIL_INDEX_V(which, ccdik_data_size, false);
-
- if (what == "bone_name") {
- set_ccdik_joint_bone_name(which, p_value);
- } else if (what == "bone_index") {
- set_ccdik_joint_bone_index(which, p_value);
- } else if (what == "ccdik_axis") {
- set_ccdik_joint_ccdik_axis(which, p_value);
- } else if (what == "enable_joint_constraint") {
- set_ccdik_joint_enable_constraint(which, p_value);
- } else if (what == "joint_constraint_angle_min") {
- set_ccdik_joint_constraint_angle_min(which, Math::deg_to_rad(real_t(p_value)));
- } else if (what == "joint_constraint_angle_max") {
- set_ccdik_joint_constraint_angle_max(which, Math::deg_to_rad(real_t(p_value)));
- } else if (what == "joint_constraint_angles_invert") {
- set_ccdik_joint_constraint_invert(which, p_value);
- }
- return true;
- }
- return true;
-}
-
-bool SkeletonModification3DCCDIK::_get(const StringName &p_path, Variant &r_ret) const {
- String path = p_path;
-
- if (path.begins_with("joint_data/")) {
- const int ccdik_data_size = ccdik_data_chain.size();
- int which = path.get_slicec('/', 1).to_int();
- String what = path.get_slicec('/', 2);
- ERR_FAIL_INDEX_V(which, ccdik_data_size, false);
-
- if (what == "bone_name") {
- r_ret = get_ccdik_joint_bone_name(which);
- } else if (what == "bone_index") {
- r_ret = get_ccdik_joint_bone_index(which);
- } else if (what == "ccdik_axis") {
- r_ret = get_ccdik_joint_ccdik_axis(which);
- } else if (what == "enable_joint_constraint") {
- r_ret = get_ccdik_joint_enable_constraint(which);
- } else if (what == "joint_constraint_angle_min") {
- r_ret = Math::rad_to_deg(get_ccdik_joint_constraint_angle_min(which));
- } else if (what == "joint_constraint_angle_max") {
- r_ret = Math::rad_to_deg(get_ccdik_joint_constraint_angle_max(which));
- } else if (what == "joint_constraint_angles_invert") {
- r_ret = get_ccdik_joint_constraint_invert(which);
- }
- return true;
- }
- return true;
-}
-
-void SkeletonModification3DCCDIK::_get_property_list(List<PropertyInfo> *p_list) const {
- for (uint32_t i = 0; i < ccdik_data_chain.size(); i++) {
- String base_string = "joint_data/" + itos(i) + "/";
-
- p_list->push_back(PropertyInfo(Variant::STRING_NAME, base_string + "bone_name", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
- p_list->push_back(PropertyInfo(Variant::INT, base_string + "bone_index", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
-
- p_list->push_back(PropertyInfo(Variant::INT, base_string + "ccdik_axis",
- PROPERTY_HINT_ENUM, "X Axis,Y Axis,Z Axis", PROPERTY_USAGE_DEFAULT));
-
- p_list->push_back(PropertyInfo(Variant::BOOL, base_string + "enable_joint_constraint", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
- if (ccdik_data_chain[i].enable_constraint) {
- p_list->push_back(PropertyInfo(Variant::FLOAT, base_string + "joint_constraint_angle_min", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
- p_list->push_back(PropertyInfo(Variant::FLOAT, base_string + "joint_constraint_angle_max", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
- p_list->push_back(PropertyInfo(Variant::BOOL, base_string + "joint_constraint_angles_invert", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
- }
- }
-}
-
-void SkeletonModification3DCCDIK::_execute(real_t p_delta) {
- ERR_FAIL_COND_MSG(!stack || !is_setup || stack->skeleton == nullptr,
- "Modification is not setup and therefore cannot execute!");
- if (!enabled) {
- return;
- }
-
- if (target_node_cache.is_null()) {
- _print_execution_error(true, "Target cache is out of date. Attempting to update");
- update_target_cache();
- return;
- }
- if (tip_node_cache.is_null()) {
- _print_execution_error(true, "Tip cache is out of date. Attempting to update");
- update_tip_cache();
- return;
- }
-
- // Reset the local bone overrides for CCDIK affected nodes
- for (uint32_t i = 0; i < ccdik_data_chain.size(); i++) {
- stack->skeleton->set_bone_local_pose_override(ccdik_data_chain[i].bone_idx,
- stack->skeleton->get_bone_local_pose_override(ccdik_data_chain[i].bone_idx),
- 0.0, false);
- }
-
- Node3D *node_target = Object::cast_to<Node3D>(ObjectDB::get_instance(target_node_cache));
- Node3D *node_tip = Object::cast_to<Node3D>(ObjectDB::get_instance(tip_node_cache));
-
- if (_print_execution_error(!node_target || !node_target->is_inside_tree(), "Target node is not in the scene tree. Cannot execute modification!")) {
- return;
- }
- if (_print_execution_error(!node_tip || !node_tip->is_inside_tree(), "Tip node is not in the scene tree. Cannot execute modification!")) {
- return;
- }
-
- if (use_high_quality_solve) {
- for (uint32_t i = 0; i < ccdik_data_chain.size(); i++) {
- for (uint32_t j = i; j < ccdik_data_chain.size(); j++) {
- _execute_ccdik_joint(j, node_target, node_tip);
- }
- }
- } else {
- for (uint32_t i = 0; i < ccdik_data_chain.size(); i++) {
- _execute_ccdik_joint(i, node_target, node_tip);
- }
- }
-
- execution_error_found = false;
-}
-
-void SkeletonModification3DCCDIK::_execute_ccdik_joint(int p_joint_idx, Node3D *p_target, Node3D *p_tip) {
- CCDIK_Joint_Data ccdik_data = ccdik_data_chain[p_joint_idx];
-
- if (_print_execution_error(ccdik_data.bone_idx < 0 || ccdik_data.bone_idx > stack->skeleton->get_bone_count(),
- "CCDIK joint: bone index for joint" + itos(p_joint_idx) + " not found. Cannot execute modification!")) {
- return;
- }
-
- Transform3D bone_trans = stack->skeleton->global_pose_to_local_pose(ccdik_data.bone_idx, stack->skeleton->get_bone_global_pose(ccdik_data.bone_idx));
- Transform3D tip_trans = stack->skeleton->global_pose_to_local_pose(ccdik_data.bone_idx, stack->skeleton->world_transform_to_global_pose(p_tip->get_global_transform()));
- Transform3D target_trans = stack->skeleton->global_pose_to_local_pose(ccdik_data.bone_idx, stack->skeleton->world_transform_to_global_pose(p_target->get_global_transform()));
-
- if (tip_trans.origin.distance_to(target_trans.origin) <= 0.01) {
- return;
- }
-
- // Inspired (and very loosely based on) by the CCDIK algorithm made by Zalo on GitHub (https://github.com/zalo/MathUtilities)
- // Convert the 3D position to a 2D position so we can use Atan2 (via the angle function)
- // to know how much rotation we need on the given axis to place the tip at the target.
- Vector2 tip_pos_2d;
- Vector2 target_pos_2d;
- if (ccdik_data.ccdik_axis == CCDIK_Axes::AXIS_X) {
- tip_pos_2d = Vector2(tip_trans.origin.y, tip_trans.origin.z);
- target_pos_2d = Vector2(target_trans.origin.y, target_trans.origin.z);
- bone_trans.basis.rotate_local(Vector3(1, 0, 0), target_pos_2d.angle() - tip_pos_2d.angle());
- } else if (ccdik_data.ccdik_axis == CCDIK_Axes::AXIS_Y) {
- tip_pos_2d = Vector2(tip_trans.origin.z, tip_trans.origin.x);
- target_pos_2d = Vector2(target_trans.origin.z, target_trans.origin.x);
- bone_trans.basis.rotate_local(Vector3(0, 1, 0), target_pos_2d.angle() - tip_pos_2d.angle());
- } else if (ccdik_data.ccdik_axis == CCDIK_Axes::AXIS_Z) {
- tip_pos_2d = Vector2(tip_trans.origin.x, tip_trans.origin.y);
- target_pos_2d = Vector2(target_trans.origin.x, target_trans.origin.y);
- bone_trans.basis.rotate_local(Vector3(0, 0, 1), target_pos_2d.angle() - tip_pos_2d.angle());
- } else {
- // Should never happen, but...
- ERR_FAIL_MSG("CCDIK joint: Unknown axis vector passed for joint" + itos(p_joint_idx) + ". Cannot execute modification!");
- }
-
- if (ccdik_data.enable_constraint) {
- Vector3 rotation_axis;
- real_t rotation_angle;
- bone_trans.basis.get_axis_angle(rotation_axis, rotation_angle);
-
- // Note: When the axis has a negative direction, the angle is OVER 180 degrees and therefore we need to account for this
- // when constraining.
- if (ccdik_data.ccdik_axis == CCDIK_Axes::AXIS_X) {
- if (rotation_axis.x < 0) {
- rotation_angle += Math_PI;
- rotation_axis = Vector3(1, 0, 0);
- }
- } else if (ccdik_data.ccdik_axis == CCDIK_Axes::AXIS_Y) {
- if (rotation_axis.y < 0) {
- rotation_angle += Math_PI;
- rotation_axis = Vector3(0, 1, 0);
- }
- } else if (ccdik_data.ccdik_axis == CCDIK_Axes::AXIS_Z) {
- if (rotation_axis.z < 0) {
- rotation_angle += Math_PI;
- rotation_axis = Vector3(0, 0, 1);
- }
- } else {
- // Should never happen, but...
- ERR_FAIL_MSG("CCDIK joint: Unknown axis vector passed for joint" + itos(p_joint_idx) + ". Cannot execute modification!");
- }
- rotation_angle = clamp_angle(rotation_angle, ccdik_data.constraint_angle_min, ccdik_data.constraint_angle_max, ccdik_data.constraint_angles_invert);
-
- bone_trans.basis.set_axis_angle(rotation_axis, rotation_angle);
- }
-
- stack->skeleton->set_bone_local_pose_override(ccdik_data.bone_idx, bone_trans, stack->strength, true);
- stack->skeleton->force_update_bone_children_transforms(ccdik_data.bone_idx);
-}
-
-void SkeletonModification3DCCDIK::_setup_modification(SkeletonModificationStack3D *p_stack) {
- stack = p_stack;
- if (stack != nullptr) {
- is_setup = true;
- execution_error_found = false;
- update_target_cache();
- update_tip_cache();
- }
-}
-
-void SkeletonModification3DCCDIK::update_target_cache() {
- if (!is_setup || !stack) {
- _print_execution_error(true, "Cannot update target cache: modification is not properly setup!");
- return;
- }
-
- target_node_cache = ObjectID();
- if (stack->skeleton) {
- if (stack->skeleton->is_inside_tree()) {
- if (stack->skeleton->has_node(target_node)) {
- Node *node = stack->skeleton->get_node(target_node);
- ERR_FAIL_COND_MSG(!node || stack->skeleton == node,
- "Cannot update target cache: node is this modification's skeleton or cannot be found!");
- ERR_FAIL_COND_MSG(!node->is_inside_tree(),
- "Cannot update target cache: node is not in scene tree!");
- target_node_cache = node->get_instance_id();
-
- execution_error_found = false;
- }
- }
- }
-}
-
-void SkeletonModification3DCCDIK::update_tip_cache() {
- if (!is_setup || !stack) {
- _print_execution_error(true, "Cannot update tip cache: modification is not properly setup!");
- return;
- }
-
- tip_node_cache = ObjectID();
- if (stack->skeleton) {
- if (stack->skeleton->is_inside_tree()) {
- if (stack->skeleton->has_node(tip_node)) {
- Node *node = stack->skeleton->get_node(tip_node);
- ERR_FAIL_COND_MSG(!node || stack->skeleton == node,
- "Cannot update tip cache: node is this modification's skeleton or cannot be found!");
- ERR_FAIL_COND_MSG(!node->is_inside_tree(),
- "Cannot update tip cache: node is not in scene tree!");
- tip_node_cache = node->get_instance_id();
-
- execution_error_found = false;
- }
- }
- }
-}
-
-void SkeletonModification3DCCDIK::set_target_node(const NodePath &p_target_node) {
- target_node = p_target_node;
- update_target_cache();
-}
-
-NodePath SkeletonModification3DCCDIK::get_target_node() const {
- return target_node;
-}
-
-void SkeletonModification3DCCDIK::set_tip_node(const NodePath &p_tip_node) {
- tip_node = p_tip_node;
- update_tip_cache();
-}
-
-NodePath SkeletonModification3DCCDIK::get_tip_node() const {
- return tip_node;
-}
-
-void SkeletonModification3DCCDIK::set_use_high_quality_solve(bool p_high_quality) {
- use_high_quality_solve = p_high_quality;
-}
-
-bool SkeletonModification3DCCDIK::get_use_high_quality_solve() const {
- return use_high_quality_solve;
-}
-
-// CCDIK joint data functions
-String SkeletonModification3DCCDIK::get_ccdik_joint_bone_name(int p_joint_idx) const {
- const int bone_chain_size = ccdik_data_chain.size();
- ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, String());
- return ccdik_data_chain[p_joint_idx].bone_name;
-}
-
-void SkeletonModification3DCCDIK::set_ccdik_joint_bone_name(int p_joint_idx, String p_bone_name) {
- const int bone_chain_size = ccdik_data_chain.size();
- ERR_FAIL_INDEX(p_joint_idx, bone_chain_size);
- ccdik_data_chain[p_joint_idx].bone_name = p_bone_name;
-
- if (stack) {
- if (stack->skeleton) {
- ccdik_data_chain[p_joint_idx].bone_idx = stack->skeleton->find_bone(p_bone_name);
- }
- }
- execution_error_found = false;
- notify_property_list_changed();
-}
-
-int SkeletonModification3DCCDIK::get_ccdik_joint_bone_index(int p_joint_idx) const {
- const int bone_chain_size = ccdik_data_chain.size();
- ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, -1);
- return ccdik_data_chain[p_joint_idx].bone_idx;
-}
-
-void SkeletonModification3DCCDIK::set_ccdik_joint_bone_index(int p_joint_idx, int p_bone_idx) {
- const int bone_chain_size = ccdik_data_chain.size();
- ERR_FAIL_INDEX(p_joint_idx, bone_chain_size);
- ERR_FAIL_COND_MSG(p_bone_idx < 0, "Bone index is out of range: The index is too low!");
- ccdik_data_chain[p_joint_idx].bone_idx = p_bone_idx;
-
- if (stack) {
- if (stack->skeleton) {
- ccdik_data_chain[p_joint_idx].bone_name = stack->skeleton->get_bone_name(p_bone_idx);
- }
- }
- execution_error_found = false;
- notify_property_list_changed();
-}
-
-int SkeletonModification3DCCDIK::get_ccdik_joint_ccdik_axis(int p_joint_idx) const {
- const int bone_chain_size = ccdik_data_chain.size();
- ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, -1);
- return ccdik_data_chain[p_joint_idx].ccdik_axis;
-}
-
-void SkeletonModification3DCCDIK::set_ccdik_joint_ccdik_axis(int p_joint_idx, int p_axis) {
- const int bone_chain_size = ccdik_data_chain.size();
- ERR_FAIL_INDEX(p_joint_idx, bone_chain_size);
- ERR_FAIL_COND_MSG(p_axis < 0, "CCDIK axis is out of range: The axis mode is too low!");
- ccdik_data_chain[p_joint_idx].ccdik_axis = p_axis;
- notify_property_list_changed();
-}
-
-bool SkeletonModification3DCCDIK::get_ccdik_joint_enable_constraint(int p_joint_idx) const {
- const int bone_chain_size = ccdik_data_chain.size();
- ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, false);
- return ccdik_data_chain[p_joint_idx].enable_constraint;
-}
-
-void SkeletonModification3DCCDIK::set_ccdik_joint_enable_constraint(int p_joint_idx, bool p_enable) {
- const int bone_chain_size = ccdik_data_chain.size();
- ERR_FAIL_INDEX(p_joint_idx, bone_chain_size);
- ccdik_data_chain[p_joint_idx].enable_constraint = p_enable;
- notify_property_list_changed();
-}
-
-real_t SkeletonModification3DCCDIK::get_ccdik_joint_constraint_angle_min(int p_joint_idx) const {
- const int bone_chain_size = ccdik_data_chain.size();
- ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, false);
- return ccdik_data_chain[p_joint_idx].constraint_angle_min;
-}
-
-void SkeletonModification3DCCDIK::set_ccdik_joint_constraint_angle_min(int p_joint_idx, real_t p_angle_min) {
- const int bone_chain_size = ccdik_data_chain.size();
- ERR_FAIL_INDEX(p_joint_idx, bone_chain_size);
- ccdik_data_chain[p_joint_idx].constraint_angle_min = p_angle_min;
-}
-
-real_t SkeletonModification3DCCDIK::get_ccdik_joint_constraint_angle_max(int p_joint_idx) const {
- const int bone_chain_size = ccdik_data_chain.size();
- ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, false);
- return ccdik_data_chain[p_joint_idx].constraint_angle_max;
-}
-
-void SkeletonModification3DCCDIK::set_ccdik_joint_constraint_angle_max(int p_joint_idx, real_t p_angle_max) {
- const int bone_chain_size = ccdik_data_chain.size();
- ERR_FAIL_INDEX(p_joint_idx, bone_chain_size);
- ccdik_data_chain[p_joint_idx].constraint_angle_max = p_angle_max;
-}
-
-bool SkeletonModification3DCCDIK::get_ccdik_joint_constraint_invert(int p_joint_idx) const {
- const int bone_chain_size = ccdik_data_chain.size();
- ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, false);
- return ccdik_data_chain[p_joint_idx].constraint_angles_invert;
-}
-
-void SkeletonModification3DCCDIK::set_ccdik_joint_constraint_invert(int p_joint_idx, bool p_invert) {
- const int bone_chain_size = ccdik_data_chain.size();
- ERR_FAIL_INDEX(p_joint_idx, bone_chain_size);
- ccdik_data_chain[p_joint_idx].constraint_angles_invert = p_invert;
-}
-
-int SkeletonModification3DCCDIK::get_ccdik_data_chain_length() {
- return ccdik_data_chain.size();
-}
-void SkeletonModification3DCCDIK::set_ccdik_data_chain_length(int p_length) {
- ERR_FAIL_COND(p_length < 0);
- ccdik_data_chain.resize(p_length);
- execution_error_found = false;
- notify_property_list_changed();
-}
-
-void SkeletonModification3DCCDIK::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_target_node", "target_nodepath"), &SkeletonModification3DCCDIK::set_target_node);
- ClassDB::bind_method(D_METHOD("get_target_node"), &SkeletonModification3DCCDIK::get_target_node);
-
- ClassDB::bind_method(D_METHOD("set_tip_node", "tip_nodepath"), &SkeletonModification3DCCDIK::set_tip_node);
- ClassDB::bind_method(D_METHOD("get_tip_node"), &SkeletonModification3DCCDIK::get_tip_node);
-
- ClassDB::bind_method(D_METHOD("set_use_high_quality_solve", "high_quality_solve"), &SkeletonModification3DCCDIK::set_use_high_quality_solve);
- ClassDB::bind_method(D_METHOD("get_use_high_quality_solve"), &SkeletonModification3DCCDIK::get_use_high_quality_solve);
-
- // CCDIK joint data functions
- ClassDB::bind_method(D_METHOD("get_ccdik_joint_bone_name", "joint_idx"), &SkeletonModification3DCCDIK::get_ccdik_joint_bone_name);
- ClassDB::bind_method(D_METHOD("set_ccdik_joint_bone_name", "joint_idx", "bone_name"), &SkeletonModification3DCCDIK::set_ccdik_joint_bone_name);
- ClassDB::bind_method(D_METHOD("get_ccdik_joint_bone_index", "joint_idx"), &SkeletonModification3DCCDIK::get_ccdik_joint_bone_index);
- ClassDB::bind_method(D_METHOD("set_ccdik_joint_bone_index", "joint_idx", "bone_index"), &SkeletonModification3DCCDIK::set_ccdik_joint_bone_index);
- ClassDB::bind_method(D_METHOD("get_ccdik_joint_ccdik_axis", "joint_idx"), &SkeletonModification3DCCDIK::get_ccdik_joint_ccdik_axis);
- ClassDB::bind_method(D_METHOD("set_ccdik_joint_ccdik_axis", "joint_idx", "axis"), &SkeletonModification3DCCDIK::set_ccdik_joint_ccdik_axis);
- ClassDB::bind_method(D_METHOD("get_ccdik_joint_enable_joint_constraint", "joint_idx"), &SkeletonModification3DCCDIK::get_ccdik_joint_enable_constraint);
- ClassDB::bind_method(D_METHOD("set_ccdik_joint_enable_joint_constraint", "joint_idx", "enable"), &SkeletonModification3DCCDIK::set_ccdik_joint_enable_constraint);
- ClassDB::bind_method(D_METHOD("get_ccdik_joint_constraint_angle_min", "joint_idx"), &SkeletonModification3DCCDIK::get_ccdik_joint_constraint_angle_min);
- ClassDB::bind_method(D_METHOD("set_ccdik_joint_constraint_angle_min", "joint_idx", "min_angle"), &SkeletonModification3DCCDIK::set_ccdik_joint_constraint_angle_min);
- ClassDB::bind_method(D_METHOD("get_ccdik_joint_constraint_angle_max", "joint_idx"), &SkeletonModification3DCCDIK::get_ccdik_joint_constraint_angle_max);
- ClassDB::bind_method(D_METHOD("set_ccdik_joint_constraint_angle_max", "joint_idx", "max_angle"), &SkeletonModification3DCCDIK::set_ccdik_joint_constraint_angle_max);
- ClassDB::bind_method(D_METHOD("get_ccdik_joint_constraint_invert", "joint_idx"), &SkeletonModification3DCCDIK::get_ccdik_joint_constraint_invert);
- ClassDB::bind_method(D_METHOD("set_ccdik_joint_constraint_invert", "joint_idx", "invert"), &SkeletonModification3DCCDIK::set_ccdik_joint_constraint_invert);
-
- ClassDB::bind_method(D_METHOD("set_ccdik_data_chain_length", "length"), &SkeletonModification3DCCDIK::set_ccdik_data_chain_length);
- ClassDB::bind_method(D_METHOD("get_ccdik_data_chain_length"), &SkeletonModification3DCCDIK::get_ccdik_data_chain_length);
-
- ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "target_nodepath", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Node3D"), "set_target_node", "get_target_node");
- ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "tip_nodepath", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Node3D"), "set_tip_node", "get_tip_node");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL, "high_quality_solve", PROPERTY_HINT_NONE, ""), "set_use_high_quality_solve", "get_use_high_quality_solve");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "ccdik_data_chain_length", PROPERTY_HINT_RANGE, "0,100,1"), "set_ccdik_data_chain_length", "get_ccdik_data_chain_length");
-}
-
-SkeletonModification3DCCDIK::SkeletonModification3DCCDIK() {
- stack = nullptr;
- is_setup = false;
- enabled = true;
-}
-
-SkeletonModification3DCCDIK::~SkeletonModification3DCCDIK() {
-}
diff --git a/scene/resources/skeleton_modification_3d_ccdik.h b/scene/resources/skeleton_modification_3d_ccdik.h
deleted file mode 100644
index 30c29bb3aa..0000000000
--- a/scene/resources/skeleton_modification_3d_ccdik.h
+++ /dev/null
@@ -1,114 +0,0 @@
-/**************************************************************************/
-/* skeleton_modification_3d_ccdik.h */
-/**************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/**************************************************************************/
-/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
-/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
-/* */
-/* 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 SKELETON_MODIFICATION_3D_CCDIK_H
-#define SKELETON_MODIFICATION_3D_CCDIK_H
-
-#include "core/templates/local_vector.h"
-#include "scene/3d/skeleton_3d.h"
-#include "scene/resources/skeleton_modification_3d.h"
-
-class SkeletonModification3DCCDIK : public SkeletonModification3D {
- GDCLASS(SkeletonModification3DCCDIK, SkeletonModification3D);
-
-private:
- enum CCDIK_Axes {
- AXIS_X,
- AXIS_Y,
- AXIS_Z
- };
-
- struct CCDIK_Joint_Data {
- String bone_name = "";
- int bone_idx = -1;
- int ccdik_axis = 0;
-
- bool enable_constraint = false;
- real_t constraint_angle_min = 0;
- real_t constraint_angle_max = (2.0 * Math_PI);
- bool constraint_angles_invert = false;
- };
-
- LocalVector<CCDIK_Joint_Data> ccdik_data_chain;
- NodePath target_node;
- ObjectID target_node_cache;
-
- NodePath tip_node;
- ObjectID tip_node_cache;
-
- bool use_high_quality_solve = true;
-
- void update_target_cache();
- void update_tip_cache();
-
- void _execute_ccdik_joint(int p_joint_idx, Node3D *p_target, Node3D *p_tip);
-
-protected:
- static void _bind_methods();
- bool _get(const StringName &p_path, Variant &r_ret) const;
- bool _set(const StringName &p_path, const Variant &p_value);
- void _get_property_list(List<PropertyInfo> *p_list) const;
-
-public:
- virtual void _execute(real_t p_delta) override;
- virtual void _setup_modification(SkeletonModificationStack3D *p_stack) override;
-
- void set_target_node(const NodePath &p_target_node);
- NodePath get_target_node() const;
-
- void set_tip_node(const NodePath &p_tip_node);
- NodePath get_tip_node() const;
-
- void set_use_high_quality_solve(bool p_solve);
- bool get_use_high_quality_solve() const;
-
- String get_ccdik_joint_bone_name(int p_joint_idx) const;
- void set_ccdik_joint_bone_name(int p_joint_idx, String p_bone_name);
- int get_ccdik_joint_bone_index(int p_joint_idx) const;
- void set_ccdik_joint_bone_index(int p_joint_idx, int p_bone_idx);
- int get_ccdik_joint_ccdik_axis(int p_joint_idx) const;
- void set_ccdik_joint_ccdik_axis(int p_joint_idx, int p_axis);
- bool get_ccdik_joint_enable_constraint(int p_joint_idx) const;
- void set_ccdik_joint_enable_constraint(int p_joint_idx, bool p_enable);
- real_t get_ccdik_joint_constraint_angle_min(int p_joint_idx) const;
- void set_ccdik_joint_constraint_angle_min(int p_joint_idx, real_t p_angle_min);
- real_t get_ccdik_joint_constraint_angle_max(int p_joint_idx) const;
- void set_ccdik_joint_constraint_angle_max(int p_joint_idx, real_t p_angle_max);
- bool get_ccdik_joint_constraint_invert(int p_joint_idx) const;
- void set_ccdik_joint_constraint_invert(int p_joint_idx, bool p_invert);
-
- int get_ccdik_data_chain_length();
- void set_ccdik_data_chain_length(int p_new_length);
-
- SkeletonModification3DCCDIK();
- ~SkeletonModification3DCCDIK();
-};
-
-#endif // SKELETON_MODIFICATION_3D_CCDIK_H
diff --git a/scene/resources/skeleton_modification_3d_fabrik.cpp b/scene/resources/skeleton_modification_3d_fabrik.cpp
deleted file mode 100644
index 9fb7ade155..0000000000
--- a/scene/resources/skeleton_modification_3d_fabrik.cpp
+++ /dev/null
@@ -1,628 +0,0 @@
-/**************************************************************************/
-/* skeleton_modification_3d_fabrik.cpp */
-/**************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/**************************************************************************/
-/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
-/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
-/* */
-/* 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 "scene/resources/skeleton_modification_3d_fabrik.h"
-#include "scene/3d/skeleton_3d.h"
-#include "scene/resources/skeleton_modification_3d.h"
-
-bool SkeletonModification3DFABRIK::_set(const StringName &p_path, const Variant &p_value) {
- String path = p_path;
-
- if (path.begins_with("joint_data/")) {
- int fabrik_data_size = fabrik_data_chain.size();
- int which = path.get_slicec('/', 1).to_int();
- String what = path.get_slicec('/', 2);
- ERR_FAIL_INDEX_V(which, fabrik_data_size, false);
-
- if (what == "bone_name") {
- set_fabrik_joint_bone_name(which, p_value);
- } else if (what == "bone_index") {
- set_fabrik_joint_bone_index(which, p_value);
- } else if (what == "length") {
- set_fabrik_joint_length(which, p_value);
- } else if (what == "magnet_position") {
- set_fabrik_joint_magnet(which, p_value);
- } else if (what == "auto_calculate_length") {
- set_fabrik_joint_auto_calculate_length(which, p_value);
- } else if (what == "use_tip_node") {
- set_fabrik_joint_use_tip_node(which, p_value);
- } else if (what == "tip_node") {
- set_fabrik_joint_tip_node(which, p_value);
- } else if (what == "use_target_basis") {
- set_fabrik_joint_use_target_basis(which, p_value);
- } else if (what == "roll") {
- set_fabrik_joint_roll(which, Math::deg_to_rad(real_t(p_value)));
- }
- return true;
- }
- return true;
-}
-
-bool SkeletonModification3DFABRIK::_get(const StringName &p_path, Variant &r_ret) const {
- String path = p_path;
-
- if (path.begins_with("joint_data/")) {
- const int fabrik_data_size = fabrik_data_chain.size();
- int which = path.get_slicec('/', 1).to_int();
- String what = path.get_slicec('/', 2);
- ERR_FAIL_INDEX_V(which, fabrik_data_size, false);
-
- if (what == "bone_name") {
- r_ret = get_fabrik_joint_bone_name(which);
- } else if (what == "bone_index") {
- r_ret = get_fabrik_joint_bone_index(which);
- } else if (what == "length") {
- r_ret = get_fabrik_joint_length(which);
- } else if (what == "magnet_position") {
- r_ret = get_fabrik_joint_magnet(which);
- } else if (what == "auto_calculate_length") {
- r_ret = get_fabrik_joint_auto_calculate_length(which);
- } else if (what == "use_tip_node") {
- r_ret = get_fabrik_joint_use_tip_node(which);
- } else if (what == "tip_node") {
- r_ret = get_fabrik_joint_tip_node(which);
- } else if (what == "use_target_basis") {
- r_ret = get_fabrik_joint_use_target_basis(which);
- } else if (what == "roll") {
- r_ret = Math::rad_to_deg(get_fabrik_joint_roll(which));
- }
- return true;
- }
- return true;
-}
-
-void SkeletonModification3DFABRIK::_get_property_list(List<PropertyInfo> *p_list) const {
- for (uint32_t i = 0; i < fabrik_data_chain.size(); i++) {
- String base_string = "joint_data/" + itos(i) + "/";
-
- p_list->push_back(PropertyInfo(Variant::STRING_NAME, base_string + "bone_name", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
- p_list->push_back(PropertyInfo(Variant::INT, base_string + "bone_index", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
- p_list->push_back(PropertyInfo(Variant::FLOAT, base_string + "roll", PROPERTY_HINT_RANGE, "-360,360,0.01", PROPERTY_USAGE_DEFAULT));
- p_list->push_back(PropertyInfo(Variant::BOOL, base_string + "auto_calculate_length", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
-
- if (!fabrik_data_chain[i].auto_calculate_length) {
- p_list->push_back(PropertyInfo(Variant::FLOAT, base_string + "length", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
- } else {
- p_list->push_back(PropertyInfo(Variant::BOOL, base_string + "use_tip_node", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
- if (fabrik_data_chain[i].use_tip_node) {
- p_list->push_back(PropertyInfo(Variant::NODE_PATH, base_string + "tip_node", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Node3D", PROPERTY_USAGE_DEFAULT));
- }
- }
-
- // Cannot apply magnet to the origin of the chain, as it will not do anything.
- if (i > 0) {
- p_list->push_back(PropertyInfo(Variant::VECTOR3, base_string + "magnet_position", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
- }
- // Only give the override basis option on the last bone in the chain, so only include it for the last bone.
- if (i == fabrik_data_chain.size() - 1) {
- p_list->push_back(PropertyInfo(Variant::BOOL, base_string + "use_target_basis", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
- }
- }
-}
-
-void SkeletonModification3DFABRIK::_execute(real_t p_delta) {
- ERR_FAIL_COND_MSG(!stack || !is_setup || stack->skeleton == nullptr,
- "Modification is not setup and therefore cannot execute!");
- if (!enabled) {
- return;
- }
-
- if (target_node_cache.is_null()) {
- _print_execution_error(true, "Target cache is out of date. Attempting to update...");
- update_target_cache();
- return;
- }
-
- if (_print_execution_error(fabrik_data_chain.size() <= 1, "FABRIK requires at least two joints to operate. Cannot execute modification!")) {
- return;
- }
-
- Node3D *node_target = Object::cast_to<Node3D>(ObjectDB::get_instance(target_node_cache));
- if (_print_execution_error(!node_target || !node_target->is_inside_tree(), "Target node is not in the scene tree. Cannot execute modification!")) {
- return;
- }
-
- // Make sure the transform cache is the correct size
- if (fabrik_transforms.size() != fabrik_data_chain.size()) {
- fabrik_transforms.resize(fabrik_data_chain.size());
- }
-
- // Verify that all joints have a valid bone ID, and that all bone lengths are zero or more
- // Also, while we are here, apply magnet positions.
- for (uint32_t i = 0; i < fabrik_data_chain.size(); i++) {
- if (_print_execution_error(fabrik_data_chain[i].bone_idx < 0, "FABRIK Joint " + itos(i) + " has an invalid bone ID. Cannot execute!")) {
- return;
- }
-
- if (fabrik_data_chain[i].length < 0 && fabrik_data_chain[i].auto_calculate_length) {
- fabrik_joint_auto_calculate_length(i);
- }
- if (_print_execution_error(fabrik_data_chain[i].length < 0, "FABRIK Joint " + itos(i) + " has an invalid joint length. Cannot execute!")) {
- return;
- }
- fabrik_transforms[i] = stack->skeleton->get_bone_global_pose(fabrik_data_chain[i].bone_idx);
-
- // Apply magnet positions:
- if (stack->skeleton->get_bone_parent(fabrik_data_chain[i].bone_idx) >= 0) {
- int parent_bone_idx = stack->skeleton->get_bone_parent(fabrik_data_chain[i].bone_idx);
- Transform3D conversion_transform = (stack->skeleton->get_bone_global_pose(parent_bone_idx));
- fabrik_transforms[i].origin += conversion_transform.basis.xform_inv(fabrik_data_chain[i].magnet_position);
- } else {
- fabrik_transforms[i].origin += fabrik_data_chain[i].magnet_position;
- }
- }
- Transform3D origin_global_pose_trans = stack->skeleton->get_bone_global_pose_no_override(fabrik_data_chain[0].bone_idx);
-
- target_global_pose = stack->skeleton->world_transform_to_global_pose(node_target->get_global_transform());
- origin_global_pose = origin_global_pose_trans;
-
- final_joint_idx = fabrik_data_chain.size() - 1;
- real_t target_distance = fabrik_transforms[final_joint_idx].origin.distance_to(target_global_pose.origin);
- chain_iterations = 0;
-
- while (target_distance > chain_tolerance) {
- chain_backwards();
- chain_forwards();
-
- // update the target distance
- target_distance = fabrik_transforms[final_joint_idx].origin.distance_to(target_global_pose.origin);
-
- // update chain iterations
- chain_iterations += 1;
- if (chain_iterations >= chain_max_iterations) {
- break;
- }
- }
- chain_apply();
-
- execution_error_found = false;
-}
-
-void SkeletonModification3DFABRIK::chain_backwards() {
- int final_bone_idx = fabrik_data_chain[final_joint_idx].bone_idx;
- Transform3D final_joint_trans = fabrik_transforms[final_joint_idx];
-
- // Get the direction the final bone is facing in.
- stack->skeleton->update_bone_rest_forward_vector(final_bone_idx);
- Transform3D final_bone_direction_trans = final_joint_trans.looking_at(target_global_pose.origin, Vector3(0, 1, 0));
- final_bone_direction_trans.basis = stack->skeleton->global_pose_z_forward_to_bone_forward(final_bone_idx, final_bone_direction_trans.basis);
- Vector3 direction = final_bone_direction_trans.basis.xform(stack->skeleton->get_bone_axis_forward_vector(final_bone_idx)).normalized();
-
- // If set to override, then use the target's Basis rather than the bone's
- if (fabrik_data_chain[final_joint_idx].use_target_basis) {
- direction = target_global_pose.basis.xform(stack->skeleton->get_bone_axis_forward_vector(final_bone_idx)).normalized();
- }
-
- // set the position of the final joint to the target position
- final_joint_trans.origin = target_global_pose.origin - (direction * fabrik_data_chain[final_joint_idx].length);
- fabrik_transforms[final_joint_idx] = final_joint_trans;
-
- // for all other joints, move them towards the target
- int i = final_joint_idx;
- while (i >= 1) {
- Transform3D next_bone_trans = fabrik_transforms[i];
- i -= 1;
- Transform3D current_trans = fabrik_transforms[i];
-
- real_t length = fabrik_data_chain[i].length / (current_trans.origin.distance_to(next_bone_trans.origin));
- current_trans.origin = next_bone_trans.origin.lerp(current_trans.origin, length);
-
- // Save the result
- fabrik_transforms[i] = current_trans;
- }
-}
-
-void SkeletonModification3DFABRIK::chain_forwards() {
- // Set root at the initial position.
- Transform3D root_transform = fabrik_transforms[0];
-
- root_transform.origin = origin_global_pose.origin;
- fabrik_transforms[0] = origin_global_pose;
-
- for (uint32_t i = 0; i < fabrik_data_chain.size() - 1; i++) {
- Transform3D current_trans = fabrik_transforms[i];
- Transform3D next_bone_trans = fabrik_transforms[i + 1];
-
- real_t length = fabrik_data_chain[i].length / (next_bone_trans.origin.distance_to(current_trans.origin));
- next_bone_trans.origin = current_trans.origin.lerp(next_bone_trans.origin, length);
-
- // Save the result
- fabrik_transforms[i + 1] = next_bone_trans;
- }
-}
-
-void SkeletonModification3DFABRIK::chain_apply() {
- for (uint32_t i = 0; i < fabrik_data_chain.size(); i++) {
- int current_bone_idx = fabrik_data_chain[i].bone_idx;
- Transform3D current_trans = fabrik_transforms[i];
-
- // If this is the last bone in the chain...
- if (i == fabrik_data_chain.size() - 1) {
- if (fabrik_data_chain[i].use_target_basis == false) { // Point to target...
- // Get the forward direction that the basis is facing in right now.
- stack->skeleton->update_bone_rest_forward_vector(current_bone_idx);
- Vector3 forward_vector = stack->skeleton->get_bone_axis_forward_vector(current_bone_idx);
- // Rotate the bone towards the target:
- current_trans.basis.rotate_to_align(forward_vector, current_trans.origin.direction_to(target_global_pose.origin));
- current_trans.basis.rotate_local(forward_vector, fabrik_data_chain[i].roll);
- } else { // Use the target's Basis...
- current_trans.basis = target_global_pose.basis.orthonormalized().scaled(current_trans.basis.get_scale());
- }
- } else { // every other bone in the chain...
- Transform3D next_trans = fabrik_transforms[i + 1];
-
- // Get the forward direction that the basis is facing in right now.
- stack->skeleton->update_bone_rest_forward_vector(current_bone_idx);
- Vector3 forward_vector = stack->skeleton->get_bone_axis_forward_vector(current_bone_idx);
- // Rotate the bone towards the next bone in the chain:
- current_trans.basis.rotate_to_align(forward_vector, current_trans.origin.direction_to(next_trans.origin));
- current_trans.basis.rotate_local(forward_vector, fabrik_data_chain[i].roll);
- }
- stack->skeleton->set_bone_local_pose_override(current_bone_idx, stack->skeleton->global_pose_to_local_pose(current_bone_idx, current_trans), stack->strength, true);
- }
-
- // Update all the bones so the next modification has up-to-date data.
- stack->skeleton->force_update_all_bone_transforms();
-}
-
-void SkeletonModification3DFABRIK::_setup_modification(SkeletonModificationStack3D *p_stack) {
- stack = p_stack;
- if (stack != nullptr) {
- is_setup = true;
- execution_error_found = false;
- update_target_cache();
-
- for (uint32_t i = 0; i < fabrik_data_chain.size(); i++) {
- update_joint_tip_cache(i);
- }
- }
-}
-
-void SkeletonModification3DFABRIK::update_target_cache() {
- if (!is_setup || !stack) {
- _print_execution_error(true, "Cannot update target cache: modification is not properly setup!");
- return;
- }
- target_node_cache = ObjectID();
- if (stack->skeleton) {
- if (stack->skeleton->is_inside_tree() && target_node.is_empty() == false) {
- if (stack->skeleton->has_node(target_node)) {
- Node *node = stack->skeleton->get_node(target_node);
- ERR_FAIL_COND_MSG(!node || stack->skeleton == node,
- "Cannot update target cache: node is this modification's skeleton or cannot be found!");
- ERR_FAIL_COND_MSG(!node->is_inside_tree(),
- "Cannot update target cache: node is not in the scene tree!");
- target_node_cache = node->get_instance_id();
-
- execution_error_found = false;
- }
- }
- }
-}
-
-void SkeletonModification3DFABRIK::update_joint_tip_cache(int p_joint_idx) {
- const int bone_chain_size = fabrik_data_chain.size();
- ERR_FAIL_INDEX_MSG(p_joint_idx, bone_chain_size, "FABRIK joint not found");
- if (!is_setup || !stack) {
- _print_execution_error(true, "Cannot update tip cache: modification is not properly setup!");
- return;
- }
- fabrik_data_chain[p_joint_idx].tip_node_cache = ObjectID();
- if (stack->skeleton) {
- if (stack->skeleton->is_inside_tree() && fabrik_data_chain[p_joint_idx].tip_node.is_empty() == false) {
- if (stack->skeleton->has_node(fabrik_data_chain[p_joint_idx].tip_node)) {
- Node *node = stack->skeleton->get_node(fabrik_data_chain[p_joint_idx].tip_node);
- ERR_FAIL_COND_MSG(!node || stack->skeleton == node,
- "Cannot update tip cache for joint " + itos(p_joint_idx) + ": node is this modification's skeleton or cannot be found!");
- ERR_FAIL_COND_MSG(!node->is_inside_tree(),
- "Cannot update tip cache for joint " + itos(p_joint_idx) + ": node is not in scene tree!");
- fabrik_data_chain[p_joint_idx].tip_node_cache = node->get_instance_id();
-
- execution_error_found = false;
- }
- }
- }
-}
-
-void SkeletonModification3DFABRIK::set_target_node(const NodePath &p_target_node) {
- target_node = p_target_node;
- update_target_cache();
-}
-
-NodePath SkeletonModification3DFABRIK::get_target_node() const {
- return target_node;
-}
-
-int SkeletonModification3DFABRIK::get_fabrik_data_chain_length() {
- return fabrik_data_chain.size();
-}
-
-void SkeletonModification3DFABRIK::set_fabrik_data_chain_length(int p_length) {
- ERR_FAIL_COND(p_length < 0);
- fabrik_data_chain.resize(p_length);
- fabrik_transforms.resize(p_length);
- execution_error_found = false;
- notify_property_list_changed();
-}
-
-real_t SkeletonModification3DFABRIK::get_chain_tolerance() {
- return chain_tolerance;
-}
-
-void SkeletonModification3DFABRIK::set_chain_tolerance(real_t p_tolerance) {
- ERR_FAIL_COND_MSG(p_tolerance <= 0, "FABRIK chain tolerance must be more than zero!");
- chain_tolerance = p_tolerance;
-}
-
-int SkeletonModification3DFABRIK::get_chain_max_iterations() {
- return chain_max_iterations;
-}
-void SkeletonModification3DFABRIK::set_chain_max_iterations(int p_iterations) {
- ERR_FAIL_COND_MSG(p_iterations <= 0, "FABRIK chain iterations must be at least one. Set enabled to false to disable the FABRIK chain.");
- chain_max_iterations = p_iterations;
-}
-
-// FABRIK joint data functions
-String SkeletonModification3DFABRIK::get_fabrik_joint_bone_name(int p_joint_idx) const {
- const int bone_chain_size = fabrik_data_chain.size();
- ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, String());
- return fabrik_data_chain[p_joint_idx].bone_name;
-}
-
-void SkeletonModification3DFABRIK::set_fabrik_joint_bone_name(int p_joint_idx, String p_bone_name) {
- const int bone_chain_size = fabrik_data_chain.size();
- ERR_FAIL_INDEX(p_joint_idx, bone_chain_size);
- fabrik_data_chain[p_joint_idx].bone_name = p_bone_name;
-
- if (stack) {
- if (stack->skeleton) {
- fabrik_data_chain[p_joint_idx].bone_idx = stack->skeleton->find_bone(p_bone_name);
- }
- }
- execution_error_found = false;
- notify_property_list_changed();
-}
-
-int SkeletonModification3DFABRIK::get_fabrik_joint_bone_index(int p_joint_idx) const {
- const int bone_chain_size = fabrik_data_chain.size();
- ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, -1);
- return fabrik_data_chain[p_joint_idx].bone_idx;
-}
-
-void SkeletonModification3DFABRIK::set_fabrik_joint_bone_index(int p_joint_idx, int p_bone_idx) {
- const int bone_chain_size = fabrik_data_chain.size();
- ERR_FAIL_INDEX(p_joint_idx, bone_chain_size);
- ERR_FAIL_COND_MSG(p_bone_idx < 0, "Bone index is out of range: The index is too low!");
- fabrik_data_chain[p_joint_idx].bone_idx = p_bone_idx;
-
- if (stack) {
- if (stack->skeleton) {
- fabrik_data_chain[p_joint_idx].bone_name = stack->skeleton->get_bone_name(p_bone_idx);
- }
- }
- execution_error_found = false;
- notify_property_list_changed();
-}
-
-real_t SkeletonModification3DFABRIK::get_fabrik_joint_length(int p_joint_idx) const {
- const int bone_chain_size = fabrik_data_chain.size();
- ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, -1);
- return fabrik_data_chain[p_joint_idx].length;
-}
-
-void SkeletonModification3DFABRIK::set_fabrik_joint_length(int p_joint_idx, real_t p_bone_length) {
- const int bone_chain_size = fabrik_data_chain.size();
- ERR_FAIL_INDEX(p_joint_idx, bone_chain_size);
- ERR_FAIL_COND_MSG(p_bone_length < 0, "FABRIK joint length cannot be less than zero!");
-
- if (!is_setup) {
- fabrik_data_chain[p_joint_idx].length = p_bone_length;
- return;
- }
-
- if (fabrik_data_chain[p_joint_idx].auto_calculate_length) {
- WARN_PRINT("FABRIK Length not set: auto calculate length is enabled for this joint!");
- fabrik_joint_auto_calculate_length(p_joint_idx);
- } else {
- fabrik_data_chain[p_joint_idx].length = p_bone_length;
- }
-
- execution_error_found = false;
-}
-
-Vector3 SkeletonModification3DFABRIK::get_fabrik_joint_magnet(int p_joint_idx) const {
- const int bone_chain_size = fabrik_data_chain.size();
- ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, Vector3());
- return fabrik_data_chain[p_joint_idx].magnet_position;
-}
-
-void SkeletonModification3DFABRIK::set_fabrik_joint_magnet(int p_joint_idx, Vector3 p_magnet) {
- const int bone_chain_size = fabrik_data_chain.size();
- ERR_FAIL_INDEX(p_joint_idx, bone_chain_size);
- fabrik_data_chain[p_joint_idx].magnet_position = p_magnet;
-}
-
-bool SkeletonModification3DFABRIK::get_fabrik_joint_auto_calculate_length(int p_joint_idx) const {
- const int bone_chain_size = fabrik_data_chain.size();
- ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, false);
- return fabrik_data_chain[p_joint_idx].auto_calculate_length;
-}
-
-void SkeletonModification3DFABRIK::set_fabrik_joint_auto_calculate_length(int p_joint_idx, bool p_auto_calculate) {
- const int bone_chain_size = fabrik_data_chain.size();
- ERR_FAIL_INDEX(p_joint_idx, bone_chain_size);
- fabrik_data_chain[p_joint_idx].auto_calculate_length = p_auto_calculate;
- fabrik_joint_auto_calculate_length(p_joint_idx);
- notify_property_list_changed();
-}
-
-void SkeletonModification3DFABRIK::fabrik_joint_auto_calculate_length(int p_joint_idx) {
- const int bone_chain_size = fabrik_data_chain.size();
- ERR_FAIL_INDEX(p_joint_idx, bone_chain_size);
- if (!fabrik_data_chain[p_joint_idx].auto_calculate_length) {
- return;
- }
-
- if (!stack || !stack->skeleton || !is_setup) {
- _print_execution_error(true, "Cannot auto calculate joint length: modification is not properly setup!");
- return;
- }
- ERR_FAIL_INDEX_MSG(fabrik_data_chain[p_joint_idx].bone_idx, stack->skeleton->get_bone_count(),
- "Bone for joint " + itos(p_joint_idx) + " is not set or points to an unknown bone!");
-
- if (fabrik_data_chain[p_joint_idx].use_tip_node) { // Use the tip node to update joint length.
-
- update_joint_tip_cache(p_joint_idx);
-
- Node3D *tip_node = Object::cast_to<Node3D>(ObjectDB::get_instance(fabrik_data_chain[p_joint_idx].tip_node_cache));
- ERR_FAIL_COND_MSG(!tip_node, "Tip node for joint " + itos(p_joint_idx) + "is not a Node3D-based node. Cannot calculate length...");
- ERR_FAIL_COND_MSG(!tip_node->is_inside_tree(), "Tip node for joint " + itos(p_joint_idx) + "is not in the scene tree. Cannot calculate length...");
-
- Transform3D node_trans = tip_node->get_global_transform();
- node_trans = stack->skeleton->world_transform_to_global_pose(node_trans);
- //node_trans = stack->skeleton->global_pose_to_local_pose(fabrik_data_chain[p_joint_idx].bone_idx, node_trans);
- //fabrik_data_chain[p_joint_idx].length = node_trans.origin.length();
-
- fabrik_data_chain[p_joint_idx].length = stack->skeleton->get_bone_global_pose(fabrik_data_chain[p_joint_idx].bone_idx).origin.distance_to(node_trans.origin);
-
- } else { // Use child bone(s) to update joint length, if possible
- Vector<int> bone_children = stack->skeleton->get_bone_children(fabrik_data_chain[p_joint_idx].bone_idx);
- if (bone_children.size() <= 0) {
- ERR_FAIL_MSG("Cannot calculate length for joint " + itos(p_joint_idx) + "joint uses leaf bone. \nPlease manually set the bone length or use a tip node!");
- return;
- }
-
- Transform3D bone_trans = stack->skeleton->get_bone_global_pose(fabrik_data_chain[p_joint_idx].bone_idx);
-
- real_t final_length = 0;
- for (int i = 0; i < bone_children.size(); i++) {
- Transform3D child_transform = stack->skeleton->get_bone_global_pose(bone_children[i]);
- final_length += bone_trans.origin.distance_to(child_transform.origin);
- //final_length += stack->skeleton->global_pose_to_local_pose(fabrik_data_chain[p_joint_idx].bone_idx, child_transform).origin.length();
- }
- fabrik_data_chain[p_joint_idx].length = final_length / bone_children.size();
- }
- execution_error_found = false;
- notify_property_list_changed();
-}
-
-bool SkeletonModification3DFABRIK::get_fabrik_joint_use_tip_node(int p_joint_idx) const {
- const int bone_chain_size = fabrik_data_chain.size();
- ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, false);
- return fabrik_data_chain[p_joint_idx].use_tip_node;
-}
-
-void SkeletonModification3DFABRIK::set_fabrik_joint_use_tip_node(int p_joint_idx, bool p_use_tip_node) {
- const int bone_chain_size = fabrik_data_chain.size();
- ERR_FAIL_INDEX(p_joint_idx, bone_chain_size);
- fabrik_data_chain[p_joint_idx].use_tip_node = p_use_tip_node;
- notify_property_list_changed();
-}
-
-NodePath SkeletonModification3DFABRIK::get_fabrik_joint_tip_node(int p_joint_idx) const {
- const int bone_chain_size = fabrik_data_chain.size();
- ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, NodePath());
- return fabrik_data_chain[p_joint_idx].tip_node;
-}
-
-void SkeletonModification3DFABRIK::set_fabrik_joint_tip_node(int p_joint_idx, NodePath p_tip_node) {
- const int bone_chain_size = fabrik_data_chain.size();
- ERR_FAIL_INDEX(p_joint_idx, bone_chain_size);
- fabrik_data_chain[p_joint_idx].tip_node = p_tip_node;
- update_joint_tip_cache(p_joint_idx);
-}
-
-bool SkeletonModification3DFABRIK::get_fabrik_joint_use_target_basis(int p_joint_idx) const {
- const int bone_chain_size = fabrik_data_chain.size();
- ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, false);
- return fabrik_data_chain[p_joint_idx].use_target_basis;
-}
-
-void SkeletonModification3DFABRIK::set_fabrik_joint_use_target_basis(int p_joint_idx, bool p_use_target_basis) {
- const int bone_chain_size = fabrik_data_chain.size();
- ERR_FAIL_INDEX(p_joint_idx, bone_chain_size);
- fabrik_data_chain[p_joint_idx].use_target_basis = p_use_target_basis;
-}
-
-real_t SkeletonModification3DFABRIK::get_fabrik_joint_roll(int p_joint_idx) const {
- const int bone_chain_size = fabrik_data_chain.size();
- ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, 0.0);
- return fabrik_data_chain[p_joint_idx].roll;
-}
-
-void SkeletonModification3DFABRIK::set_fabrik_joint_roll(int p_joint_idx, real_t p_roll) {
- const int bone_chain_size = fabrik_data_chain.size();
- ERR_FAIL_INDEX(p_joint_idx, bone_chain_size);
- fabrik_data_chain[p_joint_idx].roll = p_roll;
-}
-
-void SkeletonModification3DFABRIK::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_target_node", "target_nodepath"), &SkeletonModification3DFABRIK::set_target_node);
- ClassDB::bind_method(D_METHOD("get_target_node"), &SkeletonModification3DFABRIK::get_target_node);
- ClassDB::bind_method(D_METHOD("set_fabrik_data_chain_length", "length"), &SkeletonModification3DFABRIK::set_fabrik_data_chain_length);
- ClassDB::bind_method(D_METHOD("get_fabrik_data_chain_length"), &SkeletonModification3DFABRIK::get_fabrik_data_chain_length);
- ClassDB::bind_method(D_METHOD("set_chain_tolerance", "tolerance"), &SkeletonModification3DFABRIK::set_chain_tolerance);
- ClassDB::bind_method(D_METHOD("get_chain_tolerance"), &SkeletonModification3DFABRIK::get_chain_tolerance);
- ClassDB::bind_method(D_METHOD("set_chain_max_iterations", "max_iterations"), &SkeletonModification3DFABRIK::set_chain_max_iterations);
- ClassDB::bind_method(D_METHOD("get_chain_max_iterations"), &SkeletonModification3DFABRIK::get_chain_max_iterations);
-
- // FABRIK joint data functions
- ClassDB::bind_method(D_METHOD("get_fabrik_joint_bone_name", "joint_idx"), &SkeletonModification3DFABRIK::get_fabrik_joint_bone_name);
- ClassDB::bind_method(D_METHOD("set_fabrik_joint_bone_name", "joint_idx", "bone_name"), &SkeletonModification3DFABRIK::set_fabrik_joint_bone_name);
- ClassDB::bind_method(D_METHOD("get_fabrik_joint_bone_index", "joint_idx"), &SkeletonModification3DFABRIK::get_fabrik_joint_bone_index);
- ClassDB::bind_method(D_METHOD("set_fabrik_joint_bone_index", "joint_idx", "bone_index"), &SkeletonModification3DFABRIK::set_fabrik_joint_bone_index);
- ClassDB::bind_method(D_METHOD("get_fabrik_joint_length", "joint_idx"), &SkeletonModification3DFABRIK::get_fabrik_joint_length);
- ClassDB::bind_method(D_METHOD("set_fabrik_joint_length", "joint_idx", "length"), &SkeletonModification3DFABRIK::set_fabrik_joint_length);
- ClassDB::bind_method(D_METHOD("get_fabrik_joint_magnet", "joint_idx"), &SkeletonModification3DFABRIK::get_fabrik_joint_magnet);
- ClassDB::bind_method(D_METHOD("set_fabrik_joint_magnet", "joint_idx", "magnet_position"), &SkeletonModification3DFABRIK::set_fabrik_joint_magnet);
- ClassDB::bind_method(D_METHOD("get_fabrik_joint_auto_calculate_length", "joint_idx"), &SkeletonModification3DFABRIK::get_fabrik_joint_auto_calculate_length);
- ClassDB::bind_method(D_METHOD("set_fabrik_joint_auto_calculate_length", "joint_idx", "auto_calculate_length"), &SkeletonModification3DFABRIK::set_fabrik_joint_auto_calculate_length);
- ClassDB::bind_method(D_METHOD("fabrik_joint_auto_calculate_length", "joint_idx"), &SkeletonModification3DFABRIK::fabrik_joint_auto_calculate_length);
- ClassDB::bind_method(D_METHOD("get_fabrik_joint_use_tip_node", "joint_idx"), &SkeletonModification3DFABRIK::get_fabrik_joint_use_tip_node);
- ClassDB::bind_method(D_METHOD("set_fabrik_joint_use_tip_node", "joint_idx", "use_tip_node"), &SkeletonModification3DFABRIK::set_fabrik_joint_use_tip_node);
- ClassDB::bind_method(D_METHOD("get_fabrik_joint_tip_node", "joint_idx"), &SkeletonModification3DFABRIK::get_fabrik_joint_tip_node);
- ClassDB::bind_method(D_METHOD("set_fabrik_joint_tip_node", "joint_idx", "tip_node"), &SkeletonModification3DFABRIK::set_fabrik_joint_tip_node);
- ClassDB::bind_method(D_METHOD("get_fabrik_joint_use_target_basis", "joint_idx"), &SkeletonModification3DFABRIK::get_fabrik_joint_use_target_basis);
- ClassDB::bind_method(D_METHOD("set_fabrik_joint_use_target_basis", "joint_idx", "use_target_basis"), &SkeletonModification3DFABRIK::set_fabrik_joint_use_target_basis);
-
- ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "target_nodepath", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Node3D"), "set_target_node", "get_target_node");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "fabrik_data_chain_length", PROPERTY_HINT_RANGE, "0,100,1"), "set_fabrik_data_chain_length", "get_fabrik_data_chain_length");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "chain_tolerance", PROPERTY_HINT_RANGE, "0,100,0.001"), "set_chain_tolerance", "get_chain_tolerance");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "chain_max_iterations", PROPERTY_HINT_RANGE, "1,50,1"), "set_chain_max_iterations", "get_chain_max_iterations");
-}
-
-SkeletonModification3DFABRIK::SkeletonModification3DFABRIK() {
- stack = nullptr;
- is_setup = false;
- enabled = true;
-}
-
-SkeletonModification3DFABRIK::~SkeletonModification3DFABRIK() {
-}
diff --git a/scene/resources/skeleton_modification_3d_fabrik.h b/scene/resources/skeleton_modification_3d_fabrik.h
deleted file mode 100644
index c834658093..0000000000
--- a/scene/resources/skeleton_modification_3d_fabrik.h
+++ /dev/null
@@ -1,124 +0,0 @@
-/**************************************************************************/
-/* skeleton_modification_3d_fabrik.h */
-/**************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/**************************************************************************/
-/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
-/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
-/* */
-/* 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 SKELETON_MODIFICATION_3D_FABRIK_H
-#define SKELETON_MODIFICATION_3D_FABRIK_H
-
-#include "core/templates/local_vector.h"
-#include "scene/3d/skeleton_3d.h"
-#include "scene/resources/skeleton_modification_3d.h"
-
-class SkeletonModification3DFABRIK : public SkeletonModification3D {
- GDCLASS(SkeletonModification3DFABRIK, SkeletonModification3D);
-
-private:
- struct FABRIK_Joint_Data {
- String bone_name = "";
- int bone_idx = -1;
- real_t length = -1;
- Vector3 magnet_position = Vector3(0, 0, 0);
-
- bool auto_calculate_length = true;
- bool use_tip_node = false;
- NodePath tip_node;
- ObjectID tip_node_cache;
-
- bool use_target_basis = false;
- real_t roll = 0;
- };
-
- LocalVector<FABRIK_Joint_Data> fabrik_data_chain;
- LocalVector<Transform3D> fabrik_transforms;
-
- NodePath target_node;
- ObjectID target_node_cache;
-
- real_t chain_tolerance = 0.01;
- int chain_max_iterations = 10;
- int chain_iterations = 0;
-
- void update_target_cache();
- void update_joint_tip_cache(int p_joint_idx);
-
- int final_joint_idx = 0;
- Transform3D target_global_pose;
- Transform3D origin_global_pose;
-
- void chain_backwards();
- void chain_forwards();
- void chain_apply();
-
-protected:
- static void _bind_methods();
- bool _get(const StringName &p_path, Variant &r_ret) const;
- bool _set(const StringName &p_path, const Variant &p_value);
- void _get_property_list(List<PropertyInfo> *p_list) const;
-
-public:
- virtual void _execute(real_t p_delta) override;
- virtual void _setup_modification(SkeletonModificationStack3D *p_stack) override;
-
- void set_target_node(const NodePath &p_target_node);
- NodePath get_target_node() const;
-
- int get_fabrik_data_chain_length();
- void set_fabrik_data_chain_length(int p_new_length);
-
- real_t get_chain_tolerance();
- void set_chain_tolerance(real_t p_tolerance);
-
- int get_chain_max_iterations();
- void set_chain_max_iterations(int p_iterations);
-
- String get_fabrik_joint_bone_name(int p_joint_idx) const;
- void set_fabrik_joint_bone_name(int p_joint_idx, String p_bone_name);
- int get_fabrik_joint_bone_index(int p_joint_idx) const;
- void set_fabrik_joint_bone_index(int p_joint_idx, int p_bone_idx);
- real_t get_fabrik_joint_length(int p_joint_idx) const;
- void set_fabrik_joint_length(int p_joint_idx, real_t p_bone_length);
- Vector3 get_fabrik_joint_magnet(int p_joint_idx) const;
- void set_fabrik_joint_magnet(int p_joint_idx, Vector3 p_magnet);
- bool get_fabrik_joint_auto_calculate_length(int p_joint_idx) const;
- void set_fabrik_joint_auto_calculate_length(int p_joint_idx, bool p_auto_calculate);
- void fabrik_joint_auto_calculate_length(int p_joint_idx);
- bool get_fabrik_joint_use_tip_node(int p_joint_idx) const;
- void set_fabrik_joint_use_tip_node(int p_joint_idx, bool p_use_tip_node);
- NodePath get_fabrik_joint_tip_node(int p_joint_idx) const;
- void set_fabrik_joint_tip_node(int p_joint_idx, NodePath p_tip_node);
- bool get_fabrik_joint_use_target_basis(int p_joint_idx) const;
- void set_fabrik_joint_use_target_basis(int p_joint_idx, bool p_use_basis);
- real_t get_fabrik_joint_roll(int p_joint_idx) const;
- void set_fabrik_joint_roll(int p_joint_idx, real_t p_roll);
-
- SkeletonModification3DFABRIK();
- ~SkeletonModification3DFABRIK();
-};
-
-#endif // SKELETON_MODIFICATION_3D_FABRIK_H
diff --git a/scene/resources/skeleton_modification_3d_jiggle.cpp b/scene/resources/skeleton_modification_3d_jiggle.cpp
deleted file mode 100644
index 2cfc7fb10f..0000000000
--- a/scene/resources/skeleton_modification_3d_jiggle.cpp
+++ /dev/null
@@ -1,582 +0,0 @@
-/**************************************************************************/
-/* skeleton_modification_3d_jiggle.cpp */
-/**************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/**************************************************************************/
-/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
-/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
-/* */
-/* 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 "scene/resources/skeleton_modification_3d_jiggle.h"
-#include "scene/3d/skeleton_3d.h"
-#include "scene/resources/skeleton_modification_3d.h"
-
-bool SkeletonModification3DJiggle::_set(const StringName &p_path, const Variant &p_value) {
- String path = p_path;
-
- if (path.begins_with("joint_data/")) {
- const int jiggle_size = jiggle_data_chain.size();
- int which = path.get_slicec('/', 1).to_int();
- String what = path.get_slicec('/', 2);
- ERR_FAIL_INDEX_V(which, jiggle_size, false);
-
- if (what == "bone_name") {
- set_jiggle_joint_bone_name(which, p_value);
- } else if (what == "bone_index") {
- set_jiggle_joint_bone_index(which, p_value);
- } else if (what == "override_defaults") {
- set_jiggle_joint_override(which, p_value);
- } else if (what == "stiffness") {
- set_jiggle_joint_stiffness(which, p_value);
- } else if (what == "mass") {
- set_jiggle_joint_mass(which, p_value);
- } else if (what == "damping") {
- set_jiggle_joint_damping(which, p_value);
- } else if (what == "use_gravity") {
- set_jiggle_joint_use_gravity(which, p_value);
- } else if (what == "gravity") {
- set_jiggle_joint_gravity(which, p_value);
- } else if (what == "roll") {
- set_jiggle_joint_roll(which, Math::deg_to_rad(real_t(p_value)));
- }
- return true;
- } else {
- if (path == "use_colliders") {
- set_use_colliders(p_value);
- } else if (path == "collision_mask") {
- set_collision_mask(p_value);
- }
- return true;
- }
- return true;
-}
-
-bool SkeletonModification3DJiggle::_get(const StringName &p_path, Variant &r_ret) const {
- String path = p_path;
-
- if (path.begins_with("joint_data/")) {
- const int jiggle_size = jiggle_data_chain.size();
- int which = path.get_slicec('/', 1).to_int();
- String what = path.get_slicec('/', 2);
- ERR_FAIL_INDEX_V(which, jiggle_size, false);
-
- if (what == "bone_name") {
- r_ret = get_jiggle_joint_bone_name(which);
- } else if (what == "bone_index") {
- r_ret = get_jiggle_joint_bone_index(which);
- } else if (what == "override_defaults") {
- r_ret = get_jiggle_joint_override(which);
- } else if (what == "stiffness") {
- r_ret = get_jiggle_joint_stiffness(which);
- } else if (what == "mass") {
- r_ret = get_jiggle_joint_mass(which);
- } else if (what == "damping") {
- r_ret = get_jiggle_joint_damping(which);
- } else if (what == "use_gravity") {
- r_ret = get_jiggle_joint_use_gravity(which);
- } else if (what == "gravity") {
- r_ret = get_jiggle_joint_gravity(which);
- } else if (what == "roll") {
- r_ret = Math::rad_to_deg(get_jiggle_joint_roll(which));
- }
- return true;
- } else {
- if (path == "use_colliders") {
- r_ret = get_use_colliders();
- } else if (path == "collision_mask") {
- r_ret = get_collision_mask();
- }
- return true;
- }
- return true;
-}
-
-void SkeletonModification3DJiggle::_get_property_list(List<PropertyInfo> *p_list) const {
- p_list->push_back(PropertyInfo(Variant::BOOL, "use_colliders", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
- if (use_colliders) {
- p_list->push_back(PropertyInfo(Variant::INT, "collision_mask", PROPERTY_HINT_LAYERS_3D_PHYSICS, "", PROPERTY_USAGE_DEFAULT));
- }
-
- for (uint32_t i = 0; i < jiggle_data_chain.size(); i++) {
- String base_string = "joint_data/" + itos(i) + "/";
-
- p_list->push_back(PropertyInfo(Variant::STRING_NAME, base_string + "bone_name", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
- p_list->push_back(PropertyInfo(Variant::INT, base_string + "bone_index", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
- p_list->push_back(PropertyInfo(Variant::FLOAT, base_string + "roll", PROPERTY_HINT_RANGE, "-360,360,0.01", PROPERTY_USAGE_DEFAULT));
- p_list->push_back(PropertyInfo(Variant::BOOL, base_string + "override_defaults", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
-
- if (jiggle_data_chain[i].override_defaults) {
- p_list->push_back(PropertyInfo(Variant::FLOAT, base_string + "stiffness", PROPERTY_HINT_RANGE, "0, 1000, 0.01", PROPERTY_USAGE_DEFAULT));
- p_list->push_back(PropertyInfo(Variant::FLOAT, base_string + "mass", PROPERTY_HINT_RANGE, "0, 1000, 0.01", PROPERTY_USAGE_DEFAULT));
- p_list->push_back(PropertyInfo(Variant::FLOAT, base_string + "damping", PROPERTY_HINT_RANGE, "0, 1, 0.01", PROPERTY_USAGE_DEFAULT));
- p_list->push_back(PropertyInfo(Variant::BOOL, base_string + "use_gravity", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
- if (jiggle_data_chain[i].use_gravity) {
- p_list->push_back(PropertyInfo(Variant::VECTOR3, base_string + "gravity", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
- }
- }
- }
-}
-
-void SkeletonModification3DJiggle::_execute(real_t p_delta) {
- ERR_FAIL_COND_MSG(!stack || !is_setup || stack->skeleton == nullptr,
- "Modification is not setup and therefore cannot execute!");
- if (!enabled) {
- return;
- }
- if (target_node_cache.is_null()) {
- _print_execution_error(true, "Target cache is out of date. Attempting to update...");
- update_cache();
- return;
- }
- Node3D *target = Object::cast_to<Node3D>(ObjectDB::get_instance(target_node_cache));
- _print_execution_error(!target || !target->is_inside_tree(), "Target node is not in the scene tree. Cannot execute modification!");
-
- for (uint32_t i = 0; i < jiggle_data_chain.size(); i++) {
- _execute_jiggle_joint(i, target, p_delta);
- }
-
- execution_error_found = false;
-}
-
-void SkeletonModification3DJiggle::_execute_jiggle_joint(int p_joint_idx, Node3D *p_target, real_t p_delta) {
- // Adopted from: https://wiki.unity3d.com/index.php/JiggleBone
- // With modifications by TwistedTwigleg.
-
- if (jiggle_data_chain[p_joint_idx].bone_idx <= -2) {
- jiggle_data_chain[p_joint_idx].bone_idx = stack->skeleton->find_bone(jiggle_data_chain[p_joint_idx].bone_name);
- }
- if (_print_execution_error(
- jiggle_data_chain[p_joint_idx].bone_idx < 0 || jiggle_data_chain[p_joint_idx].bone_idx > stack->skeleton->get_bone_count(),
- "Jiggle joint " + itos(p_joint_idx) + " bone index is invalid. Cannot execute modification!")) {
- return;
- }
-
- Transform3D bone_local_pos = stack->skeleton->get_bone_local_pose_override(jiggle_data_chain[p_joint_idx].bone_idx);
- if (bone_local_pos == Transform3D()) {
- bone_local_pos = stack->skeleton->get_bone_pose(jiggle_data_chain[p_joint_idx].bone_idx);
- }
-
- Transform3D new_bone_trans = stack->skeleton->local_pose_to_global_pose(jiggle_data_chain[p_joint_idx].bone_idx, bone_local_pos);
- Vector3 target_position = stack->skeleton->world_transform_to_global_pose(p_target->get_global_transform()).origin;
-
- jiggle_data_chain[p_joint_idx].force = (target_position - jiggle_data_chain[p_joint_idx].dynamic_position) * jiggle_data_chain[p_joint_idx].stiffness * p_delta;
-
- if (jiggle_data_chain[p_joint_idx].use_gravity) {
- Vector3 gravity_to_apply = new_bone_trans.basis.inverse().xform(jiggle_data_chain[p_joint_idx].gravity);
- jiggle_data_chain[p_joint_idx].force += gravity_to_apply * p_delta;
- }
-
- jiggle_data_chain[p_joint_idx].acceleration = jiggle_data_chain[p_joint_idx].force / jiggle_data_chain[p_joint_idx].mass;
- jiggle_data_chain[p_joint_idx].velocity += jiggle_data_chain[p_joint_idx].acceleration * (1 - jiggle_data_chain[p_joint_idx].damping);
-
- jiggle_data_chain[p_joint_idx].dynamic_position += jiggle_data_chain[p_joint_idx].velocity + jiggle_data_chain[p_joint_idx].force;
- jiggle_data_chain[p_joint_idx].dynamic_position += new_bone_trans.origin - jiggle_data_chain[p_joint_idx].last_position;
- jiggle_data_chain[p_joint_idx].last_position = new_bone_trans.origin;
-
- // Collision detection/response
- if (use_colliders) {
- if (execution_mode == SkeletonModificationStack3D::EXECUTION_MODE::execution_mode_physics_process) {
- Ref<World3D> world_3d = stack->skeleton->get_world_3d();
- ERR_FAIL_COND(world_3d.is_null());
- PhysicsDirectSpaceState3D *space_state = PhysicsServer3D::get_singleton()->space_get_direct_state(world_3d->get_space());
- PhysicsDirectSpaceState3D::RayResult ray_result;
-
- // Convert to world transforms, which is what the physics server needs
- Transform3D new_bone_trans_world = stack->skeleton->global_pose_to_world_transform(new_bone_trans);
- Transform3D dynamic_position_world = stack->skeleton->global_pose_to_world_transform(Transform3D(Basis(), jiggle_data_chain[p_joint_idx].dynamic_position));
-
- PhysicsDirectSpaceState3D::RayParameters ray_params;
- ray_params.from = new_bone_trans_world.origin;
- ray_params.to = dynamic_position_world.get_origin();
- ray_params.collision_mask = collision_mask;
-
- bool ray_hit = space_state->intersect_ray(ray_params, ray_result);
-
- if (ray_hit) {
- jiggle_data_chain[p_joint_idx].dynamic_position = jiggle_data_chain[p_joint_idx].last_noncollision_position;
- jiggle_data_chain[p_joint_idx].acceleration = Vector3(0, 0, 0);
- jiggle_data_chain[p_joint_idx].velocity = Vector3(0, 0, 0);
- } else {
- jiggle_data_chain[p_joint_idx].last_noncollision_position = jiggle_data_chain[p_joint_idx].dynamic_position;
- }
-
- } else {
- WARN_PRINT_ONCE("Jiggle modifier: You cannot detect colliders without the stack mode being set to _physics_process!");
- }
- }
-
- // Get the forward direction that the basis is facing in right now.
- stack->skeleton->update_bone_rest_forward_vector(jiggle_data_chain[p_joint_idx].bone_idx);
- Vector3 forward_vector = stack->skeleton->get_bone_axis_forward_vector(jiggle_data_chain[p_joint_idx].bone_idx);
-
- // Rotate the bone using the dynamic position!
- new_bone_trans.basis.rotate_to_align(forward_vector, new_bone_trans.origin.direction_to(jiggle_data_chain[p_joint_idx].dynamic_position));
-
- // Roll
- new_bone_trans.basis.rotate_local(forward_vector, jiggle_data_chain[p_joint_idx].roll);
-
- new_bone_trans = stack->skeleton->global_pose_to_local_pose(jiggle_data_chain[p_joint_idx].bone_idx, new_bone_trans);
- stack->skeleton->set_bone_local_pose_override(jiggle_data_chain[p_joint_idx].bone_idx, new_bone_trans, stack->strength, true);
- stack->skeleton->force_update_bone_children_transforms(jiggle_data_chain[p_joint_idx].bone_idx);
-}
-
-void SkeletonModification3DJiggle::_update_jiggle_joint_data() {
- for (uint32_t i = 0; i < jiggle_data_chain.size(); i++) {
- if (!jiggle_data_chain[i].override_defaults) {
- set_jiggle_joint_stiffness(i, stiffness);
- set_jiggle_joint_mass(i, mass);
- set_jiggle_joint_damping(i, damping);
- set_jiggle_joint_use_gravity(i, use_gravity);
- set_jiggle_joint_gravity(i, gravity);
- }
- }
-}
-
-void SkeletonModification3DJiggle::_setup_modification(SkeletonModificationStack3D *p_stack) {
- stack = p_stack;
-
- if (stack) {
- is_setup = true;
- execution_error_found = false;
-
- if (stack->skeleton) {
- for (uint32_t i = 0; i < jiggle_data_chain.size(); i++) {
- int bone_idx = jiggle_data_chain[i].bone_idx;
- if (bone_idx > 0 && bone_idx < stack->skeleton->get_bone_count()) {
- jiggle_data_chain[i].dynamic_position = stack->skeleton->local_pose_to_global_pose(bone_idx, stack->skeleton->get_bone_local_pose_override(bone_idx)).origin;
- }
- }
- }
-
- update_cache();
- }
-}
-
-void SkeletonModification3DJiggle::update_cache() {
- if (!is_setup || !stack) {
- _print_execution_error(true, "Cannot update target cache: modification is not properly setup!");
- return;
- }
-
- target_node_cache = ObjectID();
- if (stack->skeleton) {
- if (stack->skeleton->is_inside_tree()) {
- if (stack->skeleton->has_node(target_node)) {
- Node *node = stack->skeleton->get_node(target_node);
- ERR_FAIL_COND_MSG(!node || stack->skeleton == node,
- "Cannot update target cache: node is this modification's skeleton or cannot be found!");
- ERR_FAIL_COND_MSG(!node->is_inside_tree(),
- "Cannot update target cache: node is not in the scene tree!");
- target_node_cache = node->get_instance_id();
-
- execution_error_found = false;
- }
- }
- }
-}
-
-void SkeletonModification3DJiggle::set_target_node(const NodePath &p_target_node) {
- target_node = p_target_node;
- update_cache();
-}
-
-NodePath SkeletonModification3DJiggle::get_target_node() const {
- return target_node;
-}
-
-void SkeletonModification3DJiggle::set_stiffness(real_t p_stiffness) {
- ERR_FAIL_COND_MSG(p_stiffness < 0, "Stiffness cannot be set to a negative value!");
- stiffness = p_stiffness;
- _update_jiggle_joint_data();
-}
-
-real_t SkeletonModification3DJiggle::get_stiffness() const {
- return stiffness;
-}
-
-void SkeletonModification3DJiggle::set_mass(real_t p_mass) {
- ERR_FAIL_COND_MSG(p_mass < 0, "Mass cannot be set to a negative value!");
- mass = p_mass;
- _update_jiggle_joint_data();
-}
-
-real_t SkeletonModification3DJiggle::get_mass() const {
- return mass;
-}
-
-void SkeletonModification3DJiggle::set_damping(real_t p_damping) {
- ERR_FAIL_COND_MSG(p_damping < 0, "Damping cannot be set to a negative value!");
- ERR_FAIL_COND_MSG(p_damping > 1, "Damping cannot be more than one!");
- damping = p_damping;
- _update_jiggle_joint_data();
-}
-
-real_t SkeletonModification3DJiggle::get_damping() const {
- return damping;
-}
-
-void SkeletonModification3DJiggle::set_use_gravity(bool p_use_gravity) {
- use_gravity = p_use_gravity;
- _update_jiggle_joint_data();
-}
-
-bool SkeletonModification3DJiggle::get_use_gravity() const {
- return use_gravity;
-}
-
-void SkeletonModification3DJiggle::set_gravity(Vector3 p_gravity) {
- gravity = p_gravity;
- _update_jiggle_joint_data();
-}
-
-Vector3 SkeletonModification3DJiggle::get_gravity() const {
- return gravity;
-}
-
-void SkeletonModification3DJiggle::set_use_colliders(bool p_use_collider) {
- use_colliders = p_use_collider;
- notify_property_list_changed();
-}
-
-bool SkeletonModification3DJiggle::get_use_colliders() const {
- return use_colliders;
-}
-
-void SkeletonModification3DJiggle::set_collision_mask(int p_mask) {
- collision_mask = p_mask;
-}
-
-int SkeletonModification3DJiggle::get_collision_mask() const {
- return collision_mask;
-}
-
-// Jiggle joint data functions
-int SkeletonModification3DJiggle::get_jiggle_data_chain_length() {
- return jiggle_data_chain.size();
-}
-
-void SkeletonModification3DJiggle::set_jiggle_data_chain_length(int p_length) {
- ERR_FAIL_COND(p_length < 0);
- jiggle_data_chain.resize(p_length);
- execution_error_found = false;
- notify_property_list_changed();
-}
-
-void SkeletonModification3DJiggle::set_jiggle_joint_bone_name(int p_joint_idx, String p_name) {
- const int bone_chain_size = jiggle_data_chain.size();
- ERR_FAIL_INDEX(p_joint_idx, bone_chain_size);
-
- jiggle_data_chain[p_joint_idx].bone_name = p_name;
- if (stack && stack->skeleton) {
- jiggle_data_chain[p_joint_idx].bone_idx = stack->skeleton->find_bone(p_name);
- }
- execution_error_found = false;
- notify_property_list_changed();
-}
-
-String SkeletonModification3DJiggle::get_jiggle_joint_bone_name(int p_joint_idx) const {
- const int bone_chain_size = jiggle_data_chain.size();
- ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, "");
- return jiggle_data_chain[p_joint_idx].bone_name;
-}
-
-int SkeletonModification3DJiggle::get_jiggle_joint_bone_index(int p_joint_idx) const {
- const int bone_chain_size = jiggle_data_chain.size();
- ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, -1);
- return jiggle_data_chain[p_joint_idx].bone_idx;
-}
-
-void SkeletonModification3DJiggle::set_jiggle_joint_bone_index(int p_joint_idx, int p_bone_idx) {
- const int bone_chain_size = jiggle_data_chain.size();
- ERR_FAIL_INDEX(p_joint_idx, bone_chain_size);
- ERR_FAIL_COND_MSG(p_bone_idx < 0, "Bone index is out of range: The index is too low!");
- jiggle_data_chain[p_joint_idx].bone_idx = p_bone_idx;
-
- if (stack) {
- if (stack->skeleton) {
- jiggle_data_chain[p_joint_idx].bone_name = stack->skeleton->get_bone_name(p_bone_idx);
- }
- }
- execution_error_found = false;
- notify_property_list_changed();
-}
-
-void SkeletonModification3DJiggle::set_jiggle_joint_override(int p_joint_idx, bool p_override) {
- const int bone_chain_size = jiggle_data_chain.size();
- ERR_FAIL_INDEX(p_joint_idx, bone_chain_size);
- jiggle_data_chain[p_joint_idx].override_defaults = p_override;
- _update_jiggle_joint_data();
- notify_property_list_changed();
-}
-
-bool SkeletonModification3DJiggle::get_jiggle_joint_override(int p_joint_idx) const {
- const int bone_chain_size = jiggle_data_chain.size();
- ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, false);
- return jiggle_data_chain[p_joint_idx].override_defaults;
-}
-
-void SkeletonModification3DJiggle::set_jiggle_joint_stiffness(int p_joint_idx, real_t p_stiffness) {
- const int bone_chain_size = jiggle_data_chain.size();
- ERR_FAIL_COND_MSG(p_stiffness < 0, "Stiffness cannot be set to a negative value!");
- ERR_FAIL_INDEX(p_joint_idx, bone_chain_size);
- jiggle_data_chain[p_joint_idx].stiffness = p_stiffness;
-}
-
-real_t SkeletonModification3DJiggle::get_jiggle_joint_stiffness(int p_joint_idx) const {
- const int bone_chain_size = jiggle_data_chain.size();
- ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, -1);
- return jiggle_data_chain[p_joint_idx].stiffness;
-}
-
-void SkeletonModification3DJiggle::set_jiggle_joint_mass(int p_joint_idx, real_t p_mass) {
- const int bone_chain_size = jiggle_data_chain.size();
- ERR_FAIL_COND_MSG(p_mass < 0, "Mass cannot be set to a negative value!");
- ERR_FAIL_INDEX(p_joint_idx, bone_chain_size);
- jiggle_data_chain[p_joint_idx].mass = p_mass;
-}
-
-real_t SkeletonModification3DJiggle::get_jiggle_joint_mass(int p_joint_idx) const {
- const int bone_chain_size = jiggle_data_chain.size();
- ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, -1);
- return jiggle_data_chain[p_joint_idx].mass;
-}
-
-void SkeletonModification3DJiggle::set_jiggle_joint_damping(int p_joint_idx, real_t p_damping) {
- const int bone_chain_size = jiggle_data_chain.size();
- ERR_FAIL_COND_MSG(p_damping < 0, "Damping cannot be set to a negative value!");
- ERR_FAIL_INDEX(p_joint_idx, bone_chain_size);
- jiggle_data_chain[p_joint_idx].damping = p_damping;
-}
-
-real_t SkeletonModification3DJiggle::get_jiggle_joint_damping(int p_joint_idx) const {
- const int bone_chain_size = jiggle_data_chain.size();
- ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, -1);
- return jiggle_data_chain[p_joint_idx].damping;
-}
-
-void SkeletonModification3DJiggle::set_jiggle_joint_use_gravity(int p_joint_idx, bool p_use_gravity) {
- const int bone_chain_size = jiggle_data_chain.size();
- ERR_FAIL_INDEX(p_joint_idx, bone_chain_size);
- jiggle_data_chain[p_joint_idx].use_gravity = p_use_gravity;
- notify_property_list_changed();
-}
-
-bool SkeletonModification3DJiggle::get_jiggle_joint_use_gravity(int p_joint_idx) const {
- const int bone_chain_size = jiggle_data_chain.size();
- ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, false);
- return jiggle_data_chain[p_joint_idx].use_gravity;
-}
-
-void SkeletonModification3DJiggle::set_jiggle_joint_gravity(int p_joint_idx, Vector3 p_gravity) {
- const int bone_chain_size = jiggle_data_chain.size();
- ERR_FAIL_INDEX(p_joint_idx, bone_chain_size);
- jiggle_data_chain[p_joint_idx].gravity = p_gravity;
-}
-
-Vector3 SkeletonModification3DJiggle::get_jiggle_joint_gravity(int p_joint_idx) const {
- const int bone_chain_size = jiggle_data_chain.size();
- ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, Vector3(0, 0, 0));
- return jiggle_data_chain[p_joint_idx].gravity;
-}
-
-void SkeletonModification3DJiggle::set_jiggle_joint_roll(int p_joint_idx, real_t p_roll) {
- const int bone_chain_size = jiggle_data_chain.size();
- ERR_FAIL_INDEX(p_joint_idx, bone_chain_size);
- jiggle_data_chain[p_joint_idx].roll = p_roll;
-}
-
-real_t SkeletonModification3DJiggle::get_jiggle_joint_roll(int p_joint_idx) const {
- const int bone_chain_size = jiggle_data_chain.size();
- ERR_FAIL_INDEX_V(p_joint_idx, bone_chain_size, 0.0);
- return jiggle_data_chain[p_joint_idx].roll;
-}
-
-void SkeletonModification3DJiggle::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_target_node", "target_nodepath"), &SkeletonModification3DJiggle::set_target_node);
- ClassDB::bind_method(D_METHOD("get_target_node"), &SkeletonModification3DJiggle::get_target_node);
-
- ClassDB::bind_method(D_METHOD("set_jiggle_data_chain_length", "length"), &SkeletonModification3DJiggle::set_jiggle_data_chain_length);
- ClassDB::bind_method(D_METHOD("get_jiggle_data_chain_length"), &SkeletonModification3DJiggle::get_jiggle_data_chain_length);
-
- ClassDB::bind_method(D_METHOD("set_stiffness", "stiffness"), &SkeletonModification3DJiggle::set_stiffness);
- ClassDB::bind_method(D_METHOD("get_stiffness"), &SkeletonModification3DJiggle::get_stiffness);
- ClassDB::bind_method(D_METHOD("set_mass", "mass"), &SkeletonModification3DJiggle::set_mass);
- ClassDB::bind_method(D_METHOD("get_mass"), &SkeletonModification3DJiggle::get_mass);
- ClassDB::bind_method(D_METHOD("set_damping", "damping"), &SkeletonModification3DJiggle::set_damping);
- ClassDB::bind_method(D_METHOD("get_damping"), &SkeletonModification3DJiggle::get_damping);
- ClassDB::bind_method(D_METHOD("set_use_gravity", "use_gravity"), &SkeletonModification3DJiggle::set_use_gravity);
- ClassDB::bind_method(D_METHOD("get_use_gravity"), &SkeletonModification3DJiggle::get_use_gravity);
- ClassDB::bind_method(D_METHOD("set_gravity", "gravity"), &SkeletonModification3DJiggle::set_gravity);
- ClassDB::bind_method(D_METHOD("get_gravity"), &SkeletonModification3DJiggle::get_gravity);
-
- ClassDB::bind_method(D_METHOD("set_use_colliders", "use_colliders"), &SkeletonModification3DJiggle::set_use_colliders);
- ClassDB::bind_method(D_METHOD("get_use_colliders"), &SkeletonModification3DJiggle::get_use_colliders);
- ClassDB::bind_method(D_METHOD("set_collision_mask", "mask"), &SkeletonModification3DJiggle::set_collision_mask);
- ClassDB::bind_method(D_METHOD("get_collision_mask"), &SkeletonModification3DJiggle::get_collision_mask);
-
- // Jiggle joint data functions
- ClassDB::bind_method(D_METHOD("set_jiggle_joint_bone_name", "joint_idx", "name"), &SkeletonModification3DJiggle::set_jiggle_joint_bone_name);
- ClassDB::bind_method(D_METHOD("get_jiggle_joint_bone_name", "joint_idx"), &SkeletonModification3DJiggle::get_jiggle_joint_bone_name);
- ClassDB::bind_method(D_METHOD("set_jiggle_joint_bone_index", "joint_idx", "bone_idx"), &SkeletonModification3DJiggle::set_jiggle_joint_bone_index);
- ClassDB::bind_method(D_METHOD("get_jiggle_joint_bone_index", "joint_idx"), &SkeletonModification3DJiggle::get_jiggle_joint_bone_index);
- ClassDB::bind_method(D_METHOD("set_jiggle_joint_override", "joint_idx", "override"), &SkeletonModification3DJiggle::set_jiggle_joint_override);
- ClassDB::bind_method(D_METHOD("get_jiggle_joint_override", "joint_idx"), &SkeletonModification3DJiggle::get_jiggle_joint_override);
- ClassDB::bind_method(D_METHOD("set_jiggle_joint_stiffness", "joint_idx", "stiffness"), &SkeletonModification3DJiggle::set_jiggle_joint_stiffness);
- ClassDB::bind_method(D_METHOD("get_jiggle_joint_stiffness", "joint_idx"), &SkeletonModification3DJiggle::get_jiggle_joint_stiffness);
- ClassDB::bind_method(D_METHOD("set_jiggle_joint_mass", "joint_idx", "mass"), &SkeletonModification3DJiggle::set_jiggle_joint_mass);
- ClassDB::bind_method(D_METHOD("get_jiggle_joint_mass", "joint_idx"), &SkeletonModification3DJiggle::get_jiggle_joint_mass);
- ClassDB::bind_method(D_METHOD("set_jiggle_joint_damping", "joint_idx", "damping"), &SkeletonModification3DJiggle::set_jiggle_joint_damping);
- ClassDB::bind_method(D_METHOD("get_jiggle_joint_damping", "joint_idx"), &SkeletonModification3DJiggle::get_jiggle_joint_damping);
- ClassDB::bind_method(D_METHOD("set_jiggle_joint_use_gravity", "joint_idx", "use_gravity"), &SkeletonModification3DJiggle::set_jiggle_joint_use_gravity);
- ClassDB::bind_method(D_METHOD("get_jiggle_joint_use_gravity", "joint_idx"), &SkeletonModification3DJiggle::get_jiggle_joint_use_gravity);
- ClassDB::bind_method(D_METHOD("set_jiggle_joint_gravity", "joint_idx", "gravity"), &SkeletonModification3DJiggle::set_jiggle_joint_gravity);
- ClassDB::bind_method(D_METHOD("get_jiggle_joint_gravity", "joint_idx"), &SkeletonModification3DJiggle::get_jiggle_joint_gravity);
- ClassDB::bind_method(D_METHOD("set_jiggle_joint_roll", "joint_idx", "roll"), &SkeletonModification3DJiggle::set_jiggle_joint_roll);
- ClassDB::bind_method(D_METHOD("get_jiggle_joint_roll", "joint_idx"), &SkeletonModification3DJiggle::get_jiggle_joint_roll);
-
- ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "target_nodepath", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Node3D"), "set_target_node", "get_target_node");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "jiggle_data_chain_length", PROPERTY_HINT_RANGE, "0,100,1"), "set_jiggle_data_chain_length", "get_jiggle_data_chain_length");
- ADD_GROUP("Default Joint Settings", "");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "stiffness"), "set_stiffness", "get_stiffness");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "mass"), "set_mass", "get_mass");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "damping", PROPERTY_HINT_RANGE, "0, 1, 0.01"), "set_damping", "get_damping");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_gravity"), "set_use_gravity", "get_use_gravity");
- ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "gravity"), "set_gravity", "get_gravity");
- ADD_GROUP("", "");
-}
-
-SkeletonModification3DJiggle::SkeletonModification3DJiggle() {
- stack = nullptr;
- is_setup = false;
- jiggle_data_chain = Vector<Jiggle_Joint_Data>();
- stiffness = 3;
- mass = 0.75;
- damping = 0.75;
- use_gravity = false;
- gravity = Vector3(0, -6.0, 0);
- enabled = true;
-}
-
-SkeletonModification3DJiggle::~SkeletonModification3DJiggle() {
-}
diff --git a/scene/resources/skeleton_modification_3d_jiggle.h b/scene/resources/skeleton_modification_3d_jiggle.h
deleted file mode 100644
index cca620a72d..0000000000
--- a/scene/resources/skeleton_modification_3d_jiggle.h
+++ /dev/null
@@ -1,138 +0,0 @@
-/**************************************************************************/
-/* skeleton_modification_3d_jiggle.h */
-/**************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/**************************************************************************/
-/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
-/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
-/* */
-/* 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 SKELETON_MODIFICATION_3D_JIGGLE_H
-#define SKELETON_MODIFICATION_3D_JIGGLE_H
-
-#include "core/templates/local_vector.h"
-#include "scene/3d/skeleton_3d.h"
-#include "scene/resources/skeleton_modification_3d.h"
-
-class SkeletonModification3DJiggle : public SkeletonModification3D {
- GDCLASS(SkeletonModification3DJiggle, SkeletonModification3D);
-
-private:
- struct Jiggle_Joint_Data {
- String bone_name = "";
- int bone_idx = -1;
-
- bool override_defaults = false;
- real_t stiffness = 3;
- real_t mass = 0.75;
- real_t damping = 0.75;
- bool use_gravity = false;
- Vector3 gravity = Vector3(0, -6.0, 0);
- real_t roll = 0;
-
- Vector3 cached_rotation = Vector3(0, 0, 0);
- Vector3 force = Vector3(0, 0, 0);
- Vector3 acceleration = Vector3(0, 0, 0);
- Vector3 velocity = Vector3(0, 0, 0);
- Vector3 last_position = Vector3(0, 0, 0);
- Vector3 dynamic_position = Vector3(0, 0, 0);
-
- Vector3 last_noncollision_position = Vector3(0, 0, 0);
- };
-
- NodePath target_node;
- ObjectID target_node_cache;
- LocalVector<Jiggle_Joint_Data> jiggle_data_chain;
-
- real_t stiffness = 3;
- real_t mass = 0.75;
- real_t damping = 0.75;
- bool use_gravity = false;
- Vector3 gravity = Vector3(0, -6.0, 0);
-
- bool use_colliders = false;
- uint32_t collision_mask = 1;
-
- void update_cache();
- void _execute_jiggle_joint(int p_joint_idx, Node3D *p_target, real_t p_delta);
- void _update_jiggle_joint_data();
-
-protected:
- static void _bind_methods();
- bool _get(const StringName &p_path, Variant &r_ret) const;
- bool _set(const StringName &p_path, const Variant &p_value);
- void _get_property_list(List<PropertyInfo> *p_list) const;
-
-public:
- virtual void _execute(real_t p_delta) override;
- virtual void _setup_modification(SkeletonModificationStack3D *p_stack) override;
-
- void set_target_node(const NodePath &p_target_node);
- NodePath get_target_node() const;
-
- void set_stiffness(real_t p_stiffness);
- real_t get_stiffness() const;
- void set_mass(real_t p_mass);
- real_t get_mass() const;
- void set_damping(real_t p_damping);
- real_t get_damping() const;
-
- void set_use_gravity(bool p_use_gravity);
- bool get_use_gravity() const;
- void set_gravity(Vector3 p_gravity);
- Vector3 get_gravity() const;
-
- void set_use_colliders(bool p_use_colliders);
- bool get_use_colliders() const;
- void set_collision_mask(int p_mask);
- int get_collision_mask() const;
-
- int get_jiggle_data_chain_length();
- void set_jiggle_data_chain_length(int p_new_length);
-
- void set_jiggle_joint_bone_name(int p_joint_idx, String p_name);
- String get_jiggle_joint_bone_name(int p_joint_idx) const;
- void set_jiggle_joint_bone_index(int p_joint_idx, int p_idx);
- int get_jiggle_joint_bone_index(int p_joint_idx) const;
-
- void set_jiggle_joint_override(int p_joint_idx, bool p_override);
- bool get_jiggle_joint_override(int p_joint_idx) const;
- void set_jiggle_joint_stiffness(int p_joint_idx, real_t p_stiffness);
- real_t get_jiggle_joint_stiffness(int p_joint_idx) const;
- void set_jiggle_joint_mass(int p_joint_idx, real_t p_mass);
- real_t get_jiggle_joint_mass(int p_joint_idx) const;
- void set_jiggle_joint_damping(int p_joint_idx, real_t p_damping);
- real_t get_jiggle_joint_damping(int p_joint_idx) const;
- void set_jiggle_joint_use_gravity(int p_joint_idx, bool p_use_gravity);
- bool get_jiggle_joint_use_gravity(int p_joint_idx) const;
- void set_jiggle_joint_gravity(int p_joint_idx, Vector3 p_gravity);
- Vector3 get_jiggle_joint_gravity(int p_joint_idx) const;
- void set_jiggle_joint_roll(int p_joint_idx, real_t p_roll);
- real_t get_jiggle_joint_roll(int p_joint_idx) const;
-
- SkeletonModification3DJiggle();
- ~SkeletonModification3DJiggle();
-};
-
-#endif // SKELETON_MODIFICATION_3D_JIGGLE_H
diff --git a/scene/resources/skeleton_modification_3d_lookat.cpp b/scene/resources/skeleton_modification_3d_lookat.cpp
deleted file mode 100644
index 57eedeb64e..0000000000
--- a/scene/resources/skeleton_modification_3d_lookat.cpp
+++ /dev/null
@@ -1,267 +0,0 @@
-/**************************************************************************/
-/* skeleton_modification_3d_lookat.cpp */
-/**************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/**************************************************************************/
-/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
-/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
-/* */
-/* 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 "scene/resources/skeleton_modification_3d_lookat.h"
-#include "scene/3d/skeleton_3d.h"
-#include "scene/resources/skeleton_modification_3d.h"
-
-bool SkeletonModification3DLookAt::_set(const StringName &p_path, const Variant &p_value) {
- if (p_path == "lock_rotation_to_plane") {
- set_lock_rotation_to_plane(p_value);
- } else if (p_path == "lock_rotation_plane") {
- set_lock_rotation_plane(p_value);
- } else if (p_path == "additional_rotation") {
- Vector3 tmp = p_value;
- tmp.x = Math::deg_to_rad(tmp.x);
- tmp.y = Math::deg_to_rad(tmp.y);
- tmp.z = Math::deg_to_rad(tmp.z);
- set_additional_rotation(tmp);
- }
-
- return true;
-}
-
-bool SkeletonModification3DLookAt::_get(const StringName &p_path, Variant &r_ret) const {
- if (p_path == "lock_rotation_to_plane") {
- r_ret = get_lock_rotation_to_plane();
- } else if (p_path == "lock_rotation_plane") {
- r_ret = get_lock_rotation_plane();
- } else if (p_path == "additional_rotation") {
- Vector3 tmp = get_additional_rotation();
- tmp.x = Math::rad_to_deg(tmp.x);
- tmp.y = Math::rad_to_deg(tmp.y);
- tmp.z = Math::rad_to_deg(tmp.z);
- r_ret = tmp;
- }
-
- return true;
-}
-
-void SkeletonModification3DLookAt::_get_property_list(List<PropertyInfo> *p_list) const {
- p_list->push_back(PropertyInfo(Variant::BOOL, "lock_rotation_to_plane", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
- if (lock_rotation_to_plane) {
- p_list->push_back(PropertyInfo(Variant::INT, "lock_rotation_plane", PROPERTY_HINT_ENUM, "X plane,Y plane,Z plane", PROPERTY_USAGE_DEFAULT));
- }
- p_list->push_back(PropertyInfo(Variant::VECTOR3, "additional_rotation", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
-}
-
-void SkeletonModification3DLookAt::_execute(real_t p_delta) {
- ERR_FAIL_COND_MSG(!stack || !is_setup || stack->skeleton == nullptr,
- "Modification is not setup and therefore cannot execute!");
- if (!enabled) {
- return;
- }
-
- if (target_node_cache.is_null()) {
- _print_execution_error(true, "Target cache is out of date. Attempting to update...");
- update_cache();
- return;
- }
-
- if (bone_idx <= -2) {
- bone_idx = stack->skeleton->find_bone(bone_name);
- }
-
- Node3D *target = Object::cast_to<Node3D>(ObjectDB::get_instance(target_node_cache));
- if (_print_execution_error(!target || !target->is_inside_tree(), "Target node is not in the scene tree. Cannot execute modification!")) {
- return;
- }
- if (_print_execution_error(bone_idx <= -1, "Bone index is invalid. Cannot execute modification!")) {
- return;
- }
- Transform3D new_bone_trans = stack->skeleton->get_bone_local_pose_override(bone_idx);
- if (new_bone_trans == Transform3D()) {
- new_bone_trans = stack->skeleton->get_bone_pose(bone_idx);
- }
- Vector3 target_pos = stack->skeleton->global_pose_to_local_pose(bone_idx, stack->skeleton->world_transform_to_global_pose(target->get_global_transform())).origin;
-
- // Lock the rotation to a plane relative to the bone by changing the target position
- if (lock_rotation_to_plane) {
- if (lock_rotation_plane == ROTATION_PLANE::ROTATION_PLANE_X) {
- target_pos.x = new_bone_trans.origin.x;
- } else if (lock_rotation_plane == ROTATION_PLANE::ROTATION_PLANE_Y) {
- target_pos.y = new_bone_trans.origin.y;
- } else if (lock_rotation_plane == ROTATION_PLANE::ROTATION_PLANE_Z) {
- target_pos.z = new_bone_trans.origin.z;
- }
- }
-
- // Look at the target!
- new_bone_trans = new_bone_trans.looking_at(target_pos, Vector3(0, 1, 0));
- // Convert from Z-forward to whatever direction the bone faces.
- stack->skeleton->update_bone_rest_forward_vector(bone_idx);
- new_bone_trans.basis = stack->skeleton->global_pose_z_forward_to_bone_forward(bone_idx, new_bone_trans.basis);
-
- // Apply additional rotation
- new_bone_trans.basis.rotate_local(Vector3(1, 0, 0), additional_rotation.x);
- new_bone_trans.basis.rotate_local(Vector3(0, 1, 0), additional_rotation.y);
- new_bone_trans.basis.rotate_local(Vector3(0, 0, 1), additional_rotation.z);
-
- stack->skeleton->set_bone_local_pose_override(bone_idx, new_bone_trans, stack->strength, true);
- stack->skeleton->force_update_bone_children_transforms(bone_idx);
-
- // If we completed it successfully, then we can set execution_error_found to false
- execution_error_found = false;
-}
-
-void SkeletonModification3DLookAt::_setup_modification(SkeletonModificationStack3D *p_stack) {
- stack = p_stack;
-
- if (stack != nullptr) {
- is_setup = true;
- execution_error_found = false;
- update_cache();
- }
-}
-
-void SkeletonModification3DLookAt::set_bone_name(String p_name) {
- bone_name = p_name;
- if (stack) {
- if (stack->skeleton) {
- bone_idx = stack->skeleton->find_bone(bone_name);
- }
- }
- execution_error_found = false;
- notify_property_list_changed();
-}
-
-String SkeletonModification3DLookAt::get_bone_name() const {
- return bone_name;
-}
-
-int SkeletonModification3DLookAt::get_bone_index() const {
- return bone_idx;
-}
-
-void SkeletonModification3DLookAt::set_bone_index(int p_bone_idx) {
- ERR_FAIL_COND_MSG(p_bone_idx < 0, "Bone index is out of range: The index is too low!");
- bone_idx = p_bone_idx;
-
- if (stack) {
- if (stack->skeleton) {
- bone_name = stack->skeleton->get_bone_name(p_bone_idx);
- }
- }
- execution_error_found = false;
- notify_property_list_changed();
-}
-
-void SkeletonModification3DLookAt::update_cache() {
- if (!is_setup || !stack) {
- _print_execution_error(true, "Cannot update target cache: modification is not properly setup!");
- return;
- }
-
- target_node_cache = ObjectID();
- if (stack->skeleton) {
- if (stack->skeleton->is_inside_tree()) {
- if (stack->skeleton->has_node(target_node)) {
- Node *node = stack->skeleton->get_node(target_node);
- ERR_FAIL_COND_MSG(!node || stack->skeleton == node,
- "Cannot update target cache: Node is this modification's skeleton or cannot be found!");
- ERR_FAIL_COND_MSG(!node->is_inside_tree(),
- "Cannot update target cache: Node is not in the scene tree!");
- target_node_cache = node->get_instance_id();
-
- execution_error_found = false;
- }
- }
- }
-}
-
-void SkeletonModification3DLookAt::set_target_node(const NodePath &p_target_node) {
- target_node = p_target_node;
- update_cache();
-}
-
-NodePath SkeletonModification3DLookAt::get_target_node() const {
- return target_node;
-}
-
-Vector3 SkeletonModification3DLookAt::get_additional_rotation() const {
- return additional_rotation;
-}
-
-void SkeletonModification3DLookAt::set_additional_rotation(Vector3 p_offset) {
- additional_rotation = p_offset;
-}
-
-bool SkeletonModification3DLookAt::get_lock_rotation_to_plane() const {
- return lock_rotation_plane;
-}
-
-void SkeletonModification3DLookAt::set_lock_rotation_to_plane(bool p_lock_rotation) {
- lock_rotation_to_plane = p_lock_rotation;
- notify_property_list_changed();
-}
-
-int SkeletonModification3DLookAt::get_lock_rotation_plane() const {
- return lock_rotation_plane;
-}
-
-void SkeletonModification3DLookAt::set_lock_rotation_plane(int p_plane) {
- lock_rotation_plane = p_plane;
-}
-
-void SkeletonModification3DLookAt::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_bone_name", "name"), &SkeletonModification3DLookAt::set_bone_name);
- ClassDB::bind_method(D_METHOD("get_bone_name"), &SkeletonModification3DLookAt::get_bone_name);
-
- ClassDB::bind_method(D_METHOD("set_bone_index", "bone_idx"), &SkeletonModification3DLookAt::set_bone_index);
- ClassDB::bind_method(D_METHOD("get_bone_index"), &SkeletonModification3DLookAt::get_bone_index);
-
- ClassDB::bind_method(D_METHOD("set_target_node", "target_nodepath"), &SkeletonModification3DLookAt::set_target_node);
- ClassDB::bind_method(D_METHOD("get_target_node"), &SkeletonModification3DLookAt::get_target_node);
-
- ClassDB::bind_method(D_METHOD("set_additional_rotation", "additional_rotation"), &SkeletonModification3DLookAt::set_additional_rotation);
- ClassDB::bind_method(D_METHOD("get_additional_rotation"), &SkeletonModification3DLookAt::get_additional_rotation);
-
- ClassDB::bind_method(D_METHOD("set_lock_rotation_to_plane", "lock_to_plane"), &SkeletonModification3DLookAt::set_lock_rotation_to_plane);
- ClassDB::bind_method(D_METHOD("get_lock_rotation_to_plane"), &SkeletonModification3DLookAt::get_lock_rotation_to_plane);
- ClassDB::bind_method(D_METHOD("set_lock_rotation_plane", "plane"), &SkeletonModification3DLookAt::set_lock_rotation_plane);
- ClassDB::bind_method(D_METHOD("get_lock_rotation_plane"), &SkeletonModification3DLookAt::get_lock_rotation_plane);
-
- ADD_PROPERTY(PropertyInfo(Variant::STRING_NAME, "bone_name"), "set_bone_name", "get_bone_name");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "bone_index"), "set_bone_index", "get_bone_index");
- ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "target_nodepath", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Node3D"), "set_target_node", "get_target_node");
-}
-
-SkeletonModification3DLookAt::SkeletonModification3DLookAt() {
- stack = nullptr;
- is_setup = false;
- bone_name = "";
- bone_idx = -2;
- additional_rotation = Vector3();
- lock_rotation_to_plane = false;
- enabled = true;
-}
-
-SkeletonModification3DLookAt::~SkeletonModification3DLookAt() {
-}
diff --git a/scene/resources/skeleton_modification_3d_lookat.h b/scene/resources/skeleton_modification_3d_lookat.h
deleted file mode 100644
index 9a25ac530d..0000000000
--- a/scene/resources/skeleton_modification_3d_lookat.h
+++ /dev/null
@@ -1,89 +0,0 @@
-/**************************************************************************/
-/* skeleton_modification_3d_lookat.h */
-/**************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/**************************************************************************/
-/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
-/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
-/* */
-/* 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 SKELETON_MODIFICATION_3D_LOOKAT_H
-#define SKELETON_MODIFICATION_3D_LOOKAT_H
-
-#include "scene/3d/skeleton_3d.h"
-#include "scene/resources/skeleton_modification_3d.h"
-
-class SkeletonModification3DLookAt : public SkeletonModification3D {
- GDCLASS(SkeletonModification3DLookAt, SkeletonModification3D);
-
-private:
- String bone_name = "";
- int bone_idx = -1;
- NodePath target_node;
- ObjectID target_node_cache;
-
- Vector3 additional_rotation = Vector3(1, 0, 0);
- bool lock_rotation_to_plane = false;
- int lock_rotation_plane = ROTATION_PLANE_X;
-
- void update_cache();
-
-protected:
- static void _bind_methods();
- bool _get(const StringName &p_path, Variant &r_ret) const;
- bool _set(const StringName &p_path, const Variant &p_value);
- void _get_property_list(List<PropertyInfo> *p_list) const;
-
-public:
- enum ROTATION_PLANE {
- ROTATION_PLANE_X,
- ROTATION_PLANE_Y,
- ROTATION_PLANE_Z
- };
-
- virtual void _execute(real_t p_delta) override;
- virtual void _setup_modification(SkeletonModificationStack3D *p_stack) override;
-
- void set_bone_name(String p_name);
- String get_bone_name() const;
-
- void set_bone_index(int p_idx);
- int get_bone_index() const;
-
- void set_target_node(const NodePath &p_target_node);
- NodePath get_target_node() const;
-
- void set_additional_rotation(Vector3 p_offset);
- Vector3 get_additional_rotation() const;
-
- void set_lock_rotation_to_plane(bool p_lock_to_plane);
- bool get_lock_rotation_to_plane() const;
- void set_lock_rotation_plane(int p_plane);
- int get_lock_rotation_plane() const;
-
- SkeletonModification3DLookAt();
- ~SkeletonModification3DLookAt();
-};
-
-#endif // SKELETON_MODIFICATION_3D_LOOKAT_H
diff --git a/scene/resources/skeleton_modification_3d_stackholder.cpp b/scene/resources/skeleton_modification_3d_stackholder.cpp
deleted file mode 100644
index 1598badb30..0000000000
--- a/scene/resources/skeleton_modification_3d_stackholder.cpp
+++ /dev/null
@@ -1,104 +0,0 @@
-/**************************************************************************/
-/* skeleton_modification_3d_stackholder.cpp */
-/**************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/**************************************************************************/
-/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
-/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
-/* */
-/* 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 "scene/resources/skeleton_modification_3d_stackholder.h"
-#include "scene/3d/skeleton_3d.h"
-#include "scene/resources/skeleton_modification_3d.h"
-
-bool SkeletonModification3DStackHolder::_set(const StringName &p_path, const Variant &p_value) {
- String path = p_path;
-
- if (path == "held_modification_stack") {
- set_held_modification_stack(p_value);
- }
- return true;
-}
-
-bool SkeletonModification3DStackHolder::_get(const StringName &p_path, Variant &r_ret) const {
- String path = p_path;
-
- if (path == "held_modification_stack") {
- r_ret = get_held_modification_stack();
- }
- return true;
-}
-
-void SkeletonModification3DStackHolder::_get_property_list(List<PropertyInfo> *p_list) const {
- p_list->push_back(PropertyInfo(Variant::OBJECT, "held_modification_stack", PROPERTY_HINT_RESOURCE_TYPE, "SkeletonModificationStack3D", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_DO_NOT_SHARE_ON_DUPLICATE));
-}
-
-void SkeletonModification3DStackHolder::_execute(real_t p_delta) {
- ERR_FAIL_COND_MSG(!stack || !is_setup || stack->skeleton == nullptr,
- "Modification is not setup and therefore cannot execute!");
-
- if (held_modification_stack.is_valid()) {
- held_modification_stack->execute(p_delta, execution_mode);
- }
-}
-
-void SkeletonModification3DStackHolder::_setup_modification(SkeletonModificationStack3D *p_stack) {
- stack = p_stack;
-
- if (stack != nullptr) {
- is_setup = true;
-
- if (held_modification_stack.is_valid()) {
- held_modification_stack->set_skeleton(stack->get_skeleton());
- held_modification_stack->setup();
- }
- }
-}
-
-void SkeletonModification3DStackHolder::set_held_modification_stack(Ref<SkeletonModificationStack3D> p_held_stack) {
- held_modification_stack = p_held_stack;
-
- if (is_setup && held_modification_stack.is_valid()) {
- held_modification_stack->set_skeleton(stack->get_skeleton());
- held_modification_stack->setup();
- }
-}
-
-Ref<SkeletonModificationStack3D> SkeletonModification3DStackHolder::get_held_modification_stack() const {
- return held_modification_stack;
-}
-
-void SkeletonModification3DStackHolder::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_held_modification_stack", "held_modification_stack"), &SkeletonModification3DStackHolder::set_held_modification_stack);
- ClassDB::bind_method(D_METHOD("get_held_modification_stack"), &SkeletonModification3DStackHolder::get_held_modification_stack);
-}
-
-SkeletonModification3DStackHolder::SkeletonModification3DStackHolder() {
- stack = nullptr;
- is_setup = false;
- enabled = true;
-}
-
-SkeletonModification3DStackHolder::~SkeletonModification3DStackHolder() {
-}
diff --git a/scene/resources/skeleton_modification_3d_stackholder.h b/scene/resources/skeleton_modification_3d_stackholder.h
deleted file mode 100644
index da39044f97..0000000000
--- a/scene/resources/skeleton_modification_3d_stackholder.h
+++ /dev/null
@@ -1,59 +0,0 @@
-/**************************************************************************/
-/* skeleton_modification_3d_stackholder.h */
-/**************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/**************************************************************************/
-/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
-/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
-/* */
-/* 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 SKELETON_MODIFICATION_3D_STACKHOLDER_H
-#define SKELETON_MODIFICATION_3D_STACKHOLDER_H
-
-#include "scene/3d/skeleton_3d.h"
-#include "scene/resources/skeleton_modification_3d.h"
-
-class SkeletonModification3DStackHolder : public SkeletonModification3D {
- GDCLASS(SkeletonModification3DStackHolder, SkeletonModification3D);
-
-protected:
- static void _bind_methods();
- bool _get(const StringName &p_path, Variant &r_ret) const;
- bool _set(const StringName &p_path, const Variant &p_value);
- void _get_property_list(List<PropertyInfo> *p_list) const;
-
-public:
- Ref<SkeletonModificationStack3D> held_modification_stack;
-
- virtual void _execute(real_t p_delta) override;
- virtual void _setup_modification(SkeletonModificationStack3D *p_stack) override;
-
- void set_held_modification_stack(Ref<SkeletonModificationStack3D> p_held_stack);
- Ref<SkeletonModificationStack3D> get_held_modification_stack() const;
-
- SkeletonModification3DStackHolder();
- ~SkeletonModification3DStackHolder();
-};
-
-#endif // SKELETON_MODIFICATION_3D_STACKHOLDER_H
diff --git a/scene/resources/skeleton_modification_3d_twoboneik.cpp b/scene/resources/skeleton_modification_3d_twoboneik.cpp
deleted file mode 100644
index 7d5b4d2b55..0000000000
--- a/scene/resources/skeleton_modification_3d_twoboneik.cpp
+++ /dev/null
@@ -1,617 +0,0 @@
-/**************************************************************************/
-/* skeleton_modification_3d_twoboneik.cpp */
-/**************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/**************************************************************************/
-/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
-/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
-/* */
-/* 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 "scene/resources/skeleton_modification_3d_twoboneik.h"
-#include "scene/3d/skeleton_3d.h"
-#include "scene/resources/skeleton_modification_3d.h"
-
-bool SkeletonModification3DTwoBoneIK::_set(const StringName &p_path, const Variant &p_value) {
- String path = p_path;
-
- if (path == "use_tip_node") {
- set_use_tip_node(p_value);
- } else if (path == "tip_node") {
- set_tip_node(p_value);
- } else if (path == "auto_calculate_joint_length") {
- set_auto_calculate_joint_length(p_value);
- } else if (path == "use_pole_node") {
- set_use_pole_node(p_value);
- } else if (path == "pole_node") {
- set_pole_node(p_value);
- } else if (path == "joint_one_length") {
- set_joint_one_length(p_value);
- } else if (path == "joint_two_length") {
- set_joint_two_length(p_value);
- } else if (path == "joint_one/bone_name") {
- set_joint_one_bone_name(p_value);
- } else if (path == "joint_one/bone_idx") {
- set_joint_one_bone_idx(p_value);
- } else if (path == "joint_one/roll") {
- set_joint_one_roll(Math::deg_to_rad(real_t(p_value)));
- } else if (path == "joint_two/bone_name") {
- set_joint_two_bone_name(p_value);
- } else if (path == "joint_two/bone_idx") {
- set_joint_two_bone_idx(p_value);
- } else if (path == "joint_two/roll") {
- set_joint_two_roll(Math::deg_to_rad(real_t(p_value)));
- }
-
- return true;
-}
-
-bool SkeletonModification3DTwoBoneIK::_get(const StringName &p_path, Variant &r_ret) const {
- String path = p_path;
-
- if (path == "use_tip_node") {
- r_ret = get_use_tip_node();
- } else if (path == "tip_node") {
- r_ret = get_tip_node();
- } else if (path == "auto_calculate_joint_length") {
- r_ret = get_auto_calculate_joint_length();
- } else if (path == "use_pole_node") {
- r_ret = get_use_pole_node();
- } else if (path == "pole_node") {
- r_ret = get_pole_node();
- } else if (path == "joint_one_length") {
- r_ret = get_joint_one_length();
- } else if (path == "joint_two_length") {
- r_ret = get_joint_two_length();
- } else if (path == "joint_one/bone_name") {
- r_ret = get_joint_one_bone_name();
- } else if (path == "joint_one/bone_idx") {
- r_ret = get_joint_one_bone_idx();
- } else if (path == "joint_one/roll") {
- r_ret = Math::rad_to_deg(get_joint_one_roll());
- } else if (path == "joint_two/bone_name") {
- r_ret = get_joint_two_bone_name();
- } else if (path == "joint_two/bone_idx") {
- r_ret = get_joint_two_bone_idx();
- } else if (path == "joint_two/roll") {
- r_ret = Math::rad_to_deg(get_joint_two_roll());
- }
-
- return true;
-}
-
-void SkeletonModification3DTwoBoneIK::_get_property_list(List<PropertyInfo> *p_list) const {
- p_list->push_back(PropertyInfo(Variant::BOOL, "use_tip_node", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
- if (use_tip_node) {
- p_list->push_back(PropertyInfo(Variant::NODE_PATH, "tip_node", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Node3D", PROPERTY_USAGE_DEFAULT));
- }
-
- p_list->push_back(PropertyInfo(Variant::BOOL, "auto_calculate_joint_length", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
- if (!auto_calculate_joint_length) {
- p_list->push_back(PropertyInfo(Variant::FLOAT, "joint_one_length", PROPERTY_HINT_RANGE, "-1, 10000, 0.001", PROPERTY_USAGE_DEFAULT));
- p_list->push_back(PropertyInfo(Variant::FLOAT, "joint_two_length", PROPERTY_HINT_RANGE, "-1, 10000, 0.001", PROPERTY_USAGE_DEFAULT));
- }
-
- p_list->push_back(PropertyInfo(Variant::BOOL, "use_pole_node", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
- if (use_pole_node) {
- p_list->push_back(PropertyInfo(Variant::NODE_PATH, "pole_node", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Node3D", PROPERTY_USAGE_DEFAULT));
- }
-
- p_list->push_back(PropertyInfo(Variant::STRING_NAME, "joint_one/bone_name", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
- p_list->push_back(PropertyInfo(Variant::INT, "joint_one/bone_idx", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
- p_list->push_back(PropertyInfo(Variant::FLOAT, "joint_one/roll", PROPERTY_HINT_RANGE, "-360, 360, 0.01", PROPERTY_USAGE_DEFAULT));
-
- p_list->push_back(PropertyInfo(Variant::STRING_NAME, "joint_two/bone_name", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
- p_list->push_back(PropertyInfo(Variant::INT, "joint_two/bone_idx", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT));
- p_list->push_back(PropertyInfo(Variant::FLOAT, "joint_two/roll", PROPERTY_HINT_RANGE, "-360, 360, 0.01", PROPERTY_USAGE_DEFAULT));
-}
-
-void SkeletonModification3DTwoBoneIK::_execute(real_t p_delta) {
- ERR_FAIL_COND_MSG(!stack || !is_setup || stack->skeleton == nullptr,
- "Modification is not setup and therefore cannot execute!");
-
- if (!enabled) {
- return;
- }
-
- if (_print_execution_error(joint_one_bone_idx < 0 || joint_two_bone_idx < 0,
- "One (or more) of the bones in the modification have invalid bone indexes. Cannot execute modification!")) {
- return;
- }
-
- if (target_node_cache.is_null()) {
- _print_execution_error(true, "Target cache is out of date. Attempting to update...");
- update_cache_target();
- return;
- }
-
- // Update joint lengths (if needed)
- if (auto_calculate_joint_length && (joint_one_length < 0 || joint_two_length < 0)) {
- calculate_joint_lengths();
- }
-
- // Adopted from the links below:
- // http://theorangeduck.com/page/simple-two-joint
- // https://www.alanzucconi.com/2018/05/02/ik-2d-2/
- // With modifications by TwistedTwigleg
- Node3D *target = Object::cast_to<Node3D>(ObjectDB::get_instance(target_node_cache));
- if (_print_execution_error(!target || !target->is_inside_tree(), "Target node is not in the scene tree. Cannot execute modification!")) {
- return;
- }
- Transform3D target_trans = stack->skeleton->world_transform_to_global_pose(target->get_global_transform());
-
- Transform3D bone_one_trans;
- Transform3D bone_two_trans;
-
- // Make the first joint look at the pole, and the second look at the target. That way, the
- // TwoBoneIK solver has to really only handle extension/contraction, which should make it align with the pole.
- if (use_pole_node) {
- if (pole_node_cache.is_null()) {
- _print_execution_error(true, "Pole cache is out of date. Attempting to update...");
- update_cache_pole();
- return;
- }
-
- Node3D *pole = Object::cast_to<Node3D>(ObjectDB::get_instance(pole_node_cache));
- if (_print_execution_error(!pole || !pole->is_inside_tree(), "Pole node is not in the scene tree. Cannot execute modification!")) {
- return;
- }
- Transform3D pole_trans = stack->skeleton->world_transform_to_global_pose(pole->get_global_transform());
-
- Transform3D bone_one_local_pos = stack->skeleton->get_bone_local_pose_override(joint_one_bone_idx);
- if (bone_one_local_pos == Transform3D()) {
- bone_one_local_pos = stack->skeleton->get_bone_pose(joint_one_bone_idx);
- }
- Transform3D bone_two_local_pos = stack->skeleton->get_bone_local_pose_override(joint_two_bone_idx);
- if (bone_two_local_pos == Transform3D()) {
- bone_two_local_pos = stack->skeleton->get_bone_pose(joint_two_bone_idx);
- }
-
- bone_one_trans = stack->skeleton->local_pose_to_global_pose(joint_one_bone_idx, bone_one_local_pos);
- bone_one_trans = bone_one_trans.looking_at(pole_trans.origin, Vector3(0, 1, 0));
- bone_one_trans.basis = stack->skeleton->global_pose_z_forward_to_bone_forward(joint_one_bone_idx, bone_one_trans.basis);
- stack->skeleton->update_bone_rest_forward_vector(joint_one_bone_idx);
- bone_one_trans.basis.rotate_local(stack->skeleton->get_bone_axis_forward_vector(joint_one_bone_idx), joint_one_roll);
- stack->skeleton->set_bone_local_pose_override(joint_one_bone_idx, stack->skeleton->global_pose_to_local_pose(joint_one_bone_idx, bone_one_trans), stack->strength, true);
- stack->skeleton->force_update_bone_children_transforms(joint_one_bone_idx);
-
- bone_two_trans = stack->skeleton->local_pose_to_global_pose(joint_two_bone_idx, bone_two_local_pos);
- bone_two_trans = bone_two_trans.looking_at(target_trans.origin, Vector3(0, 1, 0));
- bone_two_trans.basis = stack->skeleton->global_pose_z_forward_to_bone_forward(joint_two_bone_idx, bone_two_trans.basis);
- stack->skeleton->update_bone_rest_forward_vector(joint_two_bone_idx);
- bone_two_trans.basis.rotate_local(stack->skeleton->get_bone_axis_forward_vector(joint_two_bone_idx), joint_two_roll);
- stack->skeleton->set_bone_local_pose_override(joint_two_bone_idx, stack->skeleton->global_pose_to_local_pose(joint_two_bone_idx, bone_two_trans), stack->strength, true);
- stack->skeleton->force_update_bone_children_transforms(joint_two_bone_idx);
- } else {
- Transform3D bone_one_local_pos = stack->skeleton->get_bone_local_pose_override(joint_one_bone_idx);
- if (bone_one_local_pos == Transform3D()) {
- bone_one_local_pos = stack->skeleton->get_bone_pose(joint_one_bone_idx);
- }
- Transform3D bone_two_local_pos = stack->skeleton->get_bone_local_pose_override(joint_two_bone_idx);
- if (bone_two_local_pos == Transform3D()) {
- bone_two_local_pos = stack->skeleton->get_bone_pose(joint_two_bone_idx);
- }
-
- bone_one_trans = stack->skeleton->local_pose_to_global_pose(joint_one_bone_idx, bone_one_local_pos);
- bone_two_trans = stack->skeleton->local_pose_to_global_pose(joint_two_bone_idx, bone_two_local_pos);
- }
-
- Transform3D bone_two_tip_trans;
- if (use_tip_node) {
- if (tip_node_cache.is_null()) {
- _print_execution_error(true, "Tip cache is out of date. Attempting to update...");
- update_cache_tip();
- return;
- }
- Node3D *tip = Object::cast_to<Node3D>(ObjectDB::get_instance(tip_node_cache));
- if (_print_execution_error(!tip || !tip->is_inside_tree(), "Tip node is not in the scene tree. Cannot execute modification!")) {
- return;
- }
- bone_two_tip_trans = stack->skeleton->world_transform_to_global_pose(tip->get_global_transform());
- } else {
- stack->skeleton->update_bone_rest_forward_vector(joint_two_bone_idx);
- bone_two_tip_trans = bone_two_trans;
- bone_two_tip_trans.origin += bone_two_trans.basis.xform(stack->skeleton->get_bone_axis_forward_vector(joint_two_bone_idx)).normalized() * joint_two_length;
- }
-
- real_t joint_one_to_target_length = bone_one_trans.origin.distance_to(target_trans.origin);
- if (joint_one_length + joint_two_length < joint_one_to_target_length) {
- // Set the target *just* out of reach to straighten the bones
- joint_one_to_target_length = joint_one_length + joint_two_length + 0.01;
- } else if (joint_one_to_target_length < joint_one_length) {
- // Place the target in reach so the solver doesn't do crazy things
- joint_one_to_target_length = joint_one_length;
- }
-
- // Get the square lengths for all three sides of the triangle we'll use to calculate the angles
- real_t sqr_one_length = joint_one_length * joint_one_length;
- real_t sqr_two_length = joint_two_length * joint_two_length;
- real_t sqr_three_length = joint_one_to_target_length * joint_one_to_target_length;
-
- // Calculate the angles for the first joint using the law of cosigns
- real_t ac_ab_0 = Math::acos(CLAMP(bone_two_tip_trans.origin.direction_to(bone_one_trans.origin).dot(bone_two_trans.origin.direction_to(bone_one_trans.origin)), -1, 1));
- real_t ac_at_0 = Math::acos(CLAMP(bone_one_trans.origin.direction_to(bone_two_tip_trans.origin).dot(bone_one_trans.origin.direction_to(target_trans.origin)), -1, 1));
- real_t ac_ab_1 = Math::acos(CLAMP((sqr_two_length - sqr_one_length - sqr_three_length) / (-2.0 * joint_one_length * joint_one_to_target_length), -1, 1));
-
- // Calculate the angles of rotation. Angle 0 is the extension/contraction axis, while angle 1 is the rotation axis to align the triangle to the target
- Vector3 axis_0 = bone_one_trans.origin.direction_to(bone_two_tip_trans.origin).cross(bone_one_trans.origin.direction_to(bone_two_trans.origin));
- Vector3 axis_1 = bone_one_trans.origin.direction_to(bone_two_tip_trans.origin).cross(bone_one_trans.origin.direction_to(target_trans.origin));
-
- // Make a quaternion with the delta rotation needed to rotate the first joint into alignment and apply it to the transform.
- Quaternion bone_one_quat = bone_one_trans.basis.get_rotation_quaternion();
- Quaternion rot_0 = Quaternion(bone_one_quat.inverse().xform(axis_0).normalized(), (ac_ab_1 - ac_ab_0));
- Quaternion rot_2 = Quaternion(bone_one_quat.inverse().xform(axis_1).normalized(), ac_at_0);
- bone_one_trans.basis.set_quaternion(bone_one_quat * (rot_0 * rot_2));
-
- stack->skeleton->update_bone_rest_forward_vector(joint_one_bone_idx);
- bone_one_trans.basis.rotate_local(stack->skeleton->get_bone_axis_forward_vector(joint_one_bone_idx), joint_one_roll);
-
- // Apply the rotation to the first joint
- bone_one_trans = stack->skeleton->global_pose_to_local_pose(joint_one_bone_idx, bone_one_trans);
- bone_one_trans.origin = Vector3(0, 0, 0);
- stack->skeleton->set_bone_local_pose_override(joint_one_bone_idx, bone_one_trans, stack->strength, true);
- stack->skeleton->force_update_bone_children_transforms(joint_one_bone_idx);
-
- if (use_pole_node) {
- // Update bone_two_trans so its at the latest position, with the rotation of bone_one_trans taken into account, then look at the target.
- bone_two_trans = stack->skeleton->local_pose_to_global_pose(joint_two_bone_idx, stack->skeleton->get_bone_local_pose_override(joint_two_bone_idx));
- stack->skeleton->update_bone_rest_forward_vector(joint_two_bone_idx);
- Vector3 forward_vector = stack->skeleton->get_bone_axis_forward_vector(joint_two_bone_idx);
- bone_two_trans.basis.rotate_to_align(forward_vector, bone_two_trans.origin.direction_to(target_trans.origin));
-
- stack->skeleton->update_bone_rest_forward_vector(joint_two_bone_idx);
- bone_two_trans.basis.rotate_local(stack->skeleton->get_bone_axis_forward_vector(joint_two_bone_idx), joint_two_roll);
-
- bone_two_trans = stack->skeleton->global_pose_to_local_pose(joint_two_bone_idx, bone_two_trans);
- stack->skeleton->set_bone_local_pose_override(joint_two_bone_idx, bone_two_trans, stack->strength, true);
- stack->skeleton->force_update_bone_children_transforms(joint_two_bone_idx);
- } else {
- // Calculate the angles for the second joint using the law of cosigns, make a quaternion with the delta rotation needed to rotate the joint into
- // alignment, and then apply it to the second joint.
- real_t ba_bc_0 = Math::acos(CLAMP(bone_two_trans.origin.direction_to(bone_one_trans.origin).dot(bone_two_trans.origin.direction_to(bone_two_tip_trans.origin)), -1, 1));
- real_t ba_bc_1 = Math::acos(CLAMP((sqr_three_length - sqr_one_length - sqr_two_length) / (-2.0 * joint_one_length * joint_two_length), -1, 1));
- Quaternion bone_two_quat = bone_two_trans.basis.get_rotation_quaternion();
- Quaternion rot_1 = Quaternion(bone_two_quat.inverse().xform(axis_0).normalized(), (ba_bc_1 - ba_bc_0));
- bone_two_trans.basis.set_quaternion(bone_two_quat * rot_1);
-
- stack->skeleton->update_bone_rest_forward_vector(joint_two_bone_idx);
- bone_two_trans.basis.rotate_local(stack->skeleton->get_bone_axis_forward_vector(joint_two_bone_idx), joint_two_roll);
-
- bone_two_trans = stack->skeleton->global_pose_to_local_pose(joint_two_bone_idx, bone_two_trans);
- bone_two_trans.origin = Vector3(0, 0, 0);
- stack->skeleton->set_bone_local_pose_override(joint_two_bone_idx, bone_two_trans, stack->strength, true);
- stack->skeleton->force_update_bone_children_transforms(joint_two_bone_idx);
- }
-}
-
-void SkeletonModification3DTwoBoneIK::_setup_modification(SkeletonModificationStack3D *p_stack) {
- stack = p_stack;
-
- if (stack != nullptr) {
- is_setup = true;
- execution_error_found = false;
- update_cache_target();
- update_cache_tip();
- }
-}
-
-void SkeletonModification3DTwoBoneIK::update_cache_target() {
- if (!is_setup || !stack) {
- _print_execution_error(true, "Cannot update target cache: modification is not properly setup!");
- return;
- }
-
- target_node_cache = ObjectID();
- if (stack->skeleton) {
- if (stack->skeleton->is_inside_tree() && target_node.is_empty() == false) {
- if (stack->skeleton->has_node(target_node)) {
- Node *node = stack->skeleton->get_node(target_node);
- ERR_FAIL_COND_MSG(!node || stack->skeleton == node,
- "Cannot update target cache: Target node is this modification's skeleton or cannot be found. Cannot execute modification");
- ERR_FAIL_COND_MSG(!node->is_inside_tree(),
- "Cannot update target cache: Target node is not in the scene tree. Cannot execute modification!");
- target_node_cache = node->get_instance_id();
-
- execution_error_found = false;
- }
- }
- }
-}
-
-void SkeletonModification3DTwoBoneIK::update_cache_tip() {
- if (!is_setup || !stack) {
- _print_execution_error(true, "Cannot update tip cache: modification is not properly setup!");
- return;
- }
-
- tip_node_cache = ObjectID();
- if (stack->skeleton) {
- if (stack->skeleton->is_inside_tree()) {
- if (stack->skeleton->has_node(tip_node)) {
- Node *node = stack->skeleton->get_node(tip_node);
- ERR_FAIL_COND_MSG(!node || stack->skeleton == node,
- "Cannot update tip cache: Tip node is this modification's skeleton or cannot be found!");
- ERR_FAIL_COND_MSG(!node->is_inside_tree(),
- "Cannot update tip cache: Tip node is not in the scene tree. Cannot execute modification!");
- tip_node_cache = node->get_instance_id();
-
- execution_error_found = false;
- }
- }
- }
-}
-
-void SkeletonModification3DTwoBoneIK::update_cache_pole() {
- if (!is_setup || !stack) {
- _print_execution_error(true, "Cannot update pole cache: modification is not properly setup!");
- return;
- }
-
- pole_node_cache = ObjectID();
- if (stack->skeleton) {
- if (stack->skeleton->is_inside_tree()) {
- if (stack->skeleton->has_node(pole_node)) {
- Node *node = stack->skeleton->get_node(pole_node);
- ERR_FAIL_COND_MSG(!node || stack->skeleton == node,
- "Cannot update pole cache: Pole node is this modification's skeleton or cannot be found!");
- ERR_FAIL_COND_MSG(!node->is_inside_tree(),
- "Cannot update pole cache: Pole node is not in the scene tree. Cannot execute modification!");
- pole_node_cache = node->get_instance_id();
-
- execution_error_found = false;
- }
- }
- }
-}
-
-void SkeletonModification3DTwoBoneIK::set_target_node(const NodePath &p_target_node) {
- target_node = p_target_node;
- update_cache_target();
-}
-
-NodePath SkeletonModification3DTwoBoneIK::get_target_node() const {
- return target_node;
-}
-
-void SkeletonModification3DTwoBoneIK::set_use_tip_node(const bool p_use_tip_node) {
- use_tip_node = p_use_tip_node;
- notify_property_list_changed();
-}
-
-bool SkeletonModification3DTwoBoneIK::get_use_tip_node() const {
- return use_tip_node;
-}
-
-void SkeletonModification3DTwoBoneIK::set_tip_node(const NodePath &p_tip_node) {
- tip_node = p_tip_node;
- update_cache_tip();
-}
-
-NodePath SkeletonModification3DTwoBoneIK::get_tip_node() const {
- return tip_node;
-}
-
-void SkeletonModification3DTwoBoneIK::set_use_pole_node(const bool p_use_pole_node) {
- use_pole_node = p_use_pole_node;
- notify_property_list_changed();
-}
-
-bool SkeletonModification3DTwoBoneIK::get_use_pole_node() const {
- return use_pole_node;
-}
-
-void SkeletonModification3DTwoBoneIK::set_pole_node(const NodePath &p_pole_node) {
- pole_node = p_pole_node;
- update_cache_pole();
-}
-
-NodePath SkeletonModification3DTwoBoneIK::get_pole_node() const {
- return pole_node;
-}
-
-void SkeletonModification3DTwoBoneIK::set_auto_calculate_joint_length(bool p_calculate) {
- auto_calculate_joint_length = p_calculate;
- if (p_calculate) {
- calculate_joint_lengths();
- }
- notify_property_list_changed();
-}
-
-bool SkeletonModification3DTwoBoneIK::get_auto_calculate_joint_length() const {
- return auto_calculate_joint_length;
-}
-
-void SkeletonModification3DTwoBoneIK::calculate_joint_lengths() {
- if (!is_setup) {
- return; // fail silently, as we likely just loaded the scene.
- }
- ERR_FAIL_COND_MSG(!stack || stack->skeleton == nullptr,
- "Modification is not setup and therefore cannot calculate joint lengths!");
- ERR_FAIL_COND_MSG(joint_one_bone_idx <= -1 || joint_two_bone_idx <= -1,
- "One of the bones in the TwoBoneIK modification are not set! Cannot calculate joint lengths!");
-
- Transform3D bone_one_rest_trans = stack->skeleton->get_bone_global_pose(joint_one_bone_idx);
- Transform3D bone_two_rest_trans = stack->skeleton->get_bone_global_pose(joint_two_bone_idx);
-
- joint_one_length = bone_one_rest_trans.origin.distance_to(bone_two_rest_trans.origin);
-
- if (use_tip_node) {
- if (tip_node_cache.is_null()) {
- update_cache_tip();
- WARN_PRINT("Tip cache is out of date. Updating...");
- }
-
- Node3D *tip = Object::cast_to<Node3D>(ObjectDB::get_instance(tip_node_cache));
- if (tip) {
- Transform3D bone_tip_trans = stack->skeleton->world_transform_to_global_pose(tip->get_global_transform());
- joint_two_length = bone_two_rest_trans.origin.distance_to(bone_tip_trans.origin);
- }
- } else {
- // Attempt to use children bones to get the length
- Vector<int> bone_two_children = stack->skeleton->get_bone_children(joint_two_bone_idx);
- if (bone_two_children.size() > 0) {
- joint_two_length = 0;
- for (int i = 0; i < bone_two_children.size(); i++) {
- joint_two_length += bone_two_rest_trans.origin.distance_to(
- stack->skeleton->get_bone_global_pose(bone_two_children[i]).origin);
- }
- joint_two_length = joint_two_length / bone_two_children.size();
- } else {
- WARN_PRINT("TwoBoneIK modification: Cannot auto calculate length for joint 2! Auto setting the length to 1...");
- joint_two_length = 1.0;
- }
- }
- execution_error_found = false;
-}
-
-void SkeletonModification3DTwoBoneIK::set_joint_one_bone_name(String p_bone_name) {
- joint_one_bone_name = p_bone_name;
- if (stack && stack->skeleton) {
- joint_one_bone_idx = stack->skeleton->find_bone(p_bone_name);
- }
- execution_error_found = false;
- notify_property_list_changed();
-}
-
-String SkeletonModification3DTwoBoneIK::get_joint_one_bone_name() const {
- return joint_one_bone_name;
-}
-
-void SkeletonModification3DTwoBoneIK::set_joint_one_bone_idx(int p_bone_idx) {
- joint_one_bone_idx = p_bone_idx;
- if (stack && stack->skeleton) {
- joint_one_bone_name = stack->skeleton->get_bone_name(p_bone_idx);
- }
- execution_error_found = false;
- notify_property_list_changed();
-}
-
-int SkeletonModification3DTwoBoneIK::get_joint_one_bone_idx() const {
- return joint_one_bone_idx;
-}
-
-void SkeletonModification3DTwoBoneIK::set_joint_one_length(real_t p_length) {
- joint_one_length = p_length;
-}
-
-real_t SkeletonModification3DTwoBoneIK::get_joint_one_length() const {
- return joint_one_length;
-}
-
-void SkeletonModification3DTwoBoneIK::set_joint_two_bone_name(String p_bone_name) {
- joint_two_bone_name = p_bone_name;
- if (stack && stack->skeleton) {
- joint_two_bone_idx = stack->skeleton->find_bone(p_bone_name);
- }
- execution_error_found = false;
- notify_property_list_changed();
-}
-
-String SkeletonModification3DTwoBoneIK::get_joint_two_bone_name() const {
- return joint_two_bone_name;
-}
-
-void SkeletonModification3DTwoBoneIK::set_joint_two_bone_idx(int p_bone_idx) {
- joint_two_bone_idx = p_bone_idx;
- if (stack && stack->skeleton) {
- joint_two_bone_name = stack->skeleton->get_bone_name(p_bone_idx);
- }
- execution_error_found = false;
- notify_property_list_changed();
-}
-
-int SkeletonModification3DTwoBoneIK::get_joint_two_bone_idx() const {
- return joint_two_bone_idx;
-}
-
-void SkeletonModification3DTwoBoneIK::set_joint_two_length(real_t p_length) {
- joint_two_length = p_length;
-}
-
-real_t SkeletonModification3DTwoBoneIK::get_joint_two_length() const {
- return joint_two_length;
-}
-
-void SkeletonModification3DTwoBoneIK::set_joint_one_roll(real_t p_roll) {
- joint_one_roll = p_roll;
-}
-
-real_t SkeletonModification3DTwoBoneIK::get_joint_one_roll() const {
- return joint_one_roll;
-}
-
-void SkeletonModification3DTwoBoneIK::set_joint_two_roll(real_t p_roll) {
- joint_two_roll = p_roll;
-}
-
-real_t SkeletonModification3DTwoBoneIK::get_joint_two_roll() const {
- return joint_two_roll;
-}
-
-void SkeletonModification3DTwoBoneIK::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_target_node", "target_nodepath"), &SkeletonModification3DTwoBoneIK::set_target_node);
- ClassDB::bind_method(D_METHOD("get_target_node"), &SkeletonModification3DTwoBoneIK::get_target_node);
-
- ClassDB::bind_method(D_METHOD("set_use_pole_node", "use_pole_node"), &SkeletonModification3DTwoBoneIK::set_use_pole_node);
- ClassDB::bind_method(D_METHOD("get_use_pole_node"), &SkeletonModification3DTwoBoneIK::get_use_pole_node);
- ClassDB::bind_method(D_METHOD("set_pole_node", "pole_nodepath"), &SkeletonModification3DTwoBoneIK::set_pole_node);
- ClassDB::bind_method(D_METHOD("get_pole_node"), &SkeletonModification3DTwoBoneIK::get_pole_node);
-
- ClassDB::bind_method(D_METHOD("set_use_tip_node", "use_tip_node"), &SkeletonModification3DTwoBoneIK::set_use_tip_node);
- ClassDB::bind_method(D_METHOD("get_use_tip_node"), &SkeletonModification3DTwoBoneIK::get_use_tip_node);
- ClassDB::bind_method(D_METHOD("set_tip_node", "tip_nodepath"), &SkeletonModification3DTwoBoneIK::set_tip_node);
- ClassDB::bind_method(D_METHOD("get_tip_node"), &SkeletonModification3DTwoBoneIK::get_tip_node);
-
- ClassDB::bind_method(D_METHOD("set_auto_calculate_joint_length", "auto_calculate_joint_length"), &SkeletonModification3DTwoBoneIK::set_auto_calculate_joint_length);
- ClassDB::bind_method(D_METHOD("get_auto_calculate_joint_length"), &SkeletonModification3DTwoBoneIK::get_auto_calculate_joint_length);
-
- ClassDB::bind_method(D_METHOD("set_joint_one_bone_name", "bone_name"), &SkeletonModification3DTwoBoneIK::set_joint_one_bone_name);
- ClassDB::bind_method(D_METHOD("get_joint_one_bone_name"), &SkeletonModification3DTwoBoneIK::get_joint_one_bone_name);
- ClassDB::bind_method(D_METHOD("set_joint_one_bone_idx", "bone_idx"), &SkeletonModification3DTwoBoneIK::set_joint_one_bone_idx);
- ClassDB::bind_method(D_METHOD("get_joint_one_bone_idx"), &SkeletonModification3DTwoBoneIK::get_joint_one_bone_idx);
- ClassDB::bind_method(D_METHOD("set_joint_one_length", "bone_length"), &SkeletonModification3DTwoBoneIK::set_joint_one_length);
- ClassDB::bind_method(D_METHOD("get_joint_one_length"), &SkeletonModification3DTwoBoneIK::get_joint_one_length);
-
- ClassDB::bind_method(D_METHOD("set_joint_two_bone_name", "bone_name"), &SkeletonModification3DTwoBoneIK::set_joint_two_bone_name);
- ClassDB::bind_method(D_METHOD("get_joint_two_bone_name"), &SkeletonModification3DTwoBoneIK::get_joint_two_bone_name);
- ClassDB::bind_method(D_METHOD("set_joint_two_bone_idx", "bone_idx"), &SkeletonModification3DTwoBoneIK::set_joint_two_bone_idx);
- ClassDB::bind_method(D_METHOD("get_joint_two_bone_idx"), &SkeletonModification3DTwoBoneIK::get_joint_two_bone_idx);
- ClassDB::bind_method(D_METHOD("set_joint_two_length", "bone_length"), &SkeletonModification3DTwoBoneIK::set_joint_two_length);
- ClassDB::bind_method(D_METHOD("get_joint_two_length"), &SkeletonModification3DTwoBoneIK::get_joint_two_length);
-
- ClassDB::bind_method(D_METHOD("set_joint_one_roll", "roll"), &SkeletonModification3DTwoBoneIK::set_joint_one_roll);
- ClassDB::bind_method(D_METHOD("get_joint_one_roll"), &SkeletonModification3DTwoBoneIK::get_joint_one_roll);
- ClassDB::bind_method(D_METHOD("set_joint_two_roll", "roll"), &SkeletonModification3DTwoBoneIK::set_joint_two_roll);
- ClassDB::bind_method(D_METHOD("get_joint_two_roll"), &SkeletonModification3DTwoBoneIK::get_joint_two_roll);
-
- ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "target_nodepath", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Node3D"), "set_target_node", "get_target_node");
- ADD_GROUP("", "");
-}
-
-SkeletonModification3DTwoBoneIK::SkeletonModification3DTwoBoneIK() {
- stack = nullptr;
- is_setup = false;
-}
-
-SkeletonModification3DTwoBoneIK::~SkeletonModification3DTwoBoneIK() {
-}
diff --git a/scene/resources/skeleton_modification_3d_twoboneik.h b/scene/resources/skeleton_modification_3d_twoboneik.h
deleted file mode 100644
index 57481e0181..0000000000
--- a/scene/resources/skeleton_modification_3d_twoboneik.h
+++ /dev/null
@@ -1,118 +0,0 @@
-/**************************************************************************/
-/* skeleton_modification_3d_twoboneik.h */
-/**************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/**************************************************************************/
-/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
-/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
-/* */
-/* 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 SKELETON_MODIFICATION_3D_TWOBONEIK_H
-#define SKELETON_MODIFICATION_3D_TWOBONEIK_H
-
-#include "scene/3d/skeleton_3d.h"
-#include "scene/resources/skeleton_modification_3d.h"
-
-class SkeletonModification3DTwoBoneIK : public SkeletonModification3D {
- GDCLASS(SkeletonModification3DTwoBoneIK, SkeletonModification3D);
-
-private:
- NodePath target_node;
- ObjectID target_node_cache;
-
- bool use_tip_node = false;
- NodePath tip_node;
- ObjectID tip_node_cache;
-
- bool use_pole_node = false;
- NodePath pole_node;
- ObjectID pole_node_cache;
-
- String joint_one_bone_name = "";
- int joint_one_bone_idx = -1;
- String joint_two_bone_name = "";
- int joint_two_bone_idx = -1;
-
- bool auto_calculate_joint_length = false;
- real_t joint_one_length = -1;
- real_t joint_two_length = -1;
-
- real_t joint_one_roll = 0;
- real_t joint_two_roll = 0;
-
- void update_cache_target();
- void update_cache_tip();
- void update_cache_pole();
-
-protected:
- static void _bind_methods();
- bool _get(const StringName &p_path, Variant &r_ret) const;
- bool _set(const StringName &p_path, const Variant &p_value);
- void _get_property_list(List<PropertyInfo> *p_list) const;
-
-public:
- virtual void _execute(real_t p_delta) override;
- virtual void _setup_modification(SkeletonModificationStack3D *p_stack) override;
-
- void set_target_node(const NodePath &p_target_node);
- NodePath get_target_node() const;
-
- void set_use_tip_node(const bool p_use_tip_node);
- bool get_use_tip_node() const;
- void set_tip_node(const NodePath &p_tip_node);
- NodePath get_tip_node() const;
-
- void set_use_pole_node(const bool p_use_pole_node);
- bool get_use_pole_node() const;
- void set_pole_node(const NodePath &p_pole_node);
- NodePath get_pole_node() const;
-
- void set_auto_calculate_joint_length(bool p_calculate);
- bool get_auto_calculate_joint_length() const;
- void calculate_joint_lengths();
-
- void set_joint_one_bone_name(String p_bone_name);
- String get_joint_one_bone_name() const;
- void set_joint_one_bone_idx(int p_bone_idx);
- int get_joint_one_bone_idx() const;
- void set_joint_one_length(real_t p_length);
- real_t get_joint_one_length() const;
-
- void set_joint_two_bone_name(String p_bone_name);
- String get_joint_two_bone_name() const;
- void set_joint_two_bone_idx(int p_bone_idx);
- int get_joint_two_bone_idx() const;
- void set_joint_two_length(real_t p_length);
- real_t get_joint_two_length() const;
-
- void set_joint_one_roll(real_t p_roll);
- real_t get_joint_one_roll() const;
- void set_joint_two_roll(real_t p_roll);
- real_t get_joint_two_roll() const;
-
- SkeletonModification3DTwoBoneIK();
- ~SkeletonModification3DTwoBoneIK();
-};
-
-#endif // SKELETON_MODIFICATION_3D_TWOBONEIK_H
diff --git a/scene/resources/skeleton_modification_stack_2d.cpp b/scene/resources/skeleton_modification_stack_2d.cpp
index 4fa287e7b6..71ddbc0898 100644
--- a/scene/resources/skeleton_modification_stack_2d.cpp
+++ b/scene/resources/skeleton_modification_stack_2d.cpp
@@ -37,7 +37,7 @@ void SkeletonModificationStack2D::_get_property_list(List<PropertyInfo> *p_list)
PropertyInfo(Variant::OBJECT, "modifications/" + itos(i),
PROPERTY_HINT_RESOURCE_TYPE,
"SkeletonModification2D",
- PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_DEFERRED_SET_RESOURCE | PROPERTY_USAGE_DO_NOT_SHARE_ON_DUPLICATE));
+ PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_DEFERRED_SET_RESOURCE | PROPERTY_USAGE_ALWAYS_DUPLICATE));
}
}
diff --git a/scene/resources/skeleton_modification_stack_3d.cpp b/scene/resources/skeleton_modification_stack_3d.cpp
deleted file mode 100644
index 32708e198a..0000000000
--- a/scene/resources/skeleton_modification_stack_3d.cpp
+++ /dev/null
@@ -1,224 +0,0 @@
-/**************************************************************************/
-/* skeleton_modification_stack_3d.cpp */
-/**************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/**************************************************************************/
-/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
-/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
-/* */
-/* 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 "skeleton_modification_stack_3d.h"
-#include "scene/3d/skeleton_3d.h"
-
-///////////////////////////////////////
-// ModificationStack3D
-///////////////////////////////////////
-
-void SkeletonModificationStack3D::_get_property_list(List<PropertyInfo> *p_list) const {
- for (uint32_t i = 0; i < modifications.size(); i++) {
- p_list->push_back(
- PropertyInfo(Variant::OBJECT, "modifications/" + itos(i),
- PROPERTY_HINT_RESOURCE_TYPE,
- "SkeletonModification3D",
- PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_DEFERRED_SET_RESOURCE | PROPERTY_USAGE_DO_NOT_SHARE_ON_DUPLICATE));
- }
-}
-
-bool SkeletonModificationStack3D::_set(const StringName &p_path, const Variant &p_value) {
- String path = p_path;
-
- if (path.begins_with("modifications/")) {
- int mod_idx = path.get_slicec('/', 1).to_int();
- set_modification(mod_idx, p_value);
- return true;
- }
- return true;
-}
-
-bool SkeletonModificationStack3D::_get(const StringName &p_path, Variant &r_ret) const {
- String path = p_path;
-
- if (path.begins_with("modifications/")) {
- int mod_idx = path.get_slicec('/', 1).to_int();
- r_ret = get_modification(mod_idx);
- return true;
- }
- return true;
-}
-
-void SkeletonModificationStack3D::setup() {
- if (is_setup) {
- return;
- }
-
- if (skeleton != nullptr) {
- is_setup = true;
- for (uint32_t i = 0; i < modifications.size(); i++) {
- if (!modifications[i].is_valid()) {
- continue;
- }
- modifications[i]->_setup_modification(this);
- }
- } else {
- WARN_PRINT("Cannot setup SkeletonModificationStack3D: no skeleton set!");
- }
-}
-
-void SkeletonModificationStack3D::execute(real_t p_delta, int p_execution_mode) {
- ERR_FAIL_COND_MSG(!is_setup || skeleton == nullptr || is_queued_for_deletion(),
- "Modification stack is not properly setup and therefore cannot execute!");
-
- if (!skeleton->is_inside_tree()) {
- ERR_PRINT_ONCE("Skeleton is not inside SceneTree! Cannot execute modification!");
- return;
- }
-
- if (!enabled) {
- return;
- }
-
- for (uint32_t i = 0; i < modifications.size(); i++) {
- if (!modifications[i].is_valid()) {
- continue;
- }
-
- if (modifications[i]->get_execution_mode() == p_execution_mode) {
- modifications[i]->_execute(p_delta);
- }
- }
-}
-
-void SkeletonModificationStack3D::enable_all_modifications(bool p_enabled) {
- for (uint32_t i = 0; i < modifications.size(); i++) {
- if (!modifications[i].is_valid()) {
- continue;
- }
- modifications[i]->set_enabled(p_enabled);
- }
-}
-
-Ref<SkeletonModification3D> SkeletonModificationStack3D::get_modification(int p_mod_idx) const {
- const int modifications_size = modifications.size();
- ERR_FAIL_INDEX_V(p_mod_idx, modifications_size, nullptr);
- return modifications[p_mod_idx];
-}
-
-void SkeletonModificationStack3D::add_modification(Ref<SkeletonModification3D> p_mod) {
- ERR_FAIL_NULL(p_mod);
- p_mod->_setup_modification(this);
- modifications.push_back(p_mod);
-}
-
-void SkeletonModificationStack3D::delete_modification(int p_mod_idx) {
- const int modifications_size = modifications.size();
- ERR_FAIL_INDEX(p_mod_idx, modifications_size);
- modifications.remove_at(p_mod_idx);
-}
-
-void SkeletonModificationStack3D::set_modification(int p_mod_idx, Ref<SkeletonModification3D> p_mod) {
- const int modifications_size = modifications.size();
- ERR_FAIL_INDEX(p_mod_idx, modifications_size);
-
- if (p_mod == nullptr) {
- modifications.remove_at(p_mod_idx);
- } else {
- p_mod->_setup_modification(this);
- modifications[p_mod_idx] = p_mod;
- }
-}
-
-void SkeletonModificationStack3D::set_modification_count(int p_count) {
- ERR_FAIL_COND_MSG(p_count < 0, "Modification count cannot be less than zero.");
- modifications.resize(p_count);
- notify_property_list_changed();
-}
-
-int SkeletonModificationStack3D::get_modification_count() const {
- return modifications.size();
-}
-
-void SkeletonModificationStack3D::set_skeleton(Skeleton3D *p_skeleton) {
- skeleton = p_skeleton;
-}
-
-Skeleton3D *SkeletonModificationStack3D::get_skeleton() const {
- return skeleton;
-}
-
-bool SkeletonModificationStack3D::get_is_setup() const {
- return is_setup;
-}
-
-void SkeletonModificationStack3D::set_enabled(bool p_enabled) {
- enabled = p_enabled;
-
- if (!enabled && is_setup && skeleton != nullptr) {
- skeleton->clear_bones_local_pose_override();
- }
-}
-
-bool SkeletonModificationStack3D::get_enabled() const {
- return enabled;
-}
-
-void SkeletonModificationStack3D::set_strength(real_t p_strength) {
- ERR_FAIL_COND_MSG(p_strength < 0, "Strength cannot be less than zero!");
- ERR_FAIL_COND_MSG(p_strength > 1, "Strength cannot be more than one!");
- strength = p_strength;
-}
-
-real_t SkeletonModificationStack3D::get_strength() const {
- return strength;
-}
-
-void SkeletonModificationStack3D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("setup"), &SkeletonModificationStack3D::setup);
- ClassDB::bind_method(D_METHOD("execute", "delta", "execution_mode"), &SkeletonModificationStack3D::execute);
-
- ClassDB::bind_method(D_METHOD("enable_all_modifications", "enabled"), &SkeletonModificationStack3D::enable_all_modifications);
- ClassDB::bind_method(D_METHOD("get_modification", "mod_idx"), &SkeletonModificationStack3D::get_modification);
- ClassDB::bind_method(D_METHOD("add_modification", "modification"), &SkeletonModificationStack3D::add_modification);
- ClassDB::bind_method(D_METHOD("delete_modification", "mod_idx"), &SkeletonModificationStack3D::delete_modification);
- ClassDB::bind_method(D_METHOD("set_modification", "mod_idx", "modification"), &SkeletonModificationStack3D::set_modification);
-
- ClassDB::bind_method(D_METHOD("set_modification_count", "count"), &SkeletonModificationStack3D::set_modification_count);
- ClassDB::bind_method(D_METHOD("get_modification_count"), &SkeletonModificationStack3D::get_modification_count);
-
- ClassDB::bind_method(D_METHOD("get_is_setup"), &SkeletonModificationStack3D::get_is_setup);
-
- ClassDB::bind_method(D_METHOD("set_enabled", "enabled"), &SkeletonModificationStack3D::set_enabled);
- ClassDB::bind_method(D_METHOD("get_enabled"), &SkeletonModificationStack3D::get_enabled);
-
- ClassDB::bind_method(D_METHOD("set_strength", "strength"), &SkeletonModificationStack3D::set_strength);
- ClassDB::bind_method(D_METHOD("get_strength"), &SkeletonModificationStack3D::get_strength);
-
- ClassDB::bind_method(D_METHOD("get_skeleton"), &SkeletonModificationStack3D::get_skeleton);
-
- ADD_PROPERTY(PropertyInfo(Variant::BOOL, "enabled"), "set_enabled", "get_enabled");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "strength", PROPERTY_HINT_RANGE, "0, 1, 0.001"), "set_strength", "get_strength");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "modification_count", PROPERTY_HINT_RANGE, "0, 100, 1", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_ARRAY, "Modifications,modifications/"), "set_modification_count", "get_modification_count");
-}
-
-SkeletonModificationStack3D::SkeletonModificationStack3D() {
-}
diff --git a/scene/resources/sprite_frames.cpp b/scene/resources/sprite_frames.cpp
index c101974248..818be38681 100644
--- a/scene/resources/sprite_frames.cpp
+++ b/scene/resources/sprite_frames.cpp
@@ -36,7 +36,7 @@ void SpriteFrames::add_frame(const StringName &p_anim, const Ref<Texture2D> &p_t
HashMap<StringName, Anim>::Iterator E = animations.find(p_anim);
ERR_FAIL_COND_MSG(!E, "Animation '" + String(p_anim) + "' doesn't exist.");
- p_duration = MAX(0.0, p_duration);
+ p_duration = MAX(SPRITE_FRAME_MINIMUM_DURATION, p_duration);
Frame frame = { p_texture, p_duration };
@@ -57,7 +57,7 @@ void SpriteFrames::set_frame(const StringName &p_anim, int p_idx, const Ref<Text
return;
}
- p_duration = MAX(0.0, p_duration);
+ p_duration = MAX(SPRITE_FRAME_MINIMUM_DURATION, p_duration);
Frame frame = { p_texture, p_duration };
@@ -214,7 +214,7 @@ void SpriteFrames::_set_animations(const Array &p_animations) {
ERR_CONTINUE(!f.has("texture"));
ERR_CONTINUE(!f.has("duration"));
- Frame frame = { f["texture"], f["duration"] };
+ Frame frame = { f["texture"], MAX(SPRITE_FRAME_MINIMUM_DURATION, (float)f["duration"]) };
anim.frames.push_back(frame);
}
diff --git a/scene/resources/sprite_frames.h b/scene/resources/sprite_frames.h
index 61bead6948..6de2b4a37b 100644
--- a/scene/resources/sprite_frames.h
+++ b/scene/resources/sprite_frames.h
@@ -33,6 +33,8 @@
#include "scene/resources/texture.h"
+static const float SPRITE_FRAME_MINIMUM_DURATION = 0.01;
+
class SpriteFrames : public Resource {
GDCLASS(SpriteFrames, Resource);
@@ -89,10 +91,10 @@ public:
_FORCE_INLINE_ float get_frame_duration(const StringName &p_anim, int p_idx) const {
HashMap<StringName, Anim>::ConstIterator E = animations.find(p_anim);
- ERR_FAIL_COND_V_MSG(!E, 0.0, "Animation '" + String(p_anim) + "' doesn't exist.");
- ERR_FAIL_COND_V(p_idx < 0, 0.0);
+ ERR_FAIL_COND_V_MSG(!E, 1.0, "Animation '" + String(p_anim) + "' doesn't exist.");
+ ERR_FAIL_COND_V(p_idx < 0, 1.0);
if (p_idx >= E->value.frames.size()) {
- return 0.0;
+ return 1.0;
}
return E->value.frames[p_idx].duration;
diff --git a/scene/resources/style_box.cpp b/scene/resources/style_box.cpp
index 6390850b24..9e0b856ecd 100644
--- a/scene/resources/style_box.cpp
+++ b/scene/resources/style_box.cpp
@@ -34,76 +34,65 @@
#include <limits.h>
-float StyleBox::get_style_margin(Side p_side) const {
- float ret = 0;
- GDVIRTUAL_REQUIRED_CALL(_get_style_margin, p_side, ret);
- return ret;
-}
+Size2 StyleBox::get_minimum_size() const {
+ Size2 min_size = Size2(get_margin(SIDE_LEFT) + get_margin(SIDE_RIGHT), get_margin(SIDE_TOP) + get_margin(SIDE_BOTTOM));
+ Size2 custom_size;
+ GDVIRTUAL_CALL(_get_minimum_size, custom_size);
-bool StyleBox::test_mask(const Point2 &p_point, const Rect2 &p_rect) const {
- bool ret = true;
- GDVIRTUAL_CALL(_test_mask, p_point, p_rect, ret);
- return ret;
-}
+ if (min_size.x < custom_size.x) {
+ min_size.x = custom_size.x;
+ }
+ if (min_size.y < custom_size.y) {
+ min_size.y = custom_size.y;
+ }
-void StyleBox::draw(RID p_canvas_item, const Rect2 &p_rect) const {
- GDVIRTUAL_REQUIRED_CALL(_draw, p_canvas_item, p_rect);
+ return min_size;
}
-void StyleBox::set_default_margin(Side p_side, float p_value) {
+void StyleBox::set_content_margin(Side p_side, float p_value) {
ERR_FAIL_INDEX((int)p_side, 4);
- margin[p_side] = p_value;
+ content_margin[p_side] = p_value;
emit_changed();
}
-void StyleBox::set_default_margin_all(float p_value) {
+void StyleBox::set_content_margin_all(float p_value) {
for (int i = 0; i < 4; i++) {
- margin[i] = p_value;
+ content_margin[i] = p_value;
}
emit_changed();
}
-void StyleBox::set_default_margin_individual(float p_left, float p_top, float p_right, float p_bottom) {
- margin[SIDE_LEFT] = p_left;
- margin[SIDE_TOP] = p_top;
- margin[SIDE_RIGHT] = p_right;
- margin[SIDE_BOTTOM] = p_bottom;
+void StyleBox::set_content_margin_individual(float p_left, float p_top, float p_right, float p_bottom) {
+ content_margin[SIDE_LEFT] = p_left;
+ content_margin[SIDE_TOP] = p_top;
+ content_margin[SIDE_RIGHT] = p_right;
+ content_margin[SIDE_BOTTOM] = p_bottom;
emit_changed();
}
-float StyleBox::get_default_margin(Side p_side) const {
+float StyleBox::get_content_margin(Side p_side) const {
ERR_FAIL_INDEX_V((int)p_side, 4, 0.0);
- return margin[p_side];
+ return content_margin[p_side];
}
float StyleBox::get_margin(Side p_side) const {
ERR_FAIL_INDEX_V((int)p_side, 4, 0.0);
- if (margin[p_side] < 0) {
+ if (content_margin[p_side] < 0) {
return get_style_margin(p_side);
} else {
- return margin[p_side];
+ return content_margin[p_side];
}
}
-CanvasItem *StyleBox::get_current_item_drawn() const {
- return CanvasItem::get_current_item_drawn();
-}
-
-Size2 StyleBox::get_minimum_size() const {
- return Size2(get_margin(SIDE_LEFT) + get_margin(SIDE_RIGHT), get_margin(SIDE_TOP) + get_margin(SIDE_BOTTOM));
-}
-
Point2 StyleBox::get_offset() const {
return Point2(get_margin(SIDE_LEFT), get_margin(SIDE_TOP));
}
-Size2 StyleBox::get_center_size() const {
- Size2 ret;
- GDVIRTUAL_CALL(_get_center_size, ret);
- return ret;
+void StyleBox::draw(RID p_canvas_item, const Rect2 &p_rect) const {
+ GDVIRTUAL_REQUIRED_CALL(_draw, p_canvas_item, p_rect);
}
Rect2 StyleBox::get_draw_rect(const Rect2 &p_rect) const {
@@ -114,37 +103,46 @@ Rect2 StyleBox::get_draw_rect(const Rect2 &p_rect) const {
return p_rect;
}
+CanvasItem *StyleBox::get_current_item_drawn() const {
+ return CanvasItem::get_current_item_drawn();
+}
+
+bool StyleBox::test_mask(const Point2 &p_point, const Rect2 &p_rect) const {
+ bool ret = true;
+ GDVIRTUAL_CALL(_test_mask, p_point, p_rect, ret);
+ return ret;
+}
+
void StyleBox::_bind_methods() {
- ClassDB::bind_method(D_METHOD("test_mask", "point", "rect"), &StyleBox::test_mask);
+ ClassDB::bind_method(D_METHOD("get_minimum_size"), &StyleBox::get_minimum_size);
- ClassDB::bind_method(D_METHOD("set_default_margin", "margin", "offset"), &StyleBox::set_default_margin);
- ClassDB::bind_method(D_METHOD("set_default_margin_all", "offset"), &StyleBox::set_default_margin_all);
- ClassDB::bind_method(D_METHOD("get_default_margin", "margin"), &StyleBox::get_default_margin);
+ ClassDB::bind_method(D_METHOD("set_content_margin", "margin", "offset"), &StyleBox::set_content_margin);
+ ClassDB::bind_method(D_METHOD("set_content_margin_all", "offset"), &StyleBox::set_content_margin_all);
+ ClassDB::bind_method(D_METHOD("get_content_margin", "margin"), &StyleBox::get_content_margin);
ClassDB::bind_method(D_METHOD("get_margin", "margin"), &StyleBox::get_margin);
- ClassDB::bind_method(D_METHOD("get_minimum_size"), &StyleBox::get_minimum_size);
- ClassDB::bind_method(D_METHOD("get_center_size"), &StyleBox::get_center_size);
ClassDB::bind_method(D_METHOD("get_offset"), &StyleBox::get_offset);
- ClassDB::bind_method(D_METHOD("get_current_item_drawn"), &StyleBox::get_current_item_drawn);
ClassDB::bind_method(D_METHOD("draw", "canvas_item", "rect"), &StyleBox::draw);
+ ClassDB::bind_method(D_METHOD("get_current_item_drawn"), &StyleBox::get_current_item_drawn);
+
+ ClassDB::bind_method(D_METHOD("test_mask", "point", "rect"), &StyleBox::test_mask);
ADD_GROUP("Content Margins", "content_margin_");
- ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "content_margin_left", PROPERTY_HINT_RANGE, "-1,2048,1,suffix:px"), "set_default_margin", "get_default_margin", SIDE_LEFT);
- ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "content_margin_top", PROPERTY_HINT_RANGE, "-1,2048,1,suffix:px"), "set_default_margin", "get_default_margin", SIDE_TOP);
- ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "content_margin_right", PROPERTY_HINT_RANGE, "-1,2048,1,suffix:px"), "set_default_margin", "get_default_margin", SIDE_RIGHT);
- ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "content_margin_bottom", PROPERTY_HINT_RANGE, "-1,2048,1,suffix:px"), "set_default_margin", "get_default_margin", SIDE_BOTTOM);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "content_margin_left", PROPERTY_HINT_RANGE, "-1,2048,1,suffix:px"), "set_content_margin", "get_content_margin", SIDE_LEFT);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "content_margin_top", PROPERTY_HINT_RANGE, "-1,2048,1,suffix:px"), "set_content_margin", "get_content_margin", SIDE_TOP);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "content_margin_right", PROPERTY_HINT_RANGE, "-1,2048,1,suffix:px"), "set_content_margin", "get_content_margin", SIDE_RIGHT);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "content_margin_bottom", PROPERTY_HINT_RANGE, "-1,2048,1,suffix:px"), "set_content_margin", "get_content_margin", SIDE_BOTTOM);
- GDVIRTUAL_BIND(_get_style_margin, "side")
- GDVIRTUAL_BIND(_test_mask, "point", "rect")
- GDVIRTUAL_BIND(_get_center_size)
- GDVIRTUAL_BIND(_get_draw_rect, "rect")
GDVIRTUAL_BIND(_draw, "to_canvas_item", "rect")
+ GDVIRTUAL_BIND(_get_draw_rect, "rect")
+ GDVIRTUAL_BIND(_get_minimum_size)
+ GDVIRTUAL_BIND(_test_mask, "point", "rect")
}
StyleBox::StyleBox() {
for (int i = 0; i < 4; i++) {
- margin[i] = -1;
+ content_margin[i] = -1;
}
}
@@ -153,11 +151,6 @@ void StyleBoxTexture::set_texture(Ref<Texture2D> p_texture) {
return;
}
texture = p_texture;
- if (p_texture.is_null()) {
- region_rect = Rect2(0, 0, 0, 0);
- } else {
- region_rect = Rect2(Point2(), texture->get_size());
- }
emit_changed();
}
@@ -165,38 +158,38 @@ Ref<Texture2D> StyleBoxTexture::get_texture() const {
return texture;
}
-void StyleBoxTexture::set_margin_size(Side p_side, float p_size) {
+void StyleBoxTexture::set_texture_margin(Side p_side, float p_size) {
ERR_FAIL_INDEX((int)p_side, 4);
- margin[p_side] = p_size;
+ texture_margin[p_side] = p_size;
emit_changed();
}
-void StyleBoxTexture::set_margin_size_all(float p_size) {
+void StyleBoxTexture::set_texture_margin_all(float p_size) {
for (int i = 0; i < 4; i++) {
- margin[i] = p_size;
+ texture_margin[i] = p_size;
}
emit_changed();
}
-void StyleBoxTexture::set_margin_size_individual(float p_left, float p_top, float p_right, float p_bottom) {
- margin[SIDE_LEFT] = p_left;
- margin[SIDE_TOP] = p_top;
- margin[SIDE_RIGHT] = p_right;
- margin[SIDE_BOTTOM] = p_bottom;
+void StyleBoxTexture::set_texture_margin_individual(float p_left, float p_top, float p_right, float p_bottom) {
+ texture_margin[SIDE_LEFT] = p_left;
+ texture_margin[SIDE_TOP] = p_top;
+ texture_margin[SIDE_RIGHT] = p_right;
+ texture_margin[SIDE_BOTTOM] = p_bottom;
emit_changed();
}
-float StyleBoxTexture::get_margin_size(Side p_side) const {
+float StyleBoxTexture::get_texture_margin(Side p_side) const {
ERR_FAIL_INDEX_V((int)p_side, 4, 0.0);
- return margin[p_side];
+ return texture_margin[p_side];
}
float StyleBoxTexture::get_style_margin(Side p_side) const {
ERR_FAIL_INDEX_V((int)p_side, 4, 0.0);
- return margin[p_side];
+ return texture_margin[p_side];
}
Rect2 StyleBoxTexture::get_draw_rect(const Rect2 &p_rect) const {
@@ -218,7 +211,10 @@ void StyleBoxTexture::draw(RID p_canvas_item, const Rect2 &p_rect) const {
rect.size.x += expand_margin[SIDE_LEFT] + expand_margin[SIDE_RIGHT];
rect.size.y += expand_margin[SIDE_TOP] + expand_margin[SIDE_BOTTOM];
- RenderingServer::get_singleton()->canvas_item_add_nine_patch(p_canvas_item, rect, src_rect, texture->get_rid(), Vector2(margin[SIDE_LEFT], margin[SIDE_TOP]), Vector2(margin[SIDE_RIGHT], margin[SIDE_BOTTOM]), RS::NinePatchAxisMode(axis_h), RS::NinePatchAxisMode(axis_v), draw_center, modulate);
+ Vector2 start_offset = Vector2(texture_margin[SIDE_LEFT], texture_margin[SIDE_TOP]);
+ Vector2 end_offset = Vector2(texture_margin[SIDE_RIGHT], texture_margin[SIDE_BOTTOM]);
+
+ RenderingServer::get_singleton()->canvas_item_add_nine_patch(p_canvas_item, rect, src_rect, texture->get_rid(), start_offset, end_offset, RS::NinePatchAxisMode(axis_h), RS::NinePatchAxisMode(axis_v), draw_center, modulate);
}
void StyleBoxTexture::set_draw_center(bool p_enabled) {
@@ -230,21 +226,13 @@ bool StyleBoxTexture::is_draw_center_enabled() const {
return draw_center;
}
-Size2 StyleBoxTexture::get_center_size() const {
- if (texture.is_null()) {
- return Size2();
- }
-
- return region_rect.size - get_minimum_size();
-}
-
-void StyleBoxTexture::set_expand_margin_size(Side p_side, float p_size) {
+void StyleBoxTexture::set_expand_margin(Side p_side, float p_size) {
ERR_FAIL_INDEX((int)p_side, 4);
expand_margin[p_side] = p_size;
emit_changed();
}
-void StyleBoxTexture::set_expand_margin_size_individual(float p_left, float p_top, float p_right, float p_bottom) {
+void StyleBoxTexture::set_expand_margin_individual(float p_left, float p_top, float p_right, float p_bottom) {
expand_margin[SIDE_LEFT] = p_left;
expand_margin[SIDE_TOP] = p_top;
expand_margin[SIDE_RIGHT] = p_right;
@@ -252,14 +240,14 @@ void StyleBoxTexture::set_expand_margin_size_individual(float p_left, float p_to
emit_changed();
}
-void StyleBoxTexture::set_expand_margin_size_all(float p_expand_margin_size) {
+void StyleBoxTexture::set_expand_margin_all(float p_expand_margin_size) {
for (int i = 0; i < 4; i++) {
expand_margin[i] = p_expand_margin_size;
}
emit_changed();
}
-float StyleBoxTexture::get_expand_margin_size(Side p_side) const {
+float StyleBoxTexture::get_expand_margin(Side p_side) const {
ERR_FAIL_INDEX_V((int)p_side, 4, 0);
return expand_margin[p_side];
}
@@ -313,13 +301,13 @@ void StyleBoxTexture::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_texture", "texture"), &StyleBoxTexture::set_texture);
ClassDB::bind_method(D_METHOD("get_texture"), &StyleBoxTexture::get_texture);
- ClassDB::bind_method(D_METHOD("set_margin_size", "margin", "size"), &StyleBoxTexture::set_margin_size);
- ClassDB::bind_method(D_METHOD("set_margin_size_all", "size"), &StyleBoxTexture::set_margin_size_all);
- ClassDB::bind_method(D_METHOD("get_margin_size", "margin"), &StyleBoxTexture::get_margin_size);
+ ClassDB::bind_method(D_METHOD("set_texture_margin", "margin", "size"), &StyleBoxTexture::set_texture_margin);
+ ClassDB::bind_method(D_METHOD("set_texture_margin_all", "size"), &StyleBoxTexture::set_texture_margin_all);
+ ClassDB::bind_method(D_METHOD("get_texture_margin", "margin"), &StyleBoxTexture::get_texture_margin);
- ClassDB::bind_method(D_METHOD("set_expand_margin_size", "margin", "size"), &StyleBoxTexture::set_expand_margin_size);
- ClassDB::bind_method(D_METHOD("set_expand_margin_all", "size"), &StyleBoxTexture::set_expand_margin_size_all);
- ClassDB::bind_method(D_METHOD("get_expand_margin_size", "margin"), &StyleBoxTexture::get_expand_margin_size);
+ ClassDB::bind_method(D_METHOD("set_expand_margin", "margin", "size"), &StyleBoxTexture::set_expand_margin);
+ ClassDB::bind_method(D_METHOD("set_expand_margin_all", "size"), &StyleBoxTexture::set_expand_margin_all);
+ ClassDB::bind_method(D_METHOD("get_expand_margin", "margin"), &StyleBoxTexture::get_expand_margin);
ClassDB::bind_method(D_METHOD("set_region_rect", "region"), &StyleBoxTexture::set_region_rect);
ClassDB::bind_method(D_METHOD("get_region_rect"), &StyleBoxTexture::get_region_rect);
@@ -338,17 +326,17 @@ void StyleBoxTexture::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture2D"), "set_texture", "get_texture");
- ADD_GROUP("Margins", "margin_");
- ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "margin_left", PROPERTY_HINT_RANGE, "0,2048,1,suffix:px"), "set_margin_size", "get_margin_size", SIDE_LEFT);
- ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "margin_top", PROPERTY_HINT_RANGE, "0,2048,1,suffix:px"), "set_margin_size", "get_margin_size", SIDE_TOP);
- ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "margin_right", PROPERTY_HINT_RANGE, "0,2048,1,suffix:px"), "set_margin_size", "get_margin_size", SIDE_RIGHT);
- ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "margin_bottom", PROPERTY_HINT_RANGE, "0,2048,1,suffix:px"), "set_margin_size", "get_margin_size", SIDE_BOTTOM);
+ ADD_GROUP("Texture Margins", "texture_margin_");
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "texture_margin_left", PROPERTY_HINT_RANGE, "0,2048,1,suffix:px"), "set_texture_margin", "get_texture_margin", SIDE_LEFT);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "texture_margin_top", PROPERTY_HINT_RANGE, "0,2048,1,suffix:px"), "set_texture_margin", "get_texture_margin", SIDE_TOP);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "texture_margin_right", PROPERTY_HINT_RANGE, "0,2048,1,suffix:px"), "set_texture_margin", "get_texture_margin", SIDE_RIGHT);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "texture_margin_bottom", PROPERTY_HINT_RANGE, "0,2048,1,suffix:px"), "set_texture_margin", "get_texture_margin", SIDE_BOTTOM);
ADD_GROUP("Expand Margins", "expand_margin_");
- ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "expand_margin_left", PROPERTY_HINT_RANGE, "0,2048,1,suffix:px"), "set_expand_margin_size", "get_expand_margin_size", SIDE_LEFT);
- ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "expand_margin_top", PROPERTY_HINT_RANGE, "0,2048,1,suffix:px"), "set_expand_margin_size", "get_expand_margin_size", SIDE_TOP);
- ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "expand_margin_right", PROPERTY_HINT_RANGE, "0,2048,1,suffix:px"), "set_expand_margin_size", "get_expand_margin_size", SIDE_RIGHT);
- ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "expand_margin_bottom", PROPERTY_HINT_RANGE, "0,2048,1,suffix:px"), "set_expand_margin_size", "get_expand_margin_size", SIDE_BOTTOM);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "expand_margin_left", PROPERTY_HINT_RANGE, "0,2048,1,suffix:px"), "set_expand_margin", "get_expand_margin", SIDE_LEFT);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "expand_margin_top", PROPERTY_HINT_RANGE, "0,2048,1,suffix:px"), "set_expand_margin", "get_expand_margin", SIDE_TOP);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "expand_margin_right", PROPERTY_HINT_RANGE, "0,2048,1,suffix:px"), "set_expand_margin", "get_expand_margin", SIDE_RIGHT);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "expand_margin_bottom", PROPERTY_HINT_RANGE, "0,2048,1,suffix:px"), "set_expand_margin", "get_expand_margin", SIDE_BOTTOM);
ADD_GROUP("Axis Stretch", "axis_stretch_");
ADD_PROPERTY(PropertyInfo(Variant::INT, "axis_stretch_horizontal", PROPERTY_HINT_ENUM, "Stretch,Tile,Tile Fit"), "set_h_axis_stretch_mode", "get_h_axis_stretch_mode");
@@ -450,13 +438,13 @@ int StyleBoxFlat::get_corner_radius(const Corner p_corner) const {
return corner_radius[p_corner];
}
-void StyleBoxFlat::set_expand_margin_size(Side p_side, float p_size) {
+void StyleBoxFlat::set_expand_margin(Side p_side, float p_size) {
ERR_FAIL_INDEX((int)p_side, 4);
expand_margin[p_side] = p_size;
emit_changed();
}
-void StyleBoxFlat::set_expand_margin_size_individual(float p_left, float p_top, float p_right, float p_bottom) {
+void StyleBoxFlat::set_expand_margin_individual(float p_left, float p_top, float p_right, float p_bottom) {
expand_margin[SIDE_LEFT] = p_left;
expand_margin[SIDE_TOP] = p_top;
expand_margin[SIDE_RIGHT] = p_right;
@@ -464,14 +452,14 @@ void StyleBoxFlat::set_expand_margin_size_individual(float p_left, float p_top,
emit_changed();
}
-void StyleBoxFlat::set_expand_margin_size_all(float p_expand_margin_size) {
+void StyleBoxFlat::set_expand_margin_all(float p_expand_margin_size) {
for (int i = 0; i < 4; i++) {
expand_margin[i] = p_expand_margin_size;
}
emit_changed();
}
-float StyleBoxFlat::get_expand_margin_size(Side p_side) const {
+float StyleBoxFlat::get_expand_margin(Side p_side) const {
ERR_FAIL_INDEX_V((int)p_side, 4, 0.0);
return expand_margin[p_side];
}
@@ -549,10 +537,6 @@ int StyleBoxFlat::get_corner_detail() const {
return corner_detail;
}
-Size2 StyleBoxFlat::get_center_size() const {
- return Size2();
-}
-
inline void set_inner_corner_radius(const Rect2 style_rect, const Rect2 inner_rect, const real_t corner_radius[4], real_t *inner_corner_radius) {
real_t border_left = inner_rect.position.x - style_rect.position.x;
real_t border_top = inner_rect.position.y - style_rect.position.y;
@@ -891,9 +875,9 @@ void StyleBoxFlat::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_corner_radius", "corner", "radius"), &StyleBoxFlat::set_corner_radius);
ClassDB::bind_method(D_METHOD("get_corner_radius", "corner"), &StyleBoxFlat::get_corner_radius);
- ClassDB::bind_method(D_METHOD("set_expand_margin", "margin", "size"), &StyleBoxFlat::set_expand_margin_size);
- ClassDB::bind_method(D_METHOD("set_expand_margin_all", "size"), &StyleBoxFlat::set_expand_margin_size_all);
- ClassDB::bind_method(D_METHOD("get_expand_margin", "margin"), &StyleBoxFlat::get_expand_margin_size);
+ ClassDB::bind_method(D_METHOD("set_expand_margin", "margin", "size"), &StyleBoxFlat::set_expand_margin);
+ ClassDB::bind_method(D_METHOD("set_expand_margin_all", "size"), &StyleBoxFlat::set_expand_margin_all);
+ ClassDB::bind_method(D_METHOD("get_expand_margin", "margin"), &StyleBoxFlat::get_expand_margin);
ClassDB::bind_method(D_METHOD("set_draw_center", "draw_center"), &StyleBoxFlat::set_draw_center);
ClassDB::bind_method(D_METHOD("is_draw_center_enabled"), &StyleBoxFlat::is_draw_center_enabled);
@@ -1023,7 +1007,7 @@ void StyleBoxLine::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::COLOR, "color"), "set_color", "get_color");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "grow_begin", PROPERTY_HINT_RANGE, "-300,300,1,suffix:px"), "set_grow_begin", "get_grow_begin");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "grow_end", PROPERTY_HINT_RANGE, "-300,300,1,suffix:px"), "set_grow_end", "get_grow_end");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "thickness", PROPERTY_HINT_RANGE, "0,10,suffix:px"), "set_thickness", "get_thickness");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "thickness", PROPERTY_HINT_RANGE, "0,100,suffix:px"), "set_thickness", "get_thickness");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "vertical"), "set_vertical", "is_vertical");
}
@@ -1041,10 +1025,6 @@ float StyleBoxLine::get_style_margin(Side p_side) const {
return 0;
}
-Size2 StyleBoxLine::get_center_size() const {
- return Size2();
-}
-
void StyleBoxLine::draw(RID p_canvas_item, const Rect2 &p_rect) const {
RenderingServer *vs = RenderingServer::get_singleton();
Rect2i r = p_rect;
diff --git a/scene/resources/style_box.h b/scene/resources/style_box.h
index 5a80b4d4e2..17acfd773e 100644
--- a/scene/resources/style_box.h
+++ b/scene/resources/style_box.h
@@ -41,36 +41,34 @@ class StyleBox : public Resource {
GDCLASS(StyleBox, Resource);
RES_BASE_EXTENSION("stylebox");
OBJ_SAVE_TYPE(StyleBox);
- float margin[4];
+ float content_margin[4];
protected:
- virtual float get_style_margin(Side p_side) const;
+ virtual float get_style_margin(Side p_side) const { return 0; }
static void _bind_methods();
- GDVIRTUAL1RC(float, _get_style_margin, Side)
- GDVIRTUAL2RC(bool, _test_mask, Point2, Rect2)
- GDVIRTUAL0RC(Size2, _get_center_size)
- GDVIRTUAL1RC(Rect2, _get_draw_rect, Rect2)
GDVIRTUAL2C(_draw, RID, Rect2)
+ GDVIRTUAL1RC(Rect2, _get_draw_rect, Rect2)
+ GDVIRTUAL0RC(Size2, _get_minimum_size)
+ GDVIRTUAL2RC(bool, _test_mask, Point2, Rect2)
public:
- virtual bool test_mask(const Point2 &p_point, const Rect2 &p_rect) const;
+ virtual Size2 get_minimum_size() const;
- void set_default_margin(Side p_side, float p_value);
- void set_default_margin_all(float p_value);
- void set_default_margin_individual(float p_left, float p_top, float p_right, float p_bottom);
- float get_default_margin(Side p_side) const;
+ void set_content_margin(Side p_side, float p_value);
+ void set_content_margin_all(float p_value);
+ void set_content_margin_individual(float p_left, float p_top, float p_right, float p_bottom);
+ float get_content_margin(Side p_side) const;
float get_margin(Side p_side) const;
- virtual Size2 get_center_size() const;
+ Point2 get_offset() const;
- virtual Rect2 get_draw_rect(const Rect2 &p_rect) const;
virtual void draw(RID p_canvas_item, const Rect2 &p_rect) const;
+ virtual Rect2 get_draw_rect(const Rect2 &p_rect) const;
CanvasItem *get_current_item_drawn() const;
- Size2 get_minimum_size() const;
- Point2 get_offset() const;
+ virtual bool test_mask(const Point2 &p_point, const Rect2 &p_rect) const;
StyleBox();
};
@@ -96,7 +94,7 @@ public:
private:
float expand_margin[4] = {};
- float margin[4] = {};
+ float texture_margin[4] = {};
Rect2 region_rect;
Ref<Texture2D> texture;
bool draw_center = true;
@@ -109,15 +107,15 @@ protected:
static void _bind_methods();
public:
- void set_expand_margin_size(Side p_expand_side, float p_size);
- void set_expand_margin_size_all(float p_expand_margin_size);
- void set_expand_margin_size_individual(float p_left, float p_top, float p_right, float p_bottom);
- float get_expand_margin_size(Side p_expand_side) const;
+ void set_expand_margin(Side p_expand_side, float p_size);
+ void set_expand_margin_all(float p_expand_margin_size);
+ void set_expand_margin_individual(float p_left, float p_top, float p_right, float p_bottom);
+ float get_expand_margin(Side p_expand_side) const;
- void set_margin_size(Side p_side, float p_size);
- void set_margin_size_all(float p_size);
- void set_margin_size_individual(float p_left, float p_top, float p_right, float p_bottom);
- float get_margin_size(Side p_side) const;
+ void set_texture_margin(Side p_side, float p_size);
+ void set_texture_margin_all(float p_size);
+ void set_texture_margin_individual(float p_left, float p_top, float p_right, float p_bottom);
+ float get_texture_margin(Side p_side) const;
void set_region_rect(const Rect2 &p_region_rect);
Rect2 get_region_rect() const;
@@ -127,7 +125,6 @@ public:
void set_draw_center(bool p_enabled);
bool is_draw_center_enabled() const;
- virtual Size2 get_center_size() const override;
void set_h_axis_stretch_mode(AxisStretchMode p_mode);
AxisStretchMode get_h_axis_stretch_mode() const;
@@ -198,10 +195,10 @@ public:
void set_corner_detail(const int &p_corner_detail);
int get_corner_detail() const;
- void set_expand_margin_size(Side p_expand_side, float p_size);
- void set_expand_margin_size_all(float p_expand_margin_size);
- void set_expand_margin_size_individual(float p_left, float p_top, float p_right, float p_bottom);
- float get_expand_margin_size(Side p_expand_side) const;
+ void set_expand_margin(Side p_expand_side, float p_size);
+ void set_expand_margin_all(float p_expand_margin_size);
+ void set_expand_margin_individual(float p_left, float p_top, float p_right, float p_bottom);
+ float get_expand_margin(Side p_expand_side) const;
void set_draw_center(bool p_enabled);
bool is_draw_center_enabled() const;
@@ -223,8 +220,6 @@ public:
void set_aa_size(const real_t p_aa_size);
real_t get_aa_size() const;
- virtual Size2 get_center_size() const override;
-
virtual Rect2 get_draw_rect(const Rect2 &p_rect) const override;
virtual void draw(RID p_canvas_item, const Rect2 &p_rect) const override;
@@ -261,8 +256,6 @@ public:
void set_grow_end(float p_grow);
float get_grow_end() const;
- virtual Size2 get_center_size() const override;
-
virtual void draw(RID p_canvas_item, const Rect2 &p_rect) const override;
StyleBoxLine();
diff --git a/scene/resources/surface_tool.cpp b/scene/resources/surface_tool.cpp
index e802e1c2d9..16cc1c3370 100644
--- a/scene/resources/surface_tool.cpp
+++ b/scene/resources/surface_tool.cpp
@@ -146,6 +146,25 @@ uint32_t SurfaceTool::VertexHasher::hash(const Vertex &p_vtx) {
return h;
}
+bool SurfaceTool::SmoothGroupVertex::operator==(const SmoothGroupVertex &p_vertex) const {
+ if (vertex != p_vertex.vertex) {
+ return false;
+ }
+
+ if (smooth_group != p_vertex.smooth_group) {
+ return false;
+ }
+
+ return true;
+}
+
+uint32_t SurfaceTool::SmoothGroupVertexHasher::hash(const SmoothGroupVertex &p_vtx) {
+ uint32_t h = hash_djb2_buffer((const uint8_t *)&p_vtx.vertex, sizeof(real_t) * 3);
+ h = hash_murmur3_one_32(p_vtx.smooth_group, h);
+ h = hash_fmix32(h);
+ return h;
+}
+
uint32_t SurfaceTool::TriangleHasher::hash(const int *p_triangle) {
int t0 = p_triangle[0];
int t1 = p_triangle[1];
@@ -732,13 +751,13 @@ void SurfaceTool::index() {
LocalVector<Vertex> old_vertex_array = vertex_array;
vertex_array.clear();
- for (uint32_t i = 0; i < old_vertex_array.size(); i++) {
- int *idxptr = indices.getptr(old_vertex_array[i]);
+ for (const Vertex &vertex : old_vertex_array) {
+ int *idxptr = indices.getptr(vertex);
int idx;
if (!idxptr) {
idx = indices.size();
- vertex_array.push_back(old_vertex_array[i]);
- indices[old_vertex_array[i]] = idx;
+ vertex_array.push_back(vertex);
+ indices[vertex] = idx;
} else {
idx = *idxptr;
}
@@ -756,9 +775,8 @@ void SurfaceTool::deindex() {
LocalVector<Vertex> old_vertex_array = vertex_array;
vertex_array.clear();
- for (uint32_t i = 0; i < index_array.size(); i++) {
- uint32_t index = index_array[i];
- ERR_FAIL_COND(index >= old_vertex_array.size());
+ for (const int &index : index_array) {
+ ERR_FAIL_COND(uint32_t(index) >= old_vertex_array.size());
vertex_array.push_back(old_vertex_array[index]);
}
format &= ~Mesh::ARRAY_FORMAT_INDEX;
@@ -1000,8 +1018,7 @@ void SurfaceTool::append_from(const Ref<Mesh> &p_existing, int p_surface, const
}
int vfrom = vertex_array.size();
- for (uint32_t vi = 0; vi < nvertices.size(); vi++) {
- Vertex v = nvertices[vi];
+ for (Vertex &v : nvertices) {
v.vertex = p_xform.xform(v.vertex);
if (nformat & RS::ARRAY_FORMAT_NORMAL) {
v.normal = p_xform.basis.xform(v.normal);
@@ -1014,8 +1031,8 @@ void SurfaceTool::append_from(const Ref<Mesh> &p_existing, int p_surface, const
vertex_array.push_back(v);
}
- for (uint32_t i = 0; i < nindices.size(); i++) {
- int dst_index = nindices[i] + vfrom;
+ for (const int &index : nindices) {
+ int dst_index = index + vfrom;
index_array.push_back(dst_index);
}
if (index_array.size() % 3) {
@@ -1132,9 +1149,9 @@ void SurfaceTool::generate_tangents() {
TangentGenerationContextUserData triangle_data;
triangle_data.vertices = &vertex_array;
- for (uint32_t i = 0; i < vertex_array.size(); i++) {
- vertex_array[i].binormal = Vector3();
- vertex_array[i].tangent = Vector3();
+ for (Vertex &vertex : vertex_array) {
+ vertex.binormal = Vector3();
+ vertex.tangent = Vector3();
}
triangle_data.indices = &index_array;
msc.m_pUserData = &triangle_data;
@@ -1154,7 +1171,7 @@ void SurfaceTool::generate_normals(bool p_flip) {
ERR_FAIL_COND((vertex_array.size() % 3) != 0);
- HashMap<Vertex, Vector3, VertexHasher> vertex_hash;
+ HashMap<SmoothGroupVertex, Vector3, SmoothGroupVertexHasher> smooth_hash;
for (uint32_t vi = 0; vi < vertex_array.size(); vi += 3) {
Vertex *v = &vertex_array[vi];
@@ -1167,21 +1184,28 @@ void SurfaceTool::generate_normals(bool p_flip) {
}
for (int i = 0; i < 3; i++) {
- Vector3 *lv = vertex_hash.getptr(v[i]);
- if (!lv) {
- vertex_hash.insert(v[i], normal);
+ // Add face normal to smooth vertex influence if vertex is member of a smoothing group
+ if (v[i].smooth_group != UINT32_MAX) {
+ Vector3 *lv = smooth_hash.getptr(v[i]);
+ if (!lv) {
+ smooth_hash.insert(v[i], normal);
+ } else {
+ (*lv) += normal;
+ }
} else {
- (*lv) += normal;
+ v[i].normal = normal;
}
}
}
- for (uint32_t vi = 0; vi < vertex_array.size(); vi++) {
- Vector3 *lv = vertex_hash.getptr(vertex_array[vi]);
- if (!lv) {
- vertex_array[vi].normal = Vector3();
- } else {
- vertex_array[vi].normal = lv->normalized();
+ for (Vertex &vertex : vertex_array) {
+ if (vertex.smooth_group != UINT32_MAX) {
+ Vector3 *lv = smooth_hash.getptr(vertex);
+ if (!lv) {
+ vertex.normal = Vector3();
+ } else {
+ vertex.normal = lv->normalized();
+ }
}
}
@@ -1283,7 +1307,8 @@ Vector<int> SurfaceTool::generate_lod(float p_threshold, int p_target_index_coun
}
float error;
- uint32_t index_count = simplify_func((unsigned int *)lod.ptrw(), (unsigned int *)index_array.ptr(), index_array.size(), vertices.ptr(), vertex_array.size(), sizeof(float) * 3, p_target_index_count, p_threshold, &error);
+ const int simplify_options = SIMPLIFY_LOCK_BORDER;
+ uint32_t index_count = simplify_func((unsigned int *)lod.ptrw(), (unsigned int *)index_array.ptr(), index_array.size(), vertices.ptr(), vertex_array.size(), sizeof(float) * 3, p_target_index_count, p_threshold, simplify_options, &error);
ERR_FAIL_COND_V(index_count == 0, lod);
lod.resize(index_count);
diff --git a/scene/resources/surface_tool.h b/scene/resources/surface_tool.h
index 25e078d2ff..77318bb061 100644
--- a/scene/resources/surface_tool.h
+++ b/scene/resources/surface_tool.h
@@ -74,11 +74,16 @@ public:
SKIN_8_WEIGHTS
};
+ enum {
+ /* Do not move vertices that are located on the topological border (vertices on triangle edges that don't have a paired triangle). Useful for simplifying portions of the larger mesh. */
+ SIMPLIFY_LOCK_BORDER = 1 << 0, // From meshopt_SimplifyLockBorder
+ };
+
typedef void (*OptimizeVertexCacheFunc)(unsigned int *destination, const unsigned int *indices, size_t index_count, size_t vertex_count);
static OptimizeVertexCacheFunc optimize_vertex_cache_func;
- typedef size_t (*SimplifyFunc)(unsigned int *destination, const unsigned int *indices, size_t index_count, const float *vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t target_index_count, float target_error, float *r_error);
+ typedef size_t (*SimplifyFunc)(unsigned int *destination, const unsigned int *indices, size_t index_count, const float *vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t target_index_count, float target_error, unsigned int options, float *r_error);
static SimplifyFunc simplify_func;
- typedef size_t (*SimplifyWithAttribFunc)(unsigned int *destination, const unsigned int *indices, size_t index_count, const float *vertex_data, size_t vertex_count, size_t vertex_stride, size_t target_index_count, float target_error, float *result_error, const float *attributes, const float *attribute_weights, size_t attribute_count);
+ typedef size_t (*SimplifyWithAttribFunc)(unsigned int *destination, const unsigned int *indices, size_t index_count, const float *vertex_data, size_t vertex_count, size_t vertex_stride, size_t target_index_count, float target_error, unsigned int options, float *result_error, const float *attributes, const float *attribute_weights, size_t attribute_count);
static SimplifyWithAttribFunc simplify_with_attrib_func;
typedef float (*SimplifyScaleFunc)(const float *vertex_positions, size_t vertex_count, size_t vertex_positions_stride);
static SimplifyScaleFunc simplify_scale_func;
@@ -97,6 +102,21 @@ private:
static _FORCE_INLINE_ uint32_t hash(const Vertex &p_vtx);
};
+ struct SmoothGroupVertex {
+ Vector3 vertex;
+ uint32_t smooth_group = 0;
+ bool operator==(const SmoothGroupVertex &p_vertex) const;
+
+ SmoothGroupVertex(const Vertex &p_vertex) {
+ vertex = p_vertex.vertex;
+ smooth_group = p_vertex.smooth_group;
+ };
+ };
+
+ struct SmoothGroupVertexHasher {
+ static _FORCE_INLINE_ uint32_t hash(const SmoothGroupVertex &p_vtx);
+ };
+
struct TriangleHasher {
static _FORCE_INLINE_ uint32_t hash(const int *p_triangle);
static _FORCE_INLINE_ bool compare(const int *p_lhs, const int *p_rhs);
diff --git a/scene/resources/text_file.cpp b/scene/resources/text_file.cpp
index 9b61a95edb..77ff0f55b1 100644
--- a/scene/resources/text_file.cpp
+++ b/scene/resources/text_file.cpp
@@ -67,5 +67,10 @@ Error TextFile::load_text(const String &p_path) {
ERR_FAIL_COND_V_MSG(s.parse_utf8((const char *)w) != OK, ERR_INVALID_DATA, "Script '" + p_path + "' contains invalid unicode (UTF-8), so it was not loaded. Please ensure that scripts are saved in valid UTF-8 unicode.");
text = s;
path = p_path;
+#ifdef TOOLS_ENABLED
+ if (ResourceLoader::get_timestamp_on_load()) {
+ set_last_modified_time(FileAccess::get_modified_time(path));
+ }
+#endif // TOOLS_ENABLED
return OK;
}
diff --git a/scene/resources/text_paragraph.cpp b/scene/resources/text_paragraph.cpp
index 6d66c48b78..dfafc7d2bc 100644
--- a/scene/resources/text_paragraph.cpp
+++ b/scene/resources/text_paragraph.cpp
@@ -135,8 +135,8 @@ void TextParagraph::_bind_methods() {
void TextParagraph::_shape_lines() {
if (lines_dirty) {
- for (int i = 0; i < (int)lines_rid.size(); i++) {
- TS->free_rid(lines_rid[i]);
+ for (const RID &line_rid : lines_rid) {
+ TS->free_rid(line_rid);
}
lines_rid.clear();
@@ -234,14 +234,14 @@ void TextParagraph::_shape_lines() {
} else {
// Autowrap disabled.
- for (int i = 0; i < (int)lines_rid.size(); i++) {
+ for (const RID &line_rid : lines_rid) {
if (alignment == HORIZONTAL_ALIGNMENT_FILL) {
- TS->shaped_text_fit_to_width(lines_rid[i], width, jst_flags);
+ TS->shaped_text_fit_to_width(line_rid, width, jst_flags);
overrun_flags.set_flag(TextServer::OVERRUN_JUSTIFICATION_AWARE);
- TS->shaped_text_overrun_trim_to_width(lines_rid[i], width, overrun_flags);
- TS->shaped_text_fit_to_width(lines_rid[i], width, jst_flags | TextServer::JUSTIFICATION_CONSTRAIN_ELLIPSIS);
+ TS->shaped_text_overrun_trim_to_width(line_rid, width, overrun_flags);
+ TS->shaped_text_fit_to_width(line_rid, width, jst_flags | TextServer::JUSTIFICATION_CONSTRAIN_ELLIPSIS);
} else {
- TS->shaped_text_overrun_trim_to_width(lines_rid[i], width, overrun_flags);
+ TS->shaped_text_overrun_trim_to_width(line_rid, width, overrun_flags);
}
}
}
@@ -268,8 +268,8 @@ RID TextParagraph::get_dropcap_rid() const {
void TextParagraph::clear() {
_THREAD_SAFE_METHOD_
- for (int i = 0; i < (int)lines_rid.size(); i++) {
- TS->free_rid(lines_rid[i]);
+ for (const RID &line_rid : lines_rid) {
+ TS->free_rid(line_rid);
}
lines_rid.clear();
TS->shaped_text_clear(rid);
@@ -915,17 +915,17 @@ int TextParagraph::hit_test(const Point2 &p_coords) const {
return 0;
}
}
- for (int i = 0; i < (int)lines_rid.size(); i++) {
- if (TS->shaped_text_get_orientation(lines_rid[i]) == TextServer::ORIENTATION_HORIZONTAL) {
- if ((p_coords.y >= ofs.y) && (p_coords.y <= ofs.y + TS->shaped_text_get_size(lines_rid[i]).y)) {
- return TS->shaped_text_hit_test_position(lines_rid[i], p_coords.x);
+ for (const RID &line_rid : lines_rid) {
+ if (TS->shaped_text_get_orientation(line_rid) == TextServer::ORIENTATION_HORIZONTAL) {
+ if ((p_coords.y >= ofs.y) && (p_coords.y <= ofs.y + TS->shaped_text_get_size(line_rid).y)) {
+ return TS->shaped_text_hit_test_position(line_rid, p_coords.x);
}
- ofs.y += TS->shaped_text_get_size(lines_rid[i]).y;
+ ofs.y += TS->shaped_text_get_size(line_rid).y;
} else {
- if ((p_coords.x >= ofs.x) && (p_coords.x <= ofs.x + TS->shaped_text_get_size(lines_rid[i]).x)) {
- return TS->shaped_text_hit_test_position(lines_rid[i], p_coords.y);
+ if ((p_coords.x >= ofs.x) && (p_coords.x <= ofs.x + TS->shaped_text_get_size(line_rid).x)) {
+ return TS->shaped_text_hit_test_position(line_rid, p_coords.y);
}
- ofs.y += TS->shaped_text_get_size(lines_rid[i]).x;
+ ofs.y += TS->shaped_text_get_size(line_rid).x;
}
}
return TS->shaped_text_get_range(rid).y;
@@ -1027,8 +1027,8 @@ TextParagraph::TextParagraph() {
}
TextParagraph::~TextParagraph() {
- for (int i = 0; i < (int)lines_rid.size(); i++) {
- TS->free_rid(lines_rid[i]);
+ for (const RID &line_rid : lines_rid) {
+ TS->free_rid(line_rid);
}
lines_rid.clear();
TS->free_rid(rid);
diff --git a/scene/resources/texture.cpp b/scene/resources/texture.cpp
index f106eebff5..7e3156d2ff 100644
--- a/scene/resources/texture.cpp
+++ b/scene/resources/texture.cpp
@@ -94,6 +94,13 @@ bool Texture2D::get_rect_region(const Rect2 &p_rect, const Rect2 &p_src_rect, Re
return true;
}
+Ref<Resource> Texture2D::create_placeholder() const {
+ Ref<PlaceholderTexture2D> placeholder;
+ placeholder.instantiate();
+ placeholder->set_size(get_size());
+ return placeholder;
+}
+
void Texture2D::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_width"), &Texture2D::get_width);
ClassDB::bind_method(D_METHOD("get_height"), &Texture2D::get_height);
@@ -103,6 +110,7 @@ void Texture2D::_bind_methods() {
ClassDB::bind_method(D_METHOD("draw_rect", "canvas_item", "rect", "tile", "modulate", "transpose"), &Texture2D::draw_rect, DEFVAL(Color(1, 1, 1)), DEFVAL(false));
ClassDB::bind_method(D_METHOD("draw_rect_region", "canvas_item", "rect", "src_rect", "modulate", "transpose", "clip_uv"), &Texture2D::draw_rect_region, DEFVAL(Color(1, 1, 1)), DEFVAL(false), DEFVAL(true));
ClassDB::bind_method(D_METHOD("get_image"), &Texture2D::get_image);
+ ClassDB::bind_method(D_METHOD("create_placeholder"), &Texture2D::create_placeholder);
ADD_GROUP("", "");
@@ -645,7 +653,7 @@ Ref<Image> CompressedTexture2D::load_image_from_file(Ref<FileAccess> f, int p_si
uint32_t mipmaps = f->get_32();
Image::Format format = Image::Format(f->get_32());
- if (data_format == DATA_FORMAT_PNG || data_format == DATA_FORMAT_WEBP || data_format == DATA_FORMAT_BASIS_UNIVERSAL) {
+ if (data_format == DATA_FORMAT_PNG || data_format == DATA_FORMAT_WEBP) {
//look for a PNG or WebP file inside
int sw = w;
@@ -676,9 +684,7 @@ Ref<Image> CompressedTexture2D::load_image_from_file(Ref<FileAccess> f, int p_si
}
Ref<Image> img;
- if (data_format == DATA_FORMAT_BASIS_UNIVERSAL && Image::basis_universal_unpacker) {
- img = Image::basis_universal_unpacker(pv);
- } else if (data_format == DATA_FORMAT_PNG && Image::png_unpacker) {
+ if (data_format == DATA_FORMAT_PNG && Image::png_unpacker) {
img = Image::png_unpacker(pv);
} else if (data_format == DATA_FORMAT_WEBP && Image::webp_unpacker) {
img = Image::webp_unpacker(pv);
@@ -737,6 +743,32 @@ Ref<Image> CompressedTexture2D::load_image_from_file(Ref<FileAccess> f, int p_si
return image;
}
+ } else if (data_format == DATA_FORMAT_BASIS_UNIVERSAL) {
+ int sw = w;
+ int sh = h;
+ uint32_t size = f->get_32();
+ if (p_size_limit > 0 && (sw > p_size_limit || sh > p_size_limit)) {
+ //can't load this due to size limit
+ sw = MAX(sw >> 1, 1);
+ sh = MAX(sh >> 1, 1);
+ f->seek(f->get_position() + size);
+ return Ref<Image>();
+ }
+ Vector<uint8_t> pv;
+ pv.resize(size);
+ {
+ uint8_t *wr = pv.ptrw();
+ f->get_buffer(wr, size);
+ }
+ Ref<Image> img;
+ img = Image::basis_universal_unpacker(pv);
+ if (img.is_null() || img->is_empty()) {
+ ERR_FAIL_COND_V(img.is_null() || img->is_empty(), Ref<Image>());
+ }
+ format = img->get_format();
+ sw = MAX(sw >> 1, 1);
+ sh = MAX(sh >> 1, 1);
+ return img;
} else if (data_format == DATA_FORMAT_IMAGE) {
int size = Image::get_image_data_size(w, h, format, mipmaps ? true : false);
@@ -1137,6 +1169,7 @@ void Texture3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_depth"), &Texture3D::get_depth);
ClassDB::bind_method(D_METHOD("has_mipmaps"), &Texture3D::has_mipmaps);
ClassDB::bind_method(D_METHOD("get_data"), &Texture3D::_get_datai);
+ ClassDB::bind_method(D_METHOD("create_placeholder"), &Texture3D::create_placeholder);
GDVIRTUAL_BIND(_get_format);
GDVIRTUAL_BIND(_get_width);
@@ -1145,6 +1178,14 @@ void Texture3D::_bind_methods() {
GDVIRTUAL_BIND(_has_mipmaps);
GDVIRTUAL_BIND(_get_data);
}
+
+Ref<Resource> Texture3D::create_placeholder() const {
+ Ref<PlaceholderTexture3D> placeholder;
+ placeholder.instantiate();
+ placeholder->set_size(Vector3i(get_width(), get_height(), get_depth()));
+ return placeholder;
+}
+
//////////////////////////////////////////
Image::Format ImageTexture3D::get_format() const {
@@ -3048,6 +3089,42 @@ ImageTextureLayered::~ImageTextureLayered() {
}
}
+void Texture2DArray::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("create_placeholder"), &Texture2DArray::create_placeholder);
+}
+
+Ref<Resource> Texture2DArray::create_placeholder() const {
+ Ref<PlaceholderTexture2DArray> placeholder;
+ placeholder.instantiate();
+ placeholder->set_size(Size2i(get_width(), get_height()));
+ placeholder->set_layers(get_layers());
+ return placeholder;
+}
+
+void Cubemap::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("create_placeholder"), &Cubemap::create_placeholder);
+}
+
+Ref<Resource> Cubemap::create_placeholder() const {
+ Ref<PlaceholderCubemap> placeholder;
+ placeholder.instantiate();
+ placeholder->set_size(Size2i(get_width(), get_height()));
+ placeholder->set_layers(get_layers());
+ return placeholder;
+}
+
+void CubemapArray::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("create_placeholder"), &CubemapArray::create_placeholder);
+}
+
+Ref<Resource> CubemapArray::create_placeholder() const {
+ Ref<PlaceholderCubemapArray> placeholder;
+ placeholder.instantiate();
+ placeholder->set_size(Size2i(get_width(), get_height()));
+ placeholder->set_layers(get_layers());
+ return placeholder;
+}
+
///////////////////////////////////////////
void CompressedTextureLayered::set_path(const String &p_path, bool p_take_over) {
diff --git a/scene/resources/texture.h b/scene/resources/texture.h
index bb86910c0c..7f74ae6941 100644
--- a/scene/resources/texture.h
+++ b/scene/resources/texture.h
@@ -82,6 +82,8 @@ public:
virtual Ref<Image> get_image() const { return Ref<Image>(); }
+ virtual Ref<Resource> create_placeholder() const;
+
Texture2D();
};
@@ -450,25 +452,41 @@ public:
class Texture2DArray : public ImageTextureLayered {
GDCLASS(Texture2DArray, ImageTextureLayered)
+
+protected:
+ static void _bind_methods();
+
public:
Texture2DArray() :
ImageTextureLayered(LAYERED_TYPE_2D_ARRAY) {}
+
+ virtual Ref<Resource> create_placeholder() const;
};
class Cubemap : public ImageTextureLayered {
GDCLASS(Cubemap, ImageTextureLayered);
+protected:
+ static void _bind_methods();
+
public:
Cubemap() :
ImageTextureLayered(LAYERED_TYPE_CUBEMAP) {}
+
+ virtual Ref<Resource> create_placeholder() const;
};
class CubemapArray : public ImageTextureLayered {
GDCLASS(CubemapArray, ImageTextureLayered);
+protected:
+ static void _bind_methods();
+
public:
CubemapArray() :
ImageTextureLayered(LAYERED_TYPE_CUBEMAP_ARRAY) {}
+
+ virtual Ref<Resource> create_placeholder() const;
};
class CompressedTextureLayered : public TextureLayered {
@@ -580,6 +598,7 @@ public:
virtual int get_depth() const;
virtual bool has_mipmaps() const;
virtual Vector<Ref<Image>> get_data() const;
+ virtual Ref<Resource> create_placeholder() const;
};
class ImageTexture3D : public Texture3D {
diff --git a/scene/resources/tile_set.cpp b/scene/resources/tile_set.cpp
index 4043b73b71..58a638804d 100644
--- a/scene/resources/tile_set.cpp
+++ b/scene/resources/tile_set.cpp
@@ -404,8 +404,8 @@ void TileSet::_update_terrains_cache() {
if (terrains_cache_dirty) {
// Organizes tiles into structures.
per_terrain_pattern_tiles.resize(terrain_sets.size());
- for (int i = 0; i < (int)per_terrain_pattern_tiles.size(); i++) {
- per_terrain_pattern_tiles[i].clear();
+ for (RBMap<TileSet::TerrainsPattern, RBSet<TileMapCell>> &tiles : per_terrain_pattern_tiles) {
+ tiles.clear();
}
for (const KeyValue<int, Ref<TileSetSource>> &kv : sources) {
@@ -473,6 +473,7 @@ void TileSet::_compute_next_source_id() {
int TileSet::add_source(Ref<TileSetSource> p_tile_set_source, int p_atlas_source_id_override) {
ERR_FAIL_COND_V(!p_tile_set_source.is_valid(), TileSet::INVALID_SOURCE);
ERR_FAIL_COND_V_MSG(p_atlas_source_id_override >= 0 && (sources.has(p_atlas_source_id_override)), TileSet::INVALID_SOURCE, vformat("Cannot create TileSet atlas source. Another atlas source exists with id %d.", p_atlas_source_id_override));
+ ERR_FAIL_COND_V_MSG(p_atlas_source_id_override < 0 && p_atlas_source_id_override != TileSet::INVALID_SOURCE, TileSet::INVALID_SOURCE, vformat("Provided source ID %d is not valid. Negative source IDs are not allowed.", p_atlas_source_id_override));
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;
@@ -990,6 +991,28 @@ uint32_t TileSet::get_navigation_layer_layers(int p_layer_index) const {
return navigation_layers[p_layer_index].layers;
}
+void TileSet::set_navigation_layer_layer_value(int p_layer_index, int p_layer_number, bool p_value) {
+ ERR_FAIL_COND_MSG(p_layer_number < 1, "Navigation layer number must be between 1 and 32 inclusive.");
+ ERR_FAIL_COND_MSG(p_layer_number > 32, "Navigation layer number must be between 1 and 32 inclusive.");
+
+ uint32_t _navigation_layers = get_navigation_layer_layers(p_layer_index);
+
+ if (p_value) {
+ _navigation_layers |= 1 << (p_layer_number - 1);
+ } else {
+ _navigation_layers &= ~(1 << (p_layer_number - 1));
+ }
+
+ set_navigation_layer_layers(p_layer_index, _navigation_layers);
+}
+
+bool TileSet::get_navigation_layer_layer_value(int p_layer_index, int p_layer_number) const {
+ ERR_FAIL_COND_V_MSG(p_layer_number < 1, false, "Navigation layer number must be between 1 and 32 inclusive.");
+ ERR_FAIL_COND_V_MSG(p_layer_number > 32, false, "Navigation layer number must be between 1 and 32 inclusive.");
+
+ return get_navigation_layer_layers(p_layer_index) & (1 << (p_layer_number - 1));
+}
+
// Custom data.
int TileSet::get_custom_data_layers_count() const {
return custom_data_layers.size();
@@ -1341,8 +1364,8 @@ void TileSet::clear_tile_proxies() {
int TileSet::add_pattern(Ref<TileMapPattern> p_pattern, int p_index) {
ERR_FAIL_COND_V(!p_pattern.is_valid(), -1);
ERR_FAIL_COND_V_MSG(p_pattern->is_empty(), -1, "Cannot add an empty pattern to the TileSet.");
- for (unsigned int i = 0; i < patterns.size(); i++) {
- ERR_FAIL_COND_V_MSG(patterns[i] == p_pattern, -1, "TileSet has already this pattern.");
+ for (const Ref<TileMapPattern> &pattern : patterns) {
+ ERR_FAIL_COND_V_MSG(pattern == p_pattern, -1, "TileSet has already this pattern.");
}
ERR_FAIL_COND_V(p_index > (int)patterns.size(), -1);
if (p_index < 0) {
@@ -2532,6 +2555,11 @@ void TileSet::_compatibility_conversion() {
bool flip_v = flags & 2;
bool transpose = flags & 4;
+ Transform2D xform;
+ xform = flip_h ? xform.scaled(Size2(-1, 1)) : xform;
+ xform = flip_v ? xform.scaled(Size2(1, -1)) : xform;
+ xform = transpose ? xform.rotated(Math_PI).scaled(Size2(-1, -1)) : xform;
+
int alternative_tile = 0;
if (!atlas_source->has_tile(coords)) {
atlas_source->create_tile(coords);
@@ -2568,14 +2596,26 @@ void TileSet::_compatibility_conversion() {
if (ctd->occluder.is_valid()) {
if (get_occlusion_layers_count() < 1) {
add_occlusion_layer();
+ };
+ Ref<OccluderPolygon2D> occluder = ctd->occluder->duplicate();
+ Vector<Vector2> polygon = ctd->occluder->get_polygon();
+ for (int index = 0; index < polygon.size(); index++) {
+ polygon.write[index] = xform.xform(polygon[index] - ctd->region.get_size() / 2.0);
}
- tile_data->set_occluder(0, ctd->occluder);
+ occluder->set_polygon(polygon);
+ tile_data->set_occluder(0, occluder);
}
if (ctd->navigation.is_valid()) {
if (get_navigation_layers_count() < 1) {
add_navigation_layer();
}
- tile_data->set_navigation_polygon(0, ctd->autotile_navpoly_map[coords]);
+ Ref<NavigationPolygon> navigation = ctd->navigation->duplicate();
+ Vector<Vector2> vertices = navigation->get_vertices();
+ for (int index = 0; index < vertices.size(); index++) {
+ vertices.write[index] = xform.xform(vertices[index] - ctd->region.get_size() / 2.0);
+ }
+ navigation->set_vertices(vertices);
+ tile_data->set_navigation_polygon(0, navigation);
}
tile_data->set_z_index(ctd->z_index);
@@ -2593,7 +2633,7 @@ void TileSet::_compatibility_conversion() {
if (convex_shape.is_valid()) {
Vector<Vector2> polygon = convex_shape->get_points();
for (int point_index = 0; point_index < polygon.size(); point_index++) {
- polygon.write[point_index] = csd.transform.xform(polygon[point_index]);
+ polygon.write[point_index] = xform.xform(csd.transform.xform(polygon[point_index]) - ctd->region.get_size() / 2.0);
}
tile_data->set_collision_polygons_count(0, tile_data->get_collision_polygons_count(0) + 1);
int index = tile_data->get_collision_polygons_count(0) - 1;
@@ -2604,9 +2644,15 @@ void TileSet::_compatibility_conversion() {
}
}
}
+ // Update the size count.
+ if (!compatibility_size_count.has(ctd->region.get_size())) {
+ compatibility_size_count[ctd->region.get_size()] = 0;
+ }
+ compatibility_size_count[ctd->region.get_size()]++;
} break;
case COMPATIBILITY_TILE_MODE_AUTO_TILE: {
// Not supported. It would need manual conversion.
+ WARN_PRINT_ONCE("Could not convert 3.x autotiles to 4.x. This operation cannot be done automatically, autotiles must be re-created using the terrain system.");
} break;
case COMPATIBILITY_TILE_MODE_ATLAS_TILE: {
atlas_source->set_margins(ctd->region.get_position());
@@ -2623,6 +2669,11 @@ void TileSet::_compatibility_conversion() {
bool flip_v = flags & 2;
bool transpose = flags & 4;
+ Transform2D xform;
+ xform = flip_h ? xform.scaled(Size2(-1, 1)) : xform;
+ xform = flip_v ? xform.scaled(Size2(1, -1)) : xform;
+ xform = transpose ? xform.rotated(Math_PI).scaled(Size2(-1, -1)) : xform;
+
int alternative_tile = 0;
if (!atlas_source->has_tile(coords)) {
atlas_source->create_tile(coords);
@@ -2660,13 +2711,25 @@ void TileSet::_compatibility_conversion() {
if (get_occlusion_layers_count() < 1) {
add_occlusion_layer();
}
- tile_data->set_occluder(0, ctd->autotile_occluder_map[coords]);
+ Ref<OccluderPolygon2D> occluder = ctd->autotile_occluder_map[coords]->duplicate();
+ Vector<Vector2> polygon = ctd->occluder->get_polygon();
+ for (int index = 0; index < polygon.size(); index++) {
+ polygon.write[index] = xform.xform(polygon[index] - ctd->region.get_size() / 2.0);
+ }
+ occluder->set_polygon(polygon);
+ tile_data->set_occluder(0, occluder);
}
if (ctd->autotile_navpoly_map.has(coords)) {
if (get_navigation_layers_count() < 1) {
add_navigation_layer();
}
- tile_data->set_navigation_polygon(0, ctd->autotile_navpoly_map[coords]);
+ Ref<NavigationPolygon> navigation = ctd->autotile_navpoly_map[coords]->duplicate();
+ Vector<Vector2> vertices = navigation->get_vertices();
+ for (int index = 0; index < vertices.size(); index++) {
+ vertices.write[index] = xform.xform(vertices[index] - ctd->region.get_size() / 2.0);
+ }
+ navigation->set_vertices(vertices);
+ tile_data->set_navigation_polygon(0, navigation);
}
if (ctd->autotile_priority_map.has(coords)) {
tile_data->set_probability(ctd->autotile_priority_map[coords]);
@@ -2688,7 +2751,7 @@ void TileSet::_compatibility_conversion() {
if (convex_shape.is_valid()) {
Vector<Vector2> polygon = convex_shape->get_points();
for (int point_index = 0; point_index < polygon.size(); point_index++) {
- polygon.write[point_index] = csd.transform.xform(polygon[point_index]);
+ polygon.write[point_index] = xform.xform(csd.transform.xform(polygon[point_index]) - ctd->autotile_tile_size / 2.0);
}
tile_data->set_collision_polygons_count(0, tile_data->get_collision_polygons_count(0) + 1);
int index = tile_data->get_collision_polygons_count(0) - 1;
@@ -2711,6 +2774,12 @@ void TileSet::_compatibility_conversion() {
}
}
}
+
+ // Update the size count.
+ if (!compatibility_size_count.has(ctd->region.get_size())) {
+ compatibility_size_count[ctd->autotile_tile_size] = 0;
+ }
+ compatibility_size_count[ctd->autotile_tile_size] += atlas_size.x * atlas_size.y;
} break;
}
@@ -2727,7 +2796,18 @@ void TileSet::_compatibility_conversion() {
}
}
- // Reset compatibility data
+ // Update the TileSet tile_size according to the most common size found.
+ Vector2i max_size = get_tile_size();
+ int max_count = 0;
+ for (KeyValue<Vector2i, int> kv : compatibility_size_count) {
+ if (kv.value > max_count) {
+ max_size = kv.key;
+ max_count = kv.value;
+ }
+ }
+ set_tile_size(max_size);
+
+ // Reset compatibility data (besides the histogram counts)
for (const KeyValue<int, CompatibilityTileData *> &E : compatibility_data) {
memdelete(E.value);
}
@@ -2908,6 +2988,10 @@ bool TileSet::_set(const StringName &p_name, const Variant &p_value) {
}
ctd->shapes.push_back(csd);
}
+ } else if (what == "occluder") {
+ ctd->occluder = p_value;
+ } else if (what == "navigation") {
+ ctd->navigation = p_value;
/*
// IGNORED FOR NOW, they seem duplicated data compared to the shapes array
@@ -3386,6 +3470,8 @@ void TileSet::_bind_methods() {
ClassDB::bind_method(D_METHOD("remove_navigation_layer", "layer_index"), &TileSet::remove_navigation_layer);
ClassDB::bind_method(D_METHOD("set_navigation_layer_layers", "layer_index", "layers"), &TileSet::set_navigation_layer_layers);
ClassDB::bind_method(D_METHOD("get_navigation_layer_layers", "layer_index"), &TileSet::get_navigation_layer_layers);
+ ClassDB::bind_method(D_METHOD("set_navigation_layer_layer_value", "layer_index", "layer_number", "value"), &TileSet::set_navigation_layer_layer_value);
+ ClassDB::bind_method(D_METHOD("get_navigation_layer_layer_value", "layer_index", "layer_number"), &TileSet::get_navigation_layer_layer_value);
// Custom data
ClassDB::bind_method(D_METHOD("get_custom_data_layers_count"), &TileSet::get_custom_data_layers_count);
@@ -4189,8 +4275,8 @@ real_t TileSetAtlasSource::get_tile_animation_total_duration(const Vector2i p_at
ERR_FAIL_COND_V_MSG(!tiles.has(p_atlas_coords), 1, vformat("TileSetAtlasSource has no tile at %s.", Vector2i(p_atlas_coords)));
real_t sum = 0.0;
- for (int frame = 0; frame < (int)tiles[p_atlas_coords].animation_frames_durations.size(); frame++) {
- sum += tiles[p_atlas_coords].animation_frames_durations[frame];
+ for (const real_t &duration : tiles[p_atlas_coords].animation_frames_durations) {
+ sum += duration;
}
return sum;
}
@@ -4281,19 +4367,11 @@ Rect2i TileSetAtlasSource::get_tile_texture_region(Vector2i p_atlas_coords, int
return Rect2(origin, region_size);
}
-Vector2i TileSetAtlasSource::get_tile_effective_texture_offset(Vector2i p_atlas_coords, int p_alternative_tile) const {
- ERR_FAIL_COND_V_MSG(!tiles.has(p_atlas_coords), Vector2i(), vformat("TileSetAtlasSource has no tile at %s.", Vector2i(p_atlas_coords)));
- ERR_FAIL_COND_V_MSG(!has_alternative_tile(p_atlas_coords, p_alternative_tile), Vector2i(), vformat("TileSetAtlasSource has no alternative tile with id %d at %s.", p_alternative_tile, String(p_atlas_coords)));
- ERR_FAIL_COND_V(!tile_set, Vector2i());
+bool TileSetAtlasSource::is_position_in_tile_texture_region(const Vector2i p_atlas_coords, int p_alternative_tile, Vector2 p_position) const {
+ Size2 size = get_tile_texture_region(p_atlas_coords).size;
+ Rect2 rect = Rect2(-size / 2 - get_tile_data(p_atlas_coords, p_alternative_tile)->get_texture_origin(), size);
- Vector2 margin = (get_tile_texture_region(p_atlas_coords).size - tile_set->get_tile_size()) / 2;
- margin = Vector2i(MAX(0, margin.x), MAX(0, margin.y));
- Vector2i effective_texture_offset = get_tile_data(p_atlas_coords, p_alternative_tile)->get_texture_offset();
- if (ABS(effective_texture_offset.x) > margin.x || ABS(effective_texture_offset.y) > margin.y) {
- effective_texture_offset = effective_texture_offset.clamp(-margin, margin);
- }
-
- return effective_texture_offset;
+ return rect.has_point(p_position);
}
// Getters for texture and tile region (padded or not)
@@ -4572,8 +4650,8 @@ void TileSetAtlasSource::_clear_tiles_outside_texture() {
}
}
- for (unsigned int i = 0; i < to_remove.size(); i++) {
- remove_tile(to_remove[i]);
+ for (const Vector2i &v : to_remove) {
+ remove_tile(v);
}
}
@@ -5045,7 +5123,7 @@ TileData *TileData::duplicate() {
output->flip_h = flip_h;
output->flip_v = flip_v;
output->transpose = transpose;
- output->tex_offset = tex_offset;
+ output->texture_origin = texture_origin;
output->material = material;
output->modulate = modulate;
output->z_index = z_index;
@@ -5095,13 +5173,13 @@ bool TileData::get_transpose() const {
return transpose;
}
-void TileData::set_texture_offset(Vector2i p_texture_offset) {
- tex_offset = p_texture_offset;
+void TileData::set_texture_origin(Vector2i p_texture_origin) {
+ texture_origin = p_texture_origin;
emit_signal(SNAME("changed"));
}
-Vector2i TileData::get_texture_offset() const {
- return tex_offset;
+Vector2i TileData::get_texture_origin() const {
+ return texture_origin;
}
void TileData::set_material(Ref<Material> p_material) {
@@ -5389,6 +5467,13 @@ Variant TileData::get_custom_data_by_layer_id(int p_layer_id) const {
}
bool TileData::_set(const StringName &p_name, const Variant &p_value) {
+#ifndef DISABLE_DEPRECATED
+ if (p_name == "texture_offset") {
+ texture_origin = p_value;
+ return true;
+ }
+#endif
+
Vector<String> components = String(p_name).split("/", true, 2);
if (components.size() == 2 && components[0].begins_with("occlusion_layer_") && components[0].trim_prefix("occlusion_layer_").is_valid_int()) {
@@ -5510,6 +5595,13 @@ bool TileData::_set(const StringName &p_name, const Variant &p_value) {
}
bool TileData::_get(const StringName &p_name, Variant &r_ret) const {
+#ifndef DISABLE_DEPRECATED
+ if (p_name == "texture_offset") {
+ r_ret = texture_origin;
+ return true;
+ }
+#endif
+
Vector<String> components = String(p_name).split("/", true, 2);
if (tile_set) {
@@ -5691,8 +5783,8 @@ void TileData::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_transpose"), &TileData::get_transpose);
ClassDB::bind_method(D_METHOD("set_material", "material"), &TileData::set_material);
ClassDB::bind_method(D_METHOD("get_material"), &TileData::get_material);
- ClassDB::bind_method(D_METHOD("set_texture_offset", "texture_offset"), &TileData::set_texture_offset);
- ClassDB::bind_method(D_METHOD("get_texture_offset"), &TileData::get_texture_offset);
+ ClassDB::bind_method(D_METHOD("set_texture_origin", "texture_origin"), &TileData::set_texture_origin);
+ ClassDB::bind_method(D_METHOD("get_texture_origin"), &TileData::get_texture_origin);
ClassDB::bind_method(D_METHOD("set_modulate", "modulate"), &TileData::set_modulate);
ClassDB::bind_method(D_METHOD("get_modulate"), &TileData::get_modulate);
ClassDB::bind_method(D_METHOD("set_z_index", "z_index"), &TileData::set_z_index);
@@ -5745,7 +5837,7 @@ void TileData::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "flip_h"), "set_flip_h", "get_flip_h");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "flip_v"), "set_flip_v", "get_flip_v");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "transpose"), "set_transpose", "get_transpose");
- ADD_PROPERTY(PropertyInfo(Variant::VECTOR2I, "texture_offset", PROPERTY_HINT_NONE, "suffix:px"), "set_texture_offset", "get_texture_offset");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR2I, "texture_origin", PROPERTY_HINT_NONE, "suffix:px"), "set_texture_origin", "get_texture_origin");
ADD_PROPERTY(PropertyInfo(Variant::COLOR, "modulate"), "set_modulate", "get_modulate");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "material", PROPERTY_HINT_RESOURCE_TYPE, "CanvasItemMaterial,ShaderMaterial"), "set_material", "get_material");
ADD_PROPERTY(PropertyInfo(Variant::INT, "z_index"), "set_z_index", "get_z_index");
diff --git a/scene/resources/tile_set.h b/scene/resources/tile_set.h
index c2ed798f2b..ad25629a1c 100644
--- a/scene/resources/tile_set.h
+++ b/scene/resources/tile_set.h
@@ -198,6 +198,7 @@ private:
HashMap<int, CompatibilityTileData *> compatibility_data;
HashMap<int, int> compatibility_tilemap_mapping_tile_modes;
HashMap<int, RBMap<Array, Array>> compatibility_tilemap_mapping;
+ HashMap<Vector2i, int> compatibility_size_count;
void _compatibility_conversion();
@@ -475,6 +476,8 @@ public:
void remove_navigation_layer(int p_index);
void set_navigation_layer_layers(int p_layer_index, uint32_t p_layers);
uint32_t get_navigation_layer_layers(int p_layer_index) const;
+ void set_navigation_layer_layer_value(int p_layer_index, int p_layer_number, bool p_value);
+ bool get_navigation_layer_layer_value(int p_layer_index, int p_layer_number) const;
// Custom data
int get_custom_data_layers_count() const;
@@ -719,7 +722,7 @@ public:
// Helpers.
Vector2i get_atlas_grid_size() const;
Rect2i get_tile_texture_region(Vector2i p_atlas_coords, int p_frame = 0) const;
- Vector2i get_tile_effective_texture_offset(Vector2i p_atlas_coords, int p_alternative_tile) const;
+ bool is_position_in_tile_texture_region(const Vector2i p_atlas_coords, int p_alternative_tile, Vector2 p_position) const;
// Getters for texture and tile region (padded or not)
Ref<Texture2D> get_runtime_texture() const;
@@ -785,7 +788,7 @@ private:
bool flip_h = false;
bool flip_v = false;
bool transpose = false;
- Vector2i tex_offset;
+ Vector2i texture_origin;
Ref<Material> material = Ref<Material>();
Color modulate = Color(1.0, 1.0, 1.0, 1.0);
int z_index = 0;
@@ -864,8 +867,8 @@ public:
void set_transpose(bool p_transpose);
bool get_transpose() const;
- void set_texture_offset(Vector2i p_texture_offset);
- Vector2i get_texture_offset() const;
+ void set_texture_origin(Vector2i p_texture_origin);
+ Vector2i get_texture_origin() const;
void set_material(Ref<Material> p_material);
Ref<Material> get_material() const;
void set_modulate(Color p_modulate);
diff --git a/scene/resources/video_stream.cpp b/scene/resources/video_stream.cpp
new file mode 100644
index 0000000000..ee1a47c338
--- /dev/null
+++ b/scene/resources/video_stream.cpp
@@ -0,0 +1,198 @@
+/**************************************************************************/
+/* video_stream.cpp */
+/**************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/**************************************************************************/
+/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
+/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
+/* */
+/* 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 "video_stream.h"
+
+#include "core/config/project_settings.h"
+#include "servers/audio_server.h"
+
+// VideoStreamPlayback starts here.
+
+void VideoStreamPlayback::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("mix_audio", "num_frames", "buffer", "offset"), &VideoStreamPlayback::mix_audio, DEFVAL(PackedFloat32Array()), DEFVAL(0));
+ GDVIRTUAL_BIND(_stop);
+ GDVIRTUAL_BIND(_play);
+ GDVIRTUAL_BIND(_is_playing);
+ GDVIRTUAL_BIND(_set_paused, "paused");
+ GDVIRTUAL_BIND(_is_paused);
+ GDVIRTUAL_BIND(_get_length);
+ GDVIRTUAL_BIND(_get_playback_position);
+ GDVIRTUAL_BIND(_seek, "time");
+ GDVIRTUAL_BIND(_set_audio_track, "idx");
+ GDVIRTUAL_BIND(_get_texture);
+ GDVIRTUAL_BIND(_update, "delta");
+ GDVIRTUAL_BIND(_get_channels);
+ GDVIRTUAL_BIND(_get_mix_rate);
+}
+
+VideoStreamPlayback::VideoStreamPlayback() {
+}
+
+VideoStreamPlayback::~VideoStreamPlayback() {
+}
+
+void VideoStreamPlayback::stop() {
+ GDVIRTUAL_CALL(_stop);
+}
+
+void VideoStreamPlayback::play() {
+ GDVIRTUAL_CALL(_play);
+}
+
+bool VideoStreamPlayback::is_playing() const {
+ bool ret;
+ if (GDVIRTUAL_CALL(_is_playing, ret)) {
+ return ret;
+ }
+ return false;
+}
+
+void VideoStreamPlayback::set_paused(bool p_paused) {
+ GDVIRTUAL_CALL(_is_playing, p_paused);
+}
+
+bool VideoStreamPlayback::is_paused() const {
+ bool ret;
+ if (GDVIRTUAL_CALL(_is_paused, ret)) {
+ return ret;
+ }
+ return false;
+}
+
+double VideoStreamPlayback::get_length() const {
+ double ret;
+ if (GDVIRTUAL_CALL(_get_length, ret)) {
+ return ret;
+ }
+ return 0;
+}
+
+double VideoStreamPlayback::get_playback_position() const {
+ double ret;
+ if (GDVIRTUAL_CALL(_get_playback_position, ret)) {
+ return ret;
+ }
+ return 0;
+}
+
+void VideoStreamPlayback::seek(double p_time) {
+ GDVIRTUAL_CALL(_seek, p_time);
+}
+
+void VideoStreamPlayback::set_audio_track(int p_idx) {
+ GDVIRTUAL_CALL(_set_audio_track, p_idx);
+}
+
+Ref<Texture2D> VideoStreamPlayback::get_texture() const {
+ Ref<Texture2D> ret;
+ if (GDVIRTUAL_CALL(_get_texture, ret)) {
+ return ret;
+ }
+ return nullptr;
+}
+
+void VideoStreamPlayback::update(double p_delta) {
+ if (!GDVIRTUAL_CALL(_update, p_delta)) {
+ ERR_FAIL_MSG("VideoStreamPlayback::update unimplemented");
+ }
+}
+
+void VideoStreamPlayback::set_mix_callback(AudioMixCallback p_callback, void *p_userdata) {
+ mix_callback = p_callback;
+ mix_udata = p_userdata;
+}
+
+int VideoStreamPlayback::get_channels() const {
+ int ret;
+ if (GDVIRTUAL_CALL(_get_channels, ret)) {
+ _channel_count = ret;
+ return ret;
+ }
+ return 0;
+}
+
+int VideoStreamPlayback::get_mix_rate() const {
+ int ret;
+ if (GDVIRTUAL_CALL(_get_mix_rate, ret)) {
+ return ret;
+ }
+ return 0;
+}
+
+int VideoStreamPlayback::mix_audio(int num_frames, PackedFloat32Array buffer, int offset) {
+ if (num_frames <= 0) {
+ return 0;
+ }
+ if (!mix_callback) {
+ return -1;
+ }
+ ERR_FAIL_INDEX_V(offset, buffer.size(), -1);
+ ERR_FAIL_INDEX_V((_channel_count < 1 ? 1 : _channel_count) * num_frames - 1, buffer.size() - offset, -1);
+ return mix_callback(mix_udata, buffer.ptr() + offset, num_frames);
+}
+
+/* --- NOTE VideoStream starts here. ----- */
+
+Ref<VideoStreamPlayback> VideoStream::instantiate_playback() {
+ Ref<VideoStreamPlayback> ret;
+ if (GDVIRTUAL_CALL(_instantiate_playback, ret)) {
+ ERR_FAIL_COND_V_MSG(ret.is_null(), nullptr, "Plugin returned null playback");
+ ret->set_audio_track(audio_track);
+ return ret;
+ }
+ return nullptr;
+}
+
+void VideoStream::set_file(const String &p_file) {
+ file = p_file;
+}
+
+String VideoStream::get_file() {
+ return file;
+}
+
+void VideoStream::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("set_file", "file"), &VideoStream::set_file);
+ ClassDB::bind_method(D_METHOD("get_file"), &VideoStream::get_file);
+
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "file"), "set_file", "get_file");
+
+ GDVIRTUAL_BIND(_instantiate_playback);
+}
+
+VideoStream::VideoStream() {
+}
+
+VideoStream::~VideoStream() {
+}
+
+void VideoStream::set_audio_track(int p_track) {
+ audio_track = p_track;
+}
diff --git a/scene/resources/video_stream.h b/scene/resources/video_stream.h
index f83c621d0a..b91a7acf35 100644
--- a/scene/resources/video_stream.h
+++ b/scene/resources/video_stream.h
@@ -31,6 +31,7 @@
#ifndef VIDEO_STREAM_H
#define VIDEO_STREAM_H
+#include "core/io/file_access.h"
#include "scene/resources/texture.h"
class VideoStreamPlayback : public Resource {
@@ -39,40 +40,77 @@ class VideoStreamPlayback : public Resource {
public:
typedef int (*AudioMixCallback)(void *p_udata, const float *p_data, int p_frames);
- virtual void stop() = 0;
- virtual void play() = 0;
+protected:
+ AudioMixCallback mix_callback = nullptr;
+ void *mix_udata = nullptr;
+ mutable int _channel_count = 0; // Used only to assist with bounds checking in mix_audio.
+
+ static void _bind_methods();
+ GDVIRTUAL0(_stop);
+ GDVIRTUAL0(_play);
+ GDVIRTUAL0RC(bool, _is_playing);
+ GDVIRTUAL1(_set_paused, bool);
+ GDVIRTUAL0RC(bool, _is_paused);
+ GDVIRTUAL0RC(double, _get_length);
+ GDVIRTUAL0RC(double, _get_playback_position);
+ GDVIRTUAL1(_seek, double);
+ GDVIRTUAL1(_set_audio_track, int);
+ GDVIRTUAL0RC(Ref<Texture2D>, _get_texture);
+ GDVIRTUAL1(_update, double);
+ GDVIRTUAL0RC(int, _get_channels);
+ GDVIRTUAL0RC(int, _get_mix_rate);
+
+ int mix_audio(int num_frames, PackedFloat32Array buffer = {}, int offset = 0);
- virtual bool is_playing() const = 0;
+public:
+ VideoStreamPlayback();
+ virtual ~VideoStreamPlayback();
- virtual void set_paused(bool p_paused) = 0;
- virtual bool is_paused() const = 0;
+ virtual void stop();
+ virtual void play();
- virtual void set_loop(bool p_enable) = 0;
- virtual bool has_loop() const = 0;
+ virtual bool is_playing() const;
- virtual double get_length() const = 0;
+ virtual void set_paused(bool p_paused);
+ virtual bool is_paused() const;
- virtual double get_playback_position() const = 0;
- virtual void seek(double p_time) = 0;
+ virtual double get_length() const;
- virtual void set_audio_track(int p_idx) = 0;
+ virtual double get_playback_position() const;
+ virtual void seek(double p_time);
- virtual Ref<Texture2D> get_texture() const = 0;
+ virtual void set_audio_track(int p_idx);
- virtual void update(double p_delta) = 0;
+ virtual Ref<Texture2D> get_texture() const;
+ virtual void update(double p_delta);
- virtual void set_mix_callback(AudioMixCallback p_callback, void *p_userdata) = 0;
- virtual int get_channels() const = 0;
- virtual int get_mix_rate() const = 0;
+ virtual void set_mix_callback(AudioMixCallback p_callback, void *p_userdata);
+ virtual int get_channels() const;
+ virtual int get_mix_rate() const;
};
class VideoStream : public Resource {
GDCLASS(VideoStream, Resource);
- OBJ_SAVE_TYPE(VideoStream); // Saves derived classes with common type so they can be interchanged.
+ OBJ_SAVE_TYPE(VideoStream);
+
+protected:
+ static void
+ _bind_methods();
+
+ GDVIRTUAL0R(Ref<VideoStreamPlayback>, _instantiate_playback);
+
+ String file;
+ int audio_track = 0;
public:
- virtual void set_audio_track(int p_track) = 0;
- virtual Ref<VideoStreamPlayback> instantiate_playback() = 0;
+ void set_file(const String &p_file);
+ String get_file();
+
+ virtual void set_audio_track(int p_track);
+ virtual Ref<VideoStreamPlayback> instantiate_playback();
+
+ VideoStream();
+ ~VideoStream();
};
#endif // VIDEO_STREAM_H
diff --git a/scene/resources/visual_shader.cpp b/scene/resources/visual_shader.cpp
index d8a963f15b..3a6d40d22c 100644
--- a/scene/resources/visual_shader.cpp
+++ b/scene/resources/visual_shader.cpp
@@ -399,10 +399,10 @@ void VisualShaderNode::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::INT, "output_port_for_preview"), "set_output_port_for_preview", "get_output_port_for_preview");
ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "default_input_values", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL), "set_default_input_values", "get_default_input_values");
ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "expanded_output_ports", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL), "_set_output_ports_expanded", "_get_output_ports_expanded");
- ADD_SIGNAL(MethodInfo("editor_refresh_request"));
BIND_ENUM_CONSTANT(PORT_TYPE_SCALAR);
BIND_ENUM_CONSTANT(PORT_TYPE_SCALAR_INT);
+ BIND_ENUM_CONSTANT(PORT_TYPE_SCALAR_UINT);
BIND_ENUM_CONSTANT(PORT_TYPE_VECTOR_2D);
BIND_ENUM_CONSTANT(PORT_TYPE_VECTOR_3D);
BIND_ENUM_CONSTANT(PORT_TYPE_VECTOR_4D);
@@ -427,7 +427,10 @@ void VisualShaderNodeCustom::update_ports() {
if (!GDVIRTUAL_CALL(_get_input_port_name, i, port.name)) {
port.name = "in" + itos(i);
}
- if (!GDVIRTUAL_CALL(_get_input_port_type, i, port.type)) {
+ PortType port_type;
+ if (GDVIRTUAL_CALL(_get_input_port_type, i, port_type)) {
+ port.type = (int)port_type;
+ } else {
port.type = (int)PortType::PORT_TYPE_SCALAR;
}
@@ -445,7 +448,10 @@ void VisualShaderNodeCustom::update_ports() {
if (!GDVIRTUAL_CALL(_get_output_port_name, i, port.name)) {
port.name = "out" + itos(i);
}
- if (!GDVIRTUAL_CALL(_get_output_port_type, i, port.type)) {
+ PortType port_type;
+ if (GDVIRTUAL_CALL(_get_output_port_type, i, port_type)) {
+ port.type = (int)port_type;
+ } else {
port.type = (int)PortType::PORT_TYPE_SCALAR;
}
@@ -809,6 +815,8 @@ void VisualShader::remove_node(Type p_type, int p_id) {
if (E->get().from_node == p_id) {
g->nodes[E->get().to_node].prev_connected_nodes.erase(p_id);
g->nodes[E->get().to_node].node->set_input_port_connected(E->get().to_port, false);
+ } else if (E->get().to_node == p_id) {
+ g->nodes[E->get().from_node].next_connected_nodes.erase(p_id);
}
}
E = N;
@@ -951,7 +959,7 @@ bool VisualShader::can_connect_nodes(Type p_type, int p_from_node, int p_from_po
}
bool VisualShader::is_port_types_compatible(int p_a, int p_b) const {
- return MAX(0, p_a - 5) == (MAX(0, p_b - 5));
+ return MAX(0, p_a - (int)VisualShaderNode::PORT_TYPE_BOOLEAN) == (MAX(0, p_b - (int)VisualShaderNode::PORT_TYPE_BOOLEAN));
}
void VisualShader::connect_nodes_forced(Type p_type, int p_from_node, int p_from_port, int p_to_node, int p_to_port) {
@@ -975,6 +983,7 @@ void VisualShader::connect_nodes_forced(Type p_type, int p_from_node, int p_from
c.to_node = p_to_node;
c.to_port = p_to_port;
g->connections.push_back(c);
+ g->nodes[p_from_node].next_connected_nodes.push_back(p_to_node);
g->nodes[p_to_node].prev_connected_nodes.push_back(p_from_node);
g->nodes[p_from_node].node->set_output_port_connected(p_from_port, true);
g->nodes[p_to_node].node->set_input_port_connected(p_to_port, true);
@@ -1008,6 +1017,7 @@ Error VisualShader::connect_nodes(Type p_type, int p_from_node, int p_from_port,
c.to_node = p_to_node;
c.to_port = p_to_port;
g->connections.push_back(c);
+ g->nodes[p_from_node].next_connected_nodes.push_back(p_to_node);
g->nodes[p_to_node].prev_connected_nodes.push_back(p_from_node);
g->nodes[p_from_node].node->set_output_port_connected(p_from_port, true);
g->nodes[p_to_node].node->set_input_port_connected(p_to_port, true);
@@ -1023,6 +1033,7 @@ void VisualShader::disconnect_nodes(Type p_type, int p_from_node, int p_from_por
for (const List<Connection>::Element *E = g->connections.front(); E; E = E->next()) {
if (E->get().from_node == p_from_node && E->get().from_port == p_from_port && E->get().to_node == p_to_node && E->get().to_port == p_to_port) {
g->connections.erase(E);
+ g->nodes[p_from_node].next_connected_nodes.erase(p_to_node);
g->nodes[p_to_node].prev_connected_nodes.erase(p_from_node);
g->nodes[p_from_node].node->set_output_port_connected(p_from_port, false);
g->nodes[p_to_node].node->set_input_port_connected(p_to_port, false);
@@ -1198,6 +1209,9 @@ String VisualShader::generate_preview_shader(Type p_type, int p_node, int p_port
case VisualShaderNode::PORT_TYPE_SCALAR_INT: {
shader_code += " COLOR.rgb = vec3(float(n_out" + itos(p_node) + "p" + itos(p_port) + "));\n";
} break;
+ case VisualShaderNode::PORT_TYPE_SCALAR_UINT: {
+ shader_code += " COLOR.rgb = vec3(float(n_out" + itos(p_node) + "p" + itos(p_port) + "));\n";
+ } break;
case VisualShaderNode::PORT_TYPE_BOOLEAN: {
shader_code += " COLOR.rgb = vec3(n_out" + itos(p_node) + "p" + itos(p_port) + " ? 1.0 : 0.0);\n";
} break;
@@ -1558,7 +1572,7 @@ void VisualShader::_get_property_list(List<PropertyInfo> *p_list) const {
prop_name += "/" + itos(E.key);
if (E.key != NODE_ID_OUTPUT) {
- p_list->push_back(PropertyInfo(Variant::OBJECT, prop_name + "/node", PROPERTY_HINT_RESOURCE_TYPE, "VisualShaderNode", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_DO_NOT_SHARE_ON_DUPLICATE));
+ p_list->push_back(PropertyInfo(Variant::OBJECT, prop_name + "/node", PROPERTY_HINT_RESOURCE_TYPE, "VisualShaderNode", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_ALWAYS_DUPLICATE));
}
p_list->push_back(PropertyInfo(Variant::VECTOR2, prop_name + "/position", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR));
@@ -1689,6 +1703,9 @@ Error VisualShader::_write_node(Type type, StringBuilder *p_global_code, StringB
case VisualShaderNode::PORT_TYPE_SCALAR_INT: {
inputs[i] = "float(" + src_var + ")";
} break;
+ case VisualShaderNode::PORT_TYPE_SCALAR_UINT: {
+ inputs[i] = "float(" + src_var + ")";
+ } break;
case VisualShaderNode::PORT_TYPE_BOOLEAN: {
inputs[i] = "(" + src_var + " ? 1.0 : 0.0)";
} break;
@@ -1710,17 +1727,44 @@ Error VisualShader::_write_node(Type type, StringBuilder *p_global_code, StringB
case VisualShaderNode::PORT_TYPE_SCALAR: {
inputs[i] = "int(" + src_var + ")";
} break;
+ case VisualShaderNode::PORT_TYPE_SCALAR_UINT: {
+ inputs[i] = "int(" + src_var + ")";
+ } break;
case VisualShaderNode::PORT_TYPE_BOOLEAN: {
inputs[i] = "(" + src_var + " ? 1 : 0)";
} break;
case VisualShaderNode::PORT_TYPE_VECTOR_2D: {
- inputs[i] = "dot(float(" + src_var + "), vec2(0.5, 0.5))";
+ inputs[i] = "int(" + src_var + ".x)";
+ } break;
+ case VisualShaderNode::PORT_TYPE_VECTOR_3D: {
+ inputs[i] = "int(" + src_var + ".x)";
+ } break;
+ case VisualShaderNode::PORT_TYPE_VECTOR_4D: {
+ inputs[i] = "int(" + src_var + ".x)";
+ } break;
+ default:
+ break;
+ }
+ } break;
+ case VisualShaderNode::PORT_TYPE_SCALAR_UINT: {
+ switch (out_type) {
+ case VisualShaderNode::PORT_TYPE_SCALAR: {
+ inputs[i] = "uint(" + src_var + ")";
+ } break;
+ case VisualShaderNode::PORT_TYPE_SCALAR_INT: {
+ inputs[i] = "uint(" + src_var + ")";
+ } break;
+ case VisualShaderNode::PORT_TYPE_BOOLEAN: {
+ inputs[i] = "(" + src_var + " ? 1u : 0u)";
+ } break;
+ case VisualShaderNode::PORT_TYPE_VECTOR_2D: {
+ inputs[i] = "uint(" + src_var + ".x)";
} break;
case VisualShaderNode::PORT_TYPE_VECTOR_3D: {
- inputs[i] = "dot(float(" + src_var + "), vec3(0.333333, 0.333333, 0.333333))";
+ inputs[i] = "uint(" + src_var + ".x)";
} break;
case VisualShaderNode::PORT_TYPE_VECTOR_4D: {
- inputs[i] = "dot(float(" + src_var + "), vec4(0.25, 0.25, 0.25, 0.25))";
+ inputs[i] = "uint(" + src_var + ".x)";
} break;
default:
break;
@@ -1734,6 +1778,9 @@ Error VisualShader::_write_node(Type type, StringBuilder *p_global_code, StringB
case VisualShaderNode::PORT_TYPE_SCALAR_INT: {
inputs[i] = src_var + " > 0 ? true : false";
} break;
+ case VisualShaderNode::PORT_TYPE_SCALAR_UINT: {
+ inputs[i] = src_var + " > 0u ? true : false";
+ } break;
case VisualShaderNode::PORT_TYPE_VECTOR_2D: {
inputs[i] = "all(bvec2(" + src_var + "))";
} break;
@@ -1755,6 +1802,9 @@ Error VisualShader::_write_node(Type type, StringBuilder *p_global_code, StringB
case VisualShaderNode::PORT_TYPE_SCALAR_INT: {
inputs[i] = "vec2(float(" + src_var + "))";
} break;
+ case VisualShaderNode::PORT_TYPE_SCALAR_UINT: {
+ inputs[i] = "vec2(float(" + src_var + "))";
+ } break;
case VisualShaderNode::PORT_TYPE_BOOLEAN: {
inputs[i] = "vec2(" + src_var + " ? 1.0 : 0.0)";
} break;
@@ -1775,6 +1825,9 @@ Error VisualShader::_write_node(Type type, StringBuilder *p_global_code, StringB
case VisualShaderNode::PORT_TYPE_SCALAR_INT: {
inputs[i] = "vec3(float(" + src_var + "))";
} break;
+ case VisualShaderNode::PORT_TYPE_SCALAR_UINT: {
+ inputs[i] = "vec3(float(" + src_var + "))";
+ } break;
case VisualShaderNode::PORT_TYPE_BOOLEAN: {
inputs[i] = "vec3(" + src_var + " ? 1.0 : 0.0)";
} break;
@@ -1796,6 +1849,9 @@ Error VisualShader::_write_node(Type type, StringBuilder *p_global_code, StringB
case VisualShaderNode::PORT_TYPE_SCALAR_INT: {
inputs[i] = "vec4(float(" + src_var + "))";
} break;
+ case VisualShaderNode::PORT_TYPE_SCALAR_UINT: {
+ inputs[i] = "vec4(float(" + src_var + "))";
+ } break;
case VisualShaderNode::PORT_TYPE_BOOLEAN: {
inputs[i] = "vec4(" + src_var + " ? 1.0 : 0.0)";
} break;
@@ -1826,7 +1882,11 @@ Error VisualShader::_write_node(Type type, StringBuilder *p_global_code, StringB
} else if (defval.get_type() == Variant::INT) {
int val = defval;
inputs[i] = "n_in" + itos(p_node) + "p" + itos(i);
- node_code += " int " + inputs[i] + " = " + itos(val) + ";\n";
+ if (vsnode->get_input_port_type(i) == VisualShaderNode::PORT_TYPE_SCALAR_UINT) {
+ node_code += " uint " + inputs[i] + " = " + itos(val) + "u;\n";
+ } else {
+ node_code += " int " + inputs[i] + " = " + itos(val) + ";\n";
+ }
} else if (defval.get_type() == Variant::BOOL) {
bool val = defval;
inputs[i] = "n_in" + itos(p_node) + "p" + itos(i);
@@ -1906,6 +1966,9 @@ Error VisualShader::_write_node(Type type, StringBuilder *p_global_code, StringB
case VisualShaderNode::PORT_TYPE_SCALAR_INT:
outputs[i] = "int " + var_name;
break;
+ case VisualShaderNode::PORT_TYPE_SCALAR_UINT:
+ outputs[i] = "uint " + var_name;
+ break;
case VisualShaderNode::PORT_TYPE_VECTOR_2D:
outputs[i] = "vec2 " + var_name;
break;
@@ -1951,6 +2014,9 @@ Error VisualShader::_write_node(Type type, StringBuilder *p_global_code, StringB
case VisualShaderNode::PORT_TYPE_SCALAR_INT:
r_code += " int " + outputs[i] + ";\n";
break;
+ case VisualShaderNode::PORT_TYPE_SCALAR_UINT:
+ r_code += " uint " + outputs[i] + ";\n";
+ break;
case VisualShaderNode::PORT_TYPE_VECTOR_2D:
r_code += " vec2 " + outputs[i] + ";\n";
break;
@@ -2214,6 +2280,12 @@ void VisualShader::_update_shader() const {
}
global_code += "int ";
break;
+ case VaryingType::VARYING_TYPE_UINT:
+ if (E.value.mode == VaryingMode::VARYING_MODE_VERTEX_TO_FRAG_LIGHT) {
+ global_code += "flat ";
+ }
+ global_code += "uint ";
+ break;
case VaryingType::VARYING_TYPE_VECTOR_2D:
global_code += "vec2 ";
break;
@@ -2283,6 +2355,9 @@ void VisualShader::_update_shader() const {
case VaryingType::VARYING_TYPE_INT:
code2 += "0";
break;
+ case VaryingType::VARYING_TYPE_UINT:
+ code2 += "0u";
+ break;
case VaryingType::VARYING_TYPE_VECTOR_2D:
code2 += "vec2(0.0)";
break;
@@ -2443,14 +2518,6 @@ void VisualShader::_update_shader() const {
global_compute_code += " return __rand_from_seed(seed) * (to - from) + from;\n";
global_compute_code += "}\n\n";
- global_compute_code += "vec2 __randv2_range(inout uint seed, vec2 from, vec2 to) {\n";
- global_compute_code += " return vec2(__randf_range(seed, from.x, to.x), __randf_range(seed, from.y, to.y));\n";
- global_compute_code += "}\n\n";
-
- global_compute_code += "vec3 __randv3_range(inout uint seed, vec3 from, vec3 to) {\n";
- global_compute_code += " return vec3(__randf_range(seed, from.x, to.x), __randf_range(seed, from.y, to.y), __randf_range(seed, from.z, to.z));\n";
- global_compute_code += "}\n\n";
-
global_compute_code += "uint __hash(uint x) {\n";
global_compute_code += " x = ((x >> uint(16)) ^ x) * uint(73244475);\n";
global_compute_code += " x = ((x >> uint(16)) ^ x) * uint(73244475);\n";
@@ -2583,6 +2650,7 @@ void VisualShader::_bind_methods() {
BIND_ENUM_CONSTANT(VARYING_TYPE_FLOAT);
BIND_ENUM_CONSTANT(VARYING_TYPE_INT);
+ BIND_ENUM_CONSTANT(VARYING_TYPE_UINT);
BIND_ENUM_CONSTANT(VARYING_TYPE_VECTOR_2D);
BIND_ENUM_CONSTANT(VARYING_TYPE_VECTOR_3D);
BIND_ENUM_CONSTANT(VARYING_TYPE_VECTOR_4D);
@@ -2645,10 +2713,11 @@ const VisualShaderNodeInput::Port VisualShaderNodeInput::ports[] = {
{ Shader::MODE_SPATIAL, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_SCALAR_INT, "view_index", "VIEW_INDEX" },
{ Shader::MODE_SPATIAL, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_SCALAR_INT, "view_mono_left", "VIEW_MONO_LEFT" },
{ Shader::MODE_SPATIAL, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_SCALAR_INT, "view_right", "VIEW_RIGHT" },
+ { Shader::MODE_SPATIAL, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_VECTOR_3D, "eye_offset", "EYE_OFFSET" },
{ 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_SCALAR_UINT, "camera_visible_layers", "CAMERA_VISIBLE_LAYERS" },
{ Shader::MODE_SPATIAL, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_VECTOR_3D, "node_position_view", "NODE_POSITION_VIEW" },
{ Shader::MODE_SPATIAL, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_VECTOR_4D, "custom0", "CUSTOM0" },
{ Shader::MODE_SPATIAL, VisualShader::TYPE_VERTEX, VisualShaderNode::PORT_TYPE_VECTOR_4D, "custom1", "CUSTOM1" },
@@ -2676,16 +2745,14 @@ const VisualShaderNodeInput::Port VisualShaderNodeInput::ports[] = {
{ Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_VECTOR_2D, "viewport_size", "VIEWPORT_SIZE" },
{ Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_BOOLEAN, "output_is_srgb", "OUTPUT_IS_SRGB" },
{ Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_BOOLEAN, "front_facing", "FRONT_FACING" },
- { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_SAMPLER, "screen_texture", "SCREEN_TEXTURE" },
- { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_SAMPLER, "normal_roughness_texture", "NORMAL_ROUGHNESS_TEXTURE" },
- { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_SAMPLER, "depth_texture", "DEPTH_TEXTURE" },
{ Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_SCALAR_INT, "view_index", "VIEW_INDEX" },
{ Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_SCALAR_INT, "view_mono_left", "VIEW_MONO_LEFT" },
{ Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_SCALAR_INT, "view_right", "VIEW_RIGHT" },
+ { Shader::MODE_SPATIAL, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_VECTOR_3D, "eye_offset", "EYE_OFFSET" },
{ 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_SCALAR_UINT, "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
@@ -2741,7 +2808,6 @@ const VisualShaderNodeInput::Port VisualShaderNodeInput::ports[] = {
{ Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_BOOLEAN, "at_light_pass", "AT_LIGHT_PASS" },
{ Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_SAMPLER, "texture", "TEXTURE" },
{ Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_SAMPLER, "normal_texture", "NORMAL_TEXTURE" },
- { Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_SAMPLER, "screen_texture", "SCREEN_TEXTURE" },
{ Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_VECTOR_4D, "specular_shininess", "SPECULAR_SHININESS" },
{ Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_SAMPLER, "specular_shininess_texture", "SPECULAR_SHININESS_TEXTURE" },
{ Shader::MODE_CANVAS_ITEM, VisualShader::TYPE_FRAGMENT, VisualShaderNode::PORT_TYPE_VECTOR_2D, "vertex", "VERTEX" },
@@ -2776,7 +2842,9 @@ const VisualShaderNodeInput::Port VisualShaderNodeInput::ports[] = {
{ Shader::MODE_PARTICLES, VisualShader::TYPE_START, VisualShaderNode::PORT_TYPE_TRANSFORM, "transform", "TRANSFORM" },
{ Shader::MODE_PARTICLES, VisualShader::TYPE_START, VisualShaderNode::PORT_TYPE_SCALAR, "delta", "DELTA" },
{ Shader::MODE_PARTICLES, VisualShader::TYPE_START, VisualShaderNode::PORT_TYPE_SCALAR, "lifetime", "LIFETIME" },
- { Shader::MODE_PARTICLES, VisualShader::TYPE_START, VisualShaderNode::PORT_TYPE_SCALAR_INT, "index", "INDEX" },
+ { Shader::MODE_PARTICLES, VisualShader::TYPE_START, VisualShaderNode::PORT_TYPE_SCALAR_UINT, "index", "INDEX" },
+ { Shader::MODE_PARTICLES, VisualShader::TYPE_START, VisualShaderNode::PORT_TYPE_SCALAR_UINT, "number", "NUMBER" },
+ { Shader::MODE_PARTICLES, VisualShader::TYPE_START, VisualShaderNode::PORT_TYPE_SCALAR_UINT, "random_seed", "RANDOM_SEED" },
{ Shader::MODE_PARTICLES, VisualShader::TYPE_START, VisualShaderNode::PORT_TYPE_TRANSFORM, "emission_transform", "EMISSION_TRANSFORM" },
{ Shader::MODE_PARTICLES, VisualShader::TYPE_START, VisualShaderNode::PORT_TYPE_SCALAR, "time", "TIME" },
@@ -2790,7 +2858,9 @@ const VisualShaderNodeInput::Port VisualShaderNodeInput::ports[] = {
{ Shader::MODE_PARTICLES, VisualShader::TYPE_START_CUSTOM, VisualShaderNode::PORT_TYPE_TRANSFORM, "transform", "TRANSFORM" },
{ Shader::MODE_PARTICLES, VisualShader::TYPE_START_CUSTOM, VisualShaderNode::PORT_TYPE_SCALAR, "delta", "DELTA" },
{ Shader::MODE_PARTICLES, VisualShader::TYPE_START_CUSTOM, VisualShaderNode::PORT_TYPE_SCALAR, "lifetime", "LIFETIME" },
- { Shader::MODE_PARTICLES, VisualShader::TYPE_START_CUSTOM, VisualShaderNode::PORT_TYPE_SCALAR_INT, "index", "INDEX" },
+ { Shader::MODE_PARTICLES, VisualShader::TYPE_START_CUSTOM, VisualShaderNode::PORT_TYPE_SCALAR_UINT, "index", "INDEX" },
+ { Shader::MODE_PARTICLES, VisualShader::TYPE_START_CUSTOM, VisualShaderNode::PORT_TYPE_SCALAR_UINT, "number", "NUMBER" },
+ { Shader::MODE_PARTICLES, VisualShader::TYPE_START_CUSTOM, VisualShaderNode::PORT_TYPE_SCALAR_UINT, "random_seed", "RANDOM_SEED" },
{ Shader::MODE_PARTICLES, VisualShader::TYPE_START_CUSTOM, VisualShaderNode::PORT_TYPE_TRANSFORM, "emission_transform", "EMISSION_TRANSFORM" },
{ Shader::MODE_PARTICLES, VisualShader::TYPE_START_CUSTOM, VisualShaderNode::PORT_TYPE_SCALAR, "time", "TIME" },
@@ -2804,7 +2874,9 @@ const VisualShaderNodeInput::Port VisualShaderNodeInput::ports[] = {
{ Shader::MODE_PARTICLES, VisualShader::TYPE_PROCESS, VisualShaderNode::PORT_TYPE_TRANSFORM, "transform", "TRANSFORM" },
{ Shader::MODE_PARTICLES, VisualShader::TYPE_PROCESS, VisualShaderNode::PORT_TYPE_SCALAR, "delta", "DELTA" },
{ Shader::MODE_PARTICLES, VisualShader::TYPE_PROCESS, VisualShaderNode::PORT_TYPE_SCALAR, "lifetime", "LIFETIME" },
- { Shader::MODE_PARTICLES, VisualShader::TYPE_PROCESS, VisualShaderNode::PORT_TYPE_SCALAR_INT, "index", "INDEX" },
+ { Shader::MODE_PARTICLES, VisualShader::TYPE_PROCESS, VisualShaderNode::PORT_TYPE_SCALAR_UINT, "index", "INDEX" },
+ { Shader::MODE_PARTICLES, VisualShader::TYPE_PROCESS, VisualShaderNode::PORT_TYPE_SCALAR_UINT, "number", "NUMBER" },
+ { Shader::MODE_PARTICLES, VisualShader::TYPE_PROCESS, VisualShaderNode::PORT_TYPE_SCALAR_UINT, "random_seed", "RANDOM_SEED" },
{ Shader::MODE_PARTICLES, VisualShader::TYPE_PROCESS, VisualShaderNode::PORT_TYPE_TRANSFORM, "emission_transform", "EMISSION_TRANSFORM" },
{ Shader::MODE_PARTICLES, VisualShader::TYPE_PROCESS, VisualShaderNode::PORT_TYPE_SCALAR, "time", "TIME" },
@@ -2818,7 +2890,9 @@ const VisualShaderNodeInput::Port VisualShaderNodeInput::ports[] = {
{ Shader::MODE_PARTICLES, VisualShader::TYPE_PROCESS_CUSTOM, VisualShaderNode::PORT_TYPE_TRANSFORM, "transform", "TRANSFORM" },
{ Shader::MODE_PARTICLES, VisualShader::TYPE_PROCESS_CUSTOM, VisualShaderNode::PORT_TYPE_SCALAR, "delta", "DELTA" },
{ Shader::MODE_PARTICLES, VisualShader::TYPE_PROCESS_CUSTOM, VisualShaderNode::PORT_TYPE_SCALAR, "lifetime", "LIFETIME" },
- { Shader::MODE_PARTICLES, VisualShader::TYPE_PROCESS_CUSTOM, VisualShaderNode::PORT_TYPE_SCALAR_INT, "index", "INDEX" },
+ { Shader::MODE_PARTICLES, VisualShader::TYPE_PROCESS_CUSTOM, VisualShaderNode::PORT_TYPE_SCALAR_UINT, "index", "INDEX" },
+ { Shader::MODE_PARTICLES, VisualShader::TYPE_PROCESS_CUSTOM, VisualShaderNode::PORT_TYPE_SCALAR_UINT, "number", "NUMBER" },
+ { Shader::MODE_PARTICLES, VisualShader::TYPE_PROCESS_CUSTOM, VisualShaderNode::PORT_TYPE_SCALAR_UINT, "random_seed", "RANDOM_SEED" },
{ Shader::MODE_PARTICLES, VisualShader::TYPE_PROCESS_CUSTOM, VisualShaderNode::PORT_TYPE_TRANSFORM, "emission_transform", "EMISSION_TRANSFORM" },
{ Shader::MODE_PARTICLES, VisualShader::TYPE_PROCESS_CUSTOM, VisualShaderNode::PORT_TYPE_SCALAR, "time", "TIME" },
@@ -2834,7 +2908,9 @@ const VisualShaderNodeInput::Port VisualShaderNodeInput::ports[] = {
{ Shader::MODE_PARTICLES, VisualShader::TYPE_COLLIDE, VisualShaderNode::PORT_TYPE_TRANSFORM, "transform", "TRANSFORM" },
{ Shader::MODE_PARTICLES, VisualShader::TYPE_COLLIDE, VisualShaderNode::PORT_TYPE_SCALAR, "delta", "DELTA" },
{ Shader::MODE_PARTICLES, VisualShader::TYPE_COLLIDE, VisualShaderNode::PORT_TYPE_SCALAR, "lifetime", "LIFETIME" },
- { Shader::MODE_PARTICLES, VisualShader::TYPE_COLLIDE, VisualShaderNode::PORT_TYPE_SCALAR_INT, "index", "INDEX" },
+ { Shader::MODE_PARTICLES, VisualShader::TYPE_COLLIDE, VisualShaderNode::PORT_TYPE_SCALAR_UINT, "index", "INDEX" },
+ { Shader::MODE_PARTICLES, VisualShader::TYPE_COLLIDE, VisualShaderNode::PORT_TYPE_SCALAR_UINT, "number", "NUMBER" },
+ { Shader::MODE_PARTICLES, VisualShader::TYPE_COLLIDE, VisualShaderNode::PORT_TYPE_SCALAR_UINT, "random_seed", "RANDOM_SEED" },
{ Shader::MODE_PARTICLES, VisualShader::TYPE_COLLIDE, VisualShaderNode::PORT_TYPE_TRANSFORM, "emission_transform", "EMISSION_TRANSFORM" },
{ Shader::MODE_PARTICLES, VisualShader::TYPE_COLLIDE, VisualShaderNode::PORT_TYPE_SCALAR, "time", "TIME" },
@@ -2873,7 +2949,7 @@ const VisualShaderNodeInput::Port VisualShaderNodeInput::ports[] = {
{ Shader::MODE_FOG, VisualShader::TYPE_FOG, VisualShaderNode::PORT_TYPE_VECTOR_3D, "world_position", "WORLD_POSITION" },
{ Shader::MODE_FOG, VisualShader::TYPE_FOG, VisualShaderNode::PORT_TYPE_VECTOR_3D, "object_position", "OBJECT_POSITION" },
{ Shader::MODE_FOG, VisualShader::TYPE_FOG, VisualShaderNode::PORT_TYPE_VECTOR_3D, "uvw", "UVW" },
- { Shader::MODE_FOG, VisualShader::TYPE_FOG, VisualShaderNode::PORT_TYPE_VECTOR_3D, "extents", "EXTENTS" },
+ { Shader::MODE_FOG, VisualShader::TYPE_FOG, VisualShaderNode::PORT_TYPE_VECTOR_3D, "size", "SIZE" },
{ Shader::MODE_FOG, VisualShader::TYPE_FOG, VisualShaderNode::PORT_TYPE_SCALAR, "sdf", "SDF" },
{ Shader::MODE_FOG, VisualShader::TYPE_FOG, VisualShaderNode::PORT_TYPE_SCALAR, "time", "TIME" },
@@ -3252,6 +3328,8 @@ int VisualShaderNodeParameterRef::get_output_port_count() const {
return 1;
case PARAMETER_TYPE_INT:
return 1;
+ case PARAMETER_TYPE_UINT:
+ return 1;
case PARAMETER_TYPE_BOOLEAN:
return 1;
case PARAMETER_TYPE_VECTOR2:
@@ -3278,6 +3356,8 @@ VisualShaderNodeParameterRef::PortType VisualShaderNodeParameterRef::get_output_
return PortType::PORT_TYPE_SCALAR;
case PARAMETER_TYPE_INT:
return PortType::PORT_TYPE_SCALAR_INT;
+ case PARAMETER_TYPE_UINT:
+ return PortType::PORT_TYPE_SCALAR_UINT;
case PARAMETER_TYPE_BOOLEAN:
return PortType::PORT_TYPE_BOOLEAN;
case PARAMETER_TYPE_VECTOR2:
@@ -3309,6 +3389,8 @@ String VisualShaderNodeParameterRef::get_output_port_name(int p_port) const {
return "";
case PARAMETER_TYPE_INT:
return "";
+ case PARAMETER_TYPE_UINT:
+ return "";
case PARAMETER_TYPE_BOOLEAN:
return "";
case PARAMETER_TYPE_VECTOR2:
@@ -3403,6 +3485,8 @@ VisualShaderNodeParameterRef::PortType VisualShaderNodeParameterRef::get_port_ty
return PORT_TYPE_SCALAR;
case PARAMETER_TYPE_INT:
return PORT_TYPE_SCALAR_INT;
+ case PARAMETER_TYPE_UINT:
+ return PORT_TYPE_SCALAR_UINT;
case UNIFORM_TYPE_SAMPLER:
return PORT_TYPE_SAMPLER;
case PARAMETER_TYPE_VECTOR2:
@@ -4659,6 +4743,8 @@ String VisualShaderNodeVarying::get_type_str() const {
return "float";
case VisualShader::VARYING_TYPE_INT:
return "int";
+ case VisualShader::VARYING_TYPE_UINT:
+ return "uint";
case VisualShader::VARYING_TYPE_VECTOR_2D:
return "vec2";
case VisualShader::VARYING_TYPE_VECTOR_3D:
@@ -4679,6 +4765,8 @@ VisualShaderNodeVarying::PortType VisualShaderNodeVarying::get_port_type(VisualS
switch (p_type) {
case VisualShader::VARYING_TYPE_INT:
return PORT_TYPE_SCALAR_INT;
+ case VisualShader::VARYING_TYPE_UINT:
+ return PORT_TYPE_SCALAR_UINT;
case VisualShader::VARYING_TYPE_VECTOR_2D:
return PORT_TYPE_VECTOR_2D;
case VisualShader::VARYING_TYPE_VECTOR_3D:
@@ -4811,6 +4899,9 @@ String VisualShaderNodeVaryingGetter::generate_code(Shader::Mode p_mode, VisualS
case VisualShader::VARYING_TYPE_INT:
from = "0";
break;
+ case VisualShader::VARYING_TYPE_UINT:
+ from = "0u";
+ break;
case VisualShader::VARYING_TYPE_VECTOR_2D:
from = "vec2(0.0)";
break;
diff --git a/scene/resources/visual_shader.h b/scene/resources/visual_shader.h
index b8ee693a84..2838a49209 100644
--- a/scene/resources/visual_shader.h
+++ b/scene/resources/visual_shader.h
@@ -80,6 +80,7 @@ public:
enum VaryingType {
VARYING_TYPE_FLOAT,
VARYING_TYPE_INT,
+ VARYING_TYPE_UINT,
VARYING_TYPE_VECTOR_2D,
VARYING_TYPE_VECTOR_3D,
VARYING_TYPE_VECTOR_4D,
@@ -121,7 +122,8 @@ private:
struct Node {
Ref<VisualShaderNode> node;
Vector2 position;
- List<int> prev_connected_nodes;
+ LocalVector<int> prev_connected_nodes;
+ LocalVector<int> next_connected_nodes;
};
struct Graph {
@@ -198,6 +200,16 @@ public: // internal methods
Vector2 get_node_position(Type p_type, int p_id) const;
Ref<VisualShaderNode> get_node(Type p_type, int p_id) const;
+ _FORCE_INLINE_ Ref<VisualShaderNode> get_node_unchecked(Type p_type, int p_id) const {
+ return graph[p_type].nodes[p_id].node;
+ }
+ _FORCE_INLINE_ void get_next_connected_nodes(Type p_type, int p_id, LocalVector<int> &r_list) const {
+ r_list = graph[p_type].nodes[p_id].next_connected_nodes;
+ }
+ _FORCE_INLINE_ void get_prev_connected_nodes(Type p_type, int p_id, LocalVector<int> &r_list) const {
+ r_list = graph[p_type].nodes[p_id].prev_connected_nodes;
+ }
+
Vector<int> get_node_list(Type p_type) const;
int get_valid_node_id(Type p_type) const;
@@ -260,6 +272,7 @@ public:
enum PortType {
PORT_TYPE_SCALAR,
PORT_TYPE_SCALAR_INT,
+ PORT_TYPE_SCALAR_UINT,
PORT_TYPE_VECTOR_2D,
PORT_TYPE_VECTOR_3D,
PORT_TYPE_VECTOR_4D,
@@ -367,12 +380,12 @@ protected:
GDVIRTUAL0RC(String, _get_name)
GDVIRTUAL0RC(String, _get_description)
GDVIRTUAL0RC(String, _get_category)
- GDVIRTUAL0RC(int, _get_return_icon_type)
+ GDVIRTUAL0RC(PortType, _get_return_icon_type)
GDVIRTUAL0RC(int, _get_input_port_count)
- GDVIRTUAL1RC(int, _get_input_port_type, int)
+ GDVIRTUAL1RC(PortType, _get_input_port_type, int)
GDVIRTUAL1RC(String, _get_input_port_name, int)
GDVIRTUAL0RC(int, _get_output_port_count)
- GDVIRTUAL1RC(int, _get_output_port_type, int)
+ GDVIRTUAL1RC(PortType, _get_output_port_type, int)
GDVIRTUAL1RC(String, _get_output_port_name, int)
GDVIRTUAL4RC(String, _get_code, TypedArray<String>, TypedArray<String>, Shader::Mode, VisualShader::Type)
GDVIRTUAL2RC(String, _get_func_code, Shader::Mode, VisualShader::Type)
@@ -550,6 +563,7 @@ public:
enum ParameterType {
PARAMETER_TYPE_FLOAT,
PARAMETER_TYPE_INT,
+ PARAMETER_TYPE_UINT,
PARAMETER_TYPE_BOOLEAN,
PARAMETER_TYPE_VECTOR2,
PARAMETER_TYPE_VECTOR3,
diff --git a/scene/resources/visual_shader_nodes.cpp b/scene/resources/visual_shader_nodes.cpp
index df8e836a51..7550f598f8 100644
--- a/scene/resources/visual_shader_nodes.cpp
+++ b/scene/resources/visual_shader_nodes.cpp
@@ -223,6 +223,68 @@ void VisualShaderNodeIntConstant::_bind_methods() {
VisualShaderNodeIntConstant::VisualShaderNodeIntConstant() {
}
+////////////// Scalar(UInt)
+
+String VisualShaderNodeUIntConstant::get_caption() const {
+ return "UIntConstant";
+}
+
+int VisualShaderNodeUIntConstant::get_input_port_count() const {
+ return 0;
+}
+
+VisualShaderNodeUIntConstant::PortType VisualShaderNodeUIntConstant::get_input_port_type(int p_port) const {
+ return PORT_TYPE_SCALAR_UINT;
+}
+
+String VisualShaderNodeUIntConstant::get_input_port_name(int p_port) const {
+ return String();
+}
+
+int VisualShaderNodeUIntConstant::get_output_port_count() const {
+ return 1;
+}
+
+VisualShaderNodeUIntConstant::PortType VisualShaderNodeUIntConstant::get_output_port_type(int p_port) const {
+ return PORT_TYPE_SCALAR_UINT;
+}
+
+String VisualShaderNodeUIntConstant::get_output_port_name(int p_port) const {
+ return ""; // No output port means the editor will be used as port.
+}
+
+String VisualShaderNodeUIntConstant::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 {
+ return " " + p_output_vars[0] + " = " + itos(constant) + "u;\n";
+}
+
+void VisualShaderNodeUIntConstant::set_constant(int p_constant) {
+ if (constant == p_constant) {
+ return;
+ }
+ constant = p_constant;
+ emit_changed();
+}
+
+int VisualShaderNodeUIntConstant::get_constant() const {
+ return constant;
+}
+
+Vector<StringName> VisualShaderNodeUIntConstant::get_editable_properties() const {
+ Vector<StringName> props;
+ props.push_back("constant");
+ return props;
+}
+
+void VisualShaderNodeUIntConstant::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("set_constant", "constant"), &VisualShaderNodeUIntConstant::set_constant);
+ ClassDB::bind_method(D_METHOD("get_constant"), &VisualShaderNodeUIntConstant::get_constant);
+
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "constant"), "set_constant", "get_constant");
+}
+
+VisualShaderNodeUIntConstant::VisualShaderNodeUIntConstant() {
+}
+
////////////// Boolean
String VisualShaderNodeBooleanConstant::get_caption() const {
@@ -694,141 +756,157 @@ Vector<VisualShader::DefaultTextureParam> VisualShaderNodeTexture::get_default_t
}
String VisualShaderNodeTexture::generate_global(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const {
- if (source == SOURCE_TEXTURE) {
- String u = "uniform sampler2D " + make_unique_id(p_type, p_id, "tex");
- switch (texture_type) {
- case TYPE_DATA:
- break;
- case TYPE_COLOR:
- u += " : source_color";
- break;
- case TYPE_NORMAL_MAP:
- u += " : hint_normal";
- break;
- default:
- break;
- }
- return u + ";\n";
+ String code;
+
+ switch (source) {
+ case SOURCE_TEXTURE: {
+ code += "uniform sampler2D " + make_unique_id(p_type, p_id, "tex");
+ switch (texture_type) {
+ case TYPE_DATA: {
+ } break;
+ case TYPE_COLOR: {
+ code += " : source_color";
+ } break;
+ case TYPE_NORMAL_MAP: {
+ code += " : hint_normal";
+ } break;
+ default: {
+ } break;
+ }
+ code += ";\n";
+ } break;
+ case SOURCE_SCREEN: {
+ if ((p_mode == Shader::MODE_SPATIAL || p_mode == Shader::MODE_CANVAS_ITEM) && p_type == VisualShader::TYPE_FRAGMENT) {
+ code += "uniform sampler2D " + make_unique_id(p_type, p_id, "screen_tex") + " : hint_screen_texture;\n";
+ }
+ } break;
+ case SOURCE_DEPTH:
+ case SOURCE_3D_NORMAL:
+ case SOURCE_ROUGHNESS: {
+ if (p_mode == Shader::MODE_SPATIAL && p_type == VisualShader::TYPE_FRAGMENT) {
+ String sampler_name = "";
+ String hint = " : ";
+ if (source == SOURCE_DEPTH) {
+ sampler_name = "depth_tex";
+ hint += "hint_depth_texture;\n";
+ } else {
+ sampler_name = source == SOURCE_ROUGHNESS ? "roughness_tex" : "normal_roughness_tex";
+ hint += "hint_normal_roughness_texture;\n";
+ }
+ code += "uniform sampler2D " + make_unique_id(p_type, p_id, sampler_name) + hint;
+ }
+ } break;
+ default: {
+ } break;
}
- return String();
+ return code;
}
String VisualShaderNodeTexture::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 default_uv;
if (p_mode == Shader::MODE_CANVAS_ITEM || p_mode == Shader::MODE_SPATIAL) {
- default_uv = "UV";
+ if (source == SOURCE_SCREEN) {
+ default_uv = "SCREEN_UV";
+ } else {
+ default_uv = "UV";
+ }
} else {
default_uv = "vec2(0.0)";
}
String code;
- if (source == SOURCE_TEXTURE) {
- String id = make_unique_id(p_type, p_id, "tex");
- if (p_input_vars[0].is_empty()) { // Use UV by default.
+ String uv = p_input_vars[0].is_empty() ? default_uv : p_input_vars[0];
+
+ switch (source) {
+ case SOURCE_PORT:
+ case SOURCE_TEXTURE: {
+ String id;
+ if (source == SOURCE_PORT) {
+ id = p_input_vars[2];
+ if (id.is_empty()) {
+ break;
+ }
+ } else { // SOURCE_TEXTURE
+ id = make_unique_id(p_type, p_id, "tex");
+ }
if (p_input_vars[1].is_empty()) {
- code += " " + p_output_vars[0] + " = texture(" + id + ", " + default_uv + ");\n";
+ code += " " + p_output_vars[0] + " = texture(" + id + ", " + uv + ");\n";
} else {
- code += " " + p_output_vars[0] + " = textureLod(" + id + ", " + default_uv + ", " + p_input_vars[1] + ");\n";
+ code += " " + p_output_vars[0] + " = textureLod(" + id + ", " + uv + ", " + p_input_vars[1] + ");\n";
}
- } else if (p_input_vars[1].is_empty()) {
- //no lod
- code += " " + p_output_vars[0] + " = texture(" + id + ", " + p_input_vars[0] + ");\n";
- } else {
- code += " " + p_output_vars[0] + " = textureLod(" + id + ", " + p_input_vars[0] + ", " + p_input_vars[1] + ");\n";
- }
- return code;
- }
-
- if (source == SOURCE_PORT) {
- String id = p_input_vars[2];
- if (id.is_empty()) {
- code += " " + p_output_vars[0] + " = vec4(0.0);\n";
- } else {
- if (p_input_vars[0].is_empty()) { // Use UV by default.
+ return code;
+ } break;
+ case SOURCE_SCREEN: {
+ if ((p_mode == Shader::MODE_SPATIAL || p_mode == Shader::MODE_CANVAS_ITEM) && p_type == VisualShader::TYPE_FRAGMENT) {
+ String id = make_unique_id(p_type, p_id, "screen_tex");
if (p_input_vars[1].is_empty()) {
- code += " " + p_output_vars[0] + " = texture(" + id + ", " + default_uv + ");\n";
+ code += " " + p_output_vars[0] + " = texture(" + id + ", " + uv + ");\n";
} else {
- code += " " + p_output_vars[0] + " = textureLod(" + id + ", " + default_uv + ", " + p_input_vars[1] + ");\n";
+ code += " " + p_output_vars[0] + " = textureLod(" + id + ", " + uv + ", " + p_input_vars[1] + ");\n";
}
- } else if (p_input_vars[1].is_empty()) {
- //no lod
- code += " " + p_output_vars[0] + " = texture(" + id + ", " + p_input_vars[0] + ");\n";
- } else {
- code += " " + p_output_vars[0] + " = textureLod(" + id + ", " + p_input_vars[0] + ", " + p_input_vars[1] + ");\n";
- }
- }
- return code;
- }
-
- if (source == SOURCE_SCREEN && (p_mode == Shader::MODE_SPATIAL || p_mode == Shader::MODE_CANVAS_ITEM) && p_type == VisualShader::TYPE_FRAGMENT) {
- if (p_input_vars[0].is_empty() || p_for_preview) { // Use UV by default.
- if (p_input_vars[1].is_empty()) {
- code += " " + p_output_vars[0] + " = textureLod(SCREEN_TEXTURE, " + default_uv + ", 0.0);\n";
- } else {
- code += " " + p_output_vars[0] + " = textureLod(SCREEN_TEXTURE, " + default_uv + ", " + p_input_vars[1] + ");\n";
+ return code;
}
- } else if (p_input_vars[1].is_empty()) {
- //no lod
- code += " " + p_output_vars[0] + " = textureLod(SCREEN_TEXTURE, " + p_input_vars[0] + ", 0.0);\n";
- } else {
- code += " " + p_output_vars[0] + " = textureLod(SCREEN_TEXTURE, " + p_input_vars[0] + ", " + p_input_vars[1] + ");\n";
- }
- return code;
- }
+ } break;
+ case SOURCE_2D_NORMAL:
+ case SOURCE_2D_TEXTURE: {
+ if (p_mode == Shader::MODE_CANVAS_ITEM && p_type == VisualShader::TYPE_FRAGMENT) {
+ String id = source == SOURCE_2D_TEXTURE ? "TEXTURE" : "NORMAL_TEXTURE";
- if (source == SOURCE_2D_TEXTURE && p_mode == Shader::MODE_CANVAS_ITEM && p_type == VisualShader::TYPE_FRAGMENT) {
- if (p_input_vars[0].is_empty()) { // Use UV by default.
- if (p_input_vars[1].is_empty()) {
- code += " " + p_output_vars[0] + " = texture(TEXTURE, " + default_uv + ");\n";
- } else {
- code += " " + p_output_vars[0] + " = textureLod(TEXTURE, " + default_uv + ", " + p_input_vars[1] + ");\n";
+ if (p_input_vars[1].is_empty()) {
+ code += " " + p_output_vars[0] + " = texture(" + id + ", " + uv + ");\n";
+ } else {
+ code += " " + p_output_vars[0] + " = textureLod(" + id + ", " + uv + ", " + p_input_vars[1] + ");\n";
+ }
+ return code;
}
- } else if (p_input_vars[1].is_empty()) {
- //no lod
- code += " " + p_output_vars[0] + " = texture(TEXTURE, " + p_input_vars[0] + ");\n";
- } else {
- code += " " + p_output_vars[0] + " = textureLod(TEXTURE, " + p_input_vars[0] + ", " + p_input_vars[1] + ");\n";
- }
- return code;
- }
+ } break;
+ case SOURCE_3D_NORMAL:
+ case SOURCE_ROUGHNESS:
+ case SOURCE_DEPTH: {
+ if (!p_for_preview && p_mode == Shader::MODE_SPATIAL && p_type == VisualShader::TYPE_FRAGMENT) {
+ String var_name = "";
+ String sampler_name = "";
+
+ switch (source) {
+ case SOURCE_DEPTH: {
+ var_name = "_depth";
+ sampler_name = "depth_tex";
+ } break;
+ case SOURCE_ROUGHNESS: {
+ var_name = "_roughness";
+ sampler_name = "roughness_tex";
+ } break;
+ case SOURCE_3D_NORMAL: {
+ var_name = "_normal";
+ sampler_name = "normal_roughness_tex";
+ } break;
+ default: {
+ } break;
+ }
- if (source == SOURCE_2D_NORMAL && p_mode == Shader::MODE_CANVAS_ITEM && p_type == VisualShader::TYPE_FRAGMENT) {
- if (p_input_vars[0].is_empty()) { // Use UV by default.
- if (p_input_vars[1].is_empty()) {
- code += " " + p_output_vars[0] + " = texture(NORMAL_TEXTURE, " + default_uv + ");\n";
- } else {
- code += " " + p_output_vars[0] + " = textureLod(NORMAL_TEXTURE, " + default_uv + ", " + p_input_vars[1] + ");\n";
- }
- } else if (p_input_vars[1].is_empty()) {
- //no lod
- code += " " + p_output_vars[0] + " = texture(NORMAL_TEXTURE, " + p_input_vars[0] + ".xy);\n";
- } else {
- code += " " + p_output_vars[0] + " = textureLod(NORMAL_TEXTURE, " + p_input_vars[0] + ".xy, " + p_input_vars[1] + ");\n";
- }
- return code;
- }
+ String id = make_unique_id(p_type, p_id, sampler_name);
+ String type = source == SOURCE_3D_NORMAL ? "vec3" : "float";
+ String components = source == SOURCE_3D_NORMAL ? "rgb" : "r";
- if (source == SOURCE_DEPTH) {
- if (!p_for_preview && p_mode == Shader::MODE_SPATIAL && p_type == VisualShader::TYPE_FRAGMENT) {
- code += " {\n";
- if (p_input_vars[0].is_empty()) { // Use UV by default.
+ code += " {\n";
if (p_input_vars[1].is_empty()) {
- code += " float _depth = texture(DEPTH_TEXTURE, " + default_uv + ").r;\n";
+ code += " " + type + " " + var_name + " = texture(" + id + ", " + uv + ")." + components + ";\n";
} else {
- code += " float _depth = textureLod(DEPTH_TEXTURE, " + default_uv + ", " + p_input_vars[1] + ").r;\n";
+ code += " " + type + " " + var_name + " = textureLod(" + id + ", " + uv + ", " + p_input_vars[1] + ")." + components + ";\n";
}
- } else if (p_input_vars[1].is_empty()) {
- //no lod
- code += " float _depth = texture(DEPTH_TEXTURE, " + p_input_vars[0] + ".xy).r;\n";
- } else {
- code += " float _depth = textureLod(DEPTH_TEXTURE, " + p_input_vars[0] + ".xy, " + p_input_vars[1] + ").r;\n";
- }
+ if (source == SOURCE_3D_NORMAL) {
+ code += " " + p_output_vars[0] + " = vec4(" + var_name + ", 1.0);\n";
+ } else {
+ code += " " + p_output_vars[0] + " = vec4(" + var_name + ", " + var_name + ", " + var_name + ", 1.0);\n";
+ }
+ code += " }\n";
- code += " " + p_output_vars[0] + " = vec4(_depth, _depth, _depth, 1.0);\n";
- code += " }\n";
- return code;
- }
+ return code;
+ }
+ } break;
+ default: {
+ } break;
}
code += " " + p_output_vars[0] + " = vec4(0.0);\n";
@@ -859,12 +937,17 @@ void VisualShaderNodeTexture::set_source(Source p_source) {
case SOURCE_PORT:
simple_decl = false;
break;
+ case SOURCE_3D_NORMAL:
+ simple_decl = false;
+ break;
+ case SOURCE_ROUGHNESS:
+ simple_decl = false;
+ break;
default:
break;
}
source = p_source;
emit_changed();
- emit_signal(SNAME("editor_refresh_request"));
}
VisualShaderNodeTexture::Source VisualShaderNodeTexture::get_source() const {
@@ -908,31 +991,34 @@ String VisualShaderNodeTexture::get_warning(Shader::Mode p_mode, VisualShader::T
return RTR("The sampler port is connected but not used. Consider changing the source to 'SamplerPort'.");
}
- if (source == SOURCE_TEXTURE) {
- return String(); // all good
- }
-
- if (source == SOURCE_PORT) {
- return String(); // all good
- }
-
- if (source == SOURCE_SCREEN && (p_mode == Shader::MODE_SPATIAL || p_mode == Shader::MODE_CANVAS_ITEM) && p_type == VisualShader::TYPE_FRAGMENT) {
- return String(); // all good
- }
-
- if (source == SOURCE_2D_TEXTURE && p_mode == Shader::MODE_CANVAS_ITEM && p_type == VisualShader::TYPE_FRAGMENT) {
- return String(); // all good
- }
-
- if (source == SOURCE_2D_NORMAL && p_mode == Shader::MODE_CANVAS_ITEM) {
- return String(); // all good
- }
-
- if (source == SOURCE_DEPTH && p_mode == Shader::MODE_SPATIAL && p_type == VisualShader::TYPE_FRAGMENT) {
- if (get_output_port_for_preview() == 0) { // DEPTH_TEXTURE is not supported in preview(canvas_item) shader
- return RTR("Invalid source for preview.");
- }
- return String(); // all good
+ switch (source) {
+ case SOURCE_TEXTURE:
+ case SOURCE_PORT: {
+ return String(); // All good.
+ } break;
+ case SOURCE_SCREEN: {
+ if ((p_mode == Shader::MODE_SPATIAL || p_mode == Shader::MODE_CANVAS_ITEM) && p_type == VisualShader::TYPE_FRAGMENT) {
+ return String(); // All good.
+ }
+ } break;
+ case SOURCE_2D_NORMAL:
+ case SOURCE_2D_TEXTURE: {
+ if (p_mode == Shader::MODE_CANVAS_ITEM && p_type == VisualShader::TYPE_FRAGMENT) {
+ return String(); // All good.
+ }
+ } break;
+ case SOURCE_3D_NORMAL:
+ case SOURCE_ROUGHNESS:
+ case SOURCE_DEPTH: {
+ if (p_mode == Shader::MODE_SPATIAL && p_type == VisualShader::TYPE_FRAGMENT) {
+ if (get_output_port_for_preview() == 0) { // Not supported in preview(canvas_item) shader.
+ return RTR("Invalid source for preview.");
+ }
+ return String(); // All good.
+ }
+ } break;
+ default: {
+ } break;
}
return RTR("Invalid source for shader.");
@@ -948,7 +1034,7 @@ void VisualShaderNodeTexture::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_texture_type", "value"), &VisualShaderNodeTexture::set_texture_type);
ClassDB::bind_method(D_METHOD("get_texture_type"), &VisualShaderNodeTexture::get_texture_type);
- ADD_PROPERTY(PropertyInfo(Variant::INT, "source", PROPERTY_HINT_ENUM, "Texture,Screen,Texture2D,NormalMap2D,Depth,SamplerPort"), "set_source", "get_source");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "source", PROPERTY_HINT_ENUM, "Texture,Screen,Texture2D,NormalMap2D,Depth,SamplerPort,Normal3D,Roughness"), "set_source", "get_source");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture2D"), "set_texture", "get_texture");
ADD_PROPERTY(PropertyInfo(Variant::INT, "texture_type", PROPERTY_HINT_ENUM, "Data,Color,Normal Map"), "set_texture_type", "get_texture_type");
@@ -958,6 +1044,8 @@ void VisualShaderNodeTexture::_bind_methods() {
BIND_ENUM_CONSTANT(SOURCE_2D_NORMAL);
BIND_ENUM_CONSTANT(SOURCE_DEPTH);
BIND_ENUM_CONSTANT(SOURCE_PORT);
+ BIND_ENUM_CONSTANT(SOURCE_3D_NORMAL);
+ BIND_ENUM_CONSTANT(SOURCE_ROUGHNESS);
BIND_ENUM_CONSTANT(SOURCE_MAX);
BIND_ENUM_CONSTANT(TYPE_DATA);
@@ -1198,6 +1286,17 @@ bool VisualShaderNodeSample3D::is_input_port_default(int p_port, Shader::Mode p_
}
String VisualShaderNodeSample3D::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;
+ String id;
+ if (source == SOURCE_TEXTURE) {
+ id = make_unique_id(p_type, p_id, "tex3d");
+ } else { // SOURCE_PORT
+ id = p_input_vars[2];
+ if (id.is_empty()) {
+ code += " " + p_output_vars[0] + " = vec4(0.0);\n";
+ return code;
+ }
+ }
String default_uv;
if (p_mode == Shader::MODE_CANVAS_ITEM || p_mode == Shader::MODE_SPATIAL) {
default_uv = "vec3(UV, 0.0)";
@@ -1205,33 +1304,12 @@ String VisualShaderNodeSample3D::generate_code(Shader::Mode p_mode, VisualShader
default_uv = "vec3(0.0)";
}
- String code;
- if (source == SOURCE_TEXTURE || source == SOURCE_PORT) {
- String id;
- if (source == SOURCE_TEXTURE) {
- id = make_unique_id(p_type, p_id, "tex3d");
- } else {
- id = p_input_vars[2];
- }
- if (!id.is_empty()) {
- if (p_input_vars[0].is_empty()) { // Use UV by default.
- if (p_input_vars[1].is_empty()) {
- code += " " + p_output_vars[0] + " = texture(" + id + ", " + default_uv + ");\n";
- } else {
- code += " " + p_output_vars[0] + " = textureLod(" + id + ", " + default_uv + ", " + p_input_vars[1] + ");\n";
- }
- } else if (p_input_vars[1].is_empty()) {
- //no lod
- code += " " + p_output_vars[0] + " = texture(" + id + ", " + p_input_vars[0] + ");\n";
- } else {
- code += " " + p_output_vars[0] + " = textureLod(" + id + ", " + p_input_vars[0] + ", " + p_input_vars[1] + ");\n";
- }
- } else {
- code += " " + p_output_vars[0] + " = vec4(0.0);\n";
- }
- return code;
+ String uv = p_input_vars[0].is_empty() ? default_uv : p_input_vars[0];
+ if (p_input_vars[1].is_empty()) {
+ code += " " + p_output_vars[0] + " = texture(" + id + ", " + uv + ");\n";
+ } else {
+ code += " " + p_output_vars[0] + " = textureLod(" + id + ", " + uv + ", " + p_input_vars[1] + ");\n";
}
- code += " " + p_output_vars[0] + " = vec4(0.0);\n";
return code;
}
@@ -1242,7 +1320,6 @@ void VisualShaderNodeSample3D::set_source(Source p_source) {
}
source = p_source;
emit_changed();
- emit_signal(SNAME("editor_refresh_request"));
}
VisualShaderNodeSample3D::Source VisualShaderNodeSample3D::get_source() const {
@@ -1264,14 +1341,7 @@ String VisualShaderNodeSample3D::get_warning(Shader::Mode p_mode, VisualShader::
if (is_input_port_connected(2) && source != SOURCE_PORT) {
return RTR("The sampler port is connected but not used. Consider changing the source to 'SamplerPort'.");
}
-
- if (source == SOURCE_TEXTURE) {
- return String(); // all good
- }
- if (source == SOURCE_PORT) {
- return String(); // all good
- }
- return RTR("Invalid source for shader.");
+ return String();
}
VisualShaderNodeSample3D::VisualShaderNodeSample3D() {
@@ -1477,42 +1547,33 @@ String VisualShaderNodeCubemap::generate_global(Shader::Mode p_mode, VisualShade
}
String VisualShaderNodeCubemap::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 default_uv;
- if (p_mode == Shader::MODE_CANVAS_ITEM || p_mode == Shader::MODE_SPATIAL) {
- default_uv = "vec3(UV, 0.0)";
- } else {
- default_uv = "vec3(0.0)";
- }
-
String code;
String id;
+
if (source == SOURCE_TEXTURE) {
id = make_unique_id(p_type, p_id, "cube");
- } else if (source == SOURCE_PORT) {
+ } else { // SOURCE_PORT
id = p_input_vars[2];
- } else {
- return code;
+ if (id.is_empty()) {
+ code += " " + p_output_vars[0] + " = vec4(0.0);\n";
+ return code;
+ }
}
- if (id.is_empty()) {
- code += " " + p_output_vars[0] + " = vec4(0.0);\n";
- return code;
+ String default_uv;
+ if (p_mode == Shader::MODE_CANVAS_ITEM || p_mode == Shader::MODE_SPATIAL) {
+ default_uv = "vec3(UV, 0.0)";
+ } else {
+ default_uv = "vec3(0.0)";
}
- if (p_input_vars[0].is_empty()) { // Use UV by default.
-
- if (p_input_vars[1].is_empty()) {
- code += " " + p_output_vars[0] + " = texture(" + id + ", " + default_uv + ");\n";
- } else {
- code += " " + p_output_vars[0] + " = textureLod(" + id + ", " + default_uv + ", " + p_input_vars[1] + ");\n";
- }
-
- } else if (p_input_vars[1].is_empty()) {
- //no lod
- code += " " + p_output_vars[0] + " = texture(" + id + ", " + p_input_vars[0] + ");\n";
+ String uv = p_input_vars[0].is_empty() ? default_uv : p_input_vars[0];
+ if (p_input_vars[1].is_empty()) {
+ code += " " + p_output_vars[0] + " = texture(" + id + ", " + uv + ");\n";
} else {
- code += " " + p_output_vars[0] + " = textureLod(" + id + ", " + p_input_vars[0] + ", " + p_input_vars[1] + ");\n";
+ code += " " + p_output_vars[0] + " = textureLod(" + id + ", " + uv + ", " + p_input_vars[1] + ");\n";
}
+
return code;
}
@@ -1532,7 +1593,6 @@ void VisualShaderNodeCubemap::set_source(Source p_source) {
}
source = p_source;
emit_changed();
- emit_signal(SNAME("editor_refresh_request"));
}
VisualShaderNodeCubemap::Source VisualShaderNodeCubemap::get_source() const {
@@ -1640,11 +1700,15 @@ bool VisualShaderNodeLinearSceneDepth::has_output_port_preview(int p_port) const
return false;
}
+String VisualShaderNodeLinearSceneDepth::generate_global(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const {
+ return "uniform sampler2D " + make_unique_id(p_type, p_id, "depth_tex") + " : hint_depth_texture;\n";
+}
+
String VisualShaderNodeLinearSceneDepth::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";
- code += " float __log_depth = textureLod(DEPTH_TEXTURE, SCREEN_UV, 0.0).x;\n";
+ code += " float __log_depth = textureLod(" + make_unique_id(p_type, p_id, "depth_tex") + ", SCREEN_UV, 0.0).x;\n";
code += " vec3 __depth_ndc = vec3(SCREEN_UV * 2.0 - 1.0, __log_depth);\n";
code += " vec4 __depth_view = INV_PROJECTION_MATRIX * vec4(__depth_ndc, 1.0);\n";
code += " __depth_view.xyz /= __depth_view.w;\n";
@@ -1797,7 +1861,7 @@ VisualShaderNodeIntOp::PortType VisualShaderNodeIntOp::get_output_port_type(int
}
String VisualShaderNodeIntOp::get_output_port_name(int p_port) const {
- return "op"; //no output port means the editor will be used as port
+ return "op"; // No output port means the editor will be used as port.
}
String VisualShaderNodeIntOp::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 {
@@ -1891,6 +1955,127 @@ VisualShaderNodeIntOp::VisualShaderNodeIntOp() {
set_input_port_default_value(1, 0);
}
+////////////// Unsigned Integer Op
+
+String VisualShaderNodeUIntOp::get_caption() const {
+ return "UIntOp";
+}
+
+int VisualShaderNodeUIntOp::get_input_port_count() const {
+ return 2;
+}
+
+VisualShaderNodeUIntOp::PortType VisualShaderNodeUIntOp::get_input_port_type(int p_port) const {
+ return PORT_TYPE_SCALAR_UINT;
+}
+
+String VisualShaderNodeUIntOp::get_input_port_name(int p_port) const {
+ return p_port == 0 ? "a" : "b";
+}
+
+int VisualShaderNodeUIntOp::get_output_port_count() const {
+ return 1;
+}
+
+VisualShaderNodeUIntOp::PortType VisualShaderNodeUIntOp::get_output_port_type(int p_port) const {
+ return PORT_TYPE_SCALAR_UINT;
+}
+
+String VisualShaderNodeUIntOp::get_output_port_name(int p_port) const {
+ return "op"; // No output port means the editor will be used as port.
+}
+
+String VisualShaderNodeUIntOp::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 = " " + p_output_vars[0] + " = ";
+ switch (op) {
+ case OP_ADD:
+ code += p_input_vars[0] + " + " + p_input_vars[1] + ";\n";
+ break;
+ case OP_SUB:
+ code += p_input_vars[0] + " - " + p_input_vars[1] + ";\n";
+ break;
+ case OP_MUL:
+ code += p_input_vars[0] + " * " + p_input_vars[1] + ";\n";
+ break;
+ case OP_DIV:
+ code += p_input_vars[0] + " / " + p_input_vars[1] + ";\n";
+ break;
+ case OP_MOD:
+ code += p_input_vars[0] + " % " + p_input_vars[1] + ";\n";
+ break;
+ case OP_MAX:
+ code += "max(" + p_input_vars[0] + ", " + p_input_vars[1] + ");\n";
+ break;
+ case OP_MIN:
+ code += "min(" + p_input_vars[0] + ", " + p_input_vars[1] + ");\n";
+ break;
+ case OP_BITWISE_AND:
+ code += p_input_vars[0] + " & " + p_input_vars[1] + ";\n";
+ break;
+ case OP_BITWISE_OR:
+ code += p_input_vars[0] + " | " + p_input_vars[1] + ";\n";
+ break;
+ case OP_BITWISE_XOR:
+ code += p_input_vars[0] + " ^ " + p_input_vars[1] + ";\n";
+ break;
+ case OP_BITWISE_LEFT_SHIFT:
+ code += p_input_vars[0] + " << " + p_input_vars[1] + ";\n";
+ break;
+ case OP_BITWISE_RIGHT_SHIFT:
+ code += p_input_vars[0] + " >> " + p_input_vars[1] + ";\n";
+ break;
+ default:
+ break;
+ }
+
+ return code;
+}
+
+void VisualShaderNodeUIntOp::set_operator(Operator p_op) {
+ ERR_FAIL_INDEX(int(p_op), OP_ENUM_SIZE);
+ if (op == p_op) {
+ return;
+ }
+ op = p_op;
+ emit_changed();
+}
+
+VisualShaderNodeUIntOp::Operator VisualShaderNodeUIntOp::get_operator() const {
+ return op;
+}
+
+Vector<StringName> VisualShaderNodeUIntOp::get_editable_properties() const {
+ Vector<StringName> props;
+ props.push_back("operator");
+ return props;
+}
+
+void VisualShaderNodeUIntOp::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("set_operator", "op"), &VisualShaderNodeUIntOp::set_operator);
+ ClassDB::bind_method(D_METHOD("get_operator"), &VisualShaderNodeUIntOp::get_operator);
+
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "operator", PROPERTY_HINT_ENUM, "Add,Subtract,Multiply,Divide,Remainder,Max,Min,Bitwise AND,Bitwise OR,Bitwise XOR,Bitwise Left Shift,Bitwise Right Shift"), "set_operator", "get_operator");
+
+ BIND_ENUM_CONSTANT(OP_ADD);
+ BIND_ENUM_CONSTANT(OP_SUB);
+ BIND_ENUM_CONSTANT(OP_MUL);
+ BIND_ENUM_CONSTANT(OP_DIV);
+ BIND_ENUM_CONSTANT(OP_MOD);
+ BIND_ENUM_CONSTANT(OP_MAX);
+ BIND_ENUM_CONSTANT(OP_MIN);
+ BIND_ENUM_CONSTANT(OP_BITWISE_AND);
+ BIND_ENUM_CONSTANT(OP_BITWISE_OR);
+ BIND_ENUM_CONSTANT(OP_BITWISE_XOR);
+ BIND_ENUM_CONSTANT(OP_BITWISE_LEFT_SHIFT);
+ BIND_ENUM_CONSTANT(OP_BITWISE_RIGHT_SHIFT);
+ BIND_ENUM_CONSTANT(OP_ENUM_SIZE);
+}
+
+VisualShaderNodeUIntOp::VisualShaderNodeUIntOp() {
+ set_input_port_default_value(0, 0);
+ set_input_port_default_value(1, 0);
+}
+
////////////// Vector Op
String VisualShaderNodeVectorOp::get_caption() const {
@@ -2626,6 +2811,79 @@ VisualShaderNodeIntFunc::VisualShaderNodeIntFunc() {
set_input_port_default_value(0, 0);
}
+////////////// Unsigned Int Func
+
+String VisualShaderNodeUIntFunc::get_caption() const {
+ return "UIntFunc";
+}
+
+int VisualShaderNodeUIntFunc::get_input_port_count() const {
+ return 1;
+}
+
+VisualShaderNodeUIntFunc::PortType VisualShaderNodeUIntFunc::get_input_port_type(int p_port) const {
+ return PORT_TYPE_SCALAR_UINT;
+}
+
+String VisualShaderNodeUIntFunc::get_input_port_name(int p_port) const {
+ return "";
+}
+
+int VisualShaderNodeUIntFunc::get_output_port_count() const {
+ return 1;
+}
+
+VisualShaderNodeUIntFunc::PortType VisualShaderNodeUIntFunc::get_output_port_type(int p_port) const {
+ return PORT_TYPE_SCALAR_UINT;
+}
+
+String VisualShaderNodeUIntFunc::get_output_port_name(int p_port) const {
+ return ""; // No output port means the editor will be used as port.
+}
+
+String VisualShaderNodeUIntFunc::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 {
+ static const char *functions[FUNC_MAX] = {
+ "-($)",
+ "~($)"
+ };
+
+ return " " + p_output_vars[0] + " = " + String(functions[func]).replace("$", p_input_vars[0]) + ";\n";
+}
+
+void VisualShaderNodeUIntFunc::set_function(Function p_func) {
+ ERR_FAIL_INDEX(int(p_func), int(FUNC_MAX));
+ if (func == p_func) {
+ return;
+ }
+ func = p_func;
+ emit_changed();
+}
+
+VisualShaderNodeUIntFunc::Function VisualShaderNodeUIntFunc::get_function() const {
+ return func;
+}
+
+Vector<StringName> VisualShaderNodeUIntFunc::get_editable_properties() const {
+ Vector<StringName> props;
+ props.push_back("function");
+ return props;
+}
+
+void VisualShaderNodeUIntFunc::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("set_function", "func"), &VisualShaderNodeUIntFunc::set_function);
+ ClassDB::bind_method(D_METHOD("get_function"), &VisualShaderNodeUIntFunc::get_function);
+
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "function", PROPERTY_HINT_ENUM, "Negate,Bitwise NOT"), "set_function", "get_function");
+
+ BIND_ENUM_CONSTANT(FUNC_NEGATE);
+ BIND_ENUM_CONSTANT(FUNC_BITWISE_NOT);
+ BIND_ENUM_CONSTANT(FUNC_MAX);
+}
+
+VisualShaderNodeUIntFunc::VisualShaderNodeUIntFunc() {
+ set_input_port_default_value(0, 0);
+}
+
////////////// Vector Func
String VisualShaderNodeVectorFunc::get_caption() const {
@@ -3091,10 +3349,10 @@ String VisualShaderNodeUVFunc::generate_code(Shader::Mode p_mode, VisualShader::
switch (func) {
case FUNC_PANNING: {
- code += vformat(" %s = fma(%s, %s, %s);\n", p_output_vars[0], offset_pivot, scale, uv);
+ code += vformat(" %s = %s * %s + %s;\n", p_output_vars[0], offset_pivot, scale, uv);
} break;
case FUNC_SCALING: {
- code += vformat(" %s = fma((%s - %s), %s, %s);\n", p_output_vars[0], uv, offset_pivot, scale, offset_pivot);
+ code += vformat(" %s = (%s - %s) * %s + %s;\n", p_output_vars[0], uv, offset_pivot, scale, offset_pivot);
} break;
default:
break;
@@ -3432,16 +3690,47 @@ String VisualShaderNodeDerivativeFunc::get_output_port_name(int p_port) const {
String VisualShaderNodeDerivativeFunc::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 {
static const char *functions[FUNC_MAX] = {
- "fwidth($)",
- "dFdx($)",
- "dFdy($)"
+ "fwidth$($)",
+ "dFdx$($)",
+ "dFdy$($)"
+ };
+
+ static const char *precisions[PRECISION_MAX] = {
+ "",
+ "Coarse",
+ "Fine"
};
String code;
- code += " " + p_output_vars[0] + " = " + String(functions[func]).replace("$", p_input_vars[0]) + ";\n";
+ if (OS::get_singleton()->get_current_rendering_method() == "gl_compatibility") {
+ code += " " + p_output_vars[0] + " = " + String(functions[func]).replace_first("$", "").replace_first("$", p_input_vars[0]) + ";\n";
+ return code;
+ }
+
+ code += " " + p_output_vars[0] + " = " + String(functions[func]).replace_first("$", String(precisions[precision])).replace_first("$", p_input_vars[0]) + ";\n";
return code;
}
+String VisualShaderNodeDerivativeFunc::get_warning(Shader::Mode p_mode, VisualShader::Type p_type) const {
+ if (precision != PRECISION_NONE && OS::get_singleton()->get_current_rendering_method() == "gl_compatibility") {
+ String precision_str;
+ switch (precision) {
+ case PRECISION_COARSE: {
+ precision_str = "Coarse";
+ } break;
+ case PRECISION_FINE: {
+ precision_str = "Fine";
+ } break;
+ default: {
+ } break;
+ }
+
+ return vformat(RTR("`%s` precision mode is not available for `gl_compatibility` profile.\nReverted to `None` precision."), precision_str);
+ }
+
+ return String();
+}
+
void VisualShaderNodeDerivativeFunc::set_op_type(OpType p_op_type) {
ERR_FAIL_INDEX((int)p_op_type, int(OP_TYPE_MAX));
if (op_type == p_op_type) {
@@ -3484,10 +3773,24 @@ VisualShaderNodeDerivativeFunc::Function VisualShaderNodeDerivativeFunc::get_fun
return func;
}
+void VisualShaderNodeDerivativeFunc::set_precision(Precision p_precision) {
+ ERR_FAIL_INDEX(int(p_precision), int(PRECISION_MAX));
+ if (precision == p_precision) {
+ return;
+ }
+ precision = p_precision;
+ emit_changed();
+}
+
+VisualShaderNodeDerivativeFunc::Precision VisualShaderNodeDerivativeFunc::get_precision() const {
+ return precision;
+}
+
Vector<StringName> VisualShaderNodeDerivativeFunc::get_editable_properties() const {
Vector<StringName> props;
props.push_back("op_type");
props.push_back("function");
+ props.push_back("precision");
return props;
}
@@ -3498,8 +3801,12 @@ void VisualShaderNodeDerivativeFunc::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_function", "func"), &VisualShaderNodeDerivativeFunc::set_function);
ClassDB::bind_method(D_METHOD("get_function"), &VisualShaderNodeDerivativeFunc::get_function);
+ ClassDB::bind_method(D_METHOD("set_precision", "precision"), &VisualShaderNodeDerivativeFunc::set_precision);
+ ClassDB::bind_method(D_METHOD("get_precision"), &VisualShaderNodeDerivativeFunc::get_precision);
+
ADD_PROPERTY(PropertyInfo(Variant::INT, "op_type", PROPERTY_HINT_ENUM, "Scalar,Vector2,Vector3,Vector4"), "set_op_type", "get_op_type");
ADD_PROPERTY(PropertyInfo(Variant::INT, "function", PROPERTY_HINT_ENUM, "Sum,X,Y"), "set_function", "get_function");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "precision", PROPERTY_HINT_ENUM, "None,Coarse,Fine"), "set_precision", "get_precision");
BIND_ENUM_CONSTANT(OP_TYPE_SCALAR);
BIND_ENUM_CONSTANT(OP_TYPE_VECTOR_2D);
@@ -3511,6 +3818,11 @@ void VisualShaderNodeDerivativeFunc::_bind_methods() {
BIND_ENUM_CONSTANT(FUNC_X);
BIND_ENUM_CONSTANT(FUNC_Y);
BIND_ENUM_CONSTANT(FUNC_MAX);
+
+ BIND_ENUM_CONSTANT(PRECISION_NONE);
+ BIND_ENUM_CONSTANT(PRECISION_COARSE);
+ BIND_ENUM_CONSTANT(PRECISION_FINE);
+ BIND_ENUM_CONSTANT(PRECISION_MAX);
}
VisualShaderNodeDerivativeFunc::VisualShaderNodeDerivativeFunc() {
@@ -3531,6 +3843,8 @@ VisualShaderNodeClamp::PortType VisualShaderNodeClamp::get_input_port_type(int p
switch (op_type) {
case OP_TYPE_INT:
return PORT_TYPE_SCALAR_INT;
+ case OP_TYPE_UINT:
+ return PORT_TYPE_SCALAR_UINT;
case OP_TYPE_VECTOR_2D:
return PORT_TYPE_VECTOR_2D;
case OP_TYPE_VECTOR_3D:
@@ -3562,6 +3876,8 @@ VisualShaderNodeClamp::PortType VisualShaderNodeClamp::get_output_port_type(int
switch (op_type) {
case OP_TYPE_INT:
return PORT_TYPE_SCALAR_INT;
+ case OP_TYPE_UINT:
+ return PORT_TYPE_SCALAR_UINT;
case OP_TYPE_VECTOR_2D:
return PORT_TYPE_VECTOR_2D;
case OP_TYPE_VECTOR_3D:
@@ -3593,6 +3909,7 @@ void VisualShaderNodeClamp::set_op_type(OpType p_op_type) {
set_input_port_default_value(1, 0.0, get_input_port_default_value(1));
set_input_port_default_value(2, 0.0, get_input_port_default_value(2));
break;
+ case OP_TYPE_UINT:
case OP_TYPE_INT:
set_input_port_default_value(0, 0, get_input_port_default_value(0));
set_input_port_default_value(1, 0, get_input_port_default_value(1));
@@ -3634,10 +3951,11 @@ void VisualShaderNodeClamp::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_op_type", "op_type"), &VisualShaderNodeClamp::set_op_type);
ClassDB::bind_method(D_METHOD("get_op_type"), &VisualShaderNodeClamp::get_op_type);
- ADD_PROPERTY(PropertyInfo(Variant::INT, "op_type", PROPERTY_HINT_ENUM, "Float,Int,Vector2,Vector3,Vector4"), "set_op_type", "get_op_type");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "op_type", PROPERTY_HINT_ENUM, "Float,Int,UInt,Vector2,Vector3,Vector4"), "set_op_type", "get_op_type");
BIND_ENUM_CONSTANT(OP_TYPE_FLOAT);
BIND_ENUM_CONSTANT(OP_TYPE_INT);
+ BIND_ENUM_CONSTANT(OP_TYPE_UINT);
BIND_ENUM_CONSTANT(OP_TYPE_VECTOR_2D);
BIND_ENUM_CONSTANT(OP_TYPE_VECTOR_3D);
BIND_ENUM_CONSTANT(OP_TYPE_VECTOR_4D);
@@ -4914,7 +5232,7 @@ Vector<StringName> VisualShaderNodeFloatParameter::get_editable_properties() con
VisualShaderNodeFloatParameter::VisualShaderNodeFloatParameter() {
}
-////////////// Integer Parametet
+////////////// Integer Parameter
String VisualShaderNodeIntParameter::get_caption() const {
return "IntParameter";
@@ -5105,6 +5423,112 @@ Vector<StringName> VisualShaderNodeIntParameter::get_editable_properties() const
VisualShaderNodeIntParameter::VisualShaderNodeIntParameter() {
}
+////////////// Unsigned Integer Parameter
+
+String VisualShaderNodeUIntParameter::get_caption() const {
+ return "UIntParameter";
+}
+
+int VisualShaderNodeUIntParameter::get_input_port_count() const {
+ return 0;
+}
+
+VisualShaderNodeUIntParameter::PortType VisualShaderNodeUIntParameter::get_input_port_type(int p_port) const {
+ return PORT_TYPE_SCALAR_UINT;
+}
+
+String VisualShaderNodeUIntParameter::get_input_port_name(int p_port) const {
+ return String();
+}
+
+int VisualShaderNodeUIntParameter::get_output_port_count() const {
+ return 1;
+}
+
+VisualShaderNodeUIntParameter::PortType VisualShaderNodeUIntParameter::get_output_port_type(int p_port) const {
+ return PORT_TYPE_SCALAR_UINT;
+}
+
+String VisualShaderNodeUIntParameter::get_output_port_name(int p_port) const {
+ return ""; // No output port means the editor will be used as port.
+}
+
+String VisualShaderNodeUIntParameter::generate_global(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const {
+ String code = _get_qual_str() + "uniform uint " + get_parameter_name();
+ if (default_value_enabled) {
+ code += " = " + itos(default_value);
+ }
+ code += ";\n";
+ return code;
+}
+
+String VisualShaderNodeUIntParameter::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 {
+ return " " + p_output_vars[0] + " = " + get_parameter_name() + ";\n";
+}
+
+bool VisualShaderNodeUIntParameter::is_show_prop_names() const {
+ return true;
+}
+
+bool VisualShaderNodeUIntParameter::is_use_prop_slots() const {
+ return true;
+}
+
+void VisualShaderNodeUIntParameter::set_default_value_enabled(bool p_default_value_enabled) {
+ if (default_value_enabled == p_default_value_enabled) {
+ return;
+ }
+ default_value_enabled = p_default_value_enabled;
+ emit_changed();
+}
+
+bool VisualShaderNodeUIntParameter::is_default_value_enabled() const {
+ return default_value_enabled;
+}
+
+void VisualShaderNodeUIntParameter::set_default_value(int p_default_value) {
+ if (default_value == p_default_value) {
+ return;
+ }
+ default_value = p_default_value;
+ emit_changed();
+}
+
+int VisualShaderNodeUIntParameter::get_default_value() const {
+ return default_value;
+}
+
+void VisualShaderNodeUIntParameter::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("set_default_value_enabled", "enabled"), &VisualShaderNodeUIntParameter::set_default_value_enabled);
+ ClassDB::bind_method(D_METHOD("is_default_value_enabled"), &VisualShaderNodeUIntParameter::is_default_value_enabled);
+
+ ClassDB::bind_method(D_METHOD("set_default_value", "value"), &VisualShaderNodeUIntParameter::set_default_value);
+ ClassDB::bind_method(D_METHOD("get_default_value"), &VisualShaderNodeUIntParameter::get_default_value);
+
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "default_value_enabled"), "set_default_value_enabled", "is_default_value_enabled");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "default_value"), "set_default_value", "get_default_value");
+}
+
+bool VisualShaderNodeUIntParameter::is_qualifier_supported(Qualifier p_qual) const {
+ return true; // All qualifiers are supported.
+}
+
+bool VisualShaderNodeUIntParameter::is_convertible_to_constant() const {
+ return true; // Conversion is allowed.
+}
+
+Vector<StringName> VisualShaderNodeUIntParameter::get_editable_properties() const {
+ Vector<StringName> props = VisualShaderNodeParameter::get_editable_properties();
+ props.push_back("default_value_enabled");
+ if (default_value_enabled) {
+ props.push_back("default_value");
+ }
+ return props;
+}
+
+VisualShaderNodeUIntParameter::VisualShaderNodeUIntParameter() {
+}
+
////////////// Boolean Parameter
String VisualShaderNodeBooleanParameter::get_caption() const {
@@ -5733,7 +6157,7 @@ VisualShaderNodeTransformParameter::VisualShaderNodeTransformParameter() {
//////////////
-String get_sampler_hint(VisualShaderNodeTextureParameter::TextureType p_texture_type, VisualShaderNodeTextureParameter::ColorDefault p_color_default, VisualShaderNodeTextureParameter::TextureFilter p_texture_filter, VisualShaderNodeTextureParameter::TextureRepeat p_texture_repeat) {
+String get_sampler_hint(VisualShaderNodeTextureParameter::TextureType p_texture_type, VisualShaderNodeTextureParameter::ColorDefault p_color_default, VisualShaderNodeTextureParameter::TextureFilter p_texture_filter, VisualShaderNodeTextureParameter::TextureRepeat p_texture_repeat, VisualShaderNodeTextureParameter::TextureSource p_texture_source) {
String code;
bool has_colon = false;
@@ -5836,6 +6260,33 @@ String get_sampler_hint(VisualShaderNodeTextureParameter::TextureType p_texture_
}
}
+ {
+ String source_code;
+
+ switch (p_texture_source) {
+ case VisualShaderNodeTextureParameter::SOURCE_SCREEN:
+ source_code = "hint_screen_texture";
+ break;
+ case VisualShaderNodeTextureParameter::SOURCE_DEPTH:
+ source_code = "hint_depth_texture";
+ break;
+ case VisualShaderNodeTextureParameter::SOURCE_NORMAL_ROUGHNESS:
+ source_code = "hint_normal_roughness_texture";
+ break;
+ default:
+ break;
+ }
+
+ if (!source_code.is_empty()) {
+ if (!has_colon) {
+ code += " : ";
+ } else {
+ code += ", ";
+ }
+ code += source_code;
+ }
+ }
+
return code;
}
@@ -5922,6 +6373,19 @@ VisualShaderNodeTextureParameter::TextureRepeat VisualShaderNodeTextureParameter
return texture_repeat;
}
+void VisualShaderNodeTextureParameter::set_texture_source(TextureSource p_source) {
+ ERR_FAIL_INDEX(int(p_source), int(SOURCE_MAX));
+ if (texture_source == p_source) {
+ return;
+ }
+ texture_source = p_source;
+ emit_changed();
+}
+
+VisualShaderNodeTextureParameter::TextureSource VisualShaderNodeTextureParameter::get_texture_source() const {
+ return texture_source;
+}
+
Vector<StringName> VisualShaderNodeTextureParameter::get_editable_properties() const {
Vector<StringName> props = VisualShaderNodeParameter::get_editable_properties();
props.push_back("texture_type");
@@ -5930,6 +6394,7 @@ Vector<StringName> VisualShaderNodeTextureParameter::get_editable_properties() c
}
props.push_back("texture_filter");
props.push_back("texture_repeat");
+ props.push_back("texture_source");
return props;
}
@@ -5943,6 +6408,7 @@ HashMap<StringName, String> VisualShaderNodeTextureParameter::get_editable_prope
names.insert("color_default", RTR("Default Color"));
names.insert("texture_filter", RTR("Filter"));
names.insert("texture_repeat", RTR("Repeat"));
+ names.insert("texture_source", RTR("Source"));
return names;
}
@@ -5950,19 +6416,23 @@ void VisualShaderNodeTextureParameter::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_texture_type", "type"), &VisualShaderNodeTextureParameter::set_texture_type);
ClassDB::bind_method(D_METHOD("get_texture_type"), &VisualShaderNodeTextureParameter::get_texture_type);
- ClassDB::bind_method(D_METHOD("set_color_default", "type"), &VisualShaderNodeTextureParameter::set_color_default);
+ ClassDB::bind_method(D_METHOD("set_color_default", "color"), &VisualShaderNodeTextureParameter::set_color_default);
ClassDB::bind_method(D_METHOD("get_color_default"), &VisualShaderNodeTextureParameter::get_color_default);
ClassDB::bind_method(D_METHOD("set_texture_filter", "filter"), &VisualShaderNodeTextureParameter::set_texture_filter);
ClassDB::bind_method(D_METHOD("get_texture_filter"), &VisualShaderNodeTextureParameter::get_texture_filter);
- ClassDB::bind_method(D_METHOD("set_texture_repeat", "type"), &VisualShaderNodeTextureParameter::set_texture_repeat);
+ ClassDB::bind_method(D_METHOD("set_texture_repeat", "repeat"), &VisualShaderNodeTextureParameter::set_texture_repeat);
ClassDB::bind_method(D_METHOD("get_texture_repeat"), &VisualShaderNodeTextureParameter::get_texture_repeat);
+ ClassDB::bind_method(D_METHOD("set_texture_source", "source"), &VisualShaderNodeTextureParameter::set_texture_source);
+ ClassDB::bind_method(D_METHOD("get_texture_source"), &VisualShaderNodeTextureParameter::get_texture_source);
+
ADD_PROPERTY(PropertyInfo(Variant::INT, "texture_type", PROPERTY_HINT_ENUM, "Data,Color,Normal Map,Anisotropic"), "set_texture_type", "get_texture_type");
ADD_PROPERTY(PropertyInfo(Variant::INT, "color_default", PROPERTY_HINT_ENUM, "White,Black,Transparent"), "set_color_default", "get_color_default");
ADD_PROPERTY(PropertyInfo(Variant::INT, "texture_filter", PROPERTY_HINT_ENUM, "Default,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, "Default,Enabled,Disabled"), "set_texture_repeat", "get_texture_repeat");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "texture_source", PROPERTY_HINT_ENUM, "None,Screen,Depth,NormalRoughness"), "set_texture_source", "get_texture_source");
BIND_ENUM_CONSTANT(TYPE_DATA);
BIND_ENUM_CONSTANT(TYPE_COLOR);
@@ -5988,6 +6458,12 @@ void VisualShaderNodeTextureParameter::_bind_methods() {
BIND_ENUM_CONSTANT(REPEAT_ENABLED);
BIND_ENUM_CONSTANT(REPEAT_DISABLED);
BIND_ENUM_CONSTANT(REPEAT_MAX);
+
+ BIND_ENUM_CONSTANT(SOURCE_NONE);
+ BIND_ENUM_CONSTANT(SOURCE_SCREEN);
+ BIND_ENUM_CONSTANT(SOURCE_DEPTH);
+ BIND_ENUM_CONSTANT(SOURCE_NORMAL_ROUGHNESS);
+ BIND_ENUM_CONSTANT(SOURCE_MAX);
}
bool VisualShaderNodeTextureParameter::is_qualifier_supported(Qualifier p_qual) const {
@@ -6028,7 +6504,7 @@ String VisualShaderNodeTexture2DParameter::get_output_port_name(int p_port) cons
String VisualShaderNodeTexture2DParameter::generate_global(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const {
String code = _get_qual_str() + "uniform sampler2D " + get_parameter_name();
- code += get_sampler_hint(texture_type, color_default, texture_filter, texture_repeat);
+ code += get_sampler_hint(texture_type, color_default, texture_filter, texture_repeat, texture_source);
code += ";\n";
return code;
}
@@ -6039,7 +6515,7 @@ VisualShaderNodeTexture2DParameter::VisualShaderNodeTexture2DParameter() {
////////////// Texture Parameter (Triplanar)
String VisualShaderNodeTextureParameterTriplanar::get_caption() const {
- return "TextureUniformTriplanar";
+ return "TextureParameterTriplanar";
}
int VisualShaderNodeTextureParameterTriplanar::get_input_port_count() const {
@@ -6128,7 +6604,7 @@ String VisualShaderNodeTextureParameterTriplanar::generate_global_per_func(Shade
String VisualShaderNodeTextureParameterTriplanar::generate_global(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const {
String code = _get_qual_str() + "uniform sampler2D " + get_parameter_name();
- code += get_sampler_hint(texture_type, color_default, texture_filter, texture_repeat);
+ code += get_sampler_hint(texture_type, color_default, texture_filter, texture_repeat, texture_source);
code += ";\n";
return code;
}
@@ -6174,7 +6650,7 @@ String VisualShaderNodeTexture2DArrayParameter::get_output_port_name(int p_port)
String VisualShaderNodeTexture2DArrayParameter::generate_global(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const {
String code = _get_qual_str() + "uniform sampler2DArray " + get_parameter_name();
- code += get_sampler_hint(texture_type, color_default, texture_filter, texture_repeat);
+ code += get_sampler_hint(texture_type, color_default, texture_filter, texture_repeat, texture_source);
code += ";\n";
return code;
}
@@ -6194,7 +6670,7 @@ String VisualShaderNodeTexture3DParameter::get_output_port_name(int p_port) cons
String VisualShaderNodeTexture3DParameter::generate_global(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const {
String code = _get_qual_str() + "uniform sampler3D " + get_parameter_name();
- code += get_sampler_hint(texture_type, color_default, texture_filter, texture_repeat);
+ code += get_sampler_hint(texture_type, color_default, texture_filter, texture_repeat, texture_source);
code += ";\n";
return code;
}
@@ -6214,7 +6690,7 @@ String VisualShaderNodeCubemapParameter::get_output_port_name(int p_port) const
String VisualShaderNodeCubemapParameter::generate_global(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const {
String code = _get_qual_str() + "uniform samplerCube " + get_parameter_name();
- code += get_sampler_hint(texture_type, color_default, texture_filter, texture_repeat);
+ code += get_sampler_hint(texture_type, color_default, texture_filter, texture_repeat, texture_source);
code += ";\n";
return code;
}
@@ -6315,6 +6791,8 @@ VisualShaderNodeSwitch::PortType VisualShaderNodeSwitch::get_input_port_type(int
switch (op_type) {
case OP_TYPE_INT:
return PORT_TYPE_SCALAR_INT;
+ case OP_TYPE_UINT:
+ return PORT_TYPE_SCALAR_UINT;
case OP_TYPE_VECTOR_2D:
return PORT_TYPE_VECTOR_2D;
case OP_TYPE_VECTOR_3D:
@@ -6353,6 +6831,8 @@ VisualShaderNodeSwitch::PortType VisualShaderNodeSwitch::get_output_port_type(in
switch (op_type) {
case OP_TYPE_INT:
return PORT_TYPE_SCALAR_INT;
+ case OP_TYPE_UINT:
+ return PORT_TYPE_SCALAR_UINT;
case OP_TYPE_VECTOR_2D:
return PORT_TYPE_VECTOR_2D;
case OP_TYPE_VECTOR_3D:
@@ -6383,6 +6863,7 @@ void VisualShaderNodeSwitch::set_op_type(OpType p_op_type) {
set_input_port_default_value(1, 1.0, get_input_port_default_value(1));
set_input_port_default_value(2, 0.0, get_input_port_default_value(2));
break;
+ case OP_TYPE_UINT:
case OP_TYPE_INT:
set_input_port_default_value(1, 1, get_input_port_default_value(1));
set_input_port_default_value(2, 0, get_input_port_default_value(2));
@@ -6428,10 +6909,11 @@ void VisualShaderNodeSwitch::_bind_methods() { // static
ClassDB::bind_method(D_METHOD("set_op_type", "type"), &VisualShaderNodeSwitch::set_op_type);
ClassDB::bind_method(D_METHOD("get_op_type"), &VisualShaderNodeSwitch::get_op_type);
- ADD_PROPERTY(PropertyInfo(Variant::INT, "op_type", PROPERTY_HINT_ENUM, "Float,Int,Vector2,Vector3,Vector4,Boolean,Transform"), "set_op_type", "get_op_type");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "op_type", PROPERTY_HINT_ENUM, "Float,Int,UInt,Vector2,Vector3,Vector4,Boolean,Transform"), "set_op_type", "get_op_type");
BIND_ENUM_CONSTANT(OP_TYPE_FLOAT);
BIND_ENUM_CONSTANT(OP_TYPE_INT);
+ BIND_ENUM_CONSTANT(OP_TYPE_UINT);
BIND_ENUM_CONSTANT(OP_TYPE_VECTOR_2D);
BIND_ENUM_CONSTANT(OP_TYPE_VECTOR_3D);
BIND_ENUM_CONSTANT(OP_TYPE_VECTOR_4D);
@@ -6441,15 +6923,34 @@ void VisualShaderNodeSwitch::_bind_methods() { // static
}
String VisualShaderNodeSwitch::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 {
+ bool use_mix = false;
+ switch (op_type) {
+ case OP_TYPE_FLOAT: {
+ use_mix = true;
+ } break;
+ case OP_TYPE_VECTOR_2D: {
+ use_mix = true;
+ } break;
+ case OP_TYPE_VECTOR_3D: {
+ use_mix = true;
+ } break;
+ case OP_TYPE_VECTOR_4D: {
+ use_mix = true;
+ } break;
+ default: {
+ } break;
+ }
+
String code;
- code += " if(" + p_input_vars[0] + ")\n";
- code += " {\n";
- code += " " + p_output_vars[0] + " = " + p_input_vars[1] + ";\n";
- code += " }\n";
- code += " else\n";
- code += " {\n";
- code += " " + p_output_vars[0] + " = " + p_input_vars[2] + ";\n";
- code += " }\n";
+ if (use_mix) {
+ code += " " + p_output_vars[0] + " = mix(" + p_input_vars[2] + ", " + p_input_vars[1] + ", float(" + p_input_vars[0] + "));\n";
+ } else {
+ code += " if (" + p_input_vars[0] + ") {\n";
+ code += " " + p_output_vars[0] + " = " + p_input_vars[1] + ";\n";
+ code += " } else {\n";
+ code += " " + p_output_vars[0] + " = " + p_input_vars[2] + ";\n";
+ code += " }\n";
+ }
return code;
}
@@ -6664,6 +7165,8 @@ VisualShaderNodeCompare::PortType VisualShaderNodeCompare::get_input_port_type(i
return PORT_TYPE_SCALAR;
case CTYPE_SCALAR_INT:
return PORT_TYPE_SCALAR_INT;
+ case CTYPE_SCALAR_UINT:
+ return PORT_TYPE_SCALAR_UINT;
case CTYPE_VECTOR_2D:
return PORT_TYPE_VECTOR_2D;
case CTYPE_VECTOR_3D:
@@ -6749,6 +7252,7 @@ String VisualShaderNodeCompare::generate_code(Shader::Mode p_mode, VisualShader:
code += " " + p_output_vars[0] + " = " + (p_input_vars[0] + " $ " + p_input_vars[1]).replace("$", operators[func]) + ";\n";
}
} break;
+ case CTYPE_SCALAR_UINT:
case CTYPE_SCALAR_INT: {
code += " " + p_output_vars[0] + " = " + (p_input_vars[0] + " $ " + p_input_vars[1]).replace("$", operators[func]) + ";\n";
} break;
@@ -6799,6 +7303,7 @@ void VisualShaderNodeCompare::set_comparison_type(ComparisonType p_comparison_ty
set_input_port_default_value(1, 0.0, get_input_port_default_value(1));
simple_decl = true;
break;
+ case CTYPE_SCALAR_UINT:
case CTYPE_SCALAR_INT:
set_input_port_default_value(0, 0, get_input_port_default_value(0));
set_input_port_default_value(1, 0, get_input_port_default_value(1));
@@ -6886,12 +7391,13 @@ void VisualShaderNodeCompare::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_condition", "condition"), &VisualShaderNodeCompare::set_condition);
ClassDB::bind_method(D_METHOD("get_condition"), &VisualShaderNodeCompare::get_condition);
- ADD_PROPERTY(PropertyInfo(Variant::INT, "type", PROPERTY_HINT_ENUM, "Float,Int,Vector2,Vector3,Vector4,Boolean,Transform"), "set_comparison_type", "get_comparison_type");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "type", PROPERTY_HINT_ENUM, "Float,Int,UInt,Vector2,Vector3,Vector4,Boolean,Transform"), "set_comparison_type", "get_comparison_type");
ADD_PROPERTY(PropertyInfo(Variant::INT, "function", PROPERTY_HINT_ENUM, "a == b,a != b,a > b,a >= b,a < b,a <= b"), "set_function", "get_function");
ADD_PROPERTY(PropertyInfo(Variant::INT, "condition", PROPERTY_HINT_ENUM, "All,Any"), "set_condition", "get_condition");
BIND_ENUM_CONSTANT(CTYPE_SCALAR);
BIND_ENUM_CONSTANT(CTYPE_SCALAR_INT);
+ BIND_ENUM_CONSTANT(CTYPE_SCALAR_UINT);
BIND_ENUM_CONSTANT(CTYPE_VECTOR_2D);
BIND_ENUM_CONSTANT(CTYPE_VECTOR_3D);
BIND_ENUM_CONSTANT(CTYPE_VECTOR_4D);
@@ -6976,6 +7482,9 @@ String VisualShaderNodeMultiplyAdd::get_output_port_name(int p_port) const {
}
String VisualShaderNodeMultiplyAdd::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 {
+ if (OS::get_singleton()->get_current_rendering_method() == "gl_compatibility") {
+ return " " + p_output_vars[0] + " = (" + p_input_vars[0] + " * " + p_input_vars[1] + ") + " + p_input_vars[2] + ";\n";
+ }
return " " + p_output_vars[0] + " = fma(" + p_input_vars[0] + ", " + p_input_vars[1] + ", " + p_input_vars[2] + ");\n";
}
@@ -7261,12 +7770,15 @@ bool VisualShaderNodeProximityFade::has_output_port_preview(int p_port) const {
return false;
}
+String VisualShaderNodeProximityFade::generate_global(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const {
+ return "uniform sampler2D " + make_unique_id(p_type, p_id, "depth_tex") + " : hint_depth_texture;\n";
+}
+
String VisualShaderNodeProximityFade::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";
- String proximity_fade_distance = vformat("%s", p_input_vars[0]);
- code += " float __depth_tex = textureLod(DEPTH_TEXTURE, SCREEN_UV, 0.0).r;\n";
+ code += " float __depth_tex = texture(" + make_unique_id(p_type, p_id, "depth_tex") + ", SCREEN_UV).r;\n";
if (!RenderingServer::get_singleton()->is_low_end()) {
code += " vec4 __depth_world_pos = INV_PROJECTION_MATRIX * vec4(SCREEN_UV * 2.0 - 1.0, __depth_tex, 1.0);\n";
} else {
diff --git a/scene/resources/visual_shader_nodes.h b/scene/resources/visual_shader_nodes.h
index b2d71a35a6..fa6b134526 100644
--- a/scene/resources/visual_shader_nodes.h
+++ b/scene/resources/visual_shader_nodes.h
@@ -160,6 +160,36 @@ public:
///////////////////////////////////////
+class VisualShaderNodeUIntConstant : public VisualShaderNodeConstant {
+ GDCLASS(VisualShaderNodeUIntConstant, VisualShaderNodeConstant);
+ int constant = 0;
+
+protected:
+ static void _bind_methods();
+
+public:
+ virtual String get_caption() const override;
+
+ virtual int get_input_port_count() const override;
+ virtual PortType get_input_port_type(int p_port) const override;
+ virtual String get_input_port_name(int p_port) const override;
+
+ virtual int get_output_port_count() const override;
+ virtual PortType get_output_port_type(int p_port) const override;
+ virtual String get_output_port_name(int p_port) const override;
+
+ virtual String 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 = false) const override;
+
+ void set_constant(int p_constant);
+ int get_constant() const;
+
+ virtual Vector<StringName> get_editable_properties() const override;
+
+ VisualShaderNodeUIntConstant();
+};
+
+///////////////////////////////////////
+
class VisualShaderNodeBooleanConstant : public VisualShaderNodeConstant {
GDCLASS(VisualShaderNodeBooleanConstant, VisualShaderNodeConstant);
bool constant = false;
@@ -355,6 +385,8 @@ public:
SOURCE_2D_NORMAL,
SOURCE_DEPTH,
SOURCE_PORT,
+ SOURCE_3D_NORMAL,
+ SOURCE_ROUGHNESS,
SOURCE_MAX,
};
@@ -638,6 +670,7 @@ public:
virtual String get_output_port_name(int p_port) const override;
virtual bool has_output_port_preview(int p_port) const override;
+ virtual String generate_global(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const override;
virtual String 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 = false) const override;
VisualShaderNodeLinearSceneDepth();
@@ -741,6 +774,54 @@ public:
VARIANT_ENUM_CAST(VisualShaderNodeIntOp::Operator)
+class VisualShaderNodeUIntOp : public VisualShaderNode {
+ GDCLASS(VisualShaderNodeUIntOp, VisualShaderNode);
+
+public:
+ enum Operator {
+ OP_ADD,
+ OP_SUB,
+ OP_MUL,
+ OP_DIV,
+ OP_MOD,
+ OP_MAX,
+ OP_MIN,
+ OP_BITWISE_AND,
+ OP_BITWISE_OR,
+ OP_BITWISE_XOR,
+ OP_BITWISE_LEFT_SHIFT,
+ OP_BITWISE_RIGHT_SHIFT,
+ OP_ENUM_SIZE,
+ };
+
+protected:
+ Operator op = OP_ADD;
+
+ static void _bind_methods();
+
+public:
+ virtual String get_caption() const override;
+
+ virtual int get_input_port_count() const override;
+ virtual PortType get_input_port_type(int p_port) const override;
+ virtual String get_input_port_name(int p_port) const override;
+
+ virtual int get_output_port_count() const override;
+ virtual PortType get_output_port_type(int p_port) const override;
+ virtual String get_output_port_name(int p_port) const override;
+
+ virtual String 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 = false) const override;
+
+ void set_operator(Operator p_op);
+ Operator get_operator() const;
+
+ virtual Vector<StringName> get_editable_properties() const override;
+
+ VisualShaderNodeUIntOp();
+};
+
+VARIANT_ENUM_CAST(VisualShaderNodeUIntOp::Operator)
+
class VisualShaderNodeVectorOp : public VisualShaderNodeVectorBase {
GDCLASS(VisualShaderNodeVectorOp, VisualShaderNodeVectorBase);
@@ -1047,6 +1128,48 @@ public:
VARIANT_ENUM_CAST(VisualShaderNodeIntFunc::Function)
///////////////////////////////////////
+/// UINT FUNC
+///////////////////////////////////////
+
+class VisualShaderNodeUIntFunc : public VisualShaderNode {
+ GDCLASS(VisualShaderNodeUIntFunc, VisualShaderNode);
+
+public:
+ enum Function {
+ FUNC_NEGATE,
+ FUNC_BITWISE_NOT,
+ FUNC_MAX,
+ };
+
+protected:
+ Function func = FUNC_NEGATE;
+
+ static void _bind_methods();
+
+public:
+ virtual String get_caption() const override;
+
+ virtual int get_input_port_count() const override;
+ virtual PortType get_input_port_type(int p_port) const override;
+ virtual String get_input_port_name(int p_port) const override;
+
+ virtual int get_output_port_count() const override;
+ virtual PortType get_output_port_type(int p_port) const override;
+ virtual String get_output_port_name(int p_port) const override;
+
+ virtual String 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 = false) const override;
+
+ void set_function(Function p_func);
+ Function get_function() const;
+
+ virtual Vector<StringName> get_editable_properties() const override;
+
+ VisualShaderNodeUIntFunc();
+};
+
+VARIANT_ENUM_CAST(VisualShaderNodeUIntFunc::Function)
+
+///////////////////////////////////////
/// VECTOR FUNC
///////////////////////////////////////
@@ -1356,6 +1479,7 @@ public:
enum OpType {
OP_TYPE_FLOAT,
OP_TYPE_INT,
+ OP_TYPE_UINT,
OP_TYPE_VECTOR_2D,
OP_TYPE_VECTOR_3D,
OP_TYPE_VECTOR_4D,
@@ -1412,9 +1536,17 @@ public:
FUNC_MAX,
};
+ enum Precision {
+ PRECISION_NONE,
+ PRECISION_COARSE,
+ PRECISION_FINE,
+ PRECISION_MAX,
+ };
+
protected:
OpType op_type = OP_TYPE_SCALAR;
Function func = FUNC_SUM;
+ Precision precision = PRECISION_NONE;
protected:
static void _bind_methods();
@@ -1431,6 +1563,7 @@ public:
virtual String get_output_port_name(int p_port) const override;
virtual String 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 = false) const override;
+ virtual String get_warning(Shader::Mode p_mode, VisualShader::Type p_type) const override;
void set_op_type(OpType p_op_type);
OpType get_op_type() const;
@@ -1438,6 +1571,9 @@ public:
void set_function(Function p_func);
Function get_function() const;
+ void set_precision(Precision p_precision);
+ Precision get_precision() const;
+
virtual Vector<StringName> get_editable_properties() const override;
VisualShaderNodeDerivativeFunc();
@@ -1445,6 +1581,7 @@ public:
VARIANT_ENUM_CAST(VisualShaderNodeDerivativeFunc::OpType)
VARIANT_ENUM_CAST(VisualShaderNodeDerivativeFunc::Function)
+VARIANT_ENUM_CAST(VisualShaderNodeDerivativeFunc::Precision)
///////////////////////////////////////
/// FACEFORWARD
@@ -1902,6 +2039,49 @@ VARIANT_ENUM_CAST(VisualShaderNodeIntParameter::Hint)
///////////////////////////////////////
+class VisualShaderNodeUIntParameter : public VisualShaderNodeParameter {
+ GDCLASS(VisualShaderNodeUIntParameter, VisualShaderNodeParameter);
+
+private:
+ bool default_value_enabled = false;
+ int default_value = 0;
+
+protected:
+ static void _bind_methods();
+
+public:
+ virtual String get_caption() const override;
+
+ virtual int get_input_port_count() const override;
+ virtual PortType get_input_port_type(int p_port) const override;
+ virtual String get_input_port_name(int p_port) const override;
+
+ virtual int get_output_port_count() const override;
+ virtual PortType get_output_port_type(int p_port) const override;
+ virtual String get_output_port_name(int p_port) const override;
+
+ virtual String generate_global(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const override;
+ virtual String 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 = false) const override;
+
+ virtual bool is_show_prop_names() const override;
+ virtual bool is_use_prop_slots() const override;
+
+ void set_default_value_enabled(bool p_enabled);
+ bool is_default_value_enabled() const;
+
+ void set_default_value(int p_value);
+ int get_default_value() const;
+
+ bool is_qualifier_supported(Qualifier p_qual) const override;
+ bool is_convertible_to_constant() const override;
+
+ virtual Vector<StringName> get_editable_properties() const override;
+
+ VisualShaderNodeUIntParameter();
+};
+
+///////////////////////////////////////
+
class VisualShaderNodeBooleanParameter : public VisualShaderNodeParameter {
GDCLASS(VisualShaderNodeBooleanParameter, VisualShaderNodeParameter);
@@ -2198,11 +2378,20 @@ public:
REPEAT_MAX,
};
+ enum TextureSource {
+ SOURCE_NONE,
+ SOURCE_SCREEN,
+ SOURCE_DEPTH,
+ SOURCE_NORMAL_ROUGHNESS,
+ SOURCE_MAX,
+ };
+
protected:
TextureType texture_type = TYPE_DATA;
ColorDefault color_default = COLOR_DEFAULT_WHITE;
TextureFilter texture_filter = FILTER_DEFAULT;
TextureRepeat texture_repeat = REPEAT_DEFAULT;
+ TextureSource texture_source = SOURCE_NONE;
protected:
static void _bind_methods();
@@ -2234,6 +2423,9 @@ public:
void set_texture_repeat(TextureRepeat p_repeat);
TextureRepeat get_texture_repeat() const;
+ void set_texture_source(TextureSource p_source);
+ TextureSource get_texture_source() const;
+
bool is_qualifier_supported(Qualifier p_qual) const override;
bool is_convertible_to_constant() const override;
@@ -2244,6 +2436,7 @@ VARIANT_ENUM_CAST(VisualShaderNodeTextureParameter::TextureType)
VARIANT_ENUM_CAST(VisualShaderNodeTextureParameter::ColorDefault)
VARIANT_ENUM_CAST(VisualShaderNodeTextureParameter::TextureFilter)
VARIANT_ENUM_CAST(VisualShaderNodeTextureParameter::TextureRepeat)
+VARIANT_ENUM_CAST(VisualShaderNodeTextureParameter::TextureSource)
///////////////////////////////////////
@@ -2361,6 +2554,7 @@ public:
enum OpType {
OP_TYPE_FLOAT,
OP_TYPE_INT,
+ OP_TYPE_UINT,
OP_TYPE_VECTOR_2D,
OP_TYPE_VECTOR_3D,
OP_TYPE_VECTOR_4D,
@@ -2476,6 +2670,7 @@ public:
enum ComparisonType {
CTYPE_SCALAR,
CTYPE_SCALAR_INT,
+ CTYPE_SCALAR_UINT,
CTYPE_VECTOR_2D,
CTYPE_VECTOR_3D,
CTYPE_VECTOR_4D,
@@ -2667,6 +2862,7 @@ public:
virtual String get_output_port_name(int p_port) const override;
virtual bool has_output_port_preview(int p_port) const override;
+ virtual String generate_global(Shader::Mode p_mode, VisualShader::Type p_type, int p_id) const override;
virtual String 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 = false) const override;
VisualShaderNodeProximityFade();
diff --git a/scene/resources/visual_shader_particle_nodes.cpp b/scene/resources/visual_shader_particle_nodes.cpp
index 4ac663f7f2..9cf42b681c 100644
--- a/scene/resources/visual_shader_particle_nodes.cpp
+++ b/scene/resources/visual_shader_particle_nodes.cpp
@@ -911,11 +911,12 @@ void VisualShaderNodeParticleRandomness::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_op_type", "type"), &VisualShaderNodeParticleRandomness::set_op_type);
ClassDB::bind_method(D_METHOD("get_op_type"), &VisualShaderNodeParticleRandomness::get_op_type);
- ADD_PROPERTY(PropertyInfo(Variant::INT, "op_type", PROPERTY_HINT_ENUM, "Scalar,Vector2,Vector3"), "set_op_type", "get_op_type");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "op_type", PROPERTY_HINT_ENUM, "Scalar,Vector2,Vector3,Vector4"), "set_op_type", "get_op_type");
BIND_ENUM_CONSTANT(OP_TYPE_SCALAR);
BIND_ENUM_CONSTANT(OP_TYPE_VECTOR_2D);
BIND_ENUM_CONSTANT(OP_TYPE_VECTOR_3D);
+ BIND_ENUM_CONSTANT(OP_TYPE_VECTOR_4D);
BIND_ENUM_CONSTANT(OP_TYPE_MAX);
}
@@ -939,6 +940,8 @@ VisualShaderNodeParticleRandomness::PortType VisualShaderNodeParticleRandomness:
return PORT_TYPE_VECTOR_2D;
case OP_TYPE_VECTOR_3D:
return PORT_TYPE_VECTOR_3D;
+ case OP_TYPE_VECTOR_4D:
+ return PORT_TYPE_VECTOR_4D;
default:
break;
}
@@ -950,48 +953,69 @@ String VisualShaderNodeParticleRandomness::get_output_port_name(int p_port) cons
}
int VisualShaderNodeParticleRandomness::get_input_port_count() const {
- return 2;
+ return 3;
}
VisualShaderNodeParticleRandomness::PortType VisualShaderNodeParticleRandomness::get_input_port_type(int p_port) const {
- switch (op_type) {
- case OP_TYPE_VECTOR_2D:
- return PORT_TYPE_VECTOR_2D;
- case OP_TYPE_VECTOR_3D:
- return PORT_TYPE_VECTOR_3D;
- default:
+ switch (p_port) {
+ case 0:
+ return PORT_TYPE_SCALAR_UINT;
+ case 1:
+ case 2:
+ switch (op_type) {
+ case OP_TYPE_VECTOR_2D:
+ return PORT_TYPE_VECTOR_2D;
+ case OP_TYPE_VECTOR_3D:
+ return PORT_TYPE_VECTOR_3D;
+ case OP_TYPE_VECTOR_4D:
+ return PORT_TYPE_VECTOR_4D;
+ default:
+ break;
+ }
break;
}
return PORT_TYPE_SCALAR;
}
String VisualShaderNodeParticleRandomness::get_input_port_name(int p_port) const {
- if (p_port == 0) {
- return "min";
- } else if (p_port == 1) {
- return "max";
+ switch (p_port) {
+ case 0:
+ return "seed";
+ case 1:
+ return "min";
+ case 2:
+ return "max";
}
return String();
}
-String VisualShaderNodeParticleRandomness::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 {
+bool VisualShaderNodeParticleRandomness::is_input_port_default(int p_port, Shader::Mode p_mode) const {
+ return p_port == 0; // seed
+}
+
+String VisualShaderNodeParticleRandomness::generate_global_per_node(Shader::Mode p_mode, int p_id) const {
String code;
- switch (op_type) {
- case OP_TYPE_SCALAR: {
- code += vformat(" %s = __randf_range(__seed, %s, %s);\n", p_output_vars[0], p_input_vars[0].is_empty() ? (String)get_input_port_default_value(0) : p_input_vars[0], p_input_vars[1].is_empty() ? (String)get_input_port_default_value(1) : p_input_vars[1]);
- } break;
- case OP_TYPE_VECTOR_2D: {
- code += vformat(" %s = __randv2_range(__seed, %s, %s);\n", p_output_vars[0], p_input_vars[0].is_empty() ? (String)get_input_port_default_value(0) : p_input_vars[0], p_input_vars[1].is_empty() ? (String)get_input_port_default_value(1) : p_input_vars[1]);
- } break;
- case OP_TYPE_VECTOR_3D: {
- code += vformat(" %s = __randv3_range(__seed, %s, %s);\n", p_output_vars[0], p_input_vars[0].is_empty() ? (String)get_input_port_default_value(0) : p_input_vars[0], p_input_vars[1].is_empty() ? (String)get_input_port_default_value(1) : p_input_vars[1]);
- } break;
- default:
- break;
- }
+
+ code += "vec2 __randv2_range(inout uint seed, vec2 from, vec2 to) {\n";
+ code += " return vec2(__randf_range(seed, from.x, to.x), __randf_range(seed, from.y, to.y));\n";
+ code += "}\n\n";
+
+ code += "vec3 __randv3_range(inout uint seed, vec3 from, vec3 to) {\n";
+ code += " return vec3(__randf_range(seed, from.x, to.x), __randf_range(seed, from.y, to.y), __randf_range(seed, from.z, to.z));\n";
+ code += "}\n\n";
+
+ code += "vec4 __randv4_range(inout uint seed, vec4 from, vec4 to) {\n";
+ code += " return vec4(__randf_range(seed, from.x, to.x), __randf_range(seed, from.y, to.y), __randf_range(seed, from.z, to.z), __randf_range(seed, from.w, to.w));\n";
+ code += "}\n\n";
+
return code;
}
+String VisualShaderNodeParticleRandomness::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 {
+ static const char *func[(int)OP_TYPE_MAX] = { "__randf_range", "__randv2_range", "__randv3_range", "__randv4_range" };
+ return vformat(" %s = %s(%s, %s, %s);\n", p_output_vars[0], func[op_type], p_input_vars[0].is_empty() ? "__seed" : p_input_vars[0], p_input_vars[1].is_empty() ? (String)get_input_port_default_value(1) : p_input_vars[1], p_input_vars[2].is_empty() ? (String)get_input_port_default_value(2) : p_input_vars[2]);
+}
+
void VisualShaderNodeParticleRandomness::set_op_type(OpType p_op_type) {
ERR_FAIL_INDEX(int(p_op_type), int(OP_TYPE_MAX));
if (op_type == p_op_type) {
@@ -999,16 +1023,20 @@ void VisualShaderNodeParticleRandomness::set_op_type(OpType p_op_type) {
}
switch (p_op_type) {
case OP_TYPE_SCALAR: {
- set_input_port_default_value(0, 0.0, get_input_port_default_value(0));
set_input_port_default_value(1, 0.0, get_input_port_default_value(1));
+ set_input_port_default_value(2, 0.0, get_input_port_default_value(2));
} break;
case OP_TYPE_VECTOR_2D: {
- set_input_port_default_value(0, Vector2(), get_input_port_default_value(0));
set_input_port_default_value(1, Vector2(), get_input_port_default_value(1));
+ set_input_port_default_value(2, Vector2(), get_input_port_default_value(2));
} break;
case OP_TYPE_VECTOR_3D: {
- set_input_port_default_value(0, Vector3(), get_input_port_default_value(0));
set_input_port_default_value(1, Vector3(), get_input_port_default_value(1));
+ set_input_port_default_value(2, Vector3(), get_input_port_default_value(2));
+ } break;
+ case OP_TYPE_VECTOR_4D: {
+ set_input_port_default_value(1, Quaternion(), get_input_port_default_value(1));
+ set_input_port_default_value(2, Quaternion(), get_input_port_default_value(2));
} break;
default:
break;
@@ -1026,8 +1054,8 @@ bool VisualShaderNodeParticleRandomness::has_output_port_preview(int p_port) con
}
VisualShaderNodeParticleRandomness::VisualShaderNodeParticleRandomness() {
- set_input_port_default_value(0, -1.0);
- set_input_port_default_value(1, 1.0);
+ set_input_port_default_value(1, -1.0);
+ set_input_port_default_value(2, 1.0);
}
// VisualShaderNodeParticleAccelerator
diff --git a/scene/resources/visual_shader_particle_nodes.h b/scene/resources/visual_shader_particle_nodes.h
index c0ab974693..08fb059534 100644
--- a/scene/resources/visual_shader_particle_nodes.h
+++ b/scene/resources/visual_shader_particle_nodes.h
@@ -216,6 +216,7 @@ public:
OP_TYPE_SCALAR,
OP_TYPE_VECTOR_2D,
OP_TYPE_VECTOR_3D,
+ OP_TYPE_VECTOR_4D,
OP_TYPE_MAX,
};
@@ -232,12 +233,14 @@ public:
virtual int get_input_port_count() const override;
virtual PortType get_input_port_type(int p_port) const override;
virtual String get_input_port_name(int p_port) const override;
+ virtual bool is_input_port_default(int p_port, Shader::Mode p_mode) const override;
virtual int get_output_port_count() const override;
virtual PortType get_output_port_type(int p_port) const override;
virtual String get_output_port_name(int p_port) const override;
virtual bool has_output_port_preview(int p_port) const override;
+ virtual String generate_global_per_node(Shader::Mode p_mode, int p_id) const override;
virtual String 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 = false) const override;
void set_op_type(OpType p_type);
diff --git a/scene/resources/world_2d.cpp b/scene/resources/world_2d.cpp
index f2ec60e084..c7304da358 100644
--- a/scene/resources/world_2d.cpp
+++ b/scene/resources/world_2d.cpp
@@ -43,10 +43,25 @@ RID World2D::get_canvas() const {
}
RID World2D::get_space() const {
+ if (space.is_null()) {
+ space = PhysicsServer2D::get_singleton()->space_create();
+ PhysicsServer2D::get_singleton()->space_set_active(space, true);
+ PhysicsServer2D::get_singleton()->area_set_param(space, PhysicsServer2D::AREA_PARAM_GRAVITY, GLOBAL_GET("physics/2d/default_gravity"));
+ PhysicsServer2D::get_singleton()->area_set_param(space, PhysicsServer2D::AREA_PARAM_GRAVITY_VECTOR, GLOBAL_GET("physics/2d/default_gravity_vector"));
+ PhysicsServer2D::get_singleton()->area_set_param(space, PhysicsServer2D::AREA_PARAM_LINEAR_DAMP, GLOBAL_GET("physics/2d/default_linear_damp"));
+ PhysicsServer2D::get_singleton()->area_set_param(space, PhysicsServer2D::AREA_PARAM_ANGULAR_DAMP, GLOBAL_GET("physics/2d/default_angular_damp"));
+ }
return space;
}
RID World2D::get_navigation_map() const {
+ if (navigation_map.is_null()) {
+ navigation_map = NavigationServer2D::get_singleton()->map_create();
+ NavigationServer2D::get_singleton()->map_set_active(navigation_map, true);
+ NavigationServer2D::get_singleton()->map_set_cell_size(navigation_map, GLOBAL_GET("navigation/2d/default_cell_size"));
+ NavigationServer2D::get_singleton()->map_set_edge_connection_margin(navigation_map, GLOBAL_GET("navigation/2d/default_edge_connection_margin"));
+ NavigationServer2D::get_singleton()->map_set_link_connection_radius(navigation_map, GLOBAL_GET("navigation/2d/default_link_connection_radius"));
+ }
return navigation_map;
}
@@ -64,28 +79,11 @@ void World2D::_bind_methods() {
}
PhysicsDirectSpaceState2D *World2D::get_direct_space_state() {
- return PhysicsServer2D::get_singleton()->space_get_direct_state(space);
+ return PhysicsServer2D::get_singleton()->space_get_direct_state(get_space());
}
World2D::World2D() {
canvas = RenderingServer::get_singleton()->canvas_create();
-
- // Create and configure space2D to be more friendly with pixels than meters
- space = PhysicsServer2D::get_singleton()->space_create();
- PhysicsServer2D::get_singleton()->space_set_active(space, true);
- PhysicsServer2D::get_singleton()->area_set_param(space, PhysicsServer2D::AREA_PARAM_GRAVITY, GLOBAL_DEF_BASIC("physics/2d/default_gravity", 980.0));
- PhysicsServer2D::get_singleton()->area_set_param(space, PhysicsServer2D::AREA_PARAM_GRAVITY_VECTOR, GLOBAL_DEF_BASIC("physics/2d/default_gravity_vector", Vector2(0, 1)));
- PhysicsServer2D::get_singleton()->area_set_param(space, PhysicsServer2D::AREA_PARAM_LINEAR_DAMP, GLOBAL_DEF("physics/2d/default_linear_damp", 0.1));
- ProjectSettings::get_singleton()->set_custom_property_info("physics/2d/default_linear_damp", PropertyInfo(Variant::FLOAT, "physics/2d/default_linear_damp", PROPERTY_HINT_RANGE, "-1,100,0.001,or_greater"));
- PhysicsServer2D::get_singleton()->area_set_param(space, PhysicsServer2D::AREA_PARAM_ANGULAR_DAMP, GLOBAL_DEF("physics/2d/default_angular_damp", 1.0));
- ProjectSettings::get_singleton()->set_custom_property_info("physics/2d/default_angular_damp", PropertyInfo(Variant::FLOAT, "physics/2d/default_angular_damp", PROPERTY_HINT_RANGE, "-1,100,0.001,or_greater"));
-
- // Create and configure the navigation_map to be more friendly with pixels than meters.
- navigation_map = NavigationServer2D::get_singleton()->map_create();
- NavigationServer2D::get_singleton()->map_set_active(navigation_map, true);
- NavigationServer2D::get_singleton()->map_set_cell_size(navigation_map, GLOBAL_DEF("navigation/2d/default_cell_size", 1));
- NavigationServer2D::get_singleton()->map_set_edge_connection_margin(navigation_map, GLOBAL_DEF("navigation/2d/default_edge_connection_margin", 1));
- NavigationServer2D::get_singleton()->map_set_link_connection_radius(navigation_map, GLOBAL_DEF("navigation/2d/default_link_connection_radius", 4));
}
World2D::~World2D() {
@@ -93,6 +91,10 @@ World2D::~World2D() {
ERR_FAIL_NULL(PhysicsServer2D::get_singleton());
ERR_FAIL_NULL(NavigationServer2D::get_singleton());
RenderingServer::get_singleton()->free(canvas);
- PhysicsServer2D::get_singleton()->free(space);
- NavigationServer2D::get_singleton()->free(navigation_map);
+ if (space.is_valid()) {
+ PhysicsServer2D::get_singleton()->free(space);
+ }
+ if (navigation_map.is_valid()) {
+ NavigationServer2D::get_singleton()->free(navigation_map);
+ }
}
diff --git a/scene/resources/world_2d.h b/scene/resources/world_2d.h
index 92239ed167..0b3b9df7dc 100644
--- a/scene/resources/world_2d.h
+++ b/scene/resources/world_2d.h
@@ -43,8 +43,8 @@ class World2D : public Resource {
GDCLASS(World2D, Resource);
RID canvas;
- RID space;
- RID navigation_map;
+ mutable RID space;
+ mutable RID navigation_map;
HashSet<Viewport *> viewports;
diff --git a/scene/resources/world_3d.cpp b/scene/resources/world_3d.cpp
index 272cc5ef78..82c056d5ee 100644
--- a/scene/resources/world_3d.cpp
+++ b/scene/resources/world_3d.cpp
@@ -51,10 +51,25 @@ void World3D::_remove_camera(Camera3D *p_camera) {
}
RID World3D::get_space() const {
+ if (space.is_null()) {
+ space = PhysicsServer3D::get_singleton()->space_create();
+ PhysicsServer3D::get_singleton()->space_set_active(space, true);
+ PhysicsServer3D::get_singleton()->area_set_param(space, PhysicsServer3D::AREA_PARAM_GRAVITY, GLOBAL_GET("physics/3d/default_gravity"));
+ PhysicsServer3D::get_singleton()->area_set_param(space, PhysicsServer3D::AREA_PARAM_GRAVITY_VECTOR, GLOBAL_GET("physics/3d/default_gravity_vector"));
+ PhysicsServer3D::get_singleton()->area_set_param(space, PhysicsServer3D::AREA_PARAM_LINEAR_DAMP, GLOBAL_GET("physics/3d/default_linear_damp"));
+ PhysicsServer3D::get_singleton()->area_set_param(space, PhysicsServer3D::AREA_PARAM_ANGULAR_DAMP, GLOBAL_GET("physics/3d/default_angular_damp"));
+ }
return space;
}
RID World3D::get_navigation_map() const {
+ if (navigation_map.is_null()) {
+ navigation_map = NavigationServer3D::get_singleton()->map_create();
+ NavigationServer3D::get_singleton()->map_set_active(navigation_map, true);
+ NavigationServer3D::get_singleton()->map_set_cell_size(navigation_map, GLOBAL_GET("navigation/3d/default_cell_size"));
+ NavigationServer3D::get_singleton()->map_set_edge_connection_margin(navigation_map, GLOBAL_GET("navigation/3d/default_edge_connection_margin"));
+ NavigationServer3D::get_singleton()->map_set_link_connection_radius(navigation_map, GLOBAL_GET("navigation/3d/default_link_connection_radius"));
+ }
return navigation_map;
}
@@ -114,7 +129,7 @@ Ref<CameraAttributes> World3D::get_camera_attributes() const {
}
PhysicsDirectSpaceState3D *World3D::get_direct_space_state() {
- return PhysicsServer3D::get_singleton()->space_get_direct_state(space);
+ return PhysicsServer3D::get_singleton()->space_get_direct_state(get_space());
}
void World3D::_bind_methods() {
@@ -138,29 +153,19 @@ void World3D::_bind_methods() {
}
World3D::World3D() {
- space = PhysicsServer3D::get_singleton()->space_create();
scenario = RenderingServer::get_singleton()->scenario_create();
-
- PhysicsServer3D::get_singleton()->space_set_active(space, true);
- PhysicsServer3D::get_singleton()->area_set_param(space, PhysicsServer3D::AREA_PARAM_GRAVITY, GLOBAL_DEF_BASIC("physics/3d/default_gravity", 9.8));
- PhysicsServer3D::get_singleton()->area_set_param(space, PhysicsServer3D::AREA_PARAM_GRAVITY_VECTOR, GLOBAL_DEF_BASIC("physics/3d/default_gravity_vector", Vector3(0, -1, 0)));
- PhysicsServer3D::get_singleton()->area_set_param(space, PhysicsServer3D::AREA_PARAM_LINEAR_DAMP, GLOBAL_DEF("physics/3d/default_linear_damp", 0.1));
- ProjectSettings::get_singleton()->set_custom_property_info("physics/3d/default_linear_damp", PropertyInfo(Variant::FLOAT, "physics/3d/default_linear_damp", PROPERTY_HINT_RANGE, "0,100,0.001,or_greater"));
- PhysicsServer3D::get_singleton()->area_set_param(space, PhysicsServer3D::AREA_PARAM_ANGULAR_DAMP, GLOBAL_DEF("physics/3d/default_angular_damp", 0.1));
- ProjectSettings::get_singleton()->set_custom_property_info("physics/3d/default_angular_damp", PropertyInfo(Variant::FLOAT, "physics/3d/default_angular_damp", PROPERTY_HINT_RANGE, "0,100,0.001,or_greater"));
-
- navigation_map = NavigationServer3D::get_singleton()->map_create();
- NavigationServer3D::get_singleton()->map_set_active(navigation_map, true);
- NavigationServer3D::get_singleton()->map_set_cell_size(navigation_map, GLOBAL_DEF("navigation/3d/default_cell_size", 0.25));
- NavigationServer3D::get_singleton()->map_set_edge_connection_margin(navigation_map, GLOBAL_DEF("navigation/3d/default_edge_connection_margin", 0.25));
- NavigationServer3D::get_singleton()->map_set_link_connection_radius(navigation_map, GLOBAL_DEF("navigation/3d/default_link_connection_radius", 1.0));
}
World3D::~World3D() {
- ERR_FAIL_NULL(PhysicsServer3D::get_singleton());
ERR_FAIL_NULL(RenderingServer::get_singleton());
+ ERR_FAIL_NULL(PhysicsServer3D::get_singleton());
ERR_FAIL_NULL(NavigationServer3D::get_singleton());
- PhysicsServer3D::get_singleton()->free(space);
+
RenderingServer::get_singleton()->free(scenario);
- NavigationServer3D::get_singleton()->free(navigation_map);
+ if (space.is_valid()) {
+ PhysicsServer3D::get_singleton()->free(space);
+ }
+ if (navigation_map.is_valid()) {
+ NavigationServer3D::get_singleton()->free(navigation_map);
+ }
}
diff --git a/scene/resources/world_3d.h b/scene/resources/world_3d.h
index 7cbc9f08c9..518fff64e2 100644
--- a/scene/resources/world_3d.h
+++ b/scene/resources/world_3d.h
@@ -45,9 +45,9 @@ class World3D : public Resource {
GDCLASS(World3D, Resource);
private:
- RID space;
- RID navigation_map;
RID scenario;
+ mutable RID space;
+ mutable RID navigation_map;
Ref<Environment> environment;
Ref<Environment> fallback_environment;
diff --git a/scene/resources/world_boundary_shape_2d.cpp b/scene/resources/world_boundary_shape_2d.cpp
index 49f0873a3e..35cb8ef13d 100644
--- a/scene/resources/world_boundary_shape_2d.cpp
+++ b/scene/resources/world_boundary_shape_2d.cpp
@@ -76,11 +76,12 @@ real_t WorldBoundaryShape2D::get_distance() const {
void WorldBoundaryShape2D::draw(const RID &p_to_rid, const Color &p_color) {
Vector2 point = get_distance() * get_normal();
+ real_t line_width = 3.0;
Vector2 l1[2] = { point - get_normal().orthogonal() * 100, point + get_normal().orthogonal() * 100 };
- RS::get_singleton()->canvas_item_add_line(p_to_rid, l1[0], l1[1], p_color, 3);
- Vector2 l2[2] = { point, point + get_normal() * 30 };
- RS::get_singleton()->canvas_item_add_line(p_to_rid, l2[0], l2[1], p_color, 3);
+ RS::get_singleton()->canvas_item_add_line(p_to_rid, l1[0], l1[1], p_color, line_width);
+ Vector2 l2[2] = { point + get_normal().normalized() * (0.5 * line_width), point + get_normal() * 30 };
+ RS::get_singleton()->canvas_item_add_line(p_to_rid, l2[0], l2[1], p_color, line_width);
}
Rect2 WorldBoundaryShape2D::get_rect() const {
diff --git a/scene/theme/theme_db.cpp b/scene/theme/theme_db.cpp
index 9f55a2a151..9b85a62c6e 100644
--- a/scene/theme/theme_db.cpp
+++ b/scene/theme/theme_db.cpp
@@ -42,29 +42,22 @@
// Default engine theme creation and configuration.
void ThemeDB::initialize_theme() {
// Allow creating the default theme at a different scale to suit higher/lower base resolutions.
- float default_theme_scale = GLOBAL_DEF("gui/theme/default_theme_scale", 1.0);
- ProjectSettings::get_singleton()->set_custom_property_info("gui/theme/default_theme_scale", PropertyInfo(Variant::FLOAT, "gui/theme/default_theme_scale", PROPERTY_HINT_RANGE, "0.5,8,0.01", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED));
+ float default_theme_scale = GLOBAL_DEF(PropertyInfo(Variant::FLOAT, "gui/theme/default_theme_scale", PROPERTY_HINT_RANGE, "0.5,8,0.01", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED), 1.0);
- String theme_path = GLOBAL_DEF_RST("gui/theme/custom", "");
- 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 theme_path = GLOBAL_DEF_RST(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,*.otf,*.ttf,*.woff,*.woff2,*.fnt,*.font,*.pfb,*.pfm", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED));
+ String font_path = GLOBAL_DEF_RST(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));
+ TextServer::FontAntialiasing font_antialiasing = (TextServer::FontAntialiasing)(int)GLOBAL_DEF_RST(PropertyInfo(Variant::INT, "gui/theme/default_font_antialiasing", PROPERTY_HINT_ENUM, "None,Grayscale,LCD Subpixel", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED), 1);
- TextServer::Hinting font_hinting = (TextServer::Hinting)(int)GLOBAL_DEF_RST("gui/theme/default_font_hinting", TextServer::HINTING_LIGHT);
- ProjectSettings::get_singleton()->set_custom_property_info("gui/theme/default_font_hinting", PropertyInfo(Variant::INT, "gui/theme/default_font_hinting", PROPERTY_HINT_ENUM, "None,Light,Normal", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED));
+ TextServer::Hinting font_hinting = (TextServer::Hinting)(int)GLOBAL_DEF_RST(PropertyInfo(Variant::INT, "gui/theme/default_font_hinting", PROPERTY_HINT_ENUM, "None,Light,Normal", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED), TextServer::HINTING_LIGHT);
- TextServer::SubpixelPositioning font_subpixel_positioning = (TextServer::SubpixelPositioning)(int)GLOBAL_DEF_RST("gui/theme/default_font_subpixel_positioning", TextServer::SUBPIXEL_POSITIONING_AUTO);
- ProjectSettings::get_singleton()->set_custom_property_info("gui/theme/default_font_subpixel_positioning", PropertyInfo(Variant::INT, "gui/theme/default_font_subpixel_positioning", PROPERTY_HINT_ENUM, "Disabled,Auto,One Half of a Pixel,One Quarter of a Pixel", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED));
+ TextServer::SubpixelPositioning font_subpixel_positioning = (TextServer::SubpixelPositioning)(int)GLOBAL_DEF_RST(PropertyInfo(Variant::INT, "gui/theme/default_font_subpixel_positioning", PROPERTY_HINT_ENUM, "Disabled,Auto,One Half of a Pixel,One Quarter of a Pixel", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED), TextServer::SUBPIXEL_POSITIONING_AUTO);
const bool font_msdf = GLOBAL_DEF_RST("gui/theme/default_font_multichannel_signed_distance_field", false);
const bool font_generate_mipmaps = GLOBAL_DEF_RST("gui/theme/default_font_generate_mipmaps", false);
- GLOBAL_DEF_RST("gui/theme/lcd_subpixel_layout", 1);
- ProjectSettings::get_singleton()->set_custom_property_info("gui/theme/lcd_subpixel_layout", PropertyInfo(Variant::INT, "gui/theme/lcd_subpixel_layout", PROPERTY_HINT_ENUM, "Disabled,Horizontal RGB,Horizontal BGR,Vertical RGB,Vertical BGR"));
+ GLOBAL_DEF_RST(PropertyInfo(Variant::INT, "gui/theme/lcd_subpixel_layout", PROPERTY_HINT_ENUM, "Disabled,Horizontal RGB,Horizontal BGR,Vertical RGB,Vertical BGR"), 1);
ProjectSettings::get_singleton()->set_restart_if_changed("gui/theme/lcd_subpixel_layout", false);
Ref<Font> font;