summaryrefslogtreecommitdiff
path: root/scene/3d
diff options
context:
space:
mode:
Diffstat (limited to 'scene/3d')
-rw-r--r--scene/3d/SCsub6
-rw-r--r--scene/3d/area_3d.cpp244
-rw-r--r--scene/3d/area_3d.h51
-rw-r--r--scene/3d/audio_listener_3d.cpp (renamed from scene/3d/listener_3d.cpp)76
-rw-r--r--scene/3d/audio_listener_3d.h (renamed from scene/3d/listener_3d.h)23
-rw-r--r--scene/3d/audio_stream_player_3d.cpp810
-rw-r--r--scene/3d/audio_stream_player_3d.h72
-rw-r--r--scene/3d/bone_attachment_3d.cpp323
-rw-r--r--scene/3d/bone_attachment_3d.h42
-rw-r--r--scene/3d/camera_3d.cpp432
-rw-r--r--scene/3d/camera_3d.h132
-rw-r--r--scene/3d/collision_object_3d.cpp272
-rw-r--r--scene/3d/collision_object_3d.h54
-rw-r--r--scene/3d/collision_polygon_3d.cpp20
-rw-r--r--scene/3d/collision_polygon_3d.h4
-rw-r--r--scene/3d/collision_shape_3d.cpp35
-rw-r--r--scene/3d/collision_shape_3d.h8
-rw-r--r--scene/3d/cpu_particles_3d.cpp712
-rw-r--r--scene/3d/cpu_particles_3d.h138
-rw-r--r--scene/3d/decal.cpp65
-rw-r--r--scene/3d/decal.h51
-rw-r--r--scene/3d/fog_volume.cpp122
-rw-r--r--scene/3d/fog_volume.h (renamed from scene/3d/immediate_geometry_3d.h)57
-rw-r--r--scene/3d/gpu_particles_3d.cpp153
-rw-r--r--scene/3d/gpu_particles_3d.h62
-rw-r--r--scene/3d/gpu_particles_collision_3d.cpp344
-rw-r--r--scene/3d/gpu_particles_collision_3d.h104
-rw-r--r--scene/3d/immediate_geometry_3d.cpp157
-rw-r--r--scene/3d/importer_mesh_instance_3d.cpp85
-rw-r--r--scene/3d/importer_mesh_instance_3d.h (renamed from scene/3d/proximity_group_3d.h)69
-rw-r--r--scene/3d/joint_3d.cpp (renamed from scene/3d/physics_joint_3d.cpp)100
-rw-r--r--scene/3d/joint_3d.h (renamed from scene/3d/physics_joint_3d.h)12
-rw-r--r--scene/3d/label_3d.cpp1010
-rw-r--r--scene/3d/label_3d.h240
-rw-r--r--scene/3d/light_3d.cpp221
-rw-r--r--scene/3d/light_3d.h58
-rw-r--r--scene/3d/lightmap_gi.cpp (renamed from scene/3d/baked_lightmap.cpp)336
-rw-r--r--scene/3d/lightmap_gi.h (renamed from scene/3d/baked_lightmap.h)46
-rw-r--r--scene/3d/lightmap_probe.cpp4
-rw-r--r--scene/3d/lightmap_probe.h4
-rw-r--r--scene/3d/lightmapper.cpp4
-rw-r--r--scene/3d/lightmapper.h21
-rw-r--r--scene/3d/mesh_instance_3d.cpp145
-rw-r--r--scene/3d/mesh_instance_3d.h28
-rw-r--r--scene/3d/multimesh_instance_3d.cpp8
-rw-r--r--scene/3d/multimesh_instance_3d.h6
-rw-r--r--scene/3d/navigation_agent_3d.cpp51
-rw-r--r--scene/3d/navigation_agent_3d.h27
-rw-r--r--scene/3d/navigation_obstacle_3d.cpp78
-rw-r--r--scene/3d/navigation_obstacle_3d.h22
-rw-r--r--scene/3d/navigation_region_3d.cpp43
-rw-r--r--scene/3d/navigation_region_3d.h11
-rw-r--r--scene/3d/node_3d.cpp587
-rw-r--r--scene/3d/node_3d.h129
-rw-r--r--scene/3d/occluder_instance_3d.cpp609
-rw-r--r--scene/3d/occluder_instance_3d.h140
-rw-r--r--scene/3d/path_3d.cpp75
-rw-r--r--scene/3d/path_3d.h21
-rw-r--r--scene/3d/physics_body_3d.cpp2185
-rw-r--r--scene/3d/physics_body_3d.h440
-rw-r--r--scene/3d/position_3d.cpp5
-rw-r--r--scene/3d/position_3d.h4
-rw-r--r--scene/3d/proximity_group_3d.cpp185
-rw-r--r--scene/3d/ray_cast_3d.cpp104
-rw-r--r--scene/3d/ray_cast_3d.h27
-rw-r--r--scene/3d/reflection_probe.cpp41
-rw-r--r--scene/3d/reflection_probe.h16
-rw-r--r--scene/3d/remote_transform_3d.cpp23
-rw-r--r--scene/3d/remote_transform_3d.h4
-rw-r--r--scene/3d/skeleton_3d.cpp980
-rw-r--r--scene/3d/skeleton_3d.h188
-rw-r--r--scene/3d/skeleton_ik_3d.cpp69
-rw-r--r--scene/3d/skeleton_ik_3d.h38
-rw-r--r--scene/3d/soft_dynamic_body_3d.cpp (renamed from scene/3d/soft_body_3d.cpp)440
-rw-r--r--scene/3d/soft_dynamic_body_3d.h (renamed from scene/3d/soft_body_3d.h)71
-rw-r--r--scene/3d/spring_arm_3d.cpp87
-rw-r--r--scene/3d/spring_arm_3d.h4
-rw-r--r--scene/3d/sprite_3d.cpp468
-rw-r--r--scene/3d/sprite_3d.h82
-rw-r--r--scene/3d/vehicle_body_3d.cpp132
-rw-r--r--scene/3d/vehicle_body_3d.h17
-rw-r--r--scene/3d/velocity_tracker_3d.cpp17
-rw-r--r--scene/3d/velocity_tracker_3d.h8
-rw-r--r--scene/3d/visibility_notifier_3d.cpp253
-rw-r--r--scene/3d/visible_on_screen_notifier_3d.cpp200
-rw-r--r--scene/3d/visible_on_screen_notifier_3d.h (renamed from scene/3d/visibility_notifier_3d.h)70
-rw-r--r--scene/3d/visual_instance_3d.cpp213
-rw-r--r--scene/3d/visual_instance_3d.h65
-rw-r--r--scene/3d/voxel_gi.cpp (renamed from scene/3d/gi_probe.cpp)289
-rw-r--r--scene/3d/voxel_gi.h (renamed from scene/3d/gi_probe.h)63
-rw-r--r--scene/3d/voxelizer.cpp104
-rw-r--r--scene/3d/voxelizer.h24
-rw-r--r--scene/3d/world_environment.cpp58
-rw-r--r--scene/3d/world_environment.h6
-rw-r--r--scene/3d/xr_nodes.cpp678
-rw-r--r--scene/3d/xr_nodes.h127
96 files changed, 10497 insertions, 6047 deletions
diff --git a/scene/3d/SCsub b/scene/3d/SCsub
index ce69e8aa19..fc61250247 100644
--- a/scene/3d/SCsub
+++ b/scene/3d/SCsub
@@ -2,8 +2,4 @@
Import("env")
-if env["disable_3d"]:
- env.add_source_files(env.scene_sources, "node_3d.cpp")
- env.add_source_files(env.scene_sources, "skeleton_3d.cpp")
-else:
- env.add_source_files(env.scene_sources, "*.cpp")
+env.add_source_files(env.scene_sources, "*.cpp")
diff --git a/scene/3d/area_3d.cpp b/scene/3d/area_3d.cpp
index 44708cddff..fb37e64a1a 100644
--- a/scene/3d/area_3d.cpp
+++ b/scene/3d/area_3d.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -32,15 +32,14 @@
#include "scene/scene_string_names.h"
#include "servers/audio_server.h"
-#include "servers/physics_server_3d.h"
-void Area3D::set_space_override_mode(SpaceOverride p_mode) {
- space_override = p_mode;
- PhysicsServer3D::get_singleton()->area_set_space_override_mode(get_rid(), PhysicsServer3D::AreaSpaceOverrideMode(p_mode));
+void Area3D::set_gravity_space_override_mode(SpaceOverride p_mode) {
+ gravity_space_override = p_mode;
+ PhysicsServer3D::get_singleton()->area_set_param(get_rid(), PhysicsServer3D::AREA_PARAM_GRAVITY_OVERRIDE_MODE, p_mode);
}
-Area3D::SpaceOverride Area3D::get_space_override_mode() const {
- return space_override;
+Area3D::SpaceOverride Area3D::get_gravity_space_override_mode() const {
+ return gravity_space_override;
}
void Area3D::set_gravity_is_point(bool p_enabled) {
@@ -52,21 +51,30 @@ bool Area3D::is_gravity_a_point() const {
return gravity_is_point;
}
-void Area3D::set_gravity_distance_scale(real_t p_scale) {
+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);
}
-real_t Area3D::get_gravity_distance_scale() const {
+real_t Area3D::get_gravity_point_distance_scale() const {
return gravity_distance_scale;
}
-void Area3D::set_gravity_vector(const Vector3 &p_vec) {
- gravity_vec = p_vec;
- PhysicsServer3D::get_singleton()->area_set_param(get_rid(), PhysicsServer3D::AREA_PARAM_GRAVITY_VECTOR, p_vec);
+void Area3D::set_gravity_point_center(const Vector3 &p_center) {
+ gravity_vec = p_center;
+ PhysicsServer3D::get_singleton()->area_set_param(get_rid(), PhysicsServer3D::AREA_PARAM_GRAVITY_VECTOR, p_center);
}
-Vector3 Area3D::get_gravity_vector() const {
+const Vector3 &Area3D::get_gravity_point_center() const {
+ return gravity_vec;
+}
+
+void Area3D::set_gravity_direction(const Vector3 &p_direction) {
+ gravity_vec = p_direction;
+ PhysicsServer3D::get_singleton()->area_set_param(get_rid(), PhysicsServer3D::AREA_PARAM_GRAVITY_VECTOR, p_direction);
+}
+
+const Vector3 &Area3D::get_gravity_direction() const {
return gravity_vec;
}
@@ -79,6 +87,24 @@ real_t Area3D::get_gravity() const {
return gravity;
}
+void Area3D::set_linear_damp_space_override_mode(SpaceOverride p_mode) {
+ linear_damp_space_override = p_mode;
+ PhysicsServer3D::get_singleton()->area_set_param(get_rid(), PhysicsServer3D::AREA_PARAM_LINEAR_DAMP_OVERRIDE_MODE, p_mode);
+}
+
+Area3D::SpaceOverride Area3D::get_linear_damp_space_override_mode() const {
+ return linear_damp_space_override;
+}
+
+void Area3D::set_angular_damp_space_override_mode(SpaceOverride p_mode) {
+ angular_damp_space_override = p_mode;
+ PhysicsServer3D::get_singleton()->area_set_param(get_rid(), PhysicsServer3D::AREA_PARAM_ANGULAR_DAMP_OVERRIDE_MODE, p_mode);
+}
+
+Area3D::SpaceOverride Area3D::get_angular_damp_space_override_mode() const {
+ return angular_damp_space_override;
+}
+
void Area3D::set_linear_damp(real_t p_linear_damp) {
linear_damp = p_linear_damp;
PhysicsServer3D::get_singleton()->area_set_param(get_rid(), PhysicsServer3D::AREA_PARAM_LINEAR_DAMP, p_linear_damp);
@@ -106,6 +132,61 @@ real_t Area3D::get_priority() const {
return priority;
}
+void Area3D::set_wind_force_magnitude(real_t p_wind_force_magnitude) {
+ wind_force_magnitude = p_wind_force_magnitude;
+ if (is_inside_tree()) {
+ _initialize_wind();
+ }
+}
+
+real_t Area3D::get_wind_force_magnitude() const {
+ return wind_force_magnitude;
+}
+
+void Area3D::set_wind_attenuation_factor(real_t p_wind_force_attenuation_factor) {
+ wind_attenuation_factor = p_wind_force_attenuation_factor;
+ if (is_inside_tree()) {
+ _initialize_wind();
+ }
+}
+
+real_t Area3D::get_wind_attenuation_factor() const {
+ return wind_attenuation_factor;
+}
+
+void Area3D::set_wind_source_path(const NodePath &p_wind_source_path) {
+ wind_source_path = p_wind_source_path;
+ if (is_inside_tree()) {
+ _initialize_wind();
+ }
+}
+
+const NodePath &Area3D::get_wind_source_path() const {
+ return wind_source_path;
+}
+
+void Area3D::_initialize_wind() {
+ real_t temp_magnitude = 0.0;
+ Vector3 wind_direction(0., 0., 0.);
+ Vector3 wind_source(0., 0., 0.);
+
+ // Overwrite with area-specified info if available
+ if (!wind_source_path.is_empty()) {
+ Node3D *p_wind_source = Object::cast_to<Node3D>(get_node(wind_source_path));
+ ERR_FAIL_NULL(p_wind_source);
+ Transform3D global_transform = p_wind_source->get_transform();
+ wind_direction = -global_transform.basis.get_column(Vector3::AXIS_Z).normalized();
+ wind_source = global_transform.origin;
+ temp_magnitude = wind_force_magnitude;
+ }
+
+ // Set force, source and direction in the physics server.
+ PhysicsServer3D::get_singleton()->area_set_param(get_rid(), PhysicsServer3D::AREA_PARAM_WIND_ATTENUATION_FACTOR, wind_attenuation_factor);
+ PhysicsServer3D::get_singleton()->area_set_param(get_rid(), PhysicsServer3D::AREA_PARAM_WIND_SOURCE, wind_source);
+ PhysicsServer3D::get_singleton()->area_set_param(get_rid(), PhysicsServer3D::AREA_PARAM_WIND_DIRECTION, wind_direction);
+ PhysicsServer3D::get_singleton()->area_set_param(get_rid(), PhysicsServer3D::AREA_PARAM_WIND_FORCE_MAGNITUDE, temp_magnitude);
+}
+
void Area3D::_body_enter_tree(ObjectID p_id) {
Object *obj = ObjectDB::get_instance(p_id);
Node *node = Object::cast_to<Node>(obj);
@@ -208,8 +289,8 @@ void Area3D::_clear_monitoring() {
body_map.clear();
//disconnect all monitored stuff
- for (Map<ObjectID, BodyState>::Element *E = bmcopy.front(); E; E = E->next()) {
- Object *obj = ObjectDB::get_instance(E->key());
+ for (const KeyValue<ObjectID, BodyState> &E : bmcopy) {
+ Object *obj = ObjectDB::get_instance(E.key);
Node *node = Object::cast_to<Node>(obj);
if (!node) { //node may have been deleted in previous frame or at other legitimate point
@@ -220,12 +301,12 @@ void Area3D::_clear_monitoring() {
node->disconnect(SceneStringNames::get_singleton()->tree_entered, callable_mp(this, &Area3D::_body_enter_tree));
node->disconnect(SceneStringNames::get_singleton()->tree_exiting, callable_mp(this, &Area3D::_body_exit_tree));
- if (!E->get().in_tree) {
+ if (!E.value.in_tree) {
continue;
}
- for (int i = 0; i < E->get().shapes.size(); i++) {
- emit_signal(SceneStringNames::get_singleton()->body_shape_exited, E->get().rid, node, E->get().shapes[i].body_shape, E->get().shapes[i].area_shape);
+ for (int i = 0; i < E.value.shapes.size(); i++) {
+ emit_signal(SceneStringNames::get_singleton()->body_shape_exited, E.value.rid, node, E.value.shapes[i].body_shape, E.value.shapes[i].area_shape);
}
emit_signal(SceneStringNames::get_singleton()->body_exited, node);
@@ -237,8 +318,8 @@ void Area3D::_clear_monitoring() {
area_map.clear();
//disconnect all monitored stuff
- for (Map<ObjectID, AreaState>::Element *E = bmcopy.front(); E; E = E->next()) {
- Object *obj = ObjectDB::get_instance(E->key());
+ for (const KeyValue<ObjectID, AreaState> &E : bmcopy) {
+ Object *obj = ObjectDB::get_instance(E.key);
Node *node = Object::cast_to<Node>(obj);
if (!node) { //node may have been deleted in previous frame or at other legitimate point
@@ -249,12 +330,12 @@ void Area3D::_clear_monitoring() {
node->disconnect(SceneStringNames::get_singleton()->tree_entered, callable_mp(this, &Area3D::_area_enter_tree));
node->disconnect(SceneStringNames::get_singleton()->tree_exiting, callable_mp(this, &Area3D::_area_exit_tree));
- if (!E->get().in_tree) {
+ if (!E.value.in_tree) {
continue;
}
- for (int i = 0; i < E->get().shapes.size(); i++) {
- emit_signal(SceneStringNames::get_singleton()->area_shape_exited, E->get().rid, node, E->get().shapes[i].area_shape, E->get().shapes[i].self_shape);
+ for (int i = 0; i < E.value.shapes.size(); i++) {
+ emit_signal(SceneStringNames::get_singleton()->area_shape_exited, E.value.rid, node, E.value.shapes[i].area_shape, E.value.shapes[i].self_shape);
}
emit_signal(SceneStringNames::get_singleton()->area_exited, obj);
@@ -263,8 +344,14 @@ void Area3D::_clear_monitoring() {
}
void Area3D::_notification(int p_what) {
- if (p_what == NOTIFICATION_EXIT_TREE) {
- _clear_monitoring();
+ switch (p_what) {
+ case NOTIFICATION_EXIT_TREE: {
+ _clear_monitoring();
+ } break;
+
+ case NOTIFICATION_ENTER_TREE: {
+ _initialize_wind();
+ } break;
}
}
@@ -278,11 +365,11 @@ void Area3D::set_monitoring(bool p_enable) {
monitoring = p_enable;
if (monitoring) {
- PhysicsServer3D::get_singleton()->area_set_monitor_callback(get_rid(), this, SceneStringNames::get_singleton()->_body_inout);
- PhysicsServer3D::get_singleton()->area_set_area_monitor_callback(get_rid(), this, SceneStringNames::get_singleton()->_area_inout);
+ PhysicsServer3D::get_singleton()->area_set_monitor_callback(get_rid(), callable_mp(this, &Area3D::_body_inout));
+ PhysicsServer3D::get_singleton()->area_set_area_monitor_callback(get_rid(), callable_mp(this, &Area3D::_area_inout));
} else {
- PhysicsServer3D::get_singleton()->area_set_monitor_callback(get_rid(), nullptr, StringName());
- PhysicsServer3D::get_singleton()->area_set_area_monitor_callback(get_rid(), nullptr, StringName());
+ PhysicsServer3D::get_singleton()->area_set_monitor_callback(get_rid(), Callable());
+ PhysicsServer3D::get_singleton()->area_set_area_monitor_callback(get_rid(), Callable());
_clear_monitoring();
}
}
@@ -390,8 +477,8 @@ TypedArray<Node3D> Area3D::get_overlapping_bodies() const {
Array ret;
ret.resize(body_map.size());
int idx = 0;
- for (const Map<ObjectID, BodyState>::Element *E = body_map.front(); E; E = E->next()) {
- Object *obj = ObjectDB::get_instance(E->key());
+ for (const KeyValue<ObjectID, BodyState> &E : body_map) {
+ Object *obj = ObjectDB::get_instance(E.key);
if (!obj) {
ret.resize(ret.size() - 1); //ops
} else {
@@ -423,8 +510,8 @@ TypedArray<Area3D> Area3D::get_overlapping_areas() const {
Array ret;
ret.resize(area_map.size());
int idx = 0;
- for (const Map<ObjectID, AreaState>::Element *E = area_map.front(); E; E = E->next()) {
- Object *obj = ObjectDB::get_instance(E->key());
+ for (const KeyValue<ObjectID, AreaState> &E : area_map) {
+ Object *obj = ObjectDB::get_instance(E.key);
if (!obj) {
ret.resize(ret.size() - 1); //ops
} else {
@@ -523,25 +610,58 @@ void Area3D::_validate_property(PropertyInfo &property) const {
}
property.hint_string = options;
+ } else if (property.name.begins_with("gravity") && property.name != "gravity_space_override") {
+ if (gravity_space_override == SPACE_OVERRIDE_DISABLED) {
+ property.usage = PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL;
+ } else {
+ if (gravity_is_point) {
+ if (property.name == "gravity_direction") {
+ property.usage = PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL;
+ }
+ } else {
+ if (property.name.begins_with("gravity_point_")) {
+ property.usage = PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL;
+ }
+ }
+ }
+ } else if (property.name.begins_with("linear_damp") && property.name != "linear_damp_space_override") {
+ if (linear_damp_space_override == SPACE_OVERRIDE_DISABLED) {
+ property.usage = PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL;
+ }
+ } else if (property.name.begins_with("angular_damp") && property.name != "angular_damp_space_override") {
+ if (angular_damp_space_override == SPACE_OVERRIDE_DISABLED) {
+ property.usage = PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL;
+ }
}
+
+ CollisionObject3D::_validate_property(property);
}
void Area3D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_space_override_mode", "enable"), &Area3D::set_space_override_mode);
- ClassDB::bind_method(D_METHOD("get_space_override_mode"), &Area3D::get_space_override_mode);
+ ClassDB::bind_method(D_METHOD("set_gravity_space_override_mode", "space_override_mode"), &Area3D::set_gravity_space_override_mode);
+ ClassDB::bind_method(D_METHOD("get_gravity_space_override_mode"), &Area3D::get_gravity_space_override_mode);
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_distance_scale", "distance_scale"), &Area3D::set_gravity_distance_scale);
- ClassDB::bind_method(D_METHOD("get_gravity_distance_scale"), &Area3D::get_gravity_distance_scale);
+ 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_center", "center"), &Area3D::set_gravity_point_center);
+ ClassDB::bind_method(D_METHOD("get_gravity_point_center"), &Area3D::get_gravity_point_center);
- ClassDB::bind_method(D_METHOD("set_gravity_vector", "vector"), &Area3D::set_gravity_vector);
- ClassDB::bind_method(D_METHOD("get_gravity_vector"), &Area3D::get_gravity_vector);
+ ClassDB::bind_method(D_METHOD("set_gravity_direction", "direction"), &Area3D::set_gravity_direction);
+ ClassDB::bind_method(D_METHOD("get_gravity_direction"), &Area3D::get_gravity_direction);
ClassDB::bind_method(D_METHOD("set_gravity", "gravity"), &Area3D::set_gravity);
ClassDB::bind_method(D_METHOD("get_gravity"), &Area3D::get_gravity);
+ ClassDB::bind_method(D_METHOD("set_linear_damp_space_override_mode", "space_override_mode"), &Area3D::set_linear_damp_space_override_mode);
+ ClassDB::bind_method(D_METHOD("get_linear_damp_space_override_mode"), &Area3D::get_linear_damp_space_override_mode);
+
+ ClassDB::bind_method(D_METHOD("set_angular_damp_space_override_mode", "space_override_mode"), &Area3D::set_angular_damp_space_override_mode);
+ ClassDB::bind_method(D_METHOD("get_angular_damp_space_override_mode"), &Area3D::get_angular_damp_space_override_mode);
+
ClassDB::bind_method(D_METHOD("set_angular_damp", "angular_damp"), &Area3D::set_angular_damp);
ClassDB::bind_method(D_METHOD("get_angular_damp"), &Area3D::get_angular_damp);
@@ -551,6 +671,15 @@ void Area3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_priority", "priority"), &Area3D::set_priority);
ClassDB::bind_method(D_METHOD("get_priority"), &Area3D::get_priority);
+ ClassDB::bind_method(D_METHOD("set_wind_force_magnitude", "wind_force_magnitude"), &Area3D::set_wind_force_magnitude);
+ ClassDB::bind_method(D_METHOD("get_wind_force_magnitude"), &Area3D::get_wind_force_magnitude);
+
+ ClassDB::bind_method(D_METHOD("set_wind_attenuation_factor", "wind_attenuation_factor"), &Area3D::set_wind_attenuation_factor);
+ ClassDB::bind_method(D_METHOD("get_wind_attenuation_factor"), &Area3D::get_wind_attenuation_factor);
+
+ ClassDB::bind_method(D_METHOD("set_wind_source_path", "wind_source_path"), &Area3D::set_wind_source_path);
+ ClassDB::bind_method(D_METHOD("get_wind_source_path"), &Area3D::get_wind_source_path);
+
ClassDB::bind_method(D_METHOD("set_monitorable", "enable"), &Area3D::set_monitorable);
ClassDB::bind_method(D_METHOD("is_monitorable"), &Area3D::is_monitorable);
@@ -563,9 +692,6 @@ void Area3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("overlaps_body", "body"), &Area3D::overlaps_body);
ClassDB::bind_method(D_METHOD("overlaps_area", "area"), &Area3D::overlaps_area);
- ClassDB::bind_method(D_METHOD("_body_inout"), &Area3D::_body_inout);
- ClassDB::bind_method(D_METHOD("_area_inout"), &Area3D::_area_inout);
-
ClassDB::bind_method(D_METHOD("set_audio_bus_override", "enable"), &Area3D::set_audio_bus_override);
ClassDB::bind_method(D_METHOD("is_overriding_audio_bus"), &Area3D::is_overriding_audio_bus);
@@ -584,13 +710,13 @@ void Area3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_reverb_uniformity", "amount"), &Area3D::set_reverb_uniformity);
ClassDB::bind_method(D_METHOD("get_reverb_uniformity"), &Area3D::get_reverb_uniformity);
- ADD_SIGNAL(MethodInfo("body_shape_entered", PropertyInfo(Variant::RID, "body_rid"), PropertyInfo(Variant::OBJECT, "body", PROPERTY_HINT_RESOURCE_TYPE, "Node3D"), PropertyInfo(Variant::INT, "body_shape"), PropertyInfo(Variant::INT, "local_shape")));
- ADD_SIGNAL(MethodInfo("body_shape_exited", PropertyInfo(Variant::RID, "body_rid"), PropertyInfo(Variant::OBJECT, "body", PROPERTY_HINT_RESOURCE_TYPE, "Node3D"), PropertyInfo(Variant::INT, "body_shape"), PropertyInfo(Variant::INT, "local_shape")));
+ ADD_SIGNAL(MethodInfo("body_shape_entered", PropertyInfo(Variant::RID, "body_rid"), PropertyInfo(Variant::OBJECT, "body", PROPERTY_HINT_RESOURCE_TYPE, "Node3D"), PropertyInfo(Variant::INT, "body_shape_index"), PropertyInfo(Variant::INT, "local_shape_index")));
+ ADD_SIGNAL(MethodInfo("body_shape_exited", PropertyInfo(Variant::RID, "body_rid"), PropertyInfo(Variant::OBJECT, "body", PROPERTY_HINT_RESOURCE_TYPE, "Node3D"), PropertyInfo(Variant::INT, "body_shape_index"), PropertyInfo(Variant::INT, "local_shape_index")));
ADD_SIGNAL(MethodInfo("body_entered", PropertyInfo(Variant::OBJECT, "body", PROPERTY_HINT_RESOURCE_TYPE, "Node3D")));
ADD_SIGNAL(MethodInfo("body_exited", PropertyInfo(Variant::OBJECT, "body", PROPERTY_HINT_RESOURCE_TYPE, "Node3D")));
- ADD_SIGNAL(MethodInfo("area_shape_entered", PropertyInfo(Variant::RID, "area_rid"), PropertyInfo(Variant::OBJECT, "area", PROPERTY_HINT_RESOURCE_TYPE, "Area3D"), PropertyInfo(Variant::INT, "area_shape"), PropertyInfo(Variant::INT, "local_shape")));
- ADD_SIGNAL(MethodInfo("area_shape_exited", PropertyInfo(Variant::RID, "area_rid"), PropertyInfo(Variant::OBJECT, "area", PROPERTY_HINT_RESOURCE_TYPE, "Area3D"), PropertyInfo(Variant::INT, "area_shape"), PropertyInfo(Variant::INT, "local_shape")));
+ ADD_SIGNAL(MethodInfo("area_shape_entered", PropertyInfo(Variant::RID, "area_rid"), PropertyInfo(Variant::OBJECT, "area", PROPERTY_HINT_RESOURCE_TYPE, "Area3D"), PropertyInfo(Variant::INT, "area_shape_index"), PropertyInfo(Variant::INT, "local_shape_index")));
+ ADD_SIGNAL(MethodInfo("area_shape_exited", PropertyInfo(Variant::RID, "area_rid"), PropertyInfo(Variant::OBJECT, "area", PROPERTY_HINT_RESOURCE_TYPE, "Area3D"), PropertyInfo(Variant::INT, "area_shape_index"), PropertyInfo(Variant::INT, "local_shape_index")));
ADD_SIGNAL(MethodInfo("area_entered", PropertyInfo(Variant::OBJECT, "area", PROPERTY_HINT_RESOURCE_TYPE, "Area3D")));
ADD_SIGNAL(MethodInfo("area_exited", PropertyInfo(Variant::OBJECT, "area", PROPERTY_HINT_RESOURCE_TYPE, "Area3D")));
@@ -598,15 +724,27 @@ void Area3D::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "monitorable"), "set_monitorable", "is_monitorable");
ADD_PROPERTY(PropertyInfo(Variant::INT, "priority", PROPERTY_HINT_RANGE, "0,128,1"), "set_priority", "get_priority");
- ADD_GROUP("Physics Overrides", "");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "space_override", PROPERTY_HINT_ENUM, "Disabled,Combine,Combine-Replace,Replace,Replace-Combine"), "set_space_override_mode", "get_space_override_mode");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL, "gravity_point"), "set_gravity_is_point", "is_gravity_a_point");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "gravity_distance_scale", PROPERTY_HINT_EXP_RANGE, "0,1024,0.001,or_greater"), "set_gravity_distance_scale", "get_gravity_distance_scale");
- ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "gravity_vec"), "set_gravity_vector", "get_gravity_vector");
+ 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::VECTOR3, "gravity_point_center"), "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, "-32,32,0.001,or_lesser,or_greater"), "set_gravity", "get_gravity");
+
+ ADD_GROUP("Linear Damp", "linear_damp_");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "linear_damp_space_override", PROPERTY_HINT_ENUM, "Disabled,Combine,Combine-Replace,Replace,Replace-Combine", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), "set_linear_damp_space_override_mode", "get_linear_damp_space_override_mode");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "linear_damp", PROPERTY_HINT_RANGE, "0,100,0.001,or_greater"), "set_linear_damp", "get_linear_damp");
+
+ ADD_GROUP("Angular Damp", "angular_damp_");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "angular_damp_space_override", PROPERTY_HINT_ENUM, "Disabled,Combine,Combine-Replace,Replace,Replace-Combine", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), "set_angular_damp_space_override_mode", "get_angular_damp_space_override_mode");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "angular_damp", PROPERTY_HINT_RANGE, "0,100,0.001,or_greater"), "set_angular_damp", "get_angular_damp");
+ ADD_GROUP("Wind", "wind_");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "wind_force_magnitude", PROPERTY_HINT_RANGE, "0,10,0.001,or_greater"), "set_wind_force_magnitude", "get_wind_force_magnitude");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "wind_attenuation_factor", PROPERTY_HINT_RANGE, "0.0,3.0,0.001,or_greater"), "set_wind_attenuation_factor", "get_wind_attenuation_factor");
+ ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "wind_source_path", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Node3D"), "set_wind_source_path", "get_wind_source_path");
+
ADD_GROUP("Audio Bus", "audio_bus_");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "audio_bus_override"), "set_audio_bus_override", "is_overriding_audio_bus");
ADD_PROPERTY(PropertyInfo(Variant::STRING_NAME, "audio_bus_name", PROPERTY_HINT_ENUM, ""), "set_audio_bus_name", "get_audio_bus_name");
@@ -627,7 +765,7 @@ void Area3D::_bind_methods() {
Area3D::Area3D() :
CollisionObject3D(PhysicsServer3D::get_singleton()->area_create(), true) {
set_gravity(9.8);
- set_gravity_vector(Vector3(0, -1, 0));
+ set_gravity_direction(Vector3(0, -1, 0));
set_monitoring(true);
set_monitorable(true);
}
diff --git a/scene/3d/area_3d.h b/scene/3d/area_3d.h
index 5b8d612717..31ded00fb7 100644
--- a/scene/3d/area_3d.h
+++ b/scene/3d/area_3d.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -47,14 +47,23 @@ public:
};
private:
- SpaceOverride space_override = SPACE_OVERRIDE_DISABLED;
+ SpaceOverride gravity_space_override = SPACE_OVERRIDE_DISABLED;
Vector3 gravity_vec;
- real_t gravity;
+ real_t gravity = 0.0;
bool gravity_is_point = false;
real_t gravity_distance_scale = 0.0;
+
+ SpaceOverride linear_damp_space_override = SPACE_OVERRIDE_DISABLED;
+ SpaceOverride angular_damp_space_override = SPACE_OVERRIDE_DISABLED;
real_t angular_damp = 0.1;
real_t linear_damp = 0.1;
+
int priority = 0;
+
+ real_t wind_force_magnitude = 0.0;
+ real_t wind_attenuation_factor = 0.0;
+ NodePath wind_source_path;
+
bool monitoring = false;
bool monitorable = false;
bool locked = false;
@@ -134,26 +143,37 @@ private:
void _validate_property(PropertyInfo &property) const override;
+ void _initialize_wind();
+
protected:
void _notification(int p_what);
static void _bind_methods();
public:
- void set_space_override_mode(SpaceOverride p_mode);
- SpaceOverride get_space_override_mode() const;
+ void set_gravity_space_override_mode(SpaceOverride p_mode);
+ SpaceOverride get_gravity_space_override_mode() const;
void set_gravity_is_point(bool p_enabled);
bool is_gravity_a_point() const;
- void set_gravity_distance_scale(real_t p_scale);
- real_t get_gravity_distance_scale() const;
+ void set_gravity_point_distance_scale(real_t p_scale);
+ real_t get_gravity_point_distance_scale() const;
+
+ void set_gravity_point_center(const Vector3 &p_center);
+ const Vector3 &get_gravity_point_center() const;
- void set_gravity_vector(const Vector3 &p_vec);
- Vector3 get_gravity_vector() const;
+ void set_gravity_direction(const Vector3 &p_direction);
+ const Vector3 &get_gravity_direction() const;
void set_gravity(real_t p_gravity);
real_t get_gravity() const;
+ void set_linear_damp_space_override_mode(SpaceOverride p_mode);
+ SpaceOverride get_linear_damp_space_override_mode() const;
+
+ void set_angular_damp_space_override_mode(SpaceOverride p_mode);
+ SpaceOverride get_angular_damp_space_override_mode() const;
+
void set_angular_damp(real_t p_angular_damp);
real_t get_angular_damp() const;
@@ -163,6 +183,15 @@ public:
void set_priority(real_t p_priority);
real_t get_priority() const;
+ void set_wind_force_magnitude(real_t p_wind_force_magnitude);
+ real_t get_wind_force_magnitude() const;
+
+ void set_wind_attenuation_factor(real_t p_wind_attenuation_factor);
+ real_t get_wind_attenuation_factor() const;
+
+ void set_wind_source_path(const NodePath &p_wind_source_path);
+ const NodePath &get_wind_source_path() const;
+
void set_monitoring(bool p_enable);
bool is_monitoring() const;
@@ -199,4 +228,4 @@ public:
VARIANT_ENUM_CAST(Area3D::SpaceOverride);
-#endif // AREA__H
+#endif // AREA_3D_H
diff --git a/scene/3d/listener_3d.cpp b/scene/3d/audio_listener_3d.cpp
index 9842f152d7..1ead9bb384 100644
--- a/scene/3d/listener_3d.cpp
+++ b/scene/3d/audio_listener_3d.cpp
@@ -1,12 +1,12 @@
/*************************************************************************/
-/* listener_3d.cpp */
+/* audio_listener_3d.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -28,18 +28,18 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#include "listener_3d.h"
+#include "audio_listener_3d.h"
-#include "scene/resources/mesh.h"
+#include "scene/main/viewport.h"
-void Listener3D::_update_audio_listener_state() {
+void AudioListener3D::_update_audio_listener_state() {
}
-void Listener3D::_request_listener_update() {
+void AudioListener3D::_request_listener_update() {
_update_listener();
}
-bool Listener3D::_set(const StringName &p_name, const Variant &p_value) {
+bool AudioListener3D::_set(const StringName &p_name, const Variant &p_value) {
if (p_name == "current") {
if (p_value.operator bool()) {
make_current();
@@ -53,7 +53,7 @@ bool Listener3D::_set(const StringName &p_name, const Variant &p_value) {
return true;
}
-bool Listener3D::_get(const StringName &p_name, Variant &r_ret) const {
+bool AudioListener3D::_get(const StringName &p_name, Variant &r_ret) const {
if (p_name == "current") {
if (is_inside_tree() && get_tree()->is_node_being_edited(this)) {
r_ret = current;
@@ -67,27 +67,29 @@ bool Listener3D::_get(const StringName &p_name, Variant &r_ret) const {
return true;
}
-void Listener3D::_get_property_list(List<PropertyInfo> *p_list) const {
+void AudioListener3D::_get_property_list(List<PropertyInfo> *p_list) const {
p_list->push_back(PropertyInfo(Variant::BOOL, "current"));
}
-void Listener3D::_update_listener() {
+void AudioListener3D::_update_listener() {
if (is_inside_tree() && is_current()) {
- get_viewport()->_listener_transform_changed_notify();
+ get_viewport()->_listener_transform_3d_changed_notify();
}
}
-void Listener3D::_notification(int p_what) {
+void AudioListener3D::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_ENTER_WORLD: {
- bool first_listener = get_viewport()->_listener_add(this);
+ bool first_listener = get_viewport()->_audio_listener_3d_add(this);
if (!get_tree()->is_node_being_edited(this) && (current || first_listener)) {
make_current();
}
} break;
+
case NOTIFICATION_TRANSFORM_CHANGED: {
_request_listener_update();
} break;
+
case NOTIFICATION_EXIT_WORLD: {
if (!get_tree()->is_node_being_edited(this)) {
if (is_current()) {
@@ -99,41 +101,40 @@ void Listener3D::_notification(int p_what) {
}
}
- get_viewport()->_listener_remove(this);
-
+ get_viewport()->_audio_listener_3d_remove(this);
} break;
}
}
-Transform Listener3D::get_listener_transform() const {
+Transform3D AudioListener3D::get_listener_transform() const {
return get_global_transform().orthonormalized();
}
-void Listener3D::make_current() {
+void AudioListener3D::make_current() {
current = true;
if (!is_inside_tree()) {
return;
}
- get_viewport()->_listener_set(this);
+ get_viewport()->_audio_listener_3d_set(this);
}
-void Listener3D::clear_current() {
+void AudioListener3D::clear_current() {
current = false;
if (!is_inside_tree()) {
return;
}
- if (get_viewport()->get_listener() == this) {
- get_viewport()->_listener_set(nullptr);
- get_viewport()->_listener_make_next_current(this);
+ if (get_viewport()->get_audio_listener_3d() == this) {
+ get_viewport()->_audio_listener_3d_set(nullptr);
+ get_viewport()->_audio_listener_3d_make_next_current(this);
}
}
-bool Listener3D::is_current() const {
+bool AudioListener3D::is_current() const {
if (is_inside_tree() && !get_tree()->is_node_being_edited(this)) {
- return get_viewport()->get_listener() == this;
+ return get_viewport()->get_audio_listener_3d() == this;
} else {
return current;
}
@@ -141,27 +142,16 @@ bool Listener3D::is_current() const {
return false;
}
-bool Listener3D::_can_gizmo_scale() const {
- return false;
-}
-
-RES Listener3D::_get_gizmo_geometry() const {
- Ref<ArrayMesh> mesh = memnew(ArrayMesh);
-
- return mesh;
-}
-
-void Listener3D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("make_current"), &Listener3D::make_current);
- ClassDB::bind_method(D_METHOD("clear_current"), &Listener3D::clear_current);
- ClassDB::bind_method(D_METHOD("is_current"), &Listener3D::is_current);
- ClassDB::bind_method(D_METHOD("get_listener_transform"), &Listener3D::get_listener_transform);
+void AudioListener3D::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("make_current"), &AudioListener3D::make_current);
+ ClassDB::bind_method(D_METHOD("clear_current"), &AudioListener3D::clear_current);
+ ClassDB::bind_method(D_METHOD("is_current"), &AudioListener3D::is_current);
+ ClassDB::bind_method(D_METHOD("get_listener_transform"), &AudioListener3D::get_listener_transform);
}
-Listener3D::Listener3D() {
+AudioListener3D::AudioListener3D() {
set_notify_transform(true);
- //active=false;
}
-Listener3D::~Listener3D() {
+AudioListener3D::~AudioListener3D() {
}
diff --git a/scene/3d/listener_3d.h b/scene/3d/audio_listener_3d.h
index 85657a8e53..ebc37673ed 100644
--- a/scene/3d/listener_3d.h
+++ b/scene/3d/audio_listener_3d.h
@@ -1,12 +1,12 @@
/*************************************************************************/
-/* listener_3d.h */
+/* audio_listener_3d.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -32,10 +32,9 @@
#define LISTENER_3D_H
#include "scene/3d/node_3d.h"
-#include "scene/main/window.h"
-class Listener3D : public Node3D {
- GDCLASS(Listener3D, Node3D);
+class AudioListener3D : public Node3D {
+ GDCLASS(AudioListener3D, Node3D);
private:
bool force_change = false;
@@ -43,9 +42,6 @@ private:
RID scenario_id;
- virtual bool _can_gizmo_scale() const;
- virtual RES _get_gizmo_geometry() const;
-
friend class Viewport;
void _update_audio_listener_state();
@@ -65,13 +61,10 @@ public:
void clear_current();
bool is_current() const;
- virtual Transform get_listener_transform() const;
-
- void set_visible_layers(uint32_t p_layers);
- uint32_t get_visible_layers() const;
+ virtual Transform3D get_listener_transform() const;
- Listener3D();
- ~Listener3D();
+ AudioListener3D();
+ ~AudioListener3D();
};
#endif
diff --git a/scene/3d/audio_stream_player_3d.cpp b/scene/3d/audio_stream_player_3d.cpp
index 72392be5bd..f057c72012 100644
--- a/scene/3d/audio_stream_player_3d.cpp
+++ b/scene/3d/audio_stream_player_3d.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -30,11 +30,10 @@
#include "audio_stream_player_3d.h"
-#include "core/config/engine.h"
#include "scene/3d/area_3d.h"
+#include "scene/3d/audio_listener_3d.h"
#include "scene/3d/camera_3d.h"
-#include "scene/3d/listener_3d.h"
-#include "scene/main/window.h"
+#include "scene/main/viewport.h"
// Based on "A Novel Multichannel Panning Method for Standard and Arbitrary Loudspeaker Configurations" by Ramy Sadek and Chris Kyriakakis (2004)
// Speaker-Placement Correction Amplitude Panning (SPCAP)
@@ -96,7 +95,7 @@ static const Vector3 speaker_directions[7] = {
Vector3(1.0, 0.0, 0.0).normalized(), // side-right
};
-void AudioStreamPlayer3D::_calc_output_vol(const Vector3 &source_dir, real_t tightness, AudioStreamPlayer3D::Output &output) {
+void AudioStreamPlayer3D::_calc_output_vol(const Vector3 &source_dir, real_t tightness, Vector<AudioFrame> &output) {
unsigned int speaker_count = 0; // only main speakers (no LFE)
switch (AudioServer::get_singleton()->get_speaker_mode()) {
case AudioServer::SPEAKER_MODE_STEREO:
@@ -119,182 +118,94 @@ void AudioStreamPlayer3D::_calc_output_vol(const Vector3 &source_dir, real_t tig
switch (AudioServer::get_singleton()->get_speaker_mode()) {
case AudioServer::SPEAKER_SURROUND_71:
- output.vol[3].l = volumes[5]; // side-left
- output.vol[3].r = volumes[6]; // side-right
+ output.write[3].l = volumes[5]; // side-left
+ output.write[3].r = volumes[6]; // side-right
[[fallthrough]];
case AudioServer::SPEAKER_SURROUND_51:
- output.vol[2].l = volumes[3]; // rear-left
- output.vol[2].r = volumes[4]; // rear-right
+ output.write[2].l = volumes[3]; // rear-left
+ output.write[2].r = volumes[4]; // rear-right
[[fallthrough]];
case AudioServer::SPEAKER_SURROUND_31:
- output.vol[1].r = 1.0; // LFE - always full power
- output.vol[1].l = volumes[2]; // center
+ output.write[1].r = 1.0; // LFE - always full power
+ output.write[1].l = volumes[2]; // center
[[fallthrough]];
case AudioServer::SPEAKER_MODE_STEREO:
- output.vol[0].r = volumes[1]; // front-right
- output.vol[0].l = volumes[0]; // front-left
+ output.write[0].r = volumes[1]; // front-right
+ output.write[0].l = volumes[0]; // front-left
break;
}
}
-void AudioStreamPlayer3D::_mix_audio() {
- if (!stream_playback.is_valid() || !active.is_set() ||
- (stream_paused && !stream_paused_fade_out)) {
- return;
- }
-
- bool started = false;
- if (setseek.get() >= 0.0) {
- stream_playback->start(setseek.get());
- setseek.set(-1.0); //reset seek
- started = true;
- }
-
- //get data
- AudioFrame *buffer = mix_buffer.ptrw();
- int buffer_size = mix_buffer.size();
+void AudioStreamPlayer3D::_calc_reverb_vol(Area3D *area, Vector3 listener_area_pos, Vector<AudioFrame> direct_path_vol, Vector<AudioFrame> &reverb_vol) {
+ reverb_vol.resize(4);
+ reverb_vol.write[0] = AudioFrame(0, 0);
+ reverb_vol.write[1] = AudioFrame(0, 0);
+ reverb_vol.write[2] = AudioFrame(0, 0);
+ reverb_vol.write[3] = AudioFrame(0, 0);
- if (stream_paused_fade_out) {
- // Short fadeout ramp
- buffer_size = MIN(buffer_size, 128);
- }
+ float uniformity = area->get_reverb_uniformity();
+ float area_send = area->get_reverb_amount();
- // Mix if we're not paused or we're fading out
- if ((output_count.get() > 0 || out_of_range_mode == OUT_OF_RANGE_MIX)) {
- float output_pitch_scale = 0.0;
- if (output_count.get()) {
- //used for doppler, not realistic but good enough
- for (int i = 0; i < output_count.get(); i++) {
- output_pitch_scale += outputs[i].pitch_scale;
- }
- output_pitch_scale /= float(output_count.get());
- } else {
- output_pitch_scale = 1.0;
- }
+ if (uniformity > 0.0) {
+ float distance = listener_area_pos.length();
+ float attenuation = Math::db2linear(_get_attenuation_db(distance));
- stream_playback->mix(buffer, pitch_scale * output_pitch_scale, buffer_size);
- }
+ // Determine the fraction of sound that would come from each speaker if they were all driven uniformly.
+ float center_val[3] = { 0.5f, 0.25f, 0.16666f };
+ int channel_count = AudioServer::get_singleton()->get_channel_count();
+ AudioFrame center_frame(center_val[channel_count - 1], center_val[channel_count - 1]);
- //write all outputs
- for (int i = 0; i < output_count.get(); i++) {
- Output current = outputs[i];
+ if (attenuation < 1.0) {
+ //pan the uniform sound
+ Vector3 rev_pos = listener_area_pos;
+ rev_pos.y = 0;
+ rev_pos.normalize();
- //see if current output exists, to keep volume ramp
- bool found = false;
- for (int j = i; j < prev_output_count; j++) {
- if (prev_outputs[j].viewport == current.viewport) {
- if (j != i) {
- SWAP(prev_outputs[j], prev_outputs[i]);
- }
- found = true;
- break;
+ 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;
}
- }
- bool interpolate_filter = !started;
+ if (channel_count >= 3) {
+ // Center pair + Side pair
+ float xl = Vector3(-1, 0, -1).normalized().dot(rev_pos) * 0.5 + 0.5;
+ float xr = Vector3(1, 0, -1).normalized().dot(rev_pos) * 0.5 + 0.5;
- if (!found) {
- //create new if was not used before
- if (prev_output_count < MAX_OUTPUTS) {
- prev_outputs[prev_output_count] = prev_outputs[i]; //may be owned by another viewport
- prev_output_count++;
+ reverb_vol.write[1].l = xl;
+ reverb_vol.write[1].r = xr;
+ reverb_vol.write[2].l = 1.0 - xr;
+ reverb_vol.write[2].r = 1.0 - xl;
}
- prev_outputs[i] = current;
- interpolate_filter = false;
- }
-
- //mix!
-
- int buffers = AudioServer::get_singleton()->get_channel_count();
- for (int k = 0; k < buffers; k++) {
- AudioFrame target_volume = stream_paused_fade_out ? AudioFrame(0.f, 0.f) : current.vol[k];
- AudioFrame vol_prev = stream_paused_fade_in ? AudioFrame(0.f, 0.f) : prev_outputs[i].vol[k];
- AudioFrame vol_inc = (target_volume - vol_prev) / float(buffer_size);
- AudioFrame vol = vol_prev;
-
- if (!AudioServer::get_singleton()->thread_has_channel_mix_buffer(current.bus_index, k)) {
- continue; //may have been deleted, will be updated on process
+ 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;
}
- AudioFrame *target = AudioServer::get_singleton()->thread_get_channel_mix_buffer(current.bus_index, k);
- current.filter.set_mode(AudioFilterSW::HIGHSHELF);
- current.filter.set_sampling_rate(AudioServer::get_singleton()->get_mix_rate());
- current.filter.set_cutoff(attenuation_filter_cutoff_hz);
- current.filter.set_resonance(1);
- current.filter.set_stages(1);
- current.filter.set_gain(current.filter_gain);
-
- if (interpolate_filter) {
- current.filter_process[k * 2 + 0] = prev_outputs[i].filter_process[k * 2 + 0];
- current.filter_process[k * 2 + 1] = prev_outputs[i].filter_process[k * 2 + 1];
-
- current.filter_process[k * 2 + 0].set_filter(&current.filter, false);
- current.filter_process[k * 2 + 1].set_filter(&current.filter, false);
-
- current.filter_process[k * 2 + 0].update_coeffs(buffer_size);
- current.filter_process[k * 2 + 1].update_coeffs(buffer_size);
- for (int j = 0; j < buffer_size; j++) {
- AudioFrame f = buffer[j] * vol;
- current.filter_process[k * 2 + 0].process_one_interp(f.l);
- current.filter_process[k * 2 + 1].process_one_interp(f.r);
-
- target[j] += f;
- vol += vol_inc;
- }
- } else {
- current.filter_process[k * 2 + 0].set_filter(&current.filter);
- current.filter_process[k * 2 + 1].set_filter(&current.filter);
-
- current.filter_process[k * 2 + 0].update_coeffs();
- current.filter_process[k * 2 + 1].update_coeffs();
- for (int j = 0; j < buffer_size; j++) {
- AudioFrame f = buffer[j] * vol;
- current.filter_process[k * 2 + 0].process_one(f.l);
- current.filter_process[k * 2 + 1].process_one(f.r);
-
- target[j] += f;
- vol += vol_inc;
- }
+ for (int i = 0; i < channel_count; i++) {
+ reverb_vol.write[i] = reverb_vol[i].lerp(center_frame, attenuation);
}
-
- if (current.reverb_bus_index >= 0) {
- if (!AudioServer::get_singleton()->thread_has_channel_mix_buffer(current.reverb_bus_index, k)) {
- continue; //may have been deleted, will be updated on process
- }
-
- AudioFrame *rtarget = AudioServer::get_singleton()->thread_get_channel_mix_buffer(current.reverb_bus_index, k);
-
- if (current.reverb_bus_index == prev_outputs[i].reverb_bus_index) {
- AudioFrame rvol_inc = (current.reverb_vol[k] - prev_outputs[i].reverb_vol[k]) / float(buffer_size);
- AudioFrame rvol = prev_outputs[i].reverb_vol[k];
-
- for (int j = 0; j < buffer_size; j++) {
- rtarget[j] += buffer[j] * rvol;
- rvol += rvol_inc;
- }
- } else {
- AudioFrame rvol = current.reverb_vol[k];
- for (int j = 0; j < buffer_size; j++) {
- rtarget[j] += buffer[j] * rvol;
- }
- }
+ } else {
+ for (int i = 0; i < channel_count; i++) {
+ reverb_vol.write[i] = center_frame;
}
}
- prev_outputs[i] = current;
- }
-
- prev_output_count = output_count.get();
+ for (int i = 0; i < channel_count; i++) {
+ reverb_vol.write[i] = direct_path_vol[i].lerp(reverb_vol[i] * attenuation, uniformity);
+ reverb_vol.write[i] *= area_send;
+ }
- //stream is no longer active, disable this.
- if (!stream_playback->is_playing()) {
- active.clear();
+ } else {
+ for (int i = 0; i < 4; i++) {
+ reverb_vol.write[i] = direct_path_vol[i] * area_send;
+ }
}
-
- output_ready.clear();
- stream_paused_fade_in = false;
- stream_paused_fade_out = false;
}
float AudioStreamPlayer3D::_get_attenuation_db(float p_distance) const {
@@ -328,315 +239,288 @@ float AudioStreamPlayer3D::_get_attenuation_db(float p_distance) const {
}
void AudioStreamPlayer3D::_notification(int p_what) {
- if (p_what == NOTIFICATION_ENTER_TREE) {
- velocity_tracker->reset(get_global_transform().origin);
- AudioServer::get_singleton()->add_callback(_mix_audios, this);
- if (autoplay && !Engine::get_singleton()->is_editor_hint()) {
- play();
- }
- }
-
- if (p_what == NOTIFICATION_EXIT_TREE) {
- AudioServer::get_singleton()->remove_callback(_mix_audios, this);
- }
-
- if (p_what == NOTIFICATION_PAUSED) {
- if (!can_process()) {
- // Node can't process so we start fading out to silence
- set_stream_paused(true);
- }
- }
-
- if (p_what == NOTIFICATION_UNPAUSED) {
- set_stream_paused(false);
- }
+ switch (p_what) {
+ case NOTIFICATION_ENTER_TREE: {
+ velocity_tracker->reset(get_global_transform().origin);
+ AudioServer::get_singleton()->add_listener_changed_callback(_listener_changed_cb, this);
+ if (autoplay && !Engine::get_singleton()->is_editor_hint()) {
+ play();
+ }
+ } break;
- if (p_what == NOTIFICATION_TRANSFORM_CHANGED) {
- if (doppler_tracking != DOPPLER_TRACKING_DISABLED) {
- velocity_tracker->update_position(get_global_transform().origin);
- }
- }
+ case NOTIFICATION_EXIT_TREE: {
+ stop();
+ AudioServer::get_singleton()->remove_listener_changed_callback(_listener_changed_cb, this);
+ } break;
- if (p_what == NOTIFICATION_INTERNAL_PHYSICS_PROCESS) {
- //update anything related to position first, if possible of course
+ case NOTIFICATION_PAUSED: {
+ if (!can_process()) {
+ // Node can't process so we start fading out to silence.
+ set_stream_paused(true);
+ }
+ } break;
- if (!output_ready.is_set()) {
- Vector3 linear_velocity;
+ case NOTIFICATION_UNPAUSED: {
+ set_stream_paused(false);
+ } break;
- //compute linear velocity for doppler
+ case NOTIFICATION_TRANSFORM_CHANGED: {
if (doppler_tracking != DOPPLER_TRACKING_DISABLED) {
- linear_velocity = velocity_tracker->get_tracked_linear_velocity();
+ velocity_tracker->update_position(get_global_transform().origin);
}
+ } break;
- Ref<World3D> world_3d = get_world_3d();
- ERR_FAIL_COND(world_3d.is_null());
-
- int new_output_count = 0;
+ case NOTIFICATION_INTERNAL_PHYSICS_PROCESS: {
+ // Update anything related to position first, if possible of course.
+ Vector<AudioFrame> volume_vector;
+ if (setplay.get() > 0 || (active.is_set() && last_mix_count != AudioServer::get_singleton()->get_mix_count())) {
+ volume_vector = _update_panning();
+ }
- Vector3 global_pos = get_global_transform().origin;
+ if (setplay.get() >= 0 && stream.is_valid()) {
+ active.set();
+ Ref<AudioStreamPlayback> new_playback = stream->instance_playback();
+ ERR_FAIL_COND_MSG(new_playback.is_null(), "Failed to instantiate playback.");
+ Map<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);
+ setplay.set(-1);
+ }
- int bus_index = AudioServer::get_singleton()->thread_find_bus_index(bus);
+ if (!stream_playbacks.is_empty() && active.is_set()) {
+ // Stop playing if no longer active.
+ Vector<Ref<AudioStreamPlayback>> playbacks_to_remove;
+ for (Ref<AudioStreamPlayback> &playback : stream_playbacks) {
+ if (playback.is_valid() && !AudioServer::get_singleton()->is_playback_active(playback) && !AudioServer::get_singleton()->is_playback_paused(playback)) {
+ playbacks_to_remove.push_back(playback);
+ }
+ }
+ // Now go through and remove playbacks that have finished. Removing elements from a Vector in a range based for is asking for trouble.
+ for (Ref<AudioStreamPlayback> &playback : playbacks_to_remove) {
+ stream_playbacks.erase(playback);
+ }
+ if (!playbacks_to_remove.is_empty() && stream_playbacks.is_empty()) {
+ // This node is no longer actively playing audio.
+ active.clear();
+ set_physics_process_internal(false);
+ }
+ if (!playbacks_to_remove.is_empty()) {
+ emit_signal(SNAME("finished"));
+ }
+ }
- //check if any area is diverting sound into a bus
+ while (stream_playbacks.size() > max_polyphony) {
+ AudioServer::get_singleton()->stop_playback_stream(stream_playbacks[0]);
+ stream_playbacks.remove_at(0);
+ }
+ } break;
+ }
+}
- PhysicsDirectSpaceState3D *space_state = PhysicsServer3D::get_singleton()->space_get_direct_state(world_3d->get_space());
+Area3D *AudioStreamPlayer3D::_get_overriding_area() {
+ //check if any area is diverting sound into a bus
+ Ref<World3D> world_3d = get_world_3d();
+ ERR_FAIL_COND_V(world_3d.is_null(), nullptr);
- PhysicsDirectSpaceState3D::ShapeResult sr[MAX_INTERSECT_AREAS];
+ Vector3 global_pos = get_global_transform().origin;
- int areas = space_state->intersect_point(global_pos, sr, MAX_INTERSECT_AREAS, Set<RID>(), area_mask, false, true);
- Area3D *area = nullptr;
+ PhysicsDirectSpaceState3D *space_state = PhysicsServer3D::get_singleton()->space_get_direct_state(world_3d->get_space());
- for (int i = 0; i < areas; i++) {
- if (!sr[i].collider) {
- continue;
- }
+ PhysicsDirectSpaceState3D::ShapeResult sr[MAX_INTERSECT_AREAS];
- Area3D *tarea = Object::cast_to<Area3D>(sr[i].collider);
- if (!tarea) {
- continue;
- }
+ PhysicsDirectSpaceState3D::PointParameters point_params;
+ point_params.position = global_pos;
+ point_params.collision_mask = area_mask;
+ point_params.collide_with_bodies = false;
+ point_params.collide_with_areas = true;
- if (!tarea->is_overriding_audio_bus() && !tarea->is_using_reverb_bus()) {
- continue;
- }
+ int areas = space_state->intersect_point(point_params, sr, MAX_INTERSECT_AREAS);
- area = tarea;
- break;
- }
+ for (int i = 0; i < areas; i++) {
+ if (!sr[i].collider) {
+ continue;
+ }
- List<Camera3D *> cameras;
- world_3d->get_camera_list(&cameras);
+ Area3D *tarea = Object::cast_to<Area3D>(sr[i].collider);
+ if (!tarea) {
+ continue;
+ }
- for (List<Camera3D *>::Element *E = cameras.front(); E; E = E->next()) {
- Camera3D *camera = E->get();
- Viewport *vp = camera->get_viewport();
- if (!vp->is_audio_listener()) {
- continue;
- }
+ if (!tarea->is_overriding_audio_bus() && !tarea->is_using_reverb_bus()) {
+ continue;
+ }
- bool listener_is_camera = true;
- Node3D *listener_node = camera;
+ return tarea;
+ }
+ return nullptr;
+}
- Listener3D *listener = vp->get_listener();
- if (listener) {
- listener_node = listener;
- listener_is_camera = false;
- }
+StringName AudioStreamPlayer3D::_get_actual_bus() {
+ Area3D *overriding_area = _get_overriding_area();
+ if (overriding_area && overriding_area->is_overriding_audio_bus() && !overriding_area->is_using_reverb_bus()) {
+ return overriding_area->get_audio_bus_name();
+ }
+ return bus;
+}
- Vector3 local_pos = listener_node->get_global_transform().orthonormalized().affine_inverse().xform(global_pos);
+Vector<AudioFrame> AudioStreamPlayer3D::_update_panning() {
+ Vector<AudioFrame> output_volume_vector;
+ output_volume_vector.resize(4);
+ for (AudioFrame &frame : output_volume_vector) {
+ frame = AudioFrame(0, 0);
+ }
- float dist = local_pos.length();
+ if (!active.is_set() || stream.is_null()) {
+ return output_volume_vector;
+ }
- Vector3 area_sound_pos;
- Vector3 listener_area_pos;
+ Vector3 linear_velocity;
- if (area && area->is_using_reverb_bus() && area->get_reverb_uniformity() > 0) {
- area_sound_pos = space_state->get_closest_point_to_object_volume(area->get_rid(), listener_node->get_global_transform().origin);
- listener_area_pos = listener_node->get_global_transform().affine_inverse().xform(area_sound_pos);
- }
+ //compute linear velocity for doppler
+ if (doppler_tracking != DOPPLER_TRACKING_DISABLED) {
+ linear_velocity = velocity_tracker->get_tracked_linear_velocity();
+ }
- if (max_distance > 0) {
- float total_max = max_distance;
+ Vector3 global_pos = get_global_transform().origin;
- if (area && area->is_using_reverb_bus() && area->get_reverb_uniformity() > 0) {
- total_max = MAX(total_max, listener_area_pos.length());
- }
- if (total_max > max_distance) {
- continue; //can't hear this sound in this listener
- }
- }
+ Ref<World3D> world_3d = get_world_3d();
+ ERR_FAIL_COND_V(world_3d.is_null(), output_volume_vector);
- float multiplier = Math::db2linear(_get_attenuation_db(dist));
- if (max_distance > 0) {
- multiplier *= MAX(0, 1.0 - (dist / max_distance));
- }
+ Set<Camera3D *> cameras = world_3d->get_cameras();
+ cameras.insert(get_viewport()->get_camera_3d());
- Output output;
- output.bus_index = bus_index;
- output.reverb_bus_index = -1; //no reverb by default
- output.viewport = vp;
+ PhysicsDirectSpaceState3D *space_state = PhysicsServer3D::get_singleton()->space_get_direct_state(world_3d->get_space());
- float db_att = (1.0 - MIN(1.0, multiplier)) * attenuation_filter_db;
+ for (Camera3D *camera : cameras) {
+ if (!camera) {
+ continue;
+ }
+ Viewport *vp = camera->get_viewport();
+ if (!vp) {
+ continue;
+ }
+ if (!vp->is_audio_listener_3d()) {
+ continue;
+ }
- if (emission_angle_enabled) {
- Vector3 listenertopos = global_pos - listener_node->get_global_transform().origin;
- float c = listenertopos.normalized().dot(get_global_transform().basis.get_axis(2).normalized()); //it's z negative
- float angle = Math::rad2deg(Math::acos(c));
- if (angle > emission_angle) {
- db_att -= -emission_angle_filter_attenuation_db;
- }
- }
+ bool listener_is_camera = true;
+ Node3D *listener_node = camera;
- output.filter_gain = Math::db2linear(db_att);
+ AudioListener3D *listener = vp->get_audio_listener_3d();
+ if (listener) {
+ listener_node = listener;
+ listener_is_camera = false;
+ }
- //TODO: The lower the second parameter (tightness) the more the sound will "enclose" the listener (more undirected / playing from
- // speakers not facing the source) - this could be made distance dependent.
- _calc_output_vol(local_pos.normalized(), 4.0, output);
+ Vector3 local_pos = listener_node->get_global_transform().orthonormalized().affine_inverse().xform(global_pos);
- unsigned int cc = AudioServer::get_singleton()->get_channel_count();
- for (unsigned int k = 0; k < cc; k++) {
- output.vol[k] *= multiplier;
- }
+ float dist = local_pos.length();
- bool filled_reverb = false;
- int vol_index_max = AudioServer::get_singleton()->get_speaker_mode() + 1;
+ Vector3 area_sound_pos;
+ Vector3 listener_area_pos;
- if (area) {
- if (area->is_overriding_audio_bus()) {
- //override audio bus
- StringName bus_name = area->get_audio_bus_name();
- output.bus_index = AudioServer::get_singleton()->thread_find_bus_index(bus_name);
- }
+ Area3D *area = _get_overriding_area();
- if (area->is_using_reverb_bus()) {
- filled_reverb = true;
- StringName bus_name = area->get_reverb_bus();
- output.reverb_bus_index = AudioServer::get_singleton()->thread_find_bus_index(bus_name);
-
- float uniformity = area->get_reverb_uniformity();
- float area_send = area->get_reverb_amount();
-
- if (uniformity > 0.0) {
- float distance = listener_area_pos.length();
- float attenuation = Math::db2linear(_get_attenuation_db(distance));
-
- //float dist_att_db = -20 * Math::log(dist + 0.00001); //logarithmic attenuation, like in real life
-
- float center_val[3] = { 0.5f, 0.25f, 0.16666f };
- AudioFrame center_frame(center_val[vol_index_max - 1], center_val[vol_index_max - 1]);
-
- if (attenuation < 1.0) {
- //pan the uniform sound
- Vector3 rev_pos = listener_area_pos;
- rev_pos.y = 0;
- rev_pos.normalize();
-
- if (cc >= 1) {
- // Stereo pair
- float c = rev_pos.x * 0.5 + 0.5;
- output.reverb_vol[0].l = 1.0 - c;
- output.reverb_vol[0].r = c;
- }
-
- if (cc >= 3) {
- // Center pair + Side pair
- float xl = Vector3(-1, 0, -1).normalized().dot(rev_pos) * 0.5 + 0.5;
- float xr = Vector3(1, 0, -1).normalized().dot(rev_pos) * 0.5 + 0.5;
-
- output.reverb_vol[1].l = xl;
- output.reverb_vol[1].r = xr;
- output.reverb_vol[2].l = 1.0 - xr;
- output.reverb_vol[2].r = 1.0 - xl;
- }
-
- if (cc >= 4) {
- // Rear pair
- // FIXME: Not sure what math should be done here
- float c = rev_pos.x * 0.5 + 0.5;
- output.reverb_vol[3].l = 1.0 - c;
- output.reverb_vol[3].r = c;
- }
-
- for (int i = 0; i < vol_index_max; i++) {
- output.reverb_vol[i] = output.reverb_vol[i].lerp(center_frame, attenuation);
- }
- } else {
- for (int i = 0; i < vol_index_max; i++) {
- output.reverb_vol[i] = center_frame;
- }
- }
-
- for (int i = 0; i < vol_index_max; i++) {
- output.reverb_vol[i] = output.vol[i].lerp(output.reverb_vol[i] * attenuation, uniformity);
- output.reverb_vol[i] *= area_send;
- }
-
- } else {
- for (int i = 0; i < vol_index_max; i++) {
- output.reverb_vol[i] = output.vol[i] * area_send;
- }
- }
- }
- }
+ if (area && area->is_using_reverb_bus() && area->get_reverb_uniformity() > 0) {
+ area_sound_pos = space_state->get_closest_point_to_object_volume(area->get_rid(), listener_node->get_global_transform().origin);
+ listener_area_pos = listener_node->get_global_transform().affine_inverse().xform(area_sound_pos);
+ }
- if (doppler_tracking != DOPPLER_TRACKING_DISABLED) {
- Vector3 listener_velocity;
+ if (max_distance > 0) {
+ float total_max = max_distance;
- if (listener_is_camera) {
- listener_velocity = camera->get_doppler_tracked_velocity();
- }
+ if (area && area->is_using_reverb_bus() && area->get_reverb_uniformity() > 0) {
+ total_max = MAX(total_max, listener_area_pos.length());
+ }
+ if (total_max > max_distance) {
+ continue; //can't hear this sound in this listener
+ }
+ }
- Vector3 local_velocity = listener_node->get_global_transform().orthonormalized().basis.xform_inv(linear_velocity - listener_velocity);
+ float multiplier = Math::db2linear(_get_attenuation_db(dist));
+ if (max_distance > 0) {
+ multiplier *= MAX(0, 1.0 - (dist / max_distance));
+ }
- if (local_velocity == Vector3()) {
- output.pitch_scale = 1.0;
- } else {
- float approaching = local_pos.normalized().dot(local_velocity.normalized());
- float velocity = local_velocity.length();
- float speed_of_sound = 343.0;
+ float db_att = (1.0 - MIN(1.0, multiplier)) * attenuation_filter_db;
- output.pitch_scale = speed_of_sound / (speed_of_sound + velocity * approaching);
- output.pitch_scale = CLAMP(output.pitch_scale, (1 / 8.0), 8.0); //avoid crazy stuff
- }
+ if (emission_angle_enabled) {
+ Vector3 listenertopos = global_pos - listener_node->get_global_transform().origin;
+ float c = listenertopos.normalized().dot(get_global_transform().basis.get_column(2).normalized()); //it's z negative
+ float angle = Math::rad2deg(Math::acos(c));
+ if (angle > emission_angle) {
+ db_att -= -emission_angle_filter_attenuation_db;
+ }
+ }
- } else {
- output.pitch_scale = 1.0;
- }
+ linear_attenuation = Math::db2linear(db_att);
+ for (Ref<AudioStreamPlayback> &playback : stream_playbacks) {
+ AudioServer::get_singleton()->set_playback_highshelf_params(playback, linear_attenuation, attenuation_filter_cutoff_hz);
+ }
+ //TODO: The lower the second parameter (tightness) the more the sound will "enclose" the listener (more undirected / playing from
+ // speakers not facing the source) - this could be made distance dependent.
+ _calc_output_vol(local_pos.normalized(), 4.0, output_volume_vector);
- if (!filled_reverb) {
- for (int i = 0; i < vol_index_max; i++) {
- output.reverb_vol[i] = AudioFrame(0, 0);
- }
- }
+ for (unsigned int k = 0; k < 4; k++) {
+ output_volume_vector.write[k] = multiplier * output_volume_vector[k];
+ }
- outputs[new_output_count] = output;
- new_output_count++;
- if (new_output_count == MAX_OUTPUTS) {
- break;
- }
+ Map<StringName, Vector<AudioFrame>> bus_volumes;
+ if (area) {
+ if (area->is_overriding_audio_bus()) {
+ //override audio bus
+ bus_volumes[area->get_audio_bus_name()] = output_volume_vector;
}
- output_count.set(new_output_count);
- output_ready.set();
- }
-
- //start playing if requested
- if (setplay.get() >= 0.0) {
- setseek.set(setplay.get());
- active.set();
- setplay.set(-1);
+ if (area->is_using_reverb_bus()) {
+ StringName reverb_bus_name = area->get_reverb_bus();
+ Vector<AudioFrame> reverb_vol;
+ _calc_reverb_vol(area, listener_area_pos, output_volume_vector, reverb_vol);
+ bus_volumes[reverb_bus_name] = reverb_vol;
+ }
+ } else {
+ bus_volumes[bus] = output_volume_vector;
}
- //stop playing if no longer active
- if (!active.is_set()) {
- set_physics_process_internal(false);
- emit_signal("finished");
+ for (Ref<AudioStreamPlayback> &playback : stream_playbacks) {
+ AudioServer::get_singleton()->set_playback_bus_volumes_linear(playback, bus_volumes);
}
- }
-}
-void AudioStreamPlayer3D::set_stream(Ref<AudioStream> p_stream) {
- AudioServer::get_singleton()->lock();
+ if (doppler_tracking != DOPPLER_TRACKING_DISABLED) {
+ Vector3 listener_velocity;
- mix_buffer.resize(AudioServer::get_singleton()->thread_get_mix_buffer_size());
+ if (listener_is_camera) {
+ listener_velocity = camera->get_doppler_tracked_velocity();
+ }
- if (stream_playback.is_valid()) {
- stream_playback.unref();
- stream.unref();
- active.clear();
- setseek.set(-1);
- }
+ Vector3 local_velocity = listener_node->get_global_transform().orthonormalized().basis.xform_inv(linear_velocity - listener_velocity);
- if (p_stream.is_valid()) {
- stream = p_stream;
- stream_playback = p_stream->instance_playback();
- }
+ if (local_velocity != Vector3()) {
+ float approaching = local_pos.normalized().dot(local_velocity.normalized());
+ float velocity = local_velocity.length();
+ float speed_of_sound = 343.0;
- AudioServer::get_singleton()->unlock();
+ float doppler_pitch_scale = pitch_scale * speed_of_sound / (speed_of_sound + velocity * approaching);
+ doppler_pitch_scale = CLAMP(doppler_pitch_scale, (1 / 8.0), 8.0); //avoid crazy stuff
- if (p_stream.is_valid() && stream_playback.is_null()) {
- stream.unref();
+ actual_pitch_scale = doppler_pitch_scale;
+ } else {
+ actual_pitch_scale = pitch_scale;
+ }
+ } else {
+ actual_pitch_scale = pitch_scale;
+ }
+ for (Ref<AudioStreamPlayback> &playback : stream_playbacks) {
+ AudioServer::get_singleton()->set_playback_pitch_scale(playback, actual_pitch_scale);
+ }
}
+ return output_volume_vector;
+}
+
+void AudioStreamPlayer3D::set_stream(Ref<AudioStream> p_stream) {
+ stop();
+ stream = p_stream;
}
Ref<AudioStream> AudioStreamPlayer3D::get_stream() const {
@@ -677,49 +561,47 @@ float AudioStreamPlayer3D::get_pitch_scale() const {
}
void AudioStreamPlayer3D::play(float p_from_pos) {
- if (!is_playing()) {
- // Reset the prev_output_count if the stream is stopped
- prev_output_count = 0;
+ if (stream.is_null()) {
+ return;
}
-
- if (stream_playback.is_valid()) {
- setplay.set(p_from_pos);
- output_ready.clear();
- set_physics_process_internal(true);
+ ERR_FAIL_COND_MSG(!is_inside_tree(), "Playback can only happen when a node is inside the scene tree");
+ if (stream->is_monophonic() && is_playing()) {
+ stop();
}
+ setplay.set(p_from_pos);
+ active.set();
+ set_physics_process_internal(true);
}
void AudioStreamPlayer3D::seek(float p_seconds) {
- if (stream_playback.is_valid()) {
- setseek.set(p_seconds);
- }
+ stop();
+ play(p_seconds);
}
void AudioStreamPlayer3D::stop() {
- if (stream_playback.is_valid()) {
- active.clear();
- set_physics_process_internal(false);
- setplay.set(-1);
+ setplay.set(-1);
+ for (Ref<AudioStreamPlayback> &playback : stream_playbacks) {
+ AudioServer::get_singleton()->stop_playback_stream(playback);
}
+ stream_playbacks.clear();
+ active.clear();
+ set_physics_process_internal(false);
}
bool AudioStreamPlayer3D::is_playing() const {
- if (stream_playback.is_valid()) {
- return active.is_set() || setplay.get() >= 0;
+ for (const Ref<AudioStreamPlayback> &playback : stream_playbacks) {
+ if (AudioServer::get_singleton()->is_playback_active(playback)) {
+ return true;
+ }
}
-
return false;
}
float AudioStreamPlayer3D::get_playback_position() {
- if (stream_playback.is_valid()) {
- float ss = setseek.get();
- if (ss >= 0.0) {
- return ss;
- }
- return stream_playback->get_playback_position();
+ // Return the playback position of the most recently started playback stream.
+ if (!stream_playbacks.is_empty()) {
+ return AudioServer::get_singleton()->get_playback_position(stream_playbacks[stream_playbacks.size() - 1]);
}
-
return 0;
}
@@ -736,7 +618,7 @@ StringName AudioStreamPlayer3D::get_bus() const {
return bus;
}
}
- return "Master";
+ return SNAME("Master");
}
void AudioStreamPlayer3D::set_autoplay(bool p_enable) {
@@ -772,6 +654,8 @@ void AudioStreamPlayer3D::_validate_property(PropertyInfo &property) const {
property.hint_string = options;
}
+
+ Node3D::_validate_property(property);
}
void AudioStreamPlayer3D::_bus_layout_changed() {
@@ -797,7 +681,7 @@ uint32_t AudioStreamPlayer3D::get_area_mask() const {
void AudioStreamPlayer3D::set_emission_angle_enabled(bool p_enable) {
emission_angle_enabled = p_enable;
- update_gizmo();
+ update_gizmos();
}
bool AudioStreamPlayer3D::is_emission_angle_enabled() const {
@@ -807,7 +691,7 @@ bool AudioStreamPlayer3D::is_emission_angle_enabled() const {
void AudioStreamPlayer3D::set_emission_angle(float p_angle) {
ERR_FAIL_COND(p_angle < 0 || p_angle > 90);
emission_angle = p_angle;
- update_gizmo();
+ update_gizmos();
}
float AudioStreamPlayer3D::get_emission_angle() const {
@@ -847,15 +731,6 @@ AudioStreamPlayer3D::AttenuationModel AudioStreamPlayer3D::get_attenuation_model
return attenuation_model;
}
-void AudioStreamPlayer3D::set_out_of_range_mode(OutOfRangeMode p_mode) {
- ERR_FAIL_INDEX((int)p_mode, 2);
- out_of_range_mode = p_mode;
-}
-
-AudioStreamPlayer3D::OutOfRangeMode AudioStreamPlayer3D::get_out_of_range_mode() const {
- return out_of_range_mode;
-}
-
void AudioStreamPlayer3D::set_doppler_tracking(DopplerTracking p_tracking) {
if (doppler_tracking == p_tracking) {
return;
@@ -879,19 +754,35 @@ AudioStreamPlayer3D::DopplerTracking AudioStreamPlayer3D::get_doppler_tracking()
}
void AudioStreamPlayer3D::set_stream_paused(bool p_pause) {
- if (p_pause != stream_paused) {
- stream_paused = p_pause;
- stream_paused_fade_in = !stream_paused;
- stream_paused_fade_out = stream_paused;
+ // TODO this does not have perfect recall, fix that maybe? If there are zero playbacks registered with the AudioServer, this bool isn't persisted.
+ for (Ref<AudioStreamPlayback> &playback : stream_playbacks) {
+ AudioServer::get_singleton()->set_playback_paused(playback, p_pause);
}
}
bool AudioStreamPlayer3D::get_stream_paused() const {
- return stream_paused;
+ // There's currently no way to pause some playback streams but not others. Check the first and don't bother looking at the rest.
+ if (!stream_playbacks.is_empty()) {
+ return AudioServer::get_singleton()->is_playback_paused(stream_playbacks[0]);
+ }
+ return false;
}
Ref<AudioStreamPlayback> AudioStreamPlayer3D::get_stream_playback() {
- return stream_playback;
+ if (!stream_playbacks.is_empty()) {
+ return stream_playbacks[stream_playbacks.size() - 1];
+ }
+ return nullptr;
+}
+
+void AudioStreamPlayer3D::set_max_polyphony(int p_max_polyphony) {
+ if (p_max_polyphony > 0) {
+ max_polyphony = p_max_polyphony;
+ }
+}
+
+int AudioStreamPlayer3D::get_max_polyphony() const {
+ return max_polyphony;
}
void AudioStreamPlayer3D::_bind_methods() {
@@ -950,33 +841,33 @@ void AudioStreamPlayer3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_attenuation_model", "model"), &AudioStreamPlayer3D::set_attenuation_model);
ClassDB::bind_method(D_METHOD("get_attenuation_model"), &AudioStreamPlayer3D::get_attenuation_model);
- ClassDB::bind_method(D_METHOD("set_out_of_range_mode", "mode"), &AudioStreamPlayer3D::set_out_of_range_mode);
- ClassDB::bind_method(D_METHOD("get_out_of_range_mode"), &AudioStreamPlayer3D::get_out_of_range_mode);
-
ClassDB::bind_method(D_METHOD("set_doppler_tracking", "mode"), &AudioStreamPlayer3D::set_doppler_tracking);
ClassDB::bind_method(D_METHOD("get_doppler_tracking"), &AudioStreamPlayer3D::get_doppler_tracking);
ClassDB::bind_method(D_METHOD("set_stream_paused", "pause"), &AudioStreamPlayer3D::set_stream_paused);
ClassDB::bind_method(D_METHOD("get_stream_paused"), &AudioStreamPlayer3D::get_stream_paused);
+ ClassDB::bind_method(D_METHOD("set_max_polyphony", "max_polyphony"), &AudioStreamPlayer3D::set_max_polyphony);
+ ClassDB::bind_method(D_METHOD("get_max_polyphony"), &AudioStreamPlayer3D::get_max_polyphony);
+
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");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "attenuation_model", PROPERTY_HINT_ENUM, "Inverse,InverseSquare,Log,Disabled"), "set_attenuation_model", "get_attenuation_model");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "attenuation_model", PROPERTY_HINT_ENUM, "Inverse,Inverse Square,Logarithmic,Disabled"), "set_attenuation_model", "get_attenuation_model");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "unit_db", PROPERTY_HINT_RANGE, "-80,80"), "set_unit_db", "get_unit_db");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "unit_size", PROPERTY_HINT_RANGE, "0.1,100,0.1"), "set_unit_size", "get_unit_size");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "unit_size", PROPERTY_HINT_RANGE, "0.1,100,0.01,or_greater"), "set_unit_size", "get_unit_size");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "max_db", PROPERTY_HINT_RANGE, "-24,6"), "set_max_db", "get_max_db");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "pitch_scale", PROPERTY_HINT_RANGE, "0.01,4,0.01,or_greater"), "set_pitch_scale", "get_pitch_scale");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "playing", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR), "_set_playing", "is_playing");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "autoplay"), "set_autoplay", "is_autoplay_enabled");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "stream_paused", PROPERTY_HINT_NONE, ""), "set_stream_paused", "get_stream_paused");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "max_distance", PROPERTY_HINT_EXP_RANGE, "0,4096,1,or_greater"), "set_max_distance", "get_max_distance");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "out_of_range_mode", PROPERTY_HINT_ENUM, "Mix,Pause"), "set_out_of_range_mode", "get_out_of_range_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "max_distance", PROPERTY_HINT_RANGE, "0,4096,0.01,or_greater"), "set_max_distance", "get_max_distance");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "max_polyphony", PROPERTY_HINT_NONE, ""), "set_max_polyphony", "get_max_polyphony");
ADD_PROPERTY(PropertyInfo(Variant::STRING_NAME, "bus", PROPERTY_HINT_ENUM, ""), "set_bus", "get_bus");
ADD_PROPERTY(PropertyInfo(Variant::INT, "area_mask", PROPERTY_HINT_LAYERS_2D_PHYSICS), "set_area_mask", "get_area_mask");
ADD_GROUP("Emission Angle", "emission_angle");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "emission_angle_enabled"), "set_emission_angle_enabled", "is_emission_angle_enabled");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "emission_angle_degrees", PROPERTY_HINT_RANGE, "0.1,90,0.1"), "set_emission_angle", "get_emission_angle");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "emission_angle_degrees", PROPERTY_HINT_RANGE, "0.1,90,0.1,degrees"), "set_emission_angle", "get_emission_angle");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "emission_angle_filter_attenuation_db", PROPERTY_HINT_RANGE, "-80,0,0.1"), "set_emission_angle_filter_attenuation_db", "get_emission_angle_filter_attenuation_db");
ADD_GROUP("Attenuation Filter", "attenuation_filter_");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "attenuation_filter_cutoff_hz", PROPERTY_HINT_RANGE, "1,20500,1"), "set_attenuation_filter_cutoff_hz", "get_attenuation_filter_cutoff_hz");
@@ -989,9 +880,6 @@ void AudioStreamPlayer3D::_bind_methods() {
BIND_ENUM_CONSTANT(ATTENUATION_LOGARITHMIC);
BIND_ENUM_CONSTANT(ATTENUATION_DISABLED);
- BIND_ENUM_CONSTANT(OUT_OF_RANGE_MIX);
- BIND_ENUM_CONSTANT(OUT_OF_RANGE_PAUSE);
-
BIND_ENUM_CONSTANT(DOPPLER_TRACKING_DISABLED);
BIND_ENUM_CONSTANT(DOPPLER_TRACKING_IDLE_STEP);
BIND_ENUM_CONSTANT(DOPPLER_TRACKING_PHYSICS_STEP);
@@ -1000,7 +888,7 @@ void AudioStreamPlayer3D::_bind_methods() {
}
AudioStreamPlayer3D::AudioStreamPlayer3D() {
- velocity_tracker.instance();
+ velocity_tracker.instantiate();
AudioServer::get_singleton()->connect("bus_layout_changed", callable_mp(this, &AudioStreamPlayer3D::_bus_layout_changed));
set_disable_scale(true);
}
diff --git a/scene/3d/audio_stream_player_3d.h b/scene/3d/audio_stream_player_3d.h
index 70c535bd89..53cdd2e630 100644
--- a/scene/3d/audio_stream_player_3d.h
+++ b/scene/3d/audio_stream_player_3d.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -31,7 +31,8 @@
#ifndef AUDIO_STREAM_PLAYER_3D_H
#define AUDIO_STREAM_PLAYER_3D_H
-#include "core/templates/safe_refcount.h"
+#include "core/os/mutex.h"
+#include "scene/3d/area_3d.h"
#include "scene/3d/node_3d.h"
#include "scene/3d/velocity_tracker_3d.h"
#include "servers/audio/audio_filter_sw.h"
@@ -50,11 +51,6 @@ public:
ATTENUATION_DISABLED,
};
- enum OutOfRangeMode {
- OUT_OF_RANGE_MIX,
- OUT_OF_RANGE_PAUSE,
- };
-
enum DopplerTracking {
DOPPLER_TRACKING_DISABLED,
DOPPLER_TRACKING_IDLE_STEP,
@@ -68,51 +64,36 @@ private:
};
- struct Output {
- AudioFilterSW filter;
- AudioFilterSW::Processor filter_process[8];
- AudioFrame vol[4];
- float filter_gain = 0.0;
- float pitch_scale = 0.0;
- int bus_index = -1;
- int reverb_bus_index = -1;
- AudioFrame reverb_vol[4];
- Viewport *viewport = nullptr; //pointer only used for reference to previous mix
- };
-
- Output outputs[MAX_OUTPUTS];
- SafeNumeric<int> output_count;
- SafeFlag output_ready;
-
- //these are used by audio thread to have a reference of previous volumes (for ramping volume and avoiding clicks)
- Output prev_outputs[MAX_OUTPUTS];
- int prev_output_count = 0;
-
- Ref<AudioStreamPlayback> stream_playback;
+ Vector<Ref<AudioStreamPlayback>> stream_playbacks;
Ref<AudioStream> stream;
- Vector<AudioFrame> mix_buffer;
- SafeNumeric<float> setseek{ -1.0 };
- SafeFlag active;
+ SafeFlag active{ false };
SafeNumeric<float> setplay{ -1.0 };
AttenuationModel attenuation_model = ATTENUATION_INVERSE_DISTANCE;
float unit_db = 0.0;
- float unit_size = 1.0;
+ float unit_size = 10.0;
float max_db = 3.0;
float pitch_scale = 1.0;
+ // Internally used to take doppler tracking into account.
+ float actual_pitch_scale = 1.0;
bool autoplay = false;
- bool stream_paused = false;
- bool stream_paused_fade_in = false;
- bool stream_paused_fade_out = false;
- StringName bus;
+ StringName bus = SNAME("Master");
+ int max_polyphony = 1;
+
+ uint64_t last_mix_count = -1;
- static void _calc_output_vol(const Vector3 &source_dir, real_t tightness, Output &output);
- void _mix_audio();
- static void _mix_audios(void *self) { reinterpret_cast<AudioStreamPlayer3D *>(self)->_mix_audio(); }
+ static void _calc_output_vol(const Vector3 &source_dir, real_t tightness, Vector<AudioFrame> &output);
+
+ void _calc_reverb_vol(Area3D *area, Vector3 listener_area_pos, Vector<AudioFrame> direct_path_vol, Vector<AudioFrame> &reverb_vol);
+
+ static void _listener_changed_cb(void *self) { reinterpret_cast<AudioStreamPlayer3D *>(self)->_update_panning(); }
void _set_playing(bool p_enable);
bool _is_active() const;
+ StringName _get_actual_bus();
+ Area3D *_get_overriding_area();
+ Vector<AudioFrame> _update_panning();
void _bus_layout_changed();
@@ -124,14 +105,14 @@ private:
float attenuation_filter_cutoff_hz = 5000.0;
float attenuation_filter_db = -24.0;
+ float linear_attenuation = 0;
+
float max_distance = 0.0;
Ref<VelocityTracker3D> velocity_tracker;
DopplerTracking doppler_tracking = DOPPLER_TRACKING_DISABLED;
- OutOfRangeMode out_of_range_mode = OUT_OF_RANGE_MIX;
-
float _get_attenuation_db(float p_distance) const;
protected:
@@ -164,6 +145,9 @@ public:
void set_bus(const StringName &p_bus);
StringName get_bus() const;
+ void set_max_polyphony(int p_max_polyphony);
+ int get_max_polyphony() const;
+
void set_autoplay(bool p_enable);
bool is_autoplay_enabled();
@@ -191,9 +175,6 @@ public:
void set_attenuation_model(AttenuationModel p_model);
AttenuationModel get_attenuation_model() const;
- void set_out_of_range_mode(OutOfRangeMode p_mode);
- OutOfRangeMode get_out_of_range_mode() const;
-
void set_doppler_tracking(DopplerTracking p_tracking);
DopplerTracking get_doppler_tracking() const;
@@ -207,6 +188,5 @@ public:
};
VARIANT_ENUM_CAST(AudioStreamPlayer3D::AttenuationModel)
-VARIANT_ENUM_CAST(AudioStreamPlayer3D::OutOfRangeMode)
VARIANT_ENUM_CAST(AudioStreamPlayer3D::DopplerTracking)
#endif // AUDIO_STREAM_PLAYER_3D_H
diff --git a/scene/3d/bone_attachment_3d.cpp b/scene/3d/bone_attachment_3d.cpp
index 5315e685a0..d0aeffb166 100644
--- a/scene/3d/bone_attachment_3d.cpp
+++ b/scene/3d/bone_attachment_3d.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -32,7 +32,15 @@
void BoneAttachment3D::_validate_property(PropertyInfo &property) const {
if (property.name == "bone_name") {
- Skeleton3D *parent = Object::cast_to<Skeleton3D>(get_parent());
+ // Because it is a constant function, we cannot use the _get_skeleton_3d function.
+ const Skeleton3D *parent = nullptr;
+ if (use_external_skeleton) {
+ if (external_skeleton_node_cache.is_valid()) {
+ parent = Object::cast_to<Skeleton3D>(ObjectDB::get_instance(external_skeleton_node_cache));
+ }
+ } else {
+ parent = Object::cast_to<Skeleton3D>(get_parent());
+ }
if (parent) {
String names;
@@ -50,57 +58,322 @@ void BoneAttachment3D::_validate_property(PropertyInfo &property) const {
property.hint_string = "";
}
}
+
+ Node3D::_validate_property(property);
+}
+
+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")) {
+ set_use_external_skeleton(p_value);
+ } else if (p_path == SNAME("external_skeleton")) {
+ set_external_skeleton(p_value);
+ }
+
+ return true;
+}
+
+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")) {
+ r_ret = get_use_external_skeleton();
+ } else if (p_path == SNAME("external_skeleton")) {
+ r_ret = get_external_skeleton();
+ }
+
+ return true;
+}
+
+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"));
+ }
+}
+
+TypedArray<String> BoneAttachment3D::get_configuration_warnings() const {
+ TypedArray<String> warnings = Node3D::get_configuration_warnings();
+
+ if (use_external_skeleton) {
+ if (external_skeleton_node_cache.is_null()) {
+ warnings.push_back(RTR("External Skeleton3D node not set! Please set a path to an external Skeleton3D node."));
+ }
+ } else {
+ Skeleton3D *parent = Object::cast_to<Skeleton3D>(get_parent());
+ if (!parent) {
+ warnings.push_back(RTR("Parent node is not a Skeleton3D node! Please use an external Skeleton3D if you intend to use the BoneAttachment3D without it being a child of a Skeleton3D node."));
+ }
+ }
+
+ if (bone_idx == -1) {
+ warnings.push_back(RTR("BoneAttachment3D node is not bound to any bones! Please select a bone to attach this node."));
+ }
+
+ return warnings;
+}
+
+void BoneAttachment3D::_update_external_skeleton_cache() {
+ external_skeleton_node_cache = ObjectID();
+ if (has_node(external_skeleton_node)) {
+ Node *node = get_node(external_skeleton_node);
+ ERR_FAIL_COND_MSG(!node, "Cannot update external skeleton cache: Node cannot be found!");
+
+ // Make sure it's a skeleton3D
+ Skeleton3D *sk = Object::cast_to<Skeleton3D>(node);
+ ERR_FAIL_COND_MSG(!sk, "Cannot update external skeleton cache: Skeleton3D Nodepath does not point to a Skeleton3D node!");
+
+ external_skeleton_node_cache = node->get_instance_id();
+ } else {
+ if (external_skeleton_node.is_empty()) {
+ BoneAttachment3D *parent_attachment = Object::cast_to<BoneAttachment3D>(get_parent());
+ if (parent_attachment) {
+ parent_attachment->_update_external_skeleton_cache();
+ if (parent_attachment->has_node(parent_attachment->external_skeleton_node)) {
+ Node *node = parent_attachment->get_node(parent_attachment->external_skeleton_node);
+ ERR_FAIL_COND_MSG(!node, "Cannot update external skeleton cache: Parent's Skeleton3D node cannot be found!");
+
+ // Make sure it's a skeleton3D
+ Skeleton3D *sk = Object::cast_to<Skeleton3D>(node);
+ ERR_FAIL_COND_MSG(!sk, "Cannot update external skeleton cache: Parent Skeleton3D Nodepath does not point to a Skeleton3D node!");
+
+ external_skeleton_node_cache = node->get_instance_id();
+ external_skeleton_node = get_path_to(node);
+ }
+ }
+ }
+ }
}
void BoneAttachment3D::_check_bind() {
- Skeleton3D *sk = Object::cast_to<Skeleton3D>(get_parent());
- if (sk) {
- int idx = sk->find_bone(bone_name);
- if (idx != -1) {
- sk->bind_child_node_to_bone(idx, this);
- set_transform(sk->get_bone_global_pose(idx));
+ Skeleton3D *sk = _get_skeleton3d();
+
+ if (sk && !bound) {
+ if (bone_idx <= -1) {
+ bone_idx = sk->find_bone(bone_name);
+ }
+ if (bone_idx != -1) {
+ sk->call_deferred(SNAME("connect"), "bone_pose_changed", callable_mp(this, &BoneAttachment3D::on_bone_pose_update));
bound = true;
+ call_deferred(SNAME("on_bone_pose_update"), bone_idx);
+ }
+ }
+}
+
+Skeleton3D *BoneAttachment3D::_get_skeleton3d() {
+ if (use_external_skeleton) {
+ if (external_skeleton_node_cache.is_valid()) {
+ return Object::cast_to<Skeleton3D>(ObjectDB::get_instance(external_skeleton_node_cache));
+ } else {
+ _update_external_skeleton_cache();
+ if (external_skeleton_node_cache.is_valid()) {
+ return Object::cast_to<Skeleton3D>(ObjectDB::get_instance(external_skeleton_node_cache));
+ }
}
+ } else {
+ return Object::cast_to<Skeleton3D>(get_parent());
}
+ return nullptr;
}
void BoneAttachment3D::_check_unbind() {
if (bound) {
- Skeleton3D *sk = Object::cast_to<Skeleton3D>(get_parent());
+ Skeleton3D *sk = _get_skeleton3d();
+
if (sk) {
- int idx = sk->find_bone(bone_name);
- if (idx != -1) {
- sk->unbind_child_node_from_bone(idx, this);
- }
+ sk->disconnect(SNAME("bone_pose_changed"), callable_mp(this, &BoneAttachment3D::on_bone_pose_update));
}
bound = false;
}
}
+void BoneAttachment3D::_transform_changed() {
+ if (!is_inside_tree()) {
+ return;
+ }
+
+ if (override_pose) {
+ Skeleton3D *sk = _get_skeleton3d();
+
+ ERR_FAIL_COND_MSG(!sk, "Cannot override pose: Skeleton not found!");
+ ERR_FAIL_INDEX_MSG(bone_idx, sk->get_bone_count(), "Cannot override pose: Bone index is out of range!");
+
+ Transform3D our_trans = get_transform();
+ if (use_external_skeleton) {
+ our_trans = sk->world_transform_to_global_pose(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);
+ }
+ }
+}
+
void BoneAttachment3D::set_bone_name(const String &p_name) {
+ bone_name = p_name;
+ Skeleton3D *sk = _get_skeleton3d();
+ if (sk) {
+ set_bone_idx(sk->find_bone(bone_name));
+ }
+}
+
+String BoneAttachment3D::get_bone_name() const {
+ return bone_name;
+}
+
+void BoneAttachment3D::set_bone_idx(const int &p_idx) {
if (is_inside_tree()) {
_check_unbind();
}
- bone_name = p_name;
+ bone_idx = p_idx;
+
+ Skeleton3D *sk = _get_skeleton3d();
+ if (sk) {
+ if (bone_idx <= -1 || bone_idx >= sk->get_bone_count()) {
+ WARN_PRINT("Bone index out of range! Cannot connect BoneAttachment to node!");
+ bone_idx = -1;
+ } else {
+ bone_name = sk->get_bone_name(bone_idx);
+ }
+ }
if (is_inside_tree()) {
_check_bind();
}
+
+ notify_property_list_changed();
}
-String BoneAttachment3D::get_bone_name() const {
- return bone_name;
+int BoneAttachment3D::get_bone_idx() const {
+ return bone_idx;
+}
+
+void BoneAttachment3D::set_override_pose(bool p_override) {
+ override_pose = p_override;
+ set_notify_local_transform(override_pose);
+ set_process_internal(override_pose);
+
+ 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);
+ }
+ }
+ _transform_changed();
+ }
+ notify_property_list_changed();
+}
+
+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;
+
+ if (use_external_skeleton) {
+ _check_unbind();
+ _update_external_skeleton_cache();
+ _check_bind();
+ _transform_changed();
+ }
+
+ notify_property_list_changed();
+}
+
+bool BoneAttachment3D::get_use_external_skeleton() const {
+ return use_external_skeleton;
+}
+
+void BoneAttachment3D::set_external_skeleton(NodePath p_path) {
+ external_skeleton_node = p_path;
+ _update_external_skeleton_cache();
+ notify_property_list_changed();
+}
+
+NodePath BoneAttachment3D::get_external_skeleton() const {
+ return external_skeleton_node;
}
void BoneAttachment3D::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
+ if (use_external_skeleton) {
+ _update_external_skeleton_cache();
+ }
_check_bind();
} break;
+
case NOTIFICATION_EXIT_TREE: {
_check_unbind();
} break;
+
+ case NOTIFICATION_LOCAL_TRANSFORM_CHANGED: {
+ _transform_changed();
+ } break;
+
+ case NOTIFICATION_INTERNAL_PROCESS: {
+ if (_override_dirty) {
+ _override_dirty = false;
+ }
+ } break;
+ }
+}
+
+void BoneAttachment3D::on_bone_pose_update(int p_bone_index) {
+ if (bone_idx == p_bone_index) {
+ Skeleton3D *sk = _get_skeleton3d();
+ 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)));
+ } else {
+ set_transform(sk->get_bone_global_pose(bone_idx));
+ }
+ } else {
+ if (!_override_dirty) {
+ _transform_changed();
+ _override_dirty = true;
+ }
+ }
+ }
}
}
@@ -111,5 +384,21 @@ void BoneAttachment3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_bone_name", "bone_name"), &BoneAttachment3D::set_bone_name);
ClassDB::bind_method(D_METHOD("get_bone_name"), &BoneAttachment3D::get_bone_name);
+ ClassDB::bind_method(D_METHOD("set_bone_idx", "bone_idx"), &BoneAttachment3D::set_bone_idx);
+ ClassDB::bind_method(D_METHOD("get_bone_idx"), &BoneAttachment3D::get_bone_idx);
+
+ ClassDB::bind_method(D_METHOD("on_bone_pose_update", "bone_index"), &BoneAttachment3D::on_bone_pose_update);
+
+ 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);
+ ClassDB::bind_method(D_METHOD("set_external_skeleton", "external_skeleton"), &BoneAttachment3D::set_external_skeleton);
+ ClassDB::bind_method(D_METHOD("get_external_skeleton"), &BoneAttachment3D::get_external_skeleton);
+
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");
}
diff --git a/scene/3d/bone_attachment_3d.h b/scene/3d/bone_attachment_3d.h
index 0c6d5f12b1..395dfde1d7 100644
--- a/scene/3d/bone_attachment_3d.h
+++ b/scene/3d/bone_attachment_3d.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -38,20 +38,58 @@ class BoneAttachment3D : public Node3D {
bool bound = false;
String bone_name;
+ 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;
void _check_bind();
void _check_unbind();
+ void _transform_changed();
+ void _update_external_skeleton_cache();
+ Skeleton3D *_get_skeleton3d();
+
protected:
virtual void _validate_property(PropertyInfo &property) const override;
+ 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;
void _notification(int p_what);
static void _bind_methods();
public:
+ virtual TypedArray<String> get_configuration_warnings() const override;
+
void set_bone_name(const String &p_name);
String get_bone_name() const;
+ void set_bone_idx(const int &p_idx);
+ int get_bone_idx() const;
+
+ 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;
+ void set_external_skeleton(NodePath p_skeleton);
+ NodePath get_external_skeleton() const;
+
+ virtual void on_bone_pose_update(int p_bone_index);
+
BoneAttachment3D();
};
diff --git a/scene/3d/camera_3d.cpp b/scene/3d/camera_3d.cpp
index 041da4f6ff..4f05e80377 100644
--- a/scene/3d/camera_3d.cpp
+++ b/scene/3d/camera_3d.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -31,10 +31,8 @@
#include "camera_3d.h"
#include "collision_object_3d.h"
-#include "core/config/engine.h"
#include "core/math/camera_matrix.h"
-#include "scene/resources/material.h"
-#include "scene/resources/surface_tool.h"
+#include "scene/main/viewport.h"
void Camera3D::_update_audio_listener_state() {
}
@@ -62,17 +60,19 @@ void Camera3D::_update_camera_mode() {
void Camera3D::_validate_property(PropertyInfo &p_property) const {
if (p_property.name == "fov") {
if (mode != PROJECTION_PERSPECTIVE) {
- p_property.usage = PROPERTY_USAGE_NOEDITOR;
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
} else if (p_property.name == "size") {
if (mode != PROJECTION_ORTHOGONAL && mode != PROJECTION_FRUSTUM) {
- p_property.usage = PROPERTY_USAGE_NOEDITOR;
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
} else if (p_property.name == "frustum_offset") {
if (mode != PROJECTION_FRUSTUM) {
- p_property.usage = PROPERTY_USAGE_NOEDITOR;
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
}
}
+
+ Node3D::_validate_property(p_property);
}
void Camera3D::_update_camera() {
@@ -82,21 +82,11 @@ void Camera3D::_update_camera() {
RenderingServer::get_singleton()->camera_set_transform(camera, get_camera_transform());
- // here goes listener stuff
- /*
- if (viewport_ptr && is_inside_scene() && is_current())
- get_viewport()->_camera_transform_changed_notify();
- */
-
if (get_tree()->is_node_being_edited(this) || !is_current()) {
return;
}
- get_viewport()->_camera_transform_changed_notify();
-
- if (get_world_3d().is_valid()) {
- get_world_3d()->_update_camera(this);
- }
+ get_viewport()->_camera_3d_transform_changed_notify();
}
void Camera3D::_notification(int p_what) {
@@ -108,18 +98,19 @@ void Camera3D::_notification(int p_what) {
viewport = get_viewport();
ERR_FAIL_COND(!viewport);
- bool first_camera = viewport->_camera_add(this);
+ bool first_camera = viewport->_camera_3d_add(this);
if (current || first_camera) {
- viewport->_camera_set(this);
+ viewport->_camera_3d_set(this);
}
-
} break;
+
case NOTIFICATION_TRANSFORM_CHANGED: {
_request_camera_update();
if (doppler_tracking != DOPPLER_TRACKING_DISABLED) {
velocity_tracker->update_position(get_global_transform().origin);
}
} break;
+
case NOTIFICATION_EXIT_WORLD: {
if (!get_tree()->is_node_being_edited(this)) {
if (is_current()) {
@@ -132,16 +123,17 @@ void Camera3D::_notification(int p_what) {
}
if (viewport) {
- viewport->_camera_remove(this);
+ viewport->_camera_3d_remove(this);
viewport = nullptr;
}
-
} break;
+
case NOTIFICATION_BECAME_CURRENT: {
if (viewport) {
viewport->find_world_3d()->_register_camera(this);
}
} break;
+
case NOTIFICATION_LOST_CURRENT: {
if (viewport) {
viewport->find_world_3d()->_remove_camera(this);
@@ -150,14 +142,14 @@ void Camera3D::_notification(int p_what) {
}
}
-Transform Camera3D::get_camera_transform() const {
- Transform tr = get_global_transform().orthonormalized();
- tr.origin += tr.basis.get_axis(1) * v_offset;
- tr.origin += tr.basis.get_axis(0) * h_offset;
+Transform3D Camera3D::get_camera_transform() const {
+ Transform3D tr = get_global_transform().orthonormalized();
+ tr.origin += tr.basis.get_column(1) * v_offset;
+ tr.origin += tr.basis.get_column(0) * h_offset;
return tr;
}
-void Camera3D::set_perspective(float p_fovy_degrees, float p_z_near, float p_z_far) {
+void Camera3D::set_perspective(real_t p_fovy_degrees, real_t p_z_near, real_t p_z_far) {
if (!force_change && fov == p_fovy_degrees && p_z_near == near && p_z_far == far && mode == PROJECTION_PERSPECTIVE) {
return;
}
@@ -168,11 +160,11 @@ void Camera3D::set_perspective(float p_fovy_degrees, float p_z_near, float p_z_f
mode = PROJECTION_PERSPECTIVE;
RenderingServer::get_singleton()->camera_set_perspective(camera, fov, near, far);
- update_gizmo();
+ update_gizmos();
force_change = false;
}
-void Camera3D::set_orthogonal(float p_size, float p_z_near, float p_z_far) {
+void Camera3D::set_orthogonal(real_t p_size, real_t p_z_near, real_t p_z_far) {
if (!force_change && size == p_size && p_z_near == near && p_z_far == far && mode == PROJECTION_ORTHOGONAL) {
return;
}
@@ -185,10 +177,10 @@ void Camera3D::set_orthogonal(float p_size, float p_z_near, float p_z_far) {
force_change = false;
RenderingServer::get_singleton()->camera_set_orthogonal(camera, size, near, far);
- update_gizmo();
+ update_gizmos();
}
-void Camera3D::set_frustum(float p_size, Vector2 p_offset, float p_z_near, float p_z_far) {
+void Camera3D::set_frustum(real_t p_size, Vector2 p_offset, real_t p_z_near, real_t p_z_far) {
if (!force_change && size == p_size && frustum_offset == p_offset && p_z_near == near && p_z_far == far && mode == PROJECTION_FRUSTUM) {
return;
}
@@ -202,7 +194,7 @@ void Camera3D::set_frustum(float p_size, Vector2 p_offset, float p_z_near, float
force_change = false;
RenderingServer::get_singleton()->camera_set_frustum(camera, size, frustum_offset, near, far);
- update_gizmo();
+ update_gizmos();
}
void Camera3D::set_projection(Camera3D::Projection p_mode) {
@@ -224,7 +216,7 @@ void Camera3D::make_current() {
return;
}
- get_viewport()->_camera_set(this);
+ get_viewport()->_camera_3d_set(this);
//get_scene()->call_group(SceneMainLoop::GROUP_CALL_REALTIME,camera_group,"_camera_make_current",this);
}
@@ -235,17 +227,17 @@ void Camera3D::clear_current(bool p_enable_next) {
return;
}
- if (get_viewport()->get_camera() == this) {
- get_viewport()->_camera_set(nullptr);
+ if (get_viewport()->get_camera_3d() == this) {
+ get_viewport()->_camera_3d_set(nullptr);
if (p_enable_next) {
- get_viewport()->_camera_make_next_current(this);
+ get_viewport()->_camera_3d_make_next_current(this);
}
}
}
-void Camera3D::set_current(bool p_current) {
- if (p_current) {
+void Camera3D::set_current(bool p_enabled) {
+ if (p_enabled) {
make_current();
} else {
clear_current();
@@ -254,16 +246,12 @@ void Camera3D::set_current(bool p_current) {
bool Camera3D::is_current() const {
if (is_inside_tree() && !get_tree()->is_node_being_edited(this)) {
- return get_viewport()->get_camera() == this;
+ return get_viewport()->get_camera_3d() == this;
} else {
return current;
}
}
-bool Camera3D::_can_gizmo_scale() const {
- return false;
-}
-
Vector3 Camera3D::project_ray_normal(const Point2 &p_pos) const {
Vector3 ray = project_local_ray_normal(p_pos);
return get_camera_transform().basis.xform(ray).normalized();
@@ -299,7 +287,7 @@ Vector3 Camera3D::project_ray_origin(const Point2 &p_pos) const {
return get_camera_transform().origin;
} else {
Vector2 pos = cpos / viewport_size;
- float vsize, hsize;
+ real_t vsize, hsize;
if (keep_aspect == KEEP_WIDTH) {
vsize = size / viewport_size.aspect();
hsize = size;
@@ -318,8 +306,8 @@ Vector3 Camera3D::project_ray_origin(const Point2 &p_pos) const {
};
bool Camera3D::is_position_behind(const Vector3 &p_pos) const {
- Transform t = get_global_transform();
- Vector3 eyedir = -t.basis.get_axis(2).normalized();
+ Transform3D t = get_global_transform();
+ Vector3 eyedir = -t.basis.get_column(2).normalized();
return eyedir.dot(p_pos - t.origin) < near;
}
@@ -337,13 +325,15 @@ Vector<Vector3> Camera3D::get_near_plane_points() const {
}
Vector3 endpoints[8];
- cm.get_endpoints(Transform(), endpoints);
-
- Vector<Vector3> points;
- points.push_back(Vector3());
- for (int i = 0; i < 4; i++) {
- points.push_back(endpoints[i + 4]);
- }
+ cm.get_endpoints(Transform3D(), endpoints);
+
+ Vector<Vector3> points = {
+ Vector3(),
+ endpoints[4],
+ endpoints[5],
+ endpoints[6],
+ endpoints[7]
+ };
return points;
}
@@ -372,7 +362,7 @@ Point2 Camera3D::unproject_position(const Vector3 &p_pos) const {
return res;
}
-Vector3 Camera3D::project_position(const Point2 &p_point, float p_z_depth) const {
+Vector3 Camera3D::project_position(const Point2 &p_point, real_t p_z_depth) const {
ERR_FAIL_COND_V_MSG(!is_inside_tree(), Vector3(), "Camera is not inside scene.");
if (p_z_depth == 0 && mode != PROJECTION_ORTHOGONAL) {
@@ -470,7 +460,7 @@ void Camera3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_frustum", "size", "offset", "z_near", "z_far"), &Camera3D::set_frustum);
ClassDB::bind_method(D_METHOD("make_current"), &Camera3D::make_current);
ClassDB::bind_method(D_METHOD("clear_current", "enable_next"), &Camera3D::clear_current, DEFVAL(true));
- ClassDB::bind_method(D_METHOD("set_current"), &Camera3D::set_current);
+ ClassDB::bind_method(D_METHOD("set_current", "enabled"), &Camera3D::set_current);
ClassDB::bind_method(D_METHOD("is_current"), &Camera3D::is_current);
ClassDB::bind_method(D_METHOD("get_camera_transform"), &Camera3D::get_camera_transform);
ClassDB::bind_method(D_METHOD("get_fov"), &Camera3D::get_fov);
@@ -478,16 +468,16 @@ void Camera3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_size"), &Camera3D::get_size);
ClassDB::bind_method(D_METHOD("get_far"), &Camera3D::get_far);
ClassDB::bind_method(D_METHOD("get_near"), &Camera3D::get_near);
- ClassDB::bind_method(D_METHOD("set_fov"), &Camera3D::set_fov);
- ClassDB::bind_method(D_METHOD("set_frustum_offset"), &Camera3D::set_frustum_offset);
- ClassDB::bind_method(D_METHOD("set_size"), &Camera3D::set_size);
- ClassDB::bind_method(D_METHOD("set_far"), &Camera3D::set_far);
- ClassDB::bind_method(D_METHOD("set_near"), &Camera3D::set_near);
+ ClassDB::bind_method(D_METHOD("set_fov", "fov"), &Camera3D::set_fov);
+ ClassDB::bind_method(D_METHOD("set_frustum_offset", "offset"), &Camera3D::set_frustum_offset);
+ ClassDB::bind_method(D_METHOD("set_size", "size"), &Camera3D::set_size);
+ ClassDB::bind_method(D_METHOD("set_far", "far"), &Camera3D::set_far);
+ ClassDB::bind_method(D_METHOD("set_near", "near"), &Camera3D::set_near);
ClassDB::bind_method(D_METHOD("get_projection"), &Camera3D::get_projection);
- ClassDB::bind_method(D_METHOD("set_projection"), &Camera3D::set_projection);
- ClassDB::bind_method(D_METHOD("set_h_offset", "ofs"), &Camera3D::set_h_offset);
+ ClassDB::bind_method(D_METHOD("set_projection", "mode"), &Camera3D::set_projection);
+ ClassDB::bind_method(D_METHOD("set_h_offset", "offset"), &Camera3D::set_h_offset);
ClassDB::bind_method(D_METHOD("get_h_offset"), &Camera3D::get_h_offset);
- ClassDB::bind_method(D_METHOD("set_v_offset", "ofs"), &Camera3D::set_v_offset);
+ ClassDB::bind_method(D_METHOD("set_v_offset", "offset"), &Camera3D::set_v_offset);
ClassDB::bind_method(D_METHOD("get_v_offset"), &Camera3D::get_v_offset);
ClassDB::bind_method(D_METHOD("set_cull_mask", "mask"), &Camera3D::set_cull_mask);
ClassDB::bind_method(D_METHOD("get_cull_mask"), &Camera3D::get_cull_mask);
@@ -500,10 +490,12 @@ void Camera3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_doppler_tracking", "mode"), &Camera3D::set_doppler_tracking);
ClassDB::bind_method(D_METHOD("get_doppler_tracking"), &Camera3D::get_doppler_tracking);
ClassDB::bind_method(D_METHOD("get_frustum"), &Camera3D::get_frustum);
+ ClassDB::bind_method(D_METHOD("is_position_in_frustum", "world_point"), &Camera3D::is_position_in_frustum);
ClassDB::bind_method(D_METHOD("get_camera_rid"), &Camera3D::get_camera);
+ ClassDB::bind_method(D_METHOD("get_pyramid_shape_rid"), &Camera3D::get_pyramid_shape_rid);
- ClassDB::bind_method(D_METHOD("set_cull_mask_bit", "layer", "enable"), &Camera3D::set_cull_mask_bit);
- ClassDB::bind_method(D_METHOD("get_cull_mask_bit", "layer"), &Camera3D::get_cull_mask_bit);
+ ClassDB::bind_method(D_METHOD("set_cull_mask_value", "layer_number", "value"), &Camera3D::set_cull_mask_value);
+ ClassDB::bind_method(D_METHOD("get_cull_mask_value", "layer_number"), &Camera3D::get_cull_mask_value);
//ClassDB::bind_method(D_METHOD("_camera_make_current"),&Camera::_camera_make_current );
@@ -516,11 +508,11 @@ void Camera3D::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::INT, "doppler_tracking", PROPERTY_HINT_ENUM, "Disabled,Idle,Physics"), "set_doppler_tracking", "get_doppler_tracking");
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"), "set_fov", "get_fov");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "size", PROPERTY_HINT_RANGE, "0.1,16384,0.01"), "set_size", "get_size");
+ 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"), "set_size", "get_size");
ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "frustum_offset"), "set_frustum_offset", "get_frustum_offset");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "near", PROPERTY_HINT_EXP_RANGE, "0.001,10,0.001,or_greater"), "set_near", "get_near");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "far", PROPERTY_HINT_EXP_RANGE, "0.01,4000,0.01,or_greater"), "set_far", "get_far");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "near", PROPERTY_HINT_RANGE, "0.001,10,0.001,or_greater,exp"), "set_near", "get_near");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "far", PROPERTY_HINT_RANGE, "0.01,4000,0.01,or_greater,exp"), "set_far", "get_far");
BIND_ENUM_CONSTANT(PROJECTION_PERSPECTIVE);
BIND_ENUM_CONSTANT(PROJECTION_ORTHOGONAL);
@@ -534,15 +526,15 @@ void Camera3D::_bind_methods() {
BIND_ENUM_CONSTANT(DOPPLER_TRACKING_PHYSICS_STEP);
}
-float Camera3D::get_fov() const {
+real_t Camera3D::get_fov() const {
return fov;
}
-float Camera3D::get_size() const {
+real_t Camera3D::get_size() const {
return size;
}
-float Camera3D::get_near() const {
+real_t Camera3D::get_near() const {
return near;
}
@@ -550,7 +542,7 @@ Vector2 Camera3D::get_frustum_offset() const {
return frustum_offset;
}
-float Camera3D::get_far() const {
+real_t Camera3D::get_far() const {
return far;
}
@@ -558,19 +550,19 @@ Camera3D::Projection Camera3D::get_projection() const {
return mode;
}
-void Camera3D::set_fov(float p_fov) {
+void Camera3D::set_fov(real_t p_fov) {
ERR_FAIL_COND(p_fov < 1 || p_fov > 179);
fov = p_fov;
_update_camera_mode();
}
-void Camera3D::set_size(float p_size) {
- ERR_FAIL_COND(p_size < 0.1 || p_size > 16384);
+void Camera3D::set_size(real_t p_size) {
+ ERR_FAIL_COND(p_size < 0.001 || p_size > 16384);
size = p_size;
_update_camera_mode();
}
-void Camera3D::set_near(float p_near) {
+void Camera3D::set_near(real_t p_near) {
near = p_near;
_update_camera_mode();
}
@@ -580,7 +572,7 @@ void Camera3D::set_frustum_offset(Vector2 p_offset) {
_update_camera_mode();
}
-void Camera3D::set_far(float p_far) {
+void Camera3D::set_far(real_t p_far) {
far = p_far;
_update_camera_mode();
}
@@ -595,18 +587,22 @@ uint32_t Camera3D::get_cull_mask() const {
return layers;
}
-void Camera3D::set_cull_mask_bit(int p_layer, bool p_enable) {
- ERR_FAIL_INDEX(p_layer, 32);
- if (p_enable) {
- set_cull_mask(layers | (1 << p_layer));
+void Camera3D::set_cull_mask_value(int p_layer_number, bool p_value) {
+ ERR_FAIL_COND_MSG(p_layer_number < 1, "Render layer number must be between 1 and 20 inclusive.");
+ ERR_FAIL_COND_MSG(p_layer_number > 20, "Render layer number must be between 1 and 20 inclusive.");
+ uint32_t mask = get_cull_mask();
+ if (p_value) {
+ mask |= 1 << (p_layer_number - 1);
} else {
- set_cull_mask(layers & (~(1 << p_layer)));
+ mask &= ~(1 << (p_layer_number - 1));
}
+ set_cull_mask(mask);
}
-bool Camera3D::get_cull_mask_bit(int p_layer) const {
- ERR_FAIL_INDEX_V(p_layer, 32, false);
- return (layers & (1 << p_layer));
+bool Camera3D::get_cull_mask_value(int p_layer_number) const {
+ ERR_FAIL_COND_V_MSG(p_layer_number < 1, false, "Render layer number must be between 1 and 20 inclusive.");
+ ERR_FAIL_COND_V_MSG(p_layer_number > 20, false, "Render layer number must be between 1 and 20 inclusive.");
+ return layers & (1 << (p_layer_number - 1));
}
Vector<Plane> Camera3D::get_frustum() const {
@@ -623,21 +619,31 @@ Vector<Plane> Camera3D::get_frustum() const {
return cm.get_projection_planes(get_camera_transform());
}
-void Camera3D::set_v_offset(float p_offset) {
+bool Camera3D::is_position_in_frustum(const Vector3 &p_position) const {
+ Vector<Plane> frustum = get_frustum();
+ for (int i = 0; i < frustum.size(); i++) {
+ if (frustum[i].is_point_over(p_position)) {
+ return false;
+ }
+ }
+ return true;
+}
+
+void Camera3D::set_v_offset(real_t p_offset) {
v_offset = p_offset;
_update_camera();
}
-float Camera3D::get_v_offset() const {
+real_t Camera3D::get_v_offset() const {
return v_offset;
}
-void Camera3D::set_h_offset(float p_offset) {
+void Camera3D::set_h_offset(real_t p_offset) {
h_offset = p_offset;
_update_camera();
}
-float Camera3D::get_h_offset() const {
+real_t Camera3D::get_h_offset() const {
return h_offset;
}
@@ -649,231 +655,47 @@ Vector3 Camera3D::get_doppler_tracked_velocity() const {
}
}
-Camera3D::Camera3D() {
- camera = RenderingServer::get_singleton()->camera_create();
- set_perspective(75.0, 0.05, 4000.0);
- RenderingServer::get_singleton()->camera_set_cull_mask(camera, layers);
- //active=false;
- velocity_tracker.instance();
- set_notify_transform(true);
- set_disable_scale(true);
-}
+RID Camera3D::get_pyramid_shape_rid() {
+ ERR_FAIL_COND_V_MSG(!is_inside_tree(), RID(), "Camera is not inside scene.");
+ if (pyramid_shape == RID()) {
+ pyramid_shape_points = get_near_plane_points();
+ pyramid_shape = PhysicsServer3D::get_singleton()->convex_polygon_shape_create();
+ PhysicsServer3D::get_singleton()->shape_set_data(pyramid_shape, pyramid_shape_points);
-Camera3D::~Camera3D() {
- RenderingServer::get_singleton()->free(camera);
-}
-
-////////////////////////////////////////
-
-void ClippedCamera3D::set_margin(float p_margin) {
- margin = p_margin;
-}
+ } else { //check if points changed
+ Vector<Vector3> local_points = get_near_plane_points();
-float ClippedCamera3D::get_margin() const {
- return margin;
-}
-
-void ClippedCamera3D::set_process_callback(ClipProcessCallback p_mode) {
- if (process_callback == p_mode) {
- return;
- }
- process_callback = p_mode;
- set_process_internal(process_callback == CLIP_PROCESS_IDLE);
- set_physics_process_internal(process_callback == CLIP_PROCESS_PHYSICS);
-}
-
-ClippedCamera3D::ClipProcessCallback ClippedCamera3D::get_process_callback() const {
- return process_callback;
-}
-
-Transform ClippedCamera3D::get_camera_transform() const {
- Transform t = Camera3D::get_camera_transform();
- t.origin += -t.basis.get_axis(Vector3::AXIS_Z).normalized() * clip_offset;
- return t;
-}
-
-void ClippedCamera3D::_notification(int p_what) {
- if (p_what == NOTIFICATION_INTERNAL_PROCESS || p_what == NOTIFICATION_INTERNAL_PHYSICS_PROCESS) {
- Node3D *parent = Object::cast_to<Node3D>(get_parent());
- if (!parent) {
- return;
- }
+ bool all_equal = true;
- PhysicsDirectSpaceState3D *dspace = get_world_3d()->get_direct_space_state();
- ERR_FAIL_COND(!dspace); // most likely physics set to threads
-
- Vector3 cam_fw = -get_global_transform().basis.get_axis(Vector3::AXIS_Z).normalized();
- Vector3 cam_pos = get_global_transform().origin;
- Vector3 parent_pos = parent->get_global_transform().origin;
-
- Plane parent_plane(parent_pos, cam_fw);
-
- if (parent_plane.is_point_over(cam_pos)) {
- //cam is beyond parent plane
- return;
- }
-
- Vector3 ray_from = parent_plane.project(cam_pos);
-
- clip_offset = 0; //reset by default
-
- { //check if points changed
- Vector<Vector3> local_points = get_near_plane_points();
-
- bool all_equal = true;
-
- for (int i = 0; i < 5; i++) {
- if (points[i] != local_points[i]) {
- all_equal = false;
- break;
- }
- }
-
- if (!all_equal) {
- PhysicsServer3D::get_singleton()->shape_set_data(pyramid_shape, local_points);
- points = local_points;
+ for (int i = 0; i < 5; i++) {
+ if (local_points[i] != pyramid_shape_points[i]) {
+ all_equal = false;
+ break;
}
}
- Transform xf = get_global_transform();
- xf.origin = ray_from;
- xf.orthonormalize();
-
- float closest_safe = 1.0f, closest_unsafe = 1.0f;
- if (dspace->cast_motion(pyramid_shape, xf, cam_pos - ray_from, margin, closest_safe, closest_unsafe, exclude, collision_mask, clip_to_bodies, clip_to_areas)) {
- clip_offset = cam_pos.distance_to(ray_from + (cam_pos - ray_from) * closest_safe);
+ if (!all_equal) {
+ PhysicsServer3D::get_singleton()->shape_set_data(pyramid_shape, local_points);
+ pyramid_shape_points = local_points;
}
-
- _update_camera();
}
- if (p_what == NOTIFICATION_LOCAL_TRANSFORM_CHANGED) {
- update_gizmo();
- }
-}
-
-void ClippedCamera3D::set_collision_mask(uint32_t p_mask) {
- collision_mask = p_mask;
-}
-
-uint32_t ClippedCamera3D::get_collision_mask() const {
- return collision_mask;
+ return pyramid_shape;
}
-void ClippedCamera3D::set_collision_mask_bit(int p_bit, bool p_value) {
- ERR_FAIL_INDEX_MSG(p_bit, 32, "Collision layer bit must be between 0 and 31 inclusive.");
- uint32_t mask = get_collision_mask();
- if (p_value) {
- mask |= 1 << p_bit;
- } else {
- mask &= ~(1 << p_bit);
- }
- set_collision_mask(mask);
-}
-
-bool ClippedCamera3D::get_collision_mask_bit(int p_bit) const {
- ERR_FAIL_INDEX_V_MSG(p_bit, 32, false, "Collision mask bit must be between 0 and 31 inclusive.");
- return get_collision_mask() & (1 << p_bit);
-}
-
-void ClippedCamera3D::add_exception_rid(const RID &p_rid) {
- exclude.insert(p_rid);
-}
-
-void ClippedCamera3D::add_exception(const Object *p_object) {
- ERR_FAIL_NULL(p_object);
- const CollisionObject3D *co = Object::cast_to<CollisionObject3D>(p_object);
- if (!co) {
- return;
- }
- add_exception_rid(co->get_rid());
-}
-
-void ClippedCamera3D::remove_exception_rid(const RID &p_rid) {
- exclude.erase(p_rid);
+Camera3D::Camera3D() {
+ camera = RenderingServer::get_singleton()->camera_create();
+ set_perspective(75.0, 0.05, 4000.0);
+ RenderingServer::get_singleton()->camera_set_cull_mask(camera, layers);
+ //active=false;
+ velocity_tracker.instantiate();
+ set_notify_transform(true);
+ set_disable_scale(true);
}
-void ClippedCamera3D::remove_exception(const Object *p_object) {
- ERR_FAIL_NULL(p_object);
- const CollisionObject3D *co = Object::cast_to<CollisionObject3D>(p_object);
- if (!co) {
- return;
+Camera3D::~Camera3D() {
+ RenderingServer::get_singleton()->free(camera);
+ if (pyramid_shape.is_valid()) {
+ PhysicsServer3D::get_singleton()->free(pyramid_shape);
}
- remove_exception_rid(co->get_rid());
-}
-
-void ClippedCamera3D::clear_exceptions() {
- exclude.clear();
-}
-
-float ClippedCamera3D::get_clip_offset() const {
- return clip_offset;
-}
-
-void ClippedCamera3D::set_clip_to_areas(bool p_clip) {
- clip_to_areas = p_clip;
-}
-
-bool ClippedCamera3D::is_clip_to_areas_enabled() const {
- return clip_to_areas;
-}
-
-void ClippedCamera3D::set_clip_to_bodies(bool p_clip) {
- clip_to_bodies = p_clip;
-}
-
-bool ClippedCamera3D::is_clip_to_bodies_enabled() const {
- return clip_to_bodies;
-}
-
-void ClippedCamera3D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_margin", "margin"), &ClippedCamera3D::set_margin);
- ClassDB::bind_method(D_METHOD("get_margin"), &ClippedCamera3D::get_margin);
-
- ClassDB::bind_method(D_METHOD("set_process_callback", "process_callback"), &ClippedCamera3D::set_process_callback);
- ClassDB::bind_method(D_METHOD("get_process_callback"), &ClippedCamera3D::get_process_callback);
-
- ClassDB::bind_method(D_METHOD("set_collision_mask", "mask"), &ClippedCamera3D::set_collision_mask);
- ClassDB::bind_method(D_METHOD("get_collision_mask"), &ClippedCamera3D::get_collision_mask);
-
- ClassDB::bind_method(D_METHOD("set_collision_mask_bit", "bit", "value"), &ClippedCamera3D::set_collision_mask_bit);
- ClassDB::bind_method(D_METHOD("get_collision_mask_bit", "bit"), &ClippedCamera3D::get_collision_mask_bit);
-
- ClassDB::bind_method(D_METHOD("add_exception_rid", "rid"), &ClippedCamera3D::add_exception_rid);
- ClassDB::bind_method(D_METHOD("add_exception", "node"), &ClippedCamera3D::add_exception);
-
- ClassDB::bind_method(D_METHOD("remove_exception_rid", "rid"), &ClippedCamera3D::remove_exception_rid);
- ClassDB::bind_method(D_METHOD("remove_exception", "node"), &ClippedCamera3D::remove_exception);
-
- ClassDB::bind_method(D_METHOD("set_clip_to_areas", "enable"), &ClippedCamera3D::set_clip_to_areas);
- ClassDB::bind_method(D_METHOD("is_clip_to_areas_enabled"), &ClippedCamera3D::is_clip_to_areas_enabled);
-
- ClassDB::bind_method(D_METHOD("get_clip_offset"), &ClippedCamera3D::get_clip_offset);
-
- ClassDB::bind_method(D_METHOD("set_clip_to_bodies", "enable"), &ClippedCamera3D::set_clip_to_bodies);
- ClassDB::bind_method(D_METHOD("is_clip_to_bodies_enabled"), &ClippedCamera3D::is_clip_to_bodies_enabled);
-
- ClassDB::bind_method(D_METHOD("clear_exceptions"), &ClippedCamera3D::clear_exceptions);
-
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "margin", PROPERTY_HINT_RANGE, "0,32,0.01"), "set_margin", "get_margin");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "process_callback", PROPERTY_HINT_ENUM, "Physics,Idle"), "set_process_callback", "get_process_callback");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "collision_mask", PROPERTY_HINT_LAYERS_3D_PHYSICS), "set_collision_mask", "get_collision_mask");
-
- ADD_GROUP("Clip To", "clip_to");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL, "clip_to_areas", PROPERTY_HINT_LAYERS_3D_PHYSICS), "set_clip_to_areas", "is_clip_to_areas_enabled");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL, "clip_to_bodies", PROPERTY_HINT_LAYERS_3D_PHYSICS), "set_clip_to_bodies", "is_clip_to_bodies_enabled");
-
- BIND_ENUM_CONSTANT(CLIP_PROCESS_PHYSICS);
- BIND_ENUM_CONSTANT(CLIP_PROCESS_IDLE);
-}
-
-ClippedCamera3D::ClippedCamera3D() {
- set_physics_process_internal(true);
- set_notify_local_transform(Engine::get_singleton()->is_editor_hint());
- points.resize(5);
- pyramid_shape = PhysicsServer3D::get_singleton()->shape_create(PhysicsServer3D::SHAPE_CONVEX_POLYGON);
-}
-
-ClippedCamera3D::~ClippedCamera3D() {
- PhysicsServer3D::get_singleton()->free(pyramid_shape);
}
diff --git a/scene/3d/camera_3d.h b/scene/3d/camera_3d.h
index cea61e4db8..9f2f8ceed1 100644
--- a/scene/3d/camera_3d.h
+++ b/scene/3d/camera_3d.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -33,7 +33,6 @@
#include "scene/3d/node_3d.h"
#include "scene/3d/velocity_tracker_3d.h"
-#include "scene/main/window.h"
#include "scene/resources/camera_effects.h"
#include "scene/resources/environment.h"
@@ -47,8 +46,10 @@ public:
PROJECTION_FRUSTUM
};
- enum KeepAspect { KEEP_WIDTH,
- KEEP_HEIGHT };
+ enum KeepAspect {
+ KEEP_WIDTH,
+ KEEP_HEIGHT
+ };
enum DopplerTracking {
DOPPLER_TRACKING_DISABLED,
@@ -63,13 +64,13 @@ private:
Projection mode = PROJECTION_PERSPECTIVE;
- float fov = 0.0;
- float size = 1.0;
+ real_t fov = 0.0;
+ real_t size = 1.0;
Vector2 frustum_offset;
- float near = 0.0;
- float far = 0.0;
- float v_offset = 0.0;
- float h_offset = 0.0;
+ real_t near = 0.0;
+ real_t far = 0.0;
+ real_t v_offset = 0.0;
+ real_t h_offset = 0.0;
KeepAspect keep_aspect = KEEP_HEIGHT;
RID camera;
@@ -82,8 +83,6 @@ private:
Ref<Environment> environment;
Ref<CameraEffects> effects;
- virtual bool _can_gizmo_scale() const;
-
// void _camera_make_current(Node *p_camera);
friend class Viewport;
void _update_audio_listener_state();
@@ -91,6 +90,9 @@ private:
DopplerTracking doppler_tracking = DOPPLER_TRACKING_DISABLED;
Ref<VelocityTracker3D> velocity_tracker;
+ RID pyramid_shape;
+ Vector<Vector3> pyramid_shape_points;
+
protected:
void _update_camera();
virtual void _request_camera_update();
@@ -107,52 +109,51 @@ public:
NOTIFICATION_LOST_CURRENT = 51
};
- void set_perspective(float p_fovy_degrees, float p_z_near, float p_z_far);
- void set_orthogonal(float p_size, float p_z_near, float p_z_far);
- void set_frustum(float p_size, Vector2 p_offset, float p_z_near,
- float p_z_far);
+ void set_perspective(real_t p_fovy_degrees, real_t p_z_near, real_t p_z_far);
+ void set_orthogonal(real_t p_size, real_t p_z_near, real_t p_z_far);
+ void set_frustum(real_t p_size, Vector2 p_offset, real_t p_z_near, real_t p_z_far);
void set_projection(Camera3D::Projection p_mode);
void make_current();
void clear_current(bool p_enable_next = true);
- void set_current(bool p_current);
+ void set_current(bool p_enabled);
bool is_current() const;
RID get_camera() const;
- float get_fov() const;
- float get_size() const;
- float get_far() const;
- float get_near() const;
+ real_t get_fov() const;
+ real_t get_size() const;
+ real_t get_far() const;
+ real_t get_near() const;
Vector2 get_frustum_offset() const;
Projection get_projection() const;
- void set_fov(float p_fov);
- void set_size(float p_size);
- void set_far(float p_far);
- void set_near(float p_near);
+ void set_fov(real_t p_fov);
+ void set_size(real_t p_size);
+ void set_far(real_t p_far);
+ void set_near(real_t p_near);
void set_frustum_offset(Vector2 p_offset);
- virtual Transform get_camera_transform() const;
+ virtual Transform3D get_camera_transform() const;
virtual Vector3 project_ray_normal(const Point2 &p_pos) const;
virtual Vector3 project_ray_origin(const Point2 &p_pos) const;
virtual Vector3 project_local_ray_normal(const Point2 &p_pos) const;
virtual Point2 unproject_position(const Vector3 &p_pos) const;
bool is_position_behind(const Vector3 &p_pos) const;
- virtual Vector3 project_position(const Point2 &p_point,
- float p_z_depth) const;
+ virtual Vector3 project_position(const Point2 &p_point, real_t p_z_depth) const;
Vector<Vector3> get_near_plane_points() const;
void set_cull_mask(uint32_t p_layers);
uint32_t get_cull_mask() const;
- void set_cull_mask_bit(int p_layer, bool p_enable);
- bool get_cull_mask_bit(int p_layer) const;
+ void set_cull_mask_value(int p_layer_number, bool p_enable);
+ bool get_cull_mask_value(int p_layer_number) const;
virtual Vector<Plane> get_frustum() const;
+ bool is_position_in_frustum(const Vector3 &p_position) const;
void set_environment(const Ref<Environment> &p_environment);
Ref<Environment> get_environment() const;
@@ -163,17 +164,19 @@ public:
void set_keep_aspect_mode(KeepAspect p_aspect);
KeepAspect get_keep_aspect_mode() const;
- void set_v_offset(float p_offset);
- float get_v_offset() const;
+ void set_v_offset(real_t p_offset);
+ real_t get_v_offset() const;
- void set_h_offset(float p_offset);
- float get_h_offset() const;
+ void set_h_offset(real_t p_offset);
+ real_t get_h_offset() const;
void set_doppler_tracking(DopplerTracking p_tracking);
DopplerTracking get_doppler_tracking() const;
Vector3 get_doppler_tracked_velocity() const;
+ RID get_pyramid_shape_rid();
+
Camera3D();
~Camera3D();
};
@@ -182,63 +185,4 @@ VARIANT_ENUM_CAST(Camera3D::Projection);
VARIANT_ENUM_CAST(Camera3D::KeepAspect);
VARIANT_ENUM_CAST(Camera3D::DopplerTracking);
-class ClippedCamera3D : public Camera3D {
- GDCLASS(ClippedCamera3D, Camera3D);
-
-public:
- enum ClipProcessCallback {
- CLIP_PROCESS_PHYSICS,
- CLIP_PROCESS_IDLE,
- };
-
-private:
- ClipProcessCallback process_callback = CLIP_PROCESS_PHYSICS;
- RID pyramid_shape;
- float margin = 0.0;
- float clip_offset = 0.0;
- uint32_t collision_mask = 1;
- bool clip_to_areas = false;
- bool clip_to_bodies = true;
-
- Set<RID> exclude;
-
- Vector<Vector3> points;
-
-protected:
- void _notification(int p_what);
- static void _bind_methods();
- virtual Transform get_camera_transform() const override;
-
-public:
- void set_clip_to_areas(bool p_clip);
- bool is_clip_to_areas_enabled() const;
-
- void set_clip_to_bodies(bool p_clip);
- bool is_clip_to_bodies_enabled() const;
-
- void set_margin(float p_margin);
- float get_margin() const;
-
- void set_process_callback(ClipProcessCallback p_mode);
- ClipProcessCallback get_process_callback() const;
-
- void set_collision_mask(uint32_t p_mask);
- uint32_t get_collision_mask() const;
-
- void set_collision_mask_bit(int p_bit, bool p_value);
- bool get_collision_mask_bit(int p_bit) const;
-
- void add_exception_rid(const RID &p_rid);
- void add_exception(const Object *p_object);
- void remove_exception_rid(const RID &p_rid);
- void remove_exception(const Object *p_object);
- void clear_exceptions();
-
- float get_clip_offset() const;
-
- ClippedCamera3D();
- ~ClippedCamera3D();
-};
-
-VARIANT_ENUM_CAST(ClippedCamera3D::ClipProcessCallback);
#endif
diff --git a/scene/3d/collision_object_3d.cpp b/scene/3d/collision_object_3d.cpp
index cba769a8f8..40c09593a4 100644
--- a/scene/3d/collision_object_3d.cpp
+++ b/scene/3d/collision_object_3d.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -30,17 +30,15 @@
#include "collision_object_3d.h"
-#include "core/config/engine.h"
#include "scene/scene_string_names.h"
-#include "servers/physics_server_3d.h"
void CollisionObject3D::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
if (_are_collision_shapes_visible()) {
debug_shape_old_transform = get_global_transform();
- for (Map<uint32_t, ShapeData>::Element *E = shapes.front(); E; E = E->next()) {
- debug_shapes_to_update.insert(E->key());
+ for (const KeyValue<uint32_t, ShapeData> &E : shapes) {
+ debug_shapes_to_update.insert(E.key);
}
_update_debug_shapes();
}
@@ -59,18 +57,31 @@ void CollisionObject3D::_notification(int p_what) {
PhysicsServer3D::get_singleton()->body_set_state(rid, PhysicsServer3D::BODY_STATE_TRANSFORM, get_global_transform());
}
- RID space = get_world_3d()->get_space();
- if (area) {
- PhysicsServer3D::get_singleton()->area_set_space(rid, space);
- } else {
- PhysicsServer3D::get_singleton()->body_set_space(rid, space);
+ bool disabled = !is_enabled();
+
+ if (disabled && (disable_mode != DISABLE_MODE_REMOVE)) {
+ _apply_disabled();
+ }
+
+ if (!disabled || (disable_mode != DISABLE_MODE_REMOVE)) {
+ Ref<World3D> world_ref = get_world_3d();
+ ERR_FAIL_COND(!world_ref.is_valid());
+ RID space = world_ref->get_space();
+ if (area) {
+ PhysicsServer3D::get_singleton()->area_set_space(rid, space);
+ } else {
+ PhysicsServer3D::get_singleton()->body_set_space(rid, space);
+ }
}
_update_pickable();
- //get space
} break;
case NOTIFICATION_TRANSFORM_CHANGED: {
+ if (only_update_transform_changes) {
+ return;
+ }
+
if (area) {
PhysicsServer3D::get_singleton()->area_set_transform(rid, get_global_transform());
} else {
@@ -78,19 +89,34 @@ void CollisionObject3D::_notification(int p_what) {
}
_on_transform_changed();
-
} break;
+
case NOTIFICATION_VISIBILITY_CHANGED: {
_update_pickable();
-
} break;
+
case NOTIFICATION_EXIT_WORLD: {
- if (area) {
- PhysicsServer3D::get_singleton()->area_set_space(rid, RID());
- } else {
- PhysicsServer3D::get_singleton()->body_set_space(rid, RID());
+ bool disabled = !is_enabled();
+
+ if (!disabled || (disable_mode != DISABLE_MODE_REMOVE)) {
+ if (area) {
+ PhysicsServer3D::get_singleton()->area_set_space(rid, RID());
+ } else {
+ PhysicsServer3D::get_singleton()->body_set_space(rid, RID());
+ }
+ }
+
+ if (disabled && (disable_mode != DISABLE_MODE_REMOVE)) {
+ _apply_enabled();
}
+ } break;
+ case NOTIFICATION_DISABLED: {
+ _apply_disabled();
+ } break;
+
+ case NOTIFICATION_ENABLED: {
+ _apply_enabled();
} break;
}
}
@@ -121,42 +147,117 @@ uint32_t CollisionObject3D::get_collision_mask() const {
return collision_mask;
}
-void CollisionObject3D::set_collision_layer_bit(int p_bit, bool p_value) {
- ERR_FAIL_INDEX_MSG(p_bit, 32, "Collision layer bit must be between 0 and 31 inclusive.");
+void CollisionObject3D::set_collision_layer_value(int p_layer_number, bool p_value) {
+ ERR_FAIL_COND_MSG(p_layer_number < 1, "Collision layer number must be between 1 and 32 inclusive.");
+ ERR_FAIL_COND_MSG(p_layer_number > 32, "Collision layer number must be between 1 and 32 inclusive.");
uint32_t collision_layer = get_collision_layer();
if (p_value) {
- collision_layer |= 1 << p_bit;
+ collision_layer |= 1 << (p_layer_number - 1);
} else {
- collision_layer &= ~(1 << p_bit);
+ collision_layer &= ~(1 << (p_layer_number - 1));
}
set_collision_layer(collision_layer);
}
-bool CollisionObject3D::get_collision_layer_bit(int p_bit) const {
- ERR_FAIL_INDEX_V_MSG(p_bit, 32, false, "Collision layer bit must be between 0 and 31 inclusive.");
- return get_collision_layer() & (1 << p_bit);
+bool CollisionObject3D::get_collision_layer_value(int p_layer_number) const {
+ ERR_FAIL_COND_V_MSG(p_layer_number < 1, false, "Collision layer number must be between 1 and 32 inclusive.");
+ ERR_FAIL_COND_V_MSG(p_layer_number > 32, false, "Collision layer number must be between 1 and 32 inclusive.");
+ return get_collision_layer() & (1 << (p_layer_number - 1));
}
-void CollisionObject3D::set_collision_mask_bit(int p_bit, bool p_value) {
- ERR_FAIL_INDEX_MSG(p_bit, 32, "Collision mask bit must be between 0 and 31 inclusive.");
+void CollisionObject3D::set_collision_mask_value(int p_layer_number, bool p_value) {
+ ERR_FAIL_COND_MSG(p_layer_number < 1, "Collision layer number must be between 1 and 32 inclusive.");
+ ERR_FAIL_COND_MSG(p_layer_number > 32, "Collision layer number must be between 1 and 32 inclusive.");
uint32_t mask = get_collision_mask();
if (p_value) {
- mask |= 1 << p_bit;
+ mask |= 1 << (p_layer_number - 1);
} else {
- mask &= ~(1 << p_bit);
+ mask &= ~(1 << (p_layer_number - 1));
}
set_collision_mask(mask);
}
-bool CollisionObject3D::get_collision_mask_bit(int p_bit) const {
- ERR_FAIL_INDEX_V_MSG(p_bit, 32, false, "Collision mask bit must be between 0 and 31 inclusive.");
- return get_collision_mask() & (1 << p_bit);
+bool CollisionObject3D::get_collision_mask_value(int p_layer_number) const {
+ ERR_FAIL_COND_V_MSG(p_layer_number < 1, false, "Collision layer number must be between 1 and 32 inclusive.");
+ ERR_FAIL_COND_V_MSG(p_layer_number > 32, false, "Collision layer number must be between 1 and 32 inclusive.");
+ return get_collision_mask() & (1 << (p_layer_number - 1));
}
-void CollisionObject3D::_input_event(Node *p_camera, const Ref<InputEvent> &p_input_event, const Vector3 &p_pos, const Vector3 &p_normal, int p_shape) {
- if (get_script_instance()) {
- get_script_instance()->call(SceneStringNames::get_singleton()->_input_event, p_camera, p_input_event, p_pos, p_normal, p_shape);
+void CollisionObject3D::set_disable_mode(DisableMode p_mode) {
+ if (disable_mode == p_mode) {
+ return;
+ }
+
+ bool disabled = is_inside_tree() && !is_enabled();
+
+ if (disabled) {
+ // Cancel previous disable mode.
+ _apply_enabled();
+ }
+
+ disable_mode = p_mode;
+
+ if (disabled) {
+ // Apply new disable mode.
+ _apply_disabled();
}
+}
+
+CollisionObject3D::DisableMode CollisionObject3D::get_disable_mode() const {
+ return disable_mode;
+}
+
+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());
+ } else {
+ PhysicsServer3D::get_singleton()->body_set_space(rid, RID());
+ }
+ }
+ } break;
+
+ case DISABLE_MODE_MAKE_STATIC: {
+ if (!area && (body_mode != PhysicsServer3D::BODY_MODE_STATIC)) {
+ PhysicsServer3D::get_singleton()->body_set_mode(rid, PhysicsServer3D::BODY_MODE_STATIC);
+ }
+ } break;
+
+ case DISABLE_MODE_KEEP_ACTIVE: {
+ // Nothing to do.
+ } break;
+ }
+}
+
+void CollisionObject3D::_apply_enabled() {
+ switch (disable_mode) {
+ case DISABLE_MODE_REMOVE: {
+ if (is_inside_tree()) {
+ RID space = get_world_3d()->get_space();
+ if (area) {
+ PhysicsServer3D::get_singleton()->area_set_space(rid, space);
+ } else {
+ PhysicsServer3D::get_singleton()->body_set_space(rid, space);
+ }
+ }
+ } break;
+
+ case DISABLE_MODE_MAKE_STATIC: {
+ if (!area && (body_mode != PhysicsServer3D::BODY_MODE_STATIC)) {
+ PhysicsServer3D::get_singleton()->body_set_mode(rid, body_mode);
+ }
+ } break;
+
+ case DISABLE_MODE_KEEP_ACTIVE: {
+ // Nothing to do.
+ } break;
+ }
+}
+
+void CollisionObject3D::_input_event_call(Camera3D *p_camera, const Ref<InputEvent> &p_input_event, const Vector3 &p_pos, const Vector3 &p_normal, int p_shape) {
+ GDVIRTUAL_CALL(_input_event, p_camera, p_input_event, p_pos, p_normal, p_shape);
emit_signal(SceneStringNames::get_singleton()->input_event, p_camera, p_input_event, p_pos, p_normal, p_shape);
}
@@ -174,6 +275,30 @@ void CollisionObject3D::_mouse_exit() {
emit_signal(SceneStringNames::get_singleton()->mouse_exited);
}
+void CollisionObject3D::set_body_mode(PhysicsServer3D::BodyMode p_mode) {
+ ERR_FAIL_COND(area);
+
+ if (body_mode == p_mode) {
+ return;
+ }
+
+ body_mode = p_mode;
+
+ if (is_inside_tree() && !is_enabled() && (disable_mode == DISABLE_MODE_MAKE_STATIC)) {
+ return;
+ }
+
+ PhysicsServer3D::get_singleton()->body_set_mode(rid, p_mode);
+}
+
+void CollisionObject3D::set_only_update_transform_changes(bool p_enable) {
+ only_update_transform_changes = p_enable;
+}
+
+bool CollisionObject3D::is_only_update_transform_changes_enabled() const {
+ return only_update_transform_changes;
+}
+
void CollisionObject3D::_update_pickable() {
if (!is_inside_tree()) {
return;
@@ -201,8 +326,8 @@ void CollisionObject3D::_update_shape_data(uint32_t p_owner) {
}
void CollisionObject3D::_shape_changed(const Ref<Shape3D> &p_shape) {
- for (Map<uint32_t, ShapeData>::Element *E = shapes.front(); E; E = E->next()) {
- ShapeData &shapedata = E->get();
+ for (KeyValue<uint32_t, ShapeData> &E : shapes) {
+ ShapeData &shapedata = E.value;
ShapeData::ShapeBase *shapes = shapedata.shapes.ptrw();
for (int i = 0; i < shapedata.shapes.size(); i++) {
ShapeData::ShapeBase &s = shapes[i];
@@ -257,8 +382,8 @@ void CollisionObject3D::_update_debug_shapes() {
}
void CollisionObject3D::_clear_debug_shapes() {
- for (Map<uint32_t, ShapeData>::Element *E = shapes.front(); E; E = E->next()) {
- ShapeData &shapedata = E->get();
+ for (KeyValue<uint32_t, ShapeData> &E : shapes) {
+ ShapeData &shapedata = E.value;
ShapeData::ShapeBase *shapes = shapedata.shapes.ptrw();
for (int i = 0; i < shapedata.shapes.size(); i++) {
ShapeData::ShapeBase &s = shapes[i];
@@ -277,8 +402,8 @@ void CollisionObject3D::_clear_debug_shapes() {
void CollisionObject3D::_on_transform_changed() {
if (debug_shapes_count > 0 && !debug_shape_old_transform.is_equal_approx(get_global_transform())) {
debug_shape_old_transform = get_global_transform();
- for (Map<uint32_t, ShapeData>::Element *E = shapes.front(); E; E = E->next()) {
- ShapeData &shapedata = E->get();
+ for (KeyValue<uint32_t, ShapeData> &E : shapes) {
+ ShapeData &shapedata = E.value;
const ShapeData::ShapeBase *shapes = shapedata.shapes.ptr();
for (int i = 0; i < shapedata.shapes.size(); i++) {
RS::get_singleton()->instance_set_transform(shapes[i].debug_shape, debug_shape_old_transform * shapedata.xform);
@@ -301,10 +426,12 @@ void CollisionObject3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_collision_layer"), &CollisionObject3D::get_collision_layer);
ClassDB::bind_method(D_METHOD("set_collision_mask", "mask"), &CollisionObject3D::set_collision_mask);
ClassDB::bind_method(D_METHOD("get_collision_mask"), &CollisionObject3D::get_collision_mask);
- ClassDB::bind_method(D_METHOD("set_collision_layer_bit", "bit", "value"), &CollisionObject3D::set_collision_layer_bit);
- ClassDB::bind_method(D_METHOD("get_collision_layer_bit", "bit"), &CollisionObject3D::get_collision_layer_bit);
- ClassDB::bind_method(D_METHOD("set_collision_mask_bit", "bit", "value"), &CollisionObject3D::set_collision_mask_bit);
- ClassDB::bind_method(D_METHOD("get_collision_mask_bit", "bit"), &CollisionObject3D::get_collision_mask_bit);
+ ClassDB::bind_method(D_METHOD("set_collision_layer_value", "layer_number", "value"), &CollisionObject3D::set_collision_layer_value);
+ ClassDB::bind_method(D_METHOD("get_collision_layer_value", "layer_number"), &CollisionObject3D::get_collision_layer_value);
+ ClassDB::bind_method(D_METHOD("set_collision_mask_value", "layer_number", "value"), &CollisionObject3D::set_collision_mask_value);
+ ClassDB::bind_method(D_METHOD("get_collision_mask_value", "layer_number"), &CollisionObject3D::get_collision_mask_value);
+ ClassDB::bind_method(D_METHOD("set_disable_mode", "mode"), &CollisionObject3D::set_disable_mode);
+ ClassDB::bind_method(D_METHOD("get_disable_mode"), &CollisionObject3D::get_disable_mode);
ClassDB::bind_method(D_METHOD("set_ray_pickable", "ray_pickable"), &CollisionObject3D::set_ray_pickable);
ClassDB::bind_method(D_METHOD("is_ray_pickable"), &CollisionObject3D::is_ray_pickable);
ClassDB::bind_method(D_METHOD("set_capture_input_on_drag", "enable"), &CollisionObject3D::set_capture_input_on_drag);
@@ -326,12 +453,14 @@ void CollisionObject3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("shape_owner_clear_shapes", "owner_id"), &CollisionObject3D::shape_owner_clear_shapes);
ClassDB::bind_method(D_METHOD("shape_find_owner", "shape_index"), &CollisionObject3D::shape_find_owner);
- BIND_VMETHOD(MethodInfo("_input_event", PropertyInfo(Variant::OBJECT, "camera"), PropertyInfo(Variant::OBJECT, "event", PROPERTY_HINT_RESOURCE_TYPE, "InputEvent"), PropertyInfo(Variant::VECTOR3, "click_position"), PropertyInfo(Variant::VECTOR3, "click_normal"), PropertyInfo(Variant::INT, "shape_idx")));
+ GDVIRTUAL_BIND(_input_event, "camera", "event", "position", "normal", "shape_idx");
- ADD_SIGNAL(MethodInfo("input_event", PropertyInfo(Variant::OBJECT, "camera", PROPERTY_HINT_RESOURCE_TYPE, "Node"), PropertyInfo(Variant::OBJECT, "event", PROPERTY_HINT_RESOURCE_TYPE, "InputEvent"), PropertyInfo(Variant::VECTOR3, "click_position"), PropertyInfo(Variant::VECTOR3, "click_normal"), PropertyInfo(Variant::INT, "shape_idx")));
+ ADD_SIGNAL(MethodInfo("input_event", PropertyInfo(Variant::OBJECT, "camera", PROPERTY_HINT_RESOURCE_TYPE, "Node"), PropertyInfo(Variant::OBJECT, "event", PROPERTY_HINT_RESOURCE_TYPE, "InputEvent"), PropertyInfo(Variant::VECTOR3, "position"), PropertyInfo(Variant::VECTOR3, "normal"), PropertyInfo(Variant::INT, "shape_idx")));
ADD_SIGNAL(MethodInfo("mouse_entered"));
ADD_SIGNAL(MethodInfo("mouse_exited"));
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "disable_mode", PROPERTY_HINT_ENUM, "Remove,MakeStatic,KeepActive"), "set_disable_mode", "get_disable_mode");
+
ADD_GROUP("Collision", "collision_");
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");
@@ -339,6 +468,10 @@ void CollisionObject3D::_bind_methods() {
ADD_GROUP("Input", "input_");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "input_ray_pickable"), "set_ray_pickable", "is_ray_pickable");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "input_capture_on_drag"), "set_capture_input_on_drag", "get_capture_input_on_drag");
+
+ BIND_ENUM_CONSTANT(DISABLE_MODE_REMOVE);
+ BIND_ENUM_CONSTANT(DISABLE_MODE_MAKE_STATIC);
+ BIND_ENUM_CONSTANT(DISABLE_MODE_KEEP_ACTIVE);
}
uint32_t CollisionObject3D::create_shape_owner(Object *p_owner) {
@@ -351,7 +484,7 @@ uint32_t CollisionObject3D::create_shape_owner(Object *p_owner) {
id = shapes.back()->key() + 1;
}
- sd.owner = p_owner;
+ sd.owner_id = p_owner ? p_owner->get_instance_id() : ObjectID();
shapes[id] = sd;
@@ -392,21 +525,21 @@ bool CollisionObject3D::is_shape_owner_disabled(uint32_t p_owner) const {
}
void CollisionObject3D::get_shape_owners(List<uint32_t> *r_owners) {
- for (Map<uint32_t, ShapeData>::Element *E = shapes.front(); E; E = E->next()) {
- r_owners->push_back(E->key());
+ for (const KeyValue<uint32_t, ShapeData> &E : shapes) {
+ r_owners->push_back(E.key);
}
}
Array CollisionObject3D::_get_shape_owners() {
Array ret;
- for (Map<uint32_t, ShapeData>::Element *E = shapes.front(); E; E = E->next()) {
- ret.push_back(E->key());
+ for (const KeyValue<uint32_t, ShapeData> &E : shapes) {
+ ret.push_back(E.key);
}
return ret;
}
-void CollisionObject3D::shape_owner_set_transform(uint32_t p_owner, const Transform &p_transform) {
+void CollisionObject3D::shape_owner_set_transform(uint32_t p_owner, const Transform3D &p_transform) {
ERR_FAIL_COND(!shapes.has(p_owner));
ShapeData &sd = shapes[p_owner];
@@ -421,9 +554,8 @@ void CollisionObject3D::shape_owner_set_transform(uint32_t p_owner, const Transf
_update_shape_data(p_owner);
}
-
-Transform CollisionObject3D::shape_owner_get_transform(uint32_t p_owner) const {
- ERR_FAIL_COND_V(!shapes.has(p_owner), Transform());
+Transform3D CollisionObject3D::shape_owner_get_transform(uint32_t p_owner) const {
+ ERR_FAIL_COND_V(!shapes.has(p_owner), Transform3D());
return shapes[p_owner].xform;
}
@@ -431,7 +563,7 @@ Transform CollisionObject3D::shape_owner_get_transform(uint32_t p_owner) const {
Object *CollisionObject3D::shape_owner_get_owner(uint32_t p_owner) const {
ERR_FAIL_COND_V(!shapes.has(p_owner), nullptr);
- return shapes[p_owner].owner;
+ return ObjectDB::get_instance(shapes[p_owner].owner_id);
}
void CollisionObject3D::shape_owner_add_shape(uint32_t p_owner, const Ref<Shape3D> &p_shape) {
@@ -496,12 +628,12 @@ void CollisionObject3D::shape_owner_remove_shape(uint32_t p_owner, int p_shape)
--debug_shapes_count;
}
- shapes[p_owner].shapes.remove(p_shape);
+ shapes[p_owner].shapes.remove_at(p_shape);
- for (Map<uint32_t, ShapeData>::Element *E = shapes.front(); E; E = E->next()) {
- for (int i = 0; i < E->get().shapes.size(); i++) {
- if (E->get().shapes[i].index > index_to_remove) {
- E->get().shapes.write[i].index -= 1;
+ for (KeyValue<uint32_t, ShapeData> &E : shapes) {
+ for (int i = 0; i < E.value.shapes.size(); i++) {
+ if (E.value.shapes[i].index > index_to_remove) {
+ E.value.shapes.write[i].index -= 1;
}
}
}
@@ -518,18 +650,18 @@ void CollisionObject3D::shape_owner_clear_shapes(uint32_t p_owner) {
}
uint32_t CollisionObject3D::shape_find_owner(int p_shape_index) const {
- ERR_FAIL_INDEX_V(p_shape_index, total_subshapes, 0);
+ ERR_FAIL_INDEX_V(p_shape_index, total_subshapes, UINT32_MAX);
- for (const Map<uint32_t, ShapeData>::Element *E = shapes.front(); E; E = E->next()) {
- for (int i = 0; i < E->get().shapes.size(); i++) {
- if (E->get().shapes[i].index == p_shape_index) {
- return E->key();
+ for (const KeyValue<uint32_t, ShapeData> &E : shapes) {
+ for (int i = 0; i < E.value.shapes.size(); i++) {
+ if (E.value.shapes[i].index == p_shape_index) {
+ return E.key;
}
}
}
//in theory it should be unreachable
- return 0;
+ ERR_FAIL_V_MSG(UINT32_MAX, "Can't find owner for shape index " + itos(p_shape_index) + ".");
}
CollisionObject3D::CollisionObject3D(RID p_rid, bool p_area) {
@@ -541,8 +673,8 @@ CollisionObject3D::CollisionObject3D(RID p_rid, bool p_area) {
PhysicsServer3D::get_singleton()->area_attach_object_instance_id(rid, get_instance_id());
} else {
PhysicsServer3D::get_singleton()->body_attach_object_instance_id(rid, get_instance_id());
+ PhysicsServer3D::get_singleton()->body_set_mode(rid, body_mode);
}
- //set_transform_notify(true);
}
void CollisionObject3D::set_capture_input_on_drag(bool p_capture) {
@@ -557,7 +689,7 @@ TypedArray<String> CollisionObject3D::get_configuration_warnings() const {
TypedArray<String> warnings = Node::get_configuration_warnings();
if (shapes.is_empty()) {
- warnings.push_back(TTR("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."));
+ 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."));
}
return warnings;
diff --git a/scene/3d/collision_object_3d.h b/scene/3d/collision_object_3d.h
index 7ff3c5efde..e92843d784 100644
--- a/scene/3d/collision_object_3d.h
+++ b/scene/3d/collision_object_3d.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -31,12 +31,20 @@
#ifndef COLLISION_OBJECT_3D_H
#define COLLISION_OBJECT_3D_H
+#include "scene/3d/camera_3d.h"
#include "scene/3d/node_3d.h"
-#include "scene/resources/shape_3d.h"
class CollisionObject3D : public Node3D {
GDCLASS(CollisionObject3D, Node3D);
+public:
+ enum DisableMode {
+ DISABLE_MODE_REMOVE,
+ DISABLE_MODE_MAKE_STATIC,
+ DISABLE_MODE_KEEP_ACTIVE,
+ };
+
+private:
uint32_t collision_layer = 1;
uint32_t collision_mask = 1;
@@ -44,9 +52,13 @@ class CollisionObject3D : public Node3D {
RID rid;
+ DisableMode disable_mode = DISABLE_MODE_REMOVE;
+
+ PhysicsServer3D::BodyMode body_mode = PhysicsServer3D::BODY_MODE_STATIC;
+
struct ShapeData {
- Object *owner = nullptr;
- Transform xform;
+ ObjectID owner_id;
+ Transform3D xform;
struct ShapeBase {
RID debug_shape;
Ref<Shape3D> shape;
@@ -61,12 +73,14 @@ class CollisionObject3D : public Node3D {
Map<uint32_t, ShapeData> shapes;
+ bool only_update_transform_changes = false; // This is used for sync to physics.
+
bool capture_input_on_drag = false;
bool ray_pickable = true;
Set<uint32_t> debug_shapes_to_update;
int debug_shapes_count = 0;
- Transform debug_shape_old_transform;
+ Transform3D debug_shape_old_transform;
void _update_pickable();
@@ -76,6 +90,9 @@ class CollisionObject3D : public Node3D {
void _update_debug_shapes();
void _clear_debug_shapes();
+ void _apply_disabled();
+ void _apply_enabled();
+
protected:
CollisionObject3D(RID p_rid, bool p_area);
@@ -85,10 +102,16 @@ protected:
void _on_transform_changed();
friend class Viewport;
- virtual void _input_event(Node *p_camera, const Ref<InputEvent> &p_input_event, const Vector3 &p_pos, const Vector3 &p_normal, int p_shape);
+ virtual void _input_event_call(Camera3D *p_camera, const Ref<InputEvent> &p_input_event, const Vector3 &p_pos, const Vector3 &p_normal, int p_shape);
virtual void _mouse_enter();
virtual void _mouse_exit();
+ void set_body_mode(PhysicsServer3D::BodyMode p_mode);
+
+ void set_only_update_transform_changes(bool p_enable);
+ bool is_only_update_transform_changes_enabled() const;
+
+ GDVIRTUAL5(_input_event, Camera3D *, Ref<InputEvent>, Vector3, Vector3, int)
public:
void set_collision_layer(uint32_t p_layer);
uint32_t get_collision_layer() const;
@@ -96,19 +119,22 @@ public:
void set_collision_mask(uint32_t p_mask);
uint32_t get_collision_mask() const;
- void set_collision_layer_bit(int p_bit, bool p_value);
- bool get_collision_layer_bit(int p_bit) const;
+ void set_collision_layer_value(int p_layer_number, bool p_value);
+ bool get_collision_layer_value(int p_layer_number) const;
- void set_collision_mask_bit(int p_bit, bool p_value);
- bool get_collision_mask_bit(int p_bit) const;
+ void set_collision_mask_value(int p_layer_number, bool p_value);
+ bool get_collision_mask_value(int p_layer_number) const;
+
+ void set_disable_mode(DisableMode p_mode);
+ DisableMode get_disable_mode() const;
uint32_t create_shape_owner(Object *p_owner);
void remove_shape_owner(uint32_t owner);
void get_shape_owners(List<uint32_t> *r_owners);
Array _get_shape_owners();
- void shape_owner_set_transform(uint32_t p_owner, const Transform &p_transform);
- Transform shape_owner_get_transform(uint32_t p_owner) const;
+ void shape_owner_set_transform(uint32_t p_owner, const Transform3D &p_transform);
+ Transform3D shape_owner_get_transform(uint32_t p_owner) const;
Object *shape_owner_get_owner(uint32_t p_owner) const;
void shape_owner_set_disabled(uint32_t p_owner, bool p_disabled);
@@ -138,4 +164,6 @@ public:
~CollisionObject3D();
};
+VARIANT_ENUM_CAST(CollisionObject3D::DisableMode);
+
#endif // COLLISION_OBJECT__H
diff --git a/scene/3d/collision_polygon_3d.cpp b/scene/3d/collision_polygon_3d.cpp
index ac715b22b2..5a286d7b55 100644
--- a/scene/3d/collision_polygon_3d.cpp
+++ b/scene/3d/collision_polygon_3d.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -32,7 +32,6 @@
#include "collision_object_3d.h"
#include "core/math/geometry_2d.h"
-#include "scene/resources/concave_polygon_shape_3d.h"
#include "scene/resources/convex_polygon_shape_3d.h"
void CollisionPolygon3D::_build_polygon() {
@@ -94,18 +93,19 @@ void CollisionPolygon3D::_notification(int p_what) {
_update_in_shape_owner();
}
} break;
+
case NOTIFICATION_ENTER_TREE: {
if (parent) {
_update_in_shape_owner();
}
-
} break;
+
case NOTIFICATION_LOCAL_TRANSFORM_CHANGED: {
if (parent) {
_update_in_shape_owner(true);
}
-
} break;
+
case NOTIFICATION_UNPARENTED: {
if (parent) {
parent->remove_shape_owner(owner_id);
@@ -122,7 +122,7 @@ void CollisionPolygon3D::set_polygon(const Vector<Point2> &p_polygon) {
_build_polygon();
}
update_configuration_warnings();
- update_gizmo();
+ update_gizmos();
}
Vector<Point2> CollisionPolygon3D::get_polygon() const {
@@ -136,7 +136,7 @@ AABB CollisionPolygon3D::get_item_rect() const {
void CollisionPolygon3D::set_depth(real_t p_depth) {
depth = p_depth;
_build_polygon();
- update_gizmo();
+ update_gizmos();
}
real_t CollisionPolygon3D::get_depth() const {
@@ -145,7 +145,7 @@ real_t CollisionPolygon3D::get_depth() const {
void CollisionPolygon3D::set_disabled(bool p_disabled) {
disabled = p_disabled;
- update_gizmo();
+ update_gizmos();
if (parent) {
parent->shape_owner_set_disabled(owner_id, p_disabled);
@@ -171,11 +171,11 @@ TypedArray<String> CollisionPolygon3D::get_configuration_warnings() const {
TypedArray<String> warnings = Node::get_configuration_warnings();
if (!Object::cast_to<CollisionObject3D>(get_parent())) {
- warnings.push_back(TTR("CollisionPolygon3D only serves to provide a collision shape to a CollisionObject3D derived node. Please only use it as a child of Area3D, StaticBody3D, RigidBody3D, KinematicBody3D, etc. to give them a shape."));
+ 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, RigidDynamicBody3D, CharacterBody3D, etc. to give them a shape."));
}
if (polygon.is_empty()) {
- warnings.push_back(TTR("An empty CollisionPolygon3D has no effect on collision."));
+ warnings.push_back(RTR("An empty CollisionPolygon3D has no effect on collision."));
}
return warnings;
diff --git a/scene/3d/collision_polygon_3d.h b/scene/3d/collision_polygon_3d.h
index 73b8a8e0e3..a24d485af2 100644
--- a/scene/3d/collision_polygon_3d.h
+++ b/scene/3d/collision_polygon_3d.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
diff --git a/scene/3d/collision_shape_3d.cpp b/scene/3d/collision_shape_3d.cpp
index 70d9cebb83..759997de7b 100644
--- a/scene/3d/collision_shape_3d.cpp
+++ b/scene/3d/collision_shape_3d.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -30,19 +30,10 @@
#include "collision_shape_3d.h"
-#include "core/math/quick_hull.h"
#include "mesh_instance_3d.h"
#include "physics_body_3d.h"
-#include "scene/resources/box_shape_3d.h"
-#include "scene/resources/capsule_shape_3d.h"
#include "scene/resources/concave_polygon_shape_3d.h"
#include "scene/resources/convex_polygon_shape_3d.h"
-#include "scene/resources/ray_shape_3d.h"
-#include "scene/resources/sphere_shape_3d.h"
-#include "scene/resources/world_margin_shape_3d.h"
-#include "servers/rendering_server.h"
-
-//TODO: Implement CylinderShape and HeightMapShape?
void CollisionShape3D::make_convex_from_siblings() {
Node *p = get_parent();
@@ -96,16 +87,19 @@ void CollisionShape3D::_notification(int p_what) {
_update_in_shape_owner();
}
} break;
+
case NOTIFICATION_ENTER_TREE: {
if (parent) {
_update_in_shape_owner();
}
} break;
+
case NOTIFICATION_LOCAL_TRANSFORM_CHANGED: {
if (parent) {
_update_in_shape_owner(true);
}
} break;
+
case NOTIFICATION_UNPARENTED: {
if (parent) {
parent->remove_shape_owner(owner_id);
@@ -116,26 +110,25 @@ void CollisionShape3D::_notification(int p_what) {
}
}
-void CollisionShape3D::resource_changed(RES res) {
- update_gizmo();
+void CollisionShape3D::resource_changed(Ref<Resource> res) {
+ update_gizmos();
}
TypedArray<String> CollisionShape3D::get_configuration_warnings() const {
TypedArray<String> warnings = Node::get_configuration_warnings();
if (!Object::cast_to<CollisionObject3D>(get_parent())) {
- warnings.push_back(TTR("CollisionShape3D only serves to provide a collision shape to a CollisionObject3D derived node. Please only use it as a child of Area3D, StaticBody3D, RigidBody3D, KinematicBody3D, etc. to give them a shape."));
+ 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, RigidDynamicBody3D, CharacterBody3D, etc. to give them a shape."));
}
if (!shape.is_valid()) {
- warnings.push_back(TTR("A shape must be provided for CollisionShape3D to function. Please create a shape resource for it."));
+ warnings.push_back(RTR("A shape must be provided for CollisionShape3D to function. Please create a shape resource for it."));
}
if (shape.is_valid() &&
- Object::cast_to<RigidBody3D>(get_parent()) &&
- Object::cast_to<ConcavePolygonShape3D>(*shape) &&
- Object::cast_to<RigidBody3D>(get_parent())->get_mode() != RigidBody3D::MODE_STATIC) {
- warnings.push_back(TTR("ConcavePolygonShape3D doesn't support RigidBody3D in another mode than static."));
+ Object::cast_to<RigidDynamicBody3D>(get_parent()) &&
+ Object::cast_to<ConcavePolygonShape3D>(*shape)) {
+ warnings.push_back(RTR("ConcavePolygonShape3D doesn't support RigidDynamicBody3D in another mode than static."));
}
return warnings;
@@ -166,7 +159,7 @@ void CollisionShape3D::set_shape(const Ref<Shape3D> &p_shape) {
if (!shape.is_null()) {
shape->register_owner(this);
}
- update_gizmo();
+ update_gizmos();
if (parent) {
parent->shape_owner_clear_shapes(owner_id);
if (shape.is_valid()) {
@@ -187,7 +180,7 @@ Ref<Shape3D> CollisionShape3D::get_shape() const {
void CollisionShape3D::set_disabled(bool p_disabled) {
disabled = p_disabled;
- update_gizmo();
+ update_gizmos();
if (parent) {
parent->shape_owner_set_disabled(owner_id, p_disabled);
}
diff --git a/scene/3d/collision_shape_3d.h b/scene/3d/collision_shape_3d.h
index f69c1e38eb..5c32230942 100644
--- a/scene/3d/collision_shape_3d.h
+++ b/scene/3d/collision_shape_3d.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -33,17 +33,17 @@
#include "scene/3d/node_3d.h"
#include "scene/resources/shape_3d.h"
+
class CollisionObject3D;
class CollisionShape3D : public Node3D {
GDCLASS(CollisionShape3D, Node3D);
- OBJ_CATEGORY("3D Physics Nodes");
Ref<Shape3D> shape;
uint32_t owner_id = 0;
CollisionObject3D *parent = nullptr;
- void resource_changed(RES res);
+ void resource_changed(Ref<Resource> res);
bool disabled = false;
protected:
diff --git a/scene/3d/cpu_particles_3d.cpp b/scene/3d/cpu_particles_3d.cpp
index aa29728c73..9666994b95 100644
--- a/scene/3d/cpu_particles_3d.cpp
+++ b/scene/3d/cpu_particles_3d.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -32,17 +32,13 @@
#include "scene/3d/camera_3d.h"
#include "scene/3d/gpu_particles_3d.h"
+#include "scene/main/viewport.h"
#include "scene/resources/particles_material.h"
-#include "servers/rendering_server.h"
AABB CPUParticles3D::get_aabb() const {
return AABB();
}
-Vector<Face3> CPUParticles3D::get_faces(uint32_t p_usage_particle_flags) const {
- return Vector<Face3>();
-}
-
void CPUParticles3D::set_emitting(bool p_emitting) {
if (emitting == p_emitting) {
return;
@@ -73,12 +69,13 @@ void CPUParticles3D::set_amount(int p_amount) {
}
particle_data.resize((12 + 4 + 4) * p_amount);
+ RS::get_singleton()->multimesh_set_visible_instances(multimesh, -1);
RS::get_singleton()->multimesh_allocate_data(multimesh, p_amount, RS::MULTIMESH_TRANSFORM_3D, true, true);
particle_order.resize(p_amount);
}
-void CPUParticles3D::set_lifetime(float p_lifetime) {
+void CPUParticles3D::set_lifetime(double p_lifetime) {
ERR_FAIL_COND_MSG(p_lifetime <= 0, "Particles lifetime must be greater than 0.");
lifetime = p_lifetime;
}
@@ -87,19 +84,19 @@ void CPUParticles3D::set_one_shot(bool p_one_shot) {
one_shot = p_one_shot;
}
-void CPUParticles3D::set_pre_process_time(float p_time) {
+void CPUParticles3D::set_pre_process_time(double p_time) {
pre_process_time = p_time;
}
-void CPUParticles3D::set_explosiveness_ratio(float p_ratio) {
+void CPUParticles3D::set_explosiveness_ratio(real_t p_ratio) {
explosiveness_ratio = p_ratio;
}
-void CPUParticles3D::set_randomness_ratio(float p_ratio) {
+void CPUParticles3D::set_randomness_ratio(real_t p_ratio) {
randomness_ratio = p_ratio;
}
-void CPUParticles3D::set_lifetime_randomness(float p_random) {
+void CPUParticles3D::set_lifetime_randomness(double p_random) {
lifetime_randomness = p_random;
}
@@ -107,7 +104,7 @@ void CPUParticles3D::set_use_local_coordinates(bool p_enable) {
local_coords = p_enable;
}
-void CPUParticles3D::set_speed_scale(float p_scale) {
+void CPUParticles3D::set_speed_scale(double p_scale) {
speed_scale = p_scale;
}
@@ -119,7 +116,7 @@ int CPUParticles3D::get_amount() const {
return particles.size();
}
-float CPUParticles3D::get_lifetime() const {
+double CPUParticles3D::get_lifetime() const {
return lifetime;
}
@@ -127,19 +124,19 @@ bool CPUParticles3D::get_one_shot() const {
return one_shot;
}
-float CPUParticles3D::get_pre_process_time() const {
+double CPUParticles3D::get_pre_process_time() const {
return pre_process_time;
}
-float CPUParticles3D::get_explosiveness_ratio() const {
+real_t CPUParticles3D::get_explosiveness_ratio() const {
return explosiveness_ratio;
}
-float CPUParticles3D::get_randomness_ratio() const {
+real_t CPUParticles3D::get_randomness_ratio() const {
return randomness_ratio;
}
-float CPUParticles3D::get_lifetime_randomness() const {
+double CPUParticles3D::get_lifetime_randomness() const {
return lifetime_randomness;
}
@@ -147,7 +144,7 @@ bool CPUParticles3D::get_use_local_coordinates() const {
return local_coords;
}
-float CPUParticles3D::get_speed_scale() const {
+double CPUParticles3D::get_speed_scale() const {
return speed_scale;
}
@@ -209,12 +206,11 @@ TypedArray<String> CPUParticles3D::get_configuration_warnings() const {
anim_material_found = anim_material_found || (spat && spat->get_billboard_mode() == StandardMaterial3D::BILLBOARD_PARTICLES);
if (!mesh_found) {
- warnings.push_back(TTR("Nothing is visible because no mesh has been assigned."));
+ warnings.push_back(RTR("Nothing is visible because no mesh has been assigned."));
}
- if (!anim_material_found && (get_param(PARAM_ANIM_SPEED) != 0.0 || get_param(PARAM_ANIM_OFFSET) != 0.0 ||
- get_param_curve(PARAM_ANIM_SPEED).is_valid() || get_param_curve(PARAM_ANIM_OFFSET).is_valid())) {
- warnings.push_back(TTR("CPUParticles3D animation requires the usage of a StandardMaterial3D whose Billboard Mode is set to \"Particle Billboard\"."));
+ if (!anim_material_found && (get_param_max(PARAM_ANIM_SPEED) != 0.0 || get_param_max(PARAM_ANIM_OFFSET) != 0.0 || get_param_curve(PARAM_ANIM_SPEED).is_valid() || get_param_curve(PARAM_ANIM_OFFSET).is_valid())) {
+ warnings.push_back(RTR("CPUParticles3D animation requires the usage of a StandardMaterial3D whose Billboard Mode is set to \"Particle Billboard\"."));
}
return warnings;
@@ -247,47 +243,52 @@ Vector3 CPUParticles3D::get_direction() const {
return direction;
}
-void CPUParticles3D::set_spread(float p_spread) {
+void CPUParticles3D::set_spread(real_t p_spread) {
spread = p_spread;
}
-float CPUParticles3D::get_spread() const {
+real_t CPUParticles3D::get_spread() const {
return spread;
}
-void CPUParticles3D::set_flatness(float p_flatness) {
+void CPUParticles3D::set_flatness(real_t p_flatness) {
flatness = p_flatness;
}
-float CPUParticles3D::get_flatness() const {
+real_t CPUParticles3D::get_flatness() const {
return flatness;
}
-void CPUParticles3D::set_param(Parameter p_param, float p_value) {
+void CPUParticles3D::set_param_min(Parameter p_param, real_t p_value) {
ERR_FAIL_INDEX(p_param, PARAM_MAX);
- parameters[p_param] = p_value;
+ parameters_min[p_param] = p_value;
+ if (parameters_min[p_param] > parameters_max[p_param]) {
+ set_param_max(p_param, p_value);
+ }
}
-float CPUParticles3D::get_param(Parameter p_param) const {
+real_t CPUParticles3D::get_param_min(Parameter p_param) const {
ERR_FAIL_INDEX_V(p_param, PARAM_MAX, 0);
- return parameters[p_param];
+ return parameters_min[p_param];
}
-void CPUParticles3D::set_param_randomness(Parameter p_param, float p_value) {
+void CPUParticles3D::set_param_max(Parameter p_param, real_t p_value) {
ERR_FAIL_INDEX(p_param, PARAM_MAX);
-
- randomness[p_param] = p_value;
+ parameters_max[p_param] = p_value;
+ if (parameters_min[p_param] > parameters_max[p_param]) {
+ set_param_min(p_param, p_value);
+ }
}
-float CPUParticles3D::get_param_randomness(Parameter p_param) const {
+real_t CPUParticles3D::get_param_max(Parameter p_param) const {
ERR_FAIL_INDEX_V(p_param, PARAM_MAX, 0);
- return randomness[p_param];
+ return parameters_max[p_param];
}
-static void _adjust_curve_range(const Ref<Curve> &p_curve, float p_min, float p_max) {
+static void _adjust_curve_range(const Ref<Curve> &p_curve, real_t p_min, real_t p_max) {
Ref<Curve> curve = p_curve;
if (!curve.is_valid()) {
return;
@@ -363,6 +364,14 @@ Ref<Gradient> CPUParticles3D::get_color_ramp() const {
return color_ramp;
}
+void CPUParticles3D::set_color_initial_ramp(const Ref<Gradient> &p_ramp) {
+ color_initial_ramp = p_ramp;
+}
+
+Ref<Gradient> CPUParticles3D::get_color_initial_ramp() const {
+ return color_initial_ramp;
+}
+
void CPUParticles3D::set_particle_flag(ParticleFlags p_particle_flag, bool p_enable) {
ERR_FAIL_INDEX(p_particle_flag, PARTICLE_FLAG_MAX);
particle_flags[p_particle_flag] = p_enable;
@@ -381,7 +390,7 @@ void CPUParticles3D::set_emission_shape(EmissionShape p_shape) {
emission_shape = p_shape;
}
-void CPUParticles3D::set_emission_sphere_radius(float p_radius) {
+void CPUParticles3D::set_emission_sphere_radius(real_t p_radius) {
emission_sphere_radius = p_radius;
}
@@ -401,7 +410,40 @@ void CPUParticles3D::set_emission_colors(const Vector<Color> &p_colors) {
emission_colors = p_colors;
}
-float CPUParticles3D::get_emission_sphere_radius() const {
+void CPUParticles3D::set_emission_ring_axis(Vector3 p_axis) {
+ emission_ring_axis = p_axis;
+}
+
+void CPUParticles3D::set_emission_ring_height(real_t p_height) {
+ emission_ring_height = p_height;
+}
+
+void CPUParticles3D::set_emission_ring_radius(real_t p_radius) {
+ emission_ring_radius = p_radius;
+}
+
+void CPUParticles3D::set_emission_ring_inner_radius(real_t p_radius) {
+ emission_ring_inner_radius = p_radius;
+}
+
+void CPUParticles3D::set_scale_curve_x(Ref<Curve> p_scale_curve) {
+ scale_curve_x = p_scale_curve;
+}
+
+void CPUParticles3D::set_scale_curve_y(Ref<Curve> p_scale_curve) {
+ scale_curve_y = p_scale_curve;
+}
+
+void CPUParticles3D::set_scale_curve_z(Ref<Curve> p_scale_curve) {
+ scale_curve_z = p_scale_curve;
+}
+
+void CPUParticles3D::set_split_scale(bool p_split_scale) {
+ split_scale = p_split_scale;
+ notify_property_list_changed();
+}
+
+real_t CPUParticles3D::get_emission_sphere_radius() const {
return emission_sphere_radius;
}
@@ -421,6 +463,22 @@ Vector<Color> CPUParticles3D::get_emission_colors() const {
return emission_colors;
}
+Vector3 CPUParticles3D::get_emission_ring_axis() const {
+ return emission_ring_axis;
+}
+
+real_t CPUParticles3D::get_emission_ring_height() const {
+ return emission_ring_height;
+}
+
+real_t CPUParticles3D::get_emission_ring_radius() const {
+ return emission_ring_radius;
+}
+
+real_t CPUParticles3D::get_emission_ring_inner_radius() const {
+ return emission_ring_inner_radius;
+}
+
CPUParticles3D::EmissionShape CPUParticles3D::get_emission_shape() const {
return emission_shape;
}
@@ -433,30 +491,52 @@ Vector3 CPUParticles3D::get_gravity() const {
return gravity;
}
-void CPUParticles3D::_validate_property(PropertyInfo &property) const {
- if (property.name == "color" && color_ramp.is_valid()) {
- property.usage = 0;
- }
+Ref<Curve> CPUParticles3D::get_scale_curve_x() const {
+ return scale_curve_x;
+}
+
+Ref<Curve> CPUParticles3D::get_scale_curve_y() const {
+ return scale_curve_y;
+}
+
+Ref<Curve> CPUParticles3D::get_scale_curve_z() const {
+ return scale_curve_z;
+}
+
+bool CPUParticles3D::get_split_scale() {
+ return split_scale;
+}
- if (property.name == "emission_sphere_radius" && emission_shape != EMISSION_SHAPE_SPHERE) {
- property.usage = 0;
+void CPUParticles3D::_validate_property(PropertyInfo &property) const {
+ if (property.name == "emission_sphere_radius" && (emission_shape != EMISSION_SHAPE_SPHERE && emission_shape != EMISSION_SHAPE_SPHERE_SURFACE)) {
+ property.usage = PROPERTY_USAGE_NONE;
}
if (property.name == "emission_box_extents" && emission_shape != EMISSION_SHAPE_BOX) {
- property.usage = 0;
+ property.usage = PROPERTY_USAGE_NONE;
}
- if ((property.name == "emission_point_texture" || property.name == "emission_color_texture") && (emission_shape < EMISSION_SHAPE_POINTS)) {
- property.usage = 0;
+ if ((property.name == "emission_point_texture" || property.name == "emission_color_texture" || property.name == "emission_points") && (emission_shape != EMISSION_SHAPE_POINTS && (emission_shape != EMISSION_SHAPE_DIRECTED_POINTS))) {
+ property.usage = PROPERTY_USAGE_NONE;
}
if (property.name == "emission_normals" && emission_shape != EMISSION_SHAPE_DIRECTED_POINTS) {
- property.usage = 0;
+ property.usage = PROPERTY_USAGE_NONE;
+ }
+
+ if (property.name.begins_with("emission_ring_") && emission_shape != EMISSION_SHAPE_RING) {
+ property.usage = PROPERTY_USAGE_NONE;
}
if (property.name.begins_with("orbit_") && !particle_flags[PARTICLE_FLAG_DISABLE_Z]) {
- property.usage = 0;
+ property.usage = PROPERTY_USAGE_NONE;
}
+
+ if (property.name.begins_with("scale_curve_") && !split_scale) {
+ property.usage = PROPERTY_USAGE_NONE;
+ }
+
+ Node3D::_validate_property(property);
}
static uint32_t idhash(uint32_t x) {
@@ -466,7 +546,7 @@ static uint32_t idhash(uint32_t x) {
return x;
}
-static float rand_from_seed(uint32_t &seed) {
+static real_t rand_from_seed(uint32_t &seed) {
int k;
int s = int(seed);
if (s == 0) {
@@ -478,7 +558,7 @@ static float rand_from_seed(uint32_t &seed) {
s += 2147483647;
}
seed = uint32_t(s);
- return float(seed % uint32_t(65536)) / 65535.0;
+ return (seed % uint32_t(65536)) / 65535.0;
}
void CPUParticles3D::_update_internal() {
@@ -487,7 +567,7 @@ void CPUParticles3D::_update_internal() {
return;
}
- float delta = get_process_delta_time();
+ double delta = get_process_delta_time();
if (emitting) {
inactive_time = 0;
} else {
@@ -509,14 +589,14 @@ void CPUParticles3D::_update_internal() {
bool processed = false;
if (time == 0 && pre_process_time > 0.0) {
- float frame_time;
+ double frame_time;
if (fixed_fps > 0) {
frame_time = 1.0 / fixed_fps;
} else {
frame_time = 1.0 / 30.0;
}
- float todo = pre_process_time;
+ double todo = pre_process_time;
while (todo >= 0) {
_particles_process(frame_time);
@@ -526,16 +606,16 @@ void CPUParticles3D::_update_internal() {
}
if (fixed_fps > 0) {
- float frame_time = 1.0 / fixed_fps;
- float decr = frame_time;
+ double frame_time = 1.0 / fixed_fps;
+ double decr = frame_time;
- float ldelta = delta;
+ double ldelta = delta;
if (ldelta > 0.1) { //avoid recursive stalls if fps goes below 10
ldelta = 0.1;
} else if (ldelta <= 0.0) { //unlikely but..
ldelta = 0.001;
}
- float todo = frame_remainder + ldelta;
+ double todo = frame_remainder + ldelta;
while (todo >= frame_time) {
_particles_process(frame_time);
@@ -555,7 +635,7 @@ void CPUParticles3D::_update_internal() {
}
}
-void CPUParticles3D::_particles_process(float p_delta) {
+void CPUParticles3D::_particles_process(double p_delta) {
p_delta *= speed_scale;
int pcount = particles.size();
@@ -563,7 +643,7 @@ void CPUParticles3D::_particles_process(float p_delta) {
Particle *parray = w;
- float prev_time = time;
+ double prev_time = time;
time += p_delta;
if (time > lifetime) {
time = Math::fmod(time, lifetime);
@@ -574,14 +654,14 @@ void CPUParticles3D::_particles_process(float p_delta) {
}
}
- Transform emission_xform;
+ Transform3D emission_xform;
Basis velocity_xform;
if (!local_coords) {
emission_xform = get_global_transform();
velocity_xform = emission_xform.basis;
}
- float system_phase = time / lifetime;
+ double system_phase = time / lifetime;
for (int i = 0; i < pcount; i++) {
Particle &p = parray[i];
@@ -590,12 +670,12 @@ void CPUParticles3D::_particles_process(float p_delta) {
continue;
}
- float local_delta = p_delta;
+ double local_delta = p_delta;
// The phase is a ratio between 0 (birth) and 1 (end of life) for each particle.
// While we use time in tests later on, for randomness we use the phase as done in the
// original shader code, and we later multiply by lifetime to get the time.
- float restart_phase = float(i) / float(pcount);
+ double restart_phase = double(i) / double(pcount);
if (randomness_ratio > 0.0) {
uint32_t seed = cycle;
@@ -604,12 +684,12 @@ void CPUParticles3D::_particles_process(float p_delta) {
}
seed *= uint32_t(pcount);
seed += uint32_t(i);
- float random = float(idhash(seed) % uint32_t(65536)) / 65536.0;
- restart_phase += randomness_ratio * random * 1.0 / float(pcount);
+ double random = double(idhash(seed) % uint32_t(65536)) / 65536.0;
+ restart_phase += randomness_ratio * random * 1.0 / double(pcount);
}
restart_phase *= (1.0 - explosiveness_ratio);
- float restart_time = restart_phase * lifetime;
+ double restart_time = restart_phase * lifetime;
bool restart = false;
if (time > prev_time) {
@@ -650,17 +730,17 @@ void CPUParticles3D::_particles_process(float p_delta) {
}
p.active = true;
- /*float tex_linear_velocity = 0;
+ /*real_t tex_linear_velocity = 0;
if (curve_parameters[PARAM_INITIAL_LINEAR_VELOCITY].is_valid()) {
tex_linear_velocity = curve_parameters[PARAM_INITIAL_LINEAR_VELOCITY]->interpolate(0);
}*/
- float tex_angle = 0.0;
+ real_t tex_angle = 0.0;
if (curve_parameters[PARAM_ANGLE].is_valid()) {
tex_angle = curve_parameters[PARAM_ANGLE]->interpolate(tv);
}
- float tex_anim_offset = 0.0;
+ real_t tex_anim_offset = 0.0;
if (curve_parameters[PARAM_ANGLE].is_valid()) {
tex_anim_offset = curve_parameters[PARAM_ANGLE]->interpolate(tv);
}
@@ -672,28 +752,47 @@ void CPUParticles3D::_particles_process(float p_delta) {
p.hue_rot_rand = Math::randf();
p.anim_offset_rand = Math::randf();
+ if (color_initial_ramp.is_valid()) {
+ p.start_color_rand = color_initial_ramp->get_color_at_offset(Math::randf());
+ } else {
+ p.start_color_rand = Color(1, 1, 1, 1);
+ }
+
if (particle_flags[PARTICLE_FLAG_DISABLE_Z]) {
- float angle1_rad = Math::atan2(direction.y, direction.x) + Math::deg2rad((Math::randf() * 2.0 - 1.0) * spread);
+ real_t angle1_rad = Math::atan2(direction.y, direction.x) + Math::deg2rad((Math::randf() * 2.0 - 1.0) * spread);
Vector3 rot = Vector3(Math::cos(angle1_rad), Math::sin(angle1_rad), 0.0);
- p.velocity = rot * parameters[PARAM_INITIAL_LINEAR_VELOCITY] * Math::lerp(1.0f, float(Math::randf()), randomness[PARAM_INITIAL_LINEAR_VELOCITY]);
+ p.velocity = rot * Math::lerp(parameters_min[PARAM_INITIAL_LINEAR_VELOCITY], parameters_max[PARAM_INITIAL_LINEAR_VELOCITY], (real_t)Math::randf());
} else {
//initiate velocity spread in 3D
- float angle1_rad = Math::atan2(direction.x, direction.z) + Math::deg2rad((Math::randf() * 2.0 - 1.0) * spread);
- float angle2_rad = Math::atan2(direction.y, Math::abs(direction.z)) + Math::deg2rad((Math::randf() * 2.0 - 1.0) * (1.0 - flatness) * spread);
+ real_t angle1_rad = Math::deg2rad((Math::randf() * (real_t)2.0 - (real_t)1.0) * spread);
+ real_t angle2_rad = Math::deg2rad((Math::randf() * (real_t)2.0 - (real_t)1.0) * ((real_t)1.0 - flatness) * spread);
Vector3 direction_xz = Vector3(Math::sin(angle1_rad), 0, Math::cos(angle1_rad));
Vector3 direction_yz = Vector3(0, Math::sin(angle2_rad), Math::cos(angle2_rad));
- direction_yz.z = direction_yz.z / MAX(0.0001, Math::sqrt(ABS(direction_yz.z))); //better uniform distribution
- Vector3 direction = Vector3(direction_xz.x * direction_yz.z, direction_yz.y, direction_xz.z * direction_yz.z);
- direction.normalize();
- p.velocity = direction * parameters[PARAM_INITIAL_LINEAR_VELOCITY] * Math::lerp(1.0f, float(Math::randf()), randomness[PARAM_INITIAL_LINEAR_VELOCITY]);
+ Vector3 spread_direction = Vector3(direction_xz.x * direction_yz.z, direction_yz.y, direction_xz.z * direction_yz.z);
+ Vector3 direction_nrm = direction;
+ if (direction_nrm.length_squared() > 0) {
+ direction_nrm.normalize();
+ } else {
+ direction_nrm = Vector3(0, 0, 1);
+ }
+ // rotate spread to direction
+ Vector3 binormal = Vector3(0.0, 1.0, 0.0).cross(direction_nrm);
+ if (binormal.length_squared() < 0.00000001) {
+ // direction is parallel to Y. Choose Z as the binormal.
+ binormal = Vector3(0.0, 0.0, 1.0);
+ }
+ binormal.normalize();
+ Vector3 normal = binormal.cross(direction_nrm);
+ spread_direction = binormal * spread_direction.x + normal * spread_direction.y + direction_nrm * spread_direction.z;
+ p.velocity = spread_direction * Math::lerp(parameters_min[PARAM_INITIAL_LINEAR_VELOCITY], parameters_max[PARAM_INITIAL_LINEAR_VELOCITY], (real_t)Math::randf());
}
- float base_angle = (parameters[PARAM_ANGLE] + tex_angle) * Math::lerp(1.0f, p.angle_rand, randomness[PARAM_ANGLE]);
+ real_t base_angle = tex_angle * Math::lerp(parameters_min[PARAM_ANGLE], parameters_max[PARAM_ANGLE], p.angle_rand);
p.custom[0] = Math::deg2rad(base_angle); //angle
p.custom[1] = 0.0; //phase
- p.custom[2] = (parameters[PARAM_ANIM_OFFSET] + tex_anim_offset) * Math::lerp(1.0f, p.anim_offset_rand, randomness[PARAM_ANIM_OFFSET]); //animation offset (0-1)
- p.transform = Transform();
+ p.custom[2] = tex_anim_offset * Math::lerp(parameters_min[PARAM_ANIM_OFFSET], parameters_max[PARAM_ANIM_OFFSET], p.anim_offset_rand); //animation offset (0-1)
+ p.transform = Transform3D();
p.time = 0;
p.lifetime = lifetime * (1.0 - Math::randf() * lifetime_randomness);
p.base_color = Color(1, 1, 1, 1);
@@ -705,6 +804,13 @@ void CPUParticles3D::_particles_process(float p_delta) {
case EMISSION_SHAPE_SPHERE: {
real_t s = 2.0 * Math::randf() - 1.0;
real_t t = Math_TAU * Math::randf();
+ real_t x = Math::randf();
+ real_t radius = emission_sphere_radius * Math::sqrt(1.0 - s * s);
+ p.transform.origin = Vector3(0, 0, 0).lerp(Vector3(radius * Math::cos(t), radius * Math::sin(t), emission_sphere_radius * s), x);
+ } break;
+ case EMISSION_SHAPE_SPHERE_SURFACE: {
+ real_t s = 2.0 * Math::randf() - 1.0;
+ real_t t = Math_TAU * Math::randf();
real_t radius = emission_sphere_radius * Math::sqrt(1.0 - s * s);
p.transform.origin = Vector3(radius * Math::cos(t), radius * Math::sin(t), emission_sphere_radius * s);
} break;
@@ -727,8 +833,8 @@ void CPUParticles3D::_particles_process(float p_delta) {
Vector3 normal = emission_normals.get(random_idx);
Vector2 normal_2d(normal.x, normal.y);
Transform2D m2;
- m2.set_axis(0, normal_2d);
- m2.set_axis(1, normal_2d.orthogonal());
+ m2.columns[0] = normal_2d;
+ m2.columns[1] = normal_2d.orthogonal();
Vector2 velocity_2d(p.velocity.x, p.velocity.y);
velocity_2d = m2.basis_xform(velocity_2d);
p.velocity.x = velocity_2d.x;
@@ -739,9 +845,9 @@ void CPUParticles3D::_particles_process(float p_delta) {
Vector3 tangent = v0.cross(normal).normalized();
Vector3 bitangent = tangent.cross(normal).normalized();
Basis m3;
- m3.set_axis(0, tangent);
- m3.set_axis(1, bitangent);
- m3.set_axis(2, normal);
+ m3.set_column(0, tangent);
+ m3.set_column(1, bitangent);
+ m3.set_column(2, normal);
p.velocity = m3.xform(p.velocity);
}
}
@@ -750,6 +856,21 @@ void CPUParticles3D::_particles_process(float p_delta) {
p.base_color = emission_colors.get(random_idx);
}
} break;
+ case EMISSION_SHAPE_RING: {
+ real_t ring_random_angle = Math::randf() * Math_TAU;
+ real_t ring_random_radius = Math::randf() * (emission_ring_radius - emission_ring_inner_radius) + emission_ring_inner_radius;
+ Vector3 axis = emission_ring_axis.normalized();
+ Vector3 ortho_axis = Vector3();
+ if (axis == Vector3(1.0, 0.0, 0.0)) {
+ ortho_axis = Vector3(0.0, 1.0, 0.0).cross(axis);
+ } else {
+ ortho_axis = Vector3(1.0, 0.0, 0.0).cross(axis);
+ }
+ ortho_axis = ortho_axis.normalized();
+ ortho_axis.rotate(axis, ring_random_angle);
+ ortho_axis = ortho_axis.normalized();
+ p.transform.origin = ortho_axis * ring_random_radius + (Math::randf() * emission_ring_height - emission_ring_height / 2.0) * axis;
+ } break;
case EMISSION_SHAPE_MAX: { // Max value for validity check.
break;
}
@@ -777,53 +898,53 @@ void CPUParticles3D::_particles_process(float p_delta) {
p.custom[1] = p.time / lifetime;
tv = p.time / p.lifetime;
- float tex_linear_velocity = 0.0;
+ real_t tex_linear_velocity = 1.0;
if (curve_parameters[PARAM_INITIAL_LINEAR_VELOCITY].is_valid()) {
tex_linear_velocity = curve_parameters[PARAM_INITIAL_LINEAR_VELOCITY]->interpolate(tv);
}
- float tex_orbit_velocity = 0.0;
+ real_t tex_orbit_velocity = 1.0;
if (particle_flags[PARTICLE_FLAG_DISABLE_Z]) {
if (curve_parameters[PARAM_ORBIT_VELOCITY].is_valid()) {
tex_orbit_velocity = curve_parameters[PARAM_ORBIT_VELOCITY]->interpolate(tv);
}
}
- float tex_angular_velocity = 0.0;
+ real_t tex_angular_velocity = 1.0;
if (curve_parameters[PARAM_ANGULAR_VELOCITY].is_valid()) {
tex_angular_velocity = curve_parameters[PARAM_ANGULAR_VELOCITY]->interpolate(tv);
}
- float tex_linear_accel = 0.0;
+ real_t tex_linear_accel = 1.0;
if (curve_parameters[PARAM_LINEAR_ACCEL].is_valid()) {
tex_linear_accel = curve_parameters[PARAM_LINEAR_ACCEL]->interpolate(tv);
}
- float tex_tangential_accel = 0.0;
+ real_t tex_tangential_accel = 1.0;
if (curve_parameters[PARAM_TANGENTIAL_ACCEL].is_valid()) {
tex_tangential_accel = curve_parameters[PARAM_TANGENTIAL_ACCEL]->interpolate(tv);
}
- float tex_radial_accel = 0.0;
+ real_t tex_radial_accel = 1.0;
if (curve_parameters[PARAM_RADIAL_ACCEL].is_valid()) {
tex_radial_accel = curve_parameters[PARAM_RADIAL_ACCEL]->interpolate(tv);
}
- float tex_damping = 0.0;
+ real_t tex_damping = 1.0;
if (curve_parameters[PARAM_DAMPING].is_valid()) {
tex_damping = curve_parameters[PARAM_DAMPING]->interpolate(tv);
}
- float tex_angle = 0.0;
+ real_t tex_angle = 1.0;
if (curve_parameters[PARAM_ANGLE].is_valid()) {
tex_angle = curve_parameters[PARAM_ANGLE]->interpolate(tv);
}
- float tex_anim_speed = 0.0;
+ real_t tex_anim_speed = 1.0;
if (curve_parameters[PARAM_ANIM_SPEED].is_valid()) {
tex_anim_speed = curve_parameters[PARAM_ANIM_SPEED]->interpolate(tv);
}
- float tex_anim_offset = 0.0;
+ real_t tex_anim_offset = 1.0;
if (curve_parameters[PARAM_ANIM_OFFSET].is_valid()) {
tex_anim_offset = curve_parameters[PARAM_ANIM_OFFSET]->interpolate(tv);
}
@@ -834,28 +955,27 @@ void CPUParticles3D::_particles_process(float p_delta) {
position.z = 0.0;
}
//apply linear acceleration
- force += p.velocity.length() > 0.0 ? p.velocity.normalized() * (parameters[PARAM_LINEAR_ACCEL] + tex_linear_accel) * Math::lerp(1.0f, rand_from_seed(alt_seed), randomness[PARAM_LINEAR_ACCEL]) : Vector3();
+ force += p.velocity.length() > 0.0 ? p.velocity.normalized() * tex_linear_accel * Math::lerp(parameters_min[PARAM_LINEAR_ACCEL], parameters_max[PARAM_LINEAR_ACCEL], rand_from_seed(alt_seed)) : Vector3();
//apply radial acceleration
Vector3 org = emission_xform.origin;
Vector3 diff = position - org;
- force += diff.length() > 0.0 ? diff.normalized() * (parameters[PARAM_RADIAL_ACCEL] + tex_radial_accel) * Math::lerp(1.0f, rand_from_seed(alt_seed), randomness[PARAM_RADIAL_ACCEL]) : Vector3();
- //apply tangential acceleration;
+ force += diff.length() > 0.0 ? diff.normalized() * (tex_radial_accel)*Math::lerp(parameters_min[PARAM_RADIAL_ACCEL], parameters_max[PARAM_RADIAL_ACCEL], rand_from_seed(alt_seed)) : Vector3();
if (particle_flags[PARTICLE_FLAG_DISABLE_Z]) {
Vector2 yx = Vector2(diff.y, diff.x);
Vector2 yx2 = (yx * Vector2(-1.0, 1.0)).normalized();
- force += yx.length() > 0.0 ? Vector3(yx2.x, yx2.y, 0.0) * ((parameters[PARAM_TANGENTIAL_ACCEL] + tex_tangential_accel) * Math::lerp(1.0f, rand_from_seed(alt_seed), randomness[PARAM_TANGENTIAL_ACCEL])) : Vector3();
+ force += yx.length() > 0.0 ? Vector3(yx2.x, yx2.y, 0.0) * (tex_tangential_accel * Math::lerp(parameters_min[PARAM_TANGENTIAL_ACCEL], parameters_max[PARAM_TANGENTIAL_ACCEL], rand_from_seed(alt_seed))) : Vector3();
} else {
Vector3 crossDiff = diff.normalized().cross(gravity.normalized());
- force += crossDiff.length() > 0.0 ? crossDiff.normalized() * ((parameters[PARAM_TANGENTIAL_ACCEL] + tex_tangential_accel) * Math::lerp(1.0f, rand_from_seed(alt_seed), randomness[PARAM_TANGENTIAL_ACCEL])) : Vector3();
+ force += crossDiff.length() > 0.0 ? crossDiff.normalized() * (tex_tangential_accel * Math::lerp(parameters_min[PARAM_TANGENTIAL_ACCEL], parameters_max[PARAM_TANGENTIAL_ACCEL], rand_from_seed(alt_seed))) : Vector3();
}
//apply attractor forces
p.velocity += force * local_delta;
//orbit velocity
if (particle_flags[PARTICLE_FLAG_DISABLE_Z]) {
- float orbit_amount = (parameters[PARAM_ORBIT_VELOCITY] + tex_orbit_velocity) * Math::lerp(1.0f, rand_from_seed(alt_seed), randomness[PARAM_ORBIT_VELOCITY]);
+ real_t orbit_amount = tex_orbit_velocity * Math::lerp(parameters_min[PARAM_ORBIT_VELOCITY], parameters_max[PARAM_ORBIT_VELOCITY], rand_from_seed(alt_seed));
if (orbit_amount != 0.0) {
- float ang = orbit_amount * local_delta * Math_TAU;
+ real_t ang = orbit_amount * local_delta * Math_TAU;
// Not sure why the ParticlesMaterial code uses a clockwise rotation matrix,
// but we use -ang here to reproduce its behavior.
Transform2D rot = Transform2D(-ang, Vector2());
@@ -867,9 +987,10 @@ void CPUParticles3D::_particles_process(float p_delta) {
if (curve_parameters[PARAM_INITIAL_LINEAR_VELOCITY].is_valid()) {
p.velocity = p.velocity.normalized() * tex_linear_velocity;
}
- if (parameters[PARAM_DAMPING] + tex_damping > 0.0) {
- float v = p.velocity.length();
- float damp = (parameters[PARAM_DAMPING] + tex_damping) * Math::lerp(1.0f, rand_from_seed(alt_seed), randomness[PARAM_DAMPING]);
+
+ if (parameters_max[PARAM_DAMPING] + tex_damping > 0.0) {
+ real_t v = p.velocity.length();
+ real_t damp = tex_damping * Math::lerp(parameters_min[PARAM_DAMPING], parameters_max[PARAM_DAMPING], rand_from_seed(alt_seed));
v -= damp * local_delta;
if (v < 0.0) {
p.velocity = Vector3();
@@ -877,27 +998,48 @@ void CPUParticles3D::_particles_process(float p_delta) {
p.velocity = p.velocity.normalized() * v;
}
}
- float base_angle = (parameters[PARAM_ANGLE] + tex_angle) * Math::lerp(1.0f, p.angle_rand, randomness[PARAM_ANGLE]);
- base_angle += p.custom[1] * lifetime * (parameters[PARAM_ANGULAR_VELOCITY] + tex_angular_velocity) * Math::lerp(1.0f, rand_from_seed(alt_seed) * 2.0f - 1.0f, randomness[PARAM_ANGULAR_VELOCITY]);
+ real_t base_angle = (tex_angle)*Math::lerp(parameters_min[PARAM_ANGLE], parameters_max[PARAM_ANGLE], p.angle_rand);
+ base_angle += p.custom[1] * lifetime * tex_angular_velocity * Math::lerp(parameters_min[PARAM_ANGULAR_VELOCITY], parameters_max[PARAM_ANGULAR_VELOCITY], rand_from_seed(alt_seed));
p.custom[0] = Math::deg2rad(base_angle); //angle
- p.custom[2] = (parameters[PARAM_ANIM_OFFSET] + tex_anim_offset) * Math::lerp(1.0f, p.anim_offset_rand, randomness[PARAM_ANIM_OFFSET]) + p.custom[1] * (parameters[PARAM_ANIM_SPEED] + tex_anim_speed) * Math::lerp(1.0f, rand_from_seed(alt_seed), randomness[PARAM_ANIM_SPEED]); //angle
+ p.custom[2] = tex_anim_offset * Math::lerp(parameters_min[PARAM_ANIM_OFFSET], parameters_max[PARAM_ANIM_OFFSET], p.anim_offset_rand) + tv * tex_anim_speed * Math::lerp(parameters_min[PARAM_ANIM_SPEED], parameters_max[PARAM_ANIM_SPEED], rand_from_seed(alt_seed)); //angle
}
//apply color
//apply hue rotation
- float tex_scale = 1.0;
- if (curve_parameters[PARAM_SCALE].is_valid()) {
- tex_scale = curve_parameters[PARAM_SCALE]->interpolate(tv);
+ Vector3 tex_scale = Vector3(1.0, 1.0, 1.0);
+ if (split_scale) {
+ if (scale_curve_x.is_valid()) {
+ tex_scale.x = scale_curve_x->interpolate(tv);
+ } else {
+ tex_scale.x = 1.0;
+ }
+ if (scale_curve_y.is_valid()) {
+ tex_scale.y = scale_curve_y->interpolate(tv);
+ } else {
+ tex_scale.y = 1.0;
+ }
+ if (scale_curve_z.is_valid()) {
+ tex_scale.z = scale_curve_z->interpolate(tv);
+ } else {
+ tex_scale.z = 1.0;
+ }
+ } else {
+ if (curve_parameters[PARAM_SCALE].is_valid()) {
+ float tmp_scale = curve_parameters[PARAM_SCALE]->interpolate(tv);
+ tex_scale.x = tmp_scale;
+ tex_scale.y = tmp_scale;
+ tex_scale.z = tmp_scale;
+ }
}
- float tex_hue_variation = 0.0;
+ real_t tex_hue_variation = 0.0;
if (curve_parameters[PARAM_HUE_VARIATION].is_valid()) {
tex_hue_variation = curve_parameters[PARAM_HUE_VARIATION]->interpolate(tv);
}
- float hue_rot_angle = (parameters[PARAM_HUE_VARIATION] + tex_hue_variation) * Math_TAU * Math::lerp(1.0f, p.hue_rot_rand * 2.0f - 1.0f, randomness[PARAM_HUE_VARIATION]);
- float hue_rot_c = Math::cos(hue_rot_angle);
- float hue_rot_s = Math::sin(hue_rot_angle);
+ real_t hue_rot_angle = (tex_hue_variation)*Math_TAU * Math::lerp(parameters_min[PARAM_HUE_VARIATION], parameters_max[PARAM_HUE_VARIATION], p.hue_rot_rand);
+ real_t hue_rot_c = Math::cos(hue_rot_angle);
+ real_t hue_rot_s = Math::sin(hue_rot_angle);
Basis hue_rot_mat;
{
@@ -921,38 +1063,38 @@ void CPUParticles3D::_particles_process(float p_delta) {
p.color.g = color_rgb.y;
p.color.b = color_rgb.z;
- p.color *= p.base_color;
+ p.color *= p.base_color * p.start_color_rand;
if (particle_flags[PARTICLE_FLAG_DISABLE_Z]) {
if (particle_flags[PARTICLE_FLAG_ALIGN_Y_TO_VELOCITY]) {
if (p.velocity.length() > 0.0) {
- p.transform.basis.set_axis(1, p.velocity.normalized());
+ p.transform.basis.set_column(1, p.velocity.normalized());
} else {
- p.transform.basis.set_axis(1, p.transform.basis.get_axis(1));
+ p.transform.basis.set_column(1, p.transform.basis.get_column(1));
}
- p.transform.basis.set_axis(0, p.transform.basis.get_axis(1).cross(p.transform.basis.get_axis(2)).normalized());
- p.transform.basis.set_axis(2, Vector3(0, 0, 1));
+ p.transform.basis.set_column(0, p.transform.basis.get_column(1).cross(p.transform.basis.get_column(2)).normalized());
+ p.transform.basis.set_column(2, Vector3(0, 0, 1));
} else {
- p.transform.basis.set_axis(0, Vector3(Math::cos(p.custom[0]), -Math::sin(p.custom[0]), 0.0));
- p.transform.basis.set_axis(1, Vector3(Math::sin(p.custom[0]), Math::cos(p.custom[0]), 0.0));
- p.transform.basis.set_axis(2, Vector3(0, 0, 1));
+ p.transform.basis.set_column(0, Vector3(Math::cos(p.custom[0]), -Math::sin(p.custom[0]), 0.0));
+ p.transform.basis.set_column(1, Vector3(Math::sin(p.custom[0]), Math::cos(p.custom[0]), 0.0));
+ p.transform.basis.set_column(2, Vector3(0, 0, 1));
}
} else {
//orient particle Y towards velocity
if (particle_flags[PARTICLE_FLAG_ALIGN_Y_TO_VELOCITY]) {
if (p.velocity.length() > 0.0) {
- p.transform.basis.set_axis(1, p.velocity.normalized());
+ p.transform.basis.set_column(1, p.velocity.normalized());
} else {
- p.transform.basis.set_axis(1, p.transform.basis.get_axis(1).normalized());
+ p.transform.basis.set_column(1, p.transform.basis.get_column(1).normalized());
}
- if (p.transform.basis.get_axis(1) == p.transform.basis.get_axis(0)) {
- p.transform.basis.set_axis(0, p.transform.basis.get_axis(1).cross(p.transform.basis.get_axis(2)).normalized());
- p.transform.basis.set_axis(2, p.transform.basis.get_axis(0).cross(p.transform.basis.get_axis(1)).normalized());
+ if (p.transform.basis.get_column(1) == p.transform.basis.get_column(0)) {
+ p.transform.basis.set_column(0, p.transform.basis.get_column(1).cross(p.transform.basis.get_column(2)).normalized());
+ p.transform.basis.set_column(2, p.transform.basis.get_column(0).cross(p.transform.basis.get_column(1)).normalized());
} else {
- p.transform.basis.set_axis(2, p.transform.basis.get_axis(0).cross(p.transform.basis.get_axis(1)).normalized());
- p.transform.basis.set_axis(0, p.transform.basis.get_axis(1).cross(p.transform.basis.get_axis(2)).normalized());
+ p.transform.basis.set_column(2, p.transform.basis.get_column(0).cross(p.transform.basis.get_column(1)).normalized());
+ p.transform.basis.set_column(0, p.transform.basis.get_column(1).cross(p.transform.basis.get_column(2)).normalized());
}
} else {
p.transform.basis.orthonormalize();
@@ -965,13 +1107,21 @@ void CPUParticles3D::_particles_process(float p_delta) {
}
}
+ p.transform.basis = p.transform.basis.orthonormalized();
//scale by scale
- float base_scale = tex_scale * Math::lerp(parameters[PARAM_SCALE], 1.0f, p.scale_rand * randomness[PARAM_SCALE]);
- if (base_scale < 0.000001) {
- base_scale = 0.000001;
+
+ Vector3 base_scale = tex_scale * Math::lerp(parameters_min[PARAM_SCALE], parameters_max[PARAM_SCALE], p.scale_rand);
+ if (base_scale.x < CMP_EPSILON) {
+ base_scale.x = CMP_EPSILON;
+ }
+ if (base_scale.y < CMP_EPSILON) {
+ base_scale.y = CMP_EPSILON;
+ }
+ if (base_scale.z < CMP_EPSILON) {
+ base_scale.z = CMP_EPSILON;
}
- p.transform.basis.scale(Vector3(1, 1, 1) * base_scale);
+ p.transform.basis.scale(base_scale);
if (particle_flags[PARTICLE_FLAG_DISABLE_Z]) {
p.velocity.z = 0.0;
@@ -1007,9 +1157,9 @@ void CPUParticles3D::_update_particle_data_buffer() {
sorter.sort(order, pc);
} else if (draw_order == DRAW_ORDER_VIEW_DEPTH) {
ERR_FAIL_NULL(get_viewport());
- Camera3D *c = get_viewport()->get_camera();
+ Camera3D *c = get_viewport()->get_camera_3d();
if (c) {
- Vector3 dir = c->get_global_transform().basis.get_axis(2); //far away to close
+ Vector3 dir = c->get_global_transform().basis.get_column(2); //far away to close
if (local_coords) {
// will look different from Particles in editor as this is based on the camera in the scenetree
@@ -1030,27 +1180,27 @@ void CPUParticles3D::_update_particle_data_buffer() {
for (int i = 0; i < pc; i++) {
int idx = order ? order[i] : i;
- Transform t = r[idx].transform;
+ Transform3D t = r[idx].transform;
if (!local_coords) {
t = inv_emission_transform * t;
}
if (r[idx].active) {
- ptr[0] = t.basis.elements[0][0];
- ptr[1] = t.basis.elements[0][1];
- ptr[2] = t.basis.elements[0][2];
+ ptr[0] = t.basis.rows[0][0];
+ ptr[1] = t.basis.rows[0][1];
+ ptr[2] = t.basis.rows[0][2];
ptr[3] = t.origin.x;
- ptr[4] = t.basis.elements[1][0];
- ptr[5] = t.basis.elements[1][1];
- ptr[6] = t.basis.elements[1][2];
+ ptr[4] = t.basis.rows[1][0];
+ ptr[5] = t.basis.rows[1][1];
+ ptr[6] = t.basis.rows[1][2];
ptr[7] = t.origin.y;
- ptr[8] = t.basis.elements[2][0];
- ptr[9] = t.basis.elements[2][1];
- ptr[10] = t.basis.elements[2][2];
+ ptr[8] = t.basis.rows[2][0];
+ ptr[9] = t.basis.rows[2][1];
+ ptr[10] = t.basis.rows[2][2];
ptr[11] = t.origin.z;
} else {
- memset(ptr, 0, sizeof(float) * 12);
+ memset(ptr, 0, sizeof(Transform3D));
}
Color c = r[idx].color;
@@ -1104,65 +1254,67 @@ void CPUParticles3D::_update_render_thread() {
}
void CPUParticles3D::_notification(int p_what) {
- if (p_what == NOTIFICATION_ENTER_TREE) {
- set_process_internal(emitting);
+ switch (p_what) {
+ case NOTIFICATION_ENTER_TREE: {
+ set_process_internal(emitting);
- // first update before rendering to avoid one frame delay after emitting starts
- if (emitting && (time == 0)) {
- _update_internal();
- }
- }
+ // first update before rendering to avoid one frame delay after emitting starts
+ if (emitting && (time == 0)) {
+ _update_internal();
+ }
+ } break;
- if (p_what == NOTIFICATION_EXIT_TREE) {
- _set_redraw(false);
- }
+ case NOTIFICATION_EXIT_TREE: {
+ _set_redraw(false);
+ } break;
- if (p_what == NOTIFICATION_VISIBILITY_CHANGED) {
- // first update before rendering to avoid one frame delay after emitting starts
- if (emitting && (time == 0)) {
+ case NOTIFICATION_VISIBILITY_CHANGED: {
+ // first update before rendering to avoid one frame delay after emitting starts
+ if (emitting && (time == 0)) {
+ _update_internal();
+ }
+ } break;
+
+ case NOTIFICATION_INTERNAL_PROCESS: {
_update_internal();
- }
- }
+ } break;
- if (p_what == NOTIFICATION_INTERNAL_PROCESS) {
- _update_internal();
- }
+ case NOTIFICATION_TRANSFORM_CHANGED: {
+ inv_emission_transform = get_global_transform().affine_inverse();
- if (p_what == NOTIFICATION_TRANSFORM_CHANGED) {
- inv_emission_transform = get_global_transform().affine_inverse();
+ if (!local_coords) {
+ int pc = particles.size();
+
+ float *w = particle_data.ptrw();
+ const Particle *r = particles.ptr();
+ float *ptr = w;
+
+ for (int i = 0; i < pc; i++) {
+ Transform3D t = inv_emission_transform * r[i].transform;
+
+ if (r[i].active) {
+ ptr[0] = t.basis.rows[0][0];
+ ptr[1] = t.basis.rows[0][1];
+ ptr[2] = t.basis.rows[0][2];
+ ptr[3] = t.origin.x;
+ ptr[4] = t.basis.rows[1][0];
+ ptr[5] = t.basis.rows[1][1];
+ ptr[6] = t.basis.rows[1][2];
+ ptr[7] = t.origin.y;
+ ptr[8] = t.basis.rows[2][0];
+ ptr[9] = t.basis.rows[2][1];
+ ptr[10] = t.basis.rows[2][2];
+ ptr[11] = t.origin.z;
+ } else {
+ memset(ptr, 0, sizeof(float) * 12);
+ }
- if (!local_coords) {
- int pc = particles.size();
-
- float *w = particle_data.ptrw();
- const Particle *r = particles.ptr();
- float *ptr = w;
-
- for (int i = 0; i < pc; i++) {
- Transform t = inv_emission_transform * r[i].transform;
-
- if (r[i].active) {
- ptr[0] = t.basis.elements[0][0];
- ptr[1] = t.basis.elements[0][1];
- ptr[2] = t.basis.elements[0][2];
- ptr[3] = t.origin.x;
- ptr[4] = t.basis.elements[1][0];
- ptr[5] = t.basis.elements[1][1];
- ptr[6] = t.basis.elements[1][2];
- ptr[7] = t.origin.y;
- ptr[8] = t.basis.elements[2][0];
- ptr[9] = t.basis.elements[2][1];
- ptr[10] = t.basis.elements[2][2];
- ptr[11] = t.origin.z;
- } else {
- memset(ptr, 0, sizeof(float) * 12);
+ ptr += 20;
}
- ptr += 20;
+ can_update.set();
}
-
- can_update.set();
- }
+ } break;
}
}
@@ -1195,11 +1347,16 @@ void CPUParticles3D::convert_from_particles(Node *p_particles) {
set_color(material->get_color());
- Ref<GradientTexture> gt = material->get_color_ramp();
+ Ref<GradientTexture1D> gt = material->get_color_ramp();
if (gt.is_valid()) {
set_color_ramp(gt->get_gradient());
}
+ Ref<GradientTexture1D> gti = material->get_color_initial_ramp();
+ if (gti.is_valid()) {
+ set_color_initial_ramp(gti->get_gradient());
+ }
+
set_particle_flag(PARTICLE_FLAG_ALIGN_Y_TO_VELOCITY, material->get_particle_flag(ParticlesMaterial::PARTICLE_FLAG_ALIGN_Y_TO_VELOCITY));
set_particle_flag(PARTICLE_FLAG_ROTATE_Y, material->get_particle_flag(ParticlesMaterial::PARTICLE_FLAG_ROTATE_Y));
set_particle_flag(PARTICLE_FLAG_DISABLE_Z, material->get_particle_flag(ParticlesMaterial::PARTICLE_FLAG_DISABLE_Z));
@@ -1207,18 +1364,25 @@ void CPUParticles3D::convert_from_particles(Node *p_particles) {
set_emission_shape(EmissionShape(material->get_emission_shape()));
set_emission_sphere_radius(material->get_emission_sphere_radius());
set_emission_box_extents(material->get_emission_box_extents());
+ Ref<CurveXYZTexture> scale3D = material->get_param_texture(ParticlesMaterial::PARAM_SCALE);
+ if (scale3D.is_valid()) {
+ split_scale = true;
+ scale_curve_x = scale3D->get_curve_x();
+ scale_curve_y = scale3D->get_curve_y();
+ scale_curve_z = scale3D->get_curve_z();
+ }
set_gravity(material->get_gravity());
set_lifetime_randomness(material->get_lifetime_randomness());
#define CONVERT_PARAM(m_param) \
- set_param(m_param, material->get_param(ParticlesMaterial::m_param)); \
+ set_param_min(m_param, material->get_param_min(ParticlesMaterial::m_param)); \
{ \
Ref<CurveTexture> ctex = material->get_param_texture(ParticlesMaterial::m_param); \
if (ctex.is_valid()) \
set_param_curve(m_param, ctex->get_curve()); \
} \
- set_param_randomness(m_param, material->get_param_randomness(ParticlesMaterial::m_param));
+ set_param_max(m_param, material->get_param_max(ParticlesMaterial::m_param));
CONVERT_PARAM(PARAM_INITIAL_LINEAR_VELOCITY);
CONVERT_PARAM(PARAM_ANGULAR_VELOCITY);
@@ -1273,11 +1437,11 @@ void CPUParticles3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("restart"), &CPUParticles3D::restart);
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "emitting"), "set_emitting", "is_emitting");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "amount", PROPERTY_HINT_EXP_RANGE, "1,1000000,1"), "set_amount", "get_amount");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "amount", PROPERTY_HINT_RANGE, "1,1000000,1,exp"), "set_amount", "get_amount");
ADD_GROUP("Time", "");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "lifetime", PROPERTY_HINT_EXP_RANGE, "0.01,600.0,0.01,or_greater"), "set_lifetime", "get_lifetime");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "lifetime", PROPERTY_HINT_RANGE, "0.01,600.0,0.01,or_greater,exp"), "set_lifetime", "get_lifetime");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "one_shot"), "set_one_shot", "get_one_shot");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "preprocess", PROPERTY_HINT_EXP_RANGE, "0.00,600.0,0.01"), "set_pre_process_time", "get_pre_process_time");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "preprocess", PROPERTY_HINT_RANGE, "0.00,600.0,0.01,exp"), "set_pre_process_time", "get_pre_process_time");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "speed_scale", PROPERTY_HINT_RANGE, "0,64,0.01"), "set_speed_scale", "get_speed_scale");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "explosiveness", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_explosiveness_ratio", "get_explosiveness_ratio");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "randomness", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_randomness_ratio", "get_randomness_ratio");
@@ -1304,11 +1468,11 @@ void CPUParticles3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_flatness", "amount"), &CPUParticles3D::set_flatness);
ClassDB::bind_method(D_METHOD("get_flatness"), &CPUParticles3D::get_flatness);
- ClassDB::bind_method(D_METHOD("set_param", "param", "value"), &CPUParticles3D::set_param);
- ClassDB::bind_method(D_METHOD("get_param", "param"), &CPUParticles3D::get_param);
+ ClassDB::bind_method(D_METHOD("set_param_min", "param", "value"), &CPUParticles3D::set_param_min);
+ ClassDB::bind_method(D_METHOD("get_param_min", "param"), &CPUParticles3D::get_param_min);
- ClassDB::bind_method(D_METHOD("set_param_randomness", "param", "randomness"), &CPUParticles3D::set_param_randomness);
- ClassDB::bind_method(D_METHOD("get_param_randomness", "param"), &CPUParticles3D::get_param_randomness);
+ ClassDB::bind_method(D_METHOD("set_param_max", "param", "value"), &CPUParticles3D::set_param_max);
+ ClassDB::bind_method(D_METHOD("get_param_max", "param"), &CPUParticles3D::get_param_max);
ClassDB::bind_method(D_METHOD("set_param_curve", "param", "curve"), &CPUParticles3D::set_param_curve);
ClassDB::bind_method(D_METHOD("get_param_curve", "param"), &CPUParticles3D::get_param_curve);
@@ -1319,6 +1483,9 @@ void CPUParticles3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_color_ramp", "ramp"), &CPUParticles3D::set_color_ramp);
ClassDB::bind_method(D_METHOD("get_color_ramp"), &CPUParticles3D::get_color_ramp);
+ ClassDB::bind_method(D_METHOD("set_color_initial_ramp", "ramp"), &CPUParticles3D::set_color_initial_ramp);
+ ClassDB::bind_method(D_METHOD("get_color_initial_ramp"), &CPUParticles3D::get_color_initial_ramp);
+
ClassDB::bind_method(D_METHOD("set_particle_flag", "particle_flag", "enable"), &CPUParticles3D::set_particle_flag);
ClassDB::bind_method(D_METHOD("get_particle_flag", "particle_flag"), &CPUParticles3D::get_particle_flag);
@@ -1340,18 +1507,46 @@ void CPUParticles3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_emission_colors", "array"), &CPUParticles3D::set_emission_colors);
ClassDB::bind_method(D_METHOD("get_emission_colors"), &CPUParticles3D::get_emission_colors);
+ ClassDB::bind_method(D_METHOD("set_emission_ring_axis", "axis"), &CPUParticles3D::set_emission_ring_axis);
+ ClassDB::bind_method(D_METHOD("get_emission_ring_axis"), &CPUParticles3D::get_emission_ring_axis);
+
+ ClassDB::bind_method(D_METHOD("set_emission_ring_height", "height"), &CPUParticles3D::set_emission_ring_height);
+ ClassDB::bind_method(D_METHOD("get_emission_ring_height"), &CPUParticles3D::get_emission_ring_height);
+
+ ClassDB::bind_method(D_METHOD("set_emission_ring_radius", "radius"), &CPUParticles3D::set_emission_ring_radius);
+ ClassDB::bind_method(D_METHOD("get_emission_ring_radius"), &CPUParticles3D::get_emission_ring_radius);
+
+ ClassDB::bind_method(D_METHOD("set_emission_ring_inner_radius", "inner_radius"), &CPUParticles3D::set_emission_ring_inner_radius);
+ ClassDB::bind_method(D_METHOD("get_emission_ring_inner_radius"), &CPUParticles3D::get_emission_ring_inner_radius);
+
ClassDB::bind_method(D_METHOD("get_gravity"), &CPUParticles3D::get_gravity);
ClassDB::bind_method(D_METHOD("set_gravity", "accel_vec"), &CPUParticles3D::set_gravity);
+ ClassDB::bind_method(D_METHOD("get_split_scale"), &CPUParticles3D::get_split_scale);
+ ClassDB::bind_method(D_METHOD("set_split_scale", "split_scale"), &CPUParticles3D::set_split_scale);
+
+ ClassDB::bind_method(D_METHOD("get_scale_curve_x"), &CPUParticles3D::get_scale_curve_x);
+ ClassDB::bind_method(D_METHOD("set_scale_curve_x", "scale_curve"), &CPUParticles3D::set_scale_curve_x);
+
+ ClassDB::bind_method(D_METHOD("get_scale_curve_y"), &CPUParticles3D::get_scale_curve_y);
+ ClassDB::bind_method(D_METHOD("set_scale_curve_y", "scale_curve"), &CPUParticles3D::set_scale_curve_y);
+
+ ClassDB::bind_method(D_METHOD("get_scale_curve_z"), &CPUParticles3D::get_scale_curve_z);
+ ClassDB::bind_method(D_METHOD("set_scale_curve_z", "scale_curve"), &CPUParticles3D::set_scale_curve_z);
+
ClassDB::bind_method(D_METHOD("convert_from_particles", "particles"), &CPUParticles3D::convert_from_particles);
ADD_GROUP("Emission Shape", "emission_");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "emission_shape", PROPERTY_HINT_ENUM, "Point,Sphere,Box,Points,Directed Points", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), "set_emission_shape", "get_emission_shape");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "emission_shape", PROPERTY_HINT_ENUM, "Point,Sphere,Sphere Surface,Box,Points,Directed Points,Ring", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), "set_emission_shape", "get_emission_shape");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "emission_sphere_radius", PROPERTY_HINT_RANGE, "0.01,128,0.01"), "set_emission_sphere_radius", "get_emission_sphere_radius");
ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "emission_box_extents"), "set_emission_box_extents", "get_emission_box_extents");
ADD_PROPERTY(PropertyInfo(Variant::PACKED_VECTOR3_ARRAY, "emission_points"), "set_emission_points", "get_emission_points");
ADD_PROPERTY(PropertyInfo(Variant::PACKED_VECTOR3_ARRAY, "emission_normals"), "set_emission_normals", "get_emission_normals");
ADD_PROPERTY(PropertyInfo(Variant::PACKED_COLOR_ARRAY, "emission_colors"), "set_emission_colors", "get_emission_colors");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "emission_ring_axis"), "set_emission_ring_axis", "get_emission_ring_axis");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "emission_ring_height"), "set_emission_ring_height", "get_emission_ring_height");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "emission_ring_radius"), "set_emission_ring_radius", "get_emission_ring_radius");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "emission_ring_inner_radius"), "set_emission_ring_inner_radius", "get_emission_ring_inner_radius");
ADD_GROUP("Particle Flags", "particle_flag_");
ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "particle_flag_align_y"), "set_particle_flag", "get_particle_flag", PARTICLE_FLAG_ALIGN_Y_TO_VELOCITY);
ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "particle_flag_rotate_y"), "set_particle_flag", "get_particle_flag", PARTICLE_FLAG_ROTATE_Y);
@@ -1363,54 +1558,59 @@ void CPUParticles3D::_bind_methods() {
ADD_GROUP("Gravity", "");
ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "gravity"), "set_gravity", "get_gravity");
ADD_GROUP("Initial Velocity", "initial_");
- ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "initial_velocity", PROPERTY_HINT_RANGE, "0,1000,0.01,or_greater"), "set_param", "get_param", PARAM_INITIAL_LINEAR_VELOCITY);
- ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "initial_velocity_random", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_param_randomness", "get_param_randomness", PARAM_INITIAL_LINEAR_VELOCITY);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "initial_velocity_min", PROPERTY_HINT_RANGE, "0,1000,0.01,or_greater"), "set_param_min", "get_param_min", PARAM_INITIAL_LINEAR_VELOCITY);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "initial_velocity_max", PROPERTY_HINT_RANGE, "0,1000,0.01,or_greater"), "set_param_max", "get_param_max", PARAM_INITIAL_LINEAR_VELOCITY);
ADD_GROUP("Angular Velocity", "angular_");
- ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "angular_velocity", PROPERTY_HINT_RANGE, "-720,720,0.01,or_lesser,or_greater"), "set_param", "get_param", PARAM_ANGULAR_VELOCITY);
- ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "angular_velocity_random", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_param_randomness", "get_param_randomness", PARAM_ANGULAR_VELOCITY);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "angular_velocity_min", PROPERTY_HINT_RANGE, "-720,720,0.01,or_lesser,or_greater"), "set_param_min", "get_param_min", PARAM_ANGULAR_VELOCITY);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "angular_velocity_max", PROPERTY_HINT_RANGE, "-720,720,0.01,or_lesser,or_greater"), "set_param_max", "get_param_max", PARAM_ANGULAR_VELOCITY);
ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "angular_velocity_curve", PROPERTY_HINT_RESOURCE_TYPE, "Curve"), "set_param_curve", "get_param_curve", PARAM_ANGULAR_VELOCITY);
ADD_GROUP("Orbit Velocity", "orbit_");
- ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "orbit_velocity", PROPERTY_HINT_RANGE, "-1000,1000,0.01,or_lesser,or_greater"), "set_param", "get_param", PARAM_ORBIT_VELOCITY);
- ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "orbit_velocity_random", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_param_randomness", "get_param_randomness", PARAM_ORBIT_VELOCITY);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "orbit_velocity_min", PROPERTY_HINT_RANGE, "-1000,1000,0.01,or_lesser,or_greater"), "set_param_min", "get_param_min", PARAM_ORBIT_VELOCITY);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "orbit_velocity_max", PROPERTY_HINT_RANGE, "-1000,1000,0.01,or_lesser,or_greater"), "set_param_max", "get_param_max", PARAM_ORBIT_VELOCITY);
ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "orbit_velocity_curve", PROPERTY_HINT_RESOURCE_TYPE, "Curve"), "set_param_curve", "get_param_curve", PARAM_ORBIT_VELOCITY);
ADD_GROUP("Linear Accel", "linear_");
- ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "linear_accel", PROPERTY_HINT_RANGE, "-100,100,0.01,or_lesser,or_greater"), "set_param", "get_param", PARAM_LINEAR_ACCEL);
- ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "linear_accel_random", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_param_randomness", "get_param_randomness", PARAM_LINEAR_ACCEL);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "linear_accel_min", PROPERTY_HINT_RANGE, "-100,100,0.01,or_lesser,or_greater"), "set_param_min", "get_param_min", PARAM_LINEAR_ACCEL);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "linear_accel_max", PROPERTY_HINT_RANGE, "-100,100,0.01,or_lesser,or_greater"), "set_param_max", "get_param_max", PARAM_LINEAR_ACCEL);
ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "linear_accel_curve", PROPERTY_HINT_RESOURCE_TYPE, "Curve"), "set_param_curve", "get_param_curve", PARAM_LINEAR_ACCEL);
ADD_GROUP("Radial Accel", "radial_");
- ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "radial_accel", PROPERTY_HINT_RANGE, "-100,100,0.01,or_lesser,or_greater"), "set_param", "get_param", PARAM_RADIAL_ACCEL);
- ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "radial_accel_random", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_param_randomness", "get_param_randomness", PARAM_RADIAL_ACCEL);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "radial_accel_min", PROPERTY_HINT_RANGE, "-100,100,0.01,or_lesser,or_greater"), "set_param_min", "get_param_min", PARAM_RADIAL_ACCEL);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "radial_accel_max", PROPERTY_HINT_RANGE, "-100,100,0.01,or_lesser,or_greater"), "set_param_max", "get_param_max", PARAM_RADIAL_ACCEL);
ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "radial_accel_curve", PROPERTY_HINT_RESOURCE_TYPE, "Curve"), "set_param_curve", "get_param_curve", PARAM_RADIAL_ACCEL);
ADD_GROUP("Tangential Accel", "tangential_");
- ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "tangential_accel", PROPERTY_HINT_RANGE, "-100,100,0.01,or_lesser,or_greater"), "set_param", "get_param", PARAM_TANGENTIAL_ACCEL);
- ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "tangential_accel_random", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_param_randomness", "get_param_randomness", PARAM_TANGENTIAL_ACCEL);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "tangential_accel_min", PROPERTY_HINT_RANGE, "-100,100,0.01,or_lesser,or_greater"), "set_param_min", "get_param_min", PARAM_TANGENTIAL_ACCEL);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "tangential_accel_max", PROPERTY_HINT_RANGE, "-100,100,0.01,or_lesser,or_greater"), "set_param_max", "get_param_max", PARAM_TANGENTIAL_ACCEL);
ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "tangential_accel_curve", PROPERTY_HINT_RESOURCE_TYPE, "Curve"), "set_param_curve", "get_param_curve", PARAM_TANGENTIAL_ACCEL);
ADD_GROUP("Damping", "");
- ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "damping", PROPERTY_HINT_RANGE, "0,100,0.01"), "set_param", "get_param", PARAM_DAMPING);
- ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "damping_random", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_param_randomness", "get_param_randomness", PARAM_DAMPING);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "damping_min", PROPERTY_HINT_RANGE, "0,100,0.01"), "set_param_min", "get_param_min", PARAM_DAMPING);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "damping_max", PROPERTY_HINT_RANGE, "0,100,0.01"), "set_param_max", "get_param_max", PARAM_DAMPING);
ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "damping_curve", PROPERTY_HINT_RESOURCE_TYPE, "Curve"), "set_param_curve", "get_param_curve", PARAM_DAMPING);
ADD_GROUP("Angle", "");
- ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "angle", PROPERTY_HINT_RANGE, "-720,720,0.1,or_lesser,or_greater"), "set_param", "get_param", PARAM_ANGLE);
- ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "angle_random", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_param_randomness", "get_param_randomness", PARAM_ANGLE);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "angle_min", PROPERTY_HINT_RANGE, "-720,720,0.1,or_lesser,or_greater,degrees"), "set_param_min", "get_param_min", PARAM_ANGLE);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "angle_max", PROPERTY_HINT_RANGE, "-720,720,0.1,or_lesser,or_greater,degrees"), "set_param_max", "get_param_max", PARAM_ANGLE);
ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "angle_curve", PROPERTY_HINT_RESOURCE_TYPE, "Curve"), "set_param_curve", "get_param_curve", PARAM_ANGLE);
ADD_GROUP("Scale", "");
- ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "scale_amount", PROPERTY_HINT_RANGE, "0,1000,0.01,or_greater"), "set_param", "get_param", PARAM_SCALE);
- ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "scale_amount_random", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_param_randomness", "get_param_randomness", PARAM_SCALE);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "scale_amount_min", PROPERTY_HINT_RANGE, "0,1000,0.01,or_greater"), "set_param_min", "get_param_min", PARAM_SCALE);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "scale_amount_max", PROPERTY_HINT_RANGE, "0,1000,0.01,or_greater"), "set_param_max", "get_param_max", PARAM_SCALE);
ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "scale_amount_curve", PROPERTY_HINT_RESOURCE_TYPE, "Curve"), "set_param_curve", "get_param_curve", PARAM_SCALE);
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "split_scale"), "set_split_scale", "get_split_scale");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "scale_curve_x", PROPERTY_HINT_RESOURCE_TYPE, "Curve"), "set_scale_curve_x", "get_scale_curve_x");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "scale_curve_y", PROPERTY_HINT_RESOURCE_TYPE, "Curve"), "set_scale_curve_y", "get_scale_curve_y");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "scale_curve_z", PROPERTY_HINT_RESOURCE_TYPE, "Curve"), "set_scale_curve_z", "get_scale_curve_z");
ADD_GROUP("Color", "");
ADD_PROPERTY(PropertyInfo(Variant::COLOR, "color"), "set_color", "get_color");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "color_ramp", PROPERTY_HINT_RESOURCE_TYPE, "Gradient"), "set_color_ramp", "get_color_ramp");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "color_initial_ramp", PROPERTY_HINT_RESOURCE_TYPE, "Gradient"), "set_color_initial_ramp", "get_color_initial_ramp");
ADD_GROUP("Hue Variation", "hue_");
- ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "hue_variation", PROPERTY_HINT_RANGE, "-1,1,0.01"), "set_param", "get_param", PARAM_HUE_VARIATION);
- ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "hue_variation_random", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_param_randomness", "get_param_randomness", PARAM_HUE_VARIATION);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "hue_variation_min", PROPERTY_HINT_RANGE, "-1,1,0.01"), "set_param_min", "get_param_min", PARAM_HUE_VARIATION);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "hue_variation_max", PROPERTY_HINT_RANGE, "-1,1,0.01"), "set_param_max", "get_param_max", PARAM_HUE_VARIATION);
ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "hue_variation_curve", PROPERTY_HINT_RESOURCE_TYPE, "Curve"), "set_param_curve", "get_param_curve", PARAM_HUE_VARIATION);
ADD_GROUP("Animation", "anim_");
- ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "anim_speed", PROPERTY_HINT_RANGE, "0,128,0.01,or_greater"), "set_param", "get_param", PARAM_ANIM_SPEED);
- ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "anim_speed_random", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_param_randomness", "get_param_randomness", PARAM_ANIM_SPEED);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "anim_speed_min", PROPERTY_HINT_RANGE, "0,128,0.01,or_greater,or_lesser"), "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_lesser"), "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", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_param", "get_param", PARAM_ANIM_OFFSET);
- ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "anim_offset_random", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_param_randomness", "get_param_randomness", PARAM_ANIM_OFFSET);
+ 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::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);
@@ -1434,9 +1634,11 @@ void CPUParticles3D::_bind_methods() {
BIND_ENUM_CONSTANT(EMISSION_SHAPE_POINT);
BIND_ENUM_CONSTANT(EMISSION_SHAPE_SPHERE);
+ BIND_ENUM_CONSTANT(EMISSION_SHAPE_SPHERE_SURFACE);
BIND_ENUM_CONSTANT(EMISSION_SHAPE_BOX);
BIND_ENUM_CONSTANT(EMISSION_SHAPE_POINTS);
BIND_ENUM_CONSTANT(EMISSION_SHAPE_DIRECTED_POINTS);
+ BIND_ENUM_CONSTANT(EMISSION_SHAPE_RING);
BIND_ENUM_CONSTANT(EMISSION_SHAPE_MAX);
}
@@ -1450,28 +1652,40 @@ CPUParticles3D::CPUParticles3D() {
set_emitting(true);
set_amount(8);
- set_param(PARAM_INITIAL_LINEAR_VELOCITY, 0);
- set_param(PARAM_ANGULAR_VELOCITY, 0);
- set_param(PARAM_ORBIT_VELOCITY, 0);
- set_param(PARAM_LINEAR_ACCEL, 0);
- set_param(PARAM_RADIAL_ACCEL, 0);
- set_param(PARAM_TANGENTIAL_ACCEL, 0);
- set_param(PARAM_DAMPING, 0);
- set_param(PARAM_ANGLE, 0);
- set_param(PARAM_SCALE, 1);
- set_param(PARAM_HUE_VARIATION, 0);
- set_param(PARAM_ANIM_SPEED, 0);
- set_param(PARAM_ANIM_OFFSET, 0);
+ set_param_min(PARAM_INITIAL_LINEAR_VELOCITY, 0);
+ set_param_min(PARAM_ANGULAR_VELOCITY, 0);
+ set_param_min(PARAM_ORBIT_VELOCITY, 0);
+ set_param_min(PARAM_LINEAR_ACCEL, 0);
+ set_param_min(PARAM_RADIAL_ACCEL, 0);
+ set_param_min(PARAM_TANGENTIAL_ACCEL, 0);
+ set_param_min(PARAM_DAMPING, 0);
+ set_param_min(PARAM_ANGLE, 0);
+ set_param_min(PARAM_SCALE, 1);
+ set_param_min(PARAM_HUE_VARIATION, 0);
+ set_param_min(PARAM_ANIM_SPEED, 0);
+ set_param_min(PARAM_ANIM_OFFSET, 0);
+ set_param_max(PARAM_INITIAL_LINEAR_VELOCITY, 0);
+ set_param_max(PARAM_ANGULAR_VELOCITY, 0);
+ set_param_max(PARAM_ORBIT_VELOCITY, 0);
+ set_param_max(PARAM_LINEAR_ACCEL, 0);
+ set_param_max(PARAM_RADIAL_ACCEL, 0);
+ set_param_max(PARAM_TANGENTIAL_ACCEL, 0);
+ set_param_max(PARAM_DAMPING, 0);
+ set_param_max(PARAM_ANGLE, 0);
+ set_param_max(PARAM_SCALE, 1);
+ set_param_max(PARAM_HUE_VARIATION, 0);
+ set_param_max(PARAM_ANIM_SPEED, 0);
+ set_param_max(PARAM_ANIM_OFFSET, 0);
set_emission_shape(EMISSION_SHAPE_POINT);
set_emission_sphere_radius(1);
set_emission_box_extents(Vector3(1, 1, 1));
+ set_emission_ring_axis(Vector3(0, 0, 1.0));
+ set_emission_ring_height(1);
+ set_emission_ring_radius(1);
+ set_emission_ring_inner_radius(0);
set_gravity(Vector3(0, -9.8, 0));
- for (int i = 0; i < PARAM_MAX; i++) {
- set_param_randomness(Parameter(i), 0);
- }
-
for (int i = 0; i < PARTICLE_FLAG_MAX; i++) {
particle_flags[i] = false;
}
diff --git a/scene/3d/cpu_particles_3d.h b/scene/3d/cpu_particles_3d.h
index c073c93c47..7f225ee98d 100644
--- a/scene/3d/cpu_particles_3d.h
+++ b/scene/3d/cpu_particles_3d.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -31,8 +31,6 @@
#ifndef CPU_PARTICLES_H
#define CPU_PARTICLES_H
-#include "core/templates/rid.h"
-#include "core/templates/safe_refcount.h"
#include "scene/3d/visual_instance_3d.h"
class CPUParticles3D : public GeometryInstance3D {
@@ -73,9 +71,11 @@ public:
enum EmissionShape {
EMISSION_SHAPE_POINT,
EMISSION_SHAPE_SPHERE,
+ EMISSION_SHAPE_SPHERE_SURFACE,
EMISSION_SHAPE_BOX,
EMISSION_SHAPE_POINTS,
EMISSION_SHAPE_DIRECTED_POINTS,
+ EMISSION_SHAPE_RING,
EMISSION_SHAPE_MAX
};
@@ -83,25 +83,26 @@ private:
bool emitting = false;
struct Particle {
- Transform transform;
+ Transform3D transform;
Color color;
- float custom[4] = {};
+ real_t custom[4] = {};
Vector3 velocity;
bool active = false;
- float angle_rand = 0.0;
- float scale_rand = 0.0;
- float hue_rot_rand = 0.0;
- float anim_offset_rand = 0.0;
- float time = 0.0;
- float lifetime = 0.0;
+ real_t angle_rand = 0.0;
+ real_t scale_rand = 0.0;
+ real_t hue_rot_rand = 0.0;
+ real_t anim_offset_rand = 0.0;
+ Color start_color_rand;
+ double time = 0.0;
+ double lifetime = 0.0;
Color base_color;
uint32_t seed = 0;
};
- float time = 0.0;
- float inactive_time = 0.0;
- float frame_remainder = 0.0;
+ double time = 0.0;
+ double inactive_time = 0.0;
+ double frame_remainder = 0.0;
int cycle = 0;
bool redraw = false;
@@ -131,17 +132,17 @@ private:
bool one_shot = false;
- float lifetime = 1.0;
- float pre_process_time = 0.0;
- float explosiveness_ratio = 0.0;
- float randomness_ratio = 0.0;
- float lifetime_randomness = 0.0;
- float speed_scale = 1.0;
+ double lifetime = 1.0;
+ double pre_process_time = 0.0;
+ real_t explosiveness_ratio = 0.0;
+ real_t randomness_ratio = 0.0;
+ double lifetime_randomness = 0.0;
+ double speed_scale = 1.0;
bool local_coords = true;
int fixed_fps = 0;
bool fractional_delta = true;
- Transform inv_emission_transform;
+ Transform3D inv_emission_transform;
SafeFlag can_update;
@@ -152,30 +153,40 @@ private:
////////
Vector3 direction = Vector3(1, 0, 0);
- float spread = 45.0;
- float flatness = 0.0;
+ real_t spread = 45.0;
+ real_t flatness = 0.0;
- float parameters[PARAM_MAX];
- float randomness[PARAM_MAX] = {};
+ real_t parameters_min[PARAM_MAX];
+ real_t parameters_max[PARAM_MAX] = {};
Ref<Curve> curve_parameters[PARAM_MAX];
Color color = Color(1, 1, 1, 1);
Ref<Gradient> color_ramp;
+ Ref<Gradient> color_initial_ramp;
bool particle_flags[PARTICLE_FLAG_MAX] = {};
EmissionShape emission_shape = EMISSION_SHAPE_POINT;
- float emission_sphere_radius = 1.0;
+ real_t emission_sphere_radius = 1.0;
Vector3 emission_box_extents = Vector3(1, 1, 1);
Vector<Vector3> emission_points;
Vector<Vector3> emission_normals;
Vector<Color> emission_colors;
int emission_point_count = 0;
+ Vector3 emission_ring_axis;
+ real_t emission_ring_height = 0.0;
+ real_t emission_ring_radius = 0.0;
+ real_t emission_ring_inner_radius = 0.0;
+
+ Ref<Curve> scale_curve_x;
+ Ref<Curve> scale_curve_y;
+ Ref<Curve> scale_curve_z;
+ bool split_scale = false;
Vector3 gravity = Vector3(0, -9.8, 0);
void _update_internal();
- void _particles_process(float p_delta);
+ void _particles_process(double p_delta);
void _update_particle_data_buffer();
Mutex update_mutex;
@@ -191,31 +202,28 @@ protected:
public:
AABB get_aabb() const override;
- Vector<Face3> get_faces(uint32_t p_usage_flags) const override;
void set_emitting(bool p_emitting);
void set_amount(int p_amount);
- void set_lifetime(float p_lifetime);
+ void set_lifetime(double p_lifetime);
void set_one_shot(bool p_one_shot);
- void set_pre_process_time(float p_time);
- void set_explosiveness_ratio(float p_ratio);
- void set_randomness_ratio(float p_ratio);
- void set_lifetime_randomness(float p_random);
- void set_visibility_aabb(const AABB &p_aabb);
+ void set_pre_process_time(double p_time);
+ void set_explosiveness_ratio(real_t p_ratio);
+ void set_randomness_ratio(real_t p_ratio);
+ void set_lifetime_randomness(double p_random);
void set_use_local_coordinates(bool p_enable);
- void set_speed_scale(float p_scale);
+ void set_speed_scale(double p_scale);
bool is_emitting() const;
int get_amount() const;
- float get_lifetime() const;
+ double get_lifetime() const;
bool get_one_shot() const;
- float get_pre_process_time() const;
- float get_explosiveness_ratio() const;
- float get_randomness_ratio() const;
- float get_lifetime_randomness() const;
- AABB get_visibility_aabb() const;
+ double get_pre_process_time() const;
+ real_t get_explosiveness_ratio() const;
+ real_t get_randomness_ratio() const;
+ double get_lifetime_randomness() const;
bool get_use_local_coordinates() const;
- float get_speed_scale() const;
+ double get_speed_scale() const;
void set_fixed_fps(int p_count);
int get_fixed_fps() const;
@@ -226,9 +234,6 @@ public:
void set_draw_order(DrawOrder p_order);
DrawOrder get_draw_order() const;
- void set_draw_passes(int p_count);
- int get_draw_passes() const;
-
void set_mesh(const Ref<Mesh> &p_mesh);
Ref<Mesh> get_mesh() const;
@@ -237,17 +242,17 @@ public:
void set_direction(Vector3 p_direction);
Vector3 get_direction() const;
- void set_spread(float p_spread);
- float get_spread() const;
+ void set_spread(real_t p_spread);
+ real_t get_spread() const;
- void set_flatness(float p_flatness);
- float get_flatness() const;
+ void set_flatness(real_t p_flatness);
+ real_t get_flatness() const;
- void set_param(Parameter p_param, float p_value);
- float get_param(Parameter p_param) const;
+ void set_param_min(Parameter p_param, real_t p_value);
+ real_t get_param_min(Parameter p_param) const;
- void set_param_randomness(Parameter p_param, float p_value);
- float get_param_randomness(Parameter p_param) const;
+ void set_param_max(Parameter p_param, real_t p_value);
+ real_t get_param_max(Parameter p_param) const;
void set_param_curve(Parameter p_param, const Ref<Curve> &p_curve);
Ref<Curve> get_param_curve(Parameter p_param) const;
@@ -258,24 +263,41 @@ public:
void set_color_ramp(const Ref<Gradient> &p_ramp);
Ref<Gradient> get_color_ramp() const;
+ void set_color_initial_ramp(const Ref<Gradient> &p_ramp);
+ Ref<Gradient> get_color_initial_ramp() const;
+
void set_particle_flag(ParticleFlags p_particle_flag, bool p_enable);
bool get_particle_flag(ParticleFlags p_particle_flag) const;
void set_emission_shape(EmissionShape p_shape);
- void set_emission_sphere_radius(float p_radius);
+ void set_emission_sphere_radius(real_t p_radius);
void set_emission_box_extents(Vector3 p_extents);
void set_emission_points(const Vector<Vector3> &p_points);
void set_emission_normals(const Vector<Vector3> &p_normals);
void set_emission_colors(const Vector<Color> &p_colors);
- void set_emission_point_count(int p_count);
+ void set_emission_ring_axis(Vector3 p_axis);
+ void set_emission_ring_height(real_t p_height);
+ void set_emission_ring_radius(real_t p_radius);
+ void set_emission_ring_inner_radius(real_t p_radius);
+ void set_scale_curve_x(Ref<Curve> p_scale_curve);
+ void set_scale_curve_y(Ref<Curve> p_scale_curve);
+ void set_scale_curve_z(Ref<Curve> p_scale_curve);
+ void set_split_scale(bool p_split_scale);
EmissionShape get_emission_shape() const;
- float get_emission_sphere_radius() const;
+ real_t get_emission_sphere_radius() const;
Vector3 get_emission_box_extents() const;
Vector<Vector3> get_emission_points() const;
Vector<Vector3> get_emission_normals() const;
Vector<Color> get_emission_colors() const;
- int get_emission_point_count() const;
+ Vector3 get_emission_ring_axis() const;
+ real_t get_emission_ring_height() const;
+ real_t get_emission_ring_radius() const;
+ real_t get_emission_ring_inner_radius() const;
+ Ref<Curve> get_scale_curve_x() const;
+ Ref<Curve> get_scale_curve_y() const;
+ Ref<Curve> get_scale_curve_z() const;
+ bool get_split_scale();
void set_gravity(const Vector3 &p_gravity);
Vector3 get_gravity() const;
diff --git a/scene/3d/decal.cpp b/scene/3d/decal.cpp
index 7d6abe458a..a50f75f127 100644
--- a/scene/3d/decal.cpp
+++ b/scene/3d/decal.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -33,7 +33,7 @@
void Decal::set_extents(const Vector3 &p_extents) {
extents = p_extents;
RS::get_singleton()->decal_set_extents(decal, p_extents);
- update_gizmo();
+ update_gizmos();
}
Vector3 Decal::get_extents() const {
@@ -45,6 +45,7 @@ void Decal::set_texture(DecalTexture p_type, const Ref<Texture2D> &p_texture) {
textures[p_type] = p_texture;
RID texture_rid = p_texture.is_valid() ? p_texture->get_rid() : RID();
RS::get_singleton()->decal_set_texture(decal, RS::DecalTexture(p_type), texture_rid);
+ update_configuration_warnings();
}
Ref<Texture2D> Decal::get_texture(DecalTexture p_type) const {
@@ -52,48 +53,48 @@ Ref<Texture2D> Decal::get_texture(DecalTexture p_type) const {
return textures[p_type];
}
-void Decal::set_emission_energy(float p_energy) {
+void Decal::set_emission_energy(real_t p_energy) {
emission_energy = p_energy;
RS::get_singleton()->decal_set_emission_energy(decal, emission_energy);
}
-float Decal::get_emission_energy() const {
+real_t Decal::get_emission_energy() const {
return emission_energy;
}
-void Decal::set_albedo_mix(float p_mix) {
+void Decal::set_albedo_mix(real_t p_mix) {
albedo_mix = p_mix;
RS::get_singleton()->decal_set_albedo_mix(decal, albedo_mix);
}
-float Decal::get_albedo_mix() const {
+real_t Decal::get_albedo_mix() const {
return albedo_mix;
}
-void Decal::set_upper_fade(float p_fade) {
+void Decal::set_upper_fade(real_t p_fade) {
upper_fade = p_fade;
RS::get_singleton()->decal_set_fade(decal, upper_fade, lower_fade);
}
-float Decal::get_upper_fade() const {
+real_t Decal::get_upper_fade() const {
return upper_fade;
}
-void Decal::set_lower_fade(float p_fade) {
+void Decal::set_lower_fade(real_t p_fade) {
lower_fade = p_fade;
RS::get_singleton()->decal_set_fade(decal, upper_fade, lower_fade);
}
-float Decal::get_lower_fade() const {
+real_t Decal::get_lower_fade() const {
return lower_fade;
}
-void Decal::set_normal_fade(float p_fade) {
+void Decal::set_normal_fade(real_t p_fade) {
normal_fade = p_fade;
RS::get_singleton()->decal_set_normal_fade(decal, normal_fade);
}
-float Decal::get_normal_fade() const {
+real_t Decal::get_normal_fade() const {
return normal_fade;
}
@@ -116,27 +117,28 @@ bool Decal::is_distance_fade_enabled() const {
return distance_fade_enabled;
}
-void Decal::set_distance_fade_begin(float p_distance) {
+void Decal::set_distance_fade_begin(real_t p_distance) {
distance_fade_begin = p_distance;
RS::get_singleton()->decal_set_distance_fade(decal, distance_fade_enabled, distance_fade_begin, distance_fade_length);
}
-float Decal::get_distance_fade_begin() const {
+real_t Decal::get_distance_fade_begin() const {
return distance_fade_begin;
}
-void Decal::set_distance_fade_length(float p_length) {
+void Decal::set_distance_fade_length(real_t p_length) {
distance_fade_length = p_length;
RS::get_singleton()->decal_set_distance_fade(decal, distance_fade_enabled, distance_fade_begin, distance_fade_length);
}
-float Decal::get_distance_fade_length() const {
+real_t Decal::get_distance_fade_length() const {
return distance_fade_length;
}
void Decal::set_cull_mask(uint32_t p_layers) {
cull_mask = p_layers;
RS::get_singleton()->decal_set_cull_mask(decal, cull_mask);
+ update_configuration_warnings();
}
uint32_t Decal::get_cull_mask() const {
@@ -150,14 +152,29 @@ AABB Decal::get_aabb() const {
return aabb;
}
-Vector<Face3> Decal::get_faces(uint32_t p_usage_flags) const {
- return Vector<Face3>();
-}
-
void Decal::_validate_property(PropertyInfo &property) const {
if (!distance_fade_enabled && (property.name == "distance_fade_begin" || property.name == "distance_fade_length")) {
- property.usage = PROPERTY_USAGE_NOEDITOR;
+ property.usage = PROPERTY_USAGE_NO_EDITOR;
+ }
+ VisualInstance3D::_validate_property(property);
+}
+
+TypedArray<String> Decal::get_configuration_warnings() const {
+ TypedArray<String> warnings = Node::get_configuration_warnings();
+
+ if (textures[TEXTURE_ALBEDO].is_null() && textures[TEXTURE_NORMAL].is_null() && textures[TEXTURE_ORM].is_null() && textures[TEXTURE_EMISSION].is_null()) {
+ warnings.push_back(RTR("The decal has no textures loaded into any of its texture properties, and will therefore not be visible."));
}
+
+ if ((textures[TEXTURE_NORMAL].is_valid() || textures[TEXTURE_ORM].is_valid()) && textures[TEXTURE_ALBEDO].is_null()) {
+ warnings.push_back(RTR("The decal has a Normal and/or ORM texture, but no Albedo texture is set.\nAn Albedo texture with an alpha channel is required to blend the normal/ORM maps onto the underlying surface.\nIf you don't want the Albedo texture to be visible, set Albedo Mix to 0."));
+ }
+
+ if (cull_mask == 0) {
+ warnings.push_back(RTR("The decal's Cull Mask has no bits enabled, which means the decal will not paint objects on any layer.\nTo resolve this, enable at least one bit in the Cull Mask property."));
+ }
+
+ return warnings;
}
void Decal::_bind_methods() {
@@ -207,7 +224,9 @@ void Decal::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "emission_energy", PROPERTY_HINT_RANGE, "0,128,0.01"), "set_emission_energy", "get_emission_energy");
ADD_PROPERTY(PropertyInfo(Variant::COLOR, "modulate"), "set_modulate", "get_modulate");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "albedo_mix", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_albedo_mix", "get_albedo_mix");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "normal_fade", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_normal_fade", "get_normal_fade");
+ // A Normal Fade of 1.0 causes the decal to be invisible even if fully perpendicular to a surface.
+ // Due to this, limit Normal Fade to 0.999.
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "normal_fade", PROPERTY_HINT_RANGE, "0,0.999,0.001"), "set_normal_fade", "get_normal_fade");
ADD_GROUP("Vertical Fade", "");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "upper_fade", PROPERTY_HINT_EXP_EASING, "attenuation"), "set_upper_fade", "get_upper_fade");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "lower_fade", PROPERTY_HINT_EXP_EASING, "attenuation"), "set_lower_fade", "get_lower_fade");
diff --git a/scene/3d/decal.h b/scene/3d/decal.h
index ce19e76de1..d5990272c6 100644
--- a/scene/3d/decal.h
+++ b/scene/3d/decal.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -32,8 +32,6 @@
#define DECAL_H
#include "scene/3d/visual_instance_3d.h"
-#include "scene/resources/texture.h"
-#include "servers/rendering_server.h"
class Decal : public VisualInstance3D {
GDCLASS(Decal, VisualInstance3D);
@@ -51,60 +49,61 @@ private:
RID decal;
Vector3 extents = Vector3(1, 1, 1);
Ref<Texture2D> textures[TEXTURE_MAX];
- float emission_energy = 1.0;
- float albedo_mix = 1.0;
+ real_t emission_energy = 1.0;
+ real_t albedo_mix = 1.0;
Color modulate = Color(1, 1, 1, 1);
uint32_t cull_mask = (1 << 20) - 1;
- float normal_fade = 0.0;
- float upper_fade = 0.3;
- float lower_fade = 0.3;
+ real_t normal_fade = 0.0;
+ real_t upper_fade = 0.3;
+ real_t lower_fade = 0.3;
bool distance_fade_enabled = false;
- float distance_fade_begin = 10.0;
- float distance_fade_length = 1.0;
+ real_t distance_fade_begin = 10.0;
+ real_t distance_fade_length = 1.0;
protected:
static void _bind_methods();
void _validate_property(PropertyInfo &property) const override;
public:
+ virtual TypedArray<String> get_configuration_warnings() const override;
+
void set_extents(const Vector3 &p_extents);
Vector3 get_extents() const;
void set_texture(DecalTexture p_type, const Ref<Texture2D> &p_texture);
Ref<Texture2D> get_texture(DecalTexture p_type) const;
- void set_emission_energy(float p_energy);
- float get_emission_energy() const;
+ void set_emission_energy(real_t p_energy);
+ real_t get_emission_energy() const;
- void set_albedo_mix(float p_mix);
- float get_albedo_mix() const;
+ void set_albedo_mix(real_t p_mix);
+ real_t get_albedo_mix() const;
void set_modulate(Color p_modulate);
Color get_modulate() const;
- void set_upper_fade(float p_energy);
- float get_upper_fade() const;
+ void set_upper_fade(real_t p_energy);
+ real_t get_upper_fade() const;
- void set_lower_fade(float p_fade);
- float get_lower_fade() const;
+ void set_lower_fade(real_t p_fade);
+ real_t get_lower_fade() const;
- void set_normal_fade(float p_fade);
- float get_normal_fade() const;
+ void set_normal_fade(real_t p_fade);
+ real_t get_normal_fade() const;
void set_enable_distance_fade(bool p_enable);
bool is_distance_fade_enabled() const;
- void set_distance_fade_begin(float p_distance);
- float get_distance_fade_begin() const;
+ void set_distance_fade_begin(real_t p_distance);
+ real_t get_distance_fade_begin() const;
- void set_distance_fade_length(float p_length);
- float get_distance_fade_length() const;
+ void set_distance_fade_length(real_t p_length);
+ real_t get_distance_fade_length() const;
void set_cull_mask(uint32_t p_layers);
uint32_t get_cull_mask() const;
virtual AABB get_aabb() const override;
- virtual Vector<Face3> get_faces(uint32_t p_usage_flags) const override;
Decal();
~Decal();
diff --git a/scene/3d/fog_volume.cpp b/scene/3d/fog_volume.cpp
new file mode 100644
index 0000000000..8d05254a25
--- /dev/null
+++ b/scene/3d/fog_volume.cpp
@@ -0,0 +1,122 @@
+/*************************************************************************/
+/* fog_volume.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#include "fog_volume.h"
+
+///////////////////////////
+
+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_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"), "set_extents", "get_extents");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "shape", PROPERTY_HINT_ENUM, "Ellipsoid,Box,World"), "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 &property) const {
+ if (property.name == "extents" && shape == RS::FOG_VOLUME_SHAPE_WORLD) {
+ property.usage = PROPERTY_USAGE_NONE;
+ return;
+ }
+ VisualInstance3D::_validate_property(property);
+}
+
+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);
+ update_gizmos();
+}
+
+Vector3 FogVolume::get_extents() const {
+ return extents;
+}
+
+void FogVolume::set_shape(RS::FogVolumeShape p_type) {
+ shape = p_type;
+ RS::get_singleton()->fog_volume_set_shape(_get_volume(), shape);
+ RS::get_singleton()->instance_set_ignore_culling(get_instance(), shape == RS::FOG_VOLUME_SHAPE_WORLD);
+ update_gizmos();
+ notify_property_list_changed();
+}
+
+RS::FogVolumeShape FogVolume::get_shape() const {
+ return shape;
+}
+
+void FogVolume::set_material(const Ref<Material> &p_material) {
+ material = p_material;
+ RID material_rid;
+ if (material.is_valid()) {
+ material_rid = material->get_rid();
+ }
+ RS::get_singleton()->fog_volume_set_material(_get_volume(), material_rid);
+ update_gizmos();
+}
+
+Ref<Material> FogVolume::get_material() const {
+ return material;
+}
+
+AABB FogVolume::get_aabb() const {
+ if (shape != RS::FOG_VOLUME_SHAPE_WORLD) {
+ return AABB(-extents, extents * 2);
+ }
+ return AABB();
+}
+
+TypedArray<String> FogVolume::get_configuration_warnings() const {
+ TypedArray<String> warnings = Node::get_configuration_warnings();
+
+ Ref<Environment> environment = get_viewport()->find_world_3d()->get_environment();
+
+ if (environment.is_valid() && !environment->is_volumetric_fog_enabled()) {
+ warnings.push_back(("Fog Volumes need volumetric fog to be enabled in the scene's Environment in order to be visible."));
+ }
+
+ return warnings;
+}
+
+FogVolume::FogVolume() {
+ volume = RS::get_singleton()->fog_volume_create();
+ RS::get_singleton()->fog_volume_set_shape(volume, RS::FOG_VOLUME_SHAPE_BOX);
+ set_base(volume);
+}
+
+FogVolume::~FogVolume() {
+ RS::get_singleton()->free(volume);
+}
diff --git a/scene/3d/immediate_geometry_3d.h b/scene/3d/fog_volume.h
index ee4938d9f7..556a92ad3f 100644
--- a/scene/3d/immediate_geometry_3d.h
+++ b/scene/3d/fog_volume.h
@@ -1,12 +1,12 @@
/*************************************************************************/
-/* immediate_geometry_3d.h */
+/* fog_volume.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -28,45 +28,44 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#ifndef IMMEDIATE_GEOMETRY_3D_H
-#define IMMEDIATE_GEOMETRY_3D_H
+#ifndef FOG_VOLUME_H
+#define FOG_VOLUME_H
+#include "core/templates/rid.h"
#include "scene/3d/visual_instance_3d.h"
-#include "scene/resources/mesh.h"
+#include "scene/main/node.h"
+#include "scene/main/viewport.h"
+#include "scene/resources/material.h"
-class ImmediateGeometry3D : public GeometryInstance3D {
- GDCLASS(ImmediateGeometry3D, GeometryInstance3D);
+class FogVolume : public VisualInstance3D {
+ GDCLASS(FogVolume, VisualInstance3D);
- RID im;
- //a list of textures drawn need to be kept, to avoid references
- // in RenderingServer from becoming invalid if the texture is no longer used
- List<Ref<Texture2D>> cached_textures;
- bool empty = true;
- AABB aabb;
+ Vector3 extents = Vector3(1, 1, 1);
+ Ref<Material> material;
+ RS::FogVolumeShape shape = RS::FOG_VOLUME_SHAPE_BOX;
+
+ RID volume;
protected:
+ _FORCE_INLINE_ RID _get_volume() { return volume; }
static void _bind_methods();
+ virtual void _validate_property(PropertyInfo &property) const override;
public:
- void begin(Mesh::PrimitiveType p_primitive, const Ref<Texture2D> &p_texture = Ref<Texture2D>());
- void set_normal(const Vector3 &p_normal);
- void set_tangent(const Plane &p_tangent);
- void set_color(const Color &p_color);
- void set_uv(const Vector2 &p_uv);
- void set_uv2(const Vector2 &p_uv2);
-
- void add_vertex(const Vector3 &p_vertex);
+ void set_extents(const Vector3 &p_extents);
+ Vector3 get_extents() const;
- void end();
- void clear();
+ void set_shape(RS::FogVolumeShape p_type);
+ RS::FogVolumeShape get_shape() const;
- void add_sphere(int p_lats, int p_lons, float p_radius, bool p_add_uv = true);
+ void set_material(const Ref<Material> &p_material);
+ Ref<Material> get_material() const;
virtual AABB get_aabb() const override;
- virtual Vector<Face3> get_faces(uint32_t p_usage_flags) const override;
+ TypedArray<String> get_configuration_warnings() const override;
- ImmediateGeometry3D();
- ~ImmediateGeometry3D();
+ FogVolume();
+ ~FogVolume();
};
-#endif // IMMEDIATE_GEOMETRY_H
+#endif // FOG_VOLUME_H
diff --git a/scene/3d/gpu_particles_3d.cpp b/scene/3d/gpu_particles_3d.cpp
index 50044ddc67..33ce9fc6fe 100644
--- a/scene/3d/gpu_particles_3d.cpp
+++ b/scene/3d/gpu_particles_3d.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -30,19 +30,12 @@
#include "gpu_particles_3d.h"
-#include "core/os/os.h"
#include "scene/resources/particles_material.h"
-#include "servers/rendering_server.h"
-
AABB GPUParticles3D::get_aabb() const {
return AABB();
}
-Vector<Face3> GPUParticles3D::get_faces(uint32_t p_usage_flags) const {
- return Vector<Face3>();
-}
-
void GPUParticles3D::set_emitting(bool p_emitting) {
RS::get_singleton()->particles_set_emitting(particles, p_emitting);
@@ -59,7 +52,7 @@ void GPUParticles3D::set_amount(int p_amount) {
RS::get_singleton()->particles_set_amount(particles, amount);
}
-void GPUParticles3D::set_lifetime(float p_lifetime) {
+void GPUParticles3D::set_lifetime(double p_lifetime) {
ERR_FAIL_COND_MSG(p_lifetime <= 0, "Particles lifetime must be greater than 0.");
lifetime = p_lifetime;
RS::get_singleton()->particles_set_lifetime(particles, lifetime);
@@ -81,17 +74,17 @@ void GPUParticles3D::set_one_shot(bool p_one_shot) {
}
}
-void GPUParticles3D::set_pre_process_time(float p_time) {
+void GPUParticles3D::set_pre_process_time(double p_time) {
pre_process_time = p_time;
RS::get_singleton()->particles_set_pre_process_time(particles, pre_process_time);
}
-void GPUParticles3D::set_explosiveness_ratio(float p_ratio) {
+void GPUParticles3D::set_explosiveness_ratio(real_t p_ratio) {
explosiveness_ratio = p_ratio;
RS::get_singleton()->particles_set_explosiveness_ratio(particles, explosiveness_ratio);
}
-void GPUParticles3D::set_randomness_ratio(float p_ratio) {
+void GPUParticles3D::set_randomness_ratio(real_t p_ratio) {
randomness_ratio = p_ratio;
RS::get_singleton()->particles_set_randomness_ratio(particles, randomness_ratio);
}
@@ -99,7 +92,7 @@ void GPUParticles3D::set_randomness_ratio(float p_ratio) {
void GPUParticles3D::set_visibility_aabb(const AABB &p_aabb) {
visibility_aabb = p_aabb;
RS::get_singleton()->particles_set_custom_aabb(particles, visibility_aabb);
- update_gizmo();
+ update_gizmos();
}
void GPUParticles3D::set_use_local_coordinates(bool p_enable) {
@@ -118,12 +111,12 @@ void GPUParticles3D::set_process_material(const Ref<Material> &p_material) {
update_configuration_warnings();
}
-void GPUParticles3D::set_speed_scale(float p_scale) {
+void GPUParticles3D::set_speed_scale(double p_scale) {
speed_scale = p_scale;
RS::get_singleton()->particles_set_speed_scale(particles, p_scale);
}
-void GPUParticles3D::set_collision_base_size(float p_size) {
+void GPUParticles3D::set_collision_base_size(real_t p_size) {
collision_base_size = p_size;
RS::get_singleton()->particles_set_collision_base_size(particles, p_size);
}
@@ -136,7 +129,7 @@ int GPUParticles3D::get_amount() const {
return amount;
}
-float GPUParticles3D::get_lifetime() const {
+double GPUParticles3D::get_lifetime() const {
return lifetime;
}
@@ -144,15 +137,15 @@ bool GPUParticles3D::get_one_shot() const {
return one_shot;
}
-float GPUParticles3D::get_pre_process_time() const {
+double GPUParticles3D::get_pre_process_time() const {
return pre_process_time;
}
-float GPUParticles3D::get_explosiveness_ratio() const {
+real_t GPUParticles3D::get_explosiveness_ratio() const {
return explosiveness_ratio;
}
-float GPUParticles3D::get_randomness_ratio() const {
+real_t GPUParticles3D::get_randomness_ratio() const {
return randomness_ratio;
}
@@ -168,11 +161,11 @@ Ref<Material> GPUParticles3D::get_process_material() const {
return process_material;
}
-float GPUParticles3D::get_speed_scale() const {
+double GPUParticles3D::get_speed_scale() const {
return speed_scale;
}
-float GPUParticles3D::get_collision_base_size() const {
+real_t GPUParticles3D::get_collision_base_size() const {
return collision_base_size;
}
@@ -181,12 +174,13 @@ void GPUParticles3D::set_draw_order(DrawOrder p_order) {
RS::get_singleton()->particles_set_draw_order(particles, RS::ParticlesDrawOrder(p_order));
}
-void GPUParticles3D::set_enable_trail(bool p_enabled) {
+void GPUParticles3D::set_trail_enabled(bool p_enabled) {
trail_enabled = p_enabled;
RS::get_singleton()->particles_set_trails(particles, trail_enabled, trail_length);
update_configuration_warnings();
}
-void GPUParticles3D::set_trail_length(float p_seconds) {
+
+void GPUParticles3D::set_trail_length(double p_seconds) {
ERR_FAIL_COND(p_seconds < 0.001);
trail_length = p_seconds;
RS::get_singleton()->particles_set_trails(particles, trail_enabled, trail_length);
@@ -195,7 +189,8 @@ void GPUParticles3D::set_trail_length(float p_seconds) {
bool GPUParticles3D::is_trail_enabled() const {
return trail_enabled;
}
-float GPUParticles3D::get_trail_length() const {
+
+double GPUParticles3D::get_trail_length() const {
return trail_length;
}
@@ -278,7 +273,7 @@ TypedArray<String> GPUParticles3D::get_configuration_warnings() const {
TypedArray<String> warnings = Node::get_configuration_warnings();
if (RenderingServer::get_singleton()->is_low_end()) {
- warnings.push_back(TTR("GPU-based particles are not supported by the GLES2 video driver.\nUse the CPUParticles3D node instead. You can use the \"Convert to CPUParticles3D\" option for this purpose."));
+ warnings.push_back(RTR("GPU-based particles are not supported by the OpenGL video driver.\nUse the CPUParticles3D node instead. You can use the \"Convert to CPUParticles3D\" option for this purpose."));
}
bool meshes_found = false;
@@ -305,17 +300,17 @@ TypedArray<String> GPUParticles3D::get_configuration_warnings() const {
}
if (!meshes_found) {
- warnings.push_back(TTR("Nothing is visible because meshes have not been assigned to draw passes."));
+ warnings.push_back(RTR("Nothing is visible because meshes have not been assigned to draw passes."));
}
if (process_material.is_null()) {
- warnings.push_back(TTR("A material to process the particles is not assigned, so no behavior is imprinted."));
+ warnings.push_back(RTR("A material to process the particles is not assigned, so no behavior is imprinted."));
} else {
const ParticlesMaterial *process = Object::cast_to<ParticlesMaterial>(process_material.ptr());
if (!anim_material_found && process &&
- (process->get_param(ParticlesMaterial::PARAM_ANIM_SPEED) != 0.0 || process->get_param(ParticlesMaterial::PARAM_ANIM_OFFSET) != 0.0 ||
+ (process->get_param_max(ParticlesMaterial::PARAM_ANIM_SPEED) != 0.0 || process->get_param_max(ParticlesMaterial::PARAM_ANIM_OFFSET) != 0.0 ||
process->get_param_texture(ParticlesMaterial::PARAM_ANIM_SPEED).is_valid() || process->get_param_texture(ParticlesMaterial::PARAM_ANIM_OFFSET).is_valid())) {
- warnings.push_back(TTR("Particles animation requires the usage of a BaseMaterial3D whose Billboard Mode is set to \"Particle Billboard\"."));
+ warnings.push_back(RTR("Particles animation requires the usage of a BaseMaterial3D whose Billboard Mode is set to \"Particle Billboard\"."));
}
}
@@ -357,15 +352,15 @@ TypedArray<String> GPUParticles3D::get_configuration_warnings() const {
}
if (dp_count && skin.is_valid()) {
- warnings.push_back(TTR("Using Trail meshes with a skin causes Skin to override Trail poses. Suggest removing the Skin."));
+ warnings.push_back(RTR("Using Trail meshes with a skin causes Skin to override Trail poses. Suggest removing the Skin."));
} else if (dp_count == 0 && skin.is_null()) {
- warnings.push_back(TTR("Trails active, but neither Trail meshes or a Skin were found."));
+ warnings.push_back(RTR("Trails active, but neither Trail meshes or a Skin were found."));
} else if (dp_count > 1) {
- warnings.push_back(TTR("Only one Trail mesh is supported. If you want to use more than a single mesh, a Skin is needed (see documentation)."));
+ warnings.push_back(RTR("Only one Trail mesh is supported. If you want to use more than a single mesh, a Skin is needed (see documentation)."));
}
if ((dp_count || !skin.is_null()) && (missing_trails || no_materials)) {
- warnings.push_back(TTR("Trails enabled, but one or more mesh materials are either missing or not set for trails rendering."));
+ warnings.push_back(RTR("Trails enabled, but one or more mesh materials are either missing or not set for trails rendering."));
}
}
@@ -385,13 +380,15 @@ void GPUParticles3D::_validate_property(PropertyInfo &property) const {
if (property.name.begins_with("draw_pass_")) {
int index = property.name.get_slicec('_', 2).to_int() - 1;
if (index >= draw_passes.size()) {
- property.usage = 0;
+ property.usage = PROPERTY_USAGE_NONE;
return;
}
}
+
+ GeometryInstance3D::_validate_property(property);
}
-void GPUParticles3D::emit_particle(const Transform &p_transform, const Vector3 &p_velocity, const Color &p_color, const Color &p_custom, uint32_t p_emit_flags) {
+void GPUParticles3D::emit_particle(const Transform3D &p_transform, const Vector3 &p_velocity, const Color &p_color, const Color &p_custom, uint32_t p_emit_flags) {
RS::get_singleton()->particles_emit(particles, p_transform, p_velocity, p_color, p_custom, p_emit_flags);
}
@@ -422,43 +419,46 @@ NodePath GPUParticles3D::get_sub_emitter() const {
}
void GPUParticles3D::_notification(int p_what) {
- if (p_what == NOTIFICATION_PAUSED || p_what == NOTIFICATION_UNPAUSED) {
- if (can_process()) {
- RS::get_singleton()->particles_set_speed_scale(particles, speed_scale);
- } else {
- RS::get_singleton()->particles_set_speed_scale(particles, 0);
- }
- }
-
- // Use internal process when emitting and one_shot is on so that when
- // the shot ends the editor can properly update
- if (p_what == NOTIFICATION_INTERNAL_PROCESS) {
- if (one_shot && !is_emitting()) {
- notify_property_list_changed();
- set_process_internal(false);
- }
- }
+ switch (p_what) {
+ case NOTIFICATION_PAUSED:
+ case NOTIFICATION_UNPAUSED: {
+ if (can_process()) {
+ RS::get_singleton()->particles_set_speed_scale(particles, speed_scale);
+ } else {
+ RS::get_singleton()->particles_set_speed_scale(particles, 0);
+ }
+ } break;
+
+ // Use internal process when emitting and one_shot is on so that when
+ // the shot ends the editor can properly update.
+ case NOTIFICATION_INTERNAL_PROCESS: {
+ if (one_shot && !is_emitting()) {
+ notify_property_list_changed();
+ set_process_internal(false);
+ }
+ } break;
- if (p_what == NOTIFICATION_ENTER_TREE) {
- if (sub_emitter != NodePath()) {
- _attach_sub_emitter();
- }
- }
+ case NOTIFICATION_ENTER_TREE: {
+ if (sub_emitter != NodePath()) {
+ _attach_sub_emitter();
+ }
+ } break;
- if (p_what == NOTIFICATION_EXIT_TREE) {
- RS::get_singleton()->particles_set_subemitter(particles, RID());
- }
+ case NOTIFICATION_EXIT_TREE: {
+ RS::get_singleton()->particles_set_subemitter(particles, RID());
+ } break;
- if (p_what == NOTIFICATION_VISIBILITY_CHANGED) {
- // make sure particles are updated before rendering occurs if they were active before
- if (is_visible_in_tree() && !RS::get_singleton()->particles_is_inactive(particles)) {
- RS::get_singleton()->particles_request_process(particles);
- }
+ case NOTIFICATION_VISIBILITY_CHANGED: {
+ // Make sure particles are updated before rendering occurs if they were active before.
+ if (is_visible_in_tree() && !RS::get_singleton()->particles_is_inactive(particles)) {
+ RS::get_singleton()->particles_request_process(particles);
+ }
+ } break;
}
}
void GPUParticles3D::_skinning_changed() {
- Vector<Transform> xforms;
+ Vector<Transform3D> xforms;
if (skin.is_valid()) {
xforms.resize(skin->get_bind_count());
for (int i = 0; i < skin->get_bind_count(); i++) {
@@ -470,7 +470,7 @@ void GPUParticles3D::_skinning_changed() {
if (draw_pass.is_valid() && draw_pass->get_builtin_bind_pose_count() > 0) {
xforms.resize(draw_pass->get_builtin_bind_pose_count());
for (int j = 0; j < draw_pass->get_builtin_bind_pose_count(); j++) {
- xforms.write[i] = draw_pass->get_builtin_bind_pose(j);
+ xforms.write[j] = draw_pass->get_builtin_bind_pose(j);
}
break;
}
@@ -485,6 +485,7 @@ void GPUParticles3D::set_skin(const Ref<Skin> &p_skin) {
skin = p_skin;
_skinning_changed();
}
+
Ref<Skin> GPUParticles3D::get_skin() const {
return skin;
}
@@ -552,7 +553,7 @@ void GPUParticles3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("emit_particle", "xform", "velocity", "color", "custom", "flags"), &GPUParticles3D::emit_particle);
- ClassDB::bind_method(D_METHOD("set_enable_trail", "enabled"), &GPUParticles3D::set_enable_trail);
+ ClassDB::bind_method(D_METHOD("set_trail_enabled", "enabled"), &GPUParticles3D::set_trail_enabled);
ClassDB::bind_method(D_METHOD("set_trail_length", "secs"), &GPUParticles3D::set_trail_length);
ClassDB::bind_method(D_METHOD("is_trail_enabled"), &GPUParticles3D::is_trail_enabled);
@@ -562,12 +563,13 @@ void GPUParticles3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_transform_align"), &GPUParticles3D::get_transform_align);
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "emitting"), "set_emitting", "is_emitting");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "amount", PROPERTY_HINT_EXP_RANGE, "1,1000000,1"), "set_amount", "get_amount");
+ ADD_PROPERTY_DEFAULT("emitting", true); // Workaround for doctool in headless mode, as dummy rasterizer always returns false.
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "amount", PROPERTY_HINT_RANGE, "1,1000000,1,exp"), "set_amount", "get_amount");
ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "sub_emitter", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "GPUParticles3D"), "set_sub_emitter", "get_sub_emitter");
ADD_GROUP("Time", "");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "lifetime", PROPERTY_HINT_EXP_RANGE, "0.01,600.0,0.01,or_greater"), "set_lifetime", "get_lifetime");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "lifetime", PROPERTY_HINT_RANGE, "0.01,600.0,0.01,or_greater,exp"), "set_lifetime", "get_lifetime");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "one_shot"), "set_one_shot", "get_one_shot");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "preprocess", PROPERTY_HINT_EXP_RANGE, "0.00,600.0,0.01"), "set_pre_process_time", "get_pre_process_time");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "preprocess", PROPERTY_HINT_RANGE, "0.00,600.0,0.01,exp"), "set_pre_process_time", "get_pre_process_time");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "speed_scale", PROPERTY_HINT_RANGE, "0,64,0.01"), "set_speed_scale", "get_speed_scale");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "explosiveness", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_explosiveness_ratio", "get_explosiveness_ratio");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "randomness", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_randomness_ratio", "get_randomness_ratio");
@@ -579,11 +581,11 @@ void GPUParticles3D::_bind_methods() {
ADD_GROUP("Drawing", "");
ADD_PROPERTY(PropertyInfo(Variant::AABB, "visibility_aabb"), "set_visibility_aabb", "get_visibility_aabb");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "local_coords"), "set_use_local_coordinates", "get_use_local_coordinates");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "draw_order", PROPERTY_HINT_ENUM, "Index,Lifetime,View Depth"), "set_draw_order", "get_draw_order");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "draw_order", PROPERTY_HINT_ENUM, "Index,Lifetime,Reverse Lifetime,View Depth"), "set_draw_order", "get_draw_order");
ADD_PROPERTY(PropertyInfo(Variant::INT, "transform_align", PROPERTY_HINT_ENUM, "Disabled,ZBillboard,YToVelocity,ZBillboardYToVelocity"), "set_transform_align", "get_transform_align");
ADD_GROUP("Trails", "trail_");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL, "trail_enabled"), "set_enable_trail", "is_trail_enabled");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "trail_length_secs", PROPERTY_HINT_RANGE, "0.01,4,0.01"), "set_trail_length", "get_trail_length");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "trail_enabled"), "set_trail_enabled", "is_trail_enabled");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "trail_length_secs", PROPERTY_HINT_RANGE, "0.01,10,0.01"), "set_trail_length", "get_trail_length");
ADD_GROUP("Process Material", "");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "process_material", PROPERTY_HINT_RESOURCE_TYPE, "ShaderMaterial,ParticlesMaterial"), "set_process_material", "get_process_material");
ADD_GROUP("Draw Passes", "draw_");
@@ -595,6 +597,7 @@ void GPUParticles3D::_bind_methods() {
BIND_ENUM_CONSTANT(DRAW_ORDER_INDEX);
BIND_ENUM_CONSTANT(DRAW_ORDER_LIFETIME);
+ BIND_ENUM_CONSTANT(DRAW_ORDER_REVERSE_LIFETIME);
BIND_ENUM_CONSTANT(DRAW_ORDER_VIEW_DEPTH);
BIND_ENUM_CONSTANT(EMIT_FLAG_POSITION);
@@ -632,7 +635,7 @@ GPUParticles3D::GPUParticles3D() {
set_draw_passes(1);
set_draw_order(DRAW_ORDER_INDEX);
set_speed_scale(1);
- set_collision_base_size(0.01);
+ set_collision_base_size(collision_base_size);
set_transform_align(TRANSFORM_ALIGN_DISABLED);
}
diff --git a/scene/3d/gpu_particles_3d.h b/scene/3d/gpu_particles_3d.h
index 1f9cea79b6..adce45a0a9 100644
--- a/scene/3d/gpu_particles_3d.h
+++ b/scene/3d/gpu_particles_3d.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -31,9 +31,7 @@
#ifndef PARTICLES_H
#define PARTICLES_H
-#include "core/templates/rid.h"
#include "scene/3d/visual_instance_3d.h"
-#include "scene/resources/material.h"
#include "scene/resources/skin.h"
class GPUParticles3D : public GeometryInstance3D {
@@ -44,6 +42,7 @@ public:
enum DrawOrder {
DRAW_ORDER_INDEX,
DRAW_ORDER_LIFETIME,
+ DRAW_ORDER_REVERSE_LIFETIME,
DRAW_ORDER_VIEW_DEPTH,
};
@@ -62,22 +61,22 @@ private:
RID particles;
bool one_shot;
- int amount;
- float lifetime;
- float pre_process_time;
- float explosiveness_ratio;
- float randomness_ratio;
- float speed_scale;
+ int amount = 0;
+ double lifetime = 0.0;
+ double pre_process_time = 0.0;
+ real_t explosiveness_ratio = 0.0;
+ real_t randomness_ratio = 0.0;
+ double speed_scale = 0.0;
AABB visibility_aabb;
- bool local_coords;
- int fixed_fps;
- bool fractional_delta;
+ bool local_coords = false;
+ int fixed_fps = 0;
+ bool fractional_delta = false;
bool interpolate = true;
NodePath sub_emitter;
- float collision_base_size;
+ real_t collision_base_size = 0.01;
bool trail_enabled = false;
- float trail_length = 0.3;
+ double trail_length = 0.3;
TransformAlign transform_align = TRANSFORM_ALIGN_DISABLED;
@@ -99,37 +98,36 @@ protected:
public:
AABB get_aabb() const override;
- Vector<Face3> get_faces(uint32_t p_usage_flags) const override;
void set_emitting(bool p_emitting);
void set_amount(int p_amount);
- void set_lifetime(float p_lifetime);
+ void set_lifetime(double p_lifetime);
void set_one_shot(bool p_one_shot);
- void set_pre_process_time(float p_time);
- void set_explosiveness_ratio(float p_ratio);
- void set_randomness_ratio(float p_ratio);
+ void set_pre_process_time(double p_time);
+ void set_explosiveness_ratio(real_t p_ratio);
+ void set_randomness_ratio(real_t p_ratio);
void set_visibility_aabb(const AABB &p_aabb);
void set_use_local_coordinates(bool p_enable);
void set_process_material(const Ref<Material> &p_material);
- void set_speed_scale(float p_scale);
- void set_collision_base_size(float p_ratio);
- void set_enable_trail(bool p_enabled);
- void set_trail_length(float p_seconds);
+ void set_speed_scale(double p_scale);
+ void set_collision_base_size(real_t p_ratio);
+ void set_trail_enabled(bool p_enabled);
+ void set_trail_length(double p_seconds);
bool is_emitting() const;
int get_amount() const;
- float get_lifetime() const;
+ double get_lifetime() const;
bool get_one_shot() const;
- float get_pre_process_time() const;
- float get_explosiveness_ratio() const;
- float get_randomness_ratio() const;
+ double get_pre_process_time() const;
+ real_t get_explosiveness_ratio() const;
+ real_t get_randomness_ratio() const;
AABB get_visibility_aabb() const;
bool get_use_local_coordinates() const;
Ref<Material> get_process_material() const;
- float get_speed_scale() const;
- float get_collision_base_size() const;
+ double get_speed_scale() const;
+ real_t get_collision_base_size() const;
bool is_trail_enabled() const;
- float get_trail_length() const;
+ double get_trail_length() const;
void set_fixed_fps(int p_count);
int get_fixed_fps() const;
@@ -170,7 +168,7 @@ public:
EMIT_FLAG_CUSTOM = RS::PARTICLES_EMIT_FLAG_CUSTOM
};
- void emit_particle(const Transform &p_transform, const Vector3 &p_velocity, const Color &p_color, const Color &p_custom, uint32_t p_emit_flags);
+ void emit_particle(const Transform3D &p_transform, const Vector3 &p_velocity, const Color &p_color, const Color &p_custom, uint32_t p_emit_flags);
AABB capture_aabb() const;
GPUParticles3D();
diff --git a/scene/3d/gpu_particles_collision_3d.cpp b/scene/3d/gpu_particles_collision_3d.cpp
index 2d59461ff0..bedf0edf38 100644
--- a/scene/3d/gpu_particles_collision_3d.cpp
+++ b/scene/3d/gpu_particles_collision_3d.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -30,7 +30,6 @@
#include "gpu_particles_collision_3d.h"
-#include "core/templates/thread_work_pool.h"
#include "mesh_instance_3d.h"
#include "scene/3d/camera_3d.h"
#include "scene/main/viewport.h"
@@ -63,75 +62,75 @@ GPUParticlesCollision3D::~GPUParticlesCollision3D() {
/////////////////////////////////
-void GPUParticlesCollisionSphere::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_radius", "radius"), &GPUParticlesCollisionSphere::set_radius);
- ClassDB::bind_method(D_METHOD("get_radius"), &GPUParticlesCollisionSphere::get_radius);
+void GPUParticlesCollisionSphere3D::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("set_radius", "radius"), &GPUParticlesCollisionSphere3D::set_radius);
+ ClassDB::bind_method(D_METHOD("get_radius"), &GPUParticlesCollisionSphere3D::get_radius);
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "radius", PROPERTY_HINT_RANGE, "0.01,1024,0.01,or_greater"), "set_radius", "get_radius");
}
-void GPUParticlesCollisionSphere::set_radius(float p_radius) {
+void GPUParticlesCollisionSphere3D::set_radius(real_t p_radius) {
radius = p_radius;
RS::get_singleton()->particles_collision_set_sphere_radius(_get_collision(), radius);
- update_gizmo();
+ update_gizmos();
}
-float GPUParticlesCollisionSphere::get_radius() const {
+real_t GPUParticlesCollisionSphere3D::get_radius() const {
return radius;
}
-AABB GPUParticlesCollisionSphere::get_aabb() const {
+AABB GPUParticlesCollisionSphere3D::get_aabb() const {
return AABB(Vector3(-radius, -radius, -radius), Vector3(radius * 2, radius * 2, radius * 2));
}
-GPUParticlesCollisionSphere::GPUParticlesCollisionSphere() :
+GPUParticlesCollisionSphere3D::GPUParticlesCollisionSphere3D() :
GPUParticlesCollision3D(RS::PARTICLES_COLLISION_TYPE_SPHERE_COLLIDE) {
}
-GPUParticlesCollisionSphere::~GPUParticlesCollisionSphere() {
+GPUParticlesCollisionSphere3D::~GPUParticlesCollisionSphere3D() {
}
///////////////////////////
-void GPUParticlesCollisionBox::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_extents", "extents"), &GPUParticlesCollisionBox::set_extents);
- ClassDB::bind_method(D_METHOD("get_extents"), &GPUParticlesCollisionBox::get_extents);
+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);
ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "extents", PROPERTY_HINT_RANGE, "0.01,1024,0.01,or_greater"), "set_extents", "get_extents");
}
-void GPUParticlesCollisionBox::set_extents(const Vector3 &p_extents) {
+void GPUParticlesCollisionBox3D::set_extents(const Vector3 &p_extents) {
extents = p_extents;
RS::get_singleton()->particles_collision_set_box_extents(_get_collision(), extents);
- update_gizmo();
+ update_gizmos();
}
-Vector3 GPUParticlesCollisionBox::get_extents() const {
+Vector3 GPUParticlesCollisionBox3D::get_extents() const {
return extents;
}
-AABB GPUParticlesCollisionBox::get_aabb() const {
+AABB GPUParticlesCollisionBox3D::get_aabb() const {
return AABB(-extents, extents * 2);
}
-GPUParticlesCollisionBox::GPUParticlesCollisionBox() :
+GPUParticlesCollisionBox3D::GPUParticlesCollisionBox3D() :
GPUParticlesCollision3D(RS::PARTICLES_COLLISION_TYPE_BOX_COLLIDE) {
}
-GPUParticlesCollisionBox::~GPUParticlesCollisionBox() {
+GPUParticlesCollisionBox3D::~GPUParticlesCollisionBox3D() {
}
///////////////////////////////
///////////////////////////
-void GPUParticlesCollisionSDF::_find_meshes(const AABB &p_aabb, Node *p_at_node, List<PlotMesh> &plot_meshes) {
+void GPUParticlesCollisionSDF3D::_find_meshes(const AABB &p_aabb, Node *p_at_node, List<PlotMesh> &plot_meshes) {
MeshInstance3D *mi = Object::cast_to<MeshInstance3D>(p_at_node);
if (mi && mi->is_visible_in_tree()) {
Ref<Mesh> mesh = mi->get_mesh();
if (mesh.is_valid()) {
AABB aabb = mesh->get_aabb();
- Transform xf = get_global_transform().affine_inverse() * mi->get_global_transform();
+ Transform3D xf = get_global_transform().affine_inverse() * mi->get_global_transform();
if (p_aabb.intersects(xf.xform(aabb))) {
PlotMesh pm;
@@ -147,7 +146,7 @@ void GPUParticlesCollisionSDF::_find_meshes(const AABB &p_aabb, Node *p_at_node,
if (s->is_visible_in_tree()) {
Array meshes = p_at_node->call("get_meshes");
for (int i = 0; i < meshes.size(); i += 2) {
- Transform mxf = meshes[i];
+ Transform3D mxf = meshes[i];
Ref<Mesh> mesh = meshes[i + 1];
if (!mesh.is_valid()) {
continue;
@@ -155,7 +154,7 @@ void GPUParticlesCollisionSDF::_find_meshes(const AABB &p_aabb, Node *p_at_node,
AABB aabb = mesh->get_aabb();
- Transform xf = get_global_transform().affine_inverse() * (s->get_global_transform() * mxf);
+ Transform3D xf = get_global_transform().affine_inverse() * (s->get_global_transform() * mxf);
if (p_aabb.intersects(xf.xform(aabb))) {
PlotMesh pm;
@@ -173,7 +172,7 @@ void GPUParticlesCollisionSDF::_find_meshes(const AABB &p_aabb, Node *p_at_node,
}
}
-uint32_t GPUParticlesCollisionSDF::_create_bvh(LocalVector<BVH> &bvh_tree, FacePos *p_faces, uint32_t p_face_count, const Face3 *p_triangles, float p_thickness) {
+uint32_t GPUParticlesCollisionSDF3D::_create_bvh(LocalVector<BVH> &bvh_tree, FacePos *p_faces, uint32_t p_face_count, const Face3 *p_triangles, float p_thickness) {
if (p_face_count == 1) {
return BVH::LEAF_BIT | p_faces[0].index;
}
@@ -217,11 +216,11 @@ uint32_t GPUParticlesCollisionSDF::_create_bvh(LocalVector<BVH> &bvh_tree, FaceP
return index;
}
-static _FORCE_INLINE_ float Vector3_dot2(const Vector3 &p_vec3) {
+static _FORCE_INLINE_ real_t Vector3_dot2(const Vector3 &p_vec3) {
return p_vec3.dot(p_vec3);
}
-void GPUParticlesCollisionSDF::_find_closest_distance(const Vector3 &p_pos, const BVH *bvh, uint32_t p_bvh_cell, const Face3 *triangles, float thickness, float &closest_distance) {
+void GPUParticlesCollisionSDF3D::_find_closest_distance(const Vector3 &p_pos, const BVH *bvh, uint32_t p_bvh_cell, const Face3 *triangles, float thickness, float &closest_distance) {
if (p_bvh_cell & BVH::LEAF_BIT) {
p_bvh_cell &= BVH::LEAF_MASK; //remove bit
@@ -257,10 +256,10 @@ void GPUParticlesCollisionSDF::_find_closest_distance(const Vector3 &p_pos, cons
Vector2 pq1 = v1 - e1 * CLAMP(v1.dot(e1) / e1.dot(e1), 0.0, 1.0);
Vector2 pq2 = v2 - e2 * CLAMP(v2.dot(e2) / e2.dot(e2), 0.0, 1.0);
- float s = SGN(e0.x * e2.y - e0.y * e2.x);
+ float s = SIGN(e0.x * e2.y - e0.y * e2.x);
Vector2 d2 = Vector2(pq0.dot(pq0), s * (v0.x * e0.y - v0.y * e0.x)).min(Vector2(pq1.dot(pq1), s * (v1.x * e1.y - v1.y * e1.x))).min(Vector2(pq2.dot(pq2), s * (v2.x * e2.y - v2.y * e2.x)));
- inside_d = -Math::sqrt(d2.x) * SGN(d2.y);
+ inside_d = -Math::sqrt(d2.x) * SIGN(d2.y);
}
//make sure distance to planes is not shorter if inside
@@ -289,15 +288,12 @@ void GPUParticlesCollisionSDF::_find_closest_distance(const Vector3 &p_pos, cons
Vector3 nor = ba.cross(ac);
inside_d = Math::sqrt(
- (SGN(ba.cross(nor).dot(pa)) +
- SGN(cb.cross(nor).dot(pb)) +
- SGN(ac.cross(nor).dot(pc)) <
- 2.0) ?
- MIN(MIN(
- Vector3_dot2(ba * CLAMP(ba.dot(pa) / Vector3_dot2(ba), 0.0, 1.0) - pa),
- Vector3_dot2(cb * CLAMP(cb.dot(pb) / Vector3_dot2(cb), 0.0, 1.0) - pb)),
- Vector3_dot2(ac * CLAMP(ac.dot(pc) / Vector3_dot2(ac), 0.0, 1.0) - pc)) :
- nor.dot(pa) * nor.dot(pa) / Vector3_dot2(nor));
+ (SIGN(ba.cross(nor).dot(pa)) + SIGN(cb.cross(nor).dot(pb)) + SIGN(ac.cross(nor).dot(pc)) < 2.0)
+ ? MIN(MIN(
+ Vector3_dot2(ba * CLAMP(ba.dot(pa) / Vector3_dot2(ba), 0.0, 1.0) - pa),
+ Vector3_dot2(cb * CLAMP(cb.dot(pb) / Vector3_dot2(cb), 0.0, 1.0) - pb)),
+ Vector3_dot2(ac * CLAMP(ac.dot(pc) / Vector3_dot2(ac), 0.0, 1.0) - pc))
+ : nor.dot(pa) * nor.dot(pa) / Vector3_dot2(nor));
closest_distance = MIN(closest_distance, inside_d);
}
@@ -325,7 +321,7 @@ void GPUParticlesCollisionSDF::_find_closest_distance(const Vector3 &p_pos, cons
}
}
-void GPUParticlesCollisionSDF::_compute_sdf_z(uint32_t p_z, ComputeSDFParams *params) {
+void GPUParticlesCollisionSDF3D::_compute_sdf_z(uint32_t p_z, ComputeSDFParams *params) {
int32_t z_ofs = p_z * params->size.y * params->size.x;
for (int32_t y = 0; y < params->size.y; y++) {
int32_t y_ofs = z_ofs + y * params->size.x;
@@ -342,10 +338,10 @@ void GPUParticlesCollisionSDF::_compute_sdf_z(uint32_t p_z, ComputeSDFParams *pa
}
}
-void GPUParticlesCollisionSDF::_compute_sdf(ComputeSDFParams *params) {
+void GPUParticlesCollisionSDF3D::_compute_sdf(ComputeSDFParams *params) {
ThreadWorkPool work_pool;
work_pool.init();
- work_pool.begin_work(params->size.z, this, &GPUParticlesCollisionSDF::_compute_sdf_z, params);
+ work_pool.begin_work(params->size.z, this, &GPUParticlesCollisionSDF3D::_compute_sdf_z, params);
while (!work_pool.is_done_dispatching()) {
OS::get_singleton()->delay_usec(10000);
bake_step_function(work_pool.get_work_index() * 100 / params->size.z, "Baking SDF");
@@ -354,7 +350,7 @@ void GPUParticlesCollisionSDF::_compute_sdf(ComputeSDFParams *params) {
work_pool.finish();
}
-Vector3i GPUParticlesCollisionSDF::get_estimated_cell_size() const {
+Vector3i GPUParticlesCollisionSDF3D::get_estimated_cell_size() const {
static const int subdivs[RESOLUTION_MAX] = { 16, 32, 64, 128, 256, 512 };
int subdiv = subdivs[get_resolution()];
@@ -369,7 +365,7 @@ Vector3i GPUParticlesCollisionSDF::get_estimated_cell_size() const {
return sdf_size;
}
-Ref<Image> GPUParticlesCollisionSDF::bake() {
+Ref<Image> GPUParticlesCollisionSDF3D::bake() {
static const int subdivs[RESOLUTION_MAX] = { 16, 32, 64, 128, 256, 512 };
int subdiv = subdivs[get_resolution()];
@@ -397,9 +393,7 @@ Ref<Image> GPUParticlesCollisionSDF::bake() {
bake_step_function(0, "Finding Meshes");
}
- for (List<PlotMesh>::Element *E = plot_meshes.front(); E; E = E->next()) {
- const PlotMesh &pm = E->get();
-
+ for (const PlotMesh &pm : plot_meshes) {
for (int i = 0; i < pm.mesh->get_surface_count(); i++) {
if (pm.mesh->surface_get_primitive_type(i) != Mesh::PRIMITIVE_TRIANGLES) {
continue; //only triangles
@@ -423,7 +417,7 @@ Ref<Image> GPUParticlesCollisionSDF::bake() {
}
//test against original bounds
- if (!Geometry3D::triangle_box_overlap(aabb.position + aabb.size * 0.5, aabb.size * 0.5, face.vertex)) {
+ if (!Geometry3D::triangle_box_overlap(aabb.get_center(), aabb.size * 0.5, face.vertex)) {
continue;
}
@@ -441,7 +435,7 @@ Ref<Image> GPUParticlesCollisionSDF::bake() {
}
//test against original bounds
- if (!Geometry3D::triangle_box_overlap(aabb.position + aabb.size * 0.5, aabb.size * 0.5, face.vertex)) {
+ if (!Geometry3D::triangle_box_overlap(aabb.get_center(), aabb.size * 0.5, face.vertex)) {
continue;
}
@@ -478,7 +472,7 @@ Ref<Image> GPUParticlesCollisionSDF::bake() {
_create_bvh(bvh, face_pos.ptr(), face_pos.size(), faces.ptr(), th);
Vector<uint8_t> data;
- data.resize(sdf_size.z * sdf_size.y * sdf_size.x * sizeof(float));
+ data.resize(sdf_size.z * sdf_size.y * sdf_size.x * (int)sizeof(float));
if (bake_step_function) {
bake_step_function(0, "Baking SDF");
@@ -495,7 +489,7 @@ Ref<Image> GPUParticlesCollisionSDF::bake() {
_compute_sdf(&params);
Ref<Image> ret;
- ret.instance();
+ ret.instantiate();
ret->create(sdf_size.x, sdf_size.y * sdf_size.z, false, Image::FORMAT_RF, data);
ret->convert(Image::FORMAT_RH); //convert to half, save space
ret->set_meta("depth", sdf_size.z); //hack, make sure to add to the docs of this function
@@ -507,18 +501,18 @@ Ref<Image> GPUParticlesCollisionSDF::bake() {
return ret;
}
-void GPUParticlesCollisionSDF::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_extents", "extents"), &GPUParticlesCollisionSDF::set_extents);
- ClassDB::bind_method(D_METHOD("get_extents"), &GPUParticlesCollisionSDF::get_extents);
+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_resolution", "resolution"), &GPUParticlesCollisionSDF::set_resolution);
- ClassDB::bind_method(D_METHOD("get_resolution"), &GPUParticlesCollisionSDF::get_resolution);
+ ClassDB::bind_method(D_METHOD("set_resolution", "resolution"), &GPUParticlesCollisionSDF3D::set_resolution);
+ ClassDB::bind_method(D_METHOD("get_resolution"), &GPUParticlesCollisionSDF3D::get_resolution);
- ClassDB::bind_method(D_METHOD("set_texture", "texture"), &GPUParticlesCollisionSDF::set_texture);
- ClassDB::bind_method(D_METHOD("get_texture"), &GPUParticlesCollisionSDF::get_texture);
+ ClassDB::bind_method(D_METHOD("set_texture", "texture"), &GPUParticlesCollisionSDF3D::set_texture);
+ ClassDB::bind_method(D_METHOD("get_texture"), &GPUParticlesCollisionSDF3D::get_texture);
- ClassDB::bind_method(D_METHOD("set_thickness", "thickness"), &GPUParticlesCollisionSDF::set_thickness);
- ClassDB::bind_method(D_METHOD("get_thickness"), &GPUParticlesCollisionSDF::get_thickness);
+ ClassDB::bind_method(D_METHOD("set_thickness", "thickness"), &GPUParticlesCollisionSDF3D::set_thickness);
+ ClassDB::bind_method(D_METHOD("get_thickness"), &GPUParticlesCollisionSDF3D::get_thickness);
ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "extents", PROPERTY_HINT_RANGE, "0.01,1024,0.01,or_greater"), "set_extents", "get_extents");
ADD_PROPERTY(PropertyInfo(Variant::INT, "resolution", PROPERTY_HINT_ENUM, "16,32,64,128,256,512"), "set_resolution", "get_resolution");
@@ -534,121 +528,123 @@ void GPUParticlesCollisionSDF::_bind_methods() {
BIND_ENUM_CONSTANT(RESOLUTION_MAX);
}
-void GPUParticlesCollisionSDF::set_thickness(float p_thickness) {
+void GPUParticlesCollisionSDF3D::set_thickness(float p_thickness) {
thickness = p_thickness;
}
-float GPUParticlesCollisionSDF::get_thickness() const {
+float GPUParticlesCollisionSDF3D::get_thickness() const {
return thickness;
}
-void GPUParticlesCollisionSDF::set_extents(const Vector3 &p_extents) {
+void GPUParticlesCollisionSDF3D::set_extents(const Vector3 &p_extents) {
extents = p_extents;
RS::get_singleton()->particles_collision_set_box_extents(_get_collision(), extents);
- update_gizmo();
+ update_gizmos();
}
-Vector3 GPUParticlesCollisionSDF::get_extents() const {
+Vector3 GPUParticlesCollisionSDF3D::get_extents() const {
return extents;
}
-void GPUParticlesCollisionSDF::set_resolution(Resolution p_resolution) {
+void GPUParticlesCollisionSDF3D::set_resolution(Resolution p_resolution) {
resolution = p_resolution;
- update_gizmo();
+ update_gizmos();
}
-GPUParticlesCollisionSDF::Resolution GPUParticlesCollisionSDF::get_resolution() const {
+GPUParticlesCollisionSDF3D::Resolution GPUParticlesCollisionSDF3D::get_resolution() const {
return resolution;
}
-void GPUParticlesCollisionSDF::set_texture(const Ref<Texture3D> &p_texture) {
+void GPUParticlesCollisionSDF3D::set_texture(const Ref<Texture3D> &p_texture) {
texture = p_texture;
RID tex = texture.is_valid() ? texture->get_rid() : RID();
RS::get_singleton()->particles_collision_set_field_texture(_get_collision(), tex);
}
-Ref<Texture3D> GPUParticlesCollisionSDF::get_texture() const {
+Ref<Texture3D> GPUParticlesCollisionSDF3D::get_texture() const {
return texture;
}
-AABB GPUParticlesCollisionSDF::get_aabb() const {
+AABB GPUParticlesCollisionSDF3D::get_aabb() const {
return AABB(-extents, extents * 2);
}
-GPUParticlesCollisionSDF::BakeBeginFunc GPUParticlesCollisionSDF::bake_begin_function = nullptr;
-GPUParticlesCollisionSDF::BakeStepFunc GPUParticlesCollisionSDF::bake_step_function = nullptr;
-GPUParticlesCollisionSDF::BakeEndFunc GPUParticlesCollisionSDF::bake_end_function = nullptr;
+GPUParticlesCollisionSDF3D::BakeBeginFunc GPUParticlesCollisionSDF3D::bake_begin_function = nullptr;
+GPUParticlesCollisionSDF3D::BakeStepFunc GPUParticlesCollisionSDF3D::bake_step_function = nullptr;
+GPUParticlesCollisionSDF3D::BakeEndFunc GPUParticlesCollisionSDF3D::bake_end_function = nullptr;
-GPUParticlesCollisionSDF::GPUParticlesCollisionSDF() :
+GPUParticlesCollisionSDF3D::GPUParticlesCollisionSDF3D() :
GPUParticlesCollision3D(RS::PARTICLES_COLLISION_TYPE_SDF_COLLIDE) {
}
-GPUParticlesCollisionSDF::~GPUParticlesCollisionSDF() {
+GPUParticlesCollisionSDF3D::~GPUParticlesCollisionSDF3D() {
}
////////////////////////////
////////////////////////////
-void GPUParticlesCollisionHeightField::_notification(int p_what) {
- if (p_what == NOTIFICATION_INTERNAL_PROCESS) {
- if (update_mode == UPDATE_MODE_ALWAYS) {
- RS::get_singleton()->particles_collision_height_field_update(_get_collision());
- }
+void GPUParticlesCollisionHeightField3D::_notification(int p_what) {
+ switch (p_what) {
+ case NOTIFICATION_INTERNAL_PROCESS: {
+ if (update_mode == UPDATE_MODE_ALWAYS) {
+ RS::get_singleton()->particles_collision_height_field_update(_get_collision());
+ }
- if (follow_camera_mode && get_viewport()) {
- Camera3D *cam = get_viewport()->get_camera();
- if (cam) {
- Transform xform = get_global_transform();
- Vector3 x_axis = xform.basis.get_axis(Vector3::AXIS_X).normalized();
- Vector3 z_axis = xform.basis.get_axis(Vector3::AXIS_Z).normalized();
- float x_len = xform.basis.get_scale().x;
- float z_len = xform.basis.get_scale().z;
+ if (follow_camera_mode && get_viewport()) {
+ Camera3D *cam = get_viewport()->get_camera_3d();
+ if (cam) {
+ Transform3D xform = get_global_transform();
+ Vector3 x_axis = xform.basis.get_column(Vector3::AXIS_X).normalized();
+ Vector3 z_axis = xform.basis.get_column(Vector3::AXIS_Z).normalized();
+ float x_len = xform.basis.get_scale().x;
+ float z_len = xform.basis.get_scale().z;
- Vector3 cam_pos = cam->get_global_transform().origin;
- Transform new_xform = xform;
+ Vector3 cam_pos = cam->get_global_transform().origin;
+ Transform3D new_xform = xform;
- while (x_axis.dot(cam_pos - new_xform.origin) > x_len) {
- new_xform.origin += x_axis * x_len;
- }
- while (x_axis.dot(cam_pos - new_xform.origin) < -x_len) {
- new_xform.origin -= x_axis * x_len;
- }
+ while (x_axis.dot(cam_pos - new_xform.origin) > x_len) {
+ new_xform.origin += x_axis * x_len;
+ }
+ while (x_axis.dot(cam_pos - new_xform.origin) < -x_len) {
+ new_xform.origin -= x_axis * x_len;
+ }
- while (z_axis.dot(cam_pos - new_xform.origin) > z_len) {
- new_xform.origin += z_axis * z_len;
- }
- while (z_axis.dot(cam_pos - new_xform.origin) < -z_len) {
- new_xform.origin -= z_axis * z_len;
- }
+ while (z_axis.dot(cam_pos - new_xform.origin) > z_len) {
+ new_xform.origin += z_axis * z_len;
+ }
+ while (z_axis.dot(cam_pos - new_xform.origin) < -z_len) {
+ new_xform.origin -= z_axis * z_len;
+ }
- if (new_xform != xform) {
- set_global_transform(new_xform);
- RS::get_singleton()->particles_collision_height_field_update(_get_collision());
+ if (new_xform != xform) {
+ set_global_transform(new_xform);
+ RS::get_singleton()->particles_collision_height_field_update(_get_collision());
+ }
}
}
- }
- }
+ } break;
- if (p_what == NOTIFICATION_TRANSFORM_CHANGED) {
- RS::get_singleton()->particles_collision_height_field_update(_get_collision());
+ case NOTIFICATION_TRANSFORM_CHANGED: {
+ RS::get_singleton()->particles_collision_height_field_update(_get_collision());
+ } break;
}
}
-void GPUParticlesCollisionHeightField::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_extents", "extents"), &GPUParticlesCollisionHeightField::set_extents);
- ClassDB::bind_method(D_METHOD("get_extents"), &GPUParticlesCollisionHeightField::get_extents);
+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_resolution", "resolution"), &GPUParticlesCollisionHeightField::set_resolution);
- ClassDB::bind_method(D_METHOD("get_resolution"), &GPUParticlesCollisionHeightField::get_resolution);
+ ClassDB::bind_method(D_METHOD("set_resolution", "resolution"), &GPUParticlesCollisionHeightField3D::set_resolution);
+ ClassDB::bind_method(D_METHOD("get_resolution"), &GPUParticlesCollisionHeightField3D::get_resolution);
- ClassDB::bind_method(D_METHOD("set_update_mode", "update_mode"), &GPUParticlesCollisionHeightField::set_update_mode);
- ClassDB::bind_method(D_METHOD("get_update_mode"), &GPUParticlesCollisionHeightField::get_update_mode);
+ ClassDB::bind_method(D_METHOD("set_update_mode", "update_mode"), &GPUParticlesCollisionHeightField3D::set_update_mode);
+ ClassDB::bind_method(D_METHOD("get_update_mode"), &GPUParticlesCollisionHeightField3D::get_update_mode);
- ClassDB::bind_method(D_METHOD("set_follow_camera_mode", "enabled"), &GPUParticlesCollisionHeightField::set_follow_camera_mode);
- ClassDB::bind_method(D_METHOD("is_follow_camera_mode_enabled"), &GPUParticlesCollisionHeightField::is_follow_camera_mode_enabled);
+ ClassDB::bind_method(D_METHOD("set_follow_camera_mode", "enabled"), &GPUParticlesCollisionHeightField3D::set_follow_camera_mode);
+ ClassDB::bind_method(D_METHOD("is_follow_camera_mode_enabled"), &GPUParticlesCollisionHeightField3D::is_follow_camera_mode_enabled);
- ClassDB::bind_method(D_METHOD("set_follow_camera_push_ratio", "ratio"), &GPUParticlesCollisionHeightField::set_follow_camera_push_ratio);
- ClassDB::bind_method(D_METHOD("get_follow_camera_push_ratio"), &GPUParticlesCollisionHeightField::get_follow_camera_push_ratio);
+ ClassDB::bind_method(D_METHOD("set_follow_camera_push_ratio", "ratio"), &GPUParticlesCollisionHeightField3D::set_follow_camera_push_ratio);
+ ClassDB::bind_method(D_METHOD("get_follow_camera_push_ratio"), &GPUParticlesCollisionHeightField3D::get_follow_camera_push_ratio);
ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "extents", PROPERTY_HINT_RANGE, "0.01,1024,0.01,or_greater"), "set_extents", "get_extents");
ADD_PROPERTY(PropertyInfo(Variant::INT, "resolution", PROPERTY_HINT_ENUM, "256,512,1024,2048,4096,8192"), "set_resolution", "get_resolution");
@@ -669,63 +665,63 @@ void GPUParticlesCollisionHeightField::_bind_methods() {
BIND_ENUM_CONSTANT(UPDATE_MODE_ALWAYS);
}
-void GPUParticlesCollisionHeightField::set_follow_camera_push_ratio(float p_follow_camera_push_ratio) {
+void GPUParticlesCollisionHeightField3D::set_follow_camera_push_ratio(float p_follow_camera_push_ratio) {
follow_camera_push_ratio = p_follow_camera_push_ratio;
}
-float GPUParticlesCollisionHeightField::get_follow_camera_push_ratio() const {
+float GPUParticlesCollisionHeightField3D::get_follow_camera_push_ratio() const {
return follow_camera_push_ratio;
}
-void GPUParticlesCollisionHeightField::set_extents(const Vector3 &p_extents) {
+void GPUParticlesCollisionHeightField3D::set_extents(const Vector3 &p_extents) {
extents = p_extents;
RS::get_singleton()->particles_collision_set_box_extents(_get_collision(), extents);
- update_gizmo();
+ update_gizmos();
RS::get_singleton()->particles_collision_height_field_update(_get_collision());
}
-Vector3 GPUParticlesCollisionHeightField::get_extents() const {
+Vector3 GPUParticlesCollisionHeightField3D::get_extents() const {
return extents;
}
-void GPUParticlesCollisionHeightField::set_resolution(Resolution p_resolution) {
+void GPUParticlesCollisionHeightField3D::set_resolution(Resolution p_resolution) {
resolution = p_resolution;
RS::get_singleton()->particles_collision_set_height_field_resolution(_get_collision(), RS::ParticlesCollisionHeightfieldResolution(resolution));
- update_gizmo();
+ update_gizmos();
RS::get_singleton()->particles_collision_height_field_update(_get_collision());
}
-GPUParticlesCollisionHeightField::Resolution GPUParticlesCollisionHeightField::get_resolution() const {
+GPUParticlesCollisionHeightField3D::Resolution GPUParticlesCollisionHeightField3D::get_resolution() const {
return resolution;
}
-void GPUParticlesCollisionHeightField::set_update_mode(UpdateMode p_update_mode) {
+void GPUParticlesCollisionHeightField3D::set_update_mode(UpdateMode p_update_mode) {
update_mode = p_update_mode;
set_process_internal(follow_camera_mode || update_mode == UPDATE_MODE_ALWAYS);
}
-GPUParticlesCollisionHeightField::UpdateMode GPUParticlesCollisionHeightField::get_update_mode() const {
+GPUParticlesCollisionHeightField3D::UpdateMode GPUParticlesCollisionHeightField3D::get_update_mode() const {
return update_mode;
}
-void GPUParticlesCollisionHeightField::set_follow_camera_mode(bool p_enabled) {
+void GPUParticlesCollisionHeightField3D::set_follow_camera_mode(bool p_enabled) {
follow_camera_mode = p_enabled;
set_process_internal(follow_camera_mode || update_mode == UPDATE_MODE_ALWAYS);
}
-bool GPUParticlesCollisionHeightField::is_follow_camera_mode_enabled() const {
+bool GPUParticlesCollisionHeightField3D::is_follow_camera_mode_enabled() const {
return follow_camera_mode;
}
-AABB GPUParticlesCollisionHeightField::get_aabb() const {
+AABB GPUParticlesCollisionHeightField3D::get_aabb() const {
return AABB(-extents, extents * 2);
}
-GPUParticlesCollisionHeightField::GPUParticlesCollisionHeightField() :
+GPUParticlesCollisionHeightField3D::GPUParticlesCollisionHeightField3D() :
GPUParticlesCollision3D(RS::PARTICLES_COLLISION_TYPE_HEIGHTFIELD_COLLIDE) {
}
-GPUParticlesCollisionHeightField::~GPUParticlesCollisionHeightField() {
+GPUParticlesCollisionHeightField3D::~GPUParticlesCollisionHeightField3D() {
}
////////////////////////////
@@ -740,31 +736,31 @@ uint32_t GPUParticlesAttractor3D::get_cull_mask() const {
return cull_mask;
}
-void GPUParticlesAttractor3D::set_strength(float p_strength) {
+void GPUParticlesAttractor3D::set_strength(real_t p_strength) {
strength = p_strength;
RS::get_singleton()->particles_collision_set_attractor_strength(collision, p_strength);
}
-float GPUParticlesAttractor3D::get_strength() const {
+real_t GPUParticlesAttractor3D::get_strength() const {
return strength;
}
-void GPUParticlesAttractor3D::set_attenuation(float p_attenuation) {
+void GPUParticlesAttractor3D::set_attenuation(real_t p_attenuation) {
attenuation = p_attenuation;
RS::get_singleton()->particles_collision_set_attractor_attenuation(collision, p_attenuation);
}
-float GPUParticlesAttractor3D::get_attenuation() const {
+real_t GPUParticlesAttractor3D::get_attenuation() const {
return attenuation;
}
-void GPUParticlesAttractor3D::set_directionality(float p_directionality) {
+void GPUParticlesAttractor3D::set_directionality(real_t p_directionality) {
directionality = p_directionality;
RS::get_singleton()->particles_collision_set_attractor_directionality(collision, p_directionality);
- update_gizmo();
+ update_gizmos();
}
-float GPUParticlesAttractor3D::get_directionality() const {
+real_t GPUParticlesAttractor3D::get_directionality() const {
return directionality;
}
@@ -798,104 +794,104 @@ GPUParticlesAttractor3D::~GPUParticlesAttractor3D() {
/////////////////////////////////
-void GPUParticlesAttractorSphere::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_radius", "radius"), &GPUParticlesAttractorSphere::set_radius);
- ClassDB::bind_method(D_METHOD("get_radius"), &GPUParticlesAttractorSphere::get_radius);
+void GPUParticlesAttractorSphere3D::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("set_radius", "radius"), &GPUParticlesAttractorSphere3D::set_radius);
+ ClassDB::bind_method(D_METHOD("get_radius"), &GPUParticlesAttractorSphere3D::get_radius);
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "radius", PROPERTY_HINT_RANGE, "0.01,1024,0.01,or_greater"), "set_radius", "get_radius");
}
-void GPUParticlesAttractorSphere::set_radius(float p_radius) {
+void GPUParticlesAttractorSphere3D::set_radius(real_t p_radius) {
radius = p_radius;
RS::get_singleton()->particles_collision_set_sphere_radius(_get_collision(), radius);
- update_gizmo();
+ update_gizmos();
}
-float GPUParticlesAttractorSphere::get_radius() const {
+real_t GPUParticlesAttractorSphere3D::get_radius() const {
return radius;
}
-AABB GPUParticlesAttractorSphere::get_aabb() const {
+AABB GPUParticlesAttractorSphere3D::get_aabb() const {
return AABB(Vector3(-radius, -radius, -radius), Vector3(radius * 2, radius * 2, radius * 2));
}
-GPUParticlesAttractorSphere::GPUParticlesAttractorSphere() :
+GPUParticlesAttractorSphere3D::GPUParticlesAttractorSphere3D() :
GPUParticlesAttractor3D(RS::PARTICLES_COLLISION_TYPE_SPHERE_ATTRACT) {
}
-GPUParticlesAttractorSphere::~GPUParticlesAttractorSphere() {
+GPUParticlesAttractorSphere3D::~GPUParticlesAttractorSphere3D() {
}
///////////////////////////
-void GPUParticlesAttractorBox::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_extents", "extents"), &GPUParticlesAttractorBox::set_extents);
- ClassDB::bind_method(D_METHOD("get_extents"), &GPUParticlesAttractorBox::get_extents);
+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);
ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "extents", PROPERTY_HINT_RANGE, "0.01,1024,0.01,or_greater"), "set_extents", "get_extents");
}
-void GPUParticlesAttractorBox::set_extents(const Vector3 &p_extents) {
+void GPUParticlesAttractorBox3D::set_extents(const Vector3 &p_extents) {
extents = p_extents;
RS::get_singleton()->particles_collision_set_box_extents(_get_collision(), extents);
- update_gizmo();
+ update_gizmos();
}
-Vector3 GPUParticlesAttractorBox::get_extents() const {
+Vector3 GPUParticlesAttractorBox3D::get_extents() const {
return extents;
}
-AABB GPUParticlesAttractorBox::get_aabb() const {
+AABB GPUParticlesAttractorBox3D::get_aabb() const {
return AABB(-extents, extents * 2);
}
-GPUParticlesAttractorBox::GPUParticlesAttractorBox() :
+GPUParticlesAttractorBox3D::GPUParticlesAttractorBox3D() :
GPUParticlesAttractor3D(RS::PARTICLES_COLLISION_TYPE_BOX_ATTRACT) {
}
-GPUParticlesAttractorBox::~GPUParticlesAttractorBox() {
+GPUParticlesAttractorBox3D::~GPUParticlesAttractorBox3D() {
}
///////////////////////////
-void GPUParticlesAttractorVectorField::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_extents", "extents"), &GPUParticlesAttractorVectorField::set_extents);
- ClassDB::bind_method(D_METHOD("get_extents"), &GPUParticlesAttractorVectorField::get_extents);
+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_texture", "texture"), &GPUParticlesAttractorVectorField::set_texture);
- ClassDB::bind_method(D_METHOD("get_texture"), &GPUParticlesAttractorVectorField::get_texture);
+ 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"), "set_extents", "get_extents");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture3D"), "set_texture", "get_texture");
}
-void GPUParticlesAttractorVectorField::set_extents(const Vector3 &p_extents) {
+void GPUParticlesAttractorVectorField3D::set_extents(const Vector3 &p_extents) {
extents = p_extents;
RS::get_singleton()->particles_collision_set_box_extents(_get_collision(), extents);
- update_gizmo();
+ update_gizmos();
}
-Vector3 GPUParticlesAttractorVectorField::get_extents() const {
+Vector3 GPUParticlesAttractorVectorField3D::get_extents() const {
return extents;
}
-void GPUParticlesAttractorVectorField::set_texture(const Ref<Texture3D> &p_texture) {
+void GPUParticlesAttractorVectorField3D::set_texture(const Ref<Texture3D> &p_texture) {
texture = p_texture;
RID tex = texture.is_valid() ? texture->get_rid() : RID();
RS::get_singleton()->particles_collision_set_field_texture(_get_collision(), tex);
}
-Ref<Texture3D> GPUParticlesAttractorVectorField::get_texture() const {
+Ref<Texture3D> GPUParticlesAttractorVectorField3D::get_texture() const {
return texture;
}
-AABB GPUParticlesAttractorVectorField::get_aabb() const {
+AABB GPUParticlesAttractorVectorField3D::get_aabb() const {
return AABB(-extents, extents * 2);
}
-GPUParticlesAttractorVectorField::GPUParticlesAttractorVectorField() :
+GPUParticlesAttractorVectorField3D::GPUParticlesAttractorVectorField3D() :
GPUParticlesAttractor3D(RS::PARTICLES_COLLISION_TYPE_VECTOR_FIELD_ATTRACT) {
}
-GPUParticlesAttractorVectorField::~GPUParticlesAttractorVectorField() {
+GPUParticlesAttractorVectorField3D::~GPUParticlesAttractorVectorField3D() {
}
diff --git a/scene/3d/gpu_particles_collision_3d.h b/scene/3d/gpu_particles_collision_3d.h
index 81c33663f3..fdd2fa4b18 100644
--- a/scene/3d/gpu_particles_collision_3d.h
+++ b/scene/3d/gpu_particles_collision_3d.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -32,9 +32,7 @@
#define GPU_PARTICLES_COLLISION_3D_H
#include "core/templates/local_vector.h"
-#include "core/templates/rid.h"
#include "scene/3d/visual_instance_3d.h"
-#include "scene/resources/material.h"
class GPUParticlesCollision3D : public VisualInstance3D {
GDCLASS(GPUParticlesCollision3D, VisualInstance3D);
@@ -52,31 +50,29 @@ public:
void set_cull_mask(uint32_t p_cull_mask);
uint32_t get_cull_mask() const;
- virtual Vector<Face3> get_faces(uint32_t p_usage_flags) const override { return Vector<Face3>(); }
-
~GPUParticlesCollision3D();
};
-class GPUParticlesCollisionSphere : public GPUParticlesCollision3D {
- GDCLASS(GPUParticlesCollisionSphere, GPUParticlesCollision3D);
+class GPUParticlesCollisionSphere3D : public GPUParticlesCollision3D {
+ GDCLASS(GPUParticlesCollisionSphere3D, GPUParticlesCollision3D);
- float radius = 1.0;
+ real_t radius = 1.0;
protected:
static void _bind_methods();
public:
- void set_radius(float p_radius);
- float get_radius() const;
+ void set_radius(real_t p_radius);
+ real_t get_radius() const;
virtual AABB get_aabb() const override;
- GPUParticlesCollisionSphere();
- ~GPUParticlesCollisionSphere();
+ GPUParticlesCollisionSphere3D();
+ ~GPUParticlesCollisionSphere3D();
};
-class GPUParticlesCollisionBox : public GPUParticlesCollision3D {
- GDCLASS(GPUParticlesCollisionBox, GPUParticlesCollision3D);
+class GPUParticlesCollisionBox3D : public GPUParticlesCollision3D {
+ GDCLASS(GPUParticlesCollisionBox3D, GPUParticlesCollision3D);
Vector3 extents = Vector3(1, 1, 1);
@@ -89,12 +85,12 @@ public:
virtual AABB get_aabb() const override;
- GPUParticlesCollisionBox();
- ~GPUParticlesCollisionBox();
+ GPUParticlesCollisionBox3D();
+ ~GPUParticlesCollisionBox3D();
};
-class GPUParticlesCollisionSDF : public GPUParticlesCollision3D {
- GDCLASS(GPUParticlesCollisionSDF, GPUParticlesCollision3D);
+class GPUParticlesCollisionSDF3D : public GPUParticlesCollision3D {
+ GDCLASS(GPUParticlesCollisionSDF3D, GPUParticlesCollision3D);
public:
enum Resolution {
@@ -119,7 +115,7 @@ private:
struct PlotMesh {
Ref<Mesh> mesh;
- Transform local_xform;
+ Transform3D local_xform;
};
void _find_meshes(const AABB &p_aabb, Node *p_at_node, List<PlotMesh> &plot_meshes);
@@ -186,14 +182,14 @@ public:
static BakeStepFunc bake_step_function;
static BakeEndFunc bake_end_function;
- GPUParticlesCollisionSDF();
- ~GPUParticlesCollisionSDF();
+ GPUParticlesCollisionSDF3D();
+ ~GPUParticlesCollisionSDF3D();
};
-VARIANT_ENUM_CAST(GPUParticlesCollisionSDF::Resolution)
+VARIANT_ENUM_CAST(GPUParticlesCollisionSDF3D::Resolution)
-class GPUParticlesCollisionHeightField : public GPUParticlesCollision3D {
- GDCLASS(GPUParticlesCollisionHeightField, GPUParticlesCollision3D);
+class GPUParticlesCollisionHeightField3D : public GPUParticlesCollision3D {
+ GDCLASS(GPUParticlesCollisionHeightField3D, GPUParticlesCollision3D);
public:
enum Resolution {
@@ -241,21 +237,21 @@ public:
virtual AABB get_aabb() const override;
- GPUParticlesCollisionHeightField();
- ~GPUParticlesCollisionHeightField();
+ GPUParticlesCollisionHeightField3D();
+ ~GPUParticlesCollisionHeightField3D();
};
-VARIANT_ENUM_CAST(GPUParticlesCollisionHeightField::Resolution)
-VARIANT_ENUM_CAST(GPUParticlesCollisionHeightField::UpdateMode)
+VARIANT_ENUM_CAST(GPUParticlesCollisionHeightField3D::Resolution)
+VARIANT_ENUM_CAST(GPUParticlesCollisionHeightField3D::UpdateMode)
class GPUParticlesAttractor3D : public VisualInstance3D {
GDCLASS(GPUParticlesAttractor3D, VisualInstance3D);
uint32_t cull_mask = 0xFFFFFFFF;
RID collision;
- float strength = 1.0;
- float attenuation = 1.0;
- float directionality = 0.0;
+ real_t strength = 1.0;
+ real_t attenuation = 1.0;
+ real_t directionality = 0.0;
protected:
_FORCE_INLINE_ RID _get_collision() { return collision; }
@@ -267,40 +263,38 @@ public:
void set_cull_mask(uint32_t p_cull_mask);
uint32_t get_cull_mask() const;
- void set_strength(float p_strength);
- float get_strength() const;
-
- void set_attenuation(float p_attenuation);
- float get_attenuation() const;
+ void set_strength(real_t p_strength);
+ real_t get_strength() const;
- void set_directionality(float p_directionality);
- float get_directionality() const;
+ void set_attenuation(real_t p_attenuation);
+ real_t get_attenuation() const;
- virtual Vector<Face3> get_faces(uint32_t p_usage_flags) const override { return Vector<Face3>(); }
+ void set_directionality(real_t p_directionality);
+ real_t get_directionality() const;
~GPUParticlesAttractor3D();
};
-class GPUParticlesAttractorSphere : public GPUParticlesAttractor3D {
- GDCLASS(GPUParticlesAttractorSphere, GPUParticlesAttractor3D);
+class GPUParticlesAttractorSphere3D : public GPUParticlesAttractor3D {
+ GDCLASS(GPUParticlesAttractorSphere3D, GPUParticlesAttractor3D);
- float radius = 1.0;
+ real_t radius = 1.0;
protected:
static void _bind_methods();
public:
- void set_radius(float p_radius);
- float get_radius() const;
+ void set_radius(real_t p_radius);
+ real_t get_radius() const;
virtual AABB get_aabb() const override;
- GPUParticlesAttractorSphere();
- ~GPUParticlesAttractorSphere();
+ GPUParticlesAttractorSphere3D();
+ ~GPUParticlesAttractorSphere3D();
};
-class GPUParticlesAttractorBox : public GPUParticlesAttractor3D {
- GDCLASS(GPUParticlesAttractorBox, GPUParticlesAttractor3D);
+class GPUParticlesAttractorBox3D : public GPUParticlesAttractor3D {
+ GDCLASS(GPUParticlesAttractorBox3D, GPUParticlesAttractor3D);
Vector3 extents = Vector3(1, 1, 1);
@@ -313,12 +307,12 @@ public:
virtual AABB get_aabb() const override;
- GPUParticlesAttractorBox();
- ~GPUParticlesAttractorBox();
+ GPUParticlesAttractorBox3D();
+ ~GPUParticlesAttractorBox3D();
};
-class GPUParticlesAttractorVectorField : public GPUParticlesAttractor3D {
- GDCLASS(GPUParticlesAttractorVectorField, GPUParticlesAttractor3D);
+class GPUParticlesAttractorVectorField3D : public GPUParticlesAttractor3D {
+ GDCLASS(GPUParticlesAttractorVectorField3D, GPUParticlesAttractor3D);
Vector3 extents = Vector3(1, 1, 1);
Ref<Texture3D> texture;
@@ -335,8 +329,8 @@ public:
virtual AABB get_aabb() const override;
- GPUParticlesAttractorVectorField();
- ~GPUParticlesAttractorVectorField();
+ GPUParticlesAttractorVectorField3D();
+ ~GPUParticlesAttractorVectorField3D();
};
#endif // GPU_PARTICLES_COLLISION_3D_H
diff --git a/scene/3d/immediate_geometry_3d.cpp b/scene/3d/immediate_geometry_3d.cpp
deleted file mode 100644
index d64babaa9d..0000000000
--- a/scene/3d/immediate_geometry_3d.cpp
+++ /dev/null
@@ -1,157 +0,0 @@
-/*************************************************************************/
-/* immediate_geometry_3d.cpp */
-/*************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
-/* */
-/* Permission is hereby granted, free of charge, to any person obtaining */
-/* a copy of this software and associated documentation files (the */
-/* "Software"), to deal in the Software without restriction, including */
-/* without limitation the rights to use, copy, modify, merge, publish, */
-/* distribute, sublicense, and/or sell copies of the Software, and to */
-/* permit persons to whom the Software is furnished to do so, subject to */
-/* the following conditions: */
-/* */
-/* The above copyright notice and this permission notice shall be */
-/* included in all copies or substantial portions of the Software. */
-/* */
-/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
-/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
-/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
-/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
-/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
-/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
-/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
-/*************************************************************************/
-
-#include "immediate_geometry_3d.h"
-
-void ImmediateGeometry3D::begin(Mesh::PrimitiveType p_primitive, const Ref<Texture2D> &p_texture) {
- RS::get_singleton()->immediate_begin(im, (RS::PrimitiveType)p_primitive, p_texture.is_valid() ? p_texture->get_rid() : RID());
- if (p_texture.is_valid()) {
- cached_textures.push_back(p_texture);
- }
-}
-
-void ImmediateGeometry3D::set_normal(const Vector3 &p_normal) {
- RS::get_singleton()->immediate_normal(im, p_normal);
-}
-
-void ImmediateGeometry3D::set_tangent(const Plane &p_tangent) {
- RS::get_singleton()->immediate_tangent(im, p_tangent);
-}
-
-void ImmediateGeometry3D::set_color(const Color &p_color) {
- RS::get_singleton()->immediate_color(im, p_color);
-}
-
-void ImmediateGeometry3D::set_uv(const Vector2 &p_uv) {
- RS::get_singleton()->immediate_uv(im, p_uv);
-}
-
-void ImmediateGeometry3D::set_uv2(const Vector2 &p_uv2) {
- RS::get_singleton()->immediate_uv2(im, p_uv2);
-}
-
-void ImmediateGeometry3D::add_vertex(const Vector3 &p_vertex) {
- RS::get_singleton()->immediate_vertex(im, p_vertex);
- if (empty) {
- aabb.position = p_vertex;
- aabb.size = Vector3();
- empty = false;
- } else {
- aabb.expand_to(p_vertex);
- }
-}
-
-void ImmediateGeometry3D::end() {
- RS::get_singleton()->immediate_end(im);
-}
-
-void ImmediateGeometry3D::clear() {
- RS::get_singleton()->immediate_clear(im);
- empty = true;
- cached_textures.clear();
-}
-
-AABB ImmediateGeometry3D::get_aabb() const {
- return aabb;
-}
-
-Vector<Face3> ImmediateGeometry3D::get_faces(uint32_t p_usage_flags) const {
- return Vector<Face3>();
-}
-
-void ImmediateGeometry3D::add_sphere(int p_lats, int p_lons, float p_radius, bool p_add_uv) {
- const double lat_step = Math_TAU / p_lats;
- const double lon_step = Math_TAU / p_lons;
-
- for (int i = 1; i <= p_lats; i++) {
- double lat0 = lat_step * (i - 1) - Math_TAU / 4;
- double z0 = Math::sin(lat0);
- double zr0 = Math::cos(lat0);
-
- double lat1 = lat_step * i - Math_TAU / 4;
- double z1 = Math::sin(lat1);
- double zr1 = Math::cos(lat1);
-
- for (int j = p_lons; j >= 1; j--) {
- double lng0 = lon_step * (j - 1);
- double x0 = Math::cos(lng0);
- double y0 = Math::sin(lng0);
-
- double lng1 = lon_step * j;
- double x1 = Math::cos(lng1);
- double y1 = Math::sin(lng1);
-
- Vector3 v[4] = {
- Vector3(x1 * zr0, z0, y1 * zr0),
- Vector3(x1 * zr1, z1, y1 * zr1),
- Vector3(x0 * zr1, z1, y0 * zr1),
- Vector3(x0 * zr0, z0, y0 * zr0)
- };
-
-#define ADD_POINT(m_idx) \
- if (p_add_uv) { \
- set_uv(Vector2(Math::atan2(v[m_idx].x, v[m_idx].z) / Math_PI * 0.5 + 0.5, v[m_idx].y * 0.5 + 0.5)); \
- set_tangent(Plane(Vector3(-v[m_idx].z, v[m_idx].y, v[m_idx].x), 1)); \
- } \
- set_normal(v[m_idx]); \
- add_vertex(v[m_idx] * p_radius);
-
- ADD_POINT(0);
- ADD_POINT(1);
- ADD_POINT(2);
-
- ADD_POINT(2);
- ADD_POINT(3);
- ADD_POINT(0);
- }
- }
-}
-
-void ImmediateGeometry3D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("begin", "primitive", "texture"), &ImmediateGeometry3D::begin, DEFVAL(Ref<Texture2D>()));
- ClassDB::bind_method(D_METHOD("set_normal", "normal"), &ImmediateGeometry3D::set_normal);
- ClassDB::bind_method(D_METHOD("set_tangent", "tangent"), &ImmediateGeometry3D::set_tangent);
- ClassDB::bind_method(D_METHOD("set_color", "color"), &ImmediateGeometry3D::set_color);
- ClassDB::bind_method(D_METHOD("set_uv", "uv"), &ImmediateGeometry3D::set_uv);
- ClassDB::bind_method(D_METHOD("set_uv2", "uv"), &ImmediateGeometry3D::set_uv2);
- ClassDB::bind_method(D_METHOD("add_vertex", "position"), &ImmediateGeometry3D::add_vertex);
- ClassDB::bind_method(D_METHOD("add_sphere", "lats", "lons", "radius", "add_uv"), &ImmediateGeometry3D::add_sphere, DEFVAL(true));
- ClassDB::bind_method(D_METHOD("end"), &ImmediateGeometry3D::end);
- ClassDB::bind_method(D_METHOD("clear"), &ImmediateGeometry3D::clear);
-}
-
-ImmediateGeometry3D::ImmediateGeometry3D() {
- im = RenderingServer::get_singleton()->immediate_create();
- set_base(im);
-}
-
-ImmediateGeometry3D::~ImmediateGeometry3D() {
- RenderingServer::get_singleton()->free(im);
-}
diff --git a/scene/3d/importer_mesh_instance_3d.cpp b/scene/3d/importer_mesh_instance_3d.cpp
new file mode 100644
index 0000000000..7cd6a81532
--- /dev/null
+++ b/scene/3d/importer_mesh_instance_3d.cpp
@@ -0,0 +1,85 @@
+/*************************************************************************/
+/* importer_mesh_instance_3d.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#include "importer_mesh_instance_3d.h"
+
+#include "scene/resources/importer_mesh.h"
+
+void ImporterMeshInstance3D::set_mesh(const Ref<ImporterMesh> &p_mesh) {
+ mesh = p_mesh;
+}
+Ref<ImporterMesh> ImporterMeshInstance3D::get_mesh() const {
+ return mesh;
+}
+
+void ImporterMeshInstance3D::set_skin(const Ref<Skin> &p_skin) {
+ skin = p_skin;
+}
+Ref<Skin> ImporterMeshInstance3D::get_skin() const {
+ return skin;
+}
+
+void ImporterMeshInstance3D::set_surface_material(int p_idx, const Ref<Material> &p_material) {
+ ERR_FAIL_COND(p_idx < 0);
+ if (p_idx >= surface_materials.size()) {
+ surface_materials.resize(p_idx + 1);
+ }
+
+ surface_materials.write[p_idx] = p_material;
+}
+Ref<Material> ImporterMeshInstance3D::get_surface_material(int p_idx) const {
+ ERR_FAIL_COND_V(p_idx < 0, Ref<Material>());
+ if (p_idx >= surface_materials.size()) {
+ return Ref<Material>();
+ }
+ return surface_materials[p_idx];
+}
+
+void ImporterMeshInstance3D::set_skeleton_path(const NodePath &p_path) {
+ skeleton_path = p_path;
+}
+NodePath ImporterMeshInstance3D::get_skeleton_path() const {
+ return skeleton_path;
+}
+
+void ImporterMeshInstance3D::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("set_mesh", "mesh"), &ImporterMeshInstance3D::set_mesh);
+ ClassDB::bind_method(D_METHOD("get_mesh"), &ImporterMeshInstance3D::get_mesh);
+
+ ClassDB::bind_method(D_METHOD("set_skin", "skin"), &ImporterMeshInstance3D::set_skin);
+ ClassDB::bind_method(D_METHOD("get_skin"), &ImporterMeshInstance3D::get_skin);
+
+ ClassDB::bind_method(D_METHOD("set_skeleton_path", "skeleton_path"), &ImporterMeshInstance3D::set_skeleton_path);
+ ClassDB::bind_method(D_METHOD("get_skeleton_path"), &ImporterMeshInstance3D::get_skeleton_path);
+
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "mesh", PROPERTY_HINT_RESOURCE_TYPE, "ImporterMesh"), "set_mesh", "get_mesh");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "skin", PROPERTY_HINT_RESOURCE_TYPE, "Skin"), "set_skin", "get_skin");
+ ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "skeleton_path", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "Skeleton"), "set_skeleton_path", "get_skeleton_path");
+}
diff --git a/scene/3d/proximity_group_3d.h b/scene/3d/importer_mesh_instance_3d.h
index 05aa00b228..3daf06771d 100644
--- a/scene/3d/proximity_group_3d.h
+++ b/scene/3d/importer_mesh_instance_3d.h
@@ -1,12 +1,12 @@
/*************************************************************************/
-/* proximity_group_3d.h */
+/* importer_mesh_instance_3d.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -28,58 +28,37 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#ifndef PROXIMITY_GROUP_H
-#define PROXIMITY_GROUP_H
+#ifndef SCENE_IMPORTER_MESH_INSTANCE_3D_H
+#define SCENE_IMPORTER_MESH_INSTANCE_3D_H
-#include "node_3d.h"
+#include "scene/3d/node_3d.h"
+#include "scene/resources/immediate_mesh.h"
+#include "scene/resources/skin.h"
-class ProximityGroup3D : public Node3D {
- GDCLASS(ProximityGroup3D, Node3D);
+class ImporterMesh;
-public:
- enum DispatchMode {
- MODE_PROXY,
- MODE_SIGNAL,
- };
-
-private:
- Map<StringName, uint32_t> groups;
-
- String group_name;
- DispatchMode dispatch_mode = MODE_PROXY;
- Vector3 grid_radius = Vector3(1, 1, 1);
-
- float cell_size = 1.0;
- uint32_t group_version = 0;
-
- void _clear_groups();
- void _update_groups();
- void _add_groups(int *p_cell, String p_base, int p_depth);
- void _new_group(StringName p_name);
+class ImporterMeshInstance3D : public Node3D {
+ GDCLASS(ImporterMeshInstance3D, Node3D)
- void _proximity_group_broadcast(String p_method, Variant p_parameters);
+ Ref<ImporterMesh> mesh;
+ Ref<Skin> skin;
+ NodePath skeleton_path;
+ Vector<Ref<Material>> surface_materials;
protected:
- void _notification(int p_what);
-
static void _bind_methods();
public:
- void set_group_name(const String &p_group_name);
- String get_group_name() const;
-
- void set_dispatch_mode(DispatchMode p_mode);
- DispatchMode get_dispatch_mode() const;
+ void set_mesh(const Ref<ImporterMesh> &p_mesh);
+ Ref<ImporterMesh> get_mesh() const;
- void set_grid_radius(const Vector3 &p_radius);
- Vector3 get_grid_radius() const;
+ void set_skin(const Ref<Skin> &p_skin);
+ Ref<Skin> get_skin() const;
- void broadcast(String p_method, Variant p_parameters);
+ void set_surface_material(int p_idx, const Ref<Material> &p_material);
+ Ref<Material> get_surface_material(int p_idx) const;
- ProximityGroup3D();
- ~ProximityGroup3D() {}
+ void set_skeleton_path(const NodePath &p_path);
+ NodePath get_skeleton_path() const;
};
-
-VARIANT_ENUM_CAST(ProximityGroup3D::DispatchMode);
-
-#endif // PROXIMITY_GROUP_H
+#endif
diff --git a/scene/3d/physics_joint_3d.cpp b/scene/3d/joint_3d.cpp
index 3d58d1c10e..c22e3f6d91 100644
--- a/scene/3d/physics_joint_3d.cpp
+++ b/scene/3d/joint_3d.cpp
@@ -1,12 +1,12 @@
/*************************************************************************/
-/* physics_joint_3d.cpp */
+/* joint_3d.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -28,7 +28,7 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#include "physics_joint_3d.h"
+#include "joint_3d.h"
#include "scene/scene_string_names.h"
@@ -76,15 +76,15 @@ void Joint3D::_update_joint(bool p_only_free) {
PhysicsBody3D *body_b = Object::cast_to<PhysicsBody3D>(node_b);
if (node_a && !body_a && node_b && !body_b) {
- warning = TTR("Node A and Node B must be PhysicsBody3Ds");
+ warning = RTR("Node A and Node B must be PhysicsBody3Ds");
} else if (node_a && !body_a) {
- warning = TTR("Node A must be a PhysicsBody3D");
+ warning = RTR("Node A must be a PhysicsBody3D");
} else if (node_b && !body_b) {
- warning = TTR("Node B must be a PhysicsBody3D");
+ warning = RTR("Node B must be a PhysicsBody3D");
} else if (!body_a && !body_b) {
- warning = TTR("Joint is not connected to any PhysicsBody3Ds");
+ warning = RTR("Joint is not connected to any PhysicsBody3Ds");
} else if (body_a == body_b) {
- warning = TTR("Node A and Node B must be different PhysicsBody3Ds");
+ warning = RTR("Node A and Node B must be different PhysicsBody3Ds");
} else {
warning = String();
}
@@ -124,7 +124,7 @@ void Joint3D::set_node_a(const NodePath &p_node_a) {
return;
}
- if (joint.is_valid()) {
+ if (is_configured()) {
_disconnect_signals();
}
@@ -141,7 +141,7 @@ void Joint3D::set_node_b(const NodePath &p_node_b) {
return;
}
- if (joint.is_valid()) {
+ if (is_configured()) {
_disconnect_signals();
}
@@ -166,14 +166,18 @@ int Joint3D::get_solver_priority() const {
void Joint3D::_notification(int p_what) {
switch (p_what) {
- case NOTIFICATION_READY: {
+ case NOTIFICATION_POST_ENTER_TREE: {
+ if (is_configured()) {
+ _disconnect_signals();
+ }
_update_joint();
} break;
+
case NOTIFICATION_EXIT_TREE: {
- if (joint.is_valid()) {
+ if (is_configured()) {
_disconnect_signals();
- _update_joint(true);
}
+ _update_joint(true);
} break;
}
}
@@ -182,6 +186,10 @@ void Joint3D::set_exclude_nodes_from_collision(bool p_enable) {
if (exclude_from_collision == p_enable) {
return;
}
+ if (is_configured()) {
+ _disconnect_signals();
+ }
+ _update_joint(true);
exclude_from_collision = p_enable;
_update_joint();
}
@@ -259,11 +267,11 @@ real_t PinJoint3D::get_param(Param p_param) const {
void PinJoint3D::_configure_joint(RID p_joint, PhysicsBody3D *body_a, PhysicsBody3D *body_b) {
Vector3 pinpos = get_global_transform().origin;
- Vector3 local_a = body_a->get_global_transform().affine_inverse().xform(pinpos);
+ Vector3 local_a = body_a->to_local(pinpos);
Vector3 local_b;
if (body_b) {
- local_b = body_b->get_global_transform().affine_inverse().xform(pinpos);
+ local_b = body_b->to_local(pinpos);
} else {
local_b = pinpos;
}
@@ -348,7 +356,7 @@ void HingeJoint3D::set_param(Param p_param, real_t p_value) {
PhysicsServer3D::get_singleton()->hinge_joint_set_param(get_joint(), PhysicsServer3D::HingeJointParam(p_param), p_value);
}
- update_gizmo();
+ update_gizmos();
}
real_t HingeJoint3D::get_param(Param p_param) const {
@@ -363,7 +371,7 @@ void HingeJoint3D::set_flag(Flag p_flag, bool p_value) {
PhysicsServer3D::get_singleton()->hinge_joint_set_flag(get_joint(), PhysicsServer3D::HingeJointFlag(p_flag), p_value);
}
- update_gizmo();
+ update_gizmos();
}
bool HingeJoint3D::get_flag(Flag p_flag) const {
@@ -372,15 +380,15 @@ bool HingeJoint3D::get_flag(Flag p_flag) const {
}
void HingeJoint3D::_configure_joint(RID p_joint, PhysicsBody3D *body_a, PhysicsBody3D *body_b) {
- Transform gt = get_global_transform();
- Transform ainv = body_a->get_global_transform().affine_inverse();
+ Transform3D gt = get_global_transform();
+ Transform3D ainv = body_a->get_global_transform().affine_inverse();
- Transform local_a = ainv * gt;
+ Transform3D local_a = ainv * gt;
local_a.orthonormalize();
- Transform local_b = gt;
+ Transform3D local_b = gt;
if (body_b) {
- Transform binv = body_b->get_global_transform().affine_inverse();
+ Transform3D binv = body_b->get_global_transform().affine_inverse();
local_b = binv * gt;
}
@@ -497,7 +505,7 @@ void SliderJoint3D::set_param(Param p_param, real_t p_value) {
if (is_configured()) {
PhysicsServer3D::get_singleton()->slider_joint_set_param(get_joint(), PhysicsServer3D::SliderJointParam(p_param), p_value);
}
- update_gizmo();
+ update_gizmos();
}
real_t SliderJoint3D::get_param(Param p_param) const {
@@ -506,15 +514,15 @@ real_t SliderJoint3D::get_param(Param p_param) const {
}
void SliderJoint3D::_configure_joint(RID p_joint, PhysicsBody3D *body_a, PhysicsBody3D *body_b) {
- Transform gt = get_global_transform();
- Transform ainv = body_a->get_global_transform().affine_inverse();
+ Transform3D gt = get_global_transform();
+ Transform3D ainv = body_a->get_global_transform().affine_inverse();
- Transform local_a = ainv * gt;
+ Transform3D local_a = ainv * gt;
local_a.orthonormalize();
- Transform local_b = gt;
+ Transform3D local_b = gt;
if (body_b) {
- Transform binv = body_b->get_global_transform().affine_inverse();
+ Transform3D binv = body_b->get_global_transform().affine_inverse();
local_b = binv * gt;
}
@@ -602,7 +610,7 @@ void ConeTwistJoint3D::set_param(Param p_param, real_t p_value) {
PhysicsServer3D::get_singleton()->cone_twist_joint_set_param(get_joint(), PhysicsServer3D::ConeTwistJointParam(p_param), p_value);
}
- update_gizmo();
+ update_gizmos();
}
real_t ConeTwistJoint3D::get_param(Param p_param) const {
@@ -611,18 +619,18 @@ real_t ConeTwistJoint3D::get_param(Param p_param) const {
}
void ConeTwistJoint3D::_configure_joint(RID p_joint, PhysicsBody3D *body_a, PhysicsBody3D *body_b) {
- Transform gt = get_global_transform();
+ Transform3D gt = get_global_transform();
//Vector3 cone_twistpos = gt.origin;
//Vector3 cone_twistdir = gt.basis.get_axis(2);
- Transform ainv = body_a->get_global_transform().affine_inverse();
+ Transform3D ainv = body_a->get_global_transform().affine_inverse();
- Transform local_a = ainv * gt;
+ Transform3D local_a = ainv * gt;
local_a.orthonormalize();
- Transform local_b = gt;
+ Transform3D local_b = gt;
if (body_b) {
- Transform binv = body_b->get_global_transform().affine_inverse();
+ Transform3D binv = body_b->get_global_transform().affine_inverse();
local_b = binv * gt;
}
@@ -857,7 +865,7 @@ void Generic6DOFJoint3D::set_param_x(Param p_param, real_t p_value) {
PhysicsServer3D::get_singleton()->generic_6dof_joint_set_param(get_joint(), Vector3::AXIS_X, PhysicsServer3D::G6DOFJointAxisParam(p_param), p_value);
}
- update_gizmo();
+ update_gizmos();
}
real_t Generic6DOFJoint3D::get_param_x(Param p_param) const {
@@ -871,7 +879,7 @@ void Generic6DOFJoint3D::set_param_y(Param p_param, real_t p_value) {
if (is_configured()) {
PhysicsServer3D::get_singleton()->generic_6dof_joint_set_param(get_joint(), Vector3::AXIS_Y, PhysicsServer3D::G6DOFJointAxisParam(p_param), p_value);
}
- update_gizmo();
+ update_gizmos();
}
real_t Generic6DOFJoint3D::get_param_y(Param p_param) const {
@@ -885,7 +893,7 @@ void Generic6DOFJoint3D::set_param_z(Param p_param, real_t p_value) {
if (is_configured()) {
PhysicsServer3D::get_singleton()->generic_6dof_joint_set_param(get_joint(), Vector3::AXIS_Z, PhysicsServer3D::G6DOFJointAxisParam(p_param), p_value);
}
- update_gizmo();
+ update_gizmos();
}
real_t Generic6DOFJoint3D::get_param_z(Param p_param) const {
@@ -899,7 +907,7 @@ void Generic6DOFJoint3D::set_flag_x(Flag p_flag, bool p_enabled) {
if (is_configured()) {
PhysicsServer3D::get_singleton()->generic_6dof_joint_set_flag(get_joint(), Vector3::AXIS_X, PhysicsServer3D::G6DOFJointAxisFlag(p_flag), p_enabled);
}
- update_gizmo();
+ update_gizmos();
}
bool Generic6DOFJoint3D::get_flag_x(Flag p_flag) const {
@@ -913,7 +921,7 @@ void Generic6DOFJoint3D::set_flag_y(Flag p_flag, bool p_enabled) {
if (is_configured()) {
PhysicsServer3D::get_singleton()->generic_6dof_joint_set_flag(get_joint(), Vector3::AXIS_Y, PhysicsServer3D::G6DOFJointAxisFlag(p_flag), p_enabled);
}
- update_gizmo();
+ update_gizmos();
}
bool Generic6DOFJoint3D::get_flag_y(Flag p_flag) const {
@@ -927,7 +935,7 @@ void Generic6DOFJoint3D::set_flag_z(Flag p_flag, bool p_enabled) {
if (is_configured()) {
PhysicsServer3D::get_singleton()->generic_6dof_joint_set_flag(get_joint(), Vector3::AXIS_Z, PhysicsServer3D::G6DOFJointAxisFlag(p_flag), p_enabled);
}
- update_gizmo();
+ update_gizmos();
}
bool Generic6DOFJoint3D::get_flag_z(Flag p_flag) const {
@@ -936,18 +944,18 @@ bool Generic6DOFJoint3D::get_flag_z(Flag p_flag) const {
}
void Generic6DOFJoint3D::_configure_joint(RID p_joint, PhysicsBody3D *body_a, PhysicsBody3D *body_b) {
- Transform gt = get_global_transform();
+ Transform3D gt = get_global_transform();
//Vector3 cone_twistpos = gt.origin;
//Vector3 cone_twistdir = gt.basis.get_axis(2);
- Transform ainv = body_a->get_global_transform().affine_inverse();
+ Transform3D ainv = body_a->get_global_transform().affine_inverse();
- Transform local_a = ainv * gt;
+ Transform3D local_a = ainv * gt;
local_a.orthonormalize();
- Transform local_b = gt;
+ Transform3D local_b = gt;
if (body_b) {
- Transform binv = body_b->get_global_transform().affine_inverse();
+ Transform3D binv = body_b->get_global_transform().affine_inverse();
local_b = binv * gt;
}
diff --git a/scene/3d/physics_joint_3d.h b/scene/3d/joint_3d.h
index 3e0ea38a5c..ea356ef3b7 100644
--- a/scene/3d/physics_joint_3d.h
+++ b/scene/3d/joint_3d.h
@@ -1,12 +1,12 @@
/*************************************************************************/
-/* physics_joint_3d.h */
+/* joint_3d.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -28,8 +28,8 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#ifndef PHYSICS_JOINT_H
-#define PHYSICS_JOINT_H
+#ifndef JOINT_3D_H
+#define JOINT_3D_H
#include "scene/3d/node_3d.h"
#include "scene/3d/physics_body_3d.h"
@@ -334,4 +334,4 @@ public:
VARIANT_ENUM_CAST(Generic6DOFJoint3D::Param);
VARIANT_ENUM_CAST(Generic6DOFJoint3D::Flag);
-#endif // PHYSICS_JOINT_H
+#endif // JOINT_3D_H
diff --git a/scene/3d/label_3d.cpp b/scene/3d/label_3d.cpp
new file mode 100644
index 0000000000..9375190151
--- /dev/null
+++ b/scene/3d/label_3d.cpp
@@ -0,0 +1,1010 @@
+/*************************************************************************/
+/* label_3d.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#include "label_3d.h"
+
+#include "core/core_string_names.h"
+#include "scene/resources/theme.h"
+#include "scene/scene_string_names.h"
+
+void Label3D::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("set_horizontal_alignment", "alignment"), &Label3D::set_horizontal_alignment);
+ ClassDB::bind_method(D_METHOD("get_horizontal_alignment"), &Label3D::get_horizontal_alignment);
+
+ ClassDB::bind_method(D_METHOD("set_vertical_alignment", "alignment"), &Label3D::set_vertical_alignment);
+ ClassDB::bind_method(D_METHOD("get_vertical_alignment"), &Label3D::get_vertical_alignment);
+
+ ClassDB::bind_method(D_METHOD("set_modulate", "modulate"), &Label3D::set_modulate);
+ ClassDB::bind_method(D_METHOD("get_modulate"), &Label3D::get_modulate);
+
+ ClassDB::bind_method(D_METHOD("set_outline_modulate", "modulate"), &Label3D::set_outline_modulate);
+ ClassDB::bind_method(D_METHOD("get_outline_modulate"), &Label3D::get_outline_modulate);
+
+ ClassDB::bind_method(D_METHOD("set_text", "text"), &Label3D::set_text);
+ ClassDB::bind_method(D_METHOD("get_text"), &Label3D::get_text);
+
+ ClassDB::bind_method(D_METHOD("set_text_direction", "direction"), &Label3D::set_text_direction);
+ ClassDB::bind_method(D_METHOD("get_text_direction"), &Label3D::get_text_direction);
+
+ ClassDB::bind_method(D_METHOD("set_opentype_feature", "tag", "value"), &Label3D::set_opentype_feature);
+ ClassDB::bind_method(D_METHOD("get_opentype_feature", "tag"), &Label3D::get_opentype_feature);
+ ClassDB::bind_method(D_METHOD("clear_opentype_features"), &Label3D::clear_opentype_features);
+
+ ClassDB::bind_method(D_METHOD("set_language", "language"), &Label3D::set_language);
+ ClassDB::bind_method(D_METHOD("get_language"), &Label3D::get_language);
+
+ ClassDB::bind_method(D_METHOD("set_structured_text_bidi_override", "parser"), &Label3D::set_structured_text_bidi_override);
+ ClassDB::bind_method(D_METHOD("get_structured_text_bidi_override"), &Label3D::get_structured_text_bidi_override);
+
+ ClassDB::bind_method(D_METHOD("set_structured_text_bidi_override_options", "args"), &Label3D::set_structured_text_bidi_override_options);
+ ClassDB::bind_method(D_METHOD("get_structured_text_bidi_override_options"), &Label3D::get_structured_text_bidi_override_options);
+
+ ClassDB::bind_method(D_METHOD("set_uppercase", "enable"), &Label3D::set_uppercase);
+ ClassDB::bind_method(D_METHOD("is_uppercase"), &Label3D::is_uppercase);
+
+ ClassDB::bind_method(D_METHOD("set_render_priority", "priority"), &Label3D::set_render_priority);
+ ClassDB::bind_method(D_METHOD("get_render_priority"), &Label3D::get_render_priority);
+
+ ClassDB::bind_method(D_METHOD("set_outline_render_priority", "priority"), &Label3D::set_outline_render_priority);
+ ClassDB::bind_method(D_METHOD("get_outline_render_priority"), &Label3D::get_outline_render_priority);
+
+ ClassDB::bind_method(D_METHOD("set_font", "font"), &Label3D::set_font);
+ ClassDB::bind_method(D_METHOD("get_font"), &Label3D::get_font);
+
+ ClassDB::bind_method(D_METHOD("set_font_size", "size"), &Label3D::set_font_size);
+ ClassDB::bind_method(D_METHOD("get_font_size"), &Label3D::get_font_size);
+
+ ClassDB::bind_method(D_METHOD("set_outline_size", "outline_size"), &Label3D::set_outline_size);
+ ClassDB::bind_method(D_METHOD("get_outline_size"), &Label3D::get_outline_size);
+
+ ClassDB::bind_method(D_METHOD("set_line_spacing", "line_spacing"), &Label3D::set_line_spacing);
+ ClassDB::bind_method(D_METHOD("get_line_spacing"), &Label3D::get_line_spacing);
+
+ ClassDB::bind_method(D_METHOD("set_autowrap_mode", "autowrap_mode"), &Label3D::set_autowrap_mode);
+ ClassDB::bind_method(D_METHOD("get_autowrap_mode"), &Label3D::get_autowrap_mode);
+
+ ClassDB::bind_method(D_METHOD("set_width", "width"), &Label3D::set_width);
+ ClassDB::bind_method(D_METHOD("get_width"), &Label3D::get_width);
+
+ ClassDB::bind_method(D_METHOD("set_pixel_size", "pixel_size"), &Label3D::set_pixel_size);
+ ClassDB::bind_method(D_METHOD("get_pixel_size"), &Label3D::get_pixel_size);
+
+ ClassDB::bind_method(D_METHOD("set_offset", "offset"), &Label3D::set_offset);
+ ClassDB::bind_method(D_METHOD("get_offset"), &Label3D::get_offset);
+
+ ClassDB::bind_method(D_METHOD("set_draw_flag", "flag", "enabled"), &Label3D::set_draw_flag);
+ ClassDB::bind_method(D_METHOD("get_draw_flag", "flag"), &Label3D::get_draw_flag);
+
+ ClassDB::bind_method(D_METHOD("set_billboard_mode", "mode"), &Label3D::set_billboard_mode);
+ ClassDB::bind_method(D_METHOD("get_billboard_mode"), &Label3D::get_billboard_mode);
+
+ ClassDB::bind_method(D_METHOD("set_alpha_cut_mode", "mode"), &Label3D::set_alpha_cut_mode);
+ ClassDB::bind_method(D_METHOD("get_alpha_cut_mode"), &Label3D::get_alpha_cut_mode);
+
+ 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_texture_filter", "mode"), &Label3D::set_texture_filter);
+ ClassDB::bind_method(D_METHOD("get_texture_filter"), &Label3D::get_texture_filter);
+
+ ClassDB::bind_method(D_METHOD("generate_triangle_mesh"), &Label3D::generate_triangle_mesh);
+
+ ClassDB::bind_method(D_METHOD("_queue_update"), &Label3D::_queue_update);
+ ClassDB::bind_method(D_METHOD("_font_changed"), &Label3D::_font_changed);
+ ClassDB::bind_method(D_METHOD("_im_update"), &Label3D::_im_update);
+
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "pixel_size", PROPERTY_HINT_RANGE, "0.0001,128,0.0001"), "set_pixel_size", "get_pixel_size");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "offset"), "set_offset", "get_offset");
+
+ ADD_GROUP("Flags", "");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "billboard", PROPERTY_HINT_ENUM, "Disabled,Enabled,Y-Billboard"), "set_billboard_mode", "get_billboard_mode");
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "shaded"), "set_draw_flag", "get_draw_flag", FLAG_SHADED);
+ 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::FLOAT, "alpha_scissor_threshold", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_alpha_scissor_threshold", "get_alpha_scissor_threshold");
+ 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");
+
+ ADD_GROUP("Text", "");
+ ADD_PROPERTY(PropertyInfo(Variant::COLOR, "modulate"), "set_modulate", "get_modulate");
+ ADD_PROPERTY(PropertyInfo(Variant::COLOR, "outline_modulate"), "set_outline_modulate", "get_outline_modulate");
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "text", PROPERTY_HINT_MULTILINE_TEXT, ""), "set_text", "get_text");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "font", PROPERTY_HINT_RESOURCE_TYPE, "Font"), "set_font", "get_font");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "font_size", PROPERTY_HINT_RANGE, "1,127,1"), "set_font_size", "get_font_size");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "outline_size", PROPERTY_HINT_RANGE, "0,127,1"), "set_outline_size", "get_outline_size");
+ 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"), "set_vertical_alignment", "get_vertical_alignment");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "uppercase"), "set_uppercase", "is_uppercase");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "line_spacing"), "set_line_spacing", "get_line_spacing");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "autowrap_mode", PROPERTY_HINT_ENUM, "Off,Arbitrary,Word,Word (Smart)"), "set_autowrap_mode", "get_autowrap_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "width"), "set_width", "get_width");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "structured_text_bidi_override", PROPERTY_HINT_ENUM, "Default,URI,File,Email,List,None,Custom"), "set_structured_text_bidi_override", "get_structured_text_bidi_override");
+ ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "structured_text_bidi_override_options"), "set_structured_text_bidi_override_options", "get_structured_text_bidi_override_options");
+
+ ADD_GROUP("Locale", "");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "text_direction", PROPERTY_HINT_ENUM, "Auto,Left-to-Right,Right-to-Left"), "set_text_direction", "get_text_direction");
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "language", PROPERTY_HINT_LOCALE_ID, ""), "set_language", "get_language");
+
+ BIND_ENUM_CONSTANT(AUTOWRAP_OFF);
+ BIND_ENUM_CONSTANT(AUTOWRAP_ARBITRARY);
+ BIND_ENUM_CONSTANT(AUTOWRAP_WORD);
+ BIND_ENUM_CONSTANT(AUTOWRAP_WORD_SMART);
+
+ BIND_ENUM_CONSTANT(FLAG_SHADED);
+ BIND_ENUM_CONSTANT(FLAG_DOUBLE_SIDED);
+ BIND_ENUM_CONSTANT(FLAG_DISABLE_DEPTH_TEST);
+ BIND_ENUM_CONSTANT(FLAG_FIXED_SIZE);
+ BIND_ENUM_CONSTANT(FLAG_MAX);
+
+ BIND_ENUM_CONSTANT(ALPHA_CUT_DISABLED);
+ BIND_ENUM_CONSTANT(ALPHA_CUT_DISCARD);
+ BIND_ENUM_CONSTANT(ALPHA_CUT_OPAQUE_PREPASS);
+}
+
+bool Label3D::_set(const StringName &p_name, const Variant &p_value) {
+ String str = p_name;
+ if (str.begins_with("opentype_features/")) {
+ String name = str.get_slicec('/', 1);
+ int32_t tag = TS->name_to_tag(name);
+ int value = p_value;
+ if (value == -1) {
+ if (opentype_features.has(tag)) {
+ opentype_features.erase(tag);
+ dirty_font = true;
+ _queue_update();
+ }
+ } else {
+ if (!opentype_features.has(tag) || (int)opentype_features[tag] != value) {
+ opentype_features[tag] = value;
+ dirty_font = true;
+ _queue_update();
+ }
+ }
+ notify_property_list_changed();
+ return true;
+ }
+
+ return false;
+}
+
+bool Label3D::_get(const StringName &p_name, Variant &r_ret) const {
+ String str = p_name;
+ if (str.begins_with("opentype_features/")) {
+ String name = str.get_slicec('/', 1);
+ int32_t tag = TS->name_to_tag(name);
+ if (opentype_features.has(tag)) {
+ r_ret = opentype_features[tag];
+ return true;
+ } else {
+ r_ret = -1;
+ return true;
+ }
+ }
+ return false;
+}
+
+void Label3D::_get_property_list(List<PropertyInfo> *p_list) const {
+ for (const Variant *ftr = opentype_features.next(nullptr); ftr != nullptr; ftr = opentype_features.next(ftr)) {
+ String name = TS->tag_to_name(*ftr);
+ p_list->push_back(PropertyInfo(Variant::INT, "opentype_features/" + name));
+ }
+ p_list->push_back(PropertyInfo(Variant::NIL, "opentype_features/_new", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR));
+}
+
+void Label3D::_validate_property(PropertyInfo &property) const {
+ if (property.name == "material_override" || property.name == "material_overlay") {
+ property.usage = PROPERTY_USAGE_NO_EDITOR;
+ }
+}
+
+void Label3D::_notification(int p_what) {
+ switch (p_what) {
+ case NOTIFICATION_ENTER_TREE: {
+ if (!pending_update) {
+ _im_update();
+ }
+ } break;
+ case NOTIFICATION_TRANSLATION_CHANGED: {
+ String new_text = tr(text);
+ if (new_text == xl_text) {
+ return; // Nothing new.
+ }
+ xl_text = new_text;
+ dirty_text = true;
+ _queue_update();
+ } break;
+ }
+}
+
+void Label3D::_im_update() {
+ _shape();
+
+ triangle_mesh.unref();
+ update_gizmos();
+
+ pending_update = false;
+}
+
+void Label3D::_queue_update() {
+ if (pending_update) {
+ return;
+ }
+
+ pending_update = true;
+ call_deferred(SceneStringNames::get_singleton()->_im_update);
+}
+
+AABB Label3D::get_aabb() const {
+ return aabb;
+}
+
+Ref<TriangleMesh> Label3D::generate_triangle_mesh() const {
+ if (triangle_mesh.is_valid()) {
+ return triangle_mesh;
+ }
+
+ Ref<Font> font = _get_font_or_default();
+ if (font.is_null()) {
+ return Ref<TriangleMesh>();
+ }
+
+ Vector<Vector3> faces;
+ faces.resize(6);
+ Vector3 *facesw = faces.ptrw();
+
+ float total_h = 0.0;
+ float max_line_w = 0.0;
+ for (int i = 0; i < lines_rid.size(); i++) {
+ total_h += TS->shaped_text_get_size(lines_rid[i]).y + font->get_spacing(TextServer::SPACING_TOP) + font->get_spacing(TextServer::SPACING_BOTTOM) + line_spacing;
+ max_line_w = MAX(max_line_w, TS->shaped_text_get_width(lines_rid[i]));
+ }
+
+ float vbegin = 0;
+ switch (vertical_alignment) {
+ case VERTICAL_ALIGNMENT_FILL:
+ case VERTICAL_ALIGNMENT_TOP: {
+ // Nothing.
+ } break;
+ case VERTICAL_ALIGNMENT_CENTER: {
+ vbegin = (total_h - line_spacing) / 2.0;
+ } break;
+ case VERTICAL_ALIGNMENT_BOTTOM: {
+ vbegin = (total_h - line_spacing);
+ } break;
+ }
+
+ Vector2 offset = Vector2(0, vbegin);
+ switch (horizontal_alignment) {
+ case HORIZONTAL_ALIGNMENT_LEFT:
+ break;
+ case HORIZONTAL_ALIGNMENT_FILL:
+ case HORIZONTAL_ALIGNMENT_CENTER: {
+ offset.x = -max_line_w / 2.0;
+ } break;
+ case HORIZONTAL_ALIGNMENT_RIGHT: {
+ offset.x = -max_line_w;
+ } break;
+ }
+
+ Rect2 final_rect = Rect2(offset + lbl_offset, Size2(max_line_w, total_h));
+
+ if (final_rect.size.x == 0 || final_rect.size.y == 0) {
+ return Ref<TriangleMesh>();
+ }
+
+ real_t pixel_size = get_pixel_size();
+
+ Vector2 vertices[4] = {
+
+ (final_rect.position + Vector2(0, -final_rect.size.y)) * pixel_size,
+ (final_rect.position + Vector2(final_rect.size.x, -final_rect.size.y)) * pixel_size,
+ (final_rect.position + Vector2(final_rect.size.x, 0)) * pixel_size,
+ final_rect.position * pixel_size,
+
+ };
+
+ static const int indices[6] = {
+ 0, 1, 2,
+ 0, 2, 3
+ };
+
+ for (int j = 0; j < 6; j++) {
+ int i = indices[j];
+ Vector3 vtx;
+ vtx[0] = vertices[i][0];
+ vtx[1] = vertices[i][1];
+ facesw[j] = vtx;
+ }
+
+ triangle_mesh = Ref<TriangleMesh>(memnew(TriangleMesh));
+ triangle_mesh->create(faces);
+
+ return triangle_mesh;
+}
+
+void Label3D::_generate_glyph_surfaces(const Glyph &p_glyph, Vector2 &r_offset, const Color &p_modulate, int p_priority, int p_outline_size) {
+ for (int j = 0; j < p_glyph.repeat; j++) {
+ Vector2 gl_of;
+ Vector2 gl_sz;
+ Rect2 gl_uv;
+ Size2 texs;
+ RID tex;
+
+ if (p_glyph.font_rid != RID()) {
+ tex = TS->font_get_glyph_texture_rid(p_glyph.font_rid, Vector2i(p_glyph.font_size, p_outline_size), p_glyph.index);
+ if (tex != RID()) {
+ gl_of = (TS->font_get_glyph_offset(p_glyph.font_rid, Vector2i(p_glyph.font_size, p_outline_size), p_glyph.index) + Vector2(p_glyph.x_off, p_glyph.y_off)) * pixel_size;
+ gl_sz = TS->font_get_glyph_size(p_glyph.font_rid, Vector2i(p_glyph.font_size, p_outline_size), p_glyph.index) * pixel_size;
+ gl_uv = TS->font_get_glyph_uv_rect(p_glyph.font_rid, Vector2i(p_glyph.font_size, p_outline_size), p_glyph.index);
+ texs = TS->font_get_glyph_texture_size(p_glyph.font_rid, Vector2i(p_glyph.font_size, p_outline_size), p_glyph.index);
+ }
+ } else {
+ gl_sz = TS->get_hex_code_box_size(p_glyph.font_size, p_glyph.index) * pixel_size;
+ gl_of = Vector2(0, -gl_sz.y);
+ }
+
+ bool msdf = TS->font_is_multichannel_signed_distance_field(p_glyph.font_rid);
+
+ uint64_t mat_hash;
+ if (tex != RID()) {
+ mat_hash = hash_one_uint64(tex.get_id());
+ } else {
+ mat_hash = hash_one_uint64(0);
+ }
+ mat_hash = hash_djb2_one_64(p_priority | (p_outline_size << 31), mat_hash);
+
+ if (!surfaces.has(mat_hash)) {
+ SurfaceData surf;
+ surf.material = RenderingServer::get_singleton()->material_create();
+ // Set defaults for material, names need to match up those in StandardMaterial3D
+ RS::get_singleton()->material_set_param(surf.material, "albedo", Color(1, 1, 1, 1));
+ RS::get_singleton()->material_set_param(surf.material, "specular", 0.5);
+ RS::get_singleton()->material_set_param(surf.material, "metallic", 0.0);
+ RS::get_singleton()->material_set_param(surf.material, "roughness", 1.0);
+ RS::get_singleton()->material_set_param(surf.material, "uv1_offset", Vector3(0, 0, 0));
+ RS::get_singleton()->material_set_param(surf.material, "uv1_scale", Vector3(1, 1, 1));
+ 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);
+ 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);
+ }
+
+ 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);
+
+ RS::get_singleton()->material_set_shader(surf.material, shader_rid);
+ RS::get_singleton()->material_set_param(surf.material, "texture_albedo", tex);
+ if (get_alpha_cut_mode() == ALPHA_CUT_DISABLED) {
+ RS::get_singleton()->material_set_render_priority(surf.material, p_priority);
+ } else {
+ surf.z_shift = p_priority * pixel_size;
+ }
+
+ surfaces[mat_hash] = surf;
+ }
+ SurfaceData &s = surfaces[mat_hash];
+
+ s.mesh_vertices.resize((s.offset + 1) * 4);
+ s.mesh_normals.resize((s.offset + 1) * 4);
+ s.mesh_tangents.resize((s.offset + 1) * 16);
+ s.mesh_colors.resize((s.offset + 1) * 4);
+ s.mesh_uvs.resize((s.offset + 1) * 4);
+
+ s.mesh_vertices.write[(s.offset * 4) + 3] = Vector3(r_offset.x + gl_of.x, r_offset.y - gl_of.y - gl_sz.y, s.z_shift);
+ s.mesh_vertices.write[(s.offset * 4) + 2] = Vector3(r_offset.x + gl_of.x + gl_sz.x, r_offset.y - gl_of.y - gl_sz.y, s.z_shift);
+ s.mesh_vertices.write[(s.offset * 4) + 1] = Vector3(r_offset.x + gl_of.x + gl_sz.x, r_offset.y - gl_of.y, s.z_shift);
+ s.mesh_vertices.write[(s.offset * 4) + 0] = Vector3(r_offset.x + gl_of.x, r_offset.y - gl_of.y, s.z_shift);
+
+ for (int i = 0; i < 4; i++) {
+ s.mesh_normals.write[(s.offset * 4) + i] = Vector3(0.0, 0.0, 1.0);
+ s.mesh_tangents.write[(s.offset * 16) + (i * 4) + 0] = 1.0;
+ s.mesh_tangents.write[(s.offset * 16) + (i * 4) + 1] = 0.0;
+ s.mesh_tangents.write[(s.offset * 16) + (i * 4) + 2] = 0.0;
+ s.mesh_tangents.write[(s.offset * 16) + (i * 4) + 3] = 1.0;
+ s.mesh_colors.write[(s.offset * 4) + i] = p_modulate;
+ s.mesh_uvs.write[(s.offset * 4) + i] = Vector2();
+
+ if (aabb == AABB()) {
+ aabb.position = s.mesh_vertices[(s.offset * 4) + i];
+ } else {
+ aabb.expand_to(s.mesh_vertices[(s.offset * 4) + i]);
+ }
+ }
+
+ if (tex != RID()) {
+ s.mesh_uvs.write[(s.offset * 4) + 3] = Vector2(gl_uv.position.x / texs.x, (gl_uv.position.y + gl_uv.size.y) / texs.y);
+ s.mesh_uvs.write[(s.offset * 4) + 2] = Vector2((gl_uv.position.x + gl_uv.size.x) / texs.x, (gl_uv.position.y + gl_uv.size.y) / texs.y);
+ s.mesh_uvs.write[(s.offset * 4) + 1] = Vector2((gl_uv.position.x + gl_uv.size.x) / texs.x, gl_uv.position.y / texs.y);
+ s.mesh_uvs.write[(s.offset * 4) + 0] = Vector2(gl_uv.position.x / texs.x, gl_uv.position.y / texs.y);
+ }
+
+ s.indices.resize((s.offset + 1) * 6);
+ s.indices.write[(s.offset * 6) + 0] = (s.offset * 4) + 0;
+ s.indices.write[(s.offset * 6) + 1] = (s.offset * 4) + 1;
+ s.indices.write[(s.offset * 6) + 2] = (s.offset * 4) + 2;
+ s.indices.write[(s.offset * 6) + 3] = (s.offset * 4) + 0;
+ s.indices.write[(s.offset * 6) + 4] = (s.offset * 4) + 2;
+ s.indices.write[(s.offset * 6) + 5] = (s.offset * 4) + 3;
+
+ s.offset++;
+ r_offset.x += p_glyph.advance * pixel_size;
+ }
+}
+
+void Label3D::_shape() {
+ // Clear mesh.
+ RS::get_singleton()->mesh_clear(mesh);
+ aabb = AABB();
+
+ // Clear materials.
+ for (Map<uint64_t, SurfaceData>::Element *E = surfaces.front(); E; E = E->next()) {
+ RenderingServer::get_singleton()->free(E->get().material);
+ }
+ surfaces.clear();
+
+ Ref<Font> font = _get_font_or_default();
+ ERR_FAIL_COND(font.is_null());
+
+ // Update text buffer.
+ if (dirty_text) {
+ TS->shaped_text_clear(text_rid);
+ TS->shaped_text_set_direction(text_rid, text_direction);
+
+ String text = (uppercase) ? TS->string_to_upper(xl_text, language) : xl_text;
+ TS->shaped_text_add_string(text_rid, text, font->get_rids(), font_size, opentype_features, language);
+
+ Array stt;
+ if (st_parser == TextServer::STRUCTURED_TEXT_CUSTOM) {
+ GDVIRTUAL_CALL(_structured_text_parser, st_args, text, stt);
+ } else {
+ stt = TS->parse_structured_text(st_parser, st_args, text);
+ }
+ TS->shaped_text_set_bidi_override(text_rid, stt);
+
+ dirty_text = false;
+ dirty_font = false;
+ dirty_lines = true;
+ } else if (dirty_font) {
+ int spans = TS->shaped_get_span_count(text_rid);
+ for (int i = 0; i < spans; i++) {
+ TS->shaped_set_span_update_font(text_rid, i, font->get_rids(), font_size, opentype_features);
+ }
+
+ dirty_font = false;
+ dirty_lines = true;
+ }
+
+ if (dirty_lines) {
+ for (int i = 0; i < lines_rid.size(); i++) {
+ TS->free_rid(lines_rid[i]);
+ }
+ lines_rid.clear();
+
+ uint16_t autowrap_flags = TextServer::BREAK_MANDATORY;
+ switch (autowrap_mode) {
+ case AUTOWRAP_WORD_SMART:
+ autowrap_flags = TextServer::BREAK_WORD_BOUND_ADAPTIVE | TextServer::BREAK_MANDATORY;
+ break;
+ case AUTOWRAP_WORD:
+ autowrap_flags = TextServer::BREAK_WORD_BOUND | TextServer::BREAK_MANDATORY;
+ break;
+ case AUTOWRAP_ARBITRARY:
+ autowrap_flags = TextServer::BREAK_GRAPHEME_BOUND | TextServer::BREAK_MANDATORY;
+ break;
+ case AUTOWRAP_OFF:
+ break;
+ }
+ PackedInt32Array line_breaks = TS->shaped_text_get_line_breaks(text_rid, width, 0, autowrap_flags);
+
+ float max_line_w = 0.0;
+ for (int i = 0; i < line_breaks.size(); i = i + 2) {
+ RID line = TS->shaped_text_substr(text_rid, line_breaks[i], line_breaks[i + 1] - line_breaks[i]);
+ max_line_w = MAX(max_line_w, TS->shaped_text_get_width(line));
+ lines_rid.push_back(line);
+ }
+
+ if (horizontal_alignment == HORIZONTAL_ALIGNMENT_FILL) {
+ for (int i = 0; i < lines_rid.size() - 1; i++) {
+ TS->shaped_text_fit_to_width(lines_rid[i], (width > 0) ? width : max_line_w, TextServer::JUSTIFICATION_WORD_BOUND | TextServer::JUSTIFICATION_KASHIDA);
+ }
+ }
+ dirty_lines = false;
+ }
+
+ // Generate surfaces and materials.
+ float total_h = 0.0;
+ for (int i = 0; i < lines_rid.size(); i++) {
+ total_h += (TS->shaped_text_get_size(lines_rid[i]).y + font->get_spacing(TextServer::SPACING_TOP) + font->get_spacing(TextServer::SPACING_BOTTOM) + line_spacing) * pixel_size;
+ }
+
+ float vbegin = 0.0;
+ switch (vertical_alignment) {
+ case VERTICAL_ALIGNMENT_FILL:
+ case VERTICAL_ALIGNMENT_TOP: {
+ // Nothing.
+ } break;
+ case VERTICAL_ALIGNMENT_CENTER: {
+ vbegin = (total_h - line_spacing * pixel_size) / 2.0;
+ } break;
+ case VERTICAL_ALIGNMENT_BOTTOM: {
+ vbegin = (total_h - line_spacing * pixel_size);
+ } break;
+ }
+
+ Vector2 offset = Vector2(0, vbegin + lbl_offset.y * pixel_size);
+ for (int i = 0; i < lines_rid.size(); i++) {
+ const Glyph *glyphs = TS->shaped_text_get_glyphs(lines_rid[i]);
+ int gl_size = TS->shaped_text_get_glyph_count(lines_rid[i]);
+ float line_width = TS->shaped_text_get_width(lines_rid[i]) * pixel_size;
+
+ switch (horizontal_alignment) {
+ case HORIZONTAL_ALIGNMENT_LEFT:
+ offset.x = 0.0;
+ break;
+ case HORIZONTAL_ALIGNMENT_FILL:
+ case HORIZONTAL_ALIGNMENT_CENTER: {
+ offset.x = -line_width / 2.0;
+ } break;
+ case HORIZONTAL_ALIGNMENT_RIGHT: {
+ offset.x = -line_width;
+ } break;
+ }
+ offset.x += lbl_offset.x * pixel_size;
+ offset.y -= (TS->shaped_text_get_ascent(lines_rid[i]) + font->get_spacing(TextServer::SPACING_TOP)) * pixel_size;
+
+ if (outline_modulate.a != 0.0 && outline_size > 0) {
+ // Outline surfaces.
+ Vector2 ol_offset = offset;
+ for (int j = 0; j < gl_size; j++) {
+ _generate_glyph_surfaces(glyphs[j], ol_offset, outline_modulate, outline_render_priority, outline_size);
+ }
+ }
+
+ // Main text surfaces.
+ for (int j = 0; j < gl_size; j++) {
+ _generate_glyph_surfaces(glyphs[j], offset, modulate, render_priority);
+ }
+ offset.y -= (TS->shaped_text_get_descent(lines_rid[i]) + line_spacing + font->get_spacing(TextServer::SPACING_BOTTOM)) * pixel_size;
+ }
+
+ for (Map<uint64_t, SurfaceData>::Element *E = surfaces.front(); E; E = E->next()) {
+ Array mesh_array;
+ mesh_array.resize(RS::ARRAY_MAX);
+ mesh_array[RS::ARRAY_VERTEX] = E->get().mesh_vertices;
+ mesh_array[RS::ARRAY_NORMAL] = E->get().mesh_normals;
+ mesh_array[RS::ARRAY_TANGENT] = E->get().mesh_tangents;
+ mesh_array[RS::ARRAY_COLOR] = E->get().mesh_colors;
+ mesh_array[RS::ARRAY_TEX_UV] = E->get().mesh_uvs;
+ mesh_array[RS::ARRAY_INDEX] = E->get().indices;
+
+ RS::SurfaceData sd;
+ RS::get_singleton()->mesh_create_surface_data_from_arrays(&sd, RS::PRIMITIVE_TRIANGLES, mesh_array);
+
+ sd.material = E->get().material;
+
+ RS::get_singleton()->mesh_add_surface(mesh, sd);
+ }
+}
+
+void Label3D::set_text(const String &p_string) {
+ text = p_string;
+ xl_text = tr(p_string);
+ dirty_text = true;
+ _queue_update();
+}
+
+String Label3D::get_text() const {
+ return text;
+}
+
+void Label3D::set_horizontal_alignment(HorizontalAlignment p_alignment) {
+ ERR_FAIL_INDEX((int)p_alignment, 4);
+ if (horizontal_alignment != p_alignment) {
+ if (horizontal_alignment == HORIZONTAL_ALIGNMENT_FILL || p_alignment == HORIZONTAL_ALIGNMENT_FILL) {
+ dirty_lines = true; // Reshape lines.
+ }
+ horizontal_alignment = p_alignment;
+ _queue_update();
+ }
+}
+
+HorizontalAlignment Label3D::get_horizontal_alignment() const {
+ return horizontal_alignment;
+}
+
+void Label3D::set_vertical_alignment(VerticalAlignment p_alignment) {
+ ERR_FAIL_INDEX((int)p_alignment, 4);
+ if (vertical_alignment != p_alignment) {
+ vertical_alignment = p_alignment;
+ _queue_update();
+ }
+}
+
+VerticalAlignment Label3D::get_vertical_alignment() const {
+ return vertical_alignment;
+}
+
+void Label3D::set_text_direction(TextServer::Direction p_text_direction) {
+ ERR_FAIL_COND((int)p_text_direction < -1 || (int)p_text_direction > 3);
+ if (text_direction != p_text_direction) {
+ text_direction = p_text_direction;
+ dirty_text = true;
+ _queue_update();
+ }
+}
+
+TextServer::Direction Label3D::get_text_direction() const {
+ return text_direction;
+}
+
+void Label3D::clear_opentype_features() {
+ opentype_features.clear();
+ dirty_font = true;
+ _queue_update();
+}
+
+void Label3D::set_opentype_feature(const String &p_name, int p_value) {
+ int32_t tag = TS->name_to_tag(p_name);
+ if (!opentype_features.has(tag) || (int)opentype_features[tag] != p_value) {
+ opentype_features[tag] = p_value;
+ dirty_font = true;
+ _queue_update();
+ }
+}
+
+int Label3D::get_opentype_feature(const String &p_name) const {
+ int32_t tag = TS->name_to_tag(p_name);
+ if (!opentype_features.has(tag)) {
+ return -1;
+ }
+ return opentype_features[tag];
+}
+
+void Label3D::set_language(const String &p_language) {
+ if (language != p_language) {
+ language = p_language;
+ dirty_text = true;
+ _queue_update();
+ }
+}
+
+String Label3D::get_language() const {
+ return language;
+}
+
+void Label3D::set_structured_text_bidi_override(TextServer::StructuredTextParser p_parser) {
+ if (st_parser != p_parser) {
+ st_parser = p_parser;
+ dirty_text = true;
+ _queue_update();
+ }
+}
+
+TextServer::StructuredTextParser Label3D::get_structured_text_bidi_override() const {
+ return st_parser;
+}
+
+void Label3D::set_structured_text_bidi_override_options(Array p_args) {
+ if (st_args != p_args) {
+ st_args = p_args;
+ dirty_text = true;
+ _queue_update();
+ }
+}
+
+Array Label3D::get_structured_text_bidi_override_options() const {
+ return st_args;
+}
+
+void Label3D::set_uppercase(bool p_uppercase) {
+ if (uppercase != p_uppercase) {
+ uppercase = p_uppercase;
+ dirty_text = true;
+ _queue_update();
+ }
+}
+
+bool Label3D::is_uppercase() const {
+ return uppercase;
+}
+
+void Label3D::set_render_priority(int p_priority) {
+ ERR_FAIL_COND(p_priority < RS::MATERIAL_RENDER_PRIORITY_MIN || p_priority > RS::MATERIAL_RENDER_PRIORITY_MAX);
+ if (render_priority != p_priority) {
+ render_priority = p_priority;
+ _queue_update();
+ }
+}
+
+int Label3D::get_render_priority() const {
+ return render_priority;
+}
+
+void Label3D::set_outline_render_priority(int p_priority) {
+ ERR_FAIL_COND(p_priority < RS::MATERIAL_RENDER_PRIORITY_MIN || p_priority > RS::MATERIAL_RENDER_PRIORITY_MAX);
+ if (outline_render_priority != p_priority) {
+ outline_render_priority = p_priority;
+ _queue_update();
+ }
+}
+
+int Label3D::get_outline_render_priority() const {
+ return outline_render_priority;
+}
+
+void Label3D::_font_changed() {
+ dirty_font = true;
+ _queue_update();
+}
+
+void Label3D::set_font(const Ref<Font> &p_font) {
+ if (font_override != p_font) {
+ if (font_override.is_valid()) {
+ font_override->disconnect(CoreStringNames::get_singleton()->changed, Callable(this, "_font_changed"));
+ }
+ font_override = p_font;
+ dirty_font = true;
+ if (font_override.is_valid()) {
+ font_override->connect(CoreStringNames::get_singleton()->changed, Callable(this, "_font_changed"));
+ }
+ _queue_update();
+ }
+}
+
+Ref<Font> Label3D::get_font() const {
+ return font_override;
+}
+
+Ref<Font> Label3D::_get_font_or_default() const {
+ if (font_override.is_valid() && font_override->get_data_count() > 0) {
+ return font_override;
+ }
+
+ // Check the project-defined Theme resource.
+ if (Theme::get_project_default().is_valid()) {
+ List<StringName> theme_types;
+ Theme::get_project_default()->get_type_dependencies(get_class_name(), StringName(), &theme_types);
+
+ for (const StringName &E : theme_types) {
+ if (Theme::get_project_default()->has_theme_item(Theme::DATA_TYPE_FONT, "font", E)) {
+ return Theme::get_project_default()->get_theme_item(Theme::DATA_TYPE_FONT, "font", E);
+ }
+ }
+ }
+
+ // Lastly, fall back on the items defined in the default Theme, if they exist.
+ {
+ List<StringName> theme_types;
+ Theme::get_default()->get_type_dependencies(get_class_name(), StringName(), &theme_types);
+
+ for (const StringName &E : theme_types) {
+ if (Theme::get_default()->has_theme_item(Theme::DATA_TYPE_FONT, "font", E)) {
+ return Theme::get_default()->get_theme_item(Theme::DATA_TYPE_FONT, "font", E);
+ }
+ }
+ }
+
+ // If they don't exist, use any type to return the default/empty value.
+ return Theme::get_default()->get_theme_item(Theme::DATA_TYPE_FONT, "font", StringName());
+}
+
+void Label3D::set_font_size(int p_size) {
+ if (font_size != p_size) {
+ font_size = p_size;
+ dirty_font = true;
+ _queue_update();
+ }
+}
+
+int Label3D::get_font_size() const {
+ return font_size;
+}
+
+void Label3D::set_outline_size(int p_size) {
+ if (outline_size != p_size) {
+ outline_size = p_size;
+ _queue_update();
+ }
+}
+
+int Label3D::get_outline_size() const {
+ return outline_size;
+}
+
+void Label3D::set_modulate(const Color &p_color) {
+ if (modulate != p_color) {
+ modulate = p_color;
+ _queue_update();
+ }
+}
+
+Color Label3D::get_modulate() const {
+ return modulate;
+}
+
+void Label3D::set_outline_modulate(const Color &p_color) {
+ if (outline_modulate != p_color) {
+ outline_modulate = p_color;
+ _queue_update();
+ }
+}
+
+Color Label3D::get_outline_modulate() const {
+ return outline_modulate;
+}
+
+void Label3D::set_autowrap_mode(Label3D::AutowrapMode p_mode) {
+ if (autowrap_mode != p_mode) {
+ autowrap_mode = p_mode;
+ dirty_lines = true;
+ _queue_update();
+ }
+}
+
+Label3D::AutowrapMode Label3D::get_autowrap_mode() const {
+ return autowrap_mode;
+}
+
+void Label3D::set_width(float p_width) {
+ if (width != p_width) {
+ width = p_width;
+ dirty_lines = true;
+ _queue_update();
+ }
+}
+
+float Label3D::get_width() const {
+ return width;
+}
+
+void Label3D::set_pixel_size(real_t p_amount) {
+ if (pixel_size != p_amount) {
+ pixel_size = p_amount;
+ _queue_update();
+ }
+}
+
+real_t Label3D::get_pixel_size() const {
+ return pixel_size;
+}
+
+void Label3D::set_offset(const Point2 &p_offset) {
+ if (lbl_offset != p_offset) {
+ lbl_offset = p_offset;
+ _queue_update();
+ }
+}
+
+Point2 Label3D::get_offset() const {
+ return lbl_offset;
+}
+
+void Label3D::set_line_spacing(float p_line_spacing) {
+ if (line_spacing != p_line_spacing) {
+ line_spacing = p_line_spacing;
+ _queue_update();
+ }
+}
+
+float Label3D::get_line_spacing() const {
+ return line_spacing;
+}
+
+void Label3D::set_draw_flag(DrawFlags p_flag, bool p_enable) {
+ ERR_FAIL_INDEX(p_flag, FLAG_MAX);
+ if (flags[p_flag] != p_enable) {
+ flags[p_flag] = p_enable;
+ _queue_update();
+ }
+}
+
+bool Label3D::get_draw_flag(DrawFlags p_flag) const {
+ ERR_FAIL_INDEX_V(p_flag, FLAG_MAX, false);
+ return flags[p_flag];
+}
+
+void Label3D::set_billboard_mode(StandardMaterial3D::BillboardMode p_mode) {
+ ERR_FAIL_INDEX(p_mode, 3);
+ if (billboard_mode != p_mode) {
+ billboard_mode = p_mode;
+ _queue_update();
+ }
+}
+
+StandardMaterial3D::BillboardMode Label3D::get_billboard_mode() const {
+ return billboard_mode;
+}
+
+void Label3D::set_alpha_cut_mode(AlphaCutMode p_mode) {
+ ERR_FAIL_INDEX(p_mode, 3);
+ if (alpha_cut != p_mode) {
+ alpha_cut = p_mode;
+ _queue_update();
+ }
+}
+
+void Label3D::set_texture_filter(StandardMaterial3D::TextureFilter p_filter) {
+ if (texture_filter != p_filter) {
+ texture_filter = p_filter;
+ _queue_update();
+ }
+}
+
+StandardMaterial3D::TextureFilter Label3D::get_texture_filter() const {
+ return texture_filter;
+}
+
+Label3D::AlphaCutMode Label3D::get_alpha_cut_mode() const {
+ return alpha_cut;
+}
+
+void Label3D::set_alpha_scissor_threshold(float p_threshold) {
+ if (alpha_scissor_threshold != p_threshold) {
+ alpha_scissor_threshold = p_threshold;
+ _queue_update();
+ }
+}
+
+float Label3D::get_alpha_scissor_threshold() const {
+ return alpha_scissor_threshold;
+}
+
+Label3D::Label3D() {
+ for (int i = 0; i < FLAG_MAX; i++) {
+ flags[i] = (i == FLAG_DOUBLE_SIDED);
+ }
+
+ text_rid = TS->create_shaped_text();
+
+ mesh = RenderingServer::get_singleton()->mesh_create();
+
+ set_cast_shadows_setting(SHADOW_CASTING_SETTING_OFF);
+ set_base(mesh);
+}
+
+Label3D::~Label3D() {
+ for (int i = 0; i < lines_rid.size(); i++) {
+ TS->free_rid(lines_rid[i]);
+ }
+ lines_rid.clear();
+
+ TS->free_rid(text_rid);
+
+ RenderingServer::get_singleton()->free(mesh);
+ for (Map<uint64_t, SurfaceData>::Element *E = surfaces.front(); E; E = E->next()) {
+ RenderingServer::get_singleton()->free(E->get().material);
+ }
+ surfaces.clear();
+}
diff --git a/scene/3d/label_3d.h b/scene/3d/label_3d.h
new file mode 100644
index 0000000000..86b8faa617
--- /dev/null
+++ b/scene/3d/label_3d.h
@@ -0,0 +1,240 @@
+/*************************************************************************/
+/* label_3d.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifndef LABEL_3D_H
+#define LABEL_3D_H
+
+#include "scene/3d/visual_instance_3d.h"
+#include "scene/resources/font.h"
+
+#include "servers/text_server.h"
+
+class Label3D : public GeometryInstance3D {
+ GDCLASS(Label3D, GeometryInstance3D);
+
+public:
+ enum DrawFlags {
+ FLAG_SHADED,
+ FLAG_DOUBLE_SIDED,
+ FLAG_DISABLE_DEPTH_TEST,
+ FLAG_FIXED_SIZE,
+ FLAG_MAX
+ };
+
+ enum AlphaCutMode {
+ ALPHA_CUT_DISABLED,
+ ALPHA_CUT_DISCARD,
+ ALPHA_CUT_OPAQUE_PREPASS
+ };
+
+ enum AutowrapMode {
+ AUTOWRAP_OFF,
+ AUTOWRAP_ARBITRARY,
+ AUTOWRAP_WORD,
+ AUTOWRAP_WORD_SMART
+ };
+
+private:
+ real_t pixel_size = 0.01;
+ bool flags[FLAG_MAX] = {};
+ AlphaCutMode alpha_cut = ALPHA_CUT_DISABLED;
+ float alpha_scissor_threshold = 0.5;
+
+ AABB aabb;
+
+ mutable Ref<TriangleMesh> triangle_mesh;
+ RID mesh;
+ struct SurfaceData {
+ PackedVector3Array mesh_vertices;
+ PackedVector3Array mesh_normals;
+ PackedFloat32Array mesh_tangents;
+ PackedColorArray mesh_colors;
+ PackedVector2Array mesh_uvs;
+ PackedInt32Array indices;
+ int offset = 0;
+ float z_shift = 0.0;
+ RID material;
+ };
+
+ Map<uint64_t, SurfaceData> surfaces;
+
+ HorizontalAlignment horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER;
+ VerticalAlignment vertical_alignment = VERTICAL_ALIGNMENT_CENTER;
+ String text;
+ String xl_text;
+ bool uppercase = false;
+
+ AutowrapMode autowrap_mode = AUTOWRAP_OFF;
+ float width = 500.0;
+
+ int font_size = 16;
+ Ref<Font> font_override;
+ Color modulate = Color(1, 1, 1, 1);
+ Point2 lbl_offset;
+ int outline_render_priority = -1;
+ int render_priority = 0;
+
+ int outline_size = 0;
+ Color outline_modulate = Color(0, 0, 0, 1);
+
+ float line_spacing = 0.f;
+
+ Dictionary opentype_features;
+ String language;
+ TextServer::Direction text_direction = TextServer::DIRECTION_AUTO;
+ TextServer::StructuredTextParser st_parser = TextServer::STRUCTURED_TEXT_DEFAULT;
+ Array st_args;
+
+ RID text_rid;
+ Vector<RID> lines_rid;
+
+ RID base_material;
+ StandardMaterial3D::BillboardMode billboard_mode = StandardMaterial3D::BILLBOARD_DISABLED;
+ StandardMaterial3D::TextureFilter texture_filter = StandardMaterial3D::TEXTURE_FILTER_LINEAR_WITH_MIPMAPS;
+
+ bool pending_update = false;
+
+ bool dirty_lines = true;
+ bool dirty_font = true;
+ bool dirty_text = true;
+
+ 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)
+
+ void _notification(int p_what);
+
+ static void _bind_methods();
+
+ 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 &property) const override;
+
+ void _im_update();
+ void _font_changed();
+ void _queue_update();
+
+ void _shape();
+
+public:
+ void set_horizontal_alignment(HorizontalAlignment p_alignment);
+ HorizontalAlignment get_horizontal_alignment() const;
+
+ void set_vertical_alignment(VerticalAlignment p_alignment);
+ VerticalAlignment get_vertical_alignment() const;
+
+ void set_render_priority(int p_priority);
+ int get_render_priority() const;
+
+ void set_outline_render_priority(int p_priority);
+ int get_outline_render_priority() const;
+
+ void set_text(const String &p_string);
+ String get_text() const;
+
+ void set_text_direction(TextServer::Direction p_text_direction);
+ TextServer::Direction get_text_direction() const;
+
+ void set_opentype_feature(const String &p_name, int p_value);
+ int get_opentype_feature(const String &p_name) const;
+ void clear_opentype_features();
+
+ void set_language(const String &p_language);
+ String get_language() const;
+
+ void set_structured_text_bidi_override(TextServer::StructuredTextParser p_parser);
+ TextServer::StructuredTextParser get_structured_text_bidi_override() const;
+
+ void set_structured_text_bidi_override_options(Array p_args);
+ Array get_structured_text_bidi_override_options() const;
+
+ void set_uppercase(bool p_uppercase);
+ bool is_uppercase() const;
+
+ void set_font(const Ref<Font> &p_font);
+ Ref<Font> get_font() const;
+ Ref<Font> _get_font_or_default() const;
+
+ void set_font_size(int p_size);
+ int get_font_size() const;
+
+ void set_outline_size(int p_size);
+ int get_outline_size() const;
+
+ void set_line_spacing(float p_size);
+ float get_line_spacing() const;
+
+ void set_modulate(const Color &p_color);
+ Color get_modulate() const;
+
+ void set_outline_modulate(const Color &p_color);
+ Color get_outline_modulate() const;
+
+ void set_autowrap_mode(AutowrapMode p_mode);
+ AutowrapMode get_autowrap_mode() const;
+
+ void set_width(float p_width);
+ float get_width() const;
+
+ void set_pixel_size(real_t p_amount);
+ real_t get_pixel_size() const;
+
+ void set_offset(const Point2 &p_offset);
+ Point2 get_offset() const;
+
+ void set_draw_flag(DrawFlags p_flag, bool p_enable);
+ bool get_draw_flag(DrawFlags p_flag) const;
+
+ 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_billboard_mode(StandardMaterial3D::BillboardMode p_mode);
+ StandardMaterial3D::BillboardMode get_billboard_mode() const;
+
+ void set_texture_filter(StandardMaterial3D::TextureFilter p_filter);
+ StandardMaterial3D::TextureFilter get_texture_filter() const;
+
+ virtual AABB get_aabb() const override;
+ Ref<TriangleMesh> generate_triangle_mesh() const;
+
+ Label3D();
+ ~Label3D();
+};
+
+VARIANT_ENUM_CAST(Label3D::AutowrapMode);
+VARIANT_ENUM_CAST(Label3D::DrawFlags);
+VARIANT_ENUM_CAST(Label3D::AlphaCutMode);
+
+#endif // LABEL_3D_H
diff --git a/scene/3d/light_3d.cpp b/scene/3d/light_3d.cpp
index d45749d36b..c95806b2d0 100644
--- a/scene/3d/light_3d.cpp
+++ b/scene/3d/light_3d.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -30,22 +30,14 @@
#include "light_3d.h"
-#include "core/config/engine.h"
-#include "core/config/project_settings.h"
-#include "scene/resources/surface_tool.h"
-
-bool Light3D::_can_gizmo_scale() const {
- return false;
-}
-
-void Light3D::set_param(Param p_param, float p_value) {
+void Light3D::set_param(Param p_param, real_t p_value) {
ERR_FAIL_INDEX(p_param, PARAM_MAX);
param[p_param] = p_value;
RS::get_singleton()->light_set_param(light, RS::LightParam(p_param), p_value);
if (p_param == PARAM_SPOT_ANGLE || p_param == PARAM_RANGE) {
- update_gizmo();
+ update_gizmos();
if (p_param == PARAM_SPOT_ANGLE) {
update_configuration_warnings();
@@ -53,7 +45,7 @@ void Light3D::set_param(Param p_param, float p_value) {
}
}
-float Light3D::get_param(Param p_param) const {
+real_t Light3D::get_param(Param p_param) const {
ERR_FAIL_INDEX_V(p_param, PARAM_MAX, 0);
return param[p_param];
}
@@ -82,6 +74,43 @@ bool Light3D::is_negative() const {
return negative;
}
+void Light3D::set_enable_distance_fade(bool p_enable) {
+ distance_fade_enabled = p_enable;
+ RS::get_singleton()->light_set_distance_fade(light, distance_fade_enabled, distance_fade_begin, distance_fade_shadow, distance_fade_length);
+ notify_property_list_changed();
+}
+
+bool Light3D::is_distance_fade_enabled() const {
+ return distance_fade_enabled;
+}
+
+void Light3D::set_distance_fade_begin(real_t p_distance) {
+ distance_fade_begin = p_distance;
+ RS::get_singleton()->light_set_distance_fade(light, distance_fade_enabled, distance_fade_begin, distance_fade_shadow, distance_fade_length);
+}
+
+real_t Light3D::get_distance_fade_begin() const {
+ return distance_fade_begin;
+}
+
+void Light3D::set_distance_fade_shadow(real_t p_distance) {
+ distance_fade_shadow = p_distance;
+ RS::get_singleton()->light_set_distance_fade(light, distance_fade_enabled, distance_fade_begin, distance_fade_shadow, distance_fade_length);
+}
+
+real_t Light3D::get_distance_fade_shadow() const {
+ return distance_fade_shadow;
+}
+
+void Light3D::set_distance_fade_length(real_t p_length) {
+ distance_fade_length = p_length;
+ RS::get_singleton()->light_set_distance_fade(light, distance_fade_enabled, distance_fade_begin, distance_fade_shadow, distance_fade_length);
+}
+
+real_t Light3D::get_distance_fade_length() const {
+ return distance_fade_length;
+}
+
void Light3D::set_cull_mask(uint32_t p_cull_mask) {
cull_mask = p_cull_mask;
RS::get_singleton()->light_set_cull_mask(light, p_cull_mask);
@@ -95,22 +124,13 @@ void Light3D::set_color(const Color &p_color) {
color = p_color;
RS::get_singleton()->light_set_color(light, p_color);
// The gizmo color depends on the light color, so update it.
- update_gizmo();
+ update_gizmos();
}
Color Light3D::get_color() const {
return color;
}
-void Light3D::set_shadow_color(const Color &p_shadow_color) {
- shadow_color = p_shadow_color;
- RS::get_singleton()->light_set_shadow_color(light, p_shadow_color);
-}
-
-Color Light3D::get_shadow_color() const {
- return shadow_color;
-}
-
void Light3D::set_shadow_reverse_cull_face(bool p_enable) {
reverse_cull = p_enable;
RS::get_singleton()->light_set_reverse_cull_face_mode(light, reverse_cull);
@@ -128,18 +148,14 @@ 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) {
- float len = param[PARAM_RANGE];
- float size = Math::tan(Math::deg2rad(param[PARAM_SPOT_ANGLE])) * len;
+ real_t len = param[PARAM_RANGE];
+ real_t size = Math::tan(Math::deg2rad(param[PARAM_SPOT_ANGLE])) * len;
return AABB(Vector3(-size, -size, -len), Vector3(size * 2, size * 2, len));
}
return AABB();
}
-Vector<Face3> Light3D::get_faces(uint32_t p_usage_flags) const {
- return Vector<Face3>();
-}
-
void Light3D::set_bake_mode(BakeMode p_mode) {
bake_mode = p_mode;
RS::get_singleton()->light_set_bake_mode(light, RS::LightBakeMode(p_mode));
@@ -185,12 +201,11 @@ void Light3D::_update_visibility() {
}
void Light3D::_notification(int p_what) {
- if (p_what == NOTIFICATION_VISIBILITY_CHANGED) {
- _update_visibility();
- }
-
- if (p_what == NOTIFICATION_ENTER_TREE) {
- _update_visibility();
+ switch (p_what) {
+ case NOTIFICATION_VISIBILITY_CHANGED:
+ case NOTIFICATION_ENTER_TREE: {
+ _update_visibility();
+ } break;
}
}
@@ -204,25 +219,20 @@ bool Light3D::is_editor_only() const {
}
void Light3D::_validate_property(PropertyInfo &property) const {
- if (!shadow && (property.name == "shadow_color" || property.name == "shadow_bias" || property.name == "shadow_normal_bias" || property.name == "shadow_reverse_cull_face" || property.name == "shadow_transmittance_bias" || property.name == "shadow_fog_fade" || property.name == "shadow_blur")) {
- property.usage = PROPERTY_USAGE_NOEDITOR;
- }
-
- if (get_light_type() == RS::LIGHT_DIRECTIONAL && property.name == "light_size") {
- property.usage = 0;
+ if (!shadow && (property.name == "shadow_bias" || property.name == "shadow_normal_bias" || property.name == "shadow_reverse_cull_face" || property.name == "shadow_transmittance_bias" || property.name == "shadow_fog_fade" || property.name == "shadow_blur" || property.name == "distance_fade_shadow")) {
+ property.usage = PROPERTY_USAGE_NO_EDITOR;
}
- if (get_light_type() == RS::LIGHT_DIRECTIONAL && property.name == "light_specular") {
- property.usage = 0;
+ if (get_light_type() != RS::LIGHT_DIRECTIONAL && property.name == "light_angular_distance") {
+ // Angular distance is only used in DirectionalLight3D.
+ property.usage = PROPERTY_USAGE_NONE;
}
- if (get_light_type() == RS::LIGHT_DIRECTIONAL && property.name == "light_projector") {
- property.usage = 0;
+ if (!distance_fade_enabled && (property.name == "distance_fade_begin" || property.name == "distance_fade_shadow" || property.name == "distance_fade_length")) {
+ property.usage = PROPERTY_USAGE_NO_EDITOR;
}
- if (get_light_type() != RS::LIGHT_DIRECTIONAL && property.name == "light_angular_distance") {
- property.usage = 0;
- }
+ VisualInstance3D::_validate_property(property);
}
void Light3D::_bind_methods() {
@@ -241,15 +251,24 @@ void Light3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_cull_mask", "cull_mask"), &Light3D::set_cull_mask);
ClassDB::bind_method(D_METHOD("get_cull_mask"), &Light3D::get_cull_mask);
+ ClassDB::bind_method(D_METHOD("set_enable_distance_fade", "enable"), &Light3D::set_enable_distance_fade);
+ ClassDB::bind_method(D_METHOD("is_distance_fade_enabled"), &Light3D::is_distance_fade_enabled);
+
+ ClassDB::bind_method(D_METHOD("set_distance_fade_begin", "distance"), &Light3D::set_distance_fade_begin);
+ ClassDB::bind_method(D_METHOD("get_distance_fade_begin"), &Light3D::get_distance_fade_begin);
+
+ ClassDB::bind_method(D_METHOD("set_distance_fade_shadow", "distance"), &Light3D::set_distance_fade_shadow);
+ ClassDB::bind_method(D_METHOD("get_distance_fade_shadow"), &Light3D::get_distance_fade_shadow);
+
+ ClassDB::bind_method(D_METHOD("set_distance_fade_length", "distance"), &Light3D::set_distance_fade_length);
+ ClassDB::bind_method(D_METHOD("get_distance_fade_length"), &Light3D::get_distance_fade_length);
+
ClassDB::bind_method(D_METHOD("set_color", "color"), &Light3D::set_color);
ClassDB::bind_method(D_METHOD("get_color"), &Light3D::get_color);
ClassDB::bind_method(D_METHOD("set_shadow_reverse_cull_face", "enable"), &Light3D::set_shadow_reverse_cull_face);
ClassDB::bind_method(D_METHOD("get_shadow_reverse_cull_face"), &Light3D::get_shadow_reverse_cull_face);
- ClassDB::bind_method(D_METHOD("set_shadow_color", "shadow_color"), &Light3D::set_shadow_color);
- ClassDB::bind_method(D_METHOD("get_shadow_color"), &Light3D::get_shadow_color);
-
ClassDB::bind_method(D_METHOD("set_bake_mode", "bake_mode"), &Light3D::set_bake_mode);
ClassDB::bind_method(D_METHOD("get_bake_mode"), &Light3D::get_bake_mode);
@@ -265,17 +284,21 @@ void Light3D::_bind_methods() {
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "light_angular_distance", PROPERTY_HINT_RANGE, "0,90,0.01"), "set_param", "get_param", PARAM_SIZE);
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "light_negative"), "set_negative", "is_negative");
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "light_specular", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_param", "get_param", PARAM_SPECULAR);
- ADD_PROPERTY(PropertyInfo(Variant::INT, "light_bake_mode", PROPERTY_HINT_ENUM, "Disabled,Dynamic,Static"), "set_bake_mode", "get_bake_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "light_bake_mode", PROPERTY_HINT_ENUM, "Disabled,Static (VoxelGI/SDFGI/LightmapGI),Dynamic (VoxelGI/SDFGI only)"), "set_bake_mode", "get_bake_mode");
ADD_PROPERTY(PropertyInfo(Variant::INT, "light_cull_mask", PROPERTY_HINT_LAYERS_3D_RENDER), "set_cull_mask", "get_cull_mask");
ADD_GROUP("Shadow", "shadow_");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "shadow_enabled"), "set_shadow", "has_shadow");
- ADD_PROPERTY(PropertyInfo(Variant::COLOR, "shadow_color", PROPERTY_HINT_COLOR_NO_ALPHA), "set_shadow_color", "get_shadow_color");
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "shadow_bias", PROPERTY_HINT_RANGE, "0,10,0.001"), "set_param", "get_param", PARAM_SHADOW_BIAS);
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "shadow_normal_bias", PROPERTY_HINT_RANGE, "0,10,0.001"), "set_param", "get_param", PARAM_SHADOW_NORMAL_BIAS);
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "shadow_reverse_cull_face"), "set_shadow_reverse_cull_face", "get_shadow_reverse_cull_face");
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "shadow_transmittance_bias", PROPERTY_HINT_RANGE, "-16,16,0.01"), "set_param", "get_param", PARAM_TRANSMITTANCE_BIAS);
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "shadow_fog_fade", PROPERTY_HINT_RANGE, "0.01,10,0.01"), "set_param", "get_param", PARAM_SHADOW_VOLUMETRIC_FOG_FADE);
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "shadow_blur", PROPERTY_HINT_RANGE, "0.1,8,0.01"), "set_param", "get_param", PARAM_SHADOW_BLUR);
+ ADD_GROUP("Distance Fade", "distance_fade_");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "distance_fade_enabled"), "set_enable_distance_fade", "is_distance_fade_enabled");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "distance_fade_begin", PROPERTY_HINT_RANGE, "0.0,4096.0,0.01,or_greater"), "set_distance_fade_begin", "get_distance_fade_begin");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "distance_fade_shadow", PROPERTY_HINT_RANGE, "0.0,4096.0,0.01,or_greater"), "set_distance_fade_shadow", "get_distance_fade_shadow");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "distance_fade_length", PROPERTY_HINT_RANGE, "0.0,4096.0,0.01,or_greater"), "set_distance_fade_length", "get_distance_fade_length");
ADD_GROUP("Editor", "");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "editor_only"), "set_editor_only", "is_editor_only");
ADD_GROUP("", "");
@@ -302,8 +325,8 @@ void Light3D::_bind_methods() {
BIND_ENUM_CONSTANT(PARAM_MAX);
BIND_ENUM_CONSTANT(BAKE_DISABLED);
- BIND_ENUM_CONSTANT(BAKE_DYNAMIC);
BIND_ENUM_CONSTANT(BAKE_STATIC);
+ BIND_ENUM_CONSTANT(BAKE_DYNAMIC);
}
Light3D::Light3D(RenderingServer::LightType p_type) {
@@ -344,7 +367,7 @@ Light3D::Light3D(RenderingServer::LightType p_type) {
set_param(PARAM_SHADOW_FADE_START, 0.8);
set_param(PARAM_SHADOW_PANCAKE_SIZE, 20.0);
set_param(PARAM_SHADOW_BLUR, 1.0);
- set_param(PARAM_SHADOW_BIAS, 0.02);
+ set_param(PARAM_SHADOW_BIAS, 0.03);
set_param(PARAM_SHADOW_NORMAL_BIAS, 1.0);
set_param(PARAM_TRANSMITTANCE_BIAS, 0.05);
set_param(PARAM_SHADOW_VOLUMETRIC_FOG_FADE, 0.1);
@@ -353,7 +376,7 @@ Light3D::Light3D(RenderingServer::LightType p_type) {
}
Light3D::Light3D() {
- ERR_PRINT("Light3D should not be instanced directly; use the DirectionalLight3D, OmniLight3D or SpotLight3D subtypes instead.");
+ ERR_PRINT("Light3D should not be instantiated directly; use the DirectionalLight3D, OmniLight3D or SpotLight3D subtypes instead.");
}
Light3D::~Light3D() {
@@ -369,21 +392,13 @@ Light3D::~Light3D() {
void DirectionalLight3D::set_shadow_mode(ShadowMode p_mode) {
shadow_mode = p_mode;
RS::get_singleton()->light_directional_set_shadow_mode(light, RS::LightDirectionalShadowMode(p_mode));
+ notify_property_list_changed();
}
DirectionalLight3D::ShadowMode DirectionalLight3D::get_shadow_mode() const {
return shadow_mode;
}
-void DirectionalLight3D::set_shadow_depth_range(ShadowDepthRange p_range) {
- shadow_depth_range = p_range;
- RS::get_singleton()->light_directional_set_shadow_depth_range_mode(light, RS::LightDirectionalShadowDepthRangeMode(p_range));
-}
-
-DirectionalLight3D::ShadowDepthRange DirectionalLight3D::get_shadow_depth_range() const {
- return shadow_depth_range;
-}
-
void DirectionalLight3D::set_blend_splits(bool p_enable) {
blend_splits = p_enable;
RS::get_singleton()->light_directional_set_blend_splits(light, p_enable);
@@ -393,47 +408,69 @@ bool DirectionalLight3D::is_blend_splits_enabled() const {
return blend_splits;
}
-void DirectionalLight3D::set_sky_only(bool p_sky_only) {
- sky_only = p_sky_only;
- RS::get_singleton()->light_directional_set_sky_only(light, p_sky_only);
+void DirectionalLight3D::set_sky_mode(SkyMode p_mode) {
+ sky_mode = p_mode;
+ RS::get_singleton()->light_directional_set_sky_mode(light, RS::LightDirectionalSkyMode(p_mode));
}
-bool DirectionalLight3D::is_sky_only() const {
- return sky_only;
+DirectionalLight3D::SkyMode DirectionalLight3D::get_sky_mode() const {
+ return sky_mode;
+}
+
+void DirectionalLight3D::_validate_property(PropertyInfo &property) const {
+ if (shadow_mode == SHADOW_ORTHOGONAL && (property.name == "directional_shadow_split_1" || property.name == "directional_shadow_blend_splits")) {
+ // Split 2 and split blending are only used with the PSSM 2 Splits and PSSM 4 Splits shadow modes.
+ property.usage = PROPERTY_USAGE_NO_EDITOR;
+ }
+
+ if ((shadow_mode == SHADOW_ORTHOGONAL || shadow_mode == SHADOW_PARALLEL_2_SPLITS) && (property.name == "directional_shadow_split_2" || property.name == "directional_shadow_split_3")) {
+ // Splits 3 and 4 are only used with the PSSM 4 Splits shadow mode.
+ property.usage = PROPERTY_USAGE_NO_EDITOR;
+ }
+
+ if (property.name == "light_size" || property.name == "light_projector" || property.name == "light_specular") {
+ // Not implemented in DirectionalLight3D (`light_size` is replaced by `light_angular_distance`).
+ property.usage = PROPERTY_USAGE_NONE;
+ }
+
+ if (property.name == "distance_fade_enabled" || property.name == "distance_fade_begin" || property.name == "distance_fade_shadow" || property.name == "distance_fade_length") {
+ // Not relevant for DirectionalLight3D, as the light LOD system only pertains to point lights.
+ // For DirectionalLight3D, `directional_shadow_max_distance` can be used instead.
+ property.usage = PROPERTY_USAGE_NONE;
+ }
+
+ Light3D::_validate_property(property);
}
void DirectionalLight3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_shadow_mode", "mode"), &DirectionalLight3D::set_shadow_mode);
ClassDB::bind_method(D_METHOD("get_shadow_mode"), &DirectionalLight3D::get_shadow_mode);
- ClassDB::bind_method(D_METHOD("set_shadow_depth_range", "mode"), &DirectionalLight3D::set_shadow_depth_range);
- ClassDB::bind_method(D_METHOD("get_shadow_depth_range"), &DirectionalLight3D::get_shadow_depth_range);
-
ClassDB::bind_method(D_METHOD("set_blend_splits", "enabled"), &DirectionalLight3D::set_blend_splits);
ClassDB::bind_method(D_METHOD("is_blend_splits_enabled"), &DirectionalLight3D::is_blend_splits_enabled);
- ClassDB::bind_method(D_METHOD("set_sky_only", "priority"), &DirectionalLight3D::set_sky_only);
- ClassDB::bind_method(D_METHOD("is_sky_only"), &DirectionalLight3D::is_sky_only);
+ ClassDB::bind_method(D_METHOD("set_sky_mode", "mode"), &DirectionalLight3D::set_sky_mode);
+ ClassDB::bind_method(D_METHOD("get_sky_mode"), &DirectionalLight3D::get_sky_mode);
ADD_GROUP("Directional Shadow", "directional_shadow_");
ADD_PROPERTY(PropertyInfo(Variant::INT, "directional_shadow_mode", PROPERTY_HINT_ENUM, "Orthogonal (Fast),PSSM 2 Splits (Average),PSSM 4 Splits (Slow)"), "set_shadow_mode", "get_shadow_mode");
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "directional_shadow_split_1", PROPERTY_HINT_RANGE, "0,1,0.001"), "set_param", "get_param", PARAM_SHADOW_SPLIT_1_OFFSET);
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "directional_shadow_split_2", PROPERTY_HINT_RANGE, "0,1,0.001"), "set_param", "get_param", PARAM_SHADOW_SPLIT_2_OFFSET);
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "directional_shadow_split_3", PROPERTY_HINT_RANGE, "0,1,0.001"), "set_param", "get_param", PARAM_SHADOW_SPLIT_3_OFFSET);
- ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "directional_shadow_fade_start", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_param", "get_param", PARAM_SHADOW_FADE_START);
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "directional_shadow_blend_splits"), "set_blend_splits", "is_blend_splits_enabled");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "directional_shadow_depth_range", PROPERTY_HINT_ENUM, "Stable,Optimized"), "set_shadow_depth_range", "get_shadow_depth_range");
- ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "directional_shadow_max_distance", PROPERTY_HINT_EXP_RANGE, "0,8192,0.1,or_greater"), "set_param", "get_param", PARAM_SHADOW_MAX_DISTANCE);
- ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "directional_shadow_pancake_size", PROPERTY_HINT_EXP_RANGE, "0,1024,0.1,or_greater"), "set_param", "get_param", PARAM_SHADOW_PANCAKE_SIZE);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "directional_shadow_fade_start", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_param", "get_param", PARAM_SHADOW_FADE_START);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "directional_shadow_max_distance", PROPERTY_HINT_RANGE, "0,8192,0.1,or_greater,exp"), "set_param", "get_param", PARAM_SHADOW_MAX_DISTANCE);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "directional_shadow_pancake_size", PROPERTY_HINT_RANGE, "0,1024,0.1,or_greater,exp"), "set_param", "get_param", PARAM_SHADOW_PANCAKE_SIZE);
- ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_in_sky_only"), "set_sky_only", "is_sky_only");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "sky_mode", PROPERTY_HINT_ENUM, "Light and Sky,Light Only,Sky Only"), "set_sky_mode", "get_sky_mode");
BIND_ENUM_CONSTANT(SHADOW_ORTHOGONAL);
BIND_ENUM_CONSTANT(SHADOW_PARALLEL_2_SPLITS);
BIND_ENUM_CONSTANT(SHADOW_PARALLEL_4_SPLITS);
- BIND_ENUM_CONSTANT(SHADOW_DEPTH_RANGE_STABLE);
- BIND_ENUM_CONSTANT(SHADOW_DEPTH_RANGE_OPTIMIZED);
+ BIND_ENUM_CONSTANT(SKY_MODE_LIGHT_AND_SKY);
+ BIND_ENUM_CONSTANT(SKY_MODE_LIGHT_ONLY);
+ BIND_ENUM_CONSTANT(SKY_MODE_SKY_ONLY);
}
DirectionalLight3D::DirectionalLight3D() :
@@ -441,11 +478,10 @@ DirectionalLight3D::DirectionalLight3D() :
set_param(PARAM_SHADOW_MAX_DISTANCE, 100);
set_param(PARAM_SHADOW_FADE_START, 0.8);
// Increase the default shadow bias to better suit most scenes.
- // Leave normal bias untouched as it doesn't benefit DirectionalLight3D as much as OmniLight3D.
- set_param(PARAM_SHADOW_BIAS, 0.05);
+ set_param(PARAM_SHADOW_BIAS, 0.1);
set_shadow_mode(SHADOW_PARALLEL_4_SPLITS);
- set_shadow_depth_range(SHADOW_DEPTH_RANGE_STABLE);
blend_splits = false;
+ set_sky_mode(SKY_MODE_LIGHT_AND_SKY);
}
void OmniLight3D::set_shadow_mode(ShadowMode p_mode) {
@@ -461,7 +497,7 @@ TypedArray<String> OmniLight3D::get_configuration_warnings() const {
TypedArray<String> warnings = Node::get_configuration_warnings();
if (!has_shadow() && get_projector().is_valid()) {
- warnings.push_back(TTR("Projector texture only works with shadows active."));
+ warnings.push_back(RTR("Projector texture only works with shadows active."));
}
return warnings;
@@ -472,7 +508,7 @@ void OmniLight3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_shadow_mode"), &OmniLight3D::get_shadow_mode);
ADD_GROUP("Omni", "omni_");
- ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "omni_range", PROPERTY_HINT_EXP_RANGE, "0,4096,0.1,or_greater"), "set_param", "get_param", PARAM_RANGE);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "omni_range", PROPERTY_HINT_RANGE, "0,4096,0.1,or_greater,exp"), "set_param", "get_param", PARAM_RANGE);
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "omni_attenuation", PROPERTY_HINT_EXP_EASING, "attenuation"), "set_param", "get_param", PARAM_ATTENUATION);
ADD_PROPERTY(PropertyInfo(Variant::INT, "omni_shadow_mode", PROPERTY_HINT_ENUM, "Dual Paraboloid,Cube"), "set_shadow_mode", "get_shadow_mode");
@@ -484,19 +520,18 @@ OmniLight3D::OmniLight3D() :
Light3D(RenderingServer::LIGHT_OMNI) {
set_shadow_mode(SHADOW_CUBE);
// Increase the default shadow biases to better suit most scenes.
- set_param(PARAM_SHADOW_BIAS, 0.1);
- set_param(PARAM_SHADOW_NORMAL_BIAS, 2.0);
+ set_param(PARAM_SHADOW_BIAS, 0.2);
}
TypedArray<String> SpotLight3D::get_configuration_warnings() const {
TypedArray<String> warnings = Node::get_configuration_warnings();
if (has_shadow() && get_param(PARAM_SPOT_ANGLE) >= 90.0) {
- warnings.push_back(TTR("A SpotLight3D with an angle wider than 90 degrees cannot cast shadows."));
+ warnings.push_back(RTR("A SpotLight3D with an angle wider than 90 degrees cannot cast shadows."));
}
if (!has_shadow() && get_projector().is_valid()) {
- warnings.push_back(TTR("Projector texture only works with shadows active."));
+ warnings.push_back(RTR("Projector texture only works with shadows active."));
}
return warnings;
@@ -504,8 +539,8 @@ TypedArray<String> SpotLight3D::get_configuration_warnings() const {
void SpotLight3D::_bind_methods() {
ADD_GROUP("Spot", "spot_");
- ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "spot_range", PROPERTY_HINT_EXP_RANGE, "0,4096,0.1,or_greater"), "set_param", "get_param", PARAM_RANGE);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "spot_range", PROPERTY_HINT_RANGE, "0,4096,0.1,or_greater,exp"), "set_param", "get_param", PARAM_RANGE);
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "spot_attenuation", PROPERTY_HINT_EXP_EASING, "attenuation"), "set_param", "get_param", PARAM_ATTENUATION);
- ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "spot_angle", PROPERTY_HINT_RANGE, "0,180,0.1"), "set_param", "get_param", PARAM_SPOT_ANGLE);
+ ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "spot_angle", PROPERTY_HINT_RANGE, "0,180,0.1,degrees"), "set_param", "get_param", PARAM_SPOT_ANGLE);
ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "spot_angle_attenuation", PROPERTY_HINT_EXP_EASING, "attenuation"), "set_param", "get_param", PARAM_SPOT_ATTENUATION);
}
diff --git a/scene/3d/light_3d.h b/scene/3d/light_3d.h
index e145b08b74..383fa644e5 100644
--- a/scene/3d/light_3d.h
+++ b/scene/3d/light_3d.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -32,12 +32,9 @@
#define LIGHT_3D_H
#include "scene/3d/visual_instance_3d.h"
-#include "scene/resources/texture.h"
-#include "servers/rendering_server.h"
class Light3D : public VisualInstance3D {
GDCLASS(Light3D, VisualInstance3D);
- OBJ_CATEGORY("3D Light Nodes");
public:
enum Param {
@@ -65,18 +62,21 @@ public:
enum BakeMode {
BAKE_DISABLED,
+ BAKE_STATIC,
BAKE_DYNAMIC,
- BAKE_STATIC
};
private:
Color color;
- float param[PARAM_MAX] = {};
- Color shadow_color;
+ real_t param[PARAM_MAX] = {};
bool shadow = false;
bool negative = false;
bool reverse_cull = false;
uint32_t cull_mask = 0;
+ bool distance_fade_enabled = false;
+ real_t distance_fade_begin = 40.0;
+ real_t distance_fade_shadow = 50.0;
+ real_t distance_fade_length = 10.0;
RS::LightType type = RenderingServer::LIGHT_DIRECTIONAL;
bool editor_only = false;
void _update_visibility();
@@ -88,8 +88,6 @@ private:
protected:
RID light;
- virtual bool _can_gizmo_scale() const;
-
static void _bind_methods();
void _notification(int p_what);
virtual void _validate_property(PropertyInfo &property) const override;
@@ -102,8 +100,8 @@ public:
void set_editor_only(bool p_editor_only);
bool is_editor_only() const;
- void set_param(Param p_param, float p_value);
- float get_param(Param p_param) const;
+ void set_param(Param p_param, real_t p_value);
+ real_t get_param(Param p_param) const;
void set_shadow(bool p_enable);
bool has_shadow() const;
@@ -111,15 +109,24 @@ public:
void set_negative(bool p_enable);
bool is_negative() const;
+ void set_enable_distance_fade(bool p_enable);
+ bool is_distance_fade_enabled() const;
+
+ void set_distance_fade_begin(real_t p_distance);
+ real_t get_distance_fade_begin() const;
+
+ void set_distance_fade_shadow(real_t p_distance);
+ real_t get_distance_fade_shadow() const;
+
+ void set_distance_fade_length(real_t p_length);
+ real_t get_distance_fade_length() const;
+
void set_cull_mask(uint32_t p_cull_mask);
uint32_t get_cull_mask() const;
void set_color(const Color &p_color);
Color get_color() const;
- void set_shadow_color(const Color &p_shadow_color);
- Color get_shadow_color() const;
-
void set_shadow_reverse_cull_face(bool p_enable);
bool get_shadow_reverse_cull_face() const;
@@ -130,7 +137,6 @@ public:
Ref<Texture2D> get_projector() const;
virtual AABB get_aabb() const override;
- virtual Vector<Face3> get_faces(uint32_t p_usage_flags) const override;
Light3D();
~Light3D();
@@ -149,38 +155,36 @@ public:
SHADOW_PARALLEL_4_SPLITS,
};
- enum ShadowDepthRange {
- SHADOW_DEPTH_RANGE_STABLE = RS::LIGHT_DIRECTIONAL_SHADOW_DEPTH_RANGE_STABLE,
- SHADOW_DEPTH_RANGE_OPTIMIZED = RS::LIGHT_DIRECTIONAL_SHADOW_DEPTH_RANGE_OPTIMIZED,
+ enum SkyMode {
+ SKY_MODE_LIGHT_AND_SKY,
+ SKY_MODE_LIGHT_ONLY,
+ SKY_MODE_SKY_ONLY,
};
private:
bool blend_splits;
ShadowMode shadow_mode;
- ShadowDepthRange shadow_depth_range;
- bool sky_only = false;
+ SkyMode sky_mode = SKY_MODE_LIGHT_AND_SKY;
protected:
static void _bind_methods();
+ virtual void _validate_property(PropertyInfo &property) const override;
public:
void set_shadow_mode(ShadowMode p_mode);
ShadowMode get_shadow_mode() const;
- void set_shadow_depth_range(ShadowDepthRange p_range);
- ShadowDepthRange get_shadow_depth_range() const;
-
void set_blend_splits(bool p_enable);
bool is_blend_splits_enabled() const;
- void set_sky_only(bool p_sky_only);
- bool is_sky_only() const;
+ void set_sky_mode(SkyMode p_mode);
+ SkyMode get_sky_mode() const;
DirectionalLight3D();
};
VARIANT_ENUM_CAST(DirectionalLight3D::ShadowMode)
-VARIANT_ENUM_CAST(DirectionalLight3D::ShadowDepthRange)
+VARIANT_ENUM_CAST(DirectionalLight3D::SkyMode)
class OmniLight3D : public Light3D {
GDCLASS(OmniLight3D, Light3D);
diff --git a/scene/3d/baked_lightmap.cpp b/scene/3d/lightmap_gi.cpp
index ef648a126e..88d2c1ad69 100644
--- a/scene/3d/baked_lightmap.cpp
+++ b/scene/3d/lightmap_gi.cpp
@@ -1,12 +1,12 @@
/*************************************************************************/
-/* baked_lightmap.cpp */
+/* lightmap_gi.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -28,19 +28,14 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#include "baked_lightmap.h"
+#include "lightmap_gi.h"
#include "core/io/config_file.h"
-#include "core/io/resource_saver.h"
-#include "core/math/camera_matrix.h"
#include "core/math/delaunay_3d.h"
-#include "core/os/dir_access.h"
-#include "core/os/file_access.h"
-#include "core/os/os.h"
-#include "core/templates/sort_array.h"
#include "lightmap_probe.h"
+#include "scene/3d/mesh_instance_3d.h"
-void BakedLightmapData::add_user(const NodePath &p_path, const Rect2 &p_uv_scale, int p_slice_index, int32_t p_sub_instance) {
+void LightmapGIData::add_user(const NodePath &p_path, const Rect2 &p_uv_scale, int p_slice_index, int32_t p_sub_instance) {
User user;
user.path = p_path;
user.uv_scale = p_uv_scale;
@@ -49,35 +44,35 @@ void BakedLightmapData::add_user(const NodePath &p_path, const Rect2 &p_uv_scale
users.push_back(user);
}
-int BakedLightmapData::get_user_count() const {
+int LightmapGIData::get_user_count() const {
return users.size();
}
-NodePath BakedLightmapData::get_user_path(int p_user) const {
+NodePath LightmapGIData::get_user_path(int p_user) const {
ERR_FAIL_INDEX_V(p_user, users.size(), NodePath());
return users[p_user].path;
}
-int32_t BakedLightmapData::get_user_sub_instance(int p_user) const {
+int32_t LightmapGIData::get_user_sub_instance(int p_user) const {
ERR_FAIL_INDEX_V(p_user, users.size(), -1);
return users[p_user].sub_instance;
}
-Rect2 BakedLightmapData::get_user_lightmap_uv_scale(int p_user) const {
+Rect2 LightmapGIData::get_user_lightmap_uv_scale(int p_user) const {
ERR_FAIL_INDEX_V(p_user, users.size(), Rect2());
return users[p_user].uv_scale;
}
-int BakedLightmapData::get_user_lightmap_slice_index(int p_user) const {
+int LightmapGIData::get_user_lightmap_slice_index(int p_user) const {
ERR_FAIL_INDEX_V(p_user, users.size(), -1);
return users[p_user].slice_index;
}
-void BakedLightmapData::clear_users() {
+void LightmapGIData::clear_users() {
users.clear();
}
-void BakedLightmapData::_set_user_data(const Array &p_data) {
+void LightmapGIData::_set_user_data(const Array &p_data) {
ERR_FAIL_COND(p_data.size() <= 0);
ERR_FAIL_COND((p_data.size() % 4) != 0);
@@ -86,7 +81,7 @@ void BakedLightmapData::_set_user_data(const Array &p_data) {
}
}
-Array BakedLightmapData::_get_user_data() const {
+Array LightmapGIData::_get_user_data() const {
Array ret;
for (int i = 0; i < users.size(); i++) {
ret.push_back(users[i].path);
@@ -97,33 +92,33 @@ Array BakedLightmapData::_get_user_data() const {
return ret;
}
-RID BakedLightmapData::get_rid() const {
+RID LightmapGIData::get_rid() const {
return lightmap;
}
-void BakedLightmapData::clear() {
+void LightmapGIData::clear() {
users.clear();
}
-void BakedLightmapData::set_light_texture(const Ref<TextureLayered> &p_light_texture) {
+void LightmapGIData::set_light_texture(const Ref<TextureLayered> &p_light_texture) {
light_texture = p_light_texture;
RS::get_singleton()->lightmap_set_textures(lightmap, light_texture.is_valid() ? light_texture->get_rid() : RID(), uses_spherical_harmonics);
}
-Ref<TextureLayered> BakedLightmapData::get_light_texture() const {
+Ref<TextureLayered> LightmapGIData::get_light_texture() const {
return light_texture;
}
-void BakedLightmapData::set_uses_spherical_harmonics(bool p_enable) {
+void LightmapGIData::set_uses_spherical_harmonics(bool p_enable) {
uses_spherical_harmonics = p_enable;
RS::get_singleton()->lightmap_set_textures(lightmap, light_texture.is_valid() ? light_texture->get_rid() : RID(), uses_spherical_harmonics);
}
-bool BakedLightmapData::is_using_spherical_harmonics() const {
+bool LightmapGIData::is_using_spherical_harmonics() const {
return uses_spherical_harmonics;
}
-void BakedLightmapData::set_capture_data(const AABB &p_bounds, bool p_interior, const PackedVector3Array &p_points, const PackedColorArray &p_point_sh, const PackedInt32Array &p_tetrahedra, const PackedInt32Array &p_bsp_tree) {
+void LightmapGIData::set_capture_data(const AABB &p_bounds, bool p_interior, const PackedVector3Array &p_points, const PackedColorArray &p_point_sh, const PackedInt32Array &p_tetrahedra, const PackedInt32Array &p_bsp_tree) {
if (p_points.size()) {
int pc = p_points.size();
ERR_FAIL_COND(pc * 9 != p_point_sh.size());
@@ -141,31 +136,31 @@ void BakedLightmapData::set_capture_data(const AABB &p_bounds, bool p_interior,
bounds = p_bounds;
}
-PackedVector3Array BakedLightmapData::get_capture_points() const {
+PackedVector3Array LightmapGIData::get_capture_points() const {
return RS::get_singleton()->lightmap_get_probe_capture_points(lightmap);
}
-PackedColorArray BakedLightmapData::get_capture_sh() const {
+PackedColorArray LightmapGIData::get_capture_sh() const {
return RS::get_singleton()->lightmap_get_probe_capture_sh(lightmap);
}
-PackedInt32Array BakedLightmapData::get_capture_tetrahedra() const {
+PackedInt32Array LightmapGIData::get_capture_tetrahedra() const {
return RS::get_singleton()->lightmap_get_probe_capture_tetrahedra(lightmap);
}
-PackedInt32Array BakedLightmapData::get_capture_bsp_tree() const {
+PackedInt32Array LightmapGIData::get_capture_bsp_tree() const {
return RS::get_singleton()->lightmap_get_probe_capture_bsp_tree(lightmap);
}
-AABB BakedLightmapData::get_capture_bounds() const {
+AABB LightmapGIData::get_capture_bounds() const {
return bounds;
}
-bool BakedLightmapData::is_interior() const {
+bool LightmapGIData::is_interior() const {
return interior;
}
-void BakedLightmapData::_set_probe_data(const Dictionary &p_data) {
+void LightmapGIData::_set_probe_data(const Dictionary &p_data) {
ERR_FAIL_COND(!p_data.has("bounds"));
ERR_FAIL_COND(!p_data.has("points"));
ERR_FAIL_COND(!p_data.has("tetrahedra"));
@@ -175,7 +170,7 @@ void BakedLightmapData::_set_probe_data(const Dictionary &p_data) {
set_capture_data(p_data["bounds"], p_data["interior"], p_data["points"], p_data["sh"], p_data["tetrahedra"], p_data["bsp"]);
}
-Dictionary BakedLightmapData::_get_probe_data() const {
+Dictionary LightmapGIData::_get_probe_data() const {
Dictionary d;
d["bounds"] = get_capture_bounds();
d["points"] = get_capture_points();
@@ -186,43 +181,43 @@ Dictionary BakedLightmapData::_get_probe_data() const {
return d;
}
-void BakedLightmapData::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_set_user_data", "data"), &BakedLightmapData::_set_user_data);
- ClassDB::bind_method(D_METHOD("_get_user_data"), &BakedLightmapData::_get_user_data);
+void LightmapGIData::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("_set_user_data", "data"), &LightmapGIData::_set_user_data);
+ ClassDB::bind_method(D_METHOD("_get_user_data"), &LightmapGIData::_get_user_data);
- ClassDB::bind_method(D_METHOD("set_light_texture", "light_texture"), &BakedLightmapData::set_light_texture);
- ClassDB::bind_method(D_METHOD("get_light_texture"), &BakedLightmapData::get_light_texture);
+ ClassDB::bind_method(D_METHOD("set_light_texture", "light_texture"), &LightmapGIData::set_light_texture);
+ ClassDB::bind_method(D_METHOD("get_light_texture"), &LightmapGIData::get_light_texture);
- ClassDB::bind_method(D_METHOD("set_uses_spherical_harmonics", "uses_spherical_harmonics"), &BakedLightmapData::set_uses_spherical_harmonics);
- ClassDB::bind_method(D_METHOD("is_using_spherical_harmonics"), &BakedLightmapData::is_using_spherical_harmonics);
+ ClassDB::bind_method(D_METHOD("set_uses_spherical_harmonics", "uses_spherical_harmonics"), &LightmapGIData::set_uses_spherical_harmonics);
+ ClassDB::bind_method(D_METHOD("is_using_spherical_harmonics"), &LightmapGIData::is_using_spherical_harmonics);
- ClassDB::bind_method(D_METHOD("add_user", "path", "uv_scale", "slice_index", "sub_instance"), &BakedLightmapData::add_user);
- ClassDB::bind_method(D_METHOD("get_user_count"), &BakedLightmapData::get_user_count);
- ClassDB::bind_method(D_METHOD("get_user_path", "user_idx"), &BakedLightmapData::get_user_path);
- ClassDB::bind_method(D_METHOD("clear_users"), &BakedLightmapData::clear_users);
+ ClassDB::bind_method(D_METHOD("add_user", "path", "uv_scale", "slice_index", "sub_instance"), &LightmapGIData::add_user);
+ ClassDB::bind_method(D_METHOD("get_user_count"), &LightmapGIData::get_user_count);
+ ClassDB::bind_method(D_METHOD("get_user_path", "user_idx"), &LightmapGIData::get_user_path);
+ ClassDB::bind_method(D_METHOD("clear_users"), &LightmapGIData::clear_users);
- ClassDB::bind_method(D_METHOD("_set_probe_data", "data"), &BakedLightmapData::_set_probe_data);
- ClassDB::bind_method(D_METHOD("_get_probe_data"), &BakedLightmapData::_get_probe_data);
+ ClassDB::bind_method(D_METHOD("_set_probe_data", "data"), &LightmapGIData::_set_probe_data);
+ ClassDB::bind_method(D_METHOD("_get_probe_data"), &LightmapGIData::_get_probe_data);
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "light_texture", PROPERTY_HINT_RESOURCE_TYPE, "TextureLayered"), "set_light_texture", "get_light_texture");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL, "uses_spherical_harmonics", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL), "set_uses_spherical_harmonics", "is_using_spherical_harmonics");
- ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "user_data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL), "_set_user_data", "_get_user_data");
- ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "probe_data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL), "_set_probe_data", "_get_probe_data");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "uses_spherical_harmonics", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL), "set_uses_spherical_harmonics", "is_using_spherical_harmonics");
+ ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "user_data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL), "_set_user_data", "_get_user_data");
+ ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "probe_data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL), "_set_probe_data", "_get_probe_data");
}
-BakedLightmapData::BakedLightmapData() {
+LightmapGIData::LightmapGIData() {
lightmap = RS::get_singleton()->lightmap_create();
}
-BakedLightmapData::~BakedLightmapData() {
+LightmapGIData::~LightmapGIData() {
RS::get_singleton()->free(lightmap);
}
///////////////////////////
-void BakedLightmap::_find_meshes_and_lights(Node *p_at_node, Vector<MeshesFound> &meshes, Vector<LightsFound> &lights, Vector<Vector3> &probes) {
+void LightmapGI::_find_meshes_and_lights(Node *p_at_node, Vector<MeshesFound> &meshes, Vector<LightsFound> &lights, Vector<Vector3> &probes) {
MeshInstance3D *mi = Object::cast_to<MeshInstance3D>(p_at_node);
- if (mi && mi->get_gi_mode() == GeometryInstance3D::GI_MODE_BAKED && mi->is_visible_in_tree()) {
+ if (mi && mi->get_gi_mode() == GeometryInstance3D::GI_MODE_STATIC && mi->is_visible_in_tree()) {
Ref<Mesh> mesh = mi->get_mesh();
if (mesh.is_valid()) {
bool all_have_uv2_and_normal = true;
@@ -273,7 +268,7 @@ void BakedLightmap::_find_meshes_and_lights(Node *p_at_node, Vector<MeshesFound>
if (!mi && s) {
Array bmeshes = p_at_node->call("get_bake_bmeshes");
if (bmeshes.size() && (bmeshes.size() & 1) == 0) {
- Transform xf = get_global_transform().affine_inverse() * s->get_global_transform();
+ Transform3D xf = get_global_transform().affine_inverse() * s->get_global_transform();
for (int i = 0; i < bmeshes.size(); i += 2) {
Ref<Mesh> mesh = bmeshes[i];
if (!mesh.is_valid()) {
@@ -282,7 +277,7 @@ void BakedLightmap::_find_meshes_and_lights(Node *p_at_node, Vector<MeshesFound>
MeshesFound mf;
- Transform mesh_xf = bmeshes[i + 1];
+ Transform3D mesh_xf = bmeshes[i + 1];
mf.xform = xf * mesh_xf;
mf.node_path = get_path_to(s);
mf.subindex = i / 2;
@@ -306,7 +301,7 @@ void BakedLightmap::_find_meshes_and_lights(Node *p_at_node, Vector<MeshesFound>
LightmapProbe *probe = Object::cast_to<LightmapProbe>(p_at_node);
if (probe) {
- Transform xf = get_global_transform().affine_inverse() * probe->get_global_transform();
+ Transform3D xf = get_global_transform().affine_inverse() * probe->get_global_transform();
probes.push_back(xf.origin);
}
@@ -320,7 +315,7 @@ void BakedLightmap::_find_meshes_and_lights(Node *p_at_node, Vector<MeshesFound>
}
}
-int BakedLightmap::_bsp_get_simplex_side(const Vector<Vector3> &p_points, const LocalVector<BSPSimplex> &p_simplices, const Plane &p_plane, uint32_t p_simplex) const {
+int LightmapGI::_bsp_get_simplex_side(const Vector<Vector3> &p_points, const LocalVector<BSPSimplex> &p_simplices, const Plane &p_plane, uint32_t p_simplex) const {
int over = 0;
int under = 0;
int coplanar = 0;
@@ -348,7 +343,7 @@ int BakedLightmap::_bsp_get_simplex_side(const Vector<Vector3> &p_points, const
//#define DEBUG_BSP
-int32_t BakedLightmap::_compute_bsp_tree(const Vector<Vector3> &p_points, const LocalVector<Plane> &p_planes, LocalVector<int32_t> &planes_tested, const LocalVector<BSPSimplex> &p_simplices, const LocalVector<int32_t> &p_simplex_indices, LocalVector<BSPNode> &bsp_nodes) {
+int32_t LightmapGI::_compute_bsp_tree(const Vector<Vector3> &p_points, const LocalVector<Plane> &p_planes, LocalVector<int32_t> &planes_tested, const LocalVector<BSPSimplex> &p_simplices, const LocalVector<int32_t> &p_simplex_indices, LocalVector<BSPNode> &bsp_nodes) {
//if we reach here, it means there is more than one simplex
int32_t node_index = (int32_t)bsp_nodes.size();
bsp_nodes.push_back(BSPNode());
@@ -472,7 +467,7 @@ int32_t BakedLightmap::_compute_bsp_tree(const Vector<Vector3> &p_points, const
}
}
if (i == 0) {
- centers.push_back(bounds.position + bounds.size * 0.5);
+ centers.push_back(bounds.get_center());
} else {
bounds_all.merge_with(bounds);
}
@@ -533,7 +528,7 @@ int32_t BakedLightmap::_compute_bsp_tree(const Vector<Vector3> &p_points, const
return node_index;
}
-bool BakedLightmap::_lightmap_bake_step_function(float p_completion, const String &p_text, void *ud, bool p_refresh) {
+bool LightmapGI::_lightmap_bake_step_function(float p_completion, const String &p_text, void *ud, bool p_refresh) {
BakeStepUD *bsud = (BakeStepUD *)ud;
bool ret = false;
if (bsud->func) {
@@ -542,7 +537,7 @@ bool BakedLightmap::_lightmap_bake_step_function(float p_completion, const Strin
return ret;
}
-void BakedLightmap::_plot_triangle_into_octree(GenProbesOctree *p_cell, float p_cell_size, const Vector3 *p_triangle) {
+void LightmapGI::_plot_triangle_into_octree(GenProbesOctree *p_cell, float p_cell_size, const Vector3 *p_triangle) {
for (int i = 0; i < 8; i++) {
Vector3i pos = p_cell->offset;
uint32_t half_size = p_cell->size / 2;
@@ -560,7 +555,7 @@ void BakedLightmap::_plot_triangle_into_octree(GenProbesOctree *p_cell, float p_
subcell.position = Vector3(pos) * p_cell_size;
subcell.size = Vector3(half_size, half_size, half_size) * p_cell_size;
- if (!Geometry3D::triangle_box_overlap(subcell.position + subcell.size * 0.5, subcell.size * 0.5, p_triangle)) {
+ if (!Geometry3D::triangle_box_overlap(subcell.get_center(), subcell.size * 0.5, p_triangle)) {
continue;
}
@@ -578,7 +573,7 @@ void BakedLightmap::_plot_triangle_into_octree(GenProbesOctree *p_cell, float p_
}
}
-void BakedLightmap::_gen_new_positions_from_octree(const GenProbesOctree *p_cell, float p_cell_size, const Vector<Vector3> &probe_positions, LocalVector<Vector3> &new_probe_positions, HashMap<Vector3i, bool, Vector3iHash> &positions_used, const AABB &p_bounds) {
+void LightmapGI::_gen_new_positions_from_octree(const GenProbesOctree *p_cell, float p_cell_size, const Vector<Vector3> &probe_positions, LocalVector<Vector3> &new_probe_positions, HashMap<Vector3i, bool, Vector3iHash> &positions_used, const AABB &p_bounds) {
for (int i = 0; i < 8; i++) {
Vector3i pos = p_cell->offset;
if (i & 1) {
@@ -599,7 +594,7 @@ void BakedLightmap::_gen_new_positions_from_octree(const GenProbesOctree *p_cell
const Vector3 *pp = probe_positions.ptr();
bool exists = false;
for (int j = 0; j < ppcount; j++) {
- if (pp[j].distance_to(real_pos) < CMP_EPSILON) {
+ if (pp[j].is_equal_approx(real_pos)) {
exists = true;
break;
}
@@ -618,8 +613,8 @@ void BakedLightmap::_gen_new_positions_from_octree(const GenProbesOctree *p_cell
}
}
-BakedLightmap::BakeError BakedLightmap::bake(Node *p_from_node, String p_image_data_path, Lightmapper::BakeStepFunc p_bake_step, void *p_bake_userdata) {
- if (p_image_data_path == "") {
+LightmapGI::BakeError LightmapGI::bake(Node *p_from_node, String p_image_data_path, Lightmapper::BakeStepFunc p_bake_step, void *p_bake_userdata) {
+ if (p_image_data_path.is_empty()) {
if (get_light_data().is_null()) {
return BAKE_ERROR_NO_SAVE_PATH;
}
@@ -640,7 +635,7 @@ BakedLightmap::BakeError BakedLightmap::bake(Node *p_from_node, String p_image_d
bsud.to_percent = 0.8;
if (p_bake_step) {
- p_bake_step(0.0, TTR("Finding meshes, lights and probes"), p_bake_userdata, true);
+ p_bake_step(0.0, RTR("Finding meshes, lights and probes"), p_bake_userdata, true);
}
/* STEP 1, FIND MESHES, LIGHTS AND PROBES */
Vector<Lightmapper::MeshData> mesh_data;
@@ -660,7 +655,7 @@ BakedLightmap::BakeError BakedLightmap::bake(Node *p_from_node, String p_image_d
for (int m_i = 0; m_i < meshes_found.size(); m_i++) {
if (p_bake_step) {
float p = (float)(m_i) / meshes_found.size();
- p_bake_step(p * 0.1, vformat(TTR("Preparing geometry %d/%d"), m_i, meshes_found.size()), p_bake_userdata, false);
+ p_bake_step(p * 0.1, vformat(RTR("Preparing geometry %d/%d"), m_i, meshes_found.size()), p_bake_userdata, false);
}
MeshesFound &mf = meshes_found.write[m_i];
@@ -717,7 +712,7 @@ BakedLightmap::BakeError BakedLightmap::bake(Node *p_from_node, String p_image_d
w_albedo[i + 3] = 255;
}
- md.albedo_on_uv2.instance();
+ md.albedo_on_uv2.instantiate();
md.albedo_on_uv2->create(lightmap_size.width, lightmap_size.height, false, Image::FORMAT_RGBA8, albedom);
}
@@ -795,7 +790,7 @@ BakedLightmap::BakeError BakedLightmap::bake(Node *p_from_node, String p_image_d
/* STEP 2, CREATE PROBES */
if (p_bake_step) {
- p_bake_step(0.3, TTR("Creating probes"), p_bake_userdata, true);
+ p_bake_step(0.3, RTR("Creating probes"), p_bake_userdata, true);
}
//bounds need to include the user probes
@@ -837,7 +832,7 @@ BakedLightmap::BakeError BakedLightmap::bake(Node *p_from_node, String p_image_d
for (int i = 0; i < mesh_data.size(); i++) {
if (p_bake_step) {
float p = (float)(i) / mesh_data.size();
- p_bake_step(0.3 + p * 0.1, vformat(TTR("Creating probes from mesh %d/%d"), i, mesh_data.size()), p_bake_userdata, false);
+ p_bake_step(0.3 + p * 0.1, vformat(RTR("Creating probes from mesh %d/%d"), i, mesh_data.size()), p_bake_userdata, false);
}
for (int j = 0; j < mesh_data[i].points.size(); j += 3) {
@@ -878,7 +873,7 @@ BakedLightmap::BakeError BakedLightmap::bake(Node *p_from_node, String p_image_d
// Add everything to lightmapper
if (p_bake_step) {
- p_bake_step(0.4, TTR("Preparing Lightmapper"), p_bake_userdata, true);
+ p_bake_step(0.4, RTR("Preparing Lightmapper"), p_bake_userdata, true);
}
{
@@ -887,17 +882,18 @@ BakedLightmap::BakeError BakedLightmap::bake(Node *p_from_node, String p_image_d
}
for (int i = 0; i < lights_found.size(); i++) {
Light3D *light = lights_found[i].light;
- Transform xf = lights_found[i].xform;
+ Transform3D xf = lights_found[i].xform;
+ Color linear_color = light->get_color().srgb_to_linear();
if (Object::cast_to<DirectionalLight3D>(light)) {
DirectionalLight3D *l = Object::cast_to<DirectionalLight3D>(light);
- lightmapper->add_directional_light(light->get_bake_mode() == Light3D::BAKE_STATIC, -xf.basis.get_axis(Vector3::AXIS_Z).normalized(), l->get_color(), l->get_param(Light3D::PARAM_ENERGY), l->get_param(Light3D::PARAM_SIZE));
+ lightmapper->add_directional_light(light->get_bake_mode() == Light3D::BAKE_STATIC, -xf.basis.get_column(Vector3::AXIS_Z).normalized(), linear_color, l->get_param(Light3D::PARAM_ENERGY), l->get_param(Light3D::PARAM_SIZE));
} else if (Object::cast_to<OmniLight3D>(light)) {
OmniLight3D *l = Object::cast_to<OmniLight3D>(light);
- lightmapper->add_omni_light(light->get_bake_mode() == Light3D::BAKE_STATIC, xf.origin, l->get_color(), l->get_param(Light3D::PARAM_ENERGY), l->get_param(Light3D::PARAM_RANGE), l->get_param(Light3D::PARAM_ATTENUATION), l->get_param(Light3D::PARAM_SIZE));
+ lightmapper->add_omni_light(light->get_bake_mode() == Light3D::BAKE_STATIC, xf.origin, linear_color, l->get_param(Light3D::PARAM_ENERGY), l->get_param(Light3D::PARAM_RANGE), l->get_param(Light3D::PARAM_ATTENUATION), l->get_param(Light3D::PARAM_SIZE));
} else if (Object::cast_to<SpotLight3D>(light)) {
SpotLight3D *l = Object::cast_to<SpotLight3D>(light);
- lightmapper->add_spot_light(light->get_bake_mode() == Light3D::BAKE_STATIC, xf.origin, -xf.basis.get_axis(Vector3::AXIS_Z).normalized(), l->get_color(), l->get_param(Light3D::PARAM_ENERGY), l->get_param(Light3D::PARAM_RANGE), l->get_param(Light3D::PARAM_ATTENUATION), l->get_param(Light3D::PARAM_SPOT_ANGLE), l->get_param(Light3D::PARAM_SPOT_ATTENUATION), l->get_param(Light3D::PARAM_SIZE));
+ lightmapper->add_spot_light(light->get_bake_mode() == Light3D::BAKE_STATIC, xf.origin, -xf.basis.get_column(Vector3::AXIS_Z).normalized(), linear_color, l->get_param(Light3D::PARAM_ENERGY), l->get_param(Light3D::PARAM_RANGE), l->get_param(Light3D::PARAM_ATTENUATION), l->get_param(Light3D::PARAM_SPOT_ANGLE), l->get_param(Light3D::PARAM_SPOT_ATTENUATION), l->get_param(Light3D::PARAM_SIZE));
}
}
for (int i = 0; i < probes_found.size(); i++) {
@@ -911,7 +907,7 @@ BakedLightmap::BakeError BakedLightmap::bake(Node *p_from_node, String p_image_d
// Add everything to lightmapper
if (environment_mode != ENVIRONMENT_MODE_DISABLED) {
if (p_bake_step) {
- p_bake_step(4.1, TTR("Preparing Environment"), p_bake_userdata, true);
+ p_bake_step(4.1, RTR("Preparing Environment"), p_bake_userdata, true);
}
environment_transform = get_global_transform().basis;
@@ -940,17 +936,13 @@ BakedLightmap::BakeError BakedLightmap::bake(Node *p_from_node, String p_image_d
} break;
case ENVIRONMENT_MODE_CUSTOM_COLOR: {
- environment_image.instance();
+ environment_image.instantiate();
environment_image->create(128, 64, false, Image::FORMAT_RGBAF);
Color c = environment_custom_color;
c.r *= environment_custom_energy;
c.g *= environment_custom_energy;
c.b *= environment_custom_energy;
- for (int i = 0; i < 128; i++) {
- for (int j = 0; j < 64; j++) {
- environment_image->set_pixel(i, j, c);
- }
- }
+ environment_image->fill(c);
} break;
}
@@ -972,7 +964,7 @@ BakedLightmap::BakeError BakedLightmap::bake(Node *p_from_node, String p_image_d
}
//we assume they are all the same, so let's create a large one for saving
Ref<Image> large_image;
- large_image.instance();
+ large_image.instantiate();
large_image->create(images[0]->get_width(), images[0]->get_height() * images.size(), false, images[0]->get_format());
@@ -984,13 +976,13 @@ BakedLightmap::BakeError BakedLightmap::bake(Node *p_from_node, String p_image_d
Ref<ConfigFile> config;
- config.instance();
+ config.instantiate();
if (FileAccess::exists(base_path + ".import")) {
config->load(base_path + ".import");
}
config->set_value("remap", "importer", "2d_array_texture");
- config->set_value("remap", "type", "StreamTexture2DArray");
+ config->set_value("remap", "type", "CompressedTexture2DArray");
if (!config->has_section_key("params", "compress/mode")) {
config->set_value("params", "compress/mode", 2); //user may want another compression, so leave it be
}
@@ -1011,13 +1003,13 @@ BakedLightmap::BakeError BakedLightmap::bake(Node *p_from_node, String p_image_d
/* POSTBAKE: Save Light Data */
- Ref<BakedLightmapData> data;
+ Ref<LightmapGIData> data;
if (get_light_data().is_valid()) {
data = get_light_data();
- set_light_data(Ref<BakedLightmapData>()); //clear
+ set_light_data(Ref<LightmapGIData>()); //clear
data->clear();
} else {
- data.instance();
+ data.instantiate();
}
data->set_light_texture(texture);
@@ -1054,7 +1046,7 @@ BakedLightmap::BakeError BakedLightmap::bake(Node *p_from_node, String p_image_d
//Obtain solved simplices
if (p_bake_step) {
- p_bake_step(0.8, TTR("Generating Probe Volumes"), p_bake_userdata, true);
+ p_bake_step(0.8, RTR("Generating Probe Volumes"), p_bake_userdata, true);
}
Vector<Delaunay3D::OutputSimplex> solved_simplices = Delaunay3D::tetrahedralize(points);
@@ -1109,7 +1101,7 @@ BakedLightmap::BakeError BakedLightmap::bake(Node *p_from_node, String p_image_d
//#define DEBUG_SIMPLICES_AS_OBJ_FILE
#ifdef DEBUG_SIMPLICES_AS_OBJ_FILE
{
- FileAccessRef f = FileAccess::open("res://bsp.obj", FileAccess::WRITE);
+ Ref<FileAccess> f = FileAccess::open("res://bsp.obj", FileAccess::WRITE);
for (uint32_t i = 0; i < bsp_simplices.size(); i++) {
f->store_line("o Simplex" + itos(i));
for (int j = 0; j < 4; j++) {
@@ -1126,7 +1118,6 @@ BakedLightmap::BakeError BakedLightmap::bake(Node *p_from_node, String p_image_d
f->store_line(vformat("f %d %d %d", 4 * i + face_order[j][0], 4 * i + face_order[j][1], 4 * i + face_order[j][2]));
}
}
- f->close();
}
#endif
@@ -1138,7 +1129,7 @@ BakedLightmap::BakeError BakedLightmap::bake(Node *p_from_node, String p_image_d
}
if (p_bake_step) {
- p_bake_step(0.9, TTR("Generating Probe Acceleration Structures"), p_bake_userdata, true);
+ p_bake_step(0.9, RTR("Generating Probe Acceleration Structures"), p_bake_userdata, true);
}
_compute_bsp_tree(points, bsp_planes, planes_tested, bsp_simplices, bsp_simplex_indices, bsp_nodes);
@@ -1158,7 +1149,7 @@ BakedLightmap::BakeError BakedLightmap::bake(Node *p_from_node, String p_image_d
}
//#define DEBUG_BSP_TREE
#ifdef DEBUG_BSP_TREE
- FileAccessRef f = FileAccess::open("res://bsp.txt", FileAccess::WRITE);
+ Ref<FileAccess> f = FileAccess::open("res://bsp.txt", FileAccess::WRITE);
for (uint32_t i = 0; i < bsp_nodes.size(); i++) {
f->store_line(itos(i) + " - plane: " + bsp_nodes[i].plane + " over: " + itos(bsp_nodes[i].over) + " under: " + itos(bsp_nodes[i].under));
}
@@ -1183,21 +1174,23 @@ BakedLightmap::BakeError BakedLightmap::bake(Node *p_from_node, String p_image_d
return BAKE_ERROR_OK;
}
-void BakedLightmap::_notification(int p_what) {
- if (p_what == NOTIFICATION_POST_ENTER_TREE) {
- if (light_data.is_valid()) {
- _assign_lightmaps();
- }
- }
+void LightmapGI::_notification(int p_what) {
+ switch (p_what) {
+ case NOTIFICATION_POST_ENTER_TREE: {
+ if (light_data.is_valid()) {
+ _assign_lightmaps();
+ }
+ } break;
- if (p_what == NOTIFICATION_EXIT_TREE) {
- if (light_data.is_valid()) {
- _clear_lightmaps();
- }
+ case NOTIFICATION_EXIT_TREE: {
+ if (light_data.is_valid()) {
+ _clear_lightmaps();
+ }
+ } break;
}
}
-void BakedLightmap::_assign_lightmaps() {
+void LightmapGI::_assign_lightmaps() {
ERR_FAIL_COND(!light_data.is_valid());
for (int i = 0; i < light_data->get_user_count(); i++) {
@@ -1216,7 +1209,7 @@ void BakedLightmap::_assign_lightmaps() {
}
}
-void BakedLightmap::_clear_lightmaps() {
+void LightmapGI::_clear_lightmaps() {
ERR_FAIL_COND(!light_data.is_valid());
for (int i = 0; i < light_data->get_user_count(); i++) {
Node *node = get_node(light_data->get_user_path(i));
@@ -1234,7 +1227,7 @@ void BakedLightmap::_clear_lightmaps() {
}
}
-void BakedLightmap::set_light_data(const Ref<BakedLightmapData> &p_data) {
+void LightmapGI::set_light_data(const Ref<LightmapGIData> &p_data) {
if (light_data.is_valid()) {
if (is_inside_tree()) {
_clear_lightmaps();
@@ -1250,174 +1243,171 @@ void BakedLightmap::set_light_data(const Ref<BakedLightmapData> &p_data) {
}
}
- update_gizmo();
+ update_gizmos();
}
-Ref<BakedLightmapData> BakedLightmap::get_light_data() const {
+Ref<LightmapGIData> LightmapGI::get_light_data() const {
return light_data;
}
-void BakedLightmap::set_bake_quality(BakeQuality p_quality) {
+void LightmapGI::set_bake_quality(BakeQuality p_quality) {
bake_quality = p_quality;
}
-BakedLightmap::BakeQuality BakedLightmap::get_bake_quality() const {
+LightmapGI::BakeQuality LightmapGI::get_bake_quality() const {
return bake_quality;
}
-AABB BakedLightmap::get_aabb() const {
+AABB LightmapGI::get_aabb() const {
return AABB();
}
-Vector<Face3> BakedLightmap::get_faces(uint32_t p_usage_flags) const {
- return Vector<Face3>();
-}
-
-void BakedLightmap::set_use_denoiser(bool p_enable) {
+void LightmapGI::set_use_denoiser(bool p_enable) {
use_denoiser = p_enable;
}
-bool BakedLightmap::is_using_denoiser() const {
+bool LightmapGI::is_using_denoiser() const {
return use_denoiser;
}
-void BakedLightmap::set_directional(bool p_enable) {
+void LightmapGI::set_directional(bool p_enable) {
directional = p_enable;
}
-bool BakedLightmap::is_directional() const {
+bool LightmapGI::is_directional() const {
return directional;
}
-void BakedLightmap::set_interior(bool p_enable) {
+void LightmapGI::set_interior(bool p_enable) {
interior = p_enable;
}
-bool BakedLightmap::is_interior() const {
+bool LightmapGI::is_interior() const {
return interior;
}
-void BakedLightmap::set_environment_mode(EnvironmentMode p_mode) {
+void LightmapGI::set_environment_mode(EnvironmentMode p_mode) {
environment_mode = p_mode;
notify_property_list_changed();
}
-BakedLightmap::EnvironmentMode BakedLightmap::get_environment_mode() const {
+LightmapGI::EnvironmentMode LightmapGI::get_environment_mode() const {
return environment_mode;
}
-void BakedLightmap::set_environment_custom_sky(const Ref<Sky> &p_sky) {
+void LightmapGI::set_environment_custom_sky(const Ref<Sky> &p_sky) {
environment_custom_sky = p_sky;
}
-Ref<Sky> BakedLightmap::get_environment_custom_sky() const {
+Ref<Sky> LightmapGI::get_environment_custom_sky() const {
return environment_custom_sky;
}
-void BakedLightmap::set_environment_custom_color(const Color &p_color) {
+void LightmapGI::set_environment_custom_color(const Color &p_color) {
environment_custom_color = p_color;
}
-Color BakedLightmap::get_environment_custom_color() const {
+Color LightmapGI::get_environment_custom_color() const {
return environment_custom_color;
}
-void BakedLightmap::set_environment_custom_energy(float p_energy) {
+void LightmapGI::set_environment_custom_energy(float p_energy) {
environment_custom_energy = p_energy;
}
-float BakedLightmap::get_environment_custom_energy() const {
+float LightmapGI::get_environment_custom_energy() const {
return environment_custom_energy;
}
-void BakedLightmap::set_bounces(int p_bounces) {
+void LightmapGI::set_bounces(int p_bounces) {
ERR_FAIL_COND(p_bounces < 0 || p_bounces > 16);
bounces = p_bounces;
}
-int BakedLightmap::get_bounces() const {
+int LightmapGI::get_bounces() const {
return bounces;
}
-void BakedLightmap::set_bias(float p_bias) {
+void LightmapGI::set_bias(float p_bias) {
ERR_FAIL_COND(p_bias < 0.00001);
bias = p_bias;
}
-float BakedLightmap::get_bias() const {
+float LightmapGI::get_bias() const {
return bias;
}
-void BakedLightmap::set_max_texture_size(int p_size) {
+void LightmapGI::set_max_texture_size(int p_size) {
ERR_FAIL_COND(p_size < 2048);
max_texture_size = p_size;
}
-int BakedLightmap::get_max_texture_size() const {
+int LightmapGI::get_max_texture_size() const {
return max_texture_size;
}
-void BakedLightmap::set_generate_probes(GenerateProbes p_generate_probes) {
+void LightmapGI::set_generate_probes(GenerateProbes p_generate_probes) {
gen_probes = p_generate_probes;
}
-BakedLightmap::GenerateProbes BakedLightmap::get_generate_probes() const {
+LightmapGI::GenerateProbes LightmapGI::get_generate_probes() const {
return gen_probes;
}
-void BakedLightmap::_validate_property(PropertyInfo &property) const {
+void LightmapGI::_validate_property(PropertyInfo &property) const {
if (property.name == "environment_custom_sky" && environment_mode != ENVIRONMENT_MODE_CUSTOM_SKY) {
- property.usage = 0;
+ property.usage = PROPERTY_USAGE_NONE;
}
if (property.name == "environment_custom_color" && environment_mode != ENVIRONMENT_MODE_CUSTOM_COLOR) {
- property.usage = 0;
+ property.usage = PROPERTY_USAGE_NONE;
}
if (property.name == "environment_custom_energy" && environment_mode != ENVIRONMENT_MODE_CUSTOM_COLOR && environment_mode != ENVIRONMENT_MODE_CUSTOM_SKY) {
- property.usage = 0;
+ property.usage = PROPERTY_USAGE_NONE;
}
+ VisualInstance3D::_validate_property(property);
}
-void BakedLightmap::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_light_data", "data"), &BakedLightmap::set_light_data);
- ClassDB::bind_method(D_METHOD("get_light_data"), &BakedLightmap::get_light_data);
+void LightmapGI::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("set_light_data", "data"), &LightmapGI::set_light_data);
+ ClassDB::bind_method(D_METHOD("get_light_data"), &LightmapGI::get_light_data);
- ClassDB::bind_method(D_METHOD("set_bake_quality", "bake_quality"), &BakedLightmap::set_bake_quality);
- ClassDB::bind_method(D_METHOD("get_bake_quality"), &BakedLightmap::get_bake_quality);
+ ClassDB::bind_method(D_METHOD("set_bake_quality", "bake_quality"), &LightmapGI::set_bake_quality);
+ ClassDB::bind_method(D_METHOD("get_bake_quality"), &LightmapGI::get_bake_quality);
- ClassDB::bind_method(D_METHOD("set_bounces", "bounces"), &BakedLightmap::set_bounces);
- ClassDB::bind_method(D_METHOD("get_bounces"), &BakedLightmap::get_bounces);
+ ClassDB::bind_method(D_METHOD("set_bounces", "bounces"), &LightmapGI::set_bounces);
+ ClassDB::bind_method(D_METHOD("get_bounces"), &LightmapGI::get_bounces);
- ClassDB::bind_method(D_METHOD("set_generate_probes", "subdivision"), &BakedLightmap::set_generate_probes);
- ClassDB::bind_method(D_METHOD("get_generate_probes"), &BakedLightmap::get_generate_probes);
+ ClassDB::bind_method(D_METHOD("set_generate_probes", "subdivision"), &LightmapGI::set_generate_probes);
+ ClassDB::bind_method(D_METHOD("get_generate_probes"), &LightmapGI::get_generate_probes);
- ClassDB::bind_method(D_METHOD("set_bias", "bias"), &BakedLightmap::set_bias);
- ClassDB::bind_method(D_METHOD("get_bias"), &BakedLightmap::get_bias);
+ ClassDB::bind_method(D_METHOD("set_bias", "bias"), &LightmapGI::set_bias);
+ ClassDB::bind_method(D_METHOD("get_bias"), &LightmapGI::get_bias);
- ClassDB::bind_method(D_METHOD("set_environment_mode", "mode"), &BakedLightmap::set_environment_mode);
- ClassDB::bind_method(D_METHOD("get_environment_mode"), &BakedLightmap::get_environment_mode);
+ ClassDB::bind_method(D_METHOD("set_environment_mode", "mode"), &LightmapGI::set_environment_mode);
+ ClassDB::bind_method(D_METHOD("get_environment_mode"), &LightmapGI::get_environment_mode);
- ClassDB::bind_method(D_METHOD("set_environment_custom_sky", "sky"), &BakedLightmap::set_environment_custom_sky);
- ClassDB::bind_method(D_METHOD("get_environment_custom_sky"), &BakedLightmap::get_environment_custom_sky);
+ ClassDB::bind_method(D_METHOD("set_environment_custom_sky", "sky"), &LightmapGI::set_environment_custom_sky);
+ ClassDB::bind_method(D_METHOD("get_environment_custom_sky"), &LightmapGI::get_environment_custom_sky);
- ClassDB::bind_method(D_METHOD("set_environment_custom_color", "color"), &BakedLightmap::set_environment_custom_color);
- ClassDB::bind_method(D_METHOD("get_environment_custom_color"), &BakedLightmap::get_environment_custom_color);
+ ClassDB::bind_method(D_METHOD("set_environment_custom_color", "color"), &LightmapGI::set_environment_custom_color);
+ ClassDB::bind_method(D_METHOD("get_environment_custom_color"), &LightmapGI::get_environment_custom_color);
- ClassDB::bind_method(D_METHOD("set_environment_custom_energy", "energy"), &BakedLightmap::set_environment_custom_energy);
- ClassDB::bind_method(D_METHOD("get_environment_custom_energy"), &BakedLightmap::get_environment_custom_energy);
+ ClassDB::bind_method(D_METHOD("set_environment_custom_energy", "energy"), &LightmapGI::set_environment_custom_energy);
+ ClassDB::bind_method(D_METHOD("get_environment_custom_energy"), &LightmapGI::get_environment_custom_energy);
- ClassDB::bind_method(D_METHOD("set_max_texture_size", "max_texture_size"), &BakedLightmap::set_max_texture_size);
- ClassDB::bind_method(D_METHOD("get_max_texture_size"), &BakedLightmap::get_max_texture_size);
+ ClassDB::bind_method(D_METHOD("set_max_texture_size", "max_texture_size"), &LightmapGI::set_max_texture_size);
+ ClassDB::bind_method(D_METHOD("get_max_texture_size"), &LightmapGI::get_max_texture_size);
- ClassDB::bind_method(D_METHOD("set_use_denoiser", "use_denoiser"), &BakedLightmap::set_use_denoiser);
- ClassDB::bind_method(D_METHOD("is_using_denoiser"), &BakedLightmap::is_using_denoiser);
+ ClassDB::bind_method(D_METHOD("set_use_denoiser", "use_denoiser"), &LightmapGI::set_use_denoiser);
+ ClassDB::bind_method(D_METHOD("is_using_denoiser"), &LightmapGI::is_using_denoiser);
- ClassDB::bind_method(D_METHOD("set_interior", "enable"), &BakedLightmap::set_interior);
- ClassDB::bind_method(D_METHOD("is_interior"), &BakedLightmap::is_interior);
+ ClassDB::bind_method(D_METHOD("set_interior", "enable"), &LightmapGI::set_interior);
+ ClassDB::bind_method(D_METHOD("is_interior"), &LightmapGI::is_interior);
- ClassDB::bind_method(D_METHOD("set_directional", "directional"), &BakedLightmap::set_directional);
- ClassDB::bind_method(D_METHOD("is_directional"), &BakedLightmap::is_directional);
+ ClassDB::bind_method(D_METHOD("set_directional", "directional"), &LightmapGI::set_directional);
+ ClassDB::bind_method(D_METHOD("is_directional"), &LightmapGI::is_directional);
- // ClassDB::bind_method(D_METHOD("bake", "from_node"), &BakedLightmap::bake, DEFVAL(Variant()));
+ // ClassDB::bind_method(D_METHOD("bake", "from_node"), &LightmapGI::bake, DEFVAL(Variant()));
ADD_GROUP("Tweaks", "");
ADD_PROPERTY(PropertyInfo(Variant::INT, "quality", PROPERTY_HINT_ENUM, "Low,Medium,High,Ultra"), "set_bake_quality", "get_bake_quality");
@@ -1435,7 +1425,7 @@ void BakedLightmap::_bind_methods() {
ADD_GROUP("Gen Probes", "generate_probes_");
ADD_PROPERTY(PropertyInfo(Variant::INT, "generate_probes_subdiv", PROPERTY_HINT_ENUM, "Disabled,4,8,16,32"), "set_generate_probes", "get_generate_probes");
ADD_GROUP("Data", "");
- ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "light_data", PROPERTY_HINT_RESOURCE_TYPE, "BakedLightmapData"), "set_light_data", "get_light_data");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "light_data", PROPERTY_HINT_RESOURCE_TYPE, "LightmapGIData"), "set_light_data", "get_light_data");
BIND_ENUM_CONSTANT(BAKE_QUALITY_LOW);
BIND_ENUM_CONSTANT(BAKE_QUALITY_MEDIUM);
@@ -1462,5 +1452,5 @@ void BakedLightmap::_bind_methods() {
BIND_ENUM_CONSTANT(ENVIRONMENT_MODE_CUSTOM_COLOR);
}
-BakedLightmap::BakedLightmap() {
+LightmapGI::LightmapGI() {
}
diff --git a/scene/3d/baked_lightmap.h b/scene/3d/lightmap_gi.h
index e2d89ab2d0..d29d7a7c28 100644
--- a/scene/3d/baked_lightmap.h
+++ b/scene/3d/lightmap_gi.h
@@ -1,12 +1,12 @@
/*************************************************************************/
-/* baked_lightmap.h */
+/* lightmap_gi.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -28,19 +28,16 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#ifndef BAKED_LIGHTMAP_H
-#define BAKED_LIGHTMAP_H
+#ifndef LIGHTMAP_GI_H
+#define LIGHTMAP_GI_H
#include "core/templates/local_vector.h"
#include "scene/3d/light_3d.h"
#include "scene/3d/lightmapper.h"
-#include "scene/3d/mesh_instance_3d.h"
-#include "scene/3d/multimesh_instance_3d.h"
#include "scene/3d/visual_instance_3d.h"
-#include "scene/resources/sky.h"
-class BakedLightmapData : public Resource {
- GDCLASS(BakedLightmapData, Resource);
+class LightmapGIData : public Resource {
+ GDCLASS(LightmapGIData, Resource);
RES_BASE_EXTENSION("lmbake")
Ref<TextureLayered> light_texture;
@@ -95,12 +92,12 @@ public:
void clear();
virtual RID get_rid() const override;
- BakedLightmapData();
- ~BakedLightmapData();
+ LightmapGIData();
+ ~LightmapGIData();
};
-class BakedLightmap : public VisualInstance3D {
- GDCLASS(BakedLightmap, VisualInstance3D);
+class LightmapGI : public VisualInstance3D {
+ GDCLASS(LightmapGI, VisualInstance3D);
public:
enum BakeQuality {
@@ -149,15 +146,15 @@ private:
bool directional = false;
GenerateProbes gen_probes = GENERATE_PROBES_DISABLED;
- Ref<BakedLightmapData> light_data;
+ Ref<LightmapGIData> light_data;
struct LightsFound {
- Transform xform;
+ Transform3D xform;
Light3D *light = nullptr;
};
struct MeshesFound {
- Transform xform;
+ Transform3D xform;
NodePath node_path;
int32_t subindex = 0;
Ref<Mesh> mesh;
@@ -230,8 +227,8 @@ protected:
void _notification(int p_what);
public:
- void set_light_data(const Ref<BakedLightmapData> &p_data);
- Ref<BakedLightmapData> get_light_data() const;
+ void set_light_data(const Ref<LightmapGIData> &p_data);
+ Ref<LightmapGIData> get_light_data() const;
void set_bake_quality(BakeQuality p_quality);
BakeQuality get_bake_quality() const;
@@ -270,15 +267,14 @@ public:
GenerateProbes get_generate_probes() const;
AABB get_aabb() const override;
- Vector<Face3> get_faces(uint32_t p_usage_flags) const override;
BakeError bake(Node *p_from_node, String p_image_data_path = "", Lightmapper::BakeStepFunc p_bake_step = nullptr, void *p_bake_userdata = nullptr);
- BakedLightmap();
+ LightmapGI();
};
-VARIANT_ENUM_CAST(BakedLightmap::BakeQuality);
-VARIANT_ENUM_CAST(BakedLightmap::GenerateProbes);
-VARIANT_ENUM_CAST(BakedLightmap::BakeError);
-VARIANT_ENUM_CAST(BakedLightmap::EnvironmentMode);
+VARIANT_ENUM_CAST(LightmapGI::BakeQuality);
+VARIANT_ENUM_CAST(LightmapGI::GenerateProbes);
+VARIANT_ENUM_CAST(LightmapGI::BakeError);
+VARIANT_ENUM_CAST(LightmapGI::EnvironmentMode);
#endif // BAKED_LIGHTMAP_H
diff --git a/scene/3d/lightmap_probe.cpp b/scene/3d/lightmap_probe.cpp
index 830b97ffab..641b0a4c48 100644
--- a/scene/3d/lightmap_probe.cpp
+++ b/scene/3d/lightmap_probe.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
diff --git a/scene/3d/lightmap_probe.h b/scene/3d/lightmap_probe.h
index df87ed49dd..11b35451a1 100644
--- a/scene/3d/lightmap_probe.h
+++ b/scene/3d/lightmap_probe.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
diff --git a/scene/3d/lightmapper.cpp b/scene/3d/lightmapper.cpp
index 9e5078ba95..8ab710d98f 100644
--- a/scene/3d/lightmapper.cpp
+++ b/scene/3d/lightmapper.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
diff --git a/scene/3d/lightmapper.h b/scene/3d/lightmapper.h
index f63515f666..f641c99ec1 100644
--- a/scene/3d/lightmapper.h
+++ b/scene/3d/lightmapper.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -31,8 +31,9 @@
#ifndef LIGHTMAPPER_H
#define LIGHTMAPPER_H
-#include "scene/resources/mesh.h"
-#include "servers/rendering/rendering_device.h"
+#include "core/object/ref_counted.h"
+
+class Image;
#if !defined(__aligned)
@@ -44,8 +45,8 @@
#endif
-class LightmapDenoiser : public Reference {
- GDCLASS(LightmapDenoiser, Reference)
+class LightmapDenoiser : public RefCounted {
+ GDCLASS(LightmapDenoiser, RefCounted)
protected:
static LightmapDenoiser *(*create_function)();
@@ -54,8 +55,8 @@ public:
static Ref<LightmapDenoiser> create();
};
-class LightmapRaycaster : public Reference {
- GDCLASS(LightmapRaycaster, Reference)
+class LightmapRaycaster : public RefCounted {
+ GDCLASS(LightmapRaycaster, RefCounted)
protected:
static LightmapRaycaster *(*create_function)();
@@ -121,8 +122,8 @@ public:
static Ref<LightmapRaycaster> create();
};
-class Lightmapper : public Reference {
- GDCLASS(Lightmapper, Reference)
+class Lightmapper : public RefCounted {
+ GDCLASS(Lightmapper, RefCounted)
public:
enum GenerateProbes {
GENERATE_PROBES_DISABLED,
diff --git a/scene/3d/mesh_instance_3d.cpp b/scene/3d/mesh_instance_3d.cpp
index c495f68890..31c33a6b61 100644
--- a/scene/3d/mesh_instance_3d.cpp
+++ b/scene/3d/mesh_instance_3d.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -33,8 +33,6 @@
#include "collision_shape_3d.h"
#include "core/core_string_names.h"
#include "physics_body_3d.h"
-#include "scene/resources/material.h"
-#include "skeleton_3d.h"
bool MeshInstance3D::_set(const StringName &p_name, const Variant &p_value) {
//this is not _too_ bad performance wise, really. it only arrives here if the property was not set anywhere else.
@@ -44,10 +42,9 @@ bool MeshInstance3D::_set(const StringName &p_name, const Variant &p_value) {
return false;
}
- Map<StringName, BlendShapeTrack>::Element *E = blend_shape_tracks.find(p_name);
+ Map<StringName, int>::Element *E = blend_shape_properties.find(p_name);
if (E) {
- E->get().value = p_value;
- RenderingServer::get_singleton()->instance_set_blend_shape_weight(get_instance(), E->get().idx, E->get().value);
+ set_blend_shape_value(E->get(), p_value);
return true;
}
@@ -69,9 +66,9 @@ bool MeshInstance3D::_get(const StringName &p_name, Variant &r_ret) const {
return false;
}
- const Map<StringName, BlendShapeTrack>::Element *E = blend_shape_tracks.find(p_name);
+ const Map<StringName, int>::Element *E = blend_shape_properties.find(p_name);
if (E) {
- r_ret = E->get().value;
+ r_ret = get_blend_shape_value(E->get());
return true;
}
@@ -88,19 +85,19 @@ bool MeshInstance3D::_get(const StringName &p_name, Variant &r_ret) const {
void MeshInstance3D::_get_property_list(List<PropertyInfo> *p_list) const {
List<String> ls;
- for (const Map<StringName, BlendShapeTrack>::Element *E = blend_shape_tracks.front(); E; E = E->next()) {
- ls.push_back(E->key());
+ for (const KeyValue<StringName, int> &E : blend_shape_properties) {
+ ls.push_back(E.key);
}
ls.sort();
- for (List<String>::Element *E = ls.front(); E; E = E->next()) {
- p_list->push_back(PropertyInfo(Variant::FLOAT, E->get(), PROPERTY_HINT_RANGE, "-1,1,0.00001"));
+ for (const String &E : ls) {
+ p_list->push_back(PropertyInfo(Variant::FLOAT, E, PROPERTY_HINT_RANGE, "-1,1,0.00001"));
}
if (mesh.is_valid()) {
for (int i = 0; i < mesh->get_surface_count(); i++) {
- p_list->push_back(PropertyInfo(Variant::OBJECT, "surface_material_override/" + itos(i), PROPERTY_HINT_RESOURCE_TYPE, "ShaderMaterial,StandardMaterial3D", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_DEFERRED_SET_RESOURCE));
+ p_list->push_back(PropertyInfo(Variant::OBJECT, "surface_material_override/" + itos(i), PROPERTY_HINT_RESOURCE_TYPE, "BaseMaterial3D,ShaderMaterial", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_DEFERRED_SET_RESOURCE));
}
}
}
@@ -116,25 +113,17 @@ void MeshInstance3D::set_mesh(const Ref<Mesh> &p_mesh) {
mesh = p_mesh;
- blend_shape_tracks.clear();
if (mesh.is_valid()) {
- for (int i = 0; i < mesh->get_blend_shape_count(); i++) {
- BlendShapeTrack mt;
- mt.idx = i;
- mt.value = 0;
- blend_shape_tracks["blend_shapes/" + String(mesh->get_blend_shape_name(i))] = mt;
- }
-
mesh->connect(CoreStringNames::get_singleton()->changed, callable_mp(this, &MeshInstance3D::_mesh_changed));
- surface_override_materials.resize(mesh->get_surface_count());
-
+ _mesh_changed();
set_base(mesh->get_rid());
} else {
+ blend_shape_tracks.clear();
+ blend_shape_properties.clear();
set_base(RID());
+ update_gizmos();
}
- update_gizmo();
-
notify_property_list_changed();
}
@@ -142,17 +131,48 @@ Ref<Mesh> MeshInstance3D::get_mesh() const {
return mesh;
}
+int MeshInstance3D::get_blend_shape_count() const {
+ if (mesh.is_null()) {
+ return 0;
+ }
+ return mesh->get_blend_shape_count();
+}
+int MeshInstance3D::find_blend_shape_by_name(const StringName &p_name) {
+ if (mesh.is_null()) {
+ return -1;
+ }
+ for (int i = 0; i < mesh->get_blend_shape_count(); i++) {
+ if (mesh->get_blend_shape_name(i) == p_name) {
+ return i;
+ }
+ }
+ return -1;
+}
+float MeshInstance3D::get_blend_shape_value(int p_blend_shape) const {
+ ERR_FAIL_COND_V(mesh.is_null(), 0.0);
+ ERR_FAIL_INDEX_V(p_blend_shape, (int)blend_shape_tracks.size(), 0);
+ return blend_shape_tracks[p_blend_shape];
+}
+void MeshInstance3D::set_blend_shape_value(int p_blend_shape, float p_value) {
+ ERR_FAIL_COND(mesh.is_null());
+ ERR_FAIL_INDEX(p_blend_shape, (int)blend_shape_tracks.size());
+ blend_shape_tracks[p_blend_shape] = p_value;
+ RenderingServer::get_singleton()->instance_set_blend_shape_weight(get_instance(), p_blend_shape, p_value);
+}
+
void MeshInstance3D::_resolve_skeleton_path() {
Ref<SkinReference> new_skin_reference;
if (!skeleton_path.is_empty()) {
Skeleton3D *skeleton = Object::cast_to<Skeleton3D>(get_node(skeleton_path));
if (skeleton) {
- new_skin_reference = skeleton->register_skin(skin_internal);
if (skin_internal.is_null()) {
+ new_skin_reference = skeleton->register_skin(skeleton->create_skin_from_rest_transforms());
//a skin was created for us
skin_internal = new_skin_reference->get_skin();
notify_property_list_changed();
+ } else {
+ new_skin_reference = skeleton->register_skin(skin_internal);
}
}
}
@@ -199,18 +219,6 @@ AABB MeshInstance3D::get_aabb() const {
return AABB();
}
-Vector<Face3> MeshInstance3D::get_faces(uint32_t p_usage_flags) const {
- if (!(p_usage_flags & (FACES_SOLID | FACES_ENCLOSING))) {
- return Vector<Face3>();
- }
-
- if (mesh.is_null()) {
- return Vector<Face3>();
- }
-
- return mesh->get_faces();
-}
-
Node *MeshInstance3D::create_trimesh_collision_node() {
if (mesh.is_null()) {
return nullptr;
@@ -224,7 +232,7 @@ Node *MeshInstance3D::create_trimesh_collision_node() {
StaticBody3D *static_body = memnew(StaticBody3D);
CollisionShape3D *cshape = memnew(CollisionShape3D);
cshape->set_shape(shape);
- static_body->add_child(cshape);
+ static_body->add_child(cshape, true);
return static_body;
}
@@ -233,7 +241,7 @@ void MeshInstance3D::create_trimesh_collision() {
ERR_FAIL_COND(!static_body);
static_body->set_name(String(get_name()) + "_col");
- add_child(static_body);
+ add_child(static_body, true);
if (get_owner()) {
CollisionShape3D *cshape = Object::cast_to<CollisionShape3D>(static_body->get_child(0));
static_body->set_owner(get_owner());
@@ -241,12 +249,12 @@ void MeshInstance3D::create_trimesh_collision() {
}
}
-Node *MeshInstance3D::create_convex_collision_node() {
+Node *MeshInstance3D::create_convex_collision_node(bool p_clean, bool p_simplify) {
if (mesh.is_null()) {
return nullptr;
}
- Ref<Shape3D> shape = mesh->create_convex_shape();
+ Ref<Shape3D> shape = mesh->create_convex_shape(p_clean, p_simplify);
if (shape.is_null()) {
return nullptr;
}
@@ -254,16 +262,16 @@ Node *MeshInstance3D::create_convex_collision_node() {
StaticBody3D *static_body = memnew(StaticBody3D);
CollisionShape3D *cshape = memnew(CollisionShape3D);
cshape->set_shape(shape);
- static_body->add_child(cshape);
+ static_body->add_child(cshape, true);
return static_body;
}
-void MeshInstance3D::create_convex_collision() {
- StaticBody3D *static_body = Object::cast_to<StaticBody3D>(create_convex_collision_node());
+void MeshInstance3D::create_convex_collision(bool p_clean, bool p_simplify) {
+ StaticBody3D *static_body = Object::cast_to<StaticBody3D>(create_convex_collision_node(p_clean, p_simplify));
ERR_FAIL_COND(!static_body);
static_body->set_name(String(get_name()) + "_col");
- add_child(static_body);
+ add_child(static_body, true);
if (get_owner()) {
CollisionShape3D *cshape = Object::cast_to<CollisionShape3D>(static_body->get_child(0));
static_body->set_owner(get_owner());
@@ -276,7 +284,8 @@ Node *MeshInstance3D::create_multiple_convex_collisions_node() {
return nullptr;
}
- Vector<Ref<Shape3D>> shapes = mesh->convex_decompose();
+ Mesh::ConvexDecompositionSettings settings;
+ Vector<Ref<Shape3D>> shapes = mesh->convex_decompose(settings);
if (!shapes.size()) {
return nullptr;
}
@@ -285,7 +294,7 @@ Node *MeshInstance3D::create_multiple_convex_collisions_node() {
for (int i = 0; i < shapes.size(); i++) {
CollisionShape3D *cshape = memnew(CollisionShape3D);
cshape->set_shape(shapes[i]);
- static_body->add_child(cshape);
+ static_body->add_child(cshape, true);
}
return static_body;
}
@@ -295,7 +304,7 @@ void MeshInstance3D::create_multiple_convex_collisions() {
ERR_FAIL_COND(!static_body);
static_body->set_name(String(get_name()) + "_col");
- add_child(static_body);
+ add_child(static_body, true);
if (get_owner()) {
static_body->set_owner(get_owner());
int count = static_body->get_child_count();
@@ -307,8 +316,10 @@ void MeshInstance3D::create_multiple_convex_collisions() {
}
void MeshInstance3D::_notification(int p_what) {
- if (p_what == NOTIFICATION_ENTER_TREE) {
- _resolve_skeleton_path();
+ switch (p_what) {
+ case NOTIFICATION_ENTER_TREE: {
+ _resolve_skeleton_path();
+ } break;
}
}
@@ -356,7 +367,20 @@ Ref<Material> MeshInstance3D::get_active_material(int p_surface) const {
void MeshInstance3D::_mesh_changed() {
ERR_FAIL_COND(mesh.is_null());
surface_override_materials.resize(mesh->get_surface_count());
- update_gizmo();
+
+ uint32_t initialize_bs_from = blend_shape_tracks.size();
+ blend_shape_tracks.resize(mesh->get_blend_shape_count());
+
+ for (uint32_t i = 0; i < blend_shape_tracks.size(); i++) {
+ blend_shape_properties["blend_shapes/" + String(mesh->get_blend_shape_name(i))] = i;
+ if (i < initialize_bs_from) {
+ set_blend_shape_value(i, blend_shape_tracks[i]);
+ } else {
+ set_blend_shape_value(i, 0);
+ }
+ }
+
+ update_gizmos();
}
void MeshInstance3D::create_debug_tangents() {
@@ -370,6 +394,8 @@ void MeshInstance3D::create_debug_tangents() {
for (int i = 0; i < mesh->get_surface_count(); i++) {
Array arrays = mesh->surface_get_arrays(i);
+ ERR_CONTINUE(arrays.size() != Mesh::ARRAY_MAX);
+
Vector<Vector3> verts = arrays[Mesh::ARRAY_VERTEX];
Vector<Vector3> norms = arrays[Mesh::ARRAY_NORMAL];
if (norms.size() == 0) {
@@ -405,14 +431,14 @@ void MeshInstance3D::create_debug_tangents() {
if (lines.size()) {
Ref<StandardMaterial3D> sm;
- sm.instance();
+ sm.instantiate();
sm->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED);
sm->set_flag(StandardMaterial3D::FLAG_SRGB_VERTEX_COLOR, true);
sm->set_flag(StandardMaterial3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
Ref<ArrayMesh> am;
- am.instance();
+ am.instantiate();
Array a;
a.resize(Mesh::ARRAY_MAX);
a[Mesh::ARRAY_VERTEX] = lines;
@@ -424,7 +450,7 @@ void MeshInstance3D::create_debug_tangents() {
MeshInstance3D *mi = memnew(MeshInstance3D);
mi->set_mesh(am);
mi->set_name("DebugTangents");
- add_child(mi);
+ add_child(mi, true);
#ifdef TOOLS_ENABLED
if (is_inside_tree() && this == get_tree()->get_edited_scene_root()) {
@@ -451,11 +477,16 @@ void MeshInstance3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("create_trimesh_collision"), &MeshInstance3D::create_trimesh_collision);
ClassDB::set_method_flags("MeshInstance3D", "create_trimesh_collision", METHOD_FLAGS_DEFAULT);
- ClassDB::bind_method(D_METHOD("create_convex_collision"), &MeshInstance3D::create_convex_collision);
+ ClassDB::bind_method(D_METHOD("create_convex_collision", "clean", "simplify"), &MeshInstance3D::create_convex_collision, DEFVAL(true), DEFVAL(false));
ClassDB::set_method_flags("MeshInstance3D", "create_convex_collision", METHOD_FLAGS_DEFAULT);
ClassDB::bind_method(D_METHOD("create_multiple_convex_collisions"), &MeshInstance3D::create_multiple_convex_collisions);
ClassDB::set_method_flags("MeshInstance3D", "create_multiple_convex_collisions", METHOD_FLAGS_DEFAULT);
+ ClassDB::bind_method(D_METHOD("get_blend_shape_count"), &MeshInstance3D::get_blend_shape_count);
+ ClassDB::bind_method(D_METHOD("find_blend_shape_by_name", "name"), &MeshInstance3D::find_blend_shape_by_name);
+ ClassDB::bind_method(D_METHOD("get_blend_shape_value", "blend_shape_idx"), &MeshInstance3D::get_blend_shape_value);
+ ClassDB::bind_method(D_METHOD("set_blend_shape_value", "blend_shape_idx", "value"), &MeshInstance3D::set_blend_shape_value);
+
ClassDB::bind_method(D_METHOD("create_debug_tangents"), &MeshInstance3D::create_debug_tangents);
ClassDB::set_method_flags("MeshInstance3D", "create_debug_tangents", METHOD_FLAGS_DEFAULT | METHOD_FLAG_EDITOR);
diff --git a/scene/3d/mesh_instance_3d.h b/scene/3d/mesh_instance_3d.h
index 9dea5804e0..0bf5c32410 100644
--- a/scene/3d/mesh_instance_3d.h
+++ b/scene/3d/mesh_instance_3d.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -31,10 +31,10 @@
#ifndef MESH_INSTANCE_H
#define MESH_INSTANCE_H
-#include "scene/3d/skeleton_3d.h"
+#include "core/templates/local_vector.h"
#include "scene/3d/visual_instance_3d.h"
-#include "scene/resources/mesh.h"
-#include "scene/resources/skin.h"
+class Skin;
+class SkinReference;
class MeshInstance3D : public GeometryInstance3D {
GDCLASS(MeshInstance3D, GeometryInstance3D);
@@ -46,12 +46,8 @@ protected:
Ref<SkinReference> skin_ref;
NodePath skeleton_path = NodePath("..");
- struct BlendShapeTrack {
- int idx = 0;
- float value = 0.0;
- };
-
- Map<StringName, BlendShapeTrack> blend_shape_tracks;
+ LocalVector<float> blend_shape_tracks;
+ Map<StringName, int> blend_shape_properties;
Vector<Ref<Material>> surface_override_materials;
void _mesh_changed();
@@ -75,6 +71,11 @@ public:
void set_skeleton_path(const NodePath &p_skeleton);
NodePath get_skeleton_path();
+ int get_blend_shape_count() const;
+ int find_blend_shape_by_name(const StringName &p_name);
+ float get_blend_shape_value(int p_blend_shape) const;
+ void set_blend_shape_value(int p_blend_shape, float p_value);
+
int get_surface_override_material_count() const;
void set_surface_override_material(int p_surface, const Ref<Material> &p_material);
Ref<Material> get_surface_override_material(int p_surface) const;
@@ -83,8 +84,8 @@ public:
Node *create_trimesh_collision_node();
void create_trimesh_collision();
- Node *create_convex_collision_node();
- void create_convex_collision();
+ Node *create_convex_collision_node(bool p_clean = true, bool p_simplify = false);
+ void create_convex_collision(bool p_clean = true, bool p_simplify = false);
Node *create_multiple_convex_collisions_node();
void create_multiple_convex_collisions();
@@ -92,7 +93,6 @@ public:
void create_debug_tangents();
virtual AABB get_aabb() const override;
- virtual Vector<Face3> get_faces(uint32_t p_usage_flags) const override;
MeshInstance3D();
~MeshInstance3D();
diff --git a/scene/3d/multimesh_instance_3d.cpp b/scene/3d/multimesh_instance_3d.cpp
index 2adef115cf..d197388fad 100644
--- a/scene/3d/multimesh_instance_3d.cpp
+++ b/scene/3d/multimesh_instance_3d.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -49,10 +49,6 @@ Ref<MultiMesh> MultiMeshInstance3D::get_multimesh() const {
return multimesh;
}
-Vector<Face3> MultiMeshInstance3D::get_faces(uint32_t p_usage_flags) const {
- return Vector<Face3>();
-}
-
AABB MultiMeshInstance3D::get_aabb() const {
if (multimesh.is_null()) {
return AABB();
diff --git a/scene/3d/multimesh_instance_3d.h b/scene/3d/multimesh_instance_3d.h
index 63735fd3a6..111f1e9c09 100644
--- a/scene/3d/multimesh_instance_3d.h
+++ b/scene/3d/multimesh_instance_3d.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -44,8 +44,6 @@ protected:
// bind helpers
public:
- virtual Vector<Face3> get_faces(uint32_t p_usage_flags) const override;
-
void set_multimesh(const Ref<MultiMesh> &p_multimesh);
Ref<MultiMesh> get_multimesh() const;
diff --git a/scene/3d/navigation_agent_3d.cpp b/scene/3d/navigation_agent_3d.cpp
index 64cfe4dca7..86c11b3789 100644
--- a/scene/3d/navigation_agent_3d.cpp
+++ b/scene/3d/navigation_agent_3d.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -30,7 +30,6 @@
#include "navigation_agent_3d.h"
-#include "core/config/engine.h"
#include "servers/navigation_server_3d.h"
void NavigationAgent3D::_bind_methods() {
@@ -63,6 +62,9 @@ void NavigationAgent3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_path_max_distance", "max_speed"), &NavigationAgent3D::set_path_max_distance);
ClassDB::bind_method(D_METHOD("get_path_max_distance"), &NavigationAgent3D::get_path_max_distance);
+ ClassDB::bind_method(D_METHOD("set_navigable_layers", "navigable_layers"), &NavigationAgent3D::set_navigable_layers);
+ ClassDB::bind_method(D_METHOD("get_navigable_layers"), &NavigationAgent3D::get_navigable_layers);
+
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("get_next_location"), &NavigationAgent3D::get_next_location);
@@ -86,6 +88,7 @@ void NavigationAgent3D::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "max_speed", PROPERTY_HINT_RANGE, "0.1,10000,0.01"), "set_max_speed", "get_max_speed");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "path_max_distance", PROPERTY_HINT_RANGE, "0.01,100,0.1"), "set_path_max_distance", "get_path_max_distance");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "ignore_y"), "set_ignore_y", "get_ignore_y");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "navigable_layers", PROPERTY_HINT_LAYERS_3D_NAVIGATION), "set_navigable_layers", "get_navigable_layers");
ADD_SIGNAL(MethodInfo("path_changed"));
ADD_SIGNAL(MethodInfo("target_reached"));
@@ -104,10 +107,12 @@ void NavigationAgent3D::_notification(int p_what) {
}
set_physics_process_internal(true);
} break;
+
case NOTIFICATION_EXIT_TREE: {
agent_parent = nullptr;
set_physics_process_internal(false);
} break;
+
case NOTIFICATION_INTERNAL_PHYSICS_PROCESS: {
if (agent_parent) {
NavigationServer3D::get_singleton()->agent_set_position(agent, agent_parent->get_global_transform().origin);
@@ -132,6 +137,18 @@ NavigationAgent3D::~NavigationAgent3D() {
agent = RID(); // Pointless
}
+void NavigationAgent3D::set_navigable_layers(uint32_t p_layers) {
+ bool layers_changed = navigable_layers != p_layers;
+ navigable_layers = p_layers;
+ if (layers_changed) {
+ _request_repath();
+ }
+}
+
+uint32_t NavigationAgent3D::get_navigable_layers() const {
+ return navigable_layers;
+}
+
void NavigationAgent3D::set_target_desired_distance(real_t p_dd) {
target_desired_distance = p_dd;
}
@@ -180,10 +197,7 @@ real_t NavigationAgent3D::get_path_max_distance() {
void NavigationAgent3D::set_target_location(Vector3 p_location) {
target_location = p_location;
- navigation_path.clear();
- target_reached = false;
- navigation_finished = false;
- update_frame_id = 0;
+ _request_repath();
}
Vector3 NavigationAgent3D::get_target_location() const {
@@ -193,7 +207,7 @@ Vector3 NavigationAgent3D::get_target_location() const {
Vector3 NavigationAgent3D::get_next_location() {
update_navigation();
if (navigation_path.size() == 0) {
- ERR_FAIL_COND_V(agent_parent == nullptr, Vector3());
+ ERR_FAIL_COND_V_MSG(agent_parent == nullptr, Vector3(), "The agent has no parent.");
return agent_parent->get_global_transform().origin;
} else {
return navigation_path[nav_path_index] - Vector3(0, navigation_height_offset, 0);
@@ -201,7 +215,7 @@ Vector3 NavigationAgent3D::get_next_location() {
}
real_t NavigationAgent3D::distance_to_target() const {
- ERR_FAIL_COND_V(agent_parent == nullptr, 0.0);
+ 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);
}
@@ -242,14 +256,14 @@ void NavigationAgent3D::_avoidance_done(Vector3 p_new_velocity) {
}
velocity_submitted = false;
- emit_signal("velocity_computed", p_new_velocity);
+ emit_signal(SNAME("velocity_computed"), p_new_velocity);
}
TypedArray<String> NavigationAgent3D::get_configuration_warnings() const {
TypedArray<String> warnings = Node::get_configuration_warnings();
if (!Object::cast_to<Node3D>(get_parent())) {
- warnings.push_back(TTR("The NavigationAgent3D can be used only under a spatial node."));
+ warnings.push_back(RTR("The NavigationAgent3D can be used only under a spatial node."));
}
return warnings;
@@ -293,10 +307,10 @@ void NavigationAgent3D::update_navigation() {
}
if (reload_path) {
- navigation_path = NavigationServer3D::get_singleton()->map_get_path(agent_parent->get_world_3d()->get_navigation_map(), o, target_location, true);
+ navigation_path = NavigationServer3D::get_singleton()->map_get_path(agent_parent->get_world_3d()->get_navigation_map(), o, target_location, true, navigable_layers);
navigation_finished = false;
nav_path_index = 0;
- emit_signal("path_changed");
+ emit_signal(SNAME("path_changed"));
}
if (navigation_path.size() == 0) {
@@ -312,17 +326,24 @@ void NavigationAgent3D::update_navigation() {
_check_distance_to_target();
nav_path_index -= 1;
navigation_finished = true;
- emit_signal("navigation_finished");
+ emit_signal(SNAME("navigation_finished"));
break;
}
}
}
}
+void NavigationAgent3D::_request_repath() {
+ navigation_path.clear();
+ target_reached = false;
+ navigation_finished = false;
+ update_frame_id = 0;
+}
+
void NavigationAgent3D::_check_distance_to_target() {
if (!target_reached) {
if (distance_to_target() < target_desired_distance) {
- emit_signal("target_reached");
+ emit_signal(SNAME("target_reached"));
target_reached = true;
}
}
diff --git a/scene/3d/navigation_agent_3d.h b/scene/3d/navigation_agent_3d.h
index 56da2d1acf..283b99a24f 100644
--- a/scene/3d/navigation_agent_3d.h
+++ b/scene/3d/navigation_agent_3d.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -31,7 +31,6 @@
#ifndef NAVIGATION_AGENT_H
#define NAVIGATION_AGENT_H
-#include "core/templates/vector.h"
#include "scene/main/node.h"
class Node3D;
@@ -43,20 +42,22 @@ class NavigationAgent3D : public Node {
RID agent;
+ uint32_t navigable_layers = 1;
+
real_t target_desired_distance = 1.0;
- real_t radius;
+ real_t radius = 0.0;
real_t navigation_height_offset = 0.0;
- bool ignore_y;
- real_t neighbor_dist;
- int max_neighbors;
- real_t time_horizon;
- real_t max_speed;
+ bool ignore_y = false;
+ real_t neighbor_dist = 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;
Vector3 target_location;
Vector<Vector3> navigation_path;
- int nav_path_index;
+ int nav_path_index = 0;
bool velocity_submitted = false;
Vector3 prev_safe_velocity;
/// The submitted target velocity
@@ -64,7 +65,7 @@ class NavigationAgent3D : public Node {
bool target_reached = false;
bool navigation_finished = true;
// No initialized on purpose
- uint32_t update_frame_id;
+ uint32_t update_frame_id = 0;
protected:
static void _bind_methods();
@@ -78,6 +79,9 @@ public:
return agent;
}
+ void set_navigable_layers(uint32_t p_layers);
+ uint32_t get_navigable_layers() const;
+
void set_target_desired_distance(real_t p_dd);
real_t get_target_desired_distance() const {
return target_desired_distance;
@@ -147,6 +151,7 @@ public:
private:
void update_navigation();
+ void _request_repath();
void _check_distance_to_target();
};
diff --git a/scene/3d/navigation_obstacle_3d.cpp b/scene/3d/navigation_obstacle_3d.cpp
index 20ffc3b00e..78dbecc0c5 100644
--- a/scene/3d/navigation_obstacle_3d.cpp
+++ b/scene/3d/navigation_obstacle_3d.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -35,23 +35,49 @@
#include "servers/navigation_server_3d.h"
void NavigationObstacle3D::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("set_estimate_radius", "estimate_radius"), &NavigationObstacle3D::set_estimate_radius);
+ ClassDB::bind_method(D_METHOD("is_radius_estimated"), &NavigationObstacle3D::is_radius_estimated);
+ ClassDB::bind_method(D_METHOD("set_radius", "radius"), &NavigationObstacle3D::set_radius);
+ ClassDB::bind_method(D_METHOD("get_radius"), &NavigationObstacle3D::get_radius);
+
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "estimate_radius"), "set_estimate_radius", "is_radius_estimated");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "radius", PROPERTY_HINT_RANGE, "0.01,100,0.01"), "set_radius", "get_radius");
+}
+
+void NavigationObstacle3D::_validate_property(PropertyInfo &p_property) const {
+ if (p_property.name == "radius") {
+ if (estimate_radius) {
+ p_property.usage = PROPERTY_USAGE_NO_EDITOR;
+ }
+ }
}
void NavigationObstacle3D::_notification(int p_what) {
switch (p_what) {
- case NOTIFICATION_READY: {
+ case NOTIFICATION_ENTER_TREE: {
+ parent_node3d = Object::cast_to<Node3D>(get_parent());
+ reevaluate_agent_radius();
+ if (parent_node3d != nullptr) {
+ // place agent on navigation map first or else the RVO agent callback creation fails silently later
+ NavigationServer3D::get_singleton()->agent_set_map(get_rid(), parent_node3d->get_world_3d()->get_navigation_map());
+ }
set_physics_process_internal(true);
} break;
+
case NOTIFICATION_EXIT_TREE: {
+ parent_node3d = nullptr;
set_physics_process_internal(false);
} break;
+
case NOTIFICATION_PARENTED: {
parent_node3d = Object::cast_to<Node3D>(get_parent());
- update_agent_shape();
+ reevaluate_agent_radius();
} break;
+
case NOTIFICATION_UNPARENTED: {
parent_node3d = nullptr;
} break;
+
case NOTIFICATION_INTERNAL_PHYSICS_PROCESS: {
if (parent_node3d) {
NavigationServer3D::get_singleton()->agent_set_position(agent, parent_node3d->get_global_transform().origin);
@@ -69,6 +95,7 @@ void NavigationObstacle3D::_notification(int p_what) {
NavigationObstacle3D::NavigationObstacle3D() {
agent = NavigationServer3D::get_singleton()->agent_create();
+ initialize_agent();
}
NavigationObstacle3D::~NavigationObstacle3D() {
@@ -80,13 +107,28 @@ TypedArray<String> NavigationObstacle3D::get_configuration_warnings() const {
TypedArray<String> warnings = Node::get_configuration_warnings();
if (!Object::cast_to<Node3D>(get_parent())) {
- warnings.push_back(TTR("The NavigationObstacle3D only serves to provide collision avoidance to a spatial object."));
+ warnings.push_back(RTR("The NavigationObstacle3D only serves to provide collision avoidance to a spatial object."));
}
return warnings;
}
-void NavigationObstacle3D::update_agent_shape() {
+void NavigationObstacle3D::initialize_agent() {
+ NavigationServer3D::get_singleton()->agent_set_neighbor_dist(agent, 0.0);
+ NavigationServer3D::get_singleton()->agent_set_max_neighbors(agent, 0);
+ NavigationServer3D::get_singleton()->agent_set_time_horizon(agent, 0.0);
+ NavigationServer3D::get_singleton()->agent_set_max_speed(agent, 0.0);
+}
+
+void NavigationObstacle3D::reevaluate_agent_radius() {
+ if (!estimate_radius) {
+ NavigationServer3D::get_singleton()->agent_set_radius(agent, radius);
+ } else if (parent_node3d && parent_node3d->is_inside_tree()) {
+ NavigationServer3D::get_singleton()->agent_set_radius(agent, estimate_agent_radius());
+ }
+}
+
+real_t NavigationObstacle3D::estimate_agent_radius() const {
if (parent_node3d) {
// Estimate the radius of this physics body
real_t radius = 0.0;
@@ -110,15 +152,21 @@ void NavigationObstacle3D::update_agent_shape() {
Vector3 s = parent_node3d->get_global_transform().basis.get_scale();
radius *= MAX(s.x, MAX(s.y, s.z));
- if (radius == 0.0) {
- radius = 1.0; // Never a 0 radius
+ if (radius > 0.0) {
+ return radius;
}
-
- // Initialize the Agent as an object
- NavigationServer3D::get_singleton()->agent_set_neighbor_dist(agent, 0.0);
- NavigationServer3D::get_singleton()->agent_set_max_neighbors(agent, 0);
- NavigationServer3D::get_singleton()->agent_set_time_horizon(agent, 0.0);
- NavigationServer3D::get_singleton()->agent_set_radius(agent, radius);
- NavigationServer3D::get_singleton()->agent_set_max_speed(agent, 0.0);
}
+ return 1.0; // Never a 0 radius
+}
+
+void NavigationObstacle3D::set_estimate_radius(bool p_estimate_radius) {
+ 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.");
+ radius = p_radius;
+ reevaluate_agent_radius();
}
diff --git a/scene/3d/navigation_obstacle_3d.h b/scene/3d/navigation_obstacle_3d.h
index 2f78f624a4..542d603a0a 100644
--- a/scene/3d/navigation_obstacle_3d.h
+++ b/scene/3d/navigation_obstacle_3d.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -32,7 +32,6 @@
#define NAVIGATION_OBSTACLE_H
#include "scene/3d/node_3d.h"
-#include "scene/main/node.h"
class NavigationObstacle3D : public Node {
GDCLASS(NavigationObstacle3D, Node);
@@ -40,8 +39,12 @@ class NavigationObstacle3D : public Node {
Node3D *parent_node3d = nullptr;
RID agent;
+ bool estimate_radius = true;
+ real_t radius = 1.0;
+
protected:
static void _bind_methods();
+ void _validate_property(PropertyInfo &p_property) const override;
void _notification(int p_what);
public:
@@ -52,10 +55,21 @@ public:
return agent;
}
+ void set_estimate_radius(bool p_estimate_radius);
+ bool is_radius_estimated() const {
+ return estimate_radius;
+ }
+ void set_radius(real_t p_radius);
+ real_t get_radius() const {
+ return radius;
+ }
+
TypedArray<String> get_configuration_warnings() const override;
private:
- void update_agent_shape();
+ void initialize_agent();
+ void reevaluate_agent_radius();
+ real_t estimate_agent_radius() const;
};
#endif
diff --git a/scene/3d/navigation_region_3d.cpp b/scene/3d/navigation_region_3d.cpp
index 0afad62404..80be770dfc 100644
--- a/scene/3d/navigation_region_3d.cpp
+++ b/scene/3d/navigation_region_3d.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -30,7 +30,6 @@
#include "navigation_region_3d.h"
-#include "core/os/thread.h"
#include "mesh_instance_3d.h"
#include "servers/navigation_server_3d.h"
@@ -59,7 +58,7 @@ void NavigationRegion3D::set_enabled(bool p_enabled) {
}
}
- update_gizmo();
+ update_gizmos();
}
bool NavigationRegion3D::is_enabled() const {
@@ -74,6 +73,10 @@ uint32_t NavigationRegion3D::get_layers() const {
return NavigationServer3D::get_singleton()->region_get_layers(region);
}
+RID NavigationRegion3D::get_region_rid() const {
+ return region;
+}
+
/////////////////////////////
void NavigationRegion3D::_notification(int p_what) {
@@ -94,12 +97,12 @@ void NavigationRegion3D::_notification(int p_what) {
add_child(dm);
debug_view = dm;
}
-
} break;
+
case NOTIFICATION_TRANSFORM_CHANGED: {
NavigationServer3D::get_singleton()->region_set_transform(region, get_global_transform());
-
} break;
+
case NOTIFICATION_EXIT_TREE: {
NavigationServer3D::get_singleton()->region_set_map(region, RID());
@@ -132,9 +135,9 @@ void NavigationRegion3D::set_navigation_mesh(const Ref<NavigationMesh> &p_navmes
Object::cast_to<MeshInstance3D>(debug_view)->set_mesh(navmesh->get_debug_mesh());
}
- emit_signal("navigation_mesh_changed");
+ emit_signal(SNAME("navigation_mesh_changed"));
- update_gizmo();
+ update_gizmos();
update_configuration_warnings();
}
@@ -153,28 +156,32 @@ void _bake_navigation_mesh(void *p_user_data) {
Ref<NavigationMesh> nav_mesh = args->nav_region->get_navigation_mesh()->duplicate();
NavigationServer3D::get_singleton()->region_bake_navmesh(nav_mesh, args->nav_region);
- args->nav_region->call_deferred("_bake_finished", nav_mesh);
+ args->nav_region->call_deferred(SNAME("_bake_finished"), nav_mesh);
memdelete(args);
} else {
ERR_PRINT("Can't bake the navigation mesh if the `NavigationMesh` resource doesn't exist");
- args->nav_region->call_deferred("_bake_finished", Ref<NavigationMesh>());
+ args->nav_region->call_deferred(SNAME("_bake_finished"), Ref<NavigationMesh>());
memdelete(args);
}
}
-void NavigationRegion3D::bake_navigation_mesh() {
- ERR_FAIL_COND(bake_thread.is_started());
+void NavigationRegion3D::bake_navigation_mesh(bool p_on_thread) {
+ ERR_FAIL_COND_MSG(bake_thread.is_started(), "Unable to start another bake request. The navigation mesh bake thread is already baking a navigation mesh.");
BakeThreadsArgs *args = memnew(BakeThreadsArgs);
args->nav_region = this;
- bake_thread.start(_bake_navigation_mesh, args);
+ if (p_on_thread) {
+ bake_thread.start(_bake_navigation_mesh, args);
+ } else {
+ _bake_navigation_mesh(args);
+ }
}
void NavigationRegion3D::_bake_finished(Ref<NavigationMesh> p_nav_mesh) {
set_navigation_mesh(p_nav_mesh);
bake_thread.wait_to_finish();
- emit_signal("bake_finished");
+ emit_signal(SNAME("bake_finished"));
}
TypedArray<String> NavigationRegion3D::get_configuration_warnings() const {
@@ -182,7 +189,7 @@ TypedArray<String> NavigationRegion3D::get_configuration_warnings() const {
if (is_visible_in_tree() && is_inside_tree()) {
if (!navmesh.is_valid()) {
- warnings.push_back(TTR("A NavigationMesh resource must be set or created for this node to work."));
+ warnings.push_back(RTR("A NavigationMesh resource must be set or created for this node to work."));
}
}
@@ -199,7 +206,9 @@ void NavigationRegion3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_layers", "layers"), &NavigationRegion3D::set_layers);
ClassDB::bind_method(D_METHOD("get_layers"), &NavigationRegion3D::get_layers);
- ClassDB::bind_method(D_METHOD("bake_navigation_mesh"), &NavigationRegion3D::bake_navigation_mesh);
+ ClassDB::bind_method(D_METHOD("get_region_rid"), &NavigationRegion3D::get_region_rid);
+
+ ClassDB::bind_method(D_METHOD("bake_navigation_mesh", "on_thread"), &NavigationRegion3D::bake_navigation_mesh, DEFVAL(true));
ClassDB::bind_method(D_METHOD("_bake_finished", "nav_mesh"), &NavigationRegion3D::_bake_finished);
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "navmesh", PROPERTY_HINT_RESOURCE_TYPE, "NavigationMesh"), "set_navigation_mesh", "get_navigation_mesh");
@@ -211,7 +220,7 @@ void NavigationRegion3D::_bind_methods() {
}
void NavigationRegion3D::_navigation_changed() {
- update_gizmo();
+ update_gizmos();
update_configuration_warnings();
}
diff --git a/scene/3d/navigation_region_3d.h b/scene/3d/navigation_region_3d.h
index c2045215b1..140dfebf6a 100644
--- a/scene/3d/navigation_region_3d.h
+++ b/scene/3d/navigation_region_3d.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -32,7 +32,6 @@
#define NAVIGATION_REGION_H
#include "scene/3d/node_3d.h"
-#include "scene/resources/mesh.h"
#include "scene/resources/navigation_mesh.h"
class NavigationRegion3D : public Node3D {
@@ -58,12 +57,14 @@ public:
void set_layers(uint32_t p_layers);
uint32_t get_layers() const;
+ RID get_region_rid() const;
+
void set_navigation_mesh(const Ref<NavigationMesh> &p_navmesh);
Ref<NavigationMesh> get_navigation_mesh() const;
- /// Bakes the navigation mesh in a dedicated thread; once done, automatically
+ /// Bakes the navigation mesh; once done, automatically
/// sets the new navigation mesh and emits a signal
- void bake_navigation_mesh();
+ void bake_navigation_mesh(bool p_on_thread);
void _bake_finished(Ref<NavigationMesh> p_nav_mesh);
TypedArray<String> get_configuration_warnings() const override;
diff --git a/scene/3d/node_3d.cpp b/scene/3d/node_3d.cpp
index ba0f8cc870..bbc977647e 100644
--- a/scene/3d/node_3d.cpp
+++ b/scene/3d/node_3d.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -30,10 +30,10 @@
#include "node_3d.h"
-#include "core/config/engine.h"
#include "core/object/message_queue.h"
-#include "scene/main/scene_tree.h"
-#include "scene/main/window.h"
+#include "scene/3d/visual_instance_3d.h"
+#include "scene/main/viewport.h"
+#include "scene/property_utils.h"
#include "scene/scene_string_names.h"
/*
@@ -45,7 +45,7 @@
definition of invalidation: global is invalid
1) If a node sets a LOCAL, it produces an invalidation of everything above
- a) If above is invalid, don't keep invalidating upwards
+ . a) If above is invalid, don't keep invalidating upwards
2) If a node sets a GLOBAL, it is converted to LOCAL (and forces validation of everything pending below)
drawback: setting/reading globals is useful and used very often, and using affine inverses is slow
@@ -57,7 +57,7 @@
definition of invalidation: NONE dirty, LOCAL dirty, GLOBAL dirty
1) If a node sets a LOCAL, it must climb the tree and set it as GLOBAL dirty
- a) marking GLOBALs as dirty up all the tree must be done always
+ . a) marking GLOBALs as dirty up all the tree must be done always
2) If a node sets a GLOBAL, it marks local as dirty, and that's all?
//is clearing the dirty state correct in this case?
@@ -75,7 +75,7 @@ Node3DGizmo::Node3DGizmo() {
void Node3D::_notify_dirty() {
#ifdef TOOLS_ENABLED
- if ((data.gizmo.is_valid() || data.notify_transform) && !data.ignore_notification && !xform_change.in_list()) {
+ if ((!data.gizmos.is_empty() || data.notify_transform) && !data.ignore_notification && !xform_change.in_list()) {
#else
if (data.notify_transform && !data.ignore_notification && !xform_change.in_list()) {
@@ -85,6 +85,9 @@ void Node3D::_notify_dirty() {
}
void Node3D::_update_local_transform() const {
+ if (this->get_rotation_edit_mode() != ROTATION_EDIT_MODE_BASIS) {
+ data.local_transform = data.local_transform.orthogonalized();
+ }
data.local_transform.basis.set_euler_scale(data.rotation, data.scale);
data.dirty &= ~DIRTY_LOCAL;
@@ -95,21 +98,16 @@ void Node3D::_propagate_transform_changed(Node3D *p_origin) {
return;
}
- /*
- if (data.dirty&DIRTY_GLOBAL)
- return; //already dirty
- */
-
data.children_lock++;
- for (List<Node3D *>::Element *E = data.children.front(); E; E = E->next()) {
- if (E->get()->data.top_level_active) {
+ for (Node3D *&E : data.children) {
+ if (E->data.top_level_active) {
continue; //don't propagate to a top_level
}
- E->get()->_propagate_transform_changed(p_origin);
+ E->_propagate_transform_changed(p_origin);
}
#ifdef TOOLS_ENABLED
- if ((data.gizmo.is_valid() || data.notify_transform) && !data.ignore_notification && !xform_change.in_list()) {
+ if ((!data.gizmos.is_empty() || data.notify_transform) && !data.ignore_notification && !xform_change.in_list()) {
#else
if (data.notify_transform && !data.ignore_notification && !xform_change.in_list()) {
#endif
@@ -148,8 +146,9 @@ void Node3D::_notification(int p_what) {
_notify_dirty();
notification(NOTIFICATION_ENTER_WORLD);
-
+ _update_visibility_parent(true);
} break;
+
case NOTIFICATION_EXIT_TREE: {
notification(NOTIFICATION_EXIT_WORLD, true);
if (xform_change.in_list()) {
@@ -161,7 +160,9 @@ void Node3D::_notification(int p_what) {
data.parent = nullptr;
data.C = nullptr;
data.top_level_active = false;
+ _update_visibility_parent(true);
} break;
+
case NOTIFICATION_ENTER_WORLD: {
data.inside_world = true;
data.viewport = nullptr;
@@ -176,29 +177,17 @@ void Node3D::_notification(int p_what) {
if (get_script_instance()) {
get_script_instance()->call(SceneStringNames::get_singleton()->_enter_world);
}
+
#ifdef TOOLS_ENABLED
if (Engine::get_singleton()->is_editor_hint() && get_tree()->is_node_being_edited(this)) {
- //get_scene()->call_group(SceneMainLoop::GROUP_CALL_REALTIME,SceneStringNames::get_singleton()->_spatial_editor_group,SceneStringNames::get_singleton()->_request_gizmo,this);
get_tree()->call_group_flags(0, SceneStringNames::get_singleton()->_spatial_editor_group, SceneStringNames::get_singleton()->_request_gizmo, this);
- if (!data.gizmo_disabled) {
- if (data.gizmo.is_valid()) {
- data.gizmo->create();
- if (is_visible_in_tree()) {
- data.gizmo->redraw();
- }
- data.gizmo->transform();
- }
- }
}
#endif
-
} break;
+
case NOTIFICATION_EXIT_WORLD: {
#ifdef TOOLS_ENABLED
- if (data.gizmo.is_valid()) {
- data.gizmo->free();
- data.gizmo.unref();
- }
+ clear_gizmos();
#endif
if (get_script_instance()) {
@@ -207,23 +196,26 @@ void Node3D::_notification(int p_what) {
data.viewport = nullptr;
data.inside_world = false;
-
} break;
case NOTIFICATION_TRANSFORM_CHANGED: {
#ifdef TOOLS_ENABLED
- if (data.gizmo.is_valid()) {
- data.gizmo->transform();
+ for (int i = 0; i < data.gizmos.size(); i++) {
+ data.gizmos.write[i]->transform();
}
#endif
} break;
-
- default: {
- }
}
}
-void Node3D::set_transform(const Transform &p_transform) {
+void Node3D::set_basis(const Basis &p_basis) {
+ set_transform(Transform3D(p_basis, data.local_transform.origin));
+}
+void Node3D::set_quaternion(const Quaternion &p_quaternion) {
+ set_transform(Transform3D(Basis(p_quaternion), data.local_transform.origin));
+}
+
+void Node3D::set_transform(const Transform3D &p_transform) {
data.local_transform = p_transform;
data.dirty |= DIRTY_VECTORS;
_propagate_transform_changed(this);
@@ -232,25 +224,30 @@ void Node3D::set_transform(const Transform &p_transform) {
}
}
-void Node3D::set_global_transform(const Transform &p_transform) {
- Transform xform =
- (data.parent && !data.top_level_active) ?
- data.parent->get_global_transform().affine_inverse() * p_transform :
- p_transform;
+Basis Node3D::get_basis() const {
+ return get_transform().basis;
+}
+Quaternion Node3D::get_quaternion() const {
+ return Quaternion(get_transform().basis);
+}
+
+void Node3D::set_global_transform(const Transform3D &p_transform) {
+ Transform3D xform = (data.parent && !data.top_level_active)
+ ? data.parent->get_global_transform().affine_inverse() * p_transform
+ : p_transform;
set_transform(xform);
}
-Transform Node3D::get_transform() const {
+Transform3D Node3D::get_transform() const {
if (data.dirty & DIRTY_LOCAL) {
_update_local_transform();
}
return data.local_transform;
}
-
-Transform Node3D::get_global_transform() const {
- ERR_FAIL_COND_V(!is_inside_tree(), Transform());
+Transform3D Node3D::get_global_transform() const {
+ ERR_FAIL_COND_V(!is_inside_tree(), Transform3D());
if (data.dirty & DIRTY_GLOBAL) {
if (data.dirty & DIRTY_LOCAL) {
@@ -274,25 +271,29 @@ Transform Node3D::get_global_transform() const {
}
#ifdef TOOLS_ENABLED
-Transform Node3D::get_global_gizmo_transform() const {
+Transform3D Node3D::get_global_gizmo_transform() const {
return get_global_transform();
}
-Transform Node3D::get_local_gizmo_transform() const {
+Transform3D Node3D::get_local_gizmo_transform() const {
return get_transform();
}
#endif
-Node3D *Node3D::get_parent_spatial() const {
- return data.parent;
+Node3D *Node3D::get_parent_node_3d() const {
+ if (data.top_level) {
+ return nullptr;
+ }
+
+ return Object::cast_to<Node3D>(get_parent());
}
-Transform Node3D::get_relative_transform(const Node *p_parent) const {
+Transform3D Node3D::get_relative_transform(const Node *p_parent) const {
if (p_parent == this) {
- return Transform();
+ return Transform3D();
}
- ERR_FAIL_COND_V(!data.parent, Transform());
+ ERR_FAIL_COND_V(!data.parent, Transform3D());
if (p_parent == data.parent) {
return get_transform();
@@ -301,14 +302,61 @@ Transform Node3D::get_relative_transform(const Node *p_parent) const {
}
}
-void Node3D::set_translation(const Vector3 &p_translation) {
- data.local_transform.origin = p_translation;
+void Node3D::set_position(const Vector3 &p_position) {
+ data.local_transform.origin = p_position;
_propagate_transform_changed(this);
if (data.notify_local_transform) {
notification(NOTIFICATION_LOCAL_TRANSFORM_CHANGED);
}
}
+void Node3D::set_rotation_edit_mode(RotationEditMode p_mode) {
+ if (data.rotation_edit_mode == p_mode) {
+ return;
+ }
+ data.rotation_edit_mode = p_mode;
+
+ // Shearing is not allowed except in ROTATION_EDIT_MODE_BASIS.
+ data.dirty |= DIRTY_LOCAL;
+ _propagate_transform_changed(this);
+ if (data.notify_local_transform) {
+ notification(NOTIFICATION_LOCAL_TRANSFORM_CHANGED);
+ }
+
+ notify_property_list_changed();
+}
+
+Node3D::RotationEditMode Node3D::get_rotation_edit_mode() const {
+ return data.rotation_edit_mode;
+}
+
+void Node3D::set_rotation_order(RotationOrder p_order) {
+ Basis::EulerOrder order = Basis::EulerOrder(p_order);
+
+ if (data.rotation_order == order) {
+ return;
+ }
+
+ ERR_FAIL_INDEX(int32_t(order), 6);
+
+ if (data.dirty & DIRTY_VECTORS) {
+ data.rotation = data.local_transform.basis.get_euler_normalized(order);
+ data.scale = data.local_transform.basis.get_scale();
+ data.dirty &= ~DIRTY_VECTORS;
+ } else {
+ data.rotation = Basis::from_euler(data.rotation, data.rotation_order).get_euler_normalized(order);
+ }
+
+ data.rotation_order = order;
+ //changing rotation order should not affect transform
+
+ notify_property_list_changed(); //will change rotation
+}
+
+Node3D::RotationOrder Node3D::get_rotation_order() const {
+ return RotationOrder(data.rotation_order);
+}
+
void Node3D::set_rotation(const Vector3 &p_euler_rad) {
if (data.dirty & DIRTY_VECTORS) {
data.scale = data.local_transform.basis.get_scale();
@@ -323,13 +371,9 @@ void Node3D::set_rotation(const Vector3 &p_euler_rad) {
}
}
-void Node3D::set_rotation_degrees(const Vector3 &p_euler_deg) {
- set_rotation(p_euler_deg * (Math_PI / 180.0));
-}
-
void Node3D::set_scale(const Vector3 &p_scale) {
if (data.dirty & DIRTY_VECTORS) {
- data.rotation = data.local_transform.basis.get_rotation();
+ data.rotation = data.local_transform.basis.get_euler_normalized(data.rotation_order);
data.dirty &= ~DIRTY_VECTORS;
}
@@ -341,14 +385,14 @@ void Node3D::set_scale(const Vector3 &p_scale) {
}
}
-Vector3 Node3D::get_translation() const {
+Vector3 Node3D::get_position() const {
return data.local_transform.origin;
}
Vector3 Node3D::get_rotation() const {
if (data.dirty & DIRTY_VECTORS) {
data.scale = data.local_transform.basis.get_scale();
- data.rotation = data.local_transform.basis.get_rotation();
+ data.rotation = data.local_transform.basis.get_euler_normalized(data.rotation_order);
data.dirty &= ~DIRTY_VECTORS;
}
@@ -356,14 +400,10 @@ Vector3 Node3D::get_rotation() const {
return data.rotation;
}
-Vector3 Node3D::get_rotation_degrees() const {
- return get_rotation() * (180.0 / Math_PI);
-}
-
Vector3 Node3D::get_scale() const {
if (data.dirty & DIRTY_VECTORS) {
data.scale = data.local_transform.basis.get_scale();
- data.rotation = data.local_transform.basis.get_rotation();
+ data.rotation = data.local_transform.basis.get_euler_normalized(data.rotation_order);
data.dirty &= ~DIRTY_VECTORS;
}
@@ -371,81 +411,133 @@ Vector3 Node3D::get_scale() const {
return data.scale;
}
-void Node3D::update_gizmo() {
+void Node3D::update_gizmos() {
#ifdef TOOLS_ENABLED
if (!is_inside_world()) {
return;
}
- if (!data.gizmo.is_valid()) {
- get_tree()->call_group_flags(SceneTree::GROUP_CALL_REALTIME, SceneStringNames::get_singleton()->_spatial_editor_group, SceneStringNames::get_singleton()->_request_gizmo, this);
+
+ if (data.gizmos.is_empty()) {
+ get_tree()->call_group_flags(0, SceneStringNames::get_singleton()->_spatial_editor_group, SceneStringNames::get_singleton()->_request_gizmo, this);
+ return;
}
- if (!data.gizmo.is_valid()) {
+ if (data.gizmos_dirty) {
return;
}
- if (data.gizmo_dirty) {
+ data.gizmos_dirty = true;
+ MessageQueue::get_singleton()->push_callable(callable_mp(this, &Node3D::_update_gizmos));
+#endif
+}
+
+void Node3D::set_subgizmo_selection(Ref<Node3DGizmo> p_gizmo, int p_id, Transform3D p_transform) {
+#ifdef TOOLS_ENABLED
+ if (!is_inside_world()) {
return;
}
- data.gizmo_dirty = true;
- MessageQueue::get_singleton()->push_call(this, "_update_gizmo");
+
+ if (Engine::get_singleton()->is_editor_hint() && get_tree()->is_node_being_edited(this)) {
+ get_tree()->call_group_flags(0, SceneStringNames::get_singleton()->_spatial_editor_group, SceneStringNames::get_singleton()->_set_subgizmo_selection, this, p_gizmo, p_id, p_transform);
+ }
#endif
}
-void Node3D::set_gizmo(const Ref<Node3DGizmo> &p_gizmo) {
+void Node3D::clear_subgizmo_selection() {
#ifdef TOOLS_ENABLED
+ if (!is_inside_world()) {
+ return;
+ }
- if (data.gizmo_disabled) {
+ if (data.gizmos.is_empty()) {
return;
}
- if (data.gizmo.is_valid() && is_inside_world()) {
- data.gizmo->free();
+
+ if (Engine::get_singleton()->is_editor_hint() && get_tree()->is_node_being_edited(this)) {
+ get_tree()->call_group_flags(0, SceneStringNames::get_singleton()->_spatial_editor_group, SceneStringNames::get_singleton()->_clear_subgizmo_selection, this);
}
- data.gizmo = p_gizmo;
- if (data.gizmo.is_valid() && is_inside_world()) {
- data.gizmo->create();
+#endif
+}
+
+void Node3D::add_gizmo(Ref<Node3DGizmo> p_gizmo) {
+#ifdef TOOLS_ENABLED
+ if (data.gizmos_disabled || p_gizmo.is_null()) {
+ return;
+ }
+ data.gizmos.push_back(p_gizmo);
+
+ if (p_gizmo.is_valid() && is_inside_world()) {
+ p_gizmo->create();
if (is_visible_in_tree()) {
- data.gizmo->redraw();
+ p_gizmo->redraw();
}
- data.gizmo->transform();
+ p_gizmo->transform();
}
+#endif
+}
+void Node3D::remove_gizmo(Ref<Node3DGizmo> p_gizmo) {
+#ifdef TOOLS_ENABLED
+ int idx = data.gizmos.find(p_gizmo);
+ if (idx != -1) {
+ p_gizmo->free();
+ data.gizmos.remove_at(idx);
+ }
#endif
}
-Ref<Node3DGizmo> Node3D::get_gizmo() const {
+void Node3D::clear_gizmos() {
#ifdef TOOLS_ENABLED
+ for (int i = 0; i < data.gizmos.size(); i++) {
+ data.gizmos.write[i]->free();
+ }
+ data.gizmos.clear();
+#endif
+}
- return data.gizmo;
-#else
+Array Node3D::get_gizmos_bind() const {
+ Array ret;
- return Ref<Node3DGizmo>();
+#ifdef TOOLS_ENABLED
+ for (int i = 0; i < data.gizmos.size(); i++) {
+ ret.push_back(Variant(data.gizmos[i].ptr()));
+ }
#endif
+
+ return ret;
}
-void Node3D::_update_gizmo() {
+Vector<Ref<Node3DGizmo>> Node3D::get_gizmos() const {
#ifdef TOOLS_ENABLED
- if (!is_inside_world()) {
+ return data.gizmos;
+#else
+ return Vector<Ref<Node3DGizmo>>();
+#endif
+}
+
+void Node3D::_update_gizmos() {
+#ifdef TOOLS_ENABLED
+ if (data.gizmos_disabled || !is_inside_world() || !data.gizmos_dirty) {
+ data.gizmos_dirty = false;
return;
}
- data.gizmo_dirty = false;
- if (data.gizmo.is_valid()) {
+ data.gizmos_dirty = false;
+ for (int i = 0; i < data.gizmos.size(); i++) {
if (is_visible_in_tree()) {
- data.gizmo->redraw();
+ data.gizmos.write[i]->redraw();
} else {
- data.gizmo->clear();
+ data.gizmos.write[i]->clear();
}
}
#endif
}
+void Node3D::set_disable_gizmos(bool p_enabled) {
#ifdef TOOLS_ENABLED
-void Node3D::set_disable_gizmo(bool p_enabled) {
- data.gizmo_disabled = p_enabled;
- if (!p_enabled && data.gizmo.is_valid()) {
- data.gizmo = Ref<Node3DGizmo>();
+ data.gizmos_disabled = p_enabled;
+ if (!p_enabled) {
+ clear_gizmos();
}
-}
-
#endif
+}
void Node3D::set_disable_scale(bool p_enabled) {
data.disable_scale = p_enabled;
@@ -468,7 +560,6 @@ void Node3D::set_as_top_level(bool p_enabled) {
data.top_level = p_enabled;
data.top_level_active = p_enabled;
-
} else {
data.top_level = p_enabled;
}
@@ -488,14 +579,15 @@ Ref<World3D> Node3D::get_world_3d() const {
void Node3D::_propagate_visibility_changed() {
notification(NOTIFICATION_VISIBILITY_CHANGED);
emit_signal(SceneStringNames::get_singleton()->visibility_changed);
+
#ifdef TOOLS_ENABLED
- if (data.gizmo.is_valid()) {
- _update_gizmo();
+ if (!data.gizmos.is_empty()) {
+ data.gizmos_dirty = true;
+ _update_gizmos();
}
#endif
- for (List<Node3D *>::Element *E = data.children.front(); E; E = E->next()) {
- Node3D *c = E->get();
+ for (Node3D *c : data.children) {
if (!c || !c->data.visible) {
continue;
}
@@ -504,33 +596,30 @@ void Node3D::_propagate_visibility_changed() {
}
void Node3D::show() {
- if (data.visible) {
- return;
- }
-
- data.visible = true;
-
- if (!is_inside_tree()) {
- return;
- }
-
- _propagate_visibility_changed();
+ set_visible(true);
}
void Node3D::hide() {
- if (!data.visible) {
+ set_visible(false);
+}
+
+void Node3D::set_visible(bool p_visible) {
+ if (data.visible == p_visible) {
return;
}
- data.visible = false;
+ data.visible = p_visible;
if (!is_inside_tree()) {
return;
}
-
_propagate_visibility_changed();
}
+bool Node3D::is_visible() const {
+ return data.visible;
+}
+
bool Node3D::is_visible_in_tree() const {
const Node3D *s = this;
@@ -544,116 +633,102 @@ bool Node3D::is_visible_in_tree() const {
return true;
}
-void Node3D::set_visible(bool p_visible) {
- if (p_visible) {
- show();
- } else {
- hide();
- }
-}
-
-bool Node3D::is_visible() const {
- return data.visible;
-}
-
-void Node3D::rotate_object_local(const Vector3 &p_axis, float p_angle) {
- Transform t = get_transform();
+void Node3D::rotate_object_local(const Vector3 &p_axis, real_t p_angle) {
+ Transform3D t = get_transform();
t.basis.rotate_local(p_axis, p_angle);
set_transform(t);
}
-void Node3D::rotate(const Vector3 &p_axis, float p_angle) {
- Transform t = get_transform();
+void Node3D::rotate(const Vector3 &p_axis, real_t p_angle) {
+ Transform3D t = get_transform();
t.basis.rotate(p_axis, p_angle);
set_transform(t);
}
-void Node3D::rotate_x(float p_angle) {
- Transform t = get_transform();
+void Node3D::rotate_x(real_t p_angle) {
+ Transform3D t = get_transform();
t.basis.rotate(Vector3(1, 0, 0), p_angle);
set_transform(t);
}
-void Node3D::rotate_y(float p_angle) {
- Transform t = get_transform();
+void Node3D::rotate_y(real_t p_angle) {
+ Transform3D t = get_transform();
t.basis.rotate(Vector3(0, 1, 0), p_angle);
set_transform(t);
}
-void Node3D::rotate_z(float p_angle) {
- Transform t = get_transform();
+void Node3D::rotate_z(real_t p_angle) {
+ Transform3D t = get_transform();
t.basis.rotate(Vector3(0, 0, 1), p_angle);
set_transform(t);
}
void Node3D::translate(const Vector3 &p_offset) {
- Transform t = get_transform();
+ Transform3D t = get_transform();
t.translate(p_offset);
set_transform(t);
}
void Node3D::translate_object_local(const Vector3 &p_offset) {
- Transform t = get_transform();
+ Transform3D t = get_transform();
- Transform s;
+ Transform3D s;
s.translate(p_offset);
set_transform(t * s);
}
void Node3D::scale(const Vector3 &p_ratio) {
- Transform t = get_transform();
+ Transform3D t = get_transform();
t.basis.scale(p_ratio);
set_transform(t);
}
void Node3D::scale_object_local(const Vector3 &p_scale) {
- Transform t = get_transform();
+ Transform3D t = get_transform();
t.basis.scale_local(p_scale);
set_transform(t);
}
-void Node3D::global_rotate(const Vector3 &p_axis, float p_angle) {
- Transform t = get_global_transform();
+void Node3D::global_rotate(const Vector3 &p_axis, real_t p_angle) {
+ Transform3D t = get_global_transform();
t.basis.rotate(p_axis, p_angle);
set_global_transform(t);
}
void Node3D::global_scale(const Vector3 &p_scale) {
- Transform t = get_global_transform();
+ Transform3D t = get_global_transform();
t.basis.scale(p_scale);
set_global_transform(t);
}
void Node3D::global_translate(const Vector3 &p_offset) {
- Transform t = get_global_transform();
+ Transform3D t = get_global_transform();
t.origin += p_offset;
set_global_transform(t);
}
void Node3D::orthonormalize() {
- Transform t = get_transform();
+ Transform3D t = get_transform();
t.orthonormalize();
set_transform(t);
}
void Node3D::set_identity() {
- set_transform(Transform());
+ set_transform(Transform3D());
}
void Node3D::look_at(const Vector3 &p_target, const Vector3 &p_up) {
- Vector3 origin(get_global_transform().origin);
+ Vector3 origin = get_global_transform().origin;
look_at_from_position(origin, p_target, p_up);
}
void Node3D::look_at_from_position(const Vector3 &p_pos, const Vector3 &p_target, const Vector3 &p_up) {
- ERR_FAIL_COND_MSG(p_pos == p_target, "Node origin and target are in the same position, look_at() failed.");
- ERR_FAIL_COND_MSG(p_up.cross(p_target - p_pos) == Vector3(), "Up vector and direction between node origin and target are aligned, look_at() failed.");
-
- Transform lookat;
- lookat.origin = p_pos;
+ ERR_FAIL_COND_MSG(p_pos.is_equal_approx(p_target), "Node origin and target are in the same position, look_at() failed.");
+ ERR_FAIL_COND_MSG(p_up.is_equal_approx(Vector3()), "The up vector can't be zero, look_at() failed.");
+ ERR_FAIL_COND_MSG(p_up.cross(p_target - p_pos).is_equal_approx(Vector3()), "Up vector and direction between node origin and target are aligned, look_at() failed.");
- Vector3 original_scale(get_scale());
- lookat = lookat.looking_at(p_target, p_up);
+ Transform3D lookat = Transform3D(Basis::looking_at(p_target - p_pos, p_up), p_pos);
+ Vector3 original_scale = get_scale();
set_global_transform(lookat);
set_scale(original_scale);
}
@@ -666,16 +741,16 @@ Vector3 Node3D::to_global(Vector3 p_local) const {
return get_global_transform().xform(p_local);
}
-void Node3D::set_notify_transform(bool p_enable) {
- data.notify_transform = p_enable;
+void Node3D::set_notify_transform(bool p_enabled) {
+ data.notify_transform = p_enabled;
}
bool Node3D::is_transform_notification_enabled() const {
return data.notify_transform;
}
-void Node3D::set_notify_local_transform(bool p_enable) {
- data.notify_local_transform = p_enable;
+void Node3D::set_notify_local_transform(bool p_enabled) {
+ data.notify_local_transform = p_enabled;
}
bool Node3D::is_local_transform_notification_enabled() const {
@@ -692,20 +767,146 @@ void Node3D::force_update_transform() {
notification(NOTIFICATION_TRANSFORM_CHANGED);
}
+void Node3D::_update_visibility_parent(bool p_update_root) {
+ RID new_parent;
+
+ if (!visibility_parent_path.is_empty()) {
+ if (!p_update_root) {
+ return;
+ }
+ Node *parent = get_node_or_null(visibility_parent_path);
+ ERR_FAIL_COND_MSG(!parent, "Can't find visibility parent node at path: " + visibility_parent_path);
+ ERR_FAIL_COND_MSG(parent == this, "The visibility parent can't be the same node.");
+ GeometryInstance3D *gi = Object::cast_to<GeometryInstance3D>(parent);
+ ERR_FAIL_COND_MSG(!gi, "The visibility parent node must be a GeometryInstance3D, at path: " + visibility_parent_path);
+ new_parent = gi ? gi->get_instance() : RID();
+ } else if (data.parent) {
+ new_parent = data.parent->data.visibility_parent;
+ }
+
+ if (new_parent == data.visibility_parent) {
+ return;
+ }
+
+ data.visibility_parent = new_parent;
+
+ VisualInstance3D *vi = Object::cast_to<VisualInstance3D>(this);
+ if (vi) {
+ RS::get_singleton()->instance_set_visibility_parent(vi->get_instance(), data.visibility_parent);
+ }
+
+ for (Node3D *c : data.children) {
+ c->_update_visibility_parent(false);
+ }
+}
+
+void Node3D::set_visibility_parent(const NodePath &p_path) {
+ visibility_parent_path = p_path;
+ if (is_inside_tree()) {
+ _update_visibility_parent(true);
+ }
+}
+
+NodePath Node3D::get_visibility_parent() const {
+ return visibility_parent_path;
+}
+
+void Node3D::_validate_property(PropertyInfo &property) const {
+ if (data.rotation_edit_mode != ROTATION_EDIT_MODE_BASIS && property.name == "basis") {
+ property.usage = 0;
+ }
+ if (data.rotation_edit_mode == ROTATION_EDIT_MODE_BASIS && property.name == "scale") {
+ property.usage = 0;
+ }
+ if (data.rotation_edit_mode != ROTATION_EDIT_MODE_QUATERNION && property.name == "quaternion") {
+ property.usage = 0;
+ }
+ if (data.rotation_edit_mode != ROTATION_EDIT_MODE_EULER && property.name == "rotation") {
+ property.usage = 0;
+ }
+ if (data.rotation_edit_mode != ROTATION_EDIT_MODE_EULER && property.name == "rotation_order") {
+ property.usage = 0;
+ }
+}
+
+bool Node3D::property_can_revert(const String &p_name) {
+ if (p_name == "basis") {
+ return true;
+ } else if (p_name == "scale") {
+ return true;
+ } else if (p_name == "quaternion") {
+ return true;
+ } else if (p_name == "rotation") {
+ return true;
+ } else if (p_name == "position") {
+ return true;
+ }
+ return false;
+}
+
+Variant Node3D::property_get_revert(const String &p_name) {
+ Variant r_ret;
+ bool valid = false;
+
+ if (p_name == "basis") {
+ Variant variant = PropertyUtils::get_property_default_value(this, "transform", &valid);
+ if (valid && variant.get_type() == Variant::Type::TRANSFORM3D) {
+ r_ret = Transform3D(variant).get_basis();
+ } else {
+ r_ret = Basis();
+ }
+ } else if (p_name == "scale") {
+ Variant variant = PropertyUtils::get_property_default_value(this, "transform", &valid);
+ if (valid && variant.get_type() == Variant::Type::TRANSFORM3D) {
+ r_ret = Transform3D(variant).get_basis().get_scale();
+ } else {
+ return Vector3(1.0, 1.0, 1.0);
+ }
+ } else if (p_name == "quaternion") {
+ Variant variant = PropertyUtils::get_property_default_value(this, "transform", &valid);
+ if (valid && variant.get_type() == Variant::Type::TRANSFORM3D) {
+ r_ret = Quaternion(Transform3D(variant).get_basis());
+ } else {
+ return Quaternion();
+ }
+ } else if (p_name == "rotation") {
+ Variant variant = PropertyUtils::get_property_default_value(this, "transform", &valid);
+ if (valid && variant.get_type() == Variant::Type::TRANSFORM3D) {
+ r_ret = Transform3D(variant).get_basis().get_euler_normalized(data.rotation_order);
+ } else {
+ return Vector3();
+ }
+ } else if (p_name == "position") {
+ Variant variant = PropertyUtils::get_property_default_value(this, "transform", &valid);
+ if (valid) {
+ r_ret = Transform3D(variant).get_origin();
+ } else {
+ return Vector3();
+ }
+ }
+ return r_ret;
+}
+
void Node3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_transform", "local"), &Node3D::set_transform);
ClassDB::bind_method(D_METHOD("get_transform"), &Node3D::get_transform);
- ClassDB::bind_method(D_METHOD("set_translation", "translation"), &Node3D::set_translation);
- ClassDB::bind_method(D_METHOD("get_translation"), &Node3D::get_translation);
+ ClassDB::bind_method(D_METHOD("set_position", "position"), &Node3D::set_position);
+ ClassDB::bind_method(D_METHOD("get_position"), &Node3D::get_position);
ClassDB::bind_method(D_METHOD("set_rotation", "euler"), &Node3D::set_rotation);
ClassDB::bind_method(D_METHOD("get_rotation"), &Node3D::get_rotation);
- ClassDB::bind_method(D_METHOD("set_rotation_degrees", "euler_degrees"), &Node3D::set_rotation_degrees);
- ClassDB::bind_method(D_METHOD("get_rotation_degrees"), &Node3D::get_rotation_degrees);
+ ClassDB::bind_method(D_METHOD("set_rotation_order", "order"), &Node3D::set_rotation_order);
+ ClassDB::bind_method(D_METHOD("get_rotation_order"), &Node3D::get_rotation_order);
+ ClassDB::bind_method(D_METHOD("set_rotation_edit_mode", "edit_mode"), &Node3D::set_rotation_edit_mode);
+ ClassDB::bind_method(D_METHOD("get_rotation_edit_mode"), &Node3D::get_rotation_edit_mode);
ClassDB::bind_method(D_METHOD("set_scale", "scale"), &Node3D::set_scale);
ClassDB::bind_method(D_METHOD("get_scale"), &Node3D::get_scale);
+ ClassDB::bind_method(D_METHOD("set_quaternion", "quaternion"), &Node3D::set_quaternion);
+ ClassDB::bind_method(D_METHOD("get_quaternion"), &Node3D::get_quaternion);
+ ClassDB::bind_method(D_METHOD("set_basis", "basis"), &Node3D::set_basis);
+ ClassDB::bind_method(D_METHOD("get_basis"), &Node3D::get_basis);
ClassDB::bind_method(D_METHOD("set_global_transform", "global"), &Node3D::set_global_transform);
ClassDB::bind_method(D_METHOD("get_global_transform"), &Node3D::get_global_transform);
- ClassDB::bind_method(D_METHOD("get_parent_spatial"), &Node3D::get_parent_spatial);
+ ClassDB::bind_method(D_METHOD("get_parent_node_3d"), &Node3D::get_parent_node_3d);
ClassDB::bind_method(D_METHOD("set_ignore_transform_notification", "enabled"), &Node3D::set_ignore_transform_notification);
ClassDB::bind_method(D_METHOD("set_as_top_level", "enable"), &Node3D::set_as_top_level);
ClassDB::bind_method(D_METHOD("is_set_as_top_level"), &Node3D::is_set_as_top_level);
@@ -715,11 +916,15 @@ void Node3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("force_update_transform"), &Node3D::force_update_transform);
- ClassDB::bind_method(D_METHOD("_update_gizmo"), &Node3D::_update_gizmo);
+ ClassDB::bind_method(D_METHOD("set_visibility_parent", "path"), &Node3D::set_visibility_parent);
+ ClassDB::bind_method(D_METHOD("get_visibility_parent"), &Node3D::get_visibility_parent);
- ClassDB::bind_method(D_METHOD("update_gizmo"), &Node3D::update_gizmo);
- ClassDB::bind_method(D_METHOD("set_gizmo", "gizmo"), &Node3D::set_gizmo);
- ClassDB::bind_method(D_METHOD("get_gizmo"), &Node3D::get_gizmo);
+ ClassDB::bind_method(D_METHOD("update_gizmos"), &Node3D::update_gizmos);
+ ClassDB::bind_method(D_METHOD("add_gizmo", "gizmo"), &Node3D::add_gizmo);
+ ClassDB::bind_method(D_METHOD("get_gizmos"), &Node3D::get_gizmos_bind);
+ ClassDB::bind_method(D_METHOD("clear_gizmos"), &Node3D::clear_gizmos);
+ ClassDB::bind_method(D_METHOD("set_subgizmo_selection", "gizmo", "id", "transform"), &Node3D::set_subgizmo_selection);
+ ClassDB::bind_method(D_METHOD("clear_subgizmo_selection"), &Node3D::clear_subgizmo_selection);
ClassDB::bind_method(D_METHOD("set_visible", "visible"), &Node3D::set_visible);
ClassDB::bind_method(D_METHOD("is_visible"), &Node3D::is_visible);
@@ -753,24 +958,40 @@ void Node3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("to_local", "global_point"), &Node3D::to_local);
ClassDB::bind_method(D_METHOD("to_global", "local_point"), &Node3D::to_global);
+ ClassDB::bind_method(D_METHOD("property_can_revert", "name"), &Node3D::property_can_revert);
+ ClassDB::bind_method(D_METHOD("property_get_revert", "name"), &Node3D::property_get_revert);
+
BIND_CONSTANT(NOTIFICATION_TRANSFORM_CHANGED);
BIND_CONSTANT(NOTIFICATION_ENTER_WORLD);
BIND_CONSTANT(NOTIFICATION_EXIT_WORLD);
BIND_CONSTANT(NOTIFICATION_VISIBILITY_CHANGED);
- //ADD_PROPERTY( PropertyInfo(Variant::TRANSFORM,"transform/global",PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR ), "set_global_transform", "get_global_transform") ;
+ BIND_ENUM_CONSTANT(ROTATION_EDIT_MODE_EULER);
+ BIND_ENUM_CONSTANT(ROTATION_EDIT_MODE_QUATERNION);
+ BIND_ENUM_CONSTANT(ROTATION_EDIT_MODE_BASIS);
+
+ BIND_ENUM_CONSTANT(ROTATION_ORDER_XYZ);
+ BIND_ENUM_CONSTANT(ROTATION_ORDER_XZY);
+ BIND_ENUM_CONSTANT(ROTATION_ORDER_YXZ);
+ BIND_ENUM_CONSTANT(ROTATION_ORDER_YZX);
+ BIND_ENUM_CONSTANT(ROTATION_ORDER_ZXY);
+ BIND_ENUM_CONSTANT(ROTATION_ORDER_ZYX);
+
+ //ADD_PROPERTY( PropertyInfo(Variant::TRANSFORM3D,"transform/global",PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR ), "set_global_transform", "get_global_transform") ;
ADD_GROUP("Transform", "");
- ADD_PROPERTY(PropertyInfo(Variant::TRANSFORM, "global_transform", PROPERTY_HINT_NONE, "", 0), "set_global_transform", "get_global_transform");
- ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "translation", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR), "set_translation", "get_translation");
- ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "rotation_degrees", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR), "set_rotation_degrees", "get_rotation_degrees");
- ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "rotation", PROPERTY_HINT_NONE, "", 0), "set_rotation", "get_rotation");
+ ADD_PROPERTY(PropertyInfo(Variant::TRANSFORM3D, "transform", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "set_transform", "get_transform");
+ ADD_PROPERTY(PropertyInfo(Variant::TRANSFORM3D, "global_transform", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NONE), "set_global_transform", "get_global_transform");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "position", PROPERTY_HINT_RANGE, "-99999,99999,0.001,or_greater,or_lesser,noslider,suffix:m", PROPERTY_USAGE_EDITOR), "set_position", "get_position");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "rotation", PROPERTY_HINT_RANGE, "-360,360,0.1,or_lesser,or_greater,radians", PROPERTY_USAGE_EDITOR), "set_rotation", "get_rotation");
+ ADD_PROPERTY(PropertyInfo(Variant::QUATERNION, "quaternion", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR), "set_quaternion", "get_quaternion");
+ ADD_PROPERTY(PropertyInfo(Variant::BASIS, "basis", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR), "set_basis", "get_basis");
ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "scale", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR), "set_scale", "get_scale");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "rotation_edit_mode", PROPERTY_HINT_ENUM, "Euler,Quaternion,Basis"), "set_rotation_edit_mode", "get_rotation_edit_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "rotation_order", PROPERTY_HINT_ENUM, "XYZ,XZY,YXZ,YZX,ZXY,ZYX"), "set_rotation_order", "get_rotation_order");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "top_level"), "set_as_top_level", "is_set_as_top_level");
- ADD_GROUP("Matrix", "");
- ADD_PROPERTY(PropertyInfo(Variant::TRANSFORM, "transform", PROPERTY_HINT_NONE, ""), "set_transform", "get_transform");
ADD_GROUP("Visibility", "");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "visible"), "set_visible", "is_visible");
- ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "gizmo", PROPERTY_HINT_RESOURCE_TYPE, "Node3DGizmo", 0), "set_gizmo", "get_gizmo");
+ ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "visibility_parent", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "GeometryInstance3D"), "set_visibility_parent", "get_visibility_parent");
ADD_SIGNAL(MethodInfo("visibility_changed"));
}
diff --git a/scene/3d/node_3d.h b/scene/3d/node_3d.h
index a62c7b31a8..6d857a83ea 100644
--- a/scene/3d/node_3d.h
+++ b/scene/3d/node_3d.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -32,10 +32,10 @@
#define NODE_3D_H
#include "scene/main/node.h"
-#include "scene/main/scene_tree.h"
+#include "scene/resources/world_3d.h"
-class Node3DGizmo : public Reference {
- GDCLASS(Node3DGizmo, Reference);
+class Node3DGizmo : public RefCounted {
+ GDCLASS(Node3DGizmo, RefCounted);
public:
virtual void create() = 0;
@@ -50,8 +50,24 @@ public:
class Node3D : public Node {
GDCLASS(Node3D, Node);
- OBJ_CATEGORY("3D");
+public:
+ enum RotationEditMode {
+ ROTATION_EDIT_MODE_EULER,
+ ROTATION_EDIT_MODE_QUATERNION,
+ ROTATION_EDIT_MODE_BASIS,
+ };
+
+ enum RotationOrder {
+ ROTATION_ORDER_XYZ,
+ ROTATION_ORDER_XZY,
+ ROTATION_ORDER_YXZ,
+ ROTATION_ORDER_YZX,
+ ROTATION_ORDER_ZXY,
+ ROTATION_ORDER_ZYX
+ };
+
+private:
enum TransformDirty {
DIRTY_NONE = 0,
DIRTY_VECTORS = 1,
@@ -62,10 +78,12 @@ class Node3D : public Node {
mutable SelfList<Node> xform_change;
struct Data {
- mutable Transform global_transform;
- mutable Transform local_transform;
+ mutable Transform3D global_transform;
+ mutable Transform3D local_transform;
+ mutable Basis::EulerOrder rotation_order = Basis::EULER_ORDER_YXZ;
mutable Vector3 rotation;
mutable Vector3 scale = Vector3(1, 1, 1);
+ mutable RotationEditMode rotation_edit_mode = ROTATION_EDIT_MODE_EULER;
mutable int dirty = DIRTY_NONE;
@@ -75,6 +93,8 @@ class Node3D : public Node {
bool top_level = false;
bool inside_world = false;
+ RID visibility_parent;
+
int children_lock = 0;
Node3D *parent = nullptr;
List<Node3D *> children;
@@ -88,19 +108,25 @@ class Node3D : public Node {
bool disable_scale = false;
#ifdef TOOLS_ENABLED
- Ref<Node3DGizmo> gizmo;
- bool gizmo_disabled = false;
- bool gizmo_dirty = false;
+ Vector<Ref<Node3DGizmo>> gizmos;
+ bool gizmos_disabled = false;
+ bool gizmos_dirty = false;
+ bool transform_gizmo_visible = true;
#endif
} data;
- void _update_gizmo();
+ NodePath visibility_parent_path;
+
+ void _update_gizmos();
void _notify_dirty();
void _propagate_transform_changed(Node3D *p_origin);
void _propagate_visibility_changed();
+ void _propagate_visibility_parent();
+ void _update_visibility_parent(bool p_update_root);
+
protected:
_FORCE_INLINE_ void set_ignore_transform_notification(bool p_ignore) { data.ignore_notification = p_ignore; }
@@ -109,6 +135,11 @@ protected:
void _notification(int p_what);
static void _bind_methods();
+ virtual void _validate_property(PropertyInfo &property) const override;
+
+ bool property_can_revert(const String &p_name);
+ Variant property_get_revert(const String &p_name);
+
public:
enum {
NOTIFICATION_TRANSFORM_CHANGED = SceneTree::NOTIFICATION_TRANSFORM_CHANGED,
@@ -118,58 +149,74 @@ public:
NOTIFICATION_LOCAL_TRANSFORM_CHANGED = 44,
};
- Node3D *get_parent_spatial() const;
+ Node3D *get_parent_node_3d() const;
Ref<World3D> get_world_3d() const;
- void set_translation(const Vector3 &p_translation);
+ void set_position(const Vector3 &p_position);
+
+ void set_rotation_edit_mode(RotationEditMode p_mode);
+ RotationEditMode get_rotation_edit_mode() const;
+
+ void set_rotation_order(RotationOrder p_order);
void set_rotation(const Vector3 &p_euler_rad);
- void set_rotation_degrees(const Vector3 &p_euler_deg);
void set_scale(const Vector3 &p_scale);
- Vector3 get_translation() const;
+ Vector3 get_position() const;
+
+ RotationOrder get_rotation_order() const;
Vector3 get_rotation() const;
- Vector3 get_rotation_degrees() const;
Vector3 get_scale() const;
- void set_transform(const Transform &p_transform);
- void set_global_transform(const Transform &p_transform);
+ void set_transform(const Transform3D &p_transform);
+ void set_basis(const Basis &p_basis);
+ void set_quaternion(const Quaternion &p_quaternion);
+ void set_global_transform(const Transform3D &p_transform);
- Transform get_transform() const;
- Transform get_global_transform() const;
+ Transform3D get_transform() const;
+ Basis get_basis() const;
+ Quaternion get_quaternion() const;
+ Transform3D get_global_transform() const;
#ifdef TOOLS_ENABLED
- virtual Transform get_global_gizmo_transform() const;
- virtual Transform get_local_gizmo_transform() const;
+ virtual Transform3D get_global_gizmo_transform() const;
+ virtual Transform3D get_local_gizmo_transform() const;
+ 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
+ void set_disable_gizmos(bool p_enabled);
+ void update_gizmos();
+ void set_subgizmo_selection(Ref<Node3DGizmo> p_gizmo, int p_id, Transform3D p_transform = Transform3D());
+ void clear_subgizmo_selection();
+ Vector<Ref<Node3DGizmo>> get_gizmos() const;
+ Array get_gizmos_bind() const;
+ void add_gizmo(Ref<Node3DGizmo> p_gizmo);
+ void remove_gizmo(Ref<Node3DGizmo> p_gizmo);
+ void clear_gizmos();
+
void set_as_top_level(bool p_enabled);
bool is_set_as_top_level() const;
void set_disable_scale(bool p_enabled);
bool is_scale_disabled() const;
- void set_disable_gizmo(bool p_enabled);
- void update_gizmo();
- void set_gizmo(const Ref<Node3DGizmo> &p_gizmo);
- Ref<Node3DGizmo> get_gizmo() const;
-
_FORCE_INLINE_ bool is_inside_world() const { return data.inside_world; }
- Transform get_relative_transform(const Node *p_parent) const;
+ Transform3D get_relative_transform(const Node *p_parent) const;
- void rotate(const Vector3 &p_axis, float p_angle);
- void rotate_x(float p_angle);
- void rotate_y(float p_angle);
- void rotate_z(float p_angle);
+ void rotate(const Vector3 &p_axis, real_t p_angle);
+ void rotate_x(real_t p_angle);
+ void rotate_y(real_t p_angle);
+ void rotate_z(real_t p_angle);
void translate(const Vector3 &p_offset);
void scale(const Vector3 &p_ratio);
- void rotate_object_local(const Vector3 &p_axis, float p_angle);
+ void rotate_object_local(const Vector3 &p_axis, real_t p_angle);
void scale_object_local(const Vector3 &p_scale);
void translate_object_local(const Vector3 &p_offset);
- void global_rotate(const Vector3 &p_axis, float p_angle);
+ void global_rotate(const Vector3 &p_axis, real_t p_angle);
void global_scale(const Vector3 &p_scale);
void global_translate(const Vector3 &p_offset);
@@ -179,24 +226,30 @@ public:
Vector3 to_local(Vector3 p_global) const;
Vector3 to_global(Vector3 p_local) const;
- void set_notify_transform(bool p_enable);
+ void set_notify_transform(bool p_enabled);
bool is_transform_notification_enabled() const;
- void set_notify_local_transform(bool p_enable);
+ void set_notify_local_transform(bool p_enabled);
bool is_local_transform_notification_enabled() const;
void orthonormalize();
void set_identity();
void set_visible(bool p_visible);
- bool is_visible() const;
void show();
void hide();
+ bool is_visible() const;
bool is_visible_in_tree() const;
void force_update_transform();
+ void set_visibility_parent(const NodePath &p_path);
+ NodePath get_visibility_parent() const;
+
Node3D();
};
+VARIANT_ENUM_CAST(Node3D::RotationEditMode)
+VARIANT_ENUM_CAST(Node3D::RotationOrder)
+
#endif // NODE_3D_H
diff --git a/scene/3d/occluder_instance_3d.cpp b/scene/3d/occluder_instance_3d.cpp
index d3a256db34..f848eaab2e 100644
--- a/scene/3d/occluder_instance_3d.cpp
+++ b/scene/3d/occluder_instance_3d.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -29,42 +29,27 @@
/*************************************************************************/
#include "occluder_instance_3d.h"
+
+#include "core/config/project_settings.h"
#include "core/core_string_names.h"
+#include "core/math/geometry_2d.h"
+#include "core/math/triangulate.h"
+#include "scene/3d/importer_mesh_instance_3d.h"
#include "scene/3d/mesh_instance_3d.h"
+#include "scene/resources/importer_mesh.h"
+#include "scene/resources/surface_tool.h"
+
+#ifdef TOOLS_ENABLED
+#include "editor/editor_node.h"
+#endif
RID Occluder3D::get_rid() const {
- if (!occluder.is_valid()) {
- occluder = RS::get_singleton()->occluder_create();
- RS::get_singleton()->occluder_set_mesh(occluder, vertices, indices);
- }
return occluder;
}
-void Occluder3D::set_vertices(PackedVector3Array p_vertices) {
- vertices = p_vertices;
- if (occluder.is_valid()) {
- RS::get_singleton()->occluder_set_mesh(occluder, vertices, indices);
- }
- _update_changes();
-}
-
-PackedVector3Array Occluder3D::get_vertices() const {
- return vertices;
-}
-
-void Occluder3D::set_indices(PackedInt32Array p_indices) {
- indices = p_indices;
- if (occluder.is_valid()) {
- RS::get_singleton()->occluder_set_mesh(occluder, vertices, indices);
- }
- _update_changes();
-}
-
-PackedInt32Array Occluder3D::get_indices() const {
- return indices;
-}
+void Occluder3D::_update() {
+ _update_arrays(vertices, indices);
-void Occluder3D::_update_changes() {
aabb = AABB();
const Vector3 *ptr = vertices.ptr();
@@ -75,9 +60,18 @@ void Occluder3D::_update_changes() {
debug_lines.clear();
debug_mesh.unref();
+ RS::get_singleton()->occluder_set_mesh(occluder, vertices, indices);
emit_changed();
}
+PackedVector3Array Occluder3D::get_vertices() const {
+ return vertices;
+}
+
+PackedInt32Array Occluder3D::get_indices() const {
+ return indices;
+}
+
Vector<Vector3> Occluder3D::get_debug_lines() const {
if (!debug_lines.is_empty()) {
return debug_lines;
@@ -87,14 +81,18 @@ Vector<Vector3> Occluder3D::get_debug_lines() const {
return Vector<Vector3>();
}
+ const Vector3 *vertices_ptr = vertices.ptr();
+ debug_lines.resize(indices.size() / 3 * 6);
+ Vector3 *line_ptr = debug_lines.ptrw();
+ int line_i = 0;
for (int i = 0; i < indices.size() / 3; i++) {
for (int j = 0; j < 3; j++) {
int a = indices[i * 3 + j];
int b = indices[i * 3 + (j + 1) % 3];
ERR_FAIL_INDEX_V_MSG(a, vertices.size(), Vector<Vector3>(), "Occluder indices are out of range.");
ERR_FAIL_INDEX_V_MSG(b, vertices.size(), Vector<Vector3>(), "Occluder indices are out of range.");
- debug_lines.push_back(vertices[a]);
- debug_lines.push_back(vertices[b]);
+ line_ptr[line_i++] = vertices_ptr[a];
+ line_ptr[line_i++] = vertices_ptr[b];
}
}
return debug_lines;
@@ -105,7 +103,7 @@ Ref<ArrayMesh> Occluder3D::get_debug_mesh() const {
return debug_mesh;
}
- if (indices.size() % 3 != 0) {
+ if (vertices.is_empty() || indices.is_empty() || indices.size() % 3 != 0) {
return debug_mesh;
}
@@ -114,7 +112,7 @@ Ref<ArrayMesh> Occluder3D::get_debug_mesh() const {
arrays[Mesh::ARRAY_VERTEX] = vertices;
arrays[Mesh::ARRAY_INDEX] = indices;
- debug_mesh.instance();
+ debug_mesh.instantiate();
debug_mesh->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, arrays);
return debug_mesh;
}
@@ -123,18 +121,19 @@ AABB Occluder3D::get_aabb() const {
return aabb;
}
-void Occluder3D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_vertices", "vertices"), &Occluder3D::set_vertices);
- ClassDB::bind_method(D_METHOD("get_vertices"), &Occluder3D::get_vertices);
-
- ClassDB::bind_method(D_METHOD("set_indices", "indices"), &Occluder3D::set_indices);
- ClassDB::bind_method(D_METHOD("get_indices"), &Occluder3D::get_indices);
+void Occluder3D::_notification(int p_what) {
+ switch (p_what) {
+ case NOTIFICATION_POSTINITIALIZE: {
+ _update();
+ } break;
+ }
+}
- ADD_PROPERTY(PropertyInfo(Variant::PACKED_VECTOR3_ARRAY, "vertices", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_vertices", "get_vertices");
- ADD_PROPERTY(PropertyInfo(Variant::PACKED_INT32_ARRAY, "indices", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_indices", "get_indices");
+void Occluder3D::_bind_methods() {
}
Occluder3D::Occluder3D() {
+ occluder = RS::get_singleton()->occluder_create();
}
Occluder3D::~Occluder3D() {
@@ -142,6 +141,289 @@ Occluder3D::~Occluder3D() {
RS::get_singleton()->free(occluder);
}
}
+
+/////////////////////////////////////////////////
+
+void ArrayOccluder3D::set_arrays(PackedVector3Array p_vertices, PackedInt32Array p_indices) {
+ vertices = p_vertices;
+ indices = p_indices;
+ _update();
+}
+
+void ArrayOccluder3D::set_vertices(PackedVector3Array p_vertices) {
+ vertices = p_vertices;
+ _update();
+}
+
+void ArrayOccluder3D::set_indices(PackedInt32Array p_indices) {
+ indices = p_indices;
+ _update();
+}
+
+void ArrayOccluder3D::_update_arrays(PackedVector3Array &r_vertices, PackedInt32Array &r_indices) {
+ r_vertices = vertices;
+ r_indices = indices;
+}
+
+void ArrayOccluder3D::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("set_arrays", "vertices", "indices"), &ArrayOccluder3D::set_arrays);
+
+ ClassDB::bind_method(D_METHOD("set_vertices", "vertices"), &ArrayOccluder3D::set_vertices);
+ ClassDB::bind_method(D_METHOD("get_vertices"), &ArrayOccluder3D::get_vertices);
+
+ ClassDB::bind_method(D_METHOD("set_indices", "indices"), &ArrayOccluder3D::set_indices);
+ ClassDB::bind_method(D_METHOD("get_indices"), &ArrayOccluder3D::get_indices);
+
+ ADD_PROPERTY(PropertyInfo(Variant::PACKED_VECTOR3_ARRAY, "vertices", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "set_vertices", "get_vertices");
+ ADD_PROPERTY(PropertyInfo(Variant::PACKED_INT32_ARRAY, "indices", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "set_indices", "get_indices");
+}
+
+ArrayOccluder3D::ArrayOccluder3D() {
+}
+
+ArrayOccluder3D::~ArrayOccluder3D() {
+}
+
+/////////////////////////////////////////////////
+
+void QuadOccluder3D::set_size(const Vector2 &p_size) {
+ if (size == p_size) {
+ return;
+ }
+
+ size = p_size.max(Vector2());
+ _update();
+}
+
+Vector2 QuadOccluder3D::get_size() const {
+ return size;
+}
+
+void QuadOccluder3D::_update_arrays(PackedVector3Array &r_vertices, PackedInt32Array &r_indices) {
+ Vector2 _size = Vector2(size.x / 2.0f, size.y / 2.0f);
+
+ r_vertices = {
+ Vector3(-_size.x, -_size.y, 0),
+ Vector3(-_size.x, _size.y, 0),
+ Vector3(_size.x, _size.y, 0),
+ Vector3(_size.x, -_size.y, 0),
+ };
+
+ r_indices = {
+ 0, 1, 2,
+ 0, 2, 3
+ };
+}
+
+void QuadOccluder3D::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("set_size", "size"), &QuadOccluder3D::set_size);
+ ClassDB::bind_method(D_METHOD("get_size"), &QuadOccluder3D::get_size);
+
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "size"), "set_size", "get_size");
+}
+
+QuadOccluder3D::QuadOccluder3D() {
+}
+
+QuadOccluder3D::~QuadOccluder3D() {
+}
+
+/////////////////////////////////////////////////
+
+void BoxOccluder3D::set_size(const Vector3 &p_size) {
+ if (size == p_size) {
+ return;
+ }
+
+ size = Vector3(MAX(p_size.x, 0.0f), MAX(p_size.y, 0.0f), MAX(p_size.z, 0.0f));
+ _update();
+}
+
+Vector3 BoxOccluder3D::get_size() const {
+ return size;
+}
+
+void BoxOccluder3D::_update_arrays(PackedVector3Array &r_vertices, PackedInt32Array &r_indices) {
+ Vector3 _size = Vector3(size.x / 2.0f, size.y / 2.0f, size.z / 2.0f);
+
+ r_vertices = {
+ // front
+ Vector3(-_size.x, -_size.y, _size.z),
+ Vector3(_size.x, -_size.y, _size.z),
+ Vector3(_size.x, _size.y, _size.z),
+ Vector3(-_size.x, _size.y, _size.z),
+ // back
+ Vector3(-_size.x, -_size.y, -_size.z),
+ Vector3(_size.x, -_size.y, -_size.z),
+ Vector3(_size.x, _size.y, -_size.z),
+ Vector3(-_size.x, _size.y, -_size.z),
+ };
+
+ r_indices = {
+ // front
+ 0, 1, 2,
+ 2, 3, 0,
+ // right
+ 1, 5, 6,
+ 6, 2, 1,
+ // back
+ 7, 6, 5,
+ 5, 4, 7,
+ // left
+ 4, 0, 3,
+ 3, 7, 4,
+ // bottom
+ 4, 5, 1,
+ 1, 0, 4,
+ // top
+ 3, 2, 6,
+ 6, 7, 3
+ };
+}
+
+void BoxOccluder3D::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("set_size", "size"), &BoxOccluder3D::set_size);
+ ClassDB::bind_method(D_METHOD("get_size"), &BoxOccluder3D::get_size);
+
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "size"), "set_size", "get_size");
+}
+
+BoxOccluder3D::BoxOccluder3D() {
+}
+
+BoxOccluder3D::~BoxOccluder3D() {
+}
+
+/////////////////////////////////////////////////
+
+void SphereOccluder3D::set_radius(float p_radius) {
+ if (radius == p_radius) {
+ return;
+ }
+
+ radius = MAX(p_radius, 0.0f);
+ _update();
+}
+
+float SphereOccluder3D::get_radius() const {
+ return radius;
+}
+
+void SphereOccluder3D::_update_arrays(PackedVector3Array &r_vertices, PackedInt32Array &r_indices) {
+ r_vertices.resize((RINGS + 2) * (RADIAL_SEGMENTS + 1));
+ int vertex_i = 0;
+ Vector3 *vertex_ptr = r_vertices.ptrw();
+
+ r_indices.resize((RINGS + 1) * RADIAL_SEGMENTS * 6);
+ int idx_i = 0;
+ int *idx_ptr = r_indices.ptrw();
+
+ int current_row = 0;
+ int previous_row = 0;
+ int point = 0;
+ for (int j = 0; j <= (RINGS + 1); j++) {
+ float v = j / float(RINGS + 1);
+ float w = Math::sin(Math_PI * v);
+ float y = Math::cos(Math_PI * v);
+ for (int i = 0; i <= RADIAL_SEGMENTS; i++) {
+ float u = i / float(RADIAL_SEGMENTS);
+
+ float x = Math::cos(u * Math_TAU);
+ float z = Math::sin(u * Math_TAU);
+ vertex_ptr[vertex_i++] = Vector3(x * w, y, z * w) * radius;
+
+ if (i > 0 && j > 0) {
+ idx_ptr[idx_i++] = previous_row + i - 1;
+ idx_ptr[idx_i++] = previous_row + i;
+ idx_ptr[idx_i++] = current_row + i - 1;
+
+ idx_ptr[idx_i++] = previous_row + i;
+ idx_ptr[idx_i++] = current_row + i;
+ idx_ptr[idx_i++] = current_row + i - 1;
+ }
+
+ point++;
+ }
+
+ previous_row = current_row;
+ current_row = point;
+ }
+}
+
+void SphereOccluder3D::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("set_radius", "radius"), &SphereOccluder3D::set_radius);
+ ClassDB::bind_method(D_METHOD("get_radius"), &SphereOccluder3D::get_radius);
+
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "radius"), "set_radius", "get_radius");
+}
+
+SphereOccluder3D::SphereOccluder3D() {
+}
+
+SphereOccluder3D::~SphereOccluder3D() {
+}
+
+/////////////////////////////////////////////////
+
+void PolygonOccluder3D::set_polygon(const Vector<Vector2> &p_polygon) {
+ polygon = p_polygon;
+ _update();
+}
+
+Vector<Vector2> PolygonOccluder3D::get_polygon() const {
+ return polygon;
+}
+
+void PolygonOccluder3D::_update_arrays(PackedVector3Array &r_vertices, PackedInt32Array &r_indices) {
+ if (polygon.size() < 3) {
+ r_vertices.clear();
+ r_indices.clear();
+ return;
+ }
+
+ Vector<Point2> occluder_polygon = polygon;
+ if (Triangulate::get_area(occluder_polygon) > 0) {
+ occluder_polygon.reverse();
+ }
+
+ Vector<int> occluder_indices = Geometry2D::triangulate_polygon(occluder_polygon);
+
+ if (occluder_indices.size() < 3) {
+ r_vertices.clear();
+ r_indices.clear();
+ ERR_FAIL_MSG("Failed to triangulate PolygonOccluder3D. Make sure the polygon doesn't have any intersecting edges.");
+ }
+
+ r_vertices.resize(occluder_polygon.size());
+ Vector3 *vertex_ptr = r_vertices.ptrw();
+ const Vector2 *polygon_ptr = occluder_polygon.ptr();
+ for (int i = 0; i < occluder_polygon.size(); i++) {
+ vertex_ptr[i] = Vector3(polygon_ptr[i].x, polygon_ptr[i].y, 0.0);
+ }
+
+ r_indices.resize(occluder_indices.size());
+ memcpy(r_indices.ptrw(), occluder_indices.ptr(), occluder_indices.size() * sizeof(int));
+}
+
+bool PolygonOccluder3D::_has_editable_3d_polygon_no_depth() const {
+ return false;
+}
+
+void PolygonOccluder3D::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("set_polygon", "polygon"), &PolygonOccluder3D::set_polygon);
+ ClassDB::bind_method(D_METHOD("get_polygon"), &PolygonOccluder3D::get_polygon);
+
+ ClassDB::bind_method(D_METHOD("_has_editable_3d_polygon_no_depth"), &PolygonOccluder3D::_has_editable_3d_polygon_no_depth);
+
+ ADD_PROPERTY(PropertyInfo(Variant::PACKED_VECTOR2_ARRAY, "polygon"), "set_polygon", "get_polygon");
+}
+
+PolygonOccluder3D::PolygonOccluder3D() {
+}
+
+PolygonOccluder3D::~PolygonOccluder3D() {
+}
+
/////////////////////////////////////////////////
AABB OccluderInstance3D::get_aabb() const {
@@ -151,10 +433,6 @@ AABB OccluderInstance3D::get_aabb() const {
return AABB();
}
-Vector<Face3> OccluderInstance3D::get_faces(uint32_t p_usage_flags) const {
- return Vector<Face3>();
-}
-
void OccluderInstance3D::set_occluder(const Ref<Occluder3D> &p_occluder) {
if (occluder == p_occluder) {
return;
@@ -173,11 +451,20 @@ void OccluderInstance3D::set_occluder(const Ref<Occluder3D> &p_occluder) {
set_base(RID());
}
- update_gizmo();
+ update_gizmos();
+ update_configuration_warnings();
+
+#ifdef TOOLS_ENABLED
+ // PolygonOccluder3D is edited via an editor plugin, this ensures the plugin is shown/hidden when necessary
+ if (Engine::get_singleton()->is_editor_hint()) {
+ EditorNode::get_singleton()->call_deferred(SNAME("edit_current"));
+ }
+#endif
}
void OccluderInstance3D::_occluder_changed() {
- update_gizmo();
+ update_gizmos();
+ update_configuration_warnings();
}
Ref<Occluder3D> OccluderInstance3D::get_occluder() const {
@@ -186,24 +473,37 @@ Ref<Occluder3D> OccluderInstance3D::get_occluder() const {
void OccluderInstance3D::set_bake_mask(uint32_t p_mask) {
bake_mask = p_mask;
+ update_configuration_warnings();
}
uint32_t OccluderInstance3D::get_bake_mask() const {
return bake_mask;
}
-void OccluderInstance3D::set_bake_mask_bit(int p_layer, bool p_enable) {
- ERR_FAIL_INDEX(p_layer, 32);
- if (p_enable) {
- set_bake_mask(bake_mask | (1 << p_layer));
+void OccluderInstance3D::set_bake_simplification_distance(float p_dist) {
+ bake_simplification_dist = MAX(p_dist, 0.0f);
+}
+
+float OccluderInstance3D::get_bake_simplification_distance() const {
+ return bake_simplification_dist;
+}
+
+void OccluderInstance3D::set_bake_mask_value(int p_layer_number, bool p_value) {
+ ERR_FAIL_COND_MSG(p_layer_number < 1, "Render layer number must be between 1 and 20 inclusive.");
+ ERR_FAIL_COND_MSG(p_layer_number > 20, "Render layer number must be between 1 and 20 inclusive.");
+ uint32_t mask = get_bake_mask();
+ if (p_value) {
+ mask |= 1 << (p_layer_number - 1);
} else {
- set_bake_mask(bake_mask & (~(1 << p_layer)));
+ mask &= ~(1 << (p_layer_number - 1));
}
+ set_bake_mask(mask);
}
-bool OccluderInstance3D::get_bake_mask_bit(int p_layer) const {
- ERR_FAIL_INDEX_V(p_layer, 32, false);
- return (bake_mask & (1 << p_layer));
+bool OccluderInstance3D::get_bake_mask_value(int p_layer_number) const {
+ ERR_FAIL_COND_V_MSG(p_layer_number < 1, false, "Render layer number must be between 1 and 20 inclusive.");
+ ERR_FAIL_COND_V_MSG(p_layer_number > 20, false, "Render layer number must be between 1 and 20 inclusive.");
+ return bake_mask & (1 << (p_layer_number - 1));
}
bool OccluderInstance3D::_bake_material_check(Ref<Material> p_material) {
@@ -214,6 +514,47 @@ bool OccluderInstance3D::_bake_material_check(Ref<Material> p_material) {
return true;
}
+void OccluderInstance3D::_bake_surface(const Transform3D &p_transform, Array p_surface_arrays, Ref<Material> p_material, float p_simplification_dist, PackedVector3Array &r_vertices, PackedInt32Array &r_indices) {
+ if (!_bake_material_check(p_material)) {
+ return;
+ }
+ ERR_FAIL_COND_MSG(p_surface_arrays.size() != Mesh::ARRAY_MAX, "Invalid surface array.");
+
+ PackedVector3Array vertices = p_surface_arrays[Mesh::ARRAY_VERTEX];
+ PackedInt32Array indices = p_surface_arrays[Mesh::ARRAY_INDEX];
+
+ if (vertices.size() == 0 || indices.size() == 0) {
+ return;
+ }
+
+ Vector3 *vertices_ptr = vertices.ptrw();
+ for (int j = 0; j < vertices.size(); j++) {
+ vertices_ptr[j] = p_transform.xform(vertices_ptr[j]);
+ }
+
+ if (!Math::is_zero_approx(p_simplification_dist) && SurfaceTool::simplify_func) {
+ float error_scale = SurfaceTool::simplify_scale_func((float *)vertices.ptr(), vertices.size(), sizeof(Vector3));
+ float target_error = p_simplification_dist / error_scale;
+ float error = -1.0f;
+ int target_index_count = MIN(indices.size(), 36);
+ uint32_t index_count = SurfaceTool::simplify_func((unsigned int *)indices.ptrw(), (unsigned int *)indices.ptr(), indices.size(), (float *)vertices.ptr(), vertices.size(), sizeof(Vector3), target_index_count, target_error, &error);
+ indices.resize(index_count);
+ }
+
+ SurfaceTool::strip_mesh_arrays(vertices, indices);
+
+ int vertex_offset = r_vertices.size();
+ r_vertices.resize(vertex_offset + vertices.size());
+ memcpy(r_vertices.ptrw() + vertex_offset, vertices.ptr(), vertices.size() * sizeof(Vector3));
+
+ int index_offset = r_indices.size();
+ r_indices.resize(index_offset + indices.size());
+ int *idx_ptr = r_indices.ptrw();
+ for (int j = 0; j < indices.size(); j++) {
+ idx_ptr[index_offset + j] = vertex_offset + indices[j];
+ }
+}
+
void OccluderInstance3D::_bake_node(Node *p_node, PackedVector3Array &r_vertices, PackedInt32Array &r_indices) {
MeshInstance3D *mi = Object::cast_to<MeshInstance3D>(p_node);
if (mi && mi->is_visible_in_tree()) {
@@ -233,61 +574,79 @@ void OccluderInstance3D::_bake_node(Node *p_node, PackedVector3Array &r_vertices
}
if (valid) {
- Transform global_to_local = get_global_transform().affine_inverse() * mi->get_global_transform();
+ Transform3D global_to_local = get_global_transform().affine_inverse() * mi->get_global_transform();
for (int i = 0; i < mesh->get_surface_count(); i++) {
- if (mesh->surface_get_primitive_type(i) != Mesh::PRIMITIVE_TRIANGLES) {
- continue;
- }
+ _bake_surface(global_to_local, mesh->surface_get_arrays(i), mi->get_active_material(i), bake_simplification_dist, r_vertices, r_indices);
+ }
+ }
+ }
- if (mi->get_surface_override_material(i).is_valid()) {
- if (!_bake_material_check(mi->get_surface_override_material(i))) {
- continue;
- }
- } else {
- if (!_bake_material_check(mesh->surface_get_material(i))) {
- continue;
- }
- }
+ for (int i = 0; i < p_node->get_child_count(); i++) {
+ Node *child = p_node->get_child(i);
+ if (!child->get_owner()) {
+ continue; // may be a helper
+ }
- Array arrays = mesh->surface_get_arrays(i);
+ _bake_node(child, r_vertices, r_indices);
+ }
+}
- int vertex_offset = r_vertices.size();
- PackedVector3Array vertices = arrays[Mesh::ARRAY_VERTEX];
- r_vertices.resize(r_vertices.size() + vertices.size());
+void OccluderInstance3D::bake_single_node(const Node3D *p_node, float p_simplification_distance, PackedVector3Array &r_vertices, PackedInt32Array &r_indices) {
+ ERR_FAIL_COND(!p_node);
- Vector3 *vtx_ptr = r_vertices.ptrw();
- for (int j = 0; j < vertices.size(); j++) {
- vtx_ptr[vertex_offset + j] = global_to_local.xform(vertices[j]);
- }
+ Transform3D xform = p_node->is_inside_tree() ? p_node->get_global_transform() : p_node->get_transform();
- int index_offset = r_indices.size();
- PackedInt32Array indices = arrays[Mesh::ARRAY_INDEX];
- r_indices.resize(r_indices.size() + indices.size());
+ const MeshInstance3D *mi = Object::cast_to<MeshInstance3D>(p_node);
+ if (mi) {
+ Ref<Mesh> mesh = mi->get_mesh();
+ bool valid = true;
- int *idx_ptr = r_indices.ptrw();
- for (int j = 0; j < indices.size(); j++) {
- idx_ptr[index_offset + j] = vertex_offset + indices[j];
- }
+ if (mesh.is_null()) {
+ valid = false;
+ }
+
+ if (valid && !_bake_material_check(mi->get_material_override())) {
+ valid = false;
+ }
+
+ if (valid) {
+ for (int i = 0; i < mesh->get_surface_count(); i++) {
+ _bake_surface(xform, mesh->surface_get_arrays(i), mi->get_active_material(i), p_simplification_distance, r_vertices, r_indices);
}
}
}
- for (int i = 0; i < p_node->get_child_count(); i++) {
- Node *child = p_node->get_child(i);
- if (!child->get_owner()) {
- continue; //maybe a helper
+ const ImporterMeshInstance3D *imi = Object::cast_to<ImporterMeshInstance3D>(p_node);
+ if (imi) {
+ Ref<ImporterMesh> mesh = imi->get_mesh();
+ bool valid = true;
+
+ if (mesh.is_null()) {
+ valid = false;
}
- _bake_node(child, r_vertices, r_indices);
+ if (valid) {
+ for (int i = 0; i < mesh->get_surface_count(); i++) {
+ Ref<Material> material = imi->get_surface_material(i);
+ if (material.is_null()) {
+ material = mesh->get_surface_material(i);
+ }
+ _bake_surface(xform, mesh->get_surface_arrays(i), material, p_simplification_distance, r_vertices, r_indices);
+ }
+ }
}
}
-OccluderInstance3D::BakeError OccluderInstance3D::bake(Node *p_from_node, String p_occluder_path) {
- if (p_occluder_path == "") {
+OccluderInstance3D::BakeError OccluderInstance3D::bake_scene(Node *p_from_node, String p_occluder_path) {
+ if (p_occluder_path.is_empty()) {
if (get_occluder().is_null()) {
return BAKE_ERROR_NO_SAVE_PATH;
}
+ p_occluder_path = get_occluder()->get_path();
+ if (!p_occluder_path.is_resource_file()) {
+ return BAKE_ERROR_NO_SAVE_PATH;
+ }
}
PackedVector3Array vertices;
@@ -299,33 +658,85 @@ OccluderInstance3D::BakeError OccluderInstance3D::bake(Node *p_from_node, String
return BAKE_ERROR_NO_MESHES;
}
- Ref<Occluder3D> occ;
+ Ref<ArrayOccluder3D> occ;
if (get_occluder().is_valid()) {
occ = get_occluder();
- } else {
- occ.instance();
- occ->set_path(p_occluder_path);
+ set_occluder(Ref<Occluder3D>()); // clear
+ }
+
+ if (occ.is_null()) {
+ occ.instantiate();
}
- occ->set_vertices(vertices);
- occ->set_indices(indices);
+ occ->set_arrays(vertices, indices);
+
+ Error err = ResourceSaver::save(p_occluder_path, occ);
+
+ if (err != OK) {
+ return BAKE_ERROR_CANT_SAVE;
+ }
+
+ occ->set_path(p_occluder_path);
set_occluder(occ);
return BAKE_ERROR_OK;
}
+TypedArray<String> OccluderInstance3D::get_configuration_warnings() const {
+ TypedArray<String> warnings = Node::get_configuration_warnings();
+
+ if (!bool(GLOBAL_GET("rendering/occlusion_culling/use_occlusion_culling"))) {
+ warnings.push_back(RTR("Occlusion culling is disabled in the Project Settings, which means occlusion culling won't be performed in the root viewport.\nTo resolve this, open the Project Settings and enable Rendering > Occlusion Culling > Use Occlusion Culling."));
+ }
+
+ if (bake_mask == 0) {
+ warnings.push_back(RTR("The Bake Mask has no bits enabled, which means baking will not produce any occluder meshes for this OccluderInstance3D.\nTo resolve this, enable at least one bit in the Bake Mask property."));
+ }
+
+ if (occluder.is_null()) {
+ warnings.push_back(RTR("No occluder mesh is defined in the Occluder property, so no occlusion culling will be performed using this OccluderInstance3D.\nTo resolve this, set the Occluder property to one of the primitive occluder types or bake the scene meshes by selecting the OccluderInstance3D and pressing the Bake Occluders button at the top of the 3D editor viewport."));
+ } else {
+ Ref<ArrayOccluder3D> arr_occluder = occluder;
+ if (arr_occluder.is_valid() && arr_occluder->get_indices().size() < 3) {
+ // Setting a new ArrayOccluder3D from the inspector will create an empty occluder,
+ // so warn the user about this.
+ warnings.push_back(RTR("The occluder mesh has less than 3 vertices, so no occlusion culling will be performed using this OccluderInstance3D.\nTo generate a proper occluder mesh, select the OccluderInstance3D then use the Bake Occluders button at the top of the 3D editor viewport."));
+ }
+ Ref<PolygonOccluder3D> poly_occluder = occluder;
+ if (poly_occluder.is_valid() && poly_occluder->get_polygon().size() < 3) {
+ warnings.push_back(RTR("The polygon occluder has less than 3 vertices, so no occlusion culling will be performed using this OccluderInstance3D.\nVertices can be added in the inspector or using the polygon editing tools at the top of the 3D editor viewport."));
+ }
+ }
+
+ return warnings;
+}
+
+bool OccluderInstance3D::_is_editable_3d_polygon() const {
+ return Ref<PolygonOccluder3D>(occluder).is_valid();
+}
+
+Ref<Resource> OccluderInstance3D::_get_editable_3d_polygon_resource() const {
+ return occluder;
+}
+
void OccluderInstance3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_bake_mask", "mask"), &OccluderInstance3D::set_bake_mask);
ClassDB::bind_method(D_METHOD("get_bake_mask"), &OccluderInstance3D::get_bake_mask);
- ClassDB::bind_method(D_METHOD("set_bake_mask_bit", "layer", "enabled"), &OccluderInstance3D::set_bake_mask_bit);
- ClassDB::bind_method(D_METHOD("get_bake_mask_bit", "layer"), &OccluderInstance3D::get_bake_mask_bit);
+ ClassDB::bind_method(D_METHOD("set_bake_mask_value", "layer_number", "value"), &OccluderInstance3D::set_bake_mask_value);
+ ClassDB::bind_method(D_METHOD("get_bake_mask_value", "layer_number"), &OccluderInstance3D::get_bake_mask_value);
+ ClassDB::bind_method(D_METHOD("set_bake_simplification_distance", "simplification_distance"), &OccluderInstance3D::set_bake_simplification_distance);
+ ClassDB::bind_method(D_METHOD("get_bake_simplification_distance"), &OccluderInstance3D::get_bake_simplification_distance);
ClassDB::bind_method(D_METHOD("set_occluder", "occluder"), &OccluderInstance3D::set_occluder);
ClassDB::bind_method(D_METHOD("get_occluder"), &OccluderInstance3D::get_occluder);
+ ClassDB::bind_method(D_METHOD("_is_editable_3d_polygon"), &OccluderInstance3D::_is_editable_3d_polygon);
+ ClassDB::bind_method(D_METHOD("_get_editable_3d_polygon_resource"), &OccluderInstance3D::_get_editable_3d_polygon_resource);
+
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "occluder", PROPERTY_HINT_RESOURCE_TYPE, "Occluder3D"), "set_occluder", "get_occluder");
ADD_GROUP("Bake", "bake_");
ADD_PROPERTY(PropertyInfo(Variant::INT, "bake_mask", PROPERTY_HINT_LAYERS_3D_RENDER), "set_bake_mask", "get_bake_mask");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "bake_simplification_distance", PROPERTY_HINT_RANGE, "0.0,2.0,0.01"), "set_bake_simplification_distance", "get_bake_simplification_distance");
}
OccluderInstance3D::OccluderInstance3D() {
diff --git a/scene/3d/occluder_instance_3d.h b/scene/3d/occluder_instance_3d.h
index 4bb468274d..ed6610074e 100644
--- a/scene/3d/occluder_instance_3d.h
+++ b/scene/3d/occluder_instance_3d.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -37,24 +37,23 @@ class Occluder3D : public Resource {
GDCLASS(Occluder3D, Resource);
RES_BASE_EXTENSION("occ");
- mutable RID occluder;
- mutable Ref<ArrayMesh> debug_mesh;
- mutable Vector<Vector3> debug_lines;
- AABB aabb;
-
+ RID occluder;
PackedVector3Array vertices;
PackedInt32Array indices;
+ AABB aabb;
- void _update_changes();
+ mutable Ref<ArrayMesh> debug_mesh;
+ mutable Vector<Vector3> debug_lines;
protected:
+ void _update();
+ virtual void _update_arrays(PackedVector3Array &r_vertices, PackedInt32Array &r_indices) = 0;
+
static void _bind_methods();
+ void _notification(int p_what);
public:
- void set_vertices(PackedVector3Array p_vertices);
PackedVector3Array get_vertices() const;
-
- void set_indices(PackedInt32Array p_indices);
PackedInt32Array get_indices() const;
Vector<Vector3> get_debug_lines() const;
@@ -63,7 +62,102 @@ public:
virtual RID get_rid() const override;
Occluder3D();
- ~Occluder3D();
+ virtual ~Occluder3D();
+};
+
+class ArrayOccluder3D : public Occluder3D {
+ GDCLASS(ArrayOccluder3D, Occluder3D);
+
+ PackedVector3Array vertices;
+ PackedInt32Array indices;
+
+protected:
+ virtual void _update_arrays(PackedVector3Array &r_vertices, PackedInt32Array &r_indices) override;
+ static void _bind_methods();
+
+public:
+ void set_arrays(PackedVector3Array p_vertices, PackedInt32Array p_indices);
+ void set_vertices(PackedVector3Array p_vertices);
+ void set_indices(PackedInt32Array p_indices);
+
+ ArrayOccluder3D();
+ ~ArrayOccluder3D();
+};
+
+class QuadOccluder3D : public Occluder3D {
+ GDCLASS(QuadOccluder3D, Occluder3D);
+
+private:
+ Vector2 size = Vector2(1.0f, 1.0f);
+
+protected:
+ virtual void _update_arrays(PackedVector3Array &r_vertices, PackedInt32Array &r_indices) override;
+ static void _bind_methods();
+
+public:
+ Vector2 get_size() const;
+ void set_size(const Vector2 &p_size);
+
+ QuadOccluder3D();
+ ~QuadOccluder3D();
+};
+
+class BoxOccluder3D : public Occluder3D {
+ GDCLASS(BoxOccluder3D, Occluder3D);
+
+private:
+ Vector3 size = Vector3(1.0f, 1.0f, 1.0f);
+
+protected:
+ virtual void _update_arrays(PackedVector3Array &r_vertices, PackedInt32Array &r_indices) override;
+ static void _bind_methods();
+
+public:
+ Vector3 get_size() const;
+ void set_size(const Vector3 &p_size);
+
+ BoxOccluder3D();
+ ~BoxOccluder3D();
+};
+
+class SphereOccluder3D : public Occluder3D {
+ GDCLASS(SphereOccluder3D, Occluder3D);
+
+private:
+ static constexpr int RINGS = 7;
+ static constexpr int RADIAL_SEGMENTS = 7;
+ float radius = 1.0f;
+
+protected:
+ virtual void _update_arrays(PackedVector3Array &r_vertices, PackedInt32Array &r_indices) override;
+ static void _bind_methods();
+
+public:
+ float get_radius() const;
+ void set_radius(float p_radius);
+
+ SphereOccluder3D();
+ ~SphereOccluder3D();
+};
+
+class PolygonOccluder3D : public Occluder3D {
+ GDCLASS(PolygonOccluder3D, Occluder3D);
+
+private:
+ Vector<Vector2> polygon;
+
+ bool _has_editable_3d_polygon_no_depth() const;
+
+protected:
+ virtual void _update_arrays(PackedVector3Array &r_vertices, PackedInt32Array &r_indices) override;
+ static void _bind_methods();
+
+public:
+ void set_polygon(const Vector<Vector2> &p_polygon);
+ Vector<Vector2> get_polygon() const;
+
+ PolygonOccluder3D();
+ ~PolygonOccluder3D();
};
class OccluderInstance3D : public VisualInstance3D {
@@ -72,34 +166,46 @@ class OccluderInstance3D : public VisualInstance3D {
private:
Ref<Occluder3D> occluder;
uint32_t bake_mask = 0xFFFFFFFF;
+ float bake_simplification_dist = 0.1f;
void _occluder_changed();
- bool _bake_material_check(Ref<Material> p_material);
+ static bool _bake_material_check(Ref<Material> p_material);
+ static void _bake_surface(const Transform3D &p_transform, Array p_surface_arrays, Ref<Material> p_material, float p_simplification_dist, PackedVector3Array &r_vertices, PackedInt32Array &r_indices);
void _bake_node(Node *p_node, PackedVector3Array &r_vertices, PackedInt32Array &r_indices);
+ bool _is_editable_3d_polygon() const;
+ Ref<Resource> _get_editable_3d_polygon_resource() const;
+
protected:
static void _bind_methods();
public:
+ virtual TypedArray<String> get_configuration_warnings() const override;
+
enum BakeError {
BAKE_ERROR_OK,
BAKE_ERROR_NO_SAVE_PATH,
BAKE_ERROR_NO_MESHES,
+ BAKE_ERROR_CANT_SAVE,
};
void set_occluder(const Ref<Occluder3D> &p_occluder);
Ref<Occluder3D> get_occluder() const;
virtual AABB get_aabb() const override;
- virtual Vector<Face3> get_faces(uint32_t p_usage_flags) const override;
void set_bake_mask(uint32_t p_mask);
uint32_t get_bake_mask() const;
- void set_bake_mask_bit(int p_layer, bool p_enable);
- bool get_bake_mask_bit(int p_layer) const;
- BakeError bake(Node *p_from_node, String p_occluder_path = "");
+ void set_bake_simplification_distance(float p_dist);
+ float get_bake_simplification_distance() const;
+
+ void set_bake_mask_value(int p_layer_number, bool p_enable);
+ bool get_bake_mask_value(int p_layer_number) const;
+
+ BakeError bake_scene(Node *p_from_node, String p_occluder_path = "");
+ static void bake_single_node(const Node3D *p_node, float p_simplification_distance, PackedVector3Array &r_vertices, PackedInt32Array &r_indices);
OccluderInstance3D();
~OccluderInstance3D();
diff --git a/scene/3d/path_3d.cpp b/scene/3d/path_3d.cpp
index 4ec4ee6207..17a68f38f5 100644
--- a/scene/3d/path_3d.cpp
+++ b/scene/3d/path_3d.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -30,18 +30,12 @@
#include "path_3d.h"
-#include "core/config/engine.h"
-#include "scene/scene_string_names.h"
-
-void Path3D::_notification(int p_what) {
-}
-
void Path3D::_curve_changed() {
if (is_inside_tree() && Engine::get_singleton()->is_editor_hint()) {
- update_gizmo();
+ update_gizmos();
}
if (is_inside_tree()) {
- emit_signal("curve_changed");
+ emit_signal(SNAME("curve_changed"));
}
// update the configuration warnings of all children of type PathFollow
@@ -94,27 +88,39 @@ void PathFollow3D::_update_transform(bool p_update_xyz_rot) {
return;
}
- float bl = c->get_baked_length();
+ real_t bl = c->get_baked_length();
if (bl == 0.0) {
return;
}
- float bi = c->get_bake_interval();
- float o_next = offset + bi;
+ real_t bi = c->get_bake_interval();
+ real_t o_next = offset + bi;
+ real_t o_prev = offset - bi;
if (loop) {
o_next = Math::fposmod(o_next, bl);
- } else if (rotation_mode == ROTATION_ORIENTED && o_next >= bl) {
- o_next = bl;
+ o_prev = Math::fposmod(o_prev, bl);
+ } else if (rotation_mode == ROTATION_ORIENTED) {
+ if (o_next >= bl) {
+ o_next = bl;
+ }
+ if (o_prev <= 0) {
+ o_prev = 0;
+ }
}
Vector3 pos = c->interpolate_baked(offset, cubic);
- Transform t = get_transform();
+ Transform3D t = get_transform();
// Vector3 pos_offset = Vector3(h_offset, v_offset, 0); not used in all cases
// will be replaced by "Vector3(h_offset, v_offset, 0)" where it was formerly used
if (rotation_mode == ROTATION_ORIENTED) {
Vector3 forward = c->interpolate_baked(o_next, cubic) - pos;
+ // Try with the previous position
+ if (forward.length_squared() < CMP_EPSILON2) {
+ forward = pos - c->interpolate_baked(o_prev, cubic);
+ }
+
if (forward.length_squared() < CMP_EPSILON2) {
forward = Vector3(0, 0, 1);
} else {
@@ -140,7 +146,7 @@ void PathFollow3D::_update_transform(bool p_update_xyz_rot) {
Vector3 sideways = up.cross(forward).normalized();
up = forward.cross(sideways).normalized();
- t.basis.set(sideways, up, forward);
+ t.basis.set_columns(sideways, up, forward);
t.basis.scale_local(scale);
t.origin = pos + sideways * h_offset + up * v_offset;
@@ -157,8 +163,8 @@ void PathFollow3D::_update_transform(bool p_update_xyz_rot) {
Vector3 t_cur = (c->interpolate_baked(offset + delta_offset, cubic) - pos).normalized();
Vector3 axis = t_prev.cross(t_cur);
- float dot = t_prev.dot(t_cur);
- float angle = Math::acos(CLAMP(dot, -1, 1));
+ real_t dot = t_prev.dot(t_cur);
+ real_t angle = Math::acos(CLAMP(dot, -1, 1));
if (likely(!Math::is_zero_approx(angle))) {
if (rotation_mode == ROTATION_Y) {
@@ -177,7 +183,7 @@ void PathFollow3D::_update_transform(bool p_update_xyz_rot) {
}
// do the additional tilting
- float tilt_angle = c->interpolate_baked_tilt(offset);
+ real_t tilt_angle = c->interpolate_baked_tilt(offset);
Vector3 tilt_axis = t_cur; // not sure what tilt is supposed to do, is this correct??
if (likely(!Math::is_zero_approx(Math::abs(tilt_angle)))) {
@@ -214,8 +220,8 @@ void PathFollow3D::_notification(int p_what) {
_update_transform(false);
}
}
-
} break;
+
case NOTIFICATION_EXIT_TREE: {
path = nullptr;
} break;
@@ -232,13 +238,14 @@ bool PathFollow3D::get_cubic_interpolation() const {
void PathFollow3D::_validate_property(PropertyInfo &property) const {
if (property.name == "offset") {
- float max = 10000;
+ real_t max = 10000;
if (path && path->get_curve().is_valid()) {
max = path->get_curve()->get_baked_length();
}
property.hint_string = "0," + rtos(max) + ",0.01,or_lesser,or_greater";
}
+ Node3D::_validate_property(property);
}
TypedArray<String> PathFollow3D::get_configuration_warnings() const {
@@ -246,11 +253,11 @@ TypedArray<String> PathFollow3D::get_configuration_warnings() const {
if (is_visible_in_tree() && is_inside_tree()) {
if (!Object::cast_to<Path3D>(get_parent())) {
- warnings.push_back(TTR("PathFollow3D only works when set as a child of a Path3D node."));
+ warnings.push_back(RTR("PathFollow3D only works when set as a child of a Path3D node."));
} else {
Path3D *path = Object::cast_to<Path3D>(get_parent());
if (path->get_curve().is_valid() && !path->get_curve()->is_up_vector_enabled() && rotation_mode == ROTATION_ORIENTED) {
- warnings.push_back(TTR("PathFollow3D's ROTATION_ORIENTED requires \"Up Vector\" to be enabled in its parent Path3D's Curve resource."));
+ warnings.push_back(RTR("PathFollow3D's ROTATION_ORIENTED requires \"Up Vector\" to be enabled in its parent Path3D's Curve resource."));
}
}
}
@@ -295,15 +302,15 @@ void PathFollow3D::_bind_methods() {
BIND_ENUM_CONSTANT(ROTATION_ORIENTED);
}
-void PathFollow3D::set_offset(float p_offset) {
+void PathFollow3D::set_offset(real_t p_offset) {
delta_offset = p_offset - offset;
offset = p_offset;
if (path) {
if (path->get_curve().is_valid()) {
- float path_length = path->get_curve()->get_baked_length();
+ real_t path_length = path->get_curve()->get_baked_length();
- if (loop) {
+ if (loop && path_length) {
offset = Math::fposmod(offset, path_length);
if (!Math::is_zero_approx(p_offset) && Math::is_zero_approx(offset)) {
offset = path_length;
@@ -317,39 +324,39 @@ void PathFollow3D::set_offset(float p_offset) {
}
}
-void PathFollow3D::set_h_offset(float p_h_offset) {
+void PathFollow3D::set_h_offset(real_t p_h_offset) {
h_offset = p_h_offset;
if (path) {
_update_transform();
}
}
-float PathFollow3D::get_h_offset() const {
+real_t PathFollow3D::get_h_offset() const {
return h_offset;
}
-void PathFollow3D::set_v_offset(float p_v_offset) {
+void PathFollow3D::set_v_offset(real_t p_v_offset) {
v_offset = p_v_offset;
if (path) {
_update_transform();
}
}
-float PathFollow3D::get_v_offset() const {
+real_t PathFollow3D::get_v_offset() const {
return v_offset;
}
-float PathFollow3D::get_offset() const {
+real_t PathFollow3D::get_offset() const {
return offset;
}
-void PathFollow3D::set_unit_offset(float p_unit_offset) {
+void PathFollow3D::set_unit_offset(real_t p_unit_offset) {
if (path && path->get_curve().is_valid() && path->get_curve()->get_baked_length()) {
set_offset(p_unit_offset * path->get_curve()->get_baked_length());
}
}
-float PathFollow3D::get_unit_offset() const {
+real_t PathFollow3D::get_unit_offset() const {
if (path && path->get_curve().is_valid() && path->get_curve()->get_baked_length()) {
return get_offset() / path->get_curve()->get_baked_length();
} else {
diff --git a/scene/3d/path_3d.h b/scene/3d/path_3d.h
index 8545370a4a..e9ab557693 100644
--- a/scene/3d/path_3d.h
+++ b/scene/3d/path_3d.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -42,7 +42,6 @@ class Path3D : public Node3D {
void _curve_changed();
protected:
- void _notification(int p_what);
static void _bind_methods();
public:
@@ -83,17 +82,17 @@ protected:
static void _bind_methods();
public:
- void set_offset(float p_offset);
- float get_offset() const;
+ void set_offset(real_t p_offset);
+ real_t get_offset() const;
- void set_h_offset(float p_h_offset);
- float get_h_offset() const;
+ void set_h_offset(real_t p_h_offset);
+ real_t get_h_offset() const;
- void set_v_offset(float p_v_offset);
- float get_v_offset() const;
+ void set_v_offset(real_t p_v_offset);
+ real_t get_v_offset() const;
- void set_unit_offset(float p_unit_offset);
- float get_unit_offset() const;
+ void set_unit_offset(real_t p_unit_offset);
+ real_t get_unit_offset() const;
void set_loop(bool p_loop);
bool has_loop() const;
diff --git a/scene/3d/physics_body_3d.cpp b/scene/3d/physics_body_3d.cpp
index e895d18604..5f9bca7c49 100644
--- a/scene/3d/physics_body_3d.cpp
+++ b/scene/3d/physics_body_3d.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -30,37 +30,45 @@
#include "physics_body_3d.h"
-#include "core/config/engine.h"
#include "core/core_string_names.h"
-#include "core/object/class_db.h"
-#include "core/templates/list.h"
-#include "core/templates/rid.h"
-#include "scene/3d/collision_shape_3d.h"
#include "scene/scene_string_names.h"
-#include "servers/navigation_server_3d.h"
-#ifdef TOOLS_ENABLED
-#include "editor/plugins/node_3d_editor_plugin.h"
-#endif
+void PhysicsBody3D::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("move_and_collide", "distance", "test_only", "safe_margin", "max_collisions"), &PhysicsBody3D::_move, DEFVAL(false), DEFVAL(0.001), DEFVAL(1));
+ ClassDB::bind_method(D_METHOD("test_move", "from", "distance", "collision", "safe_margin", "max_collisions"), &PhysicsBody3D::test_move, DEFVAL(Variant()), DEFVAL(0.001), DEFVAL(1));
-Vector3 PhysicsBody3D::get_linear_velocity() const {
- return Vector3();
+ ClassDB::bind_method(D_METHOD("set_axis_lock", "axis", "lock"), &PhysicsBody3D::set_axis_lock);
+ ClassDB::bind_method(D_METHOD("get_axis_lock", "axis"), &PhysicsBody3D::get_axis_lock);
+
+ ClassDB::bind_method(D_METHOD("get_collision_exceptions"), &PhysicsBody3D::get_collision_exceptions);
+ ClassDB::bind_method(D_METHOD("add_collision_exception_with", "body"), &PhysicsBody3D::add_collision_exception_with);
+ ClassDB::bind_method(D_METHOD("remove_collision_exception_with", "body"), &PhysicsBody3D::remove_collision_exception_with);
+
+ ADD_GROUP("Axis Lock", "axis_lock_");
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "axis_lock_linear_x"), "set_axis_lock", "get_axis_lock", PhysicsServer3D::BODY_AXIS_LINEAR_X);
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "axis_lock_linear_y"), "set_axis_lock", "get_axis_lock", PhysicsServer3D::BODY_AXIS_LINEAR_Y);
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "axis_lock_linear_z"), "set_axis_lock", "get_axis_lock", PhysicsServer3D::BODY_AXIS_LINEAR_Z);
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "axis_lock_angular_x"), "set_axis_lock", "get_axis_lock", PhysicsServer3D::BODY_AXIS_ANGULAR_X);
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "axis_lock_angular_y"), "set_axis_lock", "get_axis_lock", PhysicsServer3D::BODY_AXIS_ANGULAR_Y);
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "axis_lock_angular_z"), "set_axis_lock", "get_axis_lock", PhysicsServer3D::BODY_AXIS_ANGULAR_Z);
}
-Vector3 PhysicsBody3D::get_angular_velocity() const {
- return Vector3();
+PhysicsBody3D::PhysicsBody3D(PhysicsServer3D::BodyMode p_mode) :
+ CollisionObject3D(PhysicsServer3D::get_singleton()->body_create(), false) {
+ set_body_mode(p_mode);
}
-real_t PhysicsBody3D::get_inverse_mass() const {
- return 0;
+PhysicsBody3D::~PhysicsBody3D() {
+ if (motion_cache.is_valid()) {
+ motion_cache->owner = nullptr;
+ }
}
TypedArray<PhysicsBody3D> PhysicsBody3D::get_collision_exceptions() {
List<RID> exceptions;
PhysicsServer3D::get_singleton()->body_get_collision_exceptions(get_rid(), &exceptions);
Array ret;
- for (List<RID>::Element *E = exceptions.front(); E; E = E->next()) {
- RID body = E->get();
+ for (const RID &body : exceptions) {
ObjectID instance_id = PhysicsServer3D::get_singleton()->body_get_object_instance_id(body);
Object *obj = ObjectDB::get_instance(instance_id);
PhysicsBody3D *physics_body = Object::cast_to<PhysicsBody3D>(obj);
@@ -83,11 +91,133 @@ void PhysicsBody3D::remove_collision_exception_with(Node *p_node) {
PhysicsServer3D::get_singleton()->body_remove_collision_exception(get_rid(), collision_object->get_rid());
}
-void PhysicsBody3D::_bind_methods() {}
+Ref<KinematicCollision3D> PhysicsBody3D::_move(const Vector3 &p_distance, bool p_test_only, real_t p_margin, int p_max_collisions) {
+ PhysicsServer3D::MotionParameters parameters(get_global_transform(), p_distance, p_margin);
+ parameters.max_collisions = p_max_collisions;
-PhysicsBody3D::PhysicsBody3D(PhysicsServer3D::BodyMode p_mode) :
- CollisionObject3D(PhysicsServer3D::get_singleton()->body_create(), false) {
- PhysicsServer3D::get_singleton()->body_set_mode(get_rid(), p_mode);
+ PhysicsServer3D::MotionResult result;
+
+ bool collided = move_and_collide(parameters, result, p_test_only);
+
+ // Don't report collision when the whole motion is done.
+ if (collided && result.collision_safe_fraction < 1) {
+ // Create a new instance when the cached reference is invalid or still in use in script.
+ if (motion_cache.is_null() || motion_cache->reference_get_count() > 1) {
+ motion_cache.instantiate();
+ motion_cache->owner = this;
+ }
+
+ motion_cache->result = result;
+
+ return motion_cache;
+ }
+
+ return Ref<KinematicCollision3D>();
+}
+
+bool PhysicsBody3D::move_and_collide(const PhysicsServer3D::MotionParameters &p_parameters, PhysicsServer3D::MotionResult &r_result, bool p_test_only, bool p_cancel_sliding) {
+ bool colliding = PhysicsServer3D::get_singleton()->body_test_motion(get_rid(), p_parameters, &r_result);
+
+ // Restore direction of motion to be along original motion,
+ // in order to avoid sliding due to recovery,
+ // but only if collision depth is low enough to avoid tunneling.
+ if (p_cancel_sliding) {
+ real_t motion_length = p_parameters.motion.length();
+ real_t precision = 0.001;
+
+ if (colliding) {
+ // Can't just use margin as a threshold because collision depth is calculated on unsafe motion,
+ // so even in normal resting cases the depth can be a bit more than the margin.
+ precision += motion_length * (r_result.collision_unsafe_fraction - r_result.collision_safe_fraction);
+
+ if (r_result.collisions[0].depth > p_parameters.margin + precision) {
+ p_cancel_sliding = false;
+ }
+ }
+
+ if (p_cancel_sliding) {
+ // When motion is null, recovery is the resulting motion.
+ Vector3 motion_normal;
+ if (motion_length > CMP_EPSILON) {
+ motion_normal = p_parameters.motion / motion_length;
+ }
+
+ // Check depth of recovery.
+ real_t projected_length = r_result.travel.dot(motion_normal);
+ Vector3 recovery = r_result.travel - motion_normal * projected_length;
+ real_t recovery_length = recovery.length();
+ // Fixes cases where canceling slide causes the motion to go too deep into the ground,
+ // because we're only taking rest information into account and not general recovery.
+ if (recovery_length < p_parameters.margin + precision) {
+ // Apply adjustment to motion.
+ r_result.travel = motion_normal * projected_length;
+ r_result.remainder = p_parameters.motion - r_result.travel;
+ }
+ }
+ }
+
+ for (int i = 0; i < 3; i++) {
+ if (locked_axis & (1 << i)) {
+ r_result.travel[i] = 0;
+ }
+ }
+
+ if (!p_test_only) {
+ Transform3D gt = p_parameters.from;
+ gt.origin += r_result.travel;
+ set_global_transform(gt);
+ }
+
+ return colliding;
+}
+
+bool PhysicsBody3D::test_move(const Transform3D &p_from, const Vector3 &p_distance, const Ref<KinematicCollision3D> &r_collision, real_t p_margin, int p_max_collisions) {
+ ERR_FAIL_COND_V(!is_inside_tree(), false);
+
+ PhysicsServer3D::MotionResult *r = nullptr;
+ PhysicsServer3D::MotionResult temp_result;
+ if (r_collision.is_valid()) {
+ // Needs const_cast because method bindings don't support non-const Ref.
+ r = const_cast<PhysicsServer3D::MotionResult *>(&r_collision->result);
+ } else {
+ r = &temp_result;
+ }
+
+ PhysicsServer3D::MotionParameters parameters(p_from, p_distance, p_margin);
+
+ bool colliding = PhysicsServer3D::get_singleton()->body_test_motion(get_rid(), parameters, r);
+
+ if (colliding) {
+ // Don't report collision when the whole motion is done.
+ return (r->collision_safe_fraction < 1.0);
+ } else {
+ return false;
+ }
+}
+
+void PhysicsBody3D::set_axis_lock(PhysicsServer3D::BodyAxis p_axis, bool p_lock) {
+ if (p_lock) {
+ locked_axis |= p_axis;
+ } else {
+ locked_axis &= (~p_axis);
+ }
+ PhysicsServer3D::get_singleton()->body_set_axis_lock(get_rid(), p_axis, p_lock);
+}
+
+bool PhysicsBody3D::get_axis_lock(PhysicsServer3D::BodyAxis p_axis) const {
+ return (locked_axis & p_axis);
+}
+
+Vector3 PhysicsBody3D::get_linear_velocity() const {
+ return Vector3();
+}
+
+Vector3 PhysicsBody3D::get_angular_velocity() const {
+ return Vector3();
+}
+
+real_t PhysicsBody3D::get_inverse_mass() const {
+ return 0;
}
void StaticBody3D::set_physics_material_override(const Ref<PhysicsMaterial> &p_physics_material_override) {
@@ -111,11 +241,13 @@ Ref<PhysicsMaterial> StaticBody3D::get_physics_material_override() const {
void StaticBody3D::set_constant_linear_velocity(const Vector3 &p_vel) {
constant_linear_velocity = p_vel;
+
PhysicsServer3D::get_singleton()->body_set_state(get_rid(), PhysicsServer3D::BODY_STATE_LINEAR_VELOCITY, constant_linear_velocity);
}
void StaticBody3D::set_constant_angular_velocity(const Vector3 &p_vel) {
constant_angular_velocity = p_vel;
+
PhysicsServer3D::get_singleton()->body_set_state(get_rid(), PhysicsServer3D::BODY_STATE_ANGULAR_VELOCITY, constant_angular_velocity);
}
@@ -136,21 +268,15 @@ void StaticBody3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_physics_material_override", "physics_material_override"), &StaticBody3D::set_physics_material_override);
ClassDB::bind_method(D_METHOD("get_physics_material_override"), &StaticBody3D::get_physics_material_override);
- ClassDB::bind_method(D_METHOD("get_collision_exceptions"), &PhysicsBody3D::get_collision_exceptions);
- ClassDB::bind_method(D_METHOD("add_collision_exception_with", "body"), &PhysicsBody3D::add_collision_exception_with);
- ClassDB::bind_method(D_METHOD("remove_collision_exception_with", "body"), &PhysicsBody3D::remove_collision_exception_with);
-
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "physics_material_override", PROPERTY_HINT_RESOURCE_TYPE, "PhysicsMaterial"), "set_physics_material_override", "get_physics_material_override");
ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "constant_linear_velocity"), "set_constant_linear_velocity", "get_constant_linear_velocity");
ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "constant_angular_velocity"), "set_constant_angular_velocity", "get_constant_angular_velocity");
}
-StaticBody3D::StaticBody3D() :
- PhysicsBody3D(PhysicsServer3D::BODY_MODE_STATIC) {
+StaticBody3D::StaticBody3D(PhysicsServer3D::BodyMode p_mode) :
+ PhysicsBody3D(p_mode) {
}
-StaticBody3D::~StaticBody3D() {}
-
void StaticBody3D::_reload_physics_characteristics() {
if (physics_material_override.is_null()) {
PhysicsServer3D::get_singleton()->body_set_param(get_rid(), PhysicsServer3D::BODY_PARAM_BOUNCE, 0);
@@ -161,7 +287,104 @@ void StaticBody3D::_reload_physics_characteristics() {
}
}
-void RigidBody3D::_body_enter_tree(ObjectID p_id) {
+Vector3 AnimatableBody3D::get_linear_velocity() const {
+ return linear_velocity;
+}
+
+Vector3 AnimatableBody3D::get_angular_velocity() const {
+ return angular_velocity;
+}
+
+void AnimatableBody3D::set_sync_to_physics(bool p_enable) {
+ if (sync_to_physics == p_enable) {
+ return;
+ }
+
+ sync_to_physics = p_enable;
+
+ _update_kinematic_motion();
+}
+
+bool AnimatableBody3D::is_sync_to_physics_enabled() const {
+ return sync_to_physics;
+}
+
+void AnimatableBody3D::_update_kinematic_motion() {
+#ifdef TOOLS_ENABLED
+ if (Engine::get_singleton()->is_editor_hint()) {
+ return;
+ }
+#endif
+
+ if (sync_to_physics) {
+ set_only_update_transform_changes(true);
+ set_notify_local_transform(true);
+ } else {
+ set_only_update_transform_changes(false);
+ set_notify_local_transform(false);
+ }
+}
+
+void AnimatableBody3D::_body_state_changed_callback(void *p_instance, PhysicsDirectBodyState3D *p_state) {
+ AnimatableBody3D *body = (AnimatableBody3D *)p_instance;
+ body->_body_state_changed(p_state);
+}
+
+void AnimatableBody3D::_body_state_changed(PhysicsDirectBodyState3D *p_state) {
+ linear_velocity = p_state->get_linear_velocity();
+ angular_velocity = p_state->get_angular_velocity();
+
+ if (!sync_to_physics) {
+ return;
+ }
+
+ last_valid_transform = p_state->get_transform();
+ set_notify_local_transform(false);
+ set_global_transform(last_valid_transform);
+ set_notify_local_transform(true);
+ _on_transform_changed();
+}
+
+void AnimatableBody3D::_notification(int p_what) {
+ switch (p_what) {
+ case NOTIFICATION_ENTER_TREE: {
+ last_valid_transform = get_global_transform();
+ _update_kinematic_motion();
+ } break;
+
+ case NOTIFICATION_EXIT_TREE: {
+ set_only_update_transform_changes(false);
+ set_notify_local_transform(false);
+ } break;
+
+ case NOTIFICATION_LOCAL_TRANSFORM_CHANGED: {
+ // Used by sync to physics, send the new transform to the physics...
+ Transform3D new_transform = get_global_transform();
+
+ PhysicsServer3D::get_singleton()->body_set_state(get_rid(), PhysicsServer3D::BODY_STATE_TRANSFORM, new_transform);
+
+ // ... but then revert changes.
+ set_notify_local_transform(false);
+ set_global_transform(last_valid_transform);
+ set_notify_local_transform(true);
+ _on_transform_changed();
+ } break;
+ }
+}
+
+void AnimatableBody3D::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("set_sync_to_physics", "enable"), &AnimatableBody3D::set_sync_to_physics);
+ ClassDB::bind_method(D_METHOD("is_sync_to_physics_enabled"), &AnimatableBody3D::is_sync_to_physics_enabled);
+
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "sync_to_physics"), "set_sync_to_physics", "is_sync_to_physics_enabled");
+}
+
+AnimatableBody3D::AnimatableBody3D() :
+ StaticBody3D(PhysicsServer3D::BODY_MODE_KINEMATIC) {
+ PhysicsServer3D::get_singleton()->body_set_state_sync_callback(get_rid(), this, _body_state_changed_callback);
+}
+
+void RigidDynamicBody3D::_body_enter_tree(ObjectID p_id) {
Object *obj = ObjectDB::get_instance(p_id);
Node *node = Object::cast_to<Node>(obj);
ERR_FAIL_COND(!node);
@@ -184,7 +407,7 @@ void RigidBody3D::_body_enter_tree(ObjectID p_id) {
contact_monitor->locked = false;
}
-void RigidBody3D::_body_exit_tree(ObjectID p_id) {
+void RigidDynamicBody3D::_body_exit_tree(ObjectID p_id) {
Object *obj = ObjectDB::get_instance(p_id);
Node *node = Object::cast_to<Node>(obj);
ERR_FAIL_COND(!node);
@@ -205,7 +428,7 @@ void RigidBody3D::_body_exit_tree(ObjectID p_id) {
contact_monitor->locked = false;
}
-void RigidBody3D::_body_inout(int p_status, const RID &p_body, ObjectID p_instance, int p_body_shape, int p_local_shape) {
+void RigidDynamicBody3D::_body_inout(int p_status, const RID &p_body, ObjectID p_instance, int p_body_shape, int p_local_shape) {
bool body_in = p_status == 1;
ObjectID objid = p_instance;
@@ -224,8 +447,8 @@ void RigidBody3D::_body_inout(int p_status, const RID &p_body, ObjectID p_instan
//E->get().rc=0;
E->get().in_tree = node && node->is_inside_tree();
if (node) {
- node->connect(SceneStringNames::get_singleton()->tree_entered, callable_mp(this, &RigidBody3D::_body_enter_tree), make_binds(objid));
- node->connect(SceneStringNames::get_singleton()->tree_exiting, callable_mp(this, &RigidBody3D::_body_exit_tree), make_binds(objid));
+ node->connect(SceneStringNames::get_singleton()->tree_entered, callable_mp(this, &RigidDynamicBody3D::_body_enter_tree), make_binds(objid));
+ node->connect(SceneStringNames::get_singleton()->tree_exiting, callable_mp(this, &RigidDynamicBody3D::_body_exit_tree), make_binds(objid));
if (E->get().in_tree) {
emit_signal(SceneStringNames::get_singleton()->body_entered, node);
}
@@ -251,8 +474,8 @@ void RigidBody3D::_body_inout(int p_status, const RID &p_body, ObjectID p_instan
if (E->get().shapes.is_empty()) {
if (node) {
- node->disconnect(SceneStringNames::get_singleton()->tree_entered, callable_mp(this, &RigidBody3D::_body_enter_tree));
- node->disconnect(SceneStringNames::get_singleton()->tree_exiting, callable_mp(this, &RigidBody3D::_body_exit_tree));
+ node->disconnect(SceneStringNames::get_singleton()->tree_entered, callable_mp(this, &RigidDynamicBody3D::_body_enter_tree));
+ node->disconnect(SceneStringNames::get_singleton()->tree_exiting, callable_mp(this, &RigidDynamicBody3D::_body_exit_tree));
if (in_tree) {
emit_signal(SceneStringNames::get_singleton()->body_exited, node);
}
@@ -266,33 +489,34 @@ void RigidBody3D::_body_inout(int p_status, const RID &p_body, ObjectID p_instan
}
}
-struct _RigidBodyInOut {
+struct _RigidDynamicBodyInOut {
RID rid;
ObjectID id;
int shape = 0;
int local_shape = 0;
};
-void RigidBody3D::_direct_state_changed(Object *p_state) {
-#ifdef DEBUG_ENABLED
- state = Object::cast_to<PhysicsDirectBodyState3D>(p_state);
- ERR_FAIL_NULL_MSG(state, "Method '_direct_state_changed' must receive a valid PhysicsDirectBodyState3D object as argument");
-#else
- state = (PhysicsDirectBodyState3D *)p_state; //trust it
-#endif
+void RigidDynamicBody3D::_body_state_changed_callback(void *p_instance, PhysicsDirectBodyState3D *p_state) {
+ RigidDynamicBody3D *body = (RigidDynamicBody3D *)p_instance;
+ body->_body_state_changed(p_state);
+}
+void RigidDynamicBody3D::_body_state_changed(PhysicsDirectBodyState3D *p_state) {
set_ignore_transform_notification(true);
- set_global_transform(state->get_transform());
- linear_velocity = state->get_linear_velocity();
- angular_velocity = state->get_angular_velocity();
- inverse_inertia_tensor = state->get_inverse_inertia_tensor();
- if (sleeping != state->is_sleeping()) {
- sleeping = state->is_sleeping();
+ set_global_transform(p_state->get_transform());
+
+ linear_velocity = p_state->get_linear_velocity();
+ angular_velocity = p_state->get_angular_velocity();
+
+ inverse_inertia_tensor = p_state->get_inverse_inertia_tensor();
+
+ if (sleeping != p_state->is_sleeping()) {
+ sleeping = p_state->is_sleeping();
emit_signal(SceneStringNames::get_singleton()->sleeping_state_changed);
}
- if (get_script_instance()) {
- get_script_instance()->call("_integrate_forces", state);
- }
+
+ GDVIRTUAL_CALL(_integrate_forces, p_state);
+
set_ignore_transform_notification(false);
_on_transform_changed();
@@ -301,25 +525,25 @@ void RigidBody3D::_direct_state_changed(Object *p_state) {
//untag all
int rc = 0;
- for (Map<ObjectID, BodyState>::Element *E = contact_monitor->body_map.front(); E; E = E->next()) {
- for (int i = 0; i < E->get().shapes.size(); i++) {
- E->get().shapes[i].tagged = false;
+ for (KeyValue<ObjectID, BodyState> &E : contact_monitor->body_map) {
+ for (int i = 0; i < E.value.shapes.size(); i++) {
+ E.value.shapes[i].tagged = false;
rc++;
}
}
- _RigidBodyInOut *toadd = (_RigidBodyInOut *)alloca(state->get_contact_count() * sizeof(_RigidBodyInOut));
+ _RigidDynamicBodyInOut *toadd = (_RigidDynamicBodyInOut *)alloca(p_state->get_contact_count() * sizeof(_RigidDynamicBodyInOut));
int toadd_count = 0; //state->get_contact_count();
- RigidBody3D_RemoveAction *toremove = (RigidBody3D_RemoveAction *)alloca(rc * sizeof(RigidBody3D_RemoveAction));
+ RigidDynamicBody3D_RemoveAction *toremove = (RigidDynamicBody3D_RemoveAction *)alloca(rc * sizeof(RigidDynamicBody3D_RemoveAction));
int toremove_count = 0;
//put the ones to add
- for (int i = 0; i < state->get_contact_count(); i++) {
- RID rid = state->get_contact_collider(i);
- ObjectID obj = state->get_contact_collider_id(i);
- int local_shape = state->get_contact_local_shape(i);
- int shape = state->get_contact_collider_shape(i);
+ for (int i = 0; i < p_state->get_contact_count(); i++) {
+ RID rid = p_state->get_contact_collider(i);
+ ObjectID obj = p_state->get_contact_collider_id(i);
+ int local_shape = p_state->get_contact_local_shape(i);
+ int shape = p_state->get_contact_collider_shape(i);
//bool found=false;
@@ -349,12 +573,12 @@ void RigidBody3D::_direct_state_changed(Object *p_state) {
//put the ones to remove
- for (Map<ObjectID, BodyState>::Element *E = contact_monitor->body_map.front(); E; E = E->next()) {
- for (int i = 0; i < E->get().shapes.size(); i++) {
- if (!E->get().shapes[i].tagged) {
- toremove[toremove_count].rid = E->get().rid;
- toremove[toremove_count].body_id = E->key();
- toremove[toremove_count].pair = E->get().shapes[i];
+ for (const KeyValue<ObjectID, BodyState> &E : contact_monitor->body_map) {
+ for (int i = 0; i < E.value.shapes.size(); i++) {
+ if (!E.value.shapes[i].tagged) {
+ toremove[toremove_count].rid = E.value.rid;
+ toremove[toremove_count].body_id = E.key;
+ toremove[toremove_count].pair = E.value.shapes[i];
toremove_count++;
}
}
@@ -374,154 +598,242 @@ void RigidBody3D::_direct_state_changed(Object *p_state) {
contact_monitor->locked = false;
}
-
- state = nullptr;
}
-void RigidBody3D::_notification(int p_what) {
+void RigidDynamicBody3D::_notification(int p_what) {
#ifdef TOOLS_ENABLED
- if (p_what == NOTIFICATION_ENTER_TREE) {
- if (Engine::get_singleton()->is_editor_hint()) {
- set_notify_local_transform(true); //used for warnings and only in editor
- }
+ switch (p_what) {
+ case NOTIFICATION_ENTER_TREE: {
+ if (Engine::get_singleton()->is_editor_hint()) {
+ set_notify_local_transform(true); // Used for warnings and only in editor.
+ }
+ } break;
+
+ case NOTIFICATION_LOCAL_TRANSFORM_CHANGED: {
+ if (Engine::get_singleton()->is_editor_hint()) {
+ update_configuration_warnings();
+ }
+ } break;
}
+#endif
+}
- if (p_what == NOTIFICATION_LOCAL_TRANSFORM_CHANGED) {
- if (Engine::get_singleton()->is_editor_hint()) {
- update_configuration_warnings();
+void RigidDynamicBody3D::_apply_body_mode() {
+ if (freeze) {
+ switch (freeze_mode) {
+ case FREEZE_MODE_STATIC: {
+ set_body_mode(PhysicsServer3D::BODY_MODE_STATIC);
+ } break;
+ case FREEZE_MODE_KINEMATIC: {
+ set_body_mode(PhysicsServer3D::BODY_MODE_KINEMATIC);
+ } break;
}
+ } else if (lock_rotation) {
+ set_body_mode(PhysicsServer3D::BODY_MODE_DYNAMIC_LINEAR);
+ } else {
+ set_body_mode(PhysicsServer3D::BODY_MODE_DYNAMIC);
+ }
+}
+
+void RigidDynamicBody3D::set_lock_rotation_enabled(bool p_lock_rotation) {
+ if (p_lock_rotation == lock_rotation) {
+ return;
}
-#endif
+ lock_rotation = p_lock_rotation;
+ _apply_body_mode();
}
-void RigidBody3D::set_mode(Mode p_mode) {
- mode = p_mode;
- switch (p_mode) {
- case MODE_RIGID: {
- PhysicsServer3D::get_singleton()->body_set_mode(get_rid(), PhysicsServer3D::BODY_MODE_RIGID);
- } break;
- case MODE_STATIC: {
- PhysicsServer3D::get_singleton()->body_set_mode(get_rid(), PhysicsServer3D::BODY_MODE_STATIC);
+bool RigidDynamicBody3D::is_lock_rotation_enabled() const {
+ return lock_rotation;
+}
- } break;
- case MODE_CHARACTER: {
- PhysicsServer3D::get_singleton()->body_set_mode(get_rid(), PhysicsServer3D::BODY_MODE_CHARACTER);
+void RigidDynamicBody3D::set_freeze_enabled(bool p_freeze) {
+ if (p_freeze == freeze) {
+ return;
+ }
- } break;
- case MODE_KINEMATIC: {
- PhysicsServer3D::get_singleton()->body_set_mode(get_rid(), PhysicsServer3D::BODY_MODE_KINEMATIC);
- } break;
+ freeze = p_freeze;
+ _apply_body_mode();
+}
+
+bool RigidDynamicBody3D::is_freeze_enabled() const {
+ return freeze;
+}
+
+void RigidDynamicBody3D::set_freeze_mode(FreezeMode p_freeze_mode) {
+ if (p_freeze_mode == freeze_mode) {
+ return;
}
- update_configuration_warnings();
+
+ freeze_mode = p_freeze_mode;
+ _apply_body_mode();
}
-RigidBody3D::Mode RigidBody3D::get_mode() const {
- return mode;
+RigidDynamicBody3D::FreezeMode RigidDynamicBody3D::get_freeze_mode() const {
+ return freeze_mode;
}
-void RigidBody3D::set_mass(real_t p_mass) {
+void RigidDynamicBody3D::set_mass(real_t p_mass) {
ERR_FAIL_COND(p_mass <= 0);
mass = p_mass;
PhysicsServer3D::get_singleton()->body_set_param(get_rid(), PhysicsServer3D::BODY_PARAM_MASS, mass);
}
-real_t RigidBody3D::get_mass() const {
+real_t RigidDynamicBody3D::get_mass() const {
return mass;
}
-void RigidBody3D::set_physics_material_override(const Ref<PhysicsMaterial> &p_physics_material_override) {
+void RigidDynamicBody3D::set_inertia(const Vector3 &p_inertia) {
+ ERR_FAIL_COND(p_inertia.x < 0);
+ ERR_FAIL_COND(p_inertia.y < 0);
+ ERR_FAIL_COND(p_inertia.z < 0);
+
+ inertia = p_inertia;
+ PhysicsServer3D::get_singleton()->body_set_param(get_rid(), PhysicsServer3D::BODY_PARAM_INERTIA, inertia);
+}
+
+const Vector3 &RigidDynamicBody3D::get_inertia() const {
+ return inertia;
+}
+
+void RigidDynamicBody3D::set_center_of_mass_mode(CenterOfMassMode p_mode) {
+ if (center_of_mass_mode == p_mode) {
+ return;
+ }
+
+ center_of_mass_mode = p_mode;
+
+ switch (center_of_mass_mode) {
+ case CENTER_OF_MASS_MODE_AUTO: {
+ center_of_mass = Vector3();
+ PhysicsServer3D::get_singleton()->body_reset_mass_properties(get_rid());
+ if (inertia != Vector3()) {
+ PhysicsServer3D::get_singleton()->body_set_param(get_rid(), PhysicsServer3D::BODY_PARAM_INERTIA, inertia);
+ }
+ } break;
+
+ case CENTER_OF_MASS_MODE_CUSTOM: {
+ PhysicsServer3D::get_singleton()->body_set_param(get_rid(), PhysicsServer3D::BODY_PARAM_CENTER_OF_MASS, center_of_mass);
+ } break;
+ }
+}
+
+RigidDynamicBody3D::CenterOfMassMode RigidDynamicBody3D::get_center_of_mass_mode() const {
+ return center_of_mass_mode;
+}
+
+void RigidDynamicBody3D::set_center_of_mass(const Vector3 &p_center_of_mass) {
+ if (center_of_mass == p_center_of_mass) {
+ return;
+ }
+
+ ERR_FAIL_COND(center_of_mass_mode != CENTER_OF_MASS_MODE_CUSTOM);
+ center_of_mass = p_center_of_mass;
+
+ PhysicsServer3D::get_singleton()->body_set_param(get_rid(), PhysicsServer3D::BODY_PARAM_CENTER_OF_MASS, center_of_mass);
+}
+
+const Vector3 &RigidDynamicBody3D::get_center_of_mass() const {
+ return center_of_mass;
+}
+
+void RigidDynamicBody3D::set_physics_material_override(const Ref<PhysicsMaterial> &p_physics_material_override) {
if (physics_material_override.is_valid()) {
- if (physics_material_override->is_connected(CoreStringNames::get_singleton()->changed, callable_mp(this, &RigidBody3D::_reload_physics_characteristics))) {
- physics_material_override->disconnect(CoreStringNames::get_singleton()->changed, callable_mp(this, &RigidBody3D::_reload_physics_characteristics));
+ if (physics_material_override->is_connected(CoreStringNames::get_singleton()->changed, callable_mp(this, &RigidDynamicBody3D::_reload_physics_characteristics))) {
+ physics_material_override->disconnect(CoreStringNames::get_singleton()->changed, callable_mp(this, &RigidDynamicBody3D::_reload_physics_characteristics));
}
}
physics_material_override = p_physics_material_override;
if (physics_material_override.is_valid()) {
- physics_material_override->connect(CoreStringNames::get_singleton()->changed, callable_mp(this, &RigidBody3D::_reload_physics_characteristics));
+ physics_material_override->connect(CoreStringNames::get_singleton()->changed, callable_mp(this, &RigidDynamicBody3D::_reload_physics_characteristics));
}
_reload_physics_characteristics();
}
-Ref<PhysicsMaterial> RigidBody3D::get_physics_material_override() const {
+Ref<PhysicsMaterial> RigidDynamicBody3D::get_physics_material_override() const {
return physics_material_override;
}
-void RigidBody3D::set_gravity_scale(real_t p_gravity_scale) {
+void RigidDynamicBody3D::set_gravity_scale(real_t p_gravity_scale) {
gravity_scale = p_gravity_scale;
PhysicsServer3D::get_singleton()->body_set_param(get_rid(), PhysicsServer3D::BODY_PARAM_GRAVITY_SCALE, gravity_scale);
}
-real_t RigidBody3D::get_gravity_scale() const {
+real_t RigidDynamicBody3D::get_gravity_scale() const {
return gravity_scale;
}
-void RigidBody3D::set_linear_damp(real_t p_linear_damp) {
- ERR_FAIL_COND(p_linear_damp < -1);
+void RigidDynamicBody3D::set_linear_damp_mode(DampMode p_mode) {
+ linear_damp_mode = p_mode;
+ PhysicsServer3D::get_singleton()->body_set_param(get_rid(), PhysicsServer3D::BODY_PARAM_LINEAR_DAMP_MODE, linear_damp_mode);
+}
+
+RigidDynamicBody3D::DampMode RigidDynamicBody3D::get_linear_damp_mode() const {
+ return linear_damp_mode;
+}
+
+void RigidDynamicBody3D::set_angular_damp_mode(DampMode p_mode) {
+ angular_damp_mode = p_mode;
+ PhysicsServer3D::get_singleton()->body_set_param(get_rid(), PhysicsServer3D::BODY_PARAM_ANGULAR_DAMP_MODE, angular_damp_mode);
+}
+
+RigidDynamicBody3D::DampMode RigidDynamicBody3D::get_angular_damp_mode() const {
+ return angular_damp_mode;
+}
+
+void RigidDynamicBody3D::set_linear_damp(real_t p_linear_damp) {
+ ERR_FAIL_COND(p_linear_damp < 0.0);
linear_damp = p_linear_damp;
PhysicsServer3D::get_singleton()->body_set_param(get_rid(), PhysicsServer3D::BODY_PARAM_LINEAR_DAMP, linear_damp);
}
-real_t RigidBody3D::get_linear_damp() const {
+real_t RigidDynamicBody3D::get_linear_damp() const {
return linear_damp;
}
-void RigidBody3D::set_angular_damp(real_t p_angular_damp) {
- ERR_FAIL_COND(p_angular_damp < -1);
+void RigidDynamicBody3D::set_angular_damp(real_t p_angular_damp) {
+ ERR_FAIL_COND(p_angular_damp < 0.0);
angular_damp = p_angular_damp;
PhysicsServer3D::get_singleton()->body_set_param(get_rid(), PhysicsServer3D::BODY_PARAM_ANGULAR_DAMP, angular_damp);
}
-real_t RigidBody3D::get_angular_damp() const {
+real_t RigidDynamicBody3D::get_angular_damp() const {
return angular_damp;
}
-void RigidBody3D::set_axis_velocity(const Vector3 &p_axis) {
- Vector3 v = state ? state->get_linear_velocity() : linear_velocity;
+void RigidDynamicBody3D::set_axis_velocity(const Vector3 &p_axis) {
Vector3 axis = p_axis.normalized();
- v -= axis * axis.dot(v);
- v += p_axis;
- if (state) {
- set_linear_velocity(v);
- } else {
- PhysicsServer3D::get_singleton()->body_set_axis_velocity(get_rid(), p_axis);
- linear_velocity = v;
- }
+ linear_velocity -= axis * axis.dot(linear_velocity);
+ linear_velocity += p_axis;
+ PhysicsServer3D::get_singleton()->body_set_state(get_rid(), PhysicsServer3D::BODY_STATE_LINEAR_VELOCITY, linear_velocity);
}
-void RigidBody3D::set_linear_velocity(const Vector3 &p_velocity) {
+void RigidDynamicBody3D::set_linear_velocity(const Vector3 &p_velocity) {
linear_velocity = p_velocity;
- if (state) {
- state->set_linear_velocity(linear_velocity);
- } else {
- PhysicsServer3D::get_singleton()->body_set_state(get_rid(), PhysicsServer3D::BODY_STATE_LINEAR_VELOCITY, linear_velocity);
- }
+ PhysicsServer3D::get_singleton()->body_set_state(get_rid(), PhysicsServer3D::BODY_STATE_LINEAR_VELOCITY, linear_velocity);
}
-Vector3 RigidBody3D::get_linear_velocity() const {
+Vector3 RigidDynamicBody3D::get_linear_velocity() const {
return linear_velocity;
}
-void RigidBody3D::set_angular_velocity(const Vector3 &p_velocity) {
+void RigidDynamicBody3D::set_angular_velocity(const Vector3 &p_velocity) {
angular_velocity = p_velocity;
- if (state) {
- state->set_angular_velocity(angular_velocity);
- } else {
- PhysicsServer3D::get_singleton()->body_set_state(get_rid(), PhysicsServer3D::BODY_STATE_ANGULAR_VELOCITY, angular_velocity);
- }
+ PhysicsServer3D::get_singleton()->body_set_state(get_rid(), PhysicsServer3D::BODY_STATE_ANGULAR_VELOCITY, angular_velocity);
}
-Vector3 RigidBody3D::get_angular_velocity() const {
+Vector3 RigidDynamicBody3D::get_angular_velocity() const {
return angular_velocity;
}
-Basis RigidBody3D::get_inverse_inertia_tensor() const {
+Basis RigidDynamicBody3D::get_inverse_inertia_tensor() const {
return inverse_inertia_tensor;
}
-void RigidBody3D::set_use_custom_integrator(bool p_enable) {
+void RigidDynamicBody3D::set_use_custom_integrator(bool p_enable) {
if (custom_integrator == p_enable) {
return;
}
@@ -530,73 +842,102 @@ void RigidBody3D::set_use_custom_integrator(bool p_enable) {
PhysicsServer3D::get_singleton()->body_set_omit_force_integration(get_rid(), p_enable);
}
-bool RigidBody3D::is_using_custom_integrator() {
+bool RigidDynamicBody3D::is_using_custom_integrator() {
return custom_integrator;
}
-void RigidBody3D::set_sleeping(bool p_sleeping) {
+void RigidDynamicBody3D::set_sleeping(bool p_sleeping) {
sleeping = p_sleeping;
PhysicsServer3D::get_singleton()->body_set_state(get_rid(), PhysicsServer3D::BODY_STATE_SLEEPING, sleeping);
}
-void RigidBody3D::set_can_sleep(bool p_active) {
+void RigidDynamicBody3D::set_can_sleep(bool p_active) {
can_sleep = p_active;
PhysicsServer3D::get_singleton()->body_set_state(get_rid(), PhysicsServer3D::BODY_STATE_CAN_SLEEP, p_active);
}
-bool RigidBody3D::is_able_to_sleep() const {
+bool RigidDynamicBody3D::is_able_to_sleep() const {
return can_sleep;
}
-bool RigidBody3D::is_sleeping() const {
+bool RigidDynamicBody3D::is_sleeping() const {
return sleeping;
}
-void RigidBody3D::set_max_contacts_reported(int p_amount) {
+void RigidDynamicBody3D::set_max_contacts_reported(int p_amount) {
max_contacts_reported = p_amount;
PhysicsServer3D::get_singleton()->body_set_max_contacts_reported(get_rid(), p_amount);
}
-int RigidBody3D::get_max_contacts_reported() const {
+int RigidDynamicBody3D::get_max_contacts_reported() const {
return max_contacts_reported;
}
-void RigidBody3D::add_central_force(const Vector3 &p_force) {
- PhysicsServer3D::get_singleton()->body_add_central_force(get_rid(), p_force);
+void RigidDynamicBody3D::apply_central_impulse(const Vector3 &p_impulse) {
+ PhysicsServer3D::get_singleton()->body_apply_central_impulse(get_rid(), p_impulse);
}
-void RigidBody3D::add_force(const Vector3 &p_force, const Vector3 &p_position) {
+void RigidDynamicBody3D::apply_impulse(const Vector3 &p_impulse, const Vector3 &p_position) {
PhysicsServer3D *singleton = PhysicsServer3D::get_singleton();
- singleton->body_add_force(get_rid(), p_force, p_position);
+ singleton->body_apply_impulse(get_rid(), p_impulse, p_position);
}
-void RigidBody3D::add_torque(const Vector3 &p_torque) {
- PhysicsServer3D::get_singleton()->body_add_torque(get_rid(), p_torque);
+void RigidDynamicBody3D::apply_torque_impulse(const Vector3 &p_impulse) {
+ PhysicsServer3D::get_singleton()->body_apply_torque_impulse(get_rid(), p_impulse);
}
-void RigidBody3D::apply_central_impulse(const Vector3 &p_impulse) {
- PhysicsServer3D::get_singleton()->body_apply_central_impulse(get_rid(), p_impulse);
+void RigidDynamicBody3D::apply_central_force(const Vector3 &p_force) {
+ PhysicsServer3D::get_singleton()->body_apply_central_force(get_rid(), p_force);
}
-void RigidBody3D::apply_impulse(const Vector3 &p_impulse, const Vector3 &p_position) {
+void RigidDynamicBody3D::apply_force(const Vector3 &p_force, const Vector3 &p_position) {
PhysicsServer3D *singleton = PhysicsServer3D::get_singleton();
- singleton->body_apply_impulse(get_rid(), p_impulse, p_position);
+ singleton->body_apply_force(get_rid(), p_force, p_position);
}
-void RigidBody3D::apply_torque_impulse(const Vector3 &p_impulse) {
- PhysicsServer3D::get_singleton()->body_apply_torque_impulse(get_rid(), p_impulse);
+void RigidDynamicBody3D::apply_torque(const Vector3 &p_torque) {
+ PhysicsServer3D::get_singleton()->body_apply_torque(get_rid(), p_torque);
+}
+
+void RigidDynamicBody3D::add_constant_central_force(const Vector3 &p_force) {
+ PhysicsServer3D::get_singleton()->body_add_constant_central_force(get_rid(), p_force);
+}
+
+void RigidDynamicBody3D::add_constant_force(const Vector3 &p_force, const Vector3 &p_position) {
+ PhysicsServer3D *singleton = PhysicsServer3D::get_singleton();
+ singleton->body_add_constant_force(get_rid(), p_force, p_position);
+}
+
+void RigidDynamicBody3D::add_constant_torque(const Vector3 &p_torque) {
+ PhysicsServer3D::get_singleton()->body_add_constant_torque(get_rid(), p_torque);
+}
+
+void RigidDynamicBody3D::set_constant_force(const Vector3 &p_force) {
+ PhysicsServer3D::get_singleton()->body_set_constant_force(get_rid(), p_force);
+}
+
+Vector3 RigidDynamicBody3D::get_constant_force() const {
+ return PhysicsServer3D::get_singleton()->body_get_constant_force(get_rid());
+}
+
+void RigidDynamicBody3D::set_constant_torque(const Vector3 &p_torque) {
+ PhysicsServer3D::get_singleton()->body_set_constant_torque(get_rid(), p_torque);
}
-void RigidBody3D::set_use_continuous_collision_detection(bool p_enable) {
+Vector3 RigidDynamicBody3D::get_constant_torque() const {
+ return PhysicsServer3D::get_singleton()->body_get_constant_torque(get_rid());
+}
+
+void RigidDynamicBody3D::set_use_continuous_collision_detection(bool p_enable) {
ccd = p_enable;
PhysicsServer3D::get_singleton()->body_set_enable_continuous_collision_detection(get_rid(), p_enable);
}
-bool RigidBody3D::is_using_continuous_collision_detection() const {
+bool RigidDynamicBody3D::is_using_continuous_collision_detection() const {
return ccd;
}
-void RigidBody3D::set_contact_monitor(bool p_enabled) {
+void RigidDynamicBody3D::set_contact_monitor(bool p_enabled) {
if (p_enabled == is_contact_monitor_enabled()) {
return;
}
@@ -604,14 +945,14 @@ void RigidBody3D::set_contact_monitor(bool p_enabled) {
if (!p_enabled) {
ERR_FAIL_COND_MSG(contact_monitor->locked, "Can't disable contact monitoring during in/out callback. Use call_deferred(\"set_contact_monitor\", false) instead.");
- for (Map<ObjectID, BodyState>::Element *E = contact_monitor->body_map.front(); E; E = E->next()) {
+ for (const KeyValue<ObjectID, BodyState> &E : contact_monitor->body_map) {
//clean up mess
- Object *obj = ObjectDB::get_instance(E->key());
+ Object *obj = ObjectDB::get_instance(E.key);
Node *node = Object::cast_to<Node>(obj);
if (node) {
- node->disconnect(SceneStringNames::get_singleton()->tree_entered, callable_mp(this, &RigidBody3D::_body_enter_tree));
- node->disconnect(SceneStringNames::get_singleton()->tree_exiting, callable_mp(this, &RigidBody3D::_body_exit_tree));
+ node->disconnect(SceneStringNames::get_singleton()->tree_entered, callable_mp(this, &RigidDynamicBody3D::_body_enter_tree));
+ node->disconnect(SceneStringNames::get_singleton()->tree_exiting, callable_mp(this, &RigidDynamicBody3D::_body_exit_tree));
}
}
@@ -623,26 +964,18 @@ void RigidBody3D::set_contact_monitor(bool p_enabled) {
}
}
-bool RigidBody3D::is_contact_monitor_enabled() const {
+bool RigidDynamicBody3D::is_contact_monitor_enabled() const {
return contact_monitor != nullptr;
}
-void RigidBody3D::set_axis_lock(PhysicsServer3D::BodyAxis p_axis, bool p_lock) {
- PhysicsServer3D::get_singleton()->body_set_axis_lock(get_rid(), p_axis, p_lock);
-}
-
-bool RigidBody3D::get_axis_lock(PhysicsServer3D::BodyAxis p_axis) const {
- return PhysicsServer3D::get_singleton()->body_is_axis_locked(get_rid(), p_axis);
-}
-
-Array RigidBody3D::get_colliding_bodies() const {
+Array RigidDynamicBody3D::get_colliding_bodies() const {
ERR_FAIL_COND_V(!contact_monitor, Array());
Array ret;
ret.resize(contact_monitor->body_map.size());
int idx = 0;
- for (const Map<ObjectID, BodyState>::Element *E = contact_monitor->body_map.front(); E; E = E->next()) {
- Object *obj = ObjectDB::get_instance(E->key());
+ for (const KeyValue<ObjectID, BodyState> &E : contact_monitor->body_map) {
+ Object *obj = ObjectDB::get_instance(E.key);
if (!obj) {
ret.resize(ret.size() - 1); //ops
} else {
@@ -653,82 +986,113 @@ Array RigidBody3D::get_colliding_bodies() const {
return ret;
}
-TypedArray<String> RigidBody3D::get_configuration_warnings() const {
- Transform t = get_transform();
+TypedArray<String> RigidDynamicBody3D::get_configuration_warnings() const {
+ Transform3D t = get_transform();
TypedArray<String> warnings = Node::get_configuration_warnings();
- if ((get_mode() == MODE_RIGID || get_mode() == MODE_CHARACTER) && (ABS(t.basis.get_axis(0).length() - 1.0) > 0.05 || ABS(t.basis.get_axis(1).length() - 1.0) > 0.05 || ABS(t.basis.get_axis(2).length() - 1.0) > 0.05)) {
- warnings.push_back(TTR("Size changes to RigidBody3D (in character or rigid modes) will be overridden by the physics engine when running.\nChange the size in children collision shapes instead."));
+ 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 RigidDynamicBody will be overridden by the physics engine when running.\nChange the size in children collision shapes instead."));
}
return warnings;
}
-void RigidBody3D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_mode", "mode"), &RigidBody3D::set_mode);
- ClassDB::bind_method(D_METHOD("get_mode"), &RigidBody3D::get_mode);
+void RigidDynamicBody3D::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("set_mass", "mass"), &RigidDynamicBody3D::set_mass);
+ ClassDB::bind_method(D_METHOD("get_mass"), &RigidDynamicBody3D::get_mass);
+
+ ClassDB::bind_method(D_METHOD("set_inertia", "inertia"), &RigidDynamicBody3D::set_inertia);
+ ClassDB::bind_method(D_METHOD("get_inertia"), &RigidDynamicBody3D::get_inertia);
+
+ ClassDB::bind_method(D_METHOD("set_center_of_mass_mode", "mode"), &RigidDynamicBody3D::set_center_of_mass_mode);
+ ClassDB::bind_method(D_METHOD("get_center_of_mass_mode"), &RigidDynamicBody3D::get_center_of_mass_mode);
+
+ ClassDB::bind_method(D_METHOD("set_center_of_mass", "center_of_mass"), &RigidDynamicBody3D::set_center_of_mass);
+ ClassDB::bind_method(D_METHOD("get_center_of_mass"), &RigidDynamicBody3D::get_center_of_mass);
+
+ ClassDB::bind_method(D_METHOD("set_physics_material_override", "physics_material_override"), &RigidDynamicBody3D::set_physics_material_override);
+ ClassDB::bind_method(D_METHOD("get_physics_material_override"), &RigidDynamicBody3D::get_physics_material_override);
+
+ ClassDB::bind_method(D_METHOD("set_linear_velocity", "linear_velocity"), &RigidDynamicBody3D::set_linear_velocity);
+ ClassDB::bind_method(D_METHOD("get_linear_velocity"), &RigidDynamicBody3D::get_linear_velocity);
+
+ ClassDB::bind_method(D_METHOD("set_angular_velocity", "angular_velocity"), &RigidDynamicBody3D::set_angular_velocity);
+ ClassDB::bind_method(D_METHOD("get_angular_velocity"), &RigidDynamicBody3D::get_angular_velocity);
+
+ ClassDB::bind_method(D_METHOD("get_inverse_inertia_tensor"), &RigidDynamicBody3D::get_inverse_inertia_tensor);
- ClassDB::bind_method(D_METHOD("set_mass", "mass"), &RigidBody3D::set_mass);
- ClassDB::bind_method(D_METHOD("get_mass"), &RigidBody3D::get_mass);
+ ClassDB::bind_method(D_METHOD("set_gravity_scale", "gravity_scale"), &RigidDynamicBody3D::set_gravity_scale);
+ ClassDB::bind_method(D_METHOD("get_gravity_scale"), &RigidDynamicBody3D::get_gravity_scale);
- ClassDB::bind_method(D_METHOD("set_physics_material_override", "physics_material_override"), &RigidBody3D::set_physics_material_override);
- ClassDB::bind_method(D_METHOD("get_physics_material_override"), &RigidBody3D::get_physics_material_override);
+ ClassDB::bind_method(D_METHOD("set_linear_damp_mode", "linear_damp_mode"), &RigidDynamicBody3D::set_linear_damp_mode);
+ ClassDB::bind_method(D_METHOD("get_linear_damp_mode"), &RigidDynamicBody3D::get_linear_damp_mode);
- ClassDB::bind_method(D_METHOD("set_linear_velocity", "linear_velocity"), &RigidBody3D::set_linear_velocity);
- ClassDB::bind_method(D_METHOD("get_linear_velocity"), &RigidBody3D::get_linear_velocity);
+ ClassDB::bind_method(D_METHOD("set_angular_damp_mode", "angular_damp_mode"), &RigidDynamicBody3D::set_angular_damp_mode);
+ ClassDB::bind_method(D_METHOD("get_angular_damp_mode"), &RigidDynamicBody3D::get_angular_damp_mode);
- ClassDB::bind_method(D_METHOD("set_angular_velocity", "angular_velocity"), &RigidBody3D::set_angular_velocity);
- ClassDB::bind_method(D_METHOD("get_angular_velocity"), &RigidBody3D::get_angular_velocity);
+ ClassDB::bind_method(D_METHOD("set_linear_damp", "linear_damp"), &RigidDynamicBody3D::set_linear_damp);
+ ClassDB::bind_method(D_METHOD("get_linear_damp"), &RigidDynamicBody3D::get_linear_damp);
- ClassDB::bind_method(D_METHOD("get_inverse_inertia_tensor"), &RigidBody3D::get_inverse_inertia_tensor);
+ ClassDB::bind_method(D_METHOD("set_angular_damp", "angular_damp"), &RigidDynamicBody3D::set_angular_damp);
+ ClassDB::bind_method(D_METHOD("get_angular_damp"), &RigidDynamicBody3D::get_angular_damp);
- ClassDB::bind_method(D_METHOD("set_gravity_scale", "gravity_scale"), &RigidBody3D::set_gravity_scale);
- ClassDB::bind_method(D_METHOD("get_gravity_scale"), &RigidBody3D::get_gravity_scale);
+ ClassDB::bind_method(D_METHOD("set_max_contacts_reported", "amount"), &RigidDynamicBody3D::set_max_contacts_reported);
+ ClassDB::bind_method(D_METHOD("get_max_contacts_reported"), &RigidDynamicBody3D::get_max_contacts_reported);
- ClassDB::bind_method(D_METHOD("set_linear_damp", "linear_damp"), &RigidBody3D::set_linear_damp);
- ClassDB::bind_method(D_METHOD("get_linear_damp"), &RigidBody3D::get_linear_damp);
+ ClassDB::bind_method(D_METHOD("set_use_custom_integrator", "enable"), &RigidDynamicBody3D::set_use_custom_integrator);
+ ClassDB::bind_method(D_METHOD("is_using_custom_integrator"), &RigidDynamicBody3D::is_using_custom_integrator);
- ClassDB::bind_method(D_METHOD("set_angular_damp", "angular_damp"), &RigidBody3D::set_angular_damp);
- ClassDB::bind_method(D_METHOD("get_angular_damp"), &RigidBody3D::get_angular_damp);
+ ClassDB::bind_method(D_METHOD("set_contact_monitor", "enabled"), &RigidDynamicBody3D::set_contact_monitor);
+ ClassDB::bind_method(D_METHOD("is_contact_monitor_enabled"), &RigidDynamicBody3D::is_contact_monitor_enabled);
- ClassDB::bind_method(D_METHOD("set_max_contacts_reported", "amount"), &RigidBody3D::set_max_contacts_reported);
- ClassDB::bind_method(D_METHOD("get_max_contacts_reported"), &RigidBody3D::get_max_contacts_reported);
+ ClassDB::bind_method(D_METHOD("set_use_continuous_collision_detection", "enable"), &RigidDynamicBody3D::set_use_continuous_collision_detection);
+ ClassDB::bind_method(D_METHOD("is_using_continuous_collision_detection"), &RigidDynamicBody3D::is_using_continuous_collision_detection);
- ClassDB::bind_method(D_METHOD("set_use_custom_integrator", "enable"), &RigidBody3D::set_use_custom_integrator);
- ClassDB::bind_method(D_METHOD("is_using_custom_integrator"), &RigidBody3D::is_using_custom_integrator);
+ ClassDB::bind_method(D_METHOD("set_axis_velocity", "axis_velocity"), &RigidDynamicBody3D::set_axis_velocity);
- ClassDB::bind_method(D_METHOD("set_contact_monitor", "enabled"), &RigidBody3D::set_contact_monitor);
- ClassDB::bind_method(D_METHOD("is_contact_monitor_enabled"), &RigidBody3D::is_contact_monitor_enabled);
+ ClassDB::bind_method(D_METHOD("apply_central_impulse", "impulse"), &RigidDynamicBody3D::apply_central_impulse);
+ ClassDB::bind_method(D_METHOD("apply_impulse", "impulse", "position"), &RigidDynamicBody3D::apply_impulse, Vector3());
+ ClassDB::bind_method(D_METHOD("apply_torque_impulse", "impulse"), &RigidDynamicBody3D::apply_torque_impulse);
- ClassDB::bind_method(D_METHOD("set_use_continuous_collision_detection", "enable"), &RigidBody3D::set_use_continuous_collision_detection);
- ClassDB::bind_method(D_METHOD("is_using_continuous_collision_detection"), &RigidBody3D::is_using_continuous_collision_detection);
+ ClassDB::bind_method(D_METHOD("apply_central_force", "force"), &RigidDynamicBody3D::apply_central_force);
+ ClassDB::bind_method(D_METHOD("apply_force", "force", "position"), &RigidDynamicBody3D::apply_force, Vector3());
+ ClassDB::bind_method(D_METHOD("apply_torque", "torque"), &RigidDynamicBody3D::apply_torque);
- ClassDB::bind_method(D_METHOD("set_axis_velocity", "axis_velocity"), &RigidBody3D::set_axis_velocity);
+ ClassDB::bind_method(D_METHOD("add_constant_central_force", "force"), &RigidDynamicBody3D::add_constant_central_force);
+ ClassDB::bind_method(D_METHOD("add_constant_force", "force", "position"), &RigidDynamicBody3D::add_constant_force, Vector3());
+ ClassDB::bind_method(D_METHOD("add_constant_torque", "torque"), &RigidDynamicBody3D::add_constant_torque);
- ClassDB::bind_method(D_METHOD("add_central_force", "force"), &RigidBody3D::add_central_force);
- ClassDB::bind_method(D_METHOD("add_force", "force", "position"), &RigidBody3D::add_force, Vector3());
- ClassDB::bind_method(D_METHOD("add_torque", "torque"), &RigidBody3D::add_torque);
+ ClassDB::bind_method(D_METHOD("set_constant_force", "force"), &RigidDynamicBody3D::set_constant_force);
+ ClassDB::bind_method(D_METHOD("get_constant_force"), &RigidDynamicBody3D::get_constant_force);
- ClassDB::bind_method(D_METHOD("apply_central_impulse", "impulse"), &RigidBody3D::apply_central_impulse);
- ClassDB::bind_method(D_METHOD("apply_impulse", "impulse", "position"), &RigidBody3D::apply_impulse, Vector3());
- ClassDB::bind_method(D_METHOD("apply_torque_impulse", "impulse"), &RigidBody3D::apply_torque_impulse);
+ ClassDB::bind_method(D_METHOD("set_constant_torque", "torque"), &RigidDynamicBody3D::set_constant_torque);
+ ClassDB::bind_method(D_METHOD("get_constant_torque"), &RigidDynamicBody3D::get_constant_torque);
- ClassDB::bind_method(D_METHOD("set_sleeping", "sleeping"), &RigidBody3D::set_sleeping);
- ClassDB::bind_method(D_METHOD("is_sleeping"), &RigidBody3D::is_sleeping);
+ ClassDB::bind_method(D_METHOD("set_sleeping", "sleeping"), &RigidDynamicBody3D::set_sleeping);
+ ClassDB::bind_method(D_METHOD("is_sleeping"), &RigidDynamicBody3D::is_sleeping);
- ClassDB::bind_method(D_METHOD("set_can_sleep", "able_to_sleep"), &RigidBody3D::set_can_sleep);
- ClassDB::bind_method(D_METHOD("is_able_to_sleep"), &RigidBody3D::is_able_to_sleep);
+ ClassDB::bind_method(D_METHOD("set_can_sleep", "able_to_sleep"), &RigidDynamicBody3D::set_can_sleep);
+ ClassDB::bind_method(D_METHOD("is_able_to_sleep"), &RigidDynamicBody3D::is_able_to_sleep);
- ClassDB::bind_method(D_METHOD("set_axis_lock", "axis", "lock"), &RigidBody3D::set_axis_lock);
- ClassDB::bind_method(D_METHOD("get_axis_lock", "axis"), &RigidBody3D::get_axis_lock);
+ ClassDB::bind_method(D_METHOD("set_lock_rotation_enabled", "lock_rotation"), &RigidDynamicBody3D::set_lock_rotation_enabled);
+ ClassDB::bind_method(D_METHOD("is_lock_rotation_enabled"), &RigidDynamicBody3D::is_lock_rotation_enabled);
- ClassDB::bind_method(D_METHOD("get_colliding_bodies"), &RigidBody3D::get_colliding_bodies);
+ ClassDB::bind_method(D_METHOD("set_freeze_enabled", "freeze_mode"), &RigidDynamicBody3D::set_freeze_enabled);
+ ClassDB::bind_method(D_METHOD("is_freeze_enabled"), &RigidDynamicBody3D::is_freeze_enabled);
- BIND_VMETHOD(MethodInfo("_integrate_forces", PropertyInfo(Variant::OBJECT, "state", PROPERTY_HINT_RESOURCE_TYPE, "PhysicsDirectBodyState3D")));
+ ClassDB::bind_method(D_METHOD("set_freeze_mode", "freeze_mode"), &RigidDynamicBody3D::set_freeze_mode);
+ ClassDB::bind_method(D_METHOD("get_freeze_mode"), &RigidDynamicBody3D::get_freeze_mode);
- ADD_PROPERTY(PropertyInfo(Variant::INT, "mode", PROPERTY_HINT_ENUM, "Rigid,Static,Character,Kinematic"), "set_mode", "get_mode");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "mass", PROPERTY_HINT_EXP_RANGE, "0.01,65535,0.01"), "set_mass", "get_mass");
+ ClassDB::bind_method(D_METHOD("get_colliding_bodies"), &RigidDynamicBody3D::get_colliding_bodies);
+
+ GDVIRTUAL_BIND(_integrate_forces, "state");
+
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "mass", PROPERTY_HINT_RANGE, "0.01,1000,0.01,or_greater,exp"), "set_mass", "get_mass");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "inertia", PROPERTY_HINT_RANGE, "0,1000,0.01,or_greater,exp"), "set_inertia", "get_inertia");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "center_of_mass_mode", PROPERTY_HINT_ENUM, "Auto,Custom", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), "set_center_of_mass_mode", "get_center_of_mass_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "center_of_mass", PROPERTY_HINT_RANGE, "-10,10,0.01,or_lesser,or_greater"), "set_center_of_mass", "get_center_of_mass");
+ ADD_LINKED_PROPERTY("center_of_mass_mode", "center_of_mass");
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "physics_material_override", PROPERTY_HINT_RESOURCE_TYPE, "PhysicsMaterial"), "set_physics_material_override", "get_physics_material_override");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "gravity_scale", PROPERTY_HINT_RANGE, "-128,128,0.01"), "set_gravity_scale", "get_gravity_scale");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "custom_integrator"), "set_use_custom_integrator", "is_using_custom_integrator");
@@ -737,44 +1101,58 @@ void RigidBody3D::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "contact_monitor"), "set_contact_monitor", "is_contact_monitor_enabled");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "sleeping"), "set_sleeping", "is_sleeping");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "can_sleep"), "set_can_sleep", "is_able_to_sleep");
- ADD_GROUP("Axis Lock", "axis_lock_");
- ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "axis_lock_linear_x"), "set_axis_lock", "get_axis_lock", PhysicsServer3D::BODY_AXIS_LINEAR_X);
- ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "axis_lock_linear_y"), "set_axis_lock", "get_axis_lock", PhysicsServer3D::BODY_AXIS_LINEAR_Y);
- ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "axis_lock_linear_z"), "set_axis_lock", "get_axis_lock", PhysicsServer3D::BODY_AXIS_LINEAR_Z);
- ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "axis_lock_angular_x"), "set_axis_lock", "get_axis_lock", PhysicsServer3D::BODY_AXIS_ANGULAR_X);
- ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "axis_lock_angular_y"), "set_axis_lock", "get_axis_lock", PhysicsServer3D::BODY_AXIS_ANGULAR_Y);
- ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "axis_lock_angular_z"), "set_axis_lock", "get_axis_lock", PhysicsServer3D::BODY_AXIS_ANGULAR_Z);
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "lock_rotation"), "set_lock_rotation_enabled", "is_lock_rotation_enabled");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "freeze"), "set_freeze_enabled", "is_freeze_enabled");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "freeze_mode", PROPERTY_HINT_ENUM, "Static,Kinematic"), "set_freeze_mode", "get_freeze_mode");
ADD_GROUP("Linear", "linear_");
ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "linear_velocity"), "set_linear_velocity", "get_linear_velocity");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "linear_damp", PROPERTY_HINT_RANGE, "-1,100,0.001,or_greater"), "set_linear_damp", "get_linear_damp");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "linear_damp_mode", PROPERTY_HINT_ENUM, "Combine,Replace"), "set_linear_damp_mode", "get_linear_damp_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "linear_damp", PROPERTY_HINT_RANGE, "0,100,0.001,or_greater"), "set_linear_damp", "get_linear_damp");
ADD_GROUP("Angular", "angular_");
ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "angular_velocity"), "set_angular_velocity", "get_angular_velocity");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "angular_damp", PROPERTY_HINT_RANGE, "-1,100,0.001,or_greater"), "set_angular_damp", "get_angular_damp");
-
- ADD_SIGNAL(MethodInfo("body_shape_entered", PropertyInfo(Variant::RID, "body_rid"), PropertyInfo(Variant::OBJECT, "body", PROPERTY_HINT_RESOURCE_TYPE, "Node"), PropertyInfo(Variant::INT, "body_shape"), PropertyInfo(Variant::INT, "local_shape")));
- ADD_SIGNAL(MethodInfo("body_shape_exited", PropertyInfo(Variant::RID, "body_rid"), PropertyInfo(Variant::OBJECT, "body", PROPERTY_HINT_RESOURCE_TYPE, "Node"), PropertyInfo(Variant::INT, "body_shape"), PropertyInfo(Variant::INT, "local_shape")));
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "angular_damp_mode", PROPERTY_HINT_ENUM, "Combine,Replace"), "set_angular_damp_mode", "get_angular_damp_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "angular_damp", PROPERTY_HINT_RANGE, "0,100,0.001,or_greater"), "set_angular_damp", "get_angular_damp");
+ ADD_GROUP("Constant Forces", "constant_");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "constant_force"), "set_constant_force", "get_constant_force");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "constant_torque"), "set_constant_torque", "get_constant_torque");
+
+ ADD_SIGNAL(MethodInfo("body_shape_entered", PropertyInfo(Variant::RID, "body_rid"), PropertyInfo(Variant::OBJECT, "body", PROPERTY_HINT_RESOURCE_TYPE, "Node"), PropertyInfo(Variant::INT, "body_shape_index"), PropertyInfo(Variant::INT, "local_shape_index")));
+ ADD_SIGNAL(MethodInfo("body_shape_exited", PropertyInfo(Variant::RID, "body_rid"), PropertyInfo(Variant::OBJECT, "body", PROPERTY_HINT_RESOURCE_TYPE, "Node"), PropertyInfo(Variant::INT, "body_shape_index"), PropertyInfo(Variant::INT, "local_shape_index")));
ADD_SIGNAL(MethodInfo("body_entered", PropertyInfo(Variant::OBJECT, "body", PROPERTY_HINT_RESOURCE_TYPE, "Node")));
ADD_SIGNAL(MethodInfo("body_exited", PropertyInfo(Variant::OBJECT, "body", PROPERTY_HINT_RESOURCE_TYPE, "Node")));
ADD_SIGNAL(MethodInfo("sleeping_state_changed"));
- BIND_ENUM_CONSTANT(MODE_RIGID);
- BIND_ENUM_CONSTANT(MODE_STATIC);
- BIND_ENUM_CONSTANT(MODE_CHARACTER);
- BIND_ENUM_CONSTANT(MODE_KINEMATIC);
+ BIND_ENUM_CONSTANT(FREEZE_MODE_STATIC);
+ BIND_ENUM_CONSTANT(FREEZE_MODE_KINEMATIC);
+
+ BIND_ENUM_CONSTANT(CENTER_OF_MASS_MODE_AUTO);
+ BIND_ENUM_CONSTANT(CENTER_OF_MASS_MODE_CUSTOM);
+
+ BIND_ENUM_CONSTANT(DAMP_MODE_COMBINE);
+ BIND_ENUM_CONSTANT(DAMP_MODE_REPLACE);
}
-RigidBody3D::RigidBody3D() :
- PhysicsBody3D(PhysicsServer3D::BODY_MODE_RIGID) {
- PhysicsServer3D::get_singleton()->body_set_force_integration_callback(get_rid(), callable_mp(this, &RigidBody3D::_direct_state_changed));
+void RigidDynamicBody3D::_validate_property(PropertyInfo &property) const {
+ if (center_of_mass_mode != CENTER_OF_MASS_MODE_CUSTOM) {
+ if (property.name == "center_of_mass") {
+ property.usage = PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL;
+ }
+ }
+ PhysicsBody3D::_validate_property(property);
}
-RigidBody3D::~RigidBody3D() {
+RigidDynamicBody3D::RigidDynamicBody3D() :
+ PhysicsBody3D(PhysicsServer3D::BODY_MODE_DYNAMIC) {
+ PhysicsServer3D::get_singleton()->body_set_state_sync_callback(get_rid(), this, _body_state_changed_callback);
+}
+
+RigidDynamicBody3D::~RigidDynamicBody3D() {
if (contact_monitor) {
memdelete(contact_monitor);
}
}
-void RigidBody3D::_reload_physics_characteristics() {
+void RigidDynamicBody3D::_reload_physics_characteristics() {
if (physics_material_override.is_null()) {
PhysicsServer3D::get_singleton()->body_set_param(get_rid(), PhysicsServer3D::BODY_PARAM_BOUNCE, 0);
PhysicsServer3D::get_singleton()->body_set_param(get_rid(), PhysicsServer3D::BODY_PARAM_FRICTION, 1);
@@ -784,373 +1162,882 @@ void RigidBody3D::_reload_physics_characteristics() {
}
}
-//////////////////////////////////////////////////////
-//////////////////////////
+///////////////////////////////////////
-Ref<KinematicCollision3D> KinematicBody3D::_move(const Vector3 &p_motion, bool p_infinite_inertia, bool p_exclude_raycast_shapes, bool p_test_only) {
- Collision col;
- if (move_and_collide(p_motion, p_infinite_inertia, col, p_exclude_raycast_shapes, p_test_only)) {
- if (motion_cache.is_null()) {
- motion_cache.instance();
- motion_cache->owner = this;
+//so, if you pass 45 as limit, avoid numerical precision errors when angle is 45.
+#define FLOOR_ANGLE_THRESHOLD 0.01
+
+bool CharacterBody3D::move_and_slide() {
+ // Hack in order to work with calling from _process as well as from _physics_process; calling from thread is risky
+ double delta = Engine::get_singleton()->is_in_physics_frame() ? get_physics_process_delta_time() : get_process_delta_time();
+
+ for (int i = 0; i < 3; i++) {
+ if (locked_axis & (1 << i)) {
+ velocity[i] = 0.0;
}
+ }
- motion_cache->collision = col;
+ Transform3D gt = get_global_transform();
+ previous_position = gt.origin;
- return motion_cache;
+ Vector3 current_platform_velocity = platform_velocity;
+
+ if ((collision_state.floor || collision_state.wall) && platform_rid.is_valid()) {
+ bool excluded = false;
+ if (collision_state.floor) {
+ excluded = (moving_platform_floor_layers & platform_layer) == 0;
+ } else if (collision_state.wall) {
+ excluded = (moving_platform_wall_layers & platform_layer) == 0;
+ }
+ if (!excluded) {
+ //this approach makes sure there is less delay between the actual body velocity and the one we saved
+ PhysicsDirectBodyState3D *bs = PhysicsServer3D::get_singleton()->body_get_direct_state(platform_rid);
+ if (bs) {
+ Vector3 local_position = gt.origin - bs->get_transform().origin;
+ current_platform_velocity = bs->get_velocity_at_local_position(local_position);
+ } else {
+ // Body is removed or destroyed, invalidate floor.
+ current_platform_velocity = Vector3();
+ platform_rid = RID();
+ }
+ } else {
+ current_platform_velocity = Vector3();
+ }
}
- return Ref<KinematicCollision3D>();
-}
+ motion_results.clear();
-Vector3 KinematicBody3D::get_linear_velocity() const {
- return linear_velocity;
-}
+ bool was_on_floor = collision_state.floor;
+ collision_state.state = 0;
-Vector3 KinematicBody3D::get_angular_velocity() const {
- return angular_velocity;
-}
+ last_motion = Vector3();
-bool KinematicBody3D::move_and_collide(const Vector3 &p_motion, bool p_infinite_inertia, Collision &r_collision, bool p_exclude_raycast_shapes, bool p_test_only) {
- Transform gt = get_global_transform();
- PhysicsServer3D::MotionResult result;
- bool colliding = PhysicsServer3D::get_singleton()->body_test_motion(get_rid(), gt, p_motion, p_infinite_inertia, &result, p_exclude_raycast_shapes);
+ if (!current_platform_velocity.is_equal_approx(Vector3())) {
+ PhysicsServer3D::MotionParameters parameters(get_global_transform(), current_platform_velocity * delta, margin);
+ parameters.exclude_bodies.insert(platform_rid);
+ if (platform_object_id.is_valid()) {
+ parameters.exclude_objects.insert(platform_object_id);
+ }
- if (colliding) {
- r_collision.collider_metadata = result.collider_metadata;
- r_collision.collider_shape = result.collider_shape;
- r_collision.collider_vel = result.collider_velocity;
- r_collision.collision = result.collision_point;
- r_collision.normal = result.collision_normal;
- r_collision.collider = result.collider_id;
- r_collision.collider_rid = result.collider;
- r_collision.travel = result.motion;
- r_collision.remainder = result.remainder;
- r_collision.local_shape = result.collision_local_shape;
- }
+ PhysicsServer3D::MotionResult floor_result;
+ if (move_and_collide(parameters, floor_result, false, false)) {
+ motion_results.push_back(floor_result);
- for (int i = 0; i < 3; i++) {
- if (locked_axis & (1 << i)) {
- result.motion[i] = 0;
+ CollisionState result_state;
+ _set_collision_direction(floor_result, result_state);
}
}
- if (!p_test_only) {
- gt.origin += result.motion;
- set_global_transform(gt);
+ if (motion_mode == MOTION_MODE_GROUNDED) {
+ _move_and_slide_grounded(delta, was_on_floor);
+ } else {
+ _move_and_slide_floating(delta);
}
- return colliding;
-}
+ // Compute real velocity.
+ real_velocity = get_position_delta() / delta;
-//so, if you pass 45 as limit, avoid numerical precision errors when angle is 45.
-#define FLOOR_ANGLE_THRESHOLD 0.01
-
-Vector3 KinematicBody3D::move_and_slide(const Vector3 &p_linear_velocity, const Vector3 &p_up_direction, bool p_stop_on_slope, int p_max_slides, real_t p_floor_max_angle, bool p_infinite_inertia) {
- Vector3 body_velocity = p_linear_velocity;
- Vector3 body_velocity_normal = body_velocity.normalized();
- Vector3 up_direction = p_up_direction.normalized();
-
- for (int i = 0; i < 3; i++) {
- if (locked_axis & (1 << i)) {
- body_velocity[i] = 0;
+ if (moving_platform_apply_velocity_on_leave != PLATFORM_VEL_ON_LEAVE_NEVER) {
+ // Add last platform velocity when just left a moving platform.
+ if (!collision_state.floor && !collision_state.wall) {
+ if (moving_platform_apply_velocity_on_leave == PLATFORM_VEL_ON_LEAVE_UPWARD_ONLY && current_platform_velocity.dot(up_direction) < 0) {
+ current_platform_velocity = current_platform_velocity.slide(up_direction);
+ }
+ velocity += current_platform_velocity;
}
}
- // Hack in order to work with calling from _process as well as from _physics_process; calling from thread is risky
- Vector3 motion = (floor_velocity + body_velocity) * (Engine::get_singleton()->is_in_physics_frame() ? get_physics_process_delta_time() : get_process_delta_time());
+ return motion_results.size() > 0;
+}
- on_floor = false;
- on_floor_body = RID();
- on_ceiling = false;
- on_wall = false;
- colliders.clear();
+void CharacterBody3D::_move_and_slide_grounded(double p_delta, bool p_was_on_floor) {
+ Vector3 motion = velocity * p_delta;
+ Vector3 motion_slide_up = motion.slide(up_direction);
+ Vector3 prev_floor_normal = floor_normal;
+
+ platform_rid = RID();
+ platform_object_id = ObjectID();
+ platform_velocity = Vector3();
+ platform_ceiling_velocity = Vector3();
floor_normal = Vector3();
- floor_velocity = Vector3();
-
- while (p_max_slides) {
- Collision collision;
- bool found_collision = false;
-
- for (int i = 0; i < 2; ++i) {
- bool collided;
- if (i == 0) { //collide
- collided = move_and_collide(motion, p_infinite_inertia, collision);
- if (!collided) {
- motion = Vector3(); //clear because no collision happened and motion completed
+ wall_normal = Vector3();
+ ceiling_normal = Vector3();
+
+ // No sliding on first attempt to keep floor motion stable when possible,
+ // When stop on slope is enabled or when there is no up direction.
+ bool sliding_enabled = !floor_stop_on_slope;
+ // Constant speed can be applied only the first time sliding is enabled.
+ bool can_apply_constant_speed = sliding_enabled;
+ // If the platform's ceiling push down the body.
+ bool apply_ceiling_velocity = false;
+ bool first_slide = true;
+ bool vel_dir_facing_up = velocity.dot(up_direction) > 0;
+ Vector3 total_travel;
+
+ for (int iteration = 0; iteration < max_slides; ++iteration) {
+ PhysicsServer3D::MotionParameters parameters(get_global_transform(), motion, margin);
+ parameters.max_collisions = 4;
+
+ PhysicsServer3D::MotionResult result;
+ bool collided = move_and_collide(parameters, result, false, !sliding_enabled);
+
+ last_motion = result.travel;
+
+ if (collided) {
+ motion_results.push_back(result);
+
+ CollisionState previous_state = collision_state;
+
+ CollisionState result_state;
+ _set_collision_direction(result, result_state);
+
+ // If we hit a ceiling platform, we set the vertical velocity to at least the platform one.
+ if (collision_state.ceiling && platform_ceiling_velocity != Vector3() && platform_ceiling_velocity.dot(up_direction) < 0) {
+ // If ceiling sliding is on, only apply when the ceiling is flat or when the motion is upward.
+ if (!slide_on_ceiling || motion.dot(up_direction) < 0 || (ceiling_normal + up_direction).length() < 0.01) {
+ apply_ceiling_velocity = true;
+ Vector3 ceiling_vertical_velocity = up_direction * up_direction.dot(platform_ceiling_velocity);
+ Vector3 motion_vertical_velocity = up_direction * up_direction.dot(velocity);
+ if (motion_vertical_velocity.dot(up_direction) > 0 || ceiling_vertical_velocity.length_squared() > motion_vertical_velocity.length_squared()) {
+ velocity = ceiling_vertical_velocity + velocity.slide(up_direction);
+ }
}
- } else { //separate raycasts (if any)
- collided = separate_raycast_shapes(p_infinite_inertia, collision);
- if (collided) {
- collision.remainder = motion; //keep
- collision.travel = Vector3();
+ }
+
+ if (collision_state.floor && floor_stop_on_slope && (velocity.normalized() + up_direction).length() < 0.01) {
+ Transform3D gt = get_global_transform();
+ if (result.travel.length() <= margin + CMP_EPSILON) {
+ gt.origin -= result.travel;
}
+ set_global_transform(gt);
+ velocity = Vector3();
+ motion = Vector3();
+ last_motion = Vector3();
+ break;
}
- if (collided) {
- found_collision = true;
+ if (result.remainder.is_equal_approx(Vector3())) {
+ motion = Vector3();
+ break;
+ }
- colliders.push_back(collision);
- motion = collision.remainder;
+ // Apply regular sliding by default.
+ bool apply_default_sliding = true;
+
+ // Wall collision checks.
+ if (result_state.wall && (motion_slide_up.dot(wall_normal) <= 0)) {
+ // Move on floor only checks.
+ if (floor_block_on_wall) {
+ // Needs horizontal motion from current motion instead of motion_slide_up
+ // to properly test the angle and avoid standing on slopes
+ Vector3 horizontal_motion = motion.slide(up_direction);
+ Vector3 horizontal_normal = wall_normal.slide(up_direction).normalized();
+ real_t motion_angle = Math::abs(Math::acos(-horizontal_normal.dot(horizontal_motion.normalized())));
+
+ // Avoid to move forward on a wall if floor_block_on_wall is true.
+ // Applies only when the motion angle is under 90 degrees,
+ // in order to avoid blocking lateral motion along a wall.
+ if (motion_angle < .5 * Math_PI) {
+ apply_default_sliding = false;
+ if (p_was_on_floor && !vel_dir_facing_up) {
+ // Cancel the motion.
+ Transform3D gt = get_global_transform();
+ real_t travel_total = result.travel.length();
+ real_t cancel_dist_max = MIN(0.1, margin * 20);
+ if (travel_total <= margin + CMP_EPSILON) {
+ gt.origin -= result.travel;
+ result.travel = Vector3(); // Cancel for constant speed computation.
+ } else if (travel_total < cancel_dist_max) { // If the movement is large the body can be prevented from reaching the walls.
+ gt.origin -= result.travel.slide(up_direction);
+ // Keep remaining motion in sync with amount canceled.
+ motion = motion.slide(up_direction);
+ result.travel = Vector3();
+ } else {
+ // Travel is too high to be safely cancelled, we take it into account.
+ result.travel = result.travel.slide(up_direction);
+ motion = motion.normalized() * result.travel.length();
+ }
+ set_global_transform(gt);
+ // 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.
+ motion = result.remainder;
+ }
- if (up_direction == Vector3()) {
- //all is a wall
- on_wall = true;
- } else {
- if (Math::acos(collision.normal.dot(up_direction)) <= p_floor_max_angle + FLOOR_ANGLE_THRESHOLD) { //floor
-
- on_floor = true;
- floor_normal = collision.normal;
- on_floor_body = collision.collider_rid;
- floor_velocity = collision.collider_vel;
-
- if (p_stop_on_slope) {
- if ((body_velocity_normal + up_direction).length() < 0.01 && collision.travel.length() < 1) {
- Transform gt = get_global_transform();
- gt.origin -= collision.travel.slide(up_direction);
- set_global_transform(gt);
- return Vector3();
+ // Apply slide on forward in order to allow only lateral motion on next step.
+ Vector3 forward = wall_normal.slide(up_direction).normalized();
+ motion = motion.slide(forward);
+
+ // Scales the horizontal velocity according to the wall slope.
+ if (vel_dir_facing_up) {
+ Vector3 slide_motion = velocity.slide(result.collisions[0].normal);
+ // Keeps the vertical motion from velocity and add the horizontal motion of the projection.
+ velocity = up_direction * up_direction.dot(velocity) + slide_motion.slide(up_direction);
+ } else {
+ velocity = velocity.slide(forward);
+ }
+
+ // Allow only lateral motion along previous floor when already on floor.
+ // Fixes slowing down when moving in diagonal against an inclined wall.
+ if (p_was_on_floor && !vel_dir_facing_up && (motion.dot(up_direction) > 0.0)) {
+ // Slide along the corner between the wall and previous floor.
+ Vector3 floor_side = prev_floor_normal.cross(wall_normal);
+ if (floor_side != Vector3()) {
+ motion = floor_side * motion.dot(floor_side);
}
}
- } else if (Math::acos(collision.normal.dot(-up_direction)) <= p_floor_max_angle + FLOOR_ANGLE_THRESHOLD) { //ceiling
- on_ceiling = true;
- } else {
- on_wall = true;
+
+ // Stop all motion when a second wall is hit (unless sliding down or jumping),
+ // in order to avoid jittering in corner cases.
+ bool stop_all_motion = previous_state.wall && !vel_dir_facing_up;
+
+ // Allow sliding when the body falls.
+ if (!collision_state.floor && motion.dot(up_direction) < 0) {
+ Vector3 slide_motion = motion.slide(wall_normal);
+ // Test again to allow sliding only if the result goes downwards.
+ // Fixes jittering issues at the bottom of inclined walls.
+ if (slide_motion.dot(up_direction) < 0) {
+ stop_all_motion = false;
+ motion = slide_motion;
+ }
+ }
+
+ if (stop_all_motion) {
+ motion = Vector3();
+ velocity = Vector3();
+ }
}
}
- motion = motion.slide(collision.normal);
- body_velocity = body_velocity.slide(collision.normal);
+ // Stop horizontal motion when under wall slide threshold.
+ if (p_was_on_floor && (wall_min_slide_angle > 0.0) && result_state.wall) {
+ Vector3 horizontal_normal = wall_normal.slide(up_direction).normalized();
+ real_t motion_angle = Math::abs(Math::acos(-horizontal_normal.dot(motion_slide_up.normalized())));
+ if (motion_angle < wall_min_slide_angle) {
+ motion = up_direction * motion.dot(up_direction);
+ velocity = up_direction * velocity.dot(up_direction);
- for (int j = 0; j < 3; j++) {
- if (locked_axis & (1 << j)) {
- body_velocity[j] = 0;
+ apply_default_sliding = false;
}
}
}
+
+ if (apply_default_sliding) {
+ // Regular sliding, the last part of the test handle the case when you don't want to slide on the ceiling.
+ if ((sliding_enabled || !collision_state.floor) && (!collision_state.ceiling || slide_on_ceiling || !vel_dir_facing_up) && !apply_ceiling_velocity) {
+ const PhysicsServer3D::MotionCollision &collision = result.collisions[0];
+
+ Vector3 slide_motion = result.remainder.slide(collision.normal);
+ if (collision_state.floor && !collision_state.wall && !motion_slide_up.is_equal_approx(Vector3())) {
+ // Slide using the intersection between the motion plane and the floor plane,
+ // in order to keep the direction intact.
+ real_t motion_length = slide_motion.length();
+ slide_motion = up_direction.cross(result.remainder).cross(floor_normal);
+
+ // Keep the length from default slide to change speed in slopes by default,
+ // when constant speed is not enabled.
+ slide_motion.normalize();
+ slide_motion *= motion_length;
+ }
+
+ if (slide_motion.dot(velocity) > 0.0) {
+ motion = slide_motion;
+ } else {
+ motion = Vector3();
+ }
+
+ if (slide_on_ceiling && result_state.ceiling) {
+ // Apply slide only in the direction of the input motion, otherwise just stop to avoid jittering when moving against a wall.
+ if (vel_dir_facing_up) {
+ velocity = velocity.slide(collision.normal);
+ } else {
+ // Avoid acceleration in slope when falling.
+ velocity = up_direction * up_direction.dot(velocity);
+ }
+ }
+ }
+ // No sliding on first attempt to keep floor motion stable when possible.
+ else {
+ motion = result.remainder;
+ if (result_state.ceiling && !slide_on_ceiling && vel_dir_facing_up) {
+ velocity = velocity.slide(up_direction);
+ motion = motion.slide(up_direction);
+ }
+ }
+ }
+
+ total_travel += result.travel;
+
+ // Apply Constant Speed.
+ if (p_was_on_floor && floor_constant_speed && can_apply_constant_speed && collision_state.floor && !motion.is_equal_approx(Vector3())) {
+ Vector3 travel_slide_up = total_travel.slide(up_direction);
+ motion = motion.normalized() * MAX(0, (motion_slide_up.length() - travel_slide_up.length()));
+ }
+ }
+ // When you move forward in a downward slope you don’t collide because you will be in the air.
+ // This test ensures that constant speed is applied, only if the player is still on the ground after the snap is applied.
+ else if (floor_constant_speed && first_slide && _on_floor_if_snapped(p_was_on_floor, vel_dir_facing_up)) {
+ can_apply_constant_speed = false;
+ sliding_enabled = true;
+ Transform3D gt = get_global_transform();
+ gt.origin = gt.origin - result.travel;
+ set_global_transform(gt);
+
+ // Slide using the intersection between the motion plane and the floor plane,
+ // in order to keep the direction intact.
+ Vector3 motion_slide_norm = up_direction.cross(motion).cross(prev_floor_normal);
+ motion_slide_norm.normalize();
+
+ motion = motion_slide_norm * (motion_slide_up.length());
+ collided = true;
}
- if (!found_collision || motion == Vector3()) {
+ if (!collided || motion.is_equal_approx(Vector3())) {
break;
}
- --p_max_slides;
+ can_apply_constant_speed = !can_apply_constant_speed && !sliding_enabled;
+ sliding_enabled = true;
+ first_slide = false;
}
- return body_velocity;
+ _snap_on_floor(p_was_on_floor, vel_dir_facing_up);
+
+ // Reset the gravity accumulation when touching the ground.
+ if (collision_state.floor && !vel_dir_facing_up) {
+ velocity = velocity.slide(up_direction);
+ }
}
-Vector3 KinematicBody3D::move_and_slide_with_snap(const Vector3 &p_linear_velocity, const Vector3 &p_snap, const Vector3 &p_up_direction, bool p_stop_on_slope, int p_max_slides, real_t p_floor_max_angle, bool p_infinite_inertia) {
- Vector3 up_direction = p_up_direction.normalized();
- bool was_on_floor = on_floor;
+void CharacterBody3D::_move_and_slide_floating(double p_delta) {
+ Vector3 motion = velocity * p_delta;
- Vector3 ret = move_and_slide(p_linear_velocity, up_direction, p_stop_on_slope, p_max_slides, p_floor_max_angle, p_infinite_inertia);
- if (!was_on_floor || p_snap == Vector3()) {
- return ret;
- }
+ platform_rid = RID();
+ platform_object_id = ObjectID();
+ floor_normal = Vector3();
+ platform_velocity = Vector3();
+
+ bool first_slide = true;
+ for (int iteration = 0; iteration < max_slides; ++iteration) {
+ PhysicsServer3D::MotionParameters parameters(get_global_transform(), motion, margin);
- Collision col;
- Transform gt = get_global_transform();
+ PhysicsServer3D::MotionResult result;
+ bool collided = move_and_collide(parameters, result, false, false);
+
+ last_motion = result.travel;
+
+ if (collided) {
+ motion_results.push_back(result);
+
+ CollisionState result_state;
+ _set_collision_direction(result, result_state);
+
+ if (result.remainder.is_equal_approx(Vector3())) {
+ motion = Vector3();
+ break;
+ }
- if (move_and_collide(p_snap, p_infinite_inertia, col, false, true)) {
- bool apply = true;
- if (up_direction != Vector3()) {
- if (Math::acos(col.normal.dot(up_direction)) <= p_floor_max_angle + FLOOR_ANGLE_THRESHOLD) {
- on_floor = true;
- floor_normal = col.normal;
- on_floor_body = col.collider_rid;
- floor_velocity = col.collider_vel;
- if (p_stop_on_slope) {
- // move and collide may stray the object a bit because of pre un-stucking,
- // so only ensure that motion happens on floor direction in this case.
- col.travel = col.travel.project(up_direction);
+ if (wall_min_slide_angle != 0 && Math::acos(wall_normal.dot(-velocity.normalized())) < wall_min_slide_angle + FLOOR_ANGLE_THRESHOLD) {
+ motion = Vector3();
+ if (result.travel.length() < margin + CMP_EPSILON) {
+ Transform3D gt = get_global_transform();
+ gt.origin -= result.travel;
+ set_global_transform(gt);
}
+ } else if (first_slide) {
+ Vector3 motion_slide_norm = result.remainder.slide(wall_normal).normalized();
+ motion = motion_slide_norm * (motion.length() - result.travel.length());
} else {
- apply = false; //snapped with floor direction, but did not snap to a floor, do not snap.
+ motion = result.remainder.slide(wall_normal);
+ }
+
+ if (motion.dot(velocity) <= 0.0) {
+ motion = Vector3();
}
}
- if (apply) {
- gt.origin += col.travel;
- set_global_transform(gt);
+
+ if (!collided || motion.is_equal_approx(Vector3())) {
+ break;
}
+
+ first_slide = false;
}
+}
- return ret;
+void CharacterBody3D::_snap_on_floor(bool p_was_on_floor, bool p_vel_dir_facing_up) {
+ if (collision_state.floor || !p_was_on_floor || p_vel_dir_facing_up) {
+ return;
+ }
+
+ // Snap by at least collision margin to keep floor state consistent.
+ real_t length = MAX(floor_snap_length, margin);
+
+ PhysicsServer3D::MotionParameters parameters(get_global_transform(), -up_direction * length, margin);
+ parameters.max_collisions = 4;
+ parameters.collide_separation_ray = true;
+
+ PhysicsServer3D::MotionResult result;
+ if (move_and_collide(parameters, result, true, false)) {
+ CollisionState result_state;
+ // Apply direction for floor only.
+ _set_collision_direction(result, result_state, CollisionState(true, false, false));
+
+ if (result_state.floor) {
+ if (floor_stop_on_slope) {
+ // move and collide may stray the object a bit because of pre un-stucking,
+ // so only ensure that motion happens on floor direction in this case.
+ if (result.travel.length() > margin) {
+ result.travel = up_direction * up_direction.dot(result.travel);
+ } else {
+ result.travel = Vector3();
+ }
+ }
+
+ parameters.from.origin += result.travel;
+ set_global_transform(parameters.from);
+ }
+ }
}
-bool KinematicBody3D::is_on_floor() const {
- return on_floor;
+bool CharacterBody3D::_on_floor_if_snapped(bool p_was_on_floor, bool p_vel_dir_facing_up) {
+ if (up_direction == Vector3() || collision_state.floor || !p_was_on_floor || p_vel_dir_facing_up) {
+ return false;
+ }
+
+ // Snap by at least collision margin to keep floor state consistent.
+ real_t length = MAX(floor_snap_length, margin);
+
+ PhysicsServer3D::MotionParameters parameters(get_global_transform(), -up_direction * length, margin);
+ parameters.max_collisions = 4;
+ parameters.collide_separation_ray = true;
+
+ PhysicsServer3D::MotionResult result;
+ if (move_and_collide(parameters, result, true, false)) {
+ CollisionState result_state;
+ // Don't apply direction for any type.
+ _set_collision_direction(result, result_state, CollisionState());
+
+ return result_state.floor;
+ }
+
+ return false;
}
-bool KinematicBody3D::is_on_wall() const {
- return on_wall;
+void CharacterBody3D::_set_collision_direction(const PhysicsServer3D::MotionResult &p_result, CollisionState &r_state, CollisionState p_apply_state) {
+ r_state.state = 0;
+
+ real_t wall_depth = -1.0;
+ real_t floor_depth = -1.0;
+
+ bool was_on_wall = collision_state.wall;
+ Vector3 prev_wall_normal = wall_normal;
+ int wall_collision_count = 0;
+ Vector3 combined_wall_normal;
+ Vector3 tmp_wall_col; // Avoid duplicate on average calculation.
+
+ for (int i = p_result.collision_count - 1; i >= 0; i--) {
+ const PhysicsServer3D::MotionCollision &collision = p_result.collisions[i];
+
+ if (motion_mode == MOTION_MODE_GROUNDED) {
+ // Check if any collision is floor.
+ real_t floor_angle = collision.get_angle(up_direction);
+ if (floor_angle <= floor_max_angle + FLOOR_ANGLE_THRESHOLD) {
+ r_state.floor = true;
+ if (p_apply_state.floor && collision.depth > floor_depth) {
+ collision_state.floor = true;
+ floor_normal = collision.normal;
+ floor_depth = collision.depth;
+ _set_platform_data(collision);
+ }
+ continue;
+ }
+
+ // Check if any collision is ceiling.
+ real_t ceiling_angle = collision.get_angle(-up_direction);
+ if (ceiling_angle <= floor_max_angle + FLOOR_ANGLE_THRESHOLD) {
+ r_state.ceiling = true;
+ if (p_apply_state.ceiling) {
+ platform_ceiling_velocity = collision.collider_velocity;
+ ceiling_normal = collision.normal;
+ collision_state.ceiling = true;
+ }
+ continue;
+ }
+ }
+
+ // Collision is wall by default.
+ r_state.wall = true;
+
+ if (p_apply_state.wall && collision.depth > wall_depth) {
+ collision_state.wall = true;
+ wall_depth = collision.depth;
+ wall_normal = collision.normal;
+
+ // Don't apply wall velocity when the collider is a CharacterBody3D.
+ if (Object::cast_to<CharacterBody3D>(ObjectDB::get_instance(collision.collider_id)) == nullptr) {
+ _set_platform_data(collision);
+ }
+ }
+
+ // Collect normal for calculating average.
+ if (!collision.normal.is_equal_approx(tmp_wall_col)) {
+ tmp_wall_col = collision.normal;
+ combined_wall_normal += collision.normal;
+ wall_collision_count++;
+ }
+ }
+
+ if (r_state.wall) {
+ if (wall_collision_count > 1 && !r_state.floor) {
+ // Check if wall normals cancel out to floor support.
+ if (!r_state.floor && motion_mode == MOTION_MODE_GROUNDED) {
+ combined_wall_normal.normalize();
+ real_t floor_angle = Math::acos(combined_wall_normal.dot(up_direction));
+ if (floor_angle <= floor_max_angle + FLOOR_ANGLE_THRESHOLD) {
+ r_state.floor = true;
+ r_state.wall = false;
+ if (p_apply_state.floor) {
+ collision_state.floor = true;
+ floor_normal = combined_wall_normal;
+ }
+ if (p_apply_state.wall) {
+ collision_state.wall = was_on_wall;
+ wall_normal = prev_wall_normal;
+ }
+ return;
+ }
+ }
+ }
+ }
}
-bool KinematicBody3D::is_on_ceiling() const {
- return on_ceiling;
+void CharacterBody3D::_set_platform_data(const PhysicsServer3D::MotionCollision &p_collision) {
+ platform_rid = p_collision.collider;
+ platform_object_id = p_collision.collider_id;
+ platform_velocity = p_collision.collider_velocity;
+ platform_layer = PhysicsServer3D::get_singleton()->body_get_collision_layer(platform_rid);
}
-Vector3 KinematicBody3D::get_floor_normal() const {
- return floor_normal;
+void CharacterBody3D::set_safe_margin(real_t p_margin) {
+ margin = p_margin;
}
-Vector3 KinematicBody3D::get_floor_velocity() const {
- return floor_velocity;
+real_t CharacterBody3D::get_safe_margin() const {
+ return margin;
}
-bool KinematicBody3D::test_move(const Transform &p_from, const Vector3 &p_motion, bool p_infinite_inertia) {
- ERR_FAIL_COND_V(!is_inside_tree(), false);
+const Vector3 &CharacterBody3D::get_velocity() const {
+ return velocity;
+}
- return PhysicsServer3D::get_singleton()->body_test_motion(get_rid(), p_from, p_motion, p_infinite_inertia);
+void CharacterBody3D::set_velocity(const Vector3 &p_velocity) {
+ velocity = p_velocity;
}
-bool KinematicBody3D::separate_raycast_shapes(bool p_infinite_inertia, Collision &r_collision) {
- PhysicsServer3D::SeparationResult sep_res[8]; //max 8 rays
+bool CharacterBody3D::is_on_floor() const {
+ return collision_state.floor;
+}
- Transform gt = get_global_transform();
+bool CharacterBody3D::is_on_floor_only() const {
+ return collision_state.floor && !collision_state.wall && !collision_state.ceiling;
+}
- Vector3 recover;
- int hits = PhysicsServer3D::get_singleton()->body_test_ray_separation(get_rid(), gt, p_infinite_inertia, recover, sep_res, 8, margin);
- int deepest = -1;
- real_t deepest_depth;
- for (int i = 0; i < hits; i++) {
- if (deepest == -1 || sep_res[i].collision_depth > deepest_depth) {
- deepest = i;
- deepest_depth = sep_res[i].collision_depth;
- }
- }
+bool CharacterBody3D::is_on_wall() const {
+ return collision_state.wall;
+}
- gt.origin += recover;
- set_global_transform(gt);
+bool CharacterBody3D::is_on_wall_only() const {
+ return collision_state.wall && !collision_state.floor && !collision_state.ceiling;
+}
- if (deepest != -1) {
- r_collision.collider = sep_res[deepest].collider_id;
- r_collision.collider_metadata = sep_res[deepest].collider_metadata;
- r_collision.collider_shape = sep_res[deepest].collider_shape;
- r_collision.collider_vel = sep_res[deepest].collider_velocity;
- r_collision.collision = sep_res[deepest].collision_point;
- r_collision.normal = sep_res[deepest].collision_normal;
- r_collision.local_shape = sep_res[deepest].collision_local_shape;
- r_collision.travel = recover;
- r_collision.remainder = Vector3();
+bool CharacterBody3D::is_on_ceiling() const {
+ return collision_state.ceiling;
+}
- return true;
- } else {
- return false;
- }
+bool CharacterBody3D::is_on_ceiling_only() const {
+ return collision_state.ceiling && !collision_state.floor && !collision_state.wall;
}
-void KinematicBody3D::set_axis_lock(PhysicsServer3D::BodyAxis p_axis, bool p_lock) {
- if (p_lock) {
- locked_axis |= p_axis;
- } else {
- locked_axis &= (~p_axis);
- }
- PhysicsServer3D::get_singleton()->body_set_axis_lock(get_rid(), p_axis, p_lock);
+const Vector3 &CharacterBody3D::get_floor_normal() const {
+ return floor_normal;
}
-bool KinematicBody3D::get_axis_lock(PhysicsServer3D::BodyAxis p_axis) const {
- return PhysicsServer3D::get_singleton()->body_is_axis_locked(get_rid(), p_axis);
+const Vector3 &CharacterBody3D::get_wall_normal() const {
+ return wall_normal;
}
-void KinematicBody3D::set_safe_margin(real_t p_margin) {
- margin = p_margin;
- PhysicsServer3D::get_singleton()->body_set_kinematic_safe_margin(get_rid(), margin);
+const Vector3 &CharacterBody3D::get_last_motion() const {
+ return last_motion;
}
-real_t KinematicBody3D::get_safe_margin() const {
- return margin;
+Vector3 CharacterBody3D::get_position_delta() const {
+ return get_transform().origin - previous_position;
+}
+
+const Vector3 &CharacterBody3D::get_real_velocity() const {
+ return real_velocity;
}
-int KinematicBody3D::get_slide_count() const {
- return colliders.size();
+real_t CharacterBody3D::get_floor_angle(const Vector3 &p_up_direction) const {
+ ERR_FAIL_COND_V(p_up_direction == Vector3(), 0);
+ return Math::acos(floor_normal.dot(p_up_direction));
}
-KinematicBody3D::Collision KinematicBody3D::get_slide_collision(int p_bounce) const {
- ERR_FAIL_INDEX_V(p_bounce, colliders.size(), Collision());
- return colliders[p_bounce];
+const Vector3 &CharacterBody3D::get_platform_velocity() const {
+ return platform_velocity;
}
-Ref<KinematicCollision3D> KinematicBody3D::_get_slide_collision(int p_bounce) {
- ERR_FAIL_INDEX_V(p_bounce, colliders.size(), Ref<KinematicCollision3D>());
+Vector3 CharacterBody3D::get_linear_velocity() const {
+ return get_real_velocity();
+}
+
+int CharacterBody3D::get_slide_collision_count() const {
+ return motion_results.size();
+}
+
+PhysicsServer3D::MotionResult CharacterBody3D::get_slide_collision(int p_bounce) const {
+ ERR_FAIL_INDEX_V(p_bounce, motion_results.size(), PhysicsServer3D::MotionResult());
+ return motion_results[p_bounce];
+}
+
+Ref<KinematicCollision3D> CharacterBody3D::_get_slide_collision(int p_bounce) {
+ ERR_FAIL_INDEX_V(p_bounce, motion_results.size(), Ref<KinematicCollision3D>());
if (p_bounce >= slide_colliders.size()) {
slide_colliders.resize(p_bounce + 1);
}
- if (slide_colliders[p_bounce].is_null()) {
- slide_colliders.write[p_bounce].instance();
+ // Create a new instance when the cached reference is invalid or still in use in script.
+ if (slide_colliders[p_bounce].is_null() || slide_colliders[p_bounce]->reference_get_count() > 1) {
+ slide_colliders.write[p_bounce].instantiate();
slide_colliders.write[p_bounce]->owner = this;
}
- slide_colliders.write[p_bounce]->collision = colliders[p_bounce];
+ slide_colliders.write[p_bounce]->result = motion_results[p_bounce];
return slide_colliders[p_bounce];
}
-void KinematicBody3D::_notification(int p_what) {
- if (p_what == NOTIFICATION_ENTER_TREE) {
- // Reset move_and_slide() data.
- on_floor = false;
- on_floor_body = RID();
- on_ceiling = false;
- on_wall = false;
- colliders.clear();
- floor_velocity = Vector3();
+Ref<KinematicCollision3D> CharacterBody3D::_get_last_slide_collision() {
+ if (motion_results.size() == 0) {
+ return Ref<KinematicCollision3D>();
}
+ return _get_slide_collision(motion_results.size() - 1);
}
-void KinematicBody3D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("move_and_collide", "rel_vec", "infinite_inertia", "exclude_raycast_shapes", "test_only"), &KinematicBody3D::_move, DEFVAL(true), DEFVAL(true), DEFVAL(false));
- ClassDB::bind_method(D_METHOD("move_and_slide", "linear_velocity", "up_direction", "stop_on_slope", "max_slides", "floor_max_angle", "infinite_inertia"), &KinematicBody3D::move_and_slide, DEFVAL(Vector3(0, 0, 0)), DEFVAL(false), DEFVAL(4), DEFVAL(Math::deg2rad((real_t)45.0)), DEFVAL(true));
- ClassDB::bind_method(D_METHOD("move_and_slide_with_snap", "linear_velocity", "snap", "up_direction", "stop_on_slope", "max_slides", "floor_max_angle", "infinite_inertia"), &KinematicBody3D::move_and_slide_with_snap, DEFVAL(Vector3(0, 0, 0)), DEFVAL(false), DEFVAL(4), DEFVAL(Math::deg2rad((real_t)45.0)), DEFVAL(true));
+bool CharacterBody3D::is_floor_stop_on_slope_enabled() const {
+ return floor_stop_on_slope;
+}
- ClassDB::bind_method(D_METHOD("test_move", "from", "rel_vec", "infinite_inertia"), &KinematicBody3D::test_move, DEFVAL(true));
+void CharacterBody3D::set_floor_stop_on_slope_enabled(bool p_enabled) {
+ floor_stop_on_slope = p_enabled;
+}
- ClassDB::bind_method(D_METHOD("is_on_floor"), &KinematicBody3D::is_on_floor);
- ClassDB::bind_method(D_METHOD("is_on_ceiling"), &KinematicBody3D::is_on_ceiling);
- ClassDB::bind_method(D_METHOD("is_on_wall"), &KinematicBody3D::is_on_wall);
- ClassDB::bind_method(D_METHOD("get_floor_normal"), &KinematicBody3D::get_floor_normal);
- ClassDB::bind_method(D_METHOD("get_floor_velocity"), &KinematicBody3D::get_floor_velocity);
+bool CharacterBody3D::is_floor_constant_speed_enabled() const {
+ return floor_constant_speed;
+}
- ClassDB::bind_method(D_METHOD("set_axis_lock", "axis", "lock"), &KinematicBody3D::set_axis_lock);
- ClassDB::bind_method(D_METHOD("get_axis_lock", "axis"), &KinematicBody3D::get_axis_lock);
+void CharacterBody3D::set_floor_constant_speed_enabled(bool p_enabled) {
+ floor_constant_speed = p_enabled;
+}
- ClassDB::bind_method(D_METHOD("set_safe_margin", "pixels"), &KinematicBody3D::set_safe_margin);
- ClassDB::bind_method(D_METHOD("get_safe_margin"), &KinematicBody3D::get_safe_margin);
+bool CharacterBody3D::is_floor_block_on_wall_enabled() const {
+ return floor_block_on_wall;
+}
- ClassDB::bind_method(D_METHOD("get_slide_count"), &KinematicBody3D::get_slide_count);
- ClassDB::bind_method(D_METHOD("get_slide_collision", "slide_idx"), &KinematicBody3D::_get_slide_collision);
+void CharacterBody3D::set_floor_block_on_wall_enabled(bool p_enabled) {
+ floor_block_on_wall = p_enabled;
+}
- ADD_GROUP("Axis Lock", "axis_lock_");
- ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "axis_lock_motion_x"), "set_axis_lock", "get_axis_lock", PhysicsServer3D::BODY_AXIS_LINEAR_X);
- ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "axis_lock_motion_y"), "set_axis_lock", "get_axis_lock", PhysicsServer3D::BODY_AXIS_LINEAR_Y);
- ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "axis_lock_motion_z"), "set_axis_lock", "get_axis_lock", PhysicsServer3D::BODY_AXIS_LINEAR_Z);
+bool CharacterBody3D::is_slide_on_ceiling_enabled() const {
+ return slide_on_ceiling;
+}
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "collision/safe_margin", PROPERTY_HINT_RANGE, "0.001,256,0.001"), "set_safe_margin", "get_safe_margin");
+void CharacterBody3D::set_slide_on_ceiling_enabled(bool p_enabled) {
+ slide_on_ceiling = p_enabled;
}
-void KinematicBody3D::_direct_state_changed(Object *p_state) {
-#ifdef DEBUG_ENABLED
- PhysicsDirectBodyState3D *state = Object::cast_to<PhysicsDirectBodyState3D>(p_state);
- ERR_FAIL_NULL_MSG(state, "Method '_direct_state_changed' must receive a valid PhysicsDirectBodyState3D object as argument");
-#else
- PhysicsDirectBodyState3D *state = (PhysicsDirectBodyState3D *)p_state; //trust it
-#endif
+uint32_t CharacterBody3D::get_moving_platform_floor_layers() const {
+ return moving_platform_floor_layers;
+}
- linear_velocity = state->get_linear_velocity();
- angular_velocity = state->get_angular_velocity();
+void CharacterBody3D::set_moving_platform_floor_layers(uint32_t p_exclude_layers) {
+ moving_platform_floor_layers = p_exclude_layers;
}
-KinematicBody3D::KinematicBody3D() :
- PhysicsBody3D(PhysicsServer3D::BODY_MODE_KINEMATIC) {
- set_safe_margin(0.001);
- PhysicsServer3D::get_singleton()->body_set_force_integration_callback(get_rid(), callable_mp(this, &KinematicBody3D::_direct_state_changed));
+uint32_t CharacterBody3D::get_moving_platform_wall_layers() const {
+ return moving_platform_wall_layers;
}
-KinematicBody3D::~KinematicBody3D() {
- if (motion_cache.is_valid()) {
- motion_cache->owner = nullptr;
+void CharacterBody3D::set_moving_platform_wall_layers(uint32_t p_exclude_layers) {
+ moving_platform_wall_layers = p_exclude_layers;
+}
+
+void CharacterBody3D::set_motion_mode(MotionMode p_mode) {
+ motion_mode = p_mode;
+}
+
+CharacterBody3D::MotionMode CharacterBody3D::get_motion_mode() const {
+ return motion_mode;
+}
+
+void CharacterBody3D::set_moving_platform_apply_velocity_on_leave(MovingPlatformApplyVelocityOnLeave p_on_leave_apply_velocity) {
+ moving_platform_apply_velocity_on_leave = p_on_leave_apply_velocity;
+}
+
+CharacterBody3D::MovingPlatformApplyVelocityOnLeave CharacterBody3D::get_moving_platform_apply_velocity_on_leave() const {
+ return moving_platform_apply_velocity_on_leave;
+}
+
+int CharacterBody3D::get_max_slides() const {
+ return max_slides;
+}
+
+void CharacterBody3D::set_max_slides(int p_max_slides) {
+ ERR_FAIL_COND(p_max_slides < 1);
+ max_slides = p_max_slides;
+}
+
+real_t CharacterBody3D::get_floor_max_angle() const {
+ return floor_max_angle;
+}
+
+void CharacterBody3D::set_floor_max_angle(real_t p_radians) {
+ floor_max_angle = p_radians;
+}
+
+real_t CharacterBody3D::get_floor_snap_length() {
+ return floor_snap_length;
+}
+
+void CharacterBody3D::set_floor_snap_length(real_t p_floor_snap_length) {
+ ERR_FAIL_COND(p_floor_snap_length < 0);
+ floor_snap_length = p_floor_snap_length;
+}
+
+real_t CharacterBody3D::get_wall_min_slide_angle() const {
+ return wall_min_slide_angle;
+}
+
+void CharacterBody3D::set_wall_min_slide_angle(real_t p_radians) {
+ wall_min_slide_angle = p_radians;
+}
+
+const Vector3 &CharacterBody3D::get_up_direction() const {
+ return up_direction;
+}
+
+void CharacterBody3D::set_up_direction(const Vector3 &p_up_direction) {
+ ERR_FAIL_COND_MSG(p_up_direction == Vector3(), "up_direction can't be equal to Vector3.ZERO, consider using Floating motion mode instead.");
+ up_direction = p_up_direction.normalized();
+}
+
+void CharacterBody3D::_notification(int p_what) {
+ switch (p_what) {
+ case NOTIFICATION_ENTER_TREE: {
+ // Reset move_and_slide() data.
+ collision_state.state = 0;
+ platform_rid = RID();
+ platform_object_id = ObjectID();
+ motion_results.clear();
+ platform_velocity = Vector3();
+ } break;
}
+}
+void CharacterBody3D::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("move_and_slide"), &CharacterBody3D::move_and_slide);
+
+ ClassDB::bind_method(D_METHOD("set_velocity", "velocity"), &CharacterBody3D::set_velocity);
+ ClassDB::bind_method(D_METHOD("get_velocity"), &CharacterBody3D::get_velocity);
+
+ ClassDB::bind_method(D_METHOD("set_safe_margin", "pixels"), &CharacterBody3D::set_safe_margin);
+ ClassDB::bind_method(D_METHOD("get_safe_margin"), &CharacterBody3D::get_safe_margin);
+ ClassDB::bind_method(D_METHOD("is_floor_stop_on_slope_enabled"), &CharacterBody3D::is_floor_stop_on_slope_enabled);
+ ClassDB::bind_method(D_METHOD("set_floor_stop_on_slope_enabled", "enabled"), &CharacterBody3D::set_floor_stop_on_slope_enabled);
+ ClassDB::bind_method(D_METHOD("set_floor_constant_speed_enabled", "enabled"), &CharacterBody3D::set_floor_constant_speed_enabled);
+ ClassDB::bind_method(D_METHOD("is_floor_constant_speed_enabled"), &CharacterBody3D::is_floor_constant_speed_enabled);
+ ClassDB::bind_method(D_METHOD("set_floor_block_on_wall_enabled", "enabled"), &CharacterBody3D::set_floor_block_on_wall_enabled);
+ ClassDB::bind_method(D_METHOD("is_floor_block_on_wall_enabled"), &CharacterBody3D::is_floor_block_on_wall_enabled);
+ ClassDB::bind_method(D_METHOD("set_slide_on_ceiling_enabled", "enabled"), &CharacterBody3D::set_slide_on_ceiling_enabled);
+ ClassDB::bind_method(D_METHOD("is_slide_on_ceiling_enabled"), &CharacterBody3D::is_slide_on_ceiling_enabled);
+
+ ClassDB::bind_method(D_METHOD("set_moving_platform_floor_layers", "exclude_layer"), &CharacterBody3D::set_moving_platform_floor_layers);
+ ClassDB::bind_method(D_METHOD("get_moving_platform_floor_layers"), &CharacterBody3D::get_moving_platform_floor_layers);
+ ClassDB::bind_method(D_METHOD("set_moving_platform_wall_layers", "exclude_layer"), &CharacterBody3D::set_moving_platform_wall_layers);
+ ClassDB::bind_method(D_METHOD("get_moving_platform_wall_layers"), &CharacterBody3D::get_moving_platform_wall_layers);
+
+ ClassDB::bind_method(D_METHOD("get_max_slides"), &CharacterBody3D::get_max_slides);
+ ClassDB::bind_method(D_METHOD("set_max_slides", "max_slides"), &CharacterBody3D::set_max_slides);
+ ClassDB::bind_method(D_METHOD("get_floor_max_angle"), &CharacterBody3D::get_floor_max_angle);
+ ClassDB::bind_method(D_METHOD("set_floor_max_angle", "radians"), &CharacterBody3D::set_floor_max_angle);
+ ClassDB::bind_method(D_METHOD("get_floor_snap_length"), &CharacterBody3D::get_floor_snap_length);
+ ClassDB::bind_method(D_METHOD("set_floor_snap_length", "floor_snap_length"), &CharacterBody3D::set_floor_snap_length);
+ ClassDB::bind_method(D_METHOD("get_wall_min_slide_angle"), &CharacterBody3D::get_wall_min_slide_angle);
+ ClassDB::bind_method(D_METHOD("set_wall_min_slide_angle", "radians"), &CharacterBody3D::set_wall_min_slide_angle);
+ ClassDB::bind_method(D_METHOD("get_up_direction"), &CharacterBody3D::get_up_direction);
+ ClassDB::bind_method(D_METHOD("set_up_direction", "up_direction"), &CharacterBody3D::set_up_direction);
+ ClassDB::bind_method(D_METHOD("set_motion_mode", "mode"), &CharacterBody3D::set_motion_mode);
+ ClassDB::bind_method(D_METHOD("get_motion_mode"), &CharacterBody3D::get_motion_mode);
+ ClassDB::bind_method(D_METHOD("set_moving_platform_apply_velocity_on_leave", "on_leave_apply_velocity"), &CharacterBody3D::set_moving_platform_apply_velocity_on_leave);
+ ClassDB::bind_method(D_METHOD("get_moving_platform_apply_velocity_on_leave"), &CharacterBody3D::get_moving_platform_apply_velocity_on_leave);
+
+ ClassDB::bind_method(D_METHOD("is_on_floor"), &CharacterBody3D::is_on_floor);
+ ClassDB::bind_method(D_METHOD("is_on_floor_only"), &CharacterBody3D::is_on_floor_only);
+ ClassDB::bind_method(D_METHOD("is_on_ceiling"), &CharacterBody3D::is_on_ceiling);
+ ClassDB::bind_method(D_METHOD("is_on_ceiling_only"), &CharacterBody3D::is_on_ceiling_only);
+ ClassDB::bind_method(D_METHOD("is_on_wall"), &CharacterBody3D::is_on_wall);
+ ClassDB::bind_method(D_METHOD("is_on_wall_only"), &CharacterBody3D::is_on_wall_only);
+ ClassDB::bind_method(D_METHOD("get_floor_normal"), &CharacterBody3D::get_floor_normal);
+ ClassDB::bind_method(D_METHOD("get_wall_normal"), &CharacterBody3D::get_wall_normal);
+ ClassDB::bind_method(D_METHOD("get_last_motion"), &CharacterBody3D::get_last_motion);
+ ClassDB::bind_method(D_METHOD("get_position_delta"), &CharacterBody3D::get_position_delta);
+ ClassDB::bind_method(D_METHOD("get_real_velocity"), &CharacterBody3D::get_real_velocity);
+ ClassDB::bind_method(D_METHOD("get_floor_angle", "up_direction"), &CharacterBody3D::get_floor_angle, DEFVAL(Vector3(0.0, 1.0, 0.0)));
+ ClassDB::bind_method(D_METHOD("get_platform_velocity"), &CharacterBody3D::get_platform_velocity);
+ ClassDB::bind_method(D_METHOD("get_slide_collision_count"), &CharacterBody3D::get_slide_collision_count);
+ ClassDB::bind_method(D_METHOD("get_slide_collision", "slide_idx"), &CharacterBody3D::_get_slide_collision);
+ ClassDB::bind_method(D_METHOD("get_last_slide_collision"), &CharacterBody3D::_get_last_slide_collision);
+
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "motion_mode", PROPERTY_HINT_ENUM, "Grounded,Floating", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), "set_motion_mode", "get_motion_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "up_direction"), "set_up_direction", "get_up_direction");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "slide_on_ceiling"), "set_slide_on_ceiling_enabled", "is_slide_on_ceiling_enabled");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "velocity", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "set_velocity", "get_velocity");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "max_slides", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "set_max_slides", "get_max_slides");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "wall_min_slide_angle", PROPERTY_HINT_RANGE, "0,180,0.1,radians", PROPERTY_USAGE_DEFAULT), "set_wall_min_slide_angle", "get_wall_min_slide_angle");
+ ADD_GROUP("Floor", "floor_");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "floor_stop_on_slope"), "set_floor_stop_on_slope_enabled", "is_floor_stop_on_slope_enabled");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "floor_constant_speed"), "set_floor_constant_speed_enabled", "is_floor_constant_speed_enabled");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "floor_block_on_wall"), "set_floor_block_on_wall_enabled", "is_floor_block_on_wall_enabled");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "floor_max_angle", PROPERTY_HINT_RANGE, "0,180,0.1,radians"), "set_floor_max_angle", "get_floor_max_angle");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "floor_snap_length", PROPERTY_HINT_RANGE, "0,1,0.01,or_greater"), "set_floor_snap_length", "get_floor_snap_length");
+ ADD_GROUP("Moving Platform", "moving_platform");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "moving_platform_apply_velocity_on_leave", PROPERTY_HINT_ENUM, "Always,Upward Only,Never", PROPERTY_USAGE_DEFAULT), "set_moving_platform_apply_velocity_on_leave", "get_moving_platform_apply_velocity_on_leave");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "moving_platform_floor_layers", PROPERTY_HINT_LAYERS_2D_PHYSICS), "set_moving_platform_floor_layers", "get_moving_platform_floor_layers");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "moving_platform_wall_layers", PROPERTY_HINT_LAYERS_2D_PHYSICS), "set_moving_platform_wall_layers", "get_moving_platform_wall_layers");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "collision/safe_margin", PROPERTY_HINT_RANGE, "0.001,256,0.001"), "set_safe_margin", "get_safe_margin");
+
+ BIND_ENUM_CONSTANT(MOTION_MODE_GROUNDED);
+ BIND_ENUM_CONSTANT(MOTION_MODE_FLOATING);
+
+ BIND_ENUM_CONSTANT(PLATFORM_VEL_ON_LEAVE_ALWAYS);
+ BIND_ENUM_CONSTANT(PLATFORM_VEL_ON_LEAVE_UPWARD_ONLY);
+ BIND_ENUM_CONSTANT(PLATFORM_VEL_ON_LEAVE_NEVER);
+}
+
+void CharacterBody3D::_validate_property(PropertyInfo &property) const {
+ if (motion_mode == MOTION_MODE_FLOATING) {
+ if (property.name.begins_with("floor_") || property.name == "up_direction" || property.name == "slide_on_ceiling") {
+ property.usage = PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL;
+ }
+ }
+ PhysicsBody3D::_validate_property(property);
+}
+
+CharacterBody3D::CharacterBody3D() :
+ PhysicsBody3D(PhysicsServer3D::BODY_MODE_KINEMATIC) {
+}
+
+CharacterBody3D::~CharacterBody3D() {
for (int i = 0; i < slide_colliders.size(); i++) {
if (slide_colliders[i].is_valid()) {
slide_colliders.write[i]->owner = nullptr;
@@ -1160,48 +2047,68 @@ KinematicBody3D::~KinematicBody3D() {
///////////////////////////////////////
-Vector3 KinematicCollision3D::get_position() const {
- return collision.collision;
+Vector3 KinematicCollision3D::get_travel() const {
+ return result.travel;
+}
+
+Vector3 KinematicCollision3D::get_remainder() const {
+ return result.remainder;
}
-Vector3 KinematicCollision3D::get_normal() const {
- return collision.normal;
+int KinematicCollision3D::get_collision_count() const {
+ return result.collision_count;
}
-Vector3 KinematicCollision3D::get_travel() const {
- return collision.travel;
+Vector3 KinematicCollision3D::get_position(int p_collision_index) const {
+ ERR_FAIL_INDEX_V(p_collision_index, result.collision_count, Vector3());
+ return result.collisions[p_collision_index].position;
}
-Vector3 KinematicCollision3D::get_remainder() const {
- return collision.remainder;
+Vector3 KinematicCollision3D::get_normal(int p_collision_index) const {
+ ERR_FAIL_INDEX_V(p_collision_index, result.collision_count, Vector3());
+ return result.collisions[p_collision_index].normal;
}
-Object *KinematicCollision3D::get_local_shape() const {
+real_t KinematicCollision3D::get_angle(int p_collision_index, const Vector3 &p_up_direction) const {
+ ERR_FAIL_INDEX_V(p_collision_index, result.collision_count, 0.0);
+ ERR_FAIL_COND_V(p_up_direction == Vector3(), 0);
+ return result.collisions[p_collision_index].get_angle(p_up_direction);
+}
+
+Object *KinematicCollision3D::get_local_shape(int p_collision_index) const {
+ ERR_FAIL_INDEX_V(p_collision_index, result.collision_count, nullptr);
if (!owner) {
return nullptr;
}
- uint32_t ownerid = owner->shape_find_owner(collision.local_shape);
+ uint32_t ownerid = owner->shape_find_owner(result.collisions[p_collision_index].local_shape);
return owner->shape_owner_get_owner(ownerid);
}
-Object *KinematicCollision3D::get_collider() const {
- if (collision.collider.is_valid()) {
- return ObjectDB::get_instance(collision.collider);
+Object *KinematicCollision3D::get_collider(int p_collision_index) const {
+ ERR_FAIL_INDEX_V(p_collision_index, result.collision_count, nullptr);
+ if (result.collisions[p_collision_index].collider_id.is_valid()) {
+ return ObjectDB::get_instance(result.collisions[p_collision_index].collider_id);
}
return nullptr;
}
-ObjectID KinematicCollision3D::get_collider_id() const {
- return collision.collider;
+ObjectID KinematicCollision3D::get_collider_id(int p_collision_index) const {
+ ERR_FAIL_INDEX_V(p_collision_index, result.collision_count, ObjectID());
+ return result.collisions[p_collision_index].collider_id;
+}
+
+RID KinematicCollision3D::get_collider_rid(int p_collision_index) const {
+ ERR_FAIL_INDEX_V(p_collision_index, result.collision_count, RID());
+ return result.collisions[p_collision_index].collider;
}
-Object *KinematicCollision3D::get_collider_shape() const {
- Object *collider = get_collider();
+Object *KinematicCollision3D::get_collider_shape(int p_collision_index) const {
+ Object *collider = get_collider(p_collision_index);
if (collider) {
CollisionObject3D *obj2d = Object::cast_to<CollisionObject3D>(collider);
if (obj2d) {
- uint32_t ownerid = obj2d->shape_find_owner(collision.collider_shape);
+ uint32_t ownerid = obj2d->shape_find_owner(result.collisions[p_collision_index].collider_shape);
return obj2d->shape_owner_get_owner(ownerid);
}
}
@@ -1209,48 +2116,30 @@ Object *KinematicCollision3D::get_collider_shape() const {
return nullptr;
}
-int KinematicCollision3D::get_collider_shape_index() const {
- return collision.collider_shape;
+int KinematicCollision3D::get_collider_shape_index(int p_collision_index) const {
+ ERR_FAIL_INDEX_V(p_collision_index, result.collision_count, 0);
+ return result.collisions[p_collision_index].collider_shape;
}
-Vector3 KinematicCollision3D::get_collider_velocity() const {
- return collision.collider_vel;
-}
-
-Variant KinematicCollision3D::get_collider_metadata() const {
- return Variant();
+Vector3 KinematicCollision3D::get_collider_velocity(int p_collision_index) const {
+ ERR_FAIL_INDEX_V(p_collision_index, result.collision_count, Vector3());
+ return result.collisions[p_collision_index].collider_velocity;
}
void KinematicCollision3D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("get_position"), &KinematicCollision3D::get_position);
- ClassDB::bind_method(D_METHOD("get_normal"), &KinematicCollision3D::get_normal);
ClassDB::bind_method(D_METHOD("get_travel"), &KinematicCollision3D::get_travel);
ClassDB::bind_method(D_METHOD("get_remainder"), &KinematicCollision3D::get_remainder);
- ClassDB::bind_method(D_METHOD("get_local_shape"), &KinematicCollision3D::get_local_shape);
- ClassDB::bind_method(D_METHOD("get_collider"), &KinematicCollision3D::get_collider);
- ClassDB::bind_method(D_METHOD("get_collider_id"), &KinematicCollision3D::get_collider_id);
- ClassDB::bind_method(D_METHOD("get_collider_shape"), &KinematicCollision3D::get_collider_shape);
- ClassDB::bind_method(D_METHOD("get_collider_shape_index"), &KinematicCollision3D::get_collider_shape_index);
- ClassDB::bind_method(D_METHOD("get_collider_velocity"), &KinematicCollision3D::get_collider_velocity);
- ClassDB::bind_method(D_METHOD("get_collider_metadata"), &KinematicCollision3D::get_collider_metadata);
-
- ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "position"), "", "get_position");
- ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "normal"), "", "get_normal");
- ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "travel"), "", "get_travel");
- ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "remainder"), "", "get_remainder");
- ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "local_shape"), "", "get_local_shape");
- ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "collider"), "", "get_collider");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "collider_id"), "", "get_collider_id");
- ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "collider_shape"), "", "get_collider_shape");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "collider_shape_index"), "", "get_collider_shape_index");
- ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "collider_velocity"), "", "get_collider_velocity");
- ADD_PROPERTY(PropertyInfo(Variant::NIL, "collider_metadata", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NIL_IS_VARIANT), "", "get_collider_metadata");
-}
-
-KinematicCollision3D::KinematicCollision3D() {
- collision.collider_shape = 0;
- collision.local_shape = 0;
- owner = nullptr;
+ ClassDB::bind_method(D_METHOD("get_collision_count"), &KinematicCollision3D::get_collision_count);
+ ClassDB::bind_method(D_METHOD("get_position", "collision_index"), &KinematicCollision3D::get_position, DEFVAL(0));
+ ClassDB::bind_method(D_METHOD("get_normal", "collision_index"), &KinematicCollision3D::get_normal, DEFVAL(0));
+ ClassDB::bind_method(D_METHOD("get_angle", "collision_index", "up_direction"), &KinematicCollision3D::get_angle, DEFVAL(0), DEFVAL(Vector3(0.0, 1.0, 0.0)));
+ ClassDB::bind_method(D_METHOD("get_local_shape", "collision_index"), &KinematicCollision3D::get_local_shape, DEFVAL(0));
+ ClassDB::bind_method(D_METHOD("get_collider", "collision_index"), &KinematicCollision3D::get_collider, DEFVAL(0));
+ ClassDB::bind_method(D_METHOD("get_collider_id", "collision_index"), &KinematicCollision3D::get_collider_id, DEFVAL(0));
+ ClassDB::bind_method(D_METHOD("get_collider_rid", "collision_index"), &KinematicCollision3D::get_collider_rid, DEFVAL(0));
+ ClassDB::bind_method(D_METHOD("get_collider_shape", "collision_index"), &KinematicCollision3D::get_collider_shape, DEFVAL(0));
+ ClassDB::bind_method(D_METHOD("get_collider_shape_index", "collision_index"), &KinematicCollision3D::get_collider_shape_index, DEFVAL(0));
+ ClassDB::bind_method(D_METHOD("get_collider_velocity", "collision_index"), &KinematicCollision3D::get_collider_velocity, DEFVAL(0));
}
///////////////////////////////////////
@@ -1274,6 +2163,37 @@ void PhysicalBone3D::apply_impulse(const Vector3 &p_impulse, const Vector3 &p_po
PhysicsServer3D::get_singleton()->body_apply_impulse(get_rid(), p_impulse, p_position);
}
+void PhysicalBone3D::set_linear_velocity(const Vector3 &p_velocity) {
+ linear_velocity = p_velocity;
+ PhysicsServer3D::get_singleton()->body_set_state(get_rid(), PhysicsServer3D::BODY_STATE_LINEAR_VELOCITY, linear_velocity);
+}
+
+Vector3 PhysicalBone3D::get_linear_velocity() const {
+ return linear_velocity;
+}
+
+void PhysicalBone3D::set_angular_velocity(const Vector3 &p_velocity) {
+ angular_velocity = p_velocity;
+ PhysicsServer3D::get_singleton()->body_set_state(get_rid(), PhysicsServer3D::BODY_STATE_ANGULAR_VELOCITY, angular_velocity);
+}
+
+Vector3 PhysicalBone3D::get_angular_velocity() const {
+ return angular_velocity;
+}
+
+void PhysicalBone3D::set_use_custom_integrator(bool p_enable) {
+ if (custom_integrator == p_enable) {
+ return;
+ }
+
+ custom_integrator = p_enable;
+ PhysicsServer3D::get_singleton()->body_set_omit_force_integration(get_rid(), p_enable);
+}
+
+bool PhysicalBone3D::is_using_custom_integrator() {
+ return custom_integrator;
+}
+
void PhysicalBone3D::reset_physics_simulation_state() {
if (simulate_physics) {
_start_physics_simulation();
@@ -1897,9 +2817,7 @@ bool PhysicalBone3D::_set(const StringName &p_name, const Variant &p_value) {
if (joint_data) {
if (joint_data->_set(p_name, p_value, joint)) {
#ifdef TOOLS_ENABLED
- if (get_gizmo().is_valid()) {
- get_gizmo()->redraw();
- }
+ update_gizmos();
#endif
return true;
}
@@ -1954,42 +2872,44 @@ void PhysicalBone3D::_notification(int p_what) {
_reload_joint();
}
break;
- case NOTIFICATION_EXIT_TREE:
+
+ case NOTIFICATION_EXIT_TREE: {
if (parent_skeleton) {
if (-1 != bone_id) {
parent_skeleton->unbind_physical_bone_from_bone(bone_id);
- parent_skeleton->unbind_child_node_from_bone(bone_id, this);
bone_id = -1;
}
}
parent_skeleton = nullptr;
PhysicsServer3D::get_singleton()->joint_clear(joint);
- break;
- case NOTIFICATION_TRANSFORM_CHANGED:
+ } break;
+
+ case NOTIFICATION_TRANSFORM_CHANGED: {
if (Engine::get_singleton()->is_editor_hint()) {
update_offset();
}
- break;
+ } break;
}
}
-void PhysicalBone3D::_direct_state_changed(Object *p_state) {
+void PhysicalBone3D::_body_state_changed_callback(void *p_instance, PhysicsDirectBodyState3D *p_state) {
+ PhysicalBone3D *bone = (PhysicalBone3D *)p_instance;
+ bone->_body_state_changed(p_state);
+}
+
+void PhysicalBone3D::_body_state_changed(PhysicsDirectBodyState3D *p_state) {
if (!simulate_physics || !_internal_simulate_physics) {
return;
}
- /// Update bone transform
+ linear_velocity = p_state->get_linear_velocity();
+ angular_velocity = p_state->get_angular_velocity();
- PhysicsDirectBodyState3D *state;
+ GDVIRTUAL_CALL(_integrate_forces, p_state);
-#ifdef DEBUG_ENABLED
- state = Object::cast_to<PhysicsDirectBodyState3D>(p_state);
- ERR_FAIL_NULL_MSG(state, "Method '_direct_state_changed' must receive a valid PhysicsDirectBodyState3D object as argument");
-#else
- state = (PhysicsDirectBodyState3D *)p_state; //trust it
-#endif
+ /// Update bone transform.
- Transform global_transform(state->get_transform());
+ Transform3D global_transform(p_state->get_transform());
set_ignore_transform_notification(true);
set_global_transform(global_transform);
@@ -2015,8 +2935,6 @@ void PhysicalBone3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_joint_offset"), &PhysicalBone3D::get_joint_offset);
ClassDB::bind_method(D_METHOD("set_joint_rotation", "euler"), &PhysicalBone3D::set_joint_rotation);
ClassDB::bind_method(D_METHOD("get_joint_rotation"), &PhysicalBone3D::get_joint_rotation);
- ClassDB::bind_method(D_METHOD("set_joint_rotation_degrees", "euler_degrees"), &PhysicalBone3D::set_joint_rotation_degrees);
- ClassDB::bind_method(D_METHOD("get_joint_rotation_degrees"), &PhysicalBone3D::get_joint_rotation_degrees);
ClassDB::bind_method(D_METHOD("set_body_offset", "offset"), &PhysicalBone3D::set_body_offset);
ClassDB::bind_method(D_METHOD("get_body_offset"), &PhysicalBone3D::get_body_offset);
@@ -2039,41 +2957,54 @@ void PhysicalBone3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_gravity_scale", "gravity_scale"), &PhysicalBone3D::set_gravity_scale);
ClassDB::bind_method(D_METHOD("get_gravity_scale"), &PhysicalBone3D::get_gravity_scale);
+ ClassDB::bind_method(D_METHOD("set_linear_damp_mode", "linear_damp_mode"), &PhysicalBone3D::set_linear_damp_mode);
+ ClassDB::bind_method(D_METHOD("get_linear_damp_mode"), &PhysicalBone3D::get_linear_damp_mode);
+
+ ClassDB::bind_method(D_METHOD("set_angular_damp_mode", "angular_damp_mode"), &PhysicalBone3D::set_angular_damp_mode);
+ ClassDB::bind_method(D_METHOD("get_angular_damp_mode"), &PhysicalBone3D::get_angular_damp_mode);
+
ClassDB::bind_method(D_METHOD("set_linear_damp", "linear_damp"), &PhysicalBone3D::set_linear_damp);
ClassDB::bind_method(D_METHOD("get_linear_damp"), &PhysicalBone3D::get_linear_damp);
ClassDB::bind_method(D_METHOD("set_angular_damp", "angular_damp"), &PhysicalBone3D::set_angular_damp);
ClassDB::bind_method(D_METHOD("get_angular_damp"), &PhysicalBone3D::get_angular_damp);
+ ClassDB::bind_method(D_METHOD("set_linear_velocity", "linear_velocity"), &PhysicalBone3D::set_linear_velocity);
+ ClassDB::bind_method(D_METHOD("get_linear_velocity"), &PhysicalBone3D::get_linear_velocity);
+
+ ClassDB::bind_method(D_METHOD("set_angular_velocity", "angular_velocity"), &PhysicalBone3D::set_angular_velocity);
+ ClassDB::bind_method(D_METHOD("get_angular_velocity"), &PhysicalBone3D::get_angular_velocity);
+
+ ClassDB::bind_method(D_METHOD("set_use_custom_integrator", "enable"), &PhysicalBone3D::set_use_custom_integrator);
+ ClassDB::bind_method(D_METHOD("is_using_custom_integrator"), &PhysicalBone3D::is_using_custom_integrator);
+
ClassDB::bind_method(D_METHOD("set_can_sleep", "able_to_sleep"), &PhysicalBone3D::set_can_sleep);
ClassDB::bind_method(D_METHOD("is_able_to_sleep"), &PhysicalBone3D::is_able_to_sleep);
- ClassDB::bind_method(D_METHOD("set_axis_lock", "axis", "lock"), &PhysicalBone3D::set_axis_lock);
- ClassDB::bind_method(D_METHOD("get_axis_lock", "axis"), &PhysicalBone3D::get_axis_lock);
+ GDVIRTUAL_BIND(_integrate_forces, "state");
ADD_GROUP("Joint", "joint_");
ADD_PROPERTY(PropertyInfo(Variant::INT, "joint_type", PROPERTY_HINT_ENUM, "None,PinJoint,ConeJoint,HingeJoint,SliderJoint,6DOFJoint"), "set_joint_type", "get_joint_type");
- ADD_PROPERTY(PropertyInfo(Variant::TRANSFORM, "joint_offset"), "set_joint_offset", "get_joint_offset");
- ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "joint_rotation_degrees", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR), "set_joint_rotation_degrees", "get_joint_rotation_degrees");
- ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "joint_rotation", PROPERTY_HINT_NONE, "", 0), "set_joint_rotation", "get_joint_rotation");
+ ADD_PROPERTY(PropertyInfo(Variant::TRANSFORM3D, "joint_offset"), "set_joint_offset", "get_joint_offset");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "joint_rotation", PROPERTY_HINT_RANGE, "-360,360,0.01,or_lesser,or_greater,radians"), "set_joint_rotation", "get_joint_rotation");
- ADD_PROPERTY(PropertyInfo(Variant::TRANSFORM, "body_offset"), "set_body_offset", "get_body_offset");
+ ADD_PROPERTY(PropertyInfo(Variant::TRANSFORM3D, "body_offset"), "set_body_offset", "get_body_offset");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "mass", PROPERTY_HINT_EXP_RANGE, "0.01,65535,0.01"), "set_mass", "get_mass");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "mass", PROPERTY_HINT_RANGE, "0.01,1000,0.01,or_greater,exp"), "set_mass", "get_mass");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "friction", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_friction", "get_friction");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "bounce", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_bounce", "get_bounce");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "gravity_scale", PROPERTY_HINT_RANGE, "-10,10,0.01"), "set_gravity_scale", "get_gravity_scale");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "linear_damp", PROPERTY_HINT_RANGE, "-1,100,0.001,or_greater"), "set_linear_damp", "get_linear_damp");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "angular_damp", PROPERTY_HINT_RANGE, "-1,100,0.001,or_greater"), "set_angular_damp", "get_angular_damp");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "custom_integrator"), "set_use_custom_integrator", "is_using_custom_integrator");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "linear_damp_mode", PROPERTY_HINT_ENUM, "Combine,Replace"), "set_linear_damp_mode", "get_linear_damp_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "linear_damp", PROPERTY_HINT_RANGE, "0,100,0.001,or_greater"), "set_linear_damp", "get_linear_damp");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "angular_damp_mode", PROPERTY_HINT_ENUM, "Combine,Replace"), "set_angular_damp_mode", "get_angular_damp_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "angular_damp", PROPERTY_HINT_RANGE, "0,100,0.001,or_greater"), "set_angular_damp", "get_angular_damp");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "linear_velocity"), "set_linear_velocity", "get_linear_velocity");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "angular_velocity"), "set_angular_velocity", "get_angular_velocity");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "can_sleep"), "set_can_sleep", "is_able_to_sleep");
- ADD_GROUP("Axis Lock", "axis_lock_");
- ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "axis_lock_linear_x"), "set_axis_lock", "get_axis_lock", PhysicsServer3D::BODY_AXIS_LINEAR_X);
- ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "axis_lock_linear_y"), "set_axis_lock", "get_axis_lock", PhysicsServer3D::BODY_AXIS_LINEAR_Y);
- ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "axis_lock_linear_z"), "set_axis_lock", "get_axis_lock", PhysicsServer3D::BODY_AXIS_LINEAR_Z);
- ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "axis_lock_angular_x"), "set_axis_lock", "get_axis_lock", PhysicsServer3D::BODY_AXIS_ANGULAR_X);
- ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "axis_lock_angular_y"), "set_axis_lock", "get_axis_lock", PhysicsServer3D::BODY_AXIS_ANGULAR_Y);
- ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "axis_lock_angular_z"), "set_axis_lock", "get_axis_lock", PhysicsServer3D::BODY_AXIS_ANGULAR_Z);
+ BIND_ENUM_CONSTANT(DAMP_MODE_COMBINE);
+ BIND_ENUM_CONSTANT(DAMP_MODE_REPLACE);
BIND_ENUM_CONSTANT(JOINT_TYPE_NONE);
BIND_ENUM_CONSTANT(JOINT_TYPE_PIN);
@@ -2099,9 +3030,7 @@ void PhysicalBone3D::_update_joint_offset() {
set_ignore_transform_notification(false);
#ifdef TOOLS_ENABLED
- if (get_gizmo().is_valid()) {
- get_gizmo()->redraw();
- }
+ update_gizmos();
#endif
}
@@ -2124,8 +3053,8 @@ void PhysicalBone3D::_reload_joint() {
return;
}
- Transform joint_transf = get_global_transform() * joint_offset;
- Transform local_a = body_a->get_global_transform().affine_inverse() * joint_transf;
+ Transform3D joint_transf = get_global_transform() * joint_offset;
+ Transform3D local_a = body_a->get_global_transform().affine_inverse() * joint_transf;
local_a.orthonormalize();
switch (get_joint_type()) {
@@ -2210,19 +3139,16 @@ void PhysicalBone3D::_on_bone_parent_changed() {
_reload_joint();
}
-void PhysicalBone3D::_set_gizmo_move_joint(bool p_move_joint) {
#ifdef TOOLS_ENABLED
+void PhysicalBone3D::_set_gizmo_move_joint(bool p_move_joint) {
gizmo_move_joint = p_move_joint;
- Node3DEditor::get_singleton()->update_transform_gizmo();
-#endif
}
-#ifdef TOOLS_ENABLED
-Transform PhysicalBone3D::get_global_gizmo_transform() const {
+Transform3D PhysicalBone3D::get_global_gizmo_transform() const {
return gizmo_move_joint ? get_global_transform() * joint_offset : get_global_transform();
}
-Transform PhysicalBone3D::get_local_gizmo_transform() const {
+Transform3D PhysicalBone3D::get_local_gizmo_transform() const {
return gizmo_move_joint ? get_transform() * joint_offset : get_transform();
}
#endif
@@ -2268,9 +3194,7 @@ void PhysicalBone3D::set_joint_type(JointType p_joint_type) {
#ifdef TOOLS_ENABLED
notify_property_list_changed();
- if (get_gizmo().is_valid()) {
- get_gizmo()->redraw();
- }
+ update_gizmos();
#endif
}
@@ -2278,13 +3202,13 @@ PhysicalBone3D::JointType PhysicalBone3D::get_joint_type() const {
return joint_data ? joint_data->get_joint_type() : JOINT_TYPE_NONE;
}
-void PhysicalBone3D::set_joint_offset(const Transform &p_offset) {
+void PhysicalBone3D::set_joint_offset(const Transform3D &p_offset) {
joint_offset = p_offset;
_update_joint_offset();
}
-const Transform &PhysicalBone3D::get_joint_offset() const {
+const Transform3D &PhysicalBone3D::get_joint_offset() const {
return joint_offset;
}
@@ -2295,22 +3219,14 @@ void PhysicalBone3D::set_joint_rotation(const Vector3 &p_euler_rad) {
}
Vector3 PhysicalBone3D::get_joint_rotation() const {
- return joint_offset.basis.get_rotation();
+ return joint_offset.basis.get_euler_normalized();
}
-void PhysicalBone3D::set_joint_rotation_degrees(const Vector3 &p_euler_deg) {
- set_joint_rotation(p_euler_deg * (Math_PI / 180.0));
-}
-
-Vector3 PhysicalBone3D::get_joint_rotation_degrees() const {
- return get_joint_rotation() * (180.0 / Math_PI);
-}
-
-const Transform &PhysicalBone3D::get_body_offset() const {
+const Transform3D &PhysicalBone3D::get_body_offset() const {
return body_offset;
}
-void PhysicalBone3D::set_body_offset(const Transform &p_offset) {
+void PhysicalBone3D::set_body_offset(const Transform3D &p_offset) {
body_offset = p_offset;
body_offset_inverse = body_offset.affine_inverse();
@@ -2387,8 +3303,27 @@ real_t PhysicalBone3D::get_gravity_scale() const {
return gravity_scale;
}
+void PhysicalBone3D::set_linear_damp_mode(DampMode p_mode) {
+ linear_damp_mode = p_mode;
+ PhysicsServer3D::get_singleton()->body_set_param(get_rid(), PhysicsServer3D::BODY_PARAM_LINEAR_DAMP_MODE, linear_damp_mode);
+}
+
+PhysicalBone3D::DampMode PhysicalBone3D::get_linear_damp_mode() const {
+ return linear_damp_mode;
+}
+
+void PhysicalBone3D::set_angular_damp_mode(DampMode p_mode) {
+ angular_damp_mode = p_mode;
+ PhysicsServer3D::get_singleton()->body_set_param(get_rid(), PhysicsServer3D::BODY_PARAM_ANGULAR_DAMP_MODE, angular_damp_mode);
+}
+
+PhysicalBone3D::DampMode PhysicalBone3D::get_angular_damp_mode() const {
+ return angular_damp_mode;
+}
+
void PhysicalBone3D::set_linear_damp(real_t p_linear_damp) {
- ERR_FAIL_COND(p_linear_damp < -1);
+ ERR_FAIL_COND(p_linear_damp < 0);
+
linear_damp = p_linear_damp;
PhysicsServer3D::get_singleton()->body_set_param(get_rid(), PhysicsServer3D::BODY_PARAM_LINEAR_DAMP, linear_damp);
}
@@ -2398,7 +3333,8 @@ real_t PhysicalBone3D::get_linear_damp() const {
}
void PhysicalBone3D::set_angular_damp(real_t p_angular_damp) {
- ERR_FAIL_COND(p_angular_damp < -1);
+ ERR_FAIL_COND(p_angular_damp < 0);
+
angular_damp = p_angular_damp;
PhysicsServer3D::get_singleton()->body_set_param(get_rid(), PhysicsServer3D::BODY_PARAM_ANGULAR_DAMP, angular_damp);
}
@@ -2416,14 +3352,6 @@ bool PhysicalBone3D::is_able_to_sleep() const {
return can_sleep;
}
-void PhysicalBone3D::set_axis_lock(PhysicsServer3D::BodyAxis p_axis, bool p_lock) {
- PhysicsServer3D::get_singleton()->body_set_axis_lock(get_rid(), p_axis, p_lock);
-}
-
-bool PhysicalBone3D::get_axis_lock(PhysicsServer3D::BodyAxis p_axis) const {
- return PhysicsServer3D::get_singleton()->body_is_axis_locked(get_rid(), p_axis);
-}
-
PhysicalBone3D::PhysicalBone3D() :
PhysicsBody3D(PhysicsServer3D::BODY_MODE_STATIC) {
joint = PhysicsServer3D::get_singleton()->joint_create();
@@ -2448,7 +3376,6 @@ void PhysicalBone3D::update_bone_id() {
if (-1 != bone_id) {
// Assert the unbind from old node
parent_skeleton->unbind_physical_bone_from_bone(bone_id);
- parent_skeleton->unbind_child_node_from_bone(bone_id, this);
}
bone_id = new_bone_id;
@@ -2463,7 +3390,7 @@ void PhysicalBone3D::update_bone_id() {
void PhysicalBone3D::update_offset() {
#ifdef TOOLS_ENABLED
if (parent_skeleton) {
- Transform bone_transform(parent_skeleton->get_global_transform());
+ Transform3D bone_transform(parent_skeleton->get_global_transform());
if (-1 != bone_id) {
bone_transform *= parent_skeleton->get_bone_global_pose(bone_id);
}
@@ -2483,10 +3410,10 @@ void PhysicalBone3D::_start_physics_simulation() {
return;
}
reset_to_rest_position();
- PhysicsServer3D::get_singleton()->body_set_mode(get_rid(), PhysicsServer3D::BODY_MODE_RIGID);
+ set_body_mode(PhysicsServer3D::BODY_MODE_DYNAMIC);
PhysicsServer3D::get_singleton()->body_set_collision_layer(get_rid(), get_collision_layer());
PhysicsServer3D::get_singleton()->body_set_collision_mask(get_rid(), get_collision_mask());
- PhysicsServer3D::get_singleton()->body_set_force_integration_callback(get_rid(), callable_mp(this, &PhysicalBone3D::_direct_state_changed));
+ PhysicsServer3D::get_singleton()->body_set_state_sync_callback(get_rid(), this, _body_state_changed_callback);
set_as_top_level(true);
_internal_simulate_physics = true;
}
@@ -2496,17 +3423,17 @@ void PhysicalBone3D::_stop_physics_simulation() {
return;
}
if (parent_skeleton->get_animate_physical_bones()) {
- PhysicsServer3D::get_singleton()->body_set_mode(get_rid(), PhysicsServer3D::BODY_MODE_KINEMATIC);
+ set_body_mode(PhysicsServer3D::BODY_MODE_KINEMATIC);
PhysicsServer3D::get_singleton()->body_set_collision_layer(get_rid(), get_collision_layer());
PhysicsServer3D::get_singleton()->body_set_collision_mask(get_rid(), get_collision_mask());
} else {
- PhysicsServer3D::get_singleton()->body_set_mode(get_rid(), PhysicsServer3D::BODY_MODE_STATIC);
+ set_body_mode(PhysicsServer3D::BODY_MODE_STATIC);
PhysicsServer3D::get_singleton()->body_set_collision_layer(get_rid(), 0);
PhysicsServer3D::get_singleton()->body_set_collision_mask(get_rid(), 0);
}
if (_internal_simulate_physics) {
- PhysicsServer3D::get_singleton()->body_set_force_integration_callback(get_rid(), Callable());
- parent_skeleton->set_bone_global_pose_override(bone_id, Transform(), 0.0, false);
+ PhysicsServer3D::get_singleton()->body_set_state_sync_callback(get_rid(), nullptr, nullptr);
+ parent_skeleton->set_bone_global_pose_override(bone_id, Transform3D(), 0.0, false);
set_as_top_level(false);
_internal_simulate_physics = false;
}
diff --git a/scene/3d/physics_body_3d.h b/scene/3d/physics_body_3d.h
index 818ff97730..e64987b73e 100644
--- a/scene/3d/physics_body_3d.h
+++ b/scene/3d/physics_body_3d.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -37,6 +37,8 @@
#include "servers/physics_server_3d.h"
#include "skeleton_3d.h"
+class KinematicCollision3D;
+
class PhysicsBody3D : public CollisionObject3D {
GDCLASS(PhysicsBody3D, CollisionObject3D);
@@ -44,7 +46,19 @@ protected:
static void _bind_methods();
PhysicsBody3D(PhysicsServer3D::BodyMode p_mode);
+ Ref<KinematicCollision3D> motion_cache;
+
+ uint16_t locked_axis = 0;
+
+ Ref<KinematicCollision3D> _move(const Vector3 &p_distance, bool p_test_only = false, real_t p_margin = 0.001, int p_max_collisions = 1);
+
public:
+ bool move_and_collide(const PhysicsServer3D::MotionParameters &p_parameters, PhysicsServer3D::MotionResult &r_result, bool p_test_only = false, bool p_cancel_sliding = true);
+ bool test_move(const Transform3D &p_from, const Vector3 &p_distance, const Ref<KinematicCollision3D> &r_collision = Ref<KinematicCollision3D>(), real_t p_margin = 0.001, int p_max_collisions = 1);
+
+ void set_axis_lock(PhysicsServer3D::BodyAxis p_axis, bool p_lock);
+ bool get_axis_lock(PhysicsServer3D::BodyAxis p_axis) const;
+
virtual Vector3 get_linear_velocity() const;
virtual Vector3 get_angular_velocity() const;
virtual real_t get_inverse_mass() const;
@@ -53,12 +67,13 @@ public:
void add_collision_exception_with(Node *p_node); //must be physicsbody
void remove_collision_exception_with(Node *p_node);
- PhysicsBody3D();
+ virtual ~PhysicsBody3D();
};
class StaticBody3D : public PhysicsBody3D {
GDCLASS(StaticBody3D, PhysicsBody3D);
+private:
Vector3 constant_linear_velocity;
Vector3 constant_angular_velocity;
@@ -77,38 +92,85 @@ public:
Vector3 get_constant_linear_velocity() const;
Vector3 get_constant_angular_velocity() const;
- StaticBody3D();
- ~StaticBody3D();
+ StaticBody3D(PhysicsServer3D::BodyMode p_mode = PhysicsServer3D::BODY_MODE_STATIC);
private:
void _reload_physics_characteristics();
};
-class RigidBody3D : public PhysicsBody3D {
- GDCLASS(RigidBody3D, PhysicsBody3D);
+class AnimatableBody3D : public StaticBody3D {
+ GDCLASS(AnimatableBody3D, StaticBody3D);
+
+private:
+ Vector3 linear_velocity;
+ Vector3 angular_velocity;
+
+ bool sync_to_physics = true;
+
+ Transform3D last_valid_transform;
+
+ static void _body_state_changed_callback(void *p_instance, PhysicsDirectBodyState3D *p_state);
+ void _body_state_changed(PhysicsDirectBodyState3D *p_state);
+
+protected:
+ void _notification(int p_what);
+ static void _bind_methods();
+
+public:
+ virtual Vector3 get_linear_velocity() const override;
+ virtual Vector3 get_angular_velocity() const override;
+
+ AnimatableBody3D();
+
+private:
+ void _update_kinematic_motion();
+
+ void set_sync_to_physics(bool p_enable);
+ bool is_sync_to_physics_enabled() const;
+};
+
+class RigidDynamicBody3D : public PhysicsBody3D {
+ GDCLASS(RigidDynamicBody3D, PhysicsBody3D);
public:
- enum Mode {
- MODE_RIGID,
- MODE_STATIC,
- MODE_CHARACTER,
- MODE_KINEMATIC,
+ enum FreezeMode {
+ FREEZE_MODE_STATIC,
+ FREEZE_MODE_KINEMATIC,
};
-protected:
+ enum CenterOfMassMode {
+ CENTER_OF_MASS_MODE_AUTO,
+ CENTER_OF_MASS_MODE_CUSTOM,
+ };
+
+ enum DampMode {
+ DAMP_MODE_COMBINE,
+ DAMP_MODE_REPLACE,
+ };
+
+private:
bool can_sleep = true;
- PhysicsDirectBodyState3D *state = nullptr;
- Mode mode = MODE_RIGID;
+ bool lock_rotation = false;
+ bool freeze = false;
+ FreezeMode freeze_mode = FREEZE_MODE_STATIC;
real_t mass = 1.0;
+ Vector3 inertia;
+ CenterOfMassMode center_of_mass_mode = CENTER_OF_MASS_MODE_AUTO;
+ Vector3 center_of_mass;
+
Ref<PhysicsMaterial> physics_material_override;
Vector3 linear_velocity;
Vector3 angular_velocity;
Basis inverse_inertia_tensor;
real_t gravity_scale = 1.0;
- real_t linear_damp = -1.0;
- real_t angular_damp = -1.0;
+
+ DampMode linear_damp_mode = DAMP_MODE_COMBINE;
+ DampMode angular_damp_mode = DAMP_MODE_COMBINE;
+
+ real_t linear_damp = 0.0;
+ real_t angular_damp = 0.0;
bool sleeping = false;
bool ccd = false;
@@ -136,7 +198,7 @@ protected:
tagged = false;
}
};
- struct RigidBody3D_RemoveAction {
+ struct RigidDynamicBody3D_RemoveAction {
RID rid;
ObjectID body_id;
ShapePair pair;
@@ -158,20 +220,44 @@ protected:
void _body_exit_tree(ObjectID p_id);
void _body_inout(int p_status, const RID &p_body, ObjectID p_instance, int p_body_shape, int p_local_shape);
- virtual void _direct_state_changed(Object *p_state);
+ static void _body_state_changed_callback(void *p_instance, PhysicsDirectBodyState3D *p_state);
+protected:
void _notification(int p_what);
static void _bind_methods();
+ virtual void _validate_property(PropertyInfo &property) const override;
+
+ GDVIRTUAL1(_integrate_forces, PhysicsDirectBodyState3D *)
+
+ virtual void _body_state_changed(PhysicsDirectBodyState3D *p_state);
+
+ void _apply_body_mode();
+
public:
- void set_mode(Mode p_mode);
- Mode get_mode() const;
+ void set_lock_rotation_enabled(bool p_lock_rotation);
+ bool is_lock_rotation_enabled() const;
+
+ void set_freeze_enabled(bool p_freeze);
+ bool is_freeze_enabled() const;
+
+ void set_freeze_mode(FreezeMode p_freeze_mode);
+ FreezeMode get_freeze_mode() const;
void set_mass(real_t p_mass);
real_t get_mass() const;
virtual real_t get_inverse_mass() const override { return 1.0 / mass; }
+ void set_inertia(const Vector3 &p_inertia);
+ const Vector3 &get_inertia() const;
+
+ void set_center_of_mass_mode(CenterOfMassMode p_mode);
+ CenterOfMassMode get_center_of_mass_mode() const;
+
+ void set_center_of_mass(const Vector3 &p_center_of_mass);
+ const Vector3 &get_center_of_mass() const;
+
void set_physics_material_override(const Ref<PhysicsMaterial> &p_physics_material_override);
Ref<PhysicsMaterial> get_physics_material_override() const;
@@ -188,6 +274,12 @@ public:
void set_gravity_scale(real_t p_gravity_scale);
real_t get_gravity_scale() const;
+ void set_linear_damp_mode(DampMode p_mode);
+ DampMode get_linear_damp_mode() const;
+
+ void set_angular_damp_mode(DampMode p_mode);
+ DampMode get_angular_damp_mode() const;
+
void set_linear_damp(real_t p_linear_damp);
real_t get_linear_damp() const;
@@ -212,138 +304,227 @@ public:
void set_use_continuous_collision_detection(bool p_enable);
bool is_using_continuous_collision_detection() const;
- void set_axis_lock(PhysicsServer3D::BodyAxis p_axis, bool p_lock);
- bool get_axis_lock(PhysicsServer3D::BodyAxis p_axis) const;
-
Array get_colliding_bodies() const;
- void add_central_force(const Vector3 &p_force);
- void add_force(const Vector3 &p_force, const Vector3 &p_position = Vector3());
- void add_torque(const Vector3 &p_torque);
-
void apply_central_impulse(const Vector3 &p_impulse);
void apply_impulse(const Vector3 &p_impulse, const Vector3 &p_position = Vector3());
void apply_torque_impulse(const Vector3 &p_impulse);
- TypedArray<String> get_configuration_warnings() const override;
+ void apply_central_force(const Vector3 &p_force);
+ void apply_force(const Vector3 &p_force, const Vector3 &p_position = Vector3());
+ void apply_torque(const Vector3 &p_torque);
- RigidBody3D();
- ~RigidBody3D();
+ void add_constant_central_force(const Vector3 &p_force);
+ void add_constant_force(const Vector3 &p_force, const Vector3 &p_position = Vector3());
+ void add_constant_torque(const Vector3 &p_torque);
+
+ void set_constant_force(const Vector3 &p_force);
+ Vector3 get_constant_force() const;
+
+ void set_constant_torque(const Vector3 &p_torque);
+ Vector3 get_constant_torque() const;
+
+ virtual TypedArray<String> get_configuration_warnings() const override;
+
+ RigidDynamicBody3D();
+ ~RigidDynamicBody3D();
private:
void _reload_physics_characteristics();
};
-VARIANT_ENUM_CAST(RigidBody3D::Mode);
+VARIANT_ENUM_CAST(RigidDynamicBody3D::FreezeMode);
+VARIANT_ENUM_CAST(RigidDynamicBody3D::CenterOfMassMode);
+VARIANT_ENUM_CAST(RigidDynamicBody3D::DampMode);
class KinematicCollision3D;
-class KinematicBody3D : public PhysicsBody3D {
- GDCLASS(KinematicBody3D, PhysicsBody3D);
+class CharacterBody3D : public PhysicsBody3D {
+ GDCLASS(CharacterBody3D, PhysicsBody3D);
public:
- struct Collision {
- Vector3 collision;
- Vector3 normal;
- Vector3 collider_vel;
- ObjectID collider;
- RID collider_rid;
- int collider_shape = 0;
- Variant collider_metadata;
- Vector3 remainder;
- Vector3 travel;
- int local_shape = 0;
+ enum MotionMode {
+ MOTION_MODE_GROUNDED,
+ MOTION_MODE_FLOATING,
+ };
+ enum MovingPlatformApplyVelocityOnLeave {
+ PLATFORM_VEL_ON_LEAVE_ALWAYS,
+ PLATFORM_VEL_ON_LEAVE_UPWARD_ONLY,
+ PLATFORM_VEL_ON_LEAVE_NEVER,
};
+ bool move_and_slide();
+
+ const Vector3 &get_velocity() const;
+ void set_velocity(const Vector3 &p_velocity);
+
+ bool is_on_floor() const;
+ bool is_on_floor_only() const;
+ bool is_on_wall() const;
+ bool is_on_wall_only() const;
+ bool is_on_ceiling() const;
+ bool is_on_ceiling_only() const;
+ const Vector3 &get_last_motion() const;
+ Vector3 get_position_delta() const;
+ const Vector3 &get_floor_normal() const;
+ const Vector3 &get_wall_normal() const;
+ const Vector3 &get_real_velocity() const;
+ real_t get_floor_angle(const Vector3 &p_up_direction = Vector3(0.0, 1.0, 0.0)) const;
+ const Vector3 &get_platform_velocity() const;
+
+ virtual Vector3 get_linear_velocity() const override;
+
+ int get_slide_collision_count() const;
+ PhysicsServer3D::MotionResult get_slide_collision(int p_bounce) const;
+
+ CharacterBody3D();
+ ~CharacterBody3D();
private:
- Vector3 linear_velocity;
- Vector3 angular_velocity;
+ real_t margin = 0.001;
+ MotionMode motion_mode = MOTION_MODE_GROUNDED;
+ MovingPlatformApplyVelocityOnLeave moving_platform_apply_velocity_on_leave = PLATFORM_VEL_ON_LEAVE_ALWAYS;
+ union CollisionState {
+ uint32_t state = 0;
+ struct {
+ bool floor;
+ bool wall;
+ bool ceiling;
+ };
- uint16_t locked_axis = 0;
+ CollisionState() {
+ }
- real_t margin;
+ CollisionState(bool p_floor, bool p_wall, bool p_ceiling) {
+ floor = p_floor;
+ wall = p_wall;
+ ceiling = p_ceiling;
+ }
+ };
+ CollisionState collision_state;
+ bool floor_constant_speed = false;
+ bool floor_stop_on_slope = true;
+ bool floor_block_on_wall = true;
+ bool slide_on_ceiling = true;
+ int max_slides = 6;
+ int platform_layer = 0;
+ RID platform_rid;
+ ObjectID platform_object_id;
+ uint32_t moving_platform_floor_layers = UINT32_MAX;
+ uint32_t moving_platform_wall_layers = 0;
+ real_t floor_snap_length = 0.1;
+ real_t floor_max_angle = Math::deg2rad((real_t)45.0);
+ real_t wall_min_slide_angle = Math::deg2rad((real_t)15.0);
+ Vector3 up_direction = Vector3(0.0, 1.0, 0.0);
+ Vector3 velocity;
Vector3 floor_normal;
- Vector3 floor_velocity;
- RID on_floor_body;
- bool on_floor = false;
- bool on_ceiling = false;
- bool on_wall = false;
- Vector<Collision> colliders;
+ Vector3 wall_normal;
+ Vector3 ceiling_normal;
+ Vector3 last_motion;
+ Vector3 platform_velocity;
+ Vector3 platform_ceiling_velocity;
+ Vector3 previous_position;
+ Vector3 real_velocity;
+
+ Vector<PhysicsServer3D::MotionResult> motion_results;
Vector<Ref<KinematicCollision3D>> slide_colliders;
- Ref<KinematicCollision3D> motion_cache;
- _FORCE_INLINE_ bool _ignores_mode(PhysicsServer3D::BodyMode) const;
+ void set_safe_margin(real_t p_margin);
+ real_t get_safe_margin() const;
- Ref<KinematicCollision3D> _move(const Vector3 &p_motion, bool p_infinite_inertia = true, bool p_exclude_raycast_shapes = true, bool p_test_only = false);
- Ref<KinematicCollision3D> _get_slide_collision(int p_bounce);
+ bool is_floor_stop_on_slope_enabled() const;
+ void set_floor_stop_on_slope_enabled(bool p_enabled);
-protected:
- void _notification(int p_what);
- static void _bind_methods();
+ bool is_floor_constant_speed_enabled() const;
+ void set_floor_constant_speed_enabled(bool p_enabled);
- virtual void _direct_state_changed(Object *p_state);
+ bool is_floor_block_on_wall_enabled() const;
+ void set_floor_block_on_wall_enabled(bool p_enabled);
-public:
- virtual Vector3 get_linear_velocity() const override;
- virtual Vector3 get_angular_velocity() const override;
+ bool is_slide_on_ceiling_enabled() const;
+ void set_slide_on_ceiling_enabled(bool p_enabled);
- bool move_and_collide(const Vector3 &p_motion, bool p_infinite_inertia, Collision &r_collision, bool p_exclude_raycast_shapes = true, bool p_test_only = false);
- bool test_move(const Transform &p_from, const Vector3 &p_motion, bool p_infinite_inertia);
+ int get_max_slides() const;
+ void set_max_slides(int p_max_slides);
- bool separate_raycast_shapes(bool p_infinite_inertia, Collision &r_collision);
+ real_t get_floor_max_angle() const;
+ void set_floor_max_angle(real_t p_radians);
- void set_axis_lock(PhysicsServer3D::BodyAxis p_axis, bool p_lock);
- bool get_axis_lock(PhysicsServer3D::BodyAxis p_axis) const;
+ real_t get_floor_snap_length();
+ void set_floor_snap_length(real_t p_floor_snap_length);
- void set_safe_margin(real_t p_margin);
- real_t get_safe_margin() const;
+ real_t get_wall_min_slide_angle() const;
+ void set_wall_min_slide_angle(real_t p_radians);
- Vector3 move_and_slide(const Vector3 &p_linear_velocity, const Vector3 &p_up_direction = Vector3(0, 0, 0), bool p_stop_on_slope = false, int p_max_slides = 4, real_t p_floor_max_angle = Math::deg2rad((real_t)45.0), bool p_infinite_inertia = true);
- Vector3 move_and_slide_with_snap(const Vector3 &p_linear_velocity, const Vector3 &p_snap, const Vector3 &p_up_direction = Vector3(0, 0, 0), bool p_stop_on_slope = false, int p_max_slides = 4, real_t p_floor_max_angle = Math::deg2rad((real_t)45.0), bool p_infinite_inertia = true);
- bool is_on_floor() const;
- bool is_on_wall() const;
- bool is_on_ceiling() const;
- Vector3 get_floor_normal() const;
- Vector3 get_floor_velocity() const;
+ uint32_t get_moving_platform_floor_layers() const;
+ void set_moving_platform_floor_layers(const uint32_t p_exclude_layer);
+
+ uint32_t get_moving_platform_wall_layers() const;
+ void set_moving_platform_wall_layers(const uint32_t p_exclude_layer);
+
+ void set_motion_mode(MotionMode p_mode);
+ MotionMode get_motion_mode() const;
- int get_slide_count() const;
- Collision get_slide_collision(int p_bounce) const;
+ void set_moving_platform_apply_velocity_on_leave(MovingPlatformApplyVelocityOnLeave p_on_leave_velocity);
+ MovingPlatformApplyVelocityOnLeave get_moving_platform_apply_velocity_on_leave() const;
- KinematicBody3D();
- ~KinematicBody3D();
+ void _move_and_slide_floating(double p_delta);
+ void _move_and_slide_grounded(double p_delta, bool p_was_on_floor);
+
+ Ref<KinematicCollision3D> _get_slide_collision(int p_bounce);
+ Ref<KinematicCollision3D> _get_last_slide_collision();
+ const Vector3 &get_up_direction() const;
+ bool _on_floor_if_snapped(bool p_was_on_floor, bool p_vel_dir_facing_up);
+ void set_up_direction(const Vector3 &p_up_direction);
+ void _set_collision_direction(const PhysicsServer3D::MotionResult &p_result, CollisionState &r_state, CollisionState p_apply_state = CollisionState(true, true, true));
+ void _set_platform_data(const PhysicsServer3D::MotionCollision &p_collision);
+ void _snap_on_floor(bool p_was_on_floor, bool p_vel_dir_facing_up);
+
+protected:
+ void _notification(int p_what);
+ static void _bind_methods();
+ virtual void _validate_property(PropertyInfo &property) const override;
};
-class KinematicCollision3D : public Reference {
- GDCLASS(KinematicCollision3D, Reference);
+VARIANT_ENUM_CAST(CharacterBody3D::MotionMode);
+VARIANT_ENUM_CAST(CharacterBody3D::MovingPlatformApplyVelocityOnLeave);
+
+class KinematicCollision3D : public RefCounted {
+ GDCLASS(KinematicCollision3D, RefCounted);
- KinematicBody3D *owner;
- friend class KinematicBody3D;
- KinematicBody3D::Collision collision;
+ PhysicsBody3D *owner = nullptr;
+ friend class PhysicsBody3D;
+ friend class CharacterBody3D;
+ PhysicsServer3D::MotionResult result;
protected:
static void _bind_methods();
public:
- Vector3 get_position() const;
- Vector3 get_normal() const;
Vector3 get_travel() const;
Vector3 get_remainder() const;
- Object *get_local_shape() const;
- Object *get_collider() const;
- ObjectID get_collider_id() const;
- Object *get_collider_shape() const;
- int get_collider_shape_index() const;
- Vector3 get_collider_velocity() const;
- Variant get_collider_metadata() const;
-
- KinematicCollision3D();
+ int get_collision_count() const;
+ Vector3 get_position(int p_collision_index = 0) const;
+ Vector3 get_normal(int p_collision_index = 0) const;
+ real_t get_angle(int p_collision_index = 0, const Vector3 &p_up_direction = Vector3(0.0, 1.0, 0.0)) const;
+ Object *get_local_shape(int p_collision_index = 0) const;
+ Object *get_collider(int p_collision_index = 0) const;
+ ObjectID get_collider_id(int p_collision_index = 0) const;
+ RID get_collider_rid(int p_collision_index = 0) const;
+ Object *get_collider_shape(int p_collision_index = 0) const;
+ int get_collider_shape_index(int p_collision_index = 0) const;
+ Vector3 get_collider_velocity(int p_collision_index = 0) const;
};
class PhysicalBone3D : public PhysicsBody3D {
GDCLASS(PhysicalBone3D, PhysicsBody3D);
public:
+ enum DampMode {
+ DAMP_MODE_COMBINE,
+ DAMP_MODE_REPLACE,
+ };
+
enum JointType {
JOINT_TYPE_NONE,
JOINT_TYPE_PIN,
@@ -467,12 +648,12 @@ private:
#endif
JointData *joint_data = nullptr;
- Transform joint_offset;
+ Transform3D joint_offset;
RID joint;
Skeleton3D *parent_skeleton = nullptr;
- Transform body_offset;
- Transform body_offset_inverse;
+ Transform3D body_offset;
+ Transform3D body_offset_inverse;
bool simulate_physics = false;
bool _internal_simulate_physics = false;
int bone_id = -1;
@@ -481,17 +662,27 @@ private:
real_t bounce = 0.0;
real_t mass = 1.0;
real_t friction = 1.0;
+ Vector3 linear_velocity;
+ Vector3 angular_velocity;
real_t gravity_scale = 1.0;
- real_t linear_damp = -1.0;
- real_t angular_damp = -1.0;
bool can_sleep = true;
+ bool custom_integrator = false;
+
+ DampMode linear_damp_mode = DAMP_MODE_COMBINE;
+ DampMode angular_damp_mode = DAMP_MODE_COMBINE;
+
+ real_t linear_damp = 0.0;
+ real_t angular_damp = 0.0;
+
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 _notification(int p_what);
- void _direct_state_changed(Object *p_state);
+ GDVIRTUAL1(_integrate_forces, PhysicsDirectBodyState3D *)
+ static void _body_state_changed_callback(void *p_instance, PhysicsDirectBodyState3D *p_state);
+ void _body_state_changed(PhysicsDirectBodyState3D *p_state);
static void _bind_methods();
@@ -504,12 +695,20 @@ private:
public:
void _on_bone_parent_changed();
- void _set_gizmo_move_joint(bool p_move_joint);
-public:
+ void set_linear_velocity(const Vector3 &p_velocity);
+ Vector3 get_linear_velocity() const override;
+
+ void set_angular_velocity(const Vector3 &p_velocity);
+ Vector3 get_angular_velocity() const override;
+
+ void set_use_custom_integrator(bool p_enable);
+ bool is_using_custom_integrator();
+
#ifdef TOOLS_ENABLED
- virtual Transform get_global_gizmo_transform() const override;
- virtual Transform get_local_gizmo_transform() const override;
+ void _set_gizmo_move_joint(bool p_move_joint);
+ virtual Transform3D get_global_gizmo_transform() const override;
+ virtual Transform3D get_local_gizmo_transform() const override;
#endif
const JointData *get_joint_data() const;
@@ -520,17 +719,14 @@ public:
void set_joint_type(JointType p_joint_type);
JointType get_joint_type() const;
- void set_joint_offset(const Transform &p_offset);
- const Transform &get_joint_offset() const;
+ void set_joint_offset(const Transform3D &p_offset);
+ const Transform3D &get_joint_offset() const;
void set_joint_rotation(const Vector3 &p_euler_rad);
Vector3 get_joint_rotation() const;
- void set_joint_rotation_degrees(const Vector3 &p_euler_deg);
- Vector3 get_joint_rotation_degrees() const;
-
- void set_body_offset(const Transform &p_offset);
- const Transform &get_body_offset() const;
+ void set_body_offset(const Transform3D &p_offset);
+ const Transform3D &get_body_offset() const;
void set_simulate_physics(bool p_simulate);
bool get_simulate_physics();
@@ -551,6 +747,12 @@ public:
void set_gravity_scale(real_t p_gravity_scale);
real_t get_gravity_scale() const;
+ void set_linear_damp_mode(DampMode p_mode);
+ DampMode get_linear_damp_mode() const;
+
+ void set_angular_damp_mode(DampMode p_mode);
+ DampMode get_angular_damp_mode() const;
+
void set_linear_damp(real_t p_linear_damp);
real_t get_linear_damp() const;
@@ -560,9 +762,6 @@ public:
void set_can_sleep(bool p_active);
bool is_able_to_sleep() const;
- void set_axis_lock(PhysicsServer3D::BodyAxis p_axis, bool p_lock);
- bool get_axis_lock(PhysicsServer3D::BodyAxis p_axis) const;
-
void apply_central_impulse(const Vector3 &p_impulse);
void apply_impulse(const Vector3 &p_impulse, const Vector3 &p_position = Vector3());
@@ -581,5 +780,6 @@ private:
};
VARIANT_ENUM_CAST(PhysicalBone3D::JointType);
+VARIANT_ENUM_CAST(PhysicalBone3D::DampMode);
#endif // PHYSICS_BODY__H
diff --git a/scene/3d/position_3d.cpp b/scene/3d/position_3d.cpp
index b231ba0df7..7dc1b1ace0 100644
--- a/scene/3d/position_3d.cpp
+++ b/scene/3d/position_3d.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -29,7 +29,6 @@
/*************************************************************************/
#include "position_3d.h"
-#include "scene/resources/mesh.h"
Position3D::Position3D() {
}
diff --git a/scene/3d/position_3d.h b/scene/3d/position_3d.h
index 065b14c3bd..5514399e6e 100644
--- a/scene/3d/position_3d.h
+++ b/scene/3d/position_3d.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
diff --git a/scene/3d/proximity_group_3d.cpp b/scene/3d/proximity_group_3d.cpp
deleted file mode 100644
index 9d9fea68b0..0000000000
--- a/scene/3d/proximity_group_3d.cpp
+++ /dev/null
@@ -1,185 +0,0 @@
-/*************************************************************************/
-/* proximity_group_3d.cpp */
-/*************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
-/* */
-/* Permission is hereby granted, free of charge, to any person obtaining */
-/* a copy of this software and associated documentation files (the */
-/* "Software"), to deal in the Software without restriction, including */
-/* without limitation the rights to use, copy, modify, merge, publish, */
-/* distribute, sublicense, and/or sell copies of the Software, and to */
-/* permit persons to whom the Software is furnished to do so, subject to */
-/* the following conditions: */
-/* */
-/* The above copyright notice and this permission notice shall be */
-/* included in all copies or substantial portions of the Software. */
-/* */
-/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
-/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
-/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
-/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
-/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
-/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
-/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
-/*************************************************************************/
-
-#include "proximity_group_3d.h"
-
-#include "core/math/math_funcs.h"
-
-void ProximityGroup3D::_clear_groups() {
- Map<StringName, uint32_t>::Element *E;
-
- {
- const int size = 16;
- StringName remove_list[size];
- E = groups.front();
- int num = 0;
- while (E && num < size) {
- if (E->get() != group_version) {
- remove_list[num++] = E->key();
- }
-
- E = E->next();
- }
- for (int i = 0; i < num; i++) {
- groups.erase(remove_list[i]);
- }
- }
-
- if (E) {
- _clear_groups(); // call until we go through the whole list
- }
-}
-
-void ProximityGroup3D::_update_groups() {
- if (grid_radius == Vector3(0, 0, 0)) {
- return;
- }
-
- ++group_version;
-
- Vector3 pos = get_global_transform().get_origin();
- Vector3 vcell = pos / cell_size;
- int cell[3] = { Math::fast_ftoi(vcell.x), Math::fast_ftoi(vcell.y), Math::fast_ftoi(vcell.z) };
-
- _add_groups(cell, group_name, 0);
-
- _clear_groups();
-}
-
-void ProximityGroup3D::_add_groups(int *p_cell, String p_base, int p_depth) {
- p_base = p_base + "|";
- if (grid_radius[p_depth] == 0) {
- if (p_depth == 2) {
- _new_group(p_base);
- } else {
- _add_groups(p_cell, p_base, p_depth + 1);
- }
- }
-
- int start = p_cell[p_depth] - grid_radius[p_depth];
- int end = p_cell[p_depth] + grid_radius[p_depth];
-
- for (int i = start; i <= end; i++) {
- String gname = p_base + itos(i);
- if (p_depth == 2) {
- _new_group(gname);
- } else {
- _add_groups(p_cell, gname, p_depth + 1);
- }
- }
-}
-
-void ProximityGroup3D::_new_group(StringName p_name) {
- const Map<StringName, uint32_t>::Element *E = groups.find(p_name);
- if (!E) {
- add_to_group(p_name);
- }
-
- groups[p_name] = group_version;
-}
-
-void ProximityGroup3D::_notification(int p_what) {
- switch (p_what) {
- case NOTIFICATION_EXIT_TREE:
- ++group_version;
- _clear_groups();
- break;
- case NOTIFICATION_TRANSFORM_CHANGED:
- _update_groups();
- break;
- }
-}
-
-void ProximityGroup3D::broadcast(String p_method, Variant p_parameters) {
- Map<StringName, uint32_t>::Element *E;
- E = groups.front();
- while (E) {
- get_tree()->call_group_flags(SceneTree::GROUP_CALL_DEFAULT, E->key(), "_proximity_group_broadcast", p_method, p_parameters);
- E = E->next();
- }
-}
-
-void ProximityGroup3D::_proximity_group_broadcast(String p_method, Variant p_parameters) {
- if (dispatch_mode == MODE_PROXY) {
- get_parent()->call(p_method, p_parameters);
- } else {
- emit_signal("broadcast", p_method, p_parameters);
- }
-}
-
-void ProximityGroup3D::set_group_name(const String &p_group_name) {
- group_name = p_group_name;
-}
-
-String ProximityGroup3D::get_group_name() const {
- return group_name;
-}
-
-void ProximityGroup3D::set_dispatch_mode(DispatchMode p_mode) {
- dispatch_mode = p_mode;
-}
-
-ProximityGroup3D::DispatchMode ProximityGroup3D::get_dispatch_mode() const {
- return dispatch_mode;
-}
-
-void ProximityGroup3D::set_grid_radius(const Vector3 &p_radius) {
- grid_radius = p_radius;
-}
-
-Vector3 ProximityGroup3D::get_grid_radius() const {
- return grid_radius;
-}
-
-void ProximityGroup3D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_group_name", "name"), &ProximityGroup3D::set_group_name);
- ClassDB::bind_method(D_METHOD("get_group_name"), &ProximityGroup3D::get_group_name);
- ClassDB::bind_method(D_METHOD("set_dispatch_mode", "mode"), &ProximityGroup3D::set_dispatch_mode);
- ClassDB::bind_method(D_METHOD("get_dispatch_mode"), &ProximityGroup3D::get_dispatch_mode);
- ClassDB::bind_method(D_METHOD("set_grid_radius", "radius"), &ProximityGroup3D::set_grid_radius);
- ClassDB::bind_method(D_METHOD("get_grid_radius"), &ProximityGroup3D::get_grid_radius);
-
- ClassDB::bind_method(D_METHOD("broadcast", "method", "parameters"), &ProximityGroup3D::broadcast);
-
- ClassDB::bind_method(D_METHOD("_proximity_group_broadcast", "method", "parameters"), &ProximityGroup3D::_proximity_group_broadcast);
-
- ADD_PROPERTY(PropertyInfo(Variant::STRING, "group_name"), "set_group_name", "get_group_name");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "dispatch_mode", PROPERTY_HINT_ENUM, "Proxy,Signal"), "set_dispatch_mode", "get_dispatch_mode");
- ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "grid_radius"), "set_grid_radius", "get_grid_radius");
-
- ADD_SIGNAL(MethodInfo("broadcast", PropertyInfo(Variant::STRING, "method"), PropertyInfo(Variant::ARRAY, "parameters")));
-
- BIND_ENUM_CONSTANT(MODE_PROXY);
- BIND_ENUM_CONSTANT(MODE_SIGNAL);
-}
-
-ProximityGroup3D::ProximityGroup3D() {
- set_notify_transform(true);
-}
diff --git a/scene/3d/ray_cast_3d.cpp b/scene/3d/ray_cast_3d.cpp
index 475f8c07fd..f5e08b92ca 100644
--- a/scene/3d/ray_cast_3d.cpp
+++ b/scene/3d/ray_cast_3d.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -31,13 +31,11 @@
#include "ray_cast_3d.h"
#include "collision_object_3d.h"
-#include "core/config/engine.h"
#include "mesh_instance_3d.h"
-#include "servers/physics_server_3d.h"
void RayCast3D::set_target_position(const Vector3 &p_point) {
target_position = p_point;
- update_gizmo();
+ update_gizmos();
if (Engine::get_singleton()->is_editor_hint()) {
if (is_inside_tree()) {
@@ -60,20 +58,22 @@ uint32_t RayCast3D::get_collision_mask() const {
return collision_mask;
}
-void RayCast3D::set_collision_mask_bit(int p_bit, bool p_value) {
- ERR_FAIL_INDEX_MSG(p_bit, 32, "Collision mask bit must be between 0 and 31 inclusive.");
+void RayCast3D::set_collision_mask_value(int p_layer_number, bool p_value) {
+ ERR_FAIL_COND_MSG(p_layer_number < 1, "Collision layer number must be between 1 and 32 inclusive.");
+ ERR_FAIL_COND_MSG(p_layer_number > 32, "Collision layer number must be between 1 and 32 inclusive.");
uint32_t mask = get_collision_mask();
if (p_value) {
- mask |= 1 << p_bit;
+ mask |= 1 << (p_layer_number - 1);
} else {
- mask &= ~(1 << p_bit);
+ mask &= ~(1 << (p_layer_number - 1));
}
set_collision_mask(mask);
}
-bool RayCast3D::get_collision_mask_bit(int p_bit) const {
- ERR_FAIL_INDEX_V_MSG(p_bit, 32, false, "Collision mask bit must be between 0 and 31 inclusive.");
- return get_collision_mask() & (1 << p_bit);
+bool RayCast3D::get_collision_mask_value(int p_layer_number) const {
+ ERR_FAIL_COND_V_MSG(p_layer_number < 1, false, "Collision layer number must be between 1 and 32 inclusive.");
+ ERR_FAIL_COND_V_MSG(p_layer_number > 32, false, "Collision layer number must be between 1 and 32 inclusive.");
+ return get_collision_mask() & (1 << (p_layer_number - 1));
}
bool RayCast3D::is_colliding() const {
@@ -102,7 +102,7 @@ Vector3 RayCast3D::get_collision_normal() const {
void RayCast3D::set_enabled(bool p_enabled) {
enabled = p_enabled;
- update_gizmo();
+ update_gizmos();
if (is_inside_tree() && !Engine::get_singleton()->is_editor_hint()) {
set_physics_process_internal(p_enabled);
@@ -171,8 +171,8 @@ void RayCast3D::_notification(int p_what) {
exclude.erase(Object::cast_to<CollisionObject3D>(get_parent())->get_rid());
}
}
-
} break;
+
case NOTIFICATION_EXIT_TREE: {
if (enabled) {
set_physics_process_internal(false);
@@ -181,8 +181,8 @@ void RayCast3D::_notification(int p_what) {
if (debug_shape) {
_clear_debug_shape();
}
-
} break;
+
case NOTIFICATION_INTERNAL_PHYSICS_PROCESS: {
if (!enabled) {
break;
@@ -193,7 +193,6 @@ void RayCast3D::_notification(int p_what) {
if (prev_collision_state != collided && get_tree()->is_debugging_collisions_hint()) {
_update_debug_shape_material(true);
}
-
} break;
}
}
@@ -205,16 +204,24 @@ void RayCast3D::_update_raycast_state() {
PhysicsDirectSpaceState3D *dss = PhysicsServer3D::get_singleton()->space_get_direct_state(w3d->get_space());
ERR_FAIL_COND(!dss);
- Transform gt = get_global_transform();
+ Transform3D gt = get_global_transform();
Vector3 to = target_position;
if (to == Vector3()) {
to = Vector3(0, 0.01, 0);
}
- PhysicsDirectSpaceState3D::RayResult rr;
+ PhysicsDirectSpaceState3D::RayParameters ray_params;
+ ray_params.from = gt.get_origin();
+ ray_params.to = gt.xform(to);
+ ray_params.exclude = exclude;
+ ray_params.collision_mask = collision_mask;
+ ray_params.collide_with_bodies = collide_with_bodies;
+ ray_params.collide_with_areas = collide_with_areas;
+ ray_params.hit_from_inside = hit_from_inside;
- if (dss->intersect_ray(gt.get_origin(), gt.xform(to), rr, exclude, collision_mask, collide_with_bodies, collide_with_areas)) {
+ PhysicsDirectSpaceState3D::RayResult rr;
+ if (dss->intersect_ray(ray_params, rr)) {
collided = true;
against = rr.collider_id;
collision_point = rr.position;
@@ -235,48 +242,55 @@ void RayCast3D::add_exception_rid(const RID &p_rid) {
exclude.insert(p_rid);
}
-void RayCast3D::add_exception(const Object *p_object) {
- ERR_FAIL_NULL(p_object);
- const CollisionObject3D *co = Object::cast_to<CollisionObject3D>(p_object);
- if (!co) {
- return;
- }
- add_exception_rid(co->get_rid());
+void RayCast3D::add_exception(const CollisionObject3D *p_node) {
+ ERR_FAIL_NULL_MSG(p_node, "The passed Node must be an instance of CollisionObject3D.");
+ add_exception_rid(p_node->get_rid());
}
void RayCast3D::remove_exception_rid(const RID &p_rid) {
exclude.erase(p_rid);
}
-void RayCast3D::remove_exception(const Object *p_object) {
- ERR_FAIL_NULL(p_object);
- const CollisionObject3D *co = Object::cast_to<CollisionObject3D>(p_object);
- if (!co) {
- return;
- }
- remove_exception_rid(co->get_rid());
+void RayCast3D::remove_exception(const CollisionObject3D *p_node) {
+ ERR_FAIL_NULL_MSG(p_node, "The passed Node must be an instance of CollisionObject3D.");
+ remove_exception_rid(p_node->get_rid());
}
void RayCast3D::clear_exceptions() {
exclude.clear();
+
+ if (exclude_parent_body && is_inside_tree()) {
+ CollisionObject3D *parent = Object::cast_to<CollisionObject3D>(get_parent());
+ if (parent) {
+ exclude.insert(parent->get_rid());
+ }
+ }
}
-void RayCast3D::set_collide_with_areas(bool p_clip) {
- collide_with_areas = p_clip;
+void RayCast3D::set_collide_with_areas(bool p_enabled) {
+ collide_with_areas = p_enabled;
}
bool RayCast3D::is_collide_with_areas_enabled() const {
return collide_with_areas;
}
-void RayCast3D::set_collide_with_bodies(bool p_clip) {
- collide_with_bodies = p_clip;
+void RayCast3D::set_collide_with_bodies(bool p_enabled) {
+ collide_with_bodies = p_enabled;
}
bool RayCast3D::is_collide_with_bodies_enabled() const {
return collide_with_bodies;
}
+void RayCast3D::set_hit_from_inside(bool p_enabled) {
+ hit_from_inside = p_enabled;
+}
+
+bool RayCast3D::is_hit_from_inside_enabled() const {
+ return hit_from_inside;
+}
+
void RayCast3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_enabled", "enabled"), &RayCast3D::set_enabled);
ClassDB::bind_method(D_METHOD("is_enabled"), &RayCast3D::is_enabled);
@@ -303,8 +317,8 @@ void RayCast3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_collision_mask", "mask"), &RayCast3D::set_collision_mask);
ClassDB::bind_method(D_METHOD("get_collision_mask"), &RayCast3D::get_collision_mask);
- ClassDB::bind_method(D_METHOD("set_collision_mask_bit", "bit", "value"), &RayCast3D::set_collision_mask_bit);
- ClassDB::bind_method(D_METHOD("get_collision_mask_bit", "bit"), &RayCast3D::get_collision_mask_bit);
+ ClassDB::bind_method(D_METHOD("set_collision_mask_value", "layer_number", "value"), &RayCast3D::set_collision_mask_value);
+ ClassDB::bind_method(D_METHOD("get_collision_mask_value", "layer_number"), &RayCast3D::get_collision_mask_value);
ClassDB::bind_method(D_METHOD("set_exclude_parent_body", "mask"), &RayCast3D::set_exclude_parent_body);
ClassDB::bind_method(D_METHOD("get_exclude_parent_body"), &RayCast3D::get_exclude_parent_body);
@@ -315,6 +329,9 @@ void RayCast3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_collide_with_bodies", "enable"), &RayCast3D::set_collide_with_bodies);
ClassDB::bind_method(D_METHOD("is_collide_with_bodies_enabled"), &RayCast3D::is_collide_with_bodies_enabled);
+ ClassDB::bind_method(D_METHOD("set_hit_from_inside", "enable"), &RayCast3D::set_hit_from_inside);
+ ClassDB::bind_method(D_METHOD("is_hit_from_inside_enabled"), &RayCast3D::is_hit_from_inside_enabled);
+
ClassDB::bind_method(D_METHOD("set_debug_shape_custom_color", "debug_shape_custom_color"), &RayCast3D::set_debug_shape_custom_color);
ClassDB::bind_method(D_METHOD("get_debug_shape_custom_color"), &RayCast3D::get_debug_shape_custom_color);
@@ -325,6 +342,7 @@ void RayCast3D::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "exclude_parent"), "set_exclude_parent_body", "get_exclude_parent_body");
ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "target_position"), "set_target_position", "get_target_position");
ADD_PROPERTY(PropertyInfo(Variant::INT, "collision_mask", PROPERTY_HINT_LAYERS_3D_PHYSICS), "set_collision_mask", "get_collision_mask");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "hit_from_inside"), "set_hit_from_inside", "is_hit_from_inside_enabled");
ADD_GROUP("Collide With", "collide_with");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "collide_with_areas", PROPERTY_HINT_LAYERS_3D_PHYSICS), "set_collide_with_areas", "is_collide_with_areas_enabled");
@@ -335,7 +353,7 @@ void RayCast3D::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::INT, "debug_shape_thickness", PROPERTY_HINT_RANGE, "1,5"), "set_debug_shape_thickness", "get_debug_shape_thickness");
}
-float RayCast3D::get_debug_shape_thickness() const {
+int RayCast3D::get_debug_shape_thickness() const {
return debug_shape_thickness;
}
@@ -364,9 +382,9 @@ void RayCast3D::_update_debug_shape_vertices() {
}
}
-void RayCast3D::set_debug_shape_thickness(const float p_debug_shape_thickness) {
+void RayCast3D::set_debug_shape_thickness(const int p_debug_shape_thickness) {
debug_shape_thickness = p_debug_shape_thickness;
- update_gizmo();
+ update_gizmos();
if (Engine::get_singleton()->is_editor_hint()) {
if (is_inside_tree()) {
@@ -419,6 +437,8 @@ void RayCast3D::_update_debug_shape_material(bool p_check_collision) {
debug_material = material;
material->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED);
+ // Use double-sided rendering so that the RayCast can be seen if the camera is inside.
+ material->set_cull_mode(BaseMaterial3D::CULL_DISABLED);
material->set_transparency(BaseMaterial3D::TRANSPARENCY_ALPHA);
}
diff --git a/scene/3d/ray_cast_3d.h b/scene/3d/ray_cast_3d.h
index 968cede9f2..ad85001591 100644
--- a/scene/3d/ray_cast_3d.h
+++ b/scene/3d/ray_cast_3d.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -33,6 +33,8 @@
#include "scene/3d/node_3d.h"
+class CollisionObject3D;
+
class RayCast3D : public Node3D {
GDCLASS(RayCast3D, Node3D);
@@ -65,18 +67,23 @@ class RayCast3D : public Node3D {
bool collide_with_areas = false;
bool collide_with_bodies = true;
+ bool hit_from_inside = false;
+
protected:
void _notification(int p_what);
void _update_raycast_state();
static void _bind_methods();
public:
- void set_collide_with_areas(bool p_clip);
+ void set_collide_with_areas(bool p_enabled);
bool is_collide_with_areas_enabled() const;
- void set_collide_with_bodies(bool p_clip);
+ void set_collide_with_bodies(bool p_enabled);
bool is_collide_with_bodies_enabled() const;
+ void set_hit_from_inside(bool p_enabled);
+ bool is_hit_from_inside_enabled() const;
+
void set_enabled(bool p_enabled);
bool is_enabled() const;
@@ -86,8 +93,8 @@ public:
void set_collision_mask(uint32_t p_mask);
uint32_t get_collision_mask() const;
- void set_collision_mask_bit(int p_bit, bool p_value);
- bool get_collision_mask_bit(int p_bit) const;
+ void set_collision_mask_value(int p_layer_number, bool p_value);
+ bool get_collision_mask_value(int p_layer_number) const;
void set_exclude_parent_body(bool p_exclude_parent_body);
bool get_exclude_parent_body() const;
@@ -100,8 +107,8 @@ public:
Ref<StandardMaterial3D> get_debug_material();
- float get_debug_shape_thickness() const;
- void set_debug_shape_thickness(const float p_debug_thickness);
+ int get_debug_shape_thickness() const;
+ void set_debug_shape_thickness(const int p_debug_thickness);
void force_raycast_update();
bool is_colliding() const;
@@ -111,9 +118,9 @@ public:
Vector3 get_collision_normal() const;
void add_exception_rid(const RID &p_rid);
- void add_exception(const Object *p_object);
+ void add_exception(const CollisionObject3D *p_node);
void remove_exception_rid(const RID &p_rid);
- void remove_exception(const Object *p_object);
+ void remove_exception(const CollisionObject3D *p_node);
void clear_exceptions();
RayCast3D();
diff --git a/scene/3d/reflection_probe.cpp b/scene/3d/reflection_probe.cpp
index ad24f39bce..1bebd8e335 100644
--- a/scene/3d/reflection_probe.cpp
+++ b/scene/3d/reflection_probe.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -76,13 +76,13 @@ float ReflectionProbe::get_max_distance() const {
return max_distance;
}
-void ReflectionProbe::set_lod_threshold(float p_pixels) {
- lod_threshold = p_pixels;
- RS::get_singleton()->reflection_probe_set_lod_threshold(probe, p_pixels);
+void ReflectionProbe::set_mesh_lod_threshold(float p_pixels) {
+ mesh_lod_threshold = p_pixels;
+ RS::get_singleton()->reflection_probe_set_mesh_lod_threshold(probe, p_pixels);
}
-float ReflectionProbe::get_lod_threshold() const {
- return lod_threshold;
+float ReflectionProbe::get_mesh_lod_threshold() const {
+ return mesh_lod_threshold;
}
void ReflectionProbe::set_extents(const Vector3 &p_extents) {
@@ -94,14 +94,14 @@ void ReflectionProbe::set_extents(const Vector3 &p_extents) {
}
if (extents[i] - 0.01 < ABS(origin_offset[i])) {
- origin_offset[i] = SGN(origin_offset[i]) * (extents[i] - 0.01);
+ origin_offset[i] = SIGN(origin_offset[i]) * (extents[i] - 0.01);
}
}
RS::get_singleton()->reflection_probe_set_extents(probe, extents);
RS::get_singleton()->reflection_probe_set_origin_offset(probe, origin_offset);
- update_gizmo();
+ update_gizmos();
}
Vector3 ReflectionProbe::get_extents() const {
@@ -113,13 +113,13 @@ void ReflectionProbe::set_origin_offset(const Vector3 &p_extents) {
for (int i = 0; i < 3; i++) {
if (extents[i] - 0.01 < ABS(origin_offset[i])) {
- origin_offset[i] = SGN(origin_offset[i]) * (extents[i] - 0.01);
+ origin_offset[i] = SIGN(origin_offset[i]) * (extents[i] - 0.01);
}
}
RS::get_singleton()->reflection_probe_set_extents(probe, extents);
RS::get_singleton()->reflection_probe_set_origin_offset(probe, origin_offset);
- update_gizmo();
+ update_gizmos();
}
Vector3 ReflectionProbe::get_origin_offset() const {
@@ -178,16 +178,13 @@ AABB ReflectionProbe::get_aabb() const {
return aabb;
}
-Vector<Face3> ReflectionProbe::get_faces(uint32_t p_usage_flags) const {
- return Vector<Face3>();
-}
-
void ReflectionProbe::_validate_property(PropertyInfo &property) const {
if (property.name == "interior/ambient_color" || property.name == "interior/ambient_color_energy") {
if (ambient_mode != AMBIENT_COLOR) {
- property.usage = PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL;
+ property.usage = PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL;
}
}
+ VisualInstance3D::_validate_property(property);
}
void ReflectionProbe::_bind_methods() {
@@ -206,8 +203,8 @@ void ReflectionProbe::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_max_distance", "max_distance"), &ReflectionProbe::set_max_distance);
ClassDB::bind_method(D_METHOD("get_max_distance"), &ReflectionProbe::get_max_distance);
- ClassDB::bind_method(D_METHOD("set_lod_threshold", "ratio"), &ReflectionProbe::set_lod_threshold);
- ClassDB::bind_method(D_METHOD("get_lod_threshold"), &ReflectionProbe::get_lod_threshold);
+ 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);
@@ -230,19 +227,19 @@ void ReflectionProbe::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_update_mode", "mode"), &ReflectionProbe::set_update_mode);
ClassDB::bind_method(D_METHOD("get_update_mode"), &ReflectionProbe::get_update_mode);
- ADD_PROPERTY(PropertyInfo(Variant::INT, "update_mode", PROPERTY_HINT_ENUM, "Once,Always"), "set_update_mode", "get_update_mode");
+ 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_EXP_RANGE, "0,16384,0.1,or_greater"), "set_max_distance", "get_max_distance");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "max_distance", PROPERTY_HINT_RANGE, "0,16384,0.1,or_greater,exp"), "set_max_distance", "get_max_distance");
ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "extents"), "set_extents", "get_extents");
ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "origin_offset"), "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");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "enable_shadows"), "set_enable_shadows", "are_shadows_enabled");
ADD_PROPERTY(PropertyInfo(Variant::INT, "cull_mask", PROPERTY_HINT_LAYERS_3D_RENDER), "set_cull_mask", "get_cull_mask");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "lod_threshold", PROPERTY_HINT_RANGE, "0,1024,0.1"), "set_lod_threshold", "get_lod_threshold");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "mesh_lod_threshold", PROPERTY_HINT_RANGE, "0,1024,0.1"), "set_mesh_lod_threshold", "get_mesh_lod_threshold");
ADD_GROUP("Ambient", "ambient_");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "ambient_mode", PROPERTY_HINT_ENUM, "Disabled,Environment,ConstantColor"), "set_ambient_mode", "get_ambient_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "ambient_mode", PROPERTY_HINT_ENUM, "Disabled,Environment,Constant Color"), "set_ambient_mode", "get_ambient_mode");
ADD_PROPERTY(PropertyInfo(Variant::COLOR, "ambient_color", PROPERTY_HINT_COLOR_NO_ALPHA), "set_ambient_color", "get_ambient_color");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "ambient_color_energy", PROPERTY_HINT_RANGE, "0,16,0.01"), "set_ambient_color_energy", "get_ambient_color_energy");
diff --git a/scene/3d/reflection_probe.h b/scene/3d/reflection_probe.h
index 15c2da3ae0..424976d895 100644
--- a/scene/3d/reflection_probe.h
+++ b/scene/3d/reflection_probe.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -32,9 +32,6 @@
#define REFLECTIONPROBE_H
#include "scene/3d/visual_instance_3d.h"
-#include "scene/resources/sky.h"
-#include "scene/resources/texture.h"
-#include "servers/rendering_server.h"
class ReflectionProbe : public VisualInstance3D {
GDCLASS(ReflectionProbe, VisualInstance3D);
@@ -55,7 +52,7 @@ private:
RID probe;
float intensity = 1.0;
float max_distance = 0.0;
- Vector3 extents = Vector3(1, 1, 1);
+ Vector3 extents = Vector3(10, 10, 10);
Vector3 origin_offset = Vector3(0, 0, 0);
bool box_projection = false;
bool enable_shadows = false;
@@ -63,7 +60,7 @@ private:
AmbientMode ambient_mode = AMBIENT_ENVIRONMENT;
Color ambient_color = Color(0, 0, 0);
float ambient_color_energy = 1.0;
- float lod_threshold = 1.0;
+ float mesh_lod_threshold = 1.0;
uint32_t cull_mask = (1 << 20) - 1;
UpdateMode update_mode = UPDATE_ONCE;
@@ -91,8 +88,8 @@ public:
void set_max_distance(float p_distance);
float get_max_distance() const;
- void set_lod_threshold(float p_pixels);
- float get_lod_threshold() const;
+ 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;
@@ -116,7 +113,6 @@ public:
UpdateMode get_update_mode() const;
virtual AABB get_aabb() const override;
- virtual Vector<Face3> get_faces(uint32_t p_usage_flags) const override;
ReflectionProbe();
~ReflectionProbe();
diff --git a/scene/3d/remote_transform_3d.cpp b/scene/3d/remote_transform_3d.cpp
index 29a407905b..9979052385 100644
--- a/scene/3d/remote_transform_3d.cpp
+++ b/scene/3d/remote_transform_3d.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -34,7 +34,7 @@ void RemoteTransform3D::_update_cache() {
cache = ObjectID();
if (has_node(remote_node)) {
Node *node = get_node(remote_node);
- if (!node || this == node || node->is_a_parent_of(this) || this->is_a_parent_of(node)) {
+ if (!node || this == node || node->is_ancestor_of(this) || this->is_ancestor_of(node)) {
return;
}
@@ -65,10 +65,10 @@ void RemoteTransform3D::_update_remote() {
if (update_remote_position && update_remote_rotation && update_remote_scale) {
n->set_global_transform(get_global_transform());
} else {
- Transform our_trans = get_global_transform();
+ Transform3D our_trans = get_global_transform();
if (update_remote_rotation) {
- n->set_rotation(our_trans.basis.get_rotation());
+ n->set_rotation(our_trans.basis.get_euler_normalized(Basis::EulerOrder(n->get_rotation_order())));
}
if (update_remote_scale) {
@@ -76,7 +76,7 @@ void RemoteTransform3D::_update_remote() {
}
if (update_remote_position) {
- Transform n_trans = n->get_global_transform();
+ Transform3D n_trans = n->get_global_transform();
n_trans.set_origin(our_trans.get_origin());
n->set_global_transform(n_trans);
@@ -87,10 +87,10 @@ void RemoteTransform3D::_update_remote() {
if (update_remote_position && update_remote_rotation && update_remote_scale) {
n->set_transform(get_transform());
} else {
- Transform our_trans = get_transform();
+ Transform3D our_trans = get_transform();
if (update_remote_rotation) {
- n->set_rotation(our_trans.basis.get_rotation());
+ n->set_rotation(our_trans.basis.get_euler_normalized(Basis::EulerOrder(n->get_rotation_order())));
}
if (update_remote_scale) {
@@ -98,7 +98,7 @@ void RemoteTransform3D::_update_remote() {
}
if (update_remote_position) {
- Transform n_trans = n->get_transform();
+ Transform3D n_trans = n->get_transform();
n_trans.set_origin(our_trans.get_origin());
n->set_transform(n_trans);
@@ -111,8 +111,8 @@ void RemoteTransform3D::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
_update_cache();
-
} break;
+
case NOTIFICATION_TRANSFORM_CHANGED: {
if (!is_inside_tree()) {
break;
@@ -121,7 +121,6 @@ void RemoteTransform3D::_notification(int p_what) {
if (cache.is_valid()) {
_update_remote();
}
-
} break;
}
}
@@ -183,7 +182,7 @@ TypedArray<String> RemoteTransform3D::get_configuration_warnings() const {
TypedArray<String> warnings = Node::get_configuration_warnings();
if (!has_node(remote_node) || !Object::cast_to<Node3D>(get_node(remote_node))) {
- warnings.push_back(TTR("The \"Remote Path\" property must point to a valid Node3D or Node3D-derived node to work."));
+ warnings.push_back(RTR("The \"Remote Path\" property must point to a valid Node3D or Node3D-derived node to work."));
}
return warnings;
diff --git a/scene/3d/remote_transform_3d.h b/scene/3d/remote_transform_3d.h
index 321bd3b51e..03bb253578 100644
--- a/scene/3d/remote_transform_3d.h
+++ b/scene/3d/remote_transform_3d.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
diff --git a/scene/3d/skeleton_3d.cpp b/scene/3d/skeleton_3d.cpp
index 59233708f6..9e403a6ecd 100644
--- a/scene/3d/skeleton_3d.cpp
+++ b/scene/3d/skeleton_3d.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -30,11 +30,10 @@
#include "skeleton_3d.h"
-#include "core/config/engine.h"
-#include "core/config/project_settings.h"
#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"
@@ -72,6 +71,13 @@ 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;
}
@@ -92,22 +98,12 @@ bool Skeleton3D::_set(const StringName &p_path, const Variant &p_value) {
set_bone_rest(which, p_value);
} else if (what == "enabled") {
set_bone_enabled(which, p_value);
- } else if (what == "pose") {
- set_bone_pose(which, p_value);
- } else if (what == "bound_children") {
- Array children = p_value;
-
- if (is_inside_tree()) {
- bones.write[which].nodes_bound.clear();
-
- for (int i = 0; i < children.size(); i++) {
- NodePath npath = children[i];
- ERR_CONTINUE(npath.operator String() == "");
- Node *node = get_node(npath);
- ERR_CONTINUE(!node);
- bind_child_node_to_bone(which, node);
- }
- }
+ } else if (what == "position") {
+ set_bone_pose_position(which, p_value);
+ } else if (what == "rotation") {
+ set_bone_pose_rotation(which, p_value);
+ } else if (what == "scale") {
+ set_bone_pose_scale(which, p_value);
} else {
return false;
}
@@ -118,6 +114,13 @@ 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;
}
@@ -135,21 +138,12 @@ bool Skeleton3D::_get(const StringName &p_path, Variant &r_ret) const {
r_ret = get_bone_rest(which);
} else if (what == "enabled") {
r_ret = is_bone_enabled(which);
- } else if (what == "pose") {
- r_ret = get_bone_pose(which);
- } else if (what == "bound_children") {
- Array children;
-
- for (const List<ObjectID>::Element *E = bones[which].nodes_bound.front(); E; E = E->next()) {
- Object *obj = ObjectDB::get_instance(E->get());
- ERR_CONTINUE(!obj);
- Node *node = Object::cast_to<Node>(obj);
- ERR_CONTINUE(!node);
- NodePath npath = get_path_to(node);
- children.push_back(npath);
- }
-
- r_ret = children;
+ } else if (what == "position") {
+ r_ret = get_bone_pose_position(which);
+ } else if (what == "rotation") {
+ r_ret = get_bone_pose_rotation(which);
+ } else if (what == "scale") {
+ r_ret = get_bone_pose_scale(which);
} else {
return false;
}
@@ -160,13 +154,61 @@ bool Skeleton3D::_get(const StringName &p_path, Variant &r_ret) const {
void Skeleton3D::_get_property_list(List<PropertyInfo> *p_list) const {
for (int i = 0; i < bones.size(); i++) {
String prep = "bones/" + itos(i) + "/";
- p_list->push_back(PropertyInfo(Variant::STRING, prep + "name", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR));
- p_list->push_back(PropertyInfo(Variant::INT, prep + "parent", PROPERTY_HINT_RANGE, "-1," + itos(bones.size() - 1) + ",1", PROPERTY_USAGE_NOEDITOR));
- p_list->push_back(PropertyInfo(Variant::TRANSFORM, prep + "rest", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR));
- p_list->push_back(PropertyInfo(Variant::BOOL, prep + "enabled", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR));
- p_list->push_back(PropertyInfo(Variant::TRANSFORM, prep + "pose", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR));
- p_list->push_back(PropertyInfo(Variant::ARRAY, prep + "bound_children", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR));
+ p_list->push_back(PropertyInfo(Variant::STRING, prep + "name", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR));
+ p_list->push_back(PropertyInfo(Variant::INT, prep + "parent", PROPERTY_HINT_RANGE, "-1," + itos(bones.size() - 1) + ",1", PROPERTY_USAGE_NO_EDITOR));
+ p_list->push_back(PropertyInfo(Variant::TRANSFORM3D, prep + "rest", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR));
+ p_list->push_back(PropertyInfo(Variant::BOOL, prep + "enabled", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR));
+ p_list->push_back(PropertyInfo(Variant::VECTOR3, prep + "position", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR));
+ p_list->push_back(PropertyInfo(Variant::QUATERNION, prep + "rotation", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR));
+ p_list->push_back(PropertyInfo(Variant::VECTOR3, prep + "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);
+ }
+}
+
+void Skeleton3D::_validate_property(PropertyInfo &property) const {
+ PackedStringArray split = property.name.split("/");
+ if (split.size() == 3 && split[0] == "bones") {
+ if (split[2] == "rest") {
+ property.usage |= PROPERTY_USAGE_READ_ONLY;
+ }
+ if (is_show_rest_only()) {
+ if (split[2] == "enabled") {
+ property.usage |= PROPERTY_USAGE_READ_ONLY;
+ }
+ if (split[2] == "position") {
+ property.usage |= PROPERTY_USAGE_READ_ONLY;
+ }
+ if (split[2] == "rotation") {
+ property.usage |= PROPERTY_USAGE_READ_ONLY;
+ }
+ if (split[2] == "scale") {
+ property.usage |= PROPERTY_USAGE_READ_ONLY;
+ }
+ } else if (!is_bone_enabled(split[1].to_int())) {
+ if (split[2] == "position") {
+ property.usage |= PROPERTY_USAGE_READ_ONLY;
+ }
+ if (split[2] == "rotation") {
+ property.usage |= PROPERTY_USAGE_READ_ONLY;
+ }
+ if (split[2] == "scale") {
+ property.usage |= PROPERTY_USAGE_READ_ONLY;
+ }
+ }
}
+
+ Node3D::_validate_property(property);
}
void Skeleton3D::_update_process_order() {
@@ -177,47 +219,32 @@ void Skeleton3D::_update_process_order() {
Bone *bonesptr = bones.ptrw();
int len = bones.size();
- process_order.resize(len);
- int *order = process_order.ptrw();
+ parentless_bones.clear();
+
+ for (int i = 0; i < len; i++) {
+ bonesptr[i].child_bones.clear();
+ }
+
for (int i = 0; i < len; i++) {
if (bonesptr[i].parent >= len) {
- //validate this just in case
+ // Validate this just in case.
ERR_PRINT("Bone " + itos(i) + " has invalid parent: " + itos(bonesptr[i].parent));
bonesptr[i].parent = -1;
}
- order[i] = i;
- bonesptr[i].sort_index = i;
- }
- //now check process order
- int pass_count = 0;
- while (pass_count < len * len) {
- //using bubblesort because of simplicity, it won't run every frame though.
- //bublesort worst case is O(n^2), and this may be an infinite loop if cyclic
- bool swapped = false;
- for (int i = 0; i < len; i++) {
- int parent_idx = bonesptr[order[i]].parent;
- if (parent_idx < 0) {
- continue; //do nothing because it has no parent
- }
- //swap indices
- int parent_order = bonesptr[parent_idx].sort_index;
- if (parent_order > i) {
- bonesptr[order[i]].sort_index = parent_order;
- bonesptr[parent_idx].sort_index = i;
- //swap order
- SWAP(order[i], order[parent_order]);
- swapped = true;
- }
- }
- if (!swapped) {
- break;
- }
- pass_count++;
- }
+ if (bonesptr[i].parent != -1) {
+ int parent_bone_idx = bonesptr[i].parent;
- if (pass_count == len * len) {
- ERR_PRINT("Skeleton3D parenthood graph is cyclic");
+ // Check to see if this node is already added to the parent.
+ if (bonesptr[parent_bone_idx].child_bones.find(i) < 0) {
+ // Add the child node.
+ bonesptr[parent_bone_idx].child_bones.push_back(i);
+ } else {
+ ERR_PRINT("Skeleton3D parenthood graph is cyclic");
+ }
+ } else {
+ parentless_bones.push_back(i);
+ }
}
process_order_dirty = false;
@@ -228,80 +255,14 @@ void Skeleton3D::_notification(int p_what) {
case NOTIFICATION_UPDATE_SKELETON: {
RenderingServer *rs = RenderingServer::get_singleton();
Bone *bonesptr = bones.ptrw();
- int len = bones.size();
-
- _update_process_order();
-
- const int *order = process_order.ptr();
-
- for (int i = 0; i < len; i++) {
- Bone &b = bonesptr[order[i]];
-
- if (b.disable_rest) {
- if (b.enabled) {
- Transform pose = b.pose;
- if (b.custom_pose_enable) {
- pose = b.custom_pose * pose;
- }
- if (b.parent >= 0) {
- b.pose_global = bonesptr[b.parent].pose_global * pose;
- b.pose_global_no_override = bonesptr[b.parent].pose_global * pose;
- } else {
- b.pose_global = pose;
- b.pose_global_no_override = pose;
- }
- } else {
- if (b.parent >= 0) {
- b.pose_global = bonesptr[b.parent].pose_global;
- b.pose_global_no_override = bonesptr[b.parent].pose_global;
- } else {
- b.pose_global = Transform();
- b.pose_global_no_override = Transform();
- }
- }
-
- } else {
- if (b.enabled) {
- Transform pose = b.pose;
- if (b.custom_pose_enable) {
- pose = b.custom_pose * pose;
- }
- if (b.parent >= 0) {
- b.pose_global = bonesptr[b.parent].pose_global * (b.rest * pose);
- b.pose_global_no_override = bonesptr[b.parent].pose_global * (b.rest * pose);
- } else {
- b.pose_global = b.rest * pose;
- b.pose_global_no_override = b.rest * pose;
- }
- } else {
- if (b.parent >= 0) {
- b.pose_global = bonesptr[b.parent].pose_global * b.rest;
- b.pose_global_no_override = bonesptr[b.parent].pose_global * b.rest;
- } else {
- b.pose_global = b.rest;
- b.pose_global_no_override = b.rest;
- }
- }
- }
-
- 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.global_pose_override_reset) {
- b.global_pose_override_amount = 0.0;
- }
+ int len = bones.size();
+ dirty = false;
- for (List<ObjectID>::Element *E = b.nodes_bound.front(); E; E = E->next()) {
- Object *obj = ObjectDB::get_instance(E->get());
- ERR_CONTINUE(!obj);
- Node3D *node_3d = Object::cast_to<Node3D>(obj);
- ERR_CONTINUE(!node_3d);
- node_3d->set_transform(b.pose_global);
- }
- }
+ // Update bone transforms.
+ force_update_all_bone_transforms();
- //update skins
+ // Update skins.
for (Set<SkinReference *>::Element *E = skin_bindings.front(); E; E = E->next()) {
const Skin *skin = E->get()->skin.operator->();
RID skeleton = E->get()->skeleton;
@@ -319,7 +280,7 @@ void Skeleton3D::_notification(int p_what) {
StringName bind_name = skin->get_bind_name(i);
if (bind_name != StringName()) {
- //bind name used, use this
+ // Bind name used, use this.
bool found = false;
for (int j = 0; j < len; j++) {
if (bonesptr[j].name == bind_name) {
@@ -356,35 +317,47 @@ void Skeleton3D::_notification(int p_what) {
rs->skeleton_bone_set_transform(skeleton, i, bonesptr[bone_index].pose_global * skin->get_bind_pose(i));
}
}
-
- dirty = false;
-
#ifdef TOOLS_ENABLED
emit_signal(SceneStringNames::get_singleton()->pose_updated);
#endif // TOOLS_ENABLED
-
} break;
#ifndef _3D_DISABLED
case NOTIFICATION_INTERNAL_PHYSICS_PROCESS: {
// This is active only if the skeleton animates the physical bones
// and the state of the bone is not active.
- if (animate_physical_bones) {
- for (int i = 0; i < bones.size(); i += 1) {
- if (bones[i].physical_bone) {
- if (bones[i].physical_bone->is_simulating_physics() == false) {
- bones[i].physical_bone->reset_to_rest_position();
+ if (Engine::get_singleton()->is_editor_hint()) {
+ if (animate_physical_bones) {
+ for (int i = 0; i < bones.size(); i += 1) {
+ if (bones[i].physical_bone) {
+ if (bones[i].physical_bone->is_simulating_physics() == false) {
+ bones[i].physical_bone->reset_to_rest_position();
+ }
}
}
}
}
+
+ 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: {
- if (Engine::get_singleton()->is_editor_hint()) {
- set_physics_process_internal(true);
+ set_physics_process_internal(true);
+ set_process_internal(true);
+
+ if (modification_stack.is_valid()) {
+ set_modification_stack(modification_stack);
}
} break;
-#endif
+#endif // _3D_DISABLED
}
}
@@ -396,33 +369,136 @@ void Skeleton3D::clear_bones_global_pose_override() {
_make_dirty();
}
-void Skeleton3D::set_bone_global_pose_override(int p_bone, const Transform &p_pose, float p_amount, bool p_persistent) {
- ERR_FAIL_INDEX(p_bone, bones.size());
+void Skeleton3D::set_bone_global_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].global_pose_override_amount = p_amount;
bones.write[p_bone].global_pose_override = p_pose;
bones.write[p_bone].global_pose_override_reset = !p_persistent;
_make_dirty();
}
-Transform Skeleton3D::get_bone_global_pose(int p_bone) const {
- ERR_FAIL_INDEX_V(p_bone, bones.size(), Transform());
+Transform3D Skeleton3D::get_bone_global_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].global_pose_override;
+}
+
+Transform3D Skeleton3D::get_bone_global_pose(int p_bone) const {
+ const int bone_size = bones.size();
+ ERR_FAIL_INDEX_V(p_bone, bone_size, Transform3D());
if (dirty) {
const_cast<Skeleton3D *>(this)->notification(NOTIFICATION_UPDATE_SKELETON);
}
return bones[p_bone].pose_global;
}
-Transform Skeleton3D::get_bone_global_pose_no_override(int p_bone) const {
- ERR_FAIL_INDEX_V(p_bone, bones.size(), Transform());
+Transform3D Skeleton3D::get_bone_global_pose_no_override(int p_bone) const {
+ const int bone_size = bones.size();
+ ERR_FAIL_INDEX_V(p_bone, bone_size, Transform3D());
if (dirty) {
const_cast<Skeleton3D *>(this)->notification(NOTIFICATION_UPDATE_SKELETON);
}
return bones[p_bone].pose_global_no_override;
}
-// skeleton creation api
+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;
+}
+
+// Skeleton creation api
+
void Skeleton3D::add_bone(const String &p_name) {
- ERR_FAIL_COND(p_name == "" || p_name.find(":") != -1 || p_name.find("/") != -1);
+ ERR_FAIL_COND(p_name.is_empty() || p_name.contains(":") || p_name.contains("/"));
for (int i = 0; i < bones.size(); i++) {
ERR_FAIL_COND(bones[i].name == p_name);
@@ -433,8 +509,9 @@ void Skeleton3D::add_bone(const String &p_name) {
bones.push_back(b);
process_order_dirty = true;
version++;
+ rest_dirty = true;
_make_dirty();
- update_gizmo();
+ update_gizmos();
}
int Skeleton3D::find_bone(const String &p_name) const {
@@ -448,14 +525,15 @@ int Skeleton3D::find_bone(const String &p_name) const {
}
String Skeleton3D::get_bone_name(int p_bone) const {
- ERR_FAIL_INDEX_V(p_bone, bones.size(), "");
-
+ const int bone_size = bones.size();
+ ERR_FAIL_INDEX_V(p_bone, bone_size, "");
return bones[p_bone].name;
}
void Skeleton3D::set_bone_name(int p_bone, const String &p_name) {
- ERR_FAIL_INDEX(p_bone, bones.size());
+ const int bone_size = bones.size();
+ ERR_FAIL_INDEX(p_bone, bone_size);
- for (int i = 0; i < bones.size(); i++) {
+ for (int i = 0; i < bone_size; i++) {
if (i != p_bone) {
ERR_FAIL_COND(bones[i].name == p_name);
}
@@ -483,16 +561,20 @@ int Skeleton3D::get_bone_count() const {
}
void Skeleton3D::set_bone_parent(int p_bone, int p_parent) {
- ERR_FAIL_INDEX(p_bone, bones.size());
+ const int bone_size = bones.size();
+ ERR_FAIL_INDEX(p_bone, bone_size);
ERR_FAIL_COND(p_parent != -1 && (p_parent < 0));
+ ERR_FAIL_COND(p_bone == p_parent);
bones.write[p_bone].parent = p_parent;
process_order_dirty = true;
+ rest_dirty = true;
_make_dirty();
}
void Skeleton3D::unparent_bone_and_rest(int p_bone) {
- ERR_FAIL_INDEX(p_bone, bones.size());
+ const int bone_size = bones.size();
+ ERR_FAIL_INDEX(p_bone, bone_size);
_update_process_order();
@@ -505,81 +587,109 @@ void Skeleton3D::unparent_bone_and_rest(int p_bone) {
bones.write[p_bone].parent = -1;
process_order_dirty = true;
+ rest_dirty = true;
_make_dirty();
}
-void Skeleton3D::set_bone_disable_rest(int p_bone, bool p_disable) {
- ERR_FAIL_INDEX(p_bone, bones.size());
- bones.write[p_bone].disable_rest = p_disable;
-}
-
-bool Skeleton3D::is_bone_rest_disabled(int p_bone) const {
- ERR_FAIL_INDEX_V(p_bone, bones.size(), false);
- return bones[p_bone].disable_rest;
-}
-
int Skeleton3D::get_bone_parent(int p_bone) const {
- ERR_FAIL_INDEX_V(p_bone, bones.size(), -1);
+ const int bone_size = bones.size();
+ ERR_FAIL_INDEX_V(p_bone, bone_size, -1);
return bones[p_bone].parent;
}
-void Skeleton3D::set_bone_rest(int p_bone, const Transform &p_rest) {
- ERR_FAIL_INDEX(p_bone, bones.size());
+Vector<int> Skeleton3D::get_bone_children(int p_bone) {
+ const int bone_size = bones.size();
+ ERR_FAIL_INDEX_V(p_bone, bone_size, Vector<int>());
+ return bones[p_bone].child_bones;
+}
- bones.write[p_bone].rest = p_rest;
+void Skeleton3D::set_bone_children(int p_bone, Vector<int> p_children) {
+ const int bone_size = bones.size();
+ ERR_FAIL_INDEX(p_bone, bone_size);
+ bones.write[p_bone].child_bones = p_children;
+
+ process_order_dirty = true;
+ rest_dirty = true;
_make_dirty();
}
-Transform Skeleton3D::get_bone_rest(int p_bone) const {
- ERR_FAIL_INDEX_V(p_bone, bones.size(), Transform());
+void Skeleton3D::add_bone_child(int p_bone, int p_child) {
+ const int bone_size = bones.size();
+ ERR_FAIL_INDEX(p_bone, bone_size);
+ bones.write[p_bone].child_bones.push_back(p_child);
- return bones[p_bone].rest;
+ process_order_dirty = true;
+ rest_dirty = true;
+ _make_dirty();
}
-void Skeleton3D::set_bone_enabled(int p_bone, bool p_enabled) {
- ERR_FAIL_INDEX(p_bone, bones.size());
+void Skeleton3D::remove_bone_child(int p_bone, int p_child) {
+ const int bone_size = bones.size();
+ ERR_FAIL_INDEX(p_bone, bone_size);
- bones.write[p_bone].enabled = p_enabled;
+ int child_idx = bones[p_bone].child_bones.find(p_child);
+ if (child_idx >= 0) {
+ bones.write[p_bone].child_bones.remove_at(child_idx);
+ } else {
+ WARN_PRINT("Cannot remove child bone: Child bone not found.");
+ }
+
+ process_order_dirty = true;
+ rest_dirty = true;
_make_dirty();
}
-bool Skeleton3D::is_bone_enabled(int p_bone) const {
- ERR_FAIL_INDEX_V(p_bone, bones.size(), false);
- return bones[p_bone].enabled;
+Vector<int> Skeleton3D::get_parentless_bones() {
+ return parentless_bones;
}
-void Skeleton3D::bind_child_node_to_bone(int p_bone, Node *p_node) {
- ERR_FAIL_NULL(p_node);
- ERR_FAIL_INDEX(p_bone, bones.size());
+void Skeleton3D::set_bone_rest(int p_bone, const Transform3D &p_rest) {
+ const int bone_size = bones.size();
+ ERR_FAIL_INDEX(p_bone, bone_size);
- ObjectID id = p_node->get_instance_id();
+ bones.write[p_bone].rest = p_rest;
+ rest_dirty = true;
+ _make_dirty();
+}
+Transform3D Skeleton3D::get_bone_rest(int p_bone) const {
+ const int bone_size = bones.size();
+ ERR_FAIL_INDEX_V(p_bone, bone_size, Transform3D());
- for (const List<ObjectID>::Element *E = bones[p_bone].nodes_bound.front(); E; E = E->next()) {
- if (E->get() == id) {
- return; // already here
- }
+ return bones[p_bone].rest;
+}
+Transform3D Skeleton3D::get_bone_global_rest(int p_bone) const {
+ const int bone_size = bones.size();
+ ERR_FAIL_INDEX_V(p_bone, bone_size, Transform3D());
+ if (rest_dirty) {
+ const_cast<Skeleton3D *>(this)->notification(NOTIFICATION_UPDATE_SKELETON);
}
-
- bones.write[p_bone].nodes_bound.push_back(id);
+ return bones[p_bone].global_rest;
}
-void Skeleton3D::unbind_child_node_from_bone(int p_bone, Node *p_node) {
- ERR_FAIL_NULL(p_node);
- ERR_FAIL_INDEX(p_bone, bones.size());
+void Skeleton3D::set_bone_enabled(int p_bone, bool p_enabled) {
+ const int bone_size = bones.size();
+ ERR_FAIL_INDEX(p_bone, bone_size);
+
+ bones.write[p_bone].enabled = p_enabled;
+ emit_signal(SceneStringNames::get_singleton()->bone_enabled_changed, p_bone);
+ _make_dirty();
+}
- ObjectID id = p_node->get_instance_id();
- bones.write[p_bone].nodes_bound.erase(id);
+bool Skeleton3D::is_bone_enabled(int p_bone) const {
+ const int bone_size = bones.size();
+ ERR_FAIL_INDEX_V(p_bone, bone_size, false);
+ return bones[p_bone].enabled;
}
-void Skeleton3D::get_bound_child_nodes_to_bone(int p_bone, List<Node *> *p_bound) const {
- ERR_FAIL_INDEX(p_bone, bones.size());
+void Skeleton3D::set_show_rest_only(bool p_enabled) {
+ show_rest_only = p_enabled;
+ emit_signal(SceneStringNames::get_singleton()->show_rest_only_changed);
+ _make_dirty();
+}
- for (const List<ObjectID>::Element *E = bones[p_bone].nodes_bound.front(); E; E = E->next()) {
- Object *obj = ObjectDB::get_instance(E->get());
- ERR_CONTINUE(!obj);
- p_bound->push_back(Object::cast_to<Node>(obj));
- }
+bool Skeleton3D::is_show_rest_only() const {
+ return show_rest_only;
}
void Skeleton3D::clear_bones() {
@@ -589,35 +699,62 @@ void Skeleton3D::clear_bones() {
_make_dirty();
}
-// posing api
+// Posing api
+
+void Skeleton3D::set_bone_pose_position(int p_bone, const Vector3 &p_position) {
+ const int bone_size = bones.size();
+ ERR_FAIL_INDEX(p_bone, bone_size);
-void Skeleton3D::set_bone_pose(int p_bone, const Transform &p_pose) {
- ERR_FAIL_INDEX(p_bone, bones.size());
+ bones.write[p_bone].pose_position = p_position;
+ bones.write[p_bone].pose_cache_dirty = true;
+ if (is_inside_tree()) {
+ _make_dirty();
+ }
+}
+void Skeleton3D::set_bone_pose_rotation(int p_bone, const Quaternion &p_rotation) {
+ const int bone_size = bones.size();
+ ERR_FAIL_INDEX(p_bone, bone_size);
- bones.write[p_bone].pose = p_pose;
+ bones.write[p_bone].pose_rotation = p_rotation;
+ bones.write[p_bone].pose_cache_dirty = true;
if (is_inside_tree()) {
_make_dirty();
}
}
+void Skeleton3D::set_bone_pose_scale(int p_bone, const Vector3 &p_scale) {
+ const int bone_size = bones.size();
+ ERR_FAIL_INDEX(p_bone, bone_size);
-Transform Skeleton3D::get_bone_pose(int p_bone) const {
- ERR_FAIL_INDEX_V(p_bone, bones.size(), Transform());
- return bones[p_bone].pose;
+ bones.write[p_bone].pose_scale = p_scale;
+ bones.write[p_bone].pose_cache_dirty = true;
+ if (is_inside_tree()) {
+ _make_dirty();
+ }
}
-void Skeleton3D::set_bone_custom_pose(int p_bone, const Transform &p_custom_pose) {
- ERR_FAIL_INDEX(p_bone, bones.size());
- //ERR_FAIL_COND( !is_inside_scene() );
+Vector3 Skeleton3D::get_bone_pose_position(int p_bone) const {
+ const int bone_size = bones.size();
+ ERR_FAIL_INDEX_V(p_bone, bone_size, Vector3());
+ return bones[p_bone].pose_position;
+}
- bones.write[p_bone].custom_pose_enable = (p_custom_pose != Transform());
- bones.write[p_bone].custom_pose = p_custom_pose;
+Quaternion Skeleton3D::get_bone_pose_rotation(int p_bone) const {
+ const int bone_size = bones.size();
+ ERR_FAIL_INDEX_V(p_bone, bone_size, Quaternion());
+ return bones[p_bone].pose_rotation;
+}
- _make_dirty();
+Vector3 Skeleton3D::get_bone_pose_scale(int p_bone) const {
+ const int bone_size = bones.size();
+ ERR_FAIL_INDEX_V(p_bone, bone_size, Vector3());
+ return bones[p_bone].pose_scale;
}
-Transform Skeleton3D::get_bone_custom_pose(int p_bone) const {
- ERR_FAIL_INDEX_V(p_bone, bones.size(), Transform());
- return bones[p_bone].custom_pose;
+Transform3D Skeleton3D::get_bone_pose(int p_bone) const {
+ const int bone_size = bones.size();
+ ERR_FAIL_INDEX_V(p_bone, bone_size, Transform3D());
+ ((Skeleton3D *)this)->bones.write[p_bone].update_pose_cache();
+ return bones[p_bone].pose_cache;
}
void Skeleton3D::_make_dirty() {
@@ -629,32 +766,28 @@ void Skeleton3D::_make_dirty() {
dirty = true;
}
-int Skeleton3D::get_process_order(int p_idx) {
- ERR_FAIL_INDEX_V(p_idx, bones.size(), -1);
+void Skeleton3D::localize_rests() {
_update_process_order();
- return process_order[p_idx];
-}
-Vector<int> Skeleton3D::get_bone_process_orders() {
- _update_process_order();
- return process_order;
-}
+ Vector<int> bones_to_process = get_parentless_bones();
+ while (bones_to_process.size() > 0) {
+ int current_bone_idx = bones_to_process[0];
+ bones_to_process.erase(current_bone_idx);
-void Skeleton3D::localize_rests() {
- _update_process_order();
+ if (bones[current_bone_idx].parent >= 0) {
+ set_bone_rest(current_bone_idx, bones[bones[current_bone_idx].parent].rest.affine_inverse() * bones[current_bone_idx].rest);
+ }
- for (int i = bones.size() - 1; i >= 0; i--) {
- int idx = process_order[i];
- if (bones[idx].parent >= 0) {
- set_bone_rest(idx, bones[bones[idx].parent].rest.affine_inverse() * bones[idx].rest);
+ // Add the bone's children to the list of bones to be processed.
+ int child_bone_size = bones[current_bone_idx].child_bones.size();
+ for (int i = 0; i < child_bone_size; i++) {
+ bones_to_process.push_back(bones[current_bone_idx].child_bones[i]);
}
}
}
-#ifndef _3D_DISABLED
-
-void Skeleton3D::set_animate_physical_bones(bool p_animate) {
- animate_physical_bones = p_animate;
+void Skeleton3D::set_animate_physical_bones(bool p_enabled) {
+ animate_physical_bones = p_enabled;
if (Engine::get_singleton()->is_editor_hint() == false) {
bool sim = false;
@@ -666,7 +799,7 @@ void Skeleton3D::set_animate_physical_bones(bool p_animate) {
}
}
}
- set_physics_process_internal(sim == false && p_animate);
+ set_physics_process_internal(sim == false && p_enabled);
}
}
@@ -675,7 +808,8 @@ bool Skeleton3D::get_animate_physical_bones() const {
}
void Skeleton3D::bind_physical_bone_to_bone(int p_bone, PhysicalBone3D *p_physical_bone) {
- ERR_FAIL_INDEX(p_bone, bones.size());
+ const int bone_size = bones.size();
+ ERR_FAIL_INDEX(p_bone, bone_size);
ERR_FAIL_COND(bones[p_bone].physical_bone);
ERR_FAIL_COND(!p_physical_bone);
bones.write[p_bone].physical_bone = p_physical_bone;
@@ -684,20 +818,23 @@ void Skeleton3D::bind_physical_bone_to_bone(int p_bone, PhysicalBone3D *p_physic
}
void Skeleton3D::unbind_physical_bone_from_bone(int p_bone) {
- ERR_FAIL_INDEX(p_bone, bones.size());
+ const int bone_size = bones.size();
+ ERR_FAIL_INDEX(p_bone, bone_size);
bones.write[p_bone].physical_bone = nullptr;
_rebuild_physical_bones_cache();
}
PhysicalBone3D *Skeleton3D::get_physical_bone(int p_bone) {
- ERR_FAIL_INDEX_V(p_bone, bones.size(), nullptr);
+ const int bone_size = bones.size();
+ ERR_FAIL_INDEX_V(p_bone, bone_size, nullptr);
return bones[p_bone].physical_bone;
}
PhysicalBone3D *Skeleton3D::get_physical_bone_parent(int p_bone) {
- ERR_FAIL_INDEX_V(p_bone, bones.size(), nullptr);
+ const int bone_size = bones.size();
+ ERR_FAIL_INDEX_V(p_bone, bone_size, nullptr);
if (bones[p_bone].cache_parent_physical_bone) {
return bones[p_bone].cache_parent_physical_bone;
@@ -707,7 +844,8 @@ PhysicalBone3D *Skeleton3D::get_physical_bone_parent(int p_bone) {
}
PhysicalBone3D *Skeleton3D::_get_physical_bone_parent(int p_bone) {
- ERR_FAIL_INDEX_V(p_bone, bones.size(), nullptr);
+ const int bone_size = bones.size();
+ ERR_FAIL_INDEX_V(p_bone, bone_size, nullptr);
const int parent_bone = bones[p_bone].parent;
if (0 > parent_bone) {
@@ -726,7 +864,7 @@ void Skeleton3D::_rebuild_physical_bones_cache() {
const int b_size = bones.size();
for (int i = 0; i < b_size; ++i) {
PhysicalBone3D *parent_pb = _get_physical_bone_parent(i);
- if (parent_pb != bones[i].physical_bone) {
+ if (parent_pb != bones[i].cache_parent_physical_bone) {
bones.write[i].cache_parent_physical_bone = parent_pb;
if (bones[i].physical_bone) {
bones[i].physical_bone->_on_bone_parent_changed();
@@ -774,7 +912,7 @@ void Skeleton3D::physical_bones_start_simulation_on(const TypedArray<StringName>
Vector<int> sim_bones;
if (p_bones.size() <= 0) {
- sim_bones.push_back(0); // if no bones is specified, activate ragdoll on full body
+ sim_bones.push_back(0); // If no bones is specified, activate ragdoll on full body.
} else {
sim_bones.resize(p_bones.size());
int c = 0;
@@ -813,83 +951,259 @@ void Skeleton3D::physical_bones_remove_collision_exception(RID p_exception) {
_physical_bones_add_remove_collision_exception(false, this, p_exception);
}
-#endif // _3D_DISABLED
-
void Skeleton3D::_skin_changed() {
_make_dirty();
}
+Ref<Skin> Skeleton3D::create_skin_from_rest_transforms() {
+ Ref<Skin> skin;
+
+ skin.instantiate();
+ skin->set_bind_count(bones.size());
+ _update_process_order(); // Just in case.
+
+ // Pose changed, rebuild cache of inverses.
+ const Bone *bonesptr = bones.ptr();
+ int len = bones.size();
+
+ // Calculate global rests and invert them.
+ LocalVector<int> bones_to_process;
+ bones_to_process = get_parentless_bones();
+ while (bones_to_process.size() > 0) {
+ int current_bone_idx = bones_to_process[0];
+ const Bone &b = bonesptr[current_bone_idx];
+ bones_to_process.erase(current_bone_idx);
+ LocalVector<int> child_bones_vector;
+ child_bones_vector = get_bone_children(current_bone_idx);
+ int child_bones_size = child_bones_vector.size();
+ if (b.parent < 0) {
+ skin->set_bind_pose(current_bone_idx, b.rest);
+ }
+ for (int i = 0; i < child_bones_size; i++) {
+ int child_bone_idx = child_bones_vector[i];
+ const Bone &cb = bonesptr[child_bone_idx];
+ skin->set_bind_pose(child_bone_idx, skin->get_bind_pose(current_bone_idx) * cb.rest);
+ // Add the bone's children to the list of bones to be processed.
+ bones_to_process.push_back(child_bones_vector[i]);
+ }
+ }
+
+ for (int i = 0; i < len; i++) {
+ // The inverse is what is actually required.
+ skin->set_bind_bone(i, i);
+ skin->set_bind_pose(i, skin->get_bind_pose(i).affine_inverse());
+ }
+
+ return skin;
+}
+
Ref<SkinReference> Skeleton3D::register_skin(const Ref<Skin> &p_skin) {
+ ERR_FAIL_COND_V(p_skin.is_null(), Ref<SkinReference>());
+
for (Set<SkinReference *>::Element *E = skin_bindings.front(); E; E = E->next()) {
if (E->get()->skin == p_skin) {
return Ref<SkinReference>(E->get());
}
}
- Ref<Skin> skin = p_skin;
+ Ref<SkinReference> skin_ref;
+ skin_ref.instantiate();
+
+ skin_ref->skeleton_node = this;
+ skin_ref->bind_count = 0;
+ skin_ref->skeleton = RenderingServer::get_singleton()->skeleton_create();
+ skin_ref->skeleton_node = this;
+ skin_ref->skin = p_skin;
+
+ skin_bindings.insert(skin_ref.operator->());
+
+ skin_ref->skin->connect("changed", Callable(skin_ref.operator->(), "_skin_changed"));
- if (skin.is_null()) {
- //need to create one from existing code, this is for compatibility only
- //when skeletons did not support skins. It is also used by gizmo
- //to display the skeleton.
+ _make_dirty(); // Skin needs to be updated, so update skeleton.
- skin.instance();
- skin->set_bind_count(bones.size());
- _update_process_order(); //just in case
+ return skin_ref;
+}
- // pose changed, rebuild cache of inverses
- const Bone *bonesptr = bones.ptr();
- int len = bones.size();
- const int *order = process_order.ptr();
+void Skeleton3D::force_update_all_dirty_bones() {
+ if (dirty) {
+ const_cast<Skeleton3D *>(this)->notification(NOTIFICATION_UPDATE_SKELETON);
+ }
+}
+
+void Skeleton3D::force_update_all_bone_transforms() {
+ _update_process_order();
- // calculate global rests and invert them
- for (int i = 0; i < len; i++) {
- const Bone &b = bonesptr[order[i]];
+ for (int i = 0; i < parentless_bones.size(); i++) {
+ force_update_bone_children_transforms(parentless_bones[i]);
+ }
+}
+
+void Skeleton3D::force_update_bone_children_transforms(int p_bone_idx) {
+ const int bone_size = bones.size();
+ ERR_FAIL_INDEX(p_bone_idx, bone_size);
+
+ Bone *bonesptr = bones.ptrw();
+ List<int> bones_to_process = List<int>();
+ bones_to_process.push_back(p_bone_idx);
+
+ while (bones_to_process.size() > 0) {
+ int current_bone_idx = bones_to_process[0];
+ bones_to_process.erase(current_bone_idx);
+
+ Bone &b = bonesptr[current_bone_idx];
+ bool bone_enabled = b.enabled && !show_rest_only;
+
+ if (bone_enabled) {
+ b.update_pose_cache();
+ Transform3D pose = b.pose_cache;
+
+ if (b.parent >= 0) {
+ b.pose_global = bonesptr[b.parent].pose_global * pose;
+ b.pose_global_no_override = b.pose_global;
+ } else {
+ b.pose_global = pose;
+ b.pose_global_no_override = b.pose_global;
+ }
+ } else {
+ if (b.parent >= 0) {
+ b.pose_global = bonesptr[b.parent].pose_global * b.rest;
+ b.pose_global_no_override = b.pose_global;
+ } else {
+ b.pose_global = b.rest;
+ b.pose_global_no_override = b.pose_global;
+ }
+ }
+ if (rest_dirty) {
+ 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) {
- skin->set_bind_pose(order[i], skin->get_bind_pose(b.parent) * b.rest);
+ override_local_pose = bonesptr[b.parent].pose_global * b.local_pose_override;
} else {
- skin->set_bind_pose(order[i], b.rest);
+ override_local_pose = b.local_pose_override;
}
+ b.pose_global = b.pose_global.interpolate_with(override_local_pose, b.local_pose_override_amount);
}
- for (int i = 0; i < len; i++) {
- //the inverse is what is actually required
- skin->set_bind_bone(i, i);
- skin->set_bind_pose(i, skin->get_bind_pose(i).affine_inverse());
+ 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;
+ }
+
+ // Add the bone's children to the list of bones to be processed.
+ int child_bone_size = b.child_bones.size();
+ for (int i = 0; i < child_bone_size; i++) {
+ bones_to_process.push_back(b.child_bones[i]);
+ }
+
+ emit_signal(SceneStringNames::get_singleton()->bone_pose_changed, current_bone_idx);
}
+ rest_dirty = false;
+}
- ERR_FAIL_COND_V(skin.is_null(), Ref<SkinReference>());
+// Helper functions
- Ref<SkinReference> skin_ref;
- skin_ref.instance();
+Transform3D Skeleton3D::global_pose_to_world_transform(Transform3D p_global_pose) {
+ return get_global_transform() * p_global_pose;
+}
- skin_ref->skeleton_node = this;
- skin_ref->bind_count = 0;
- skin_ref->skeleton = RenderingServer::get_singleton()->skeleton_create();
- skin_ref->skeleton_node = this;
- skin_ref->skin = skin;
+Transform3D Skeleton3D::world_transform_to_global_pose(Transform3D p_world_transform) {
+ return get_global_transform().affine_inverse() * p_world_transform;
+}
- skin_bindings.insert(skin_ref.operator->());
+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;
+ }
+}
- skin->connect("changed", Callable(skin_ref.operator->(), "_skin_changed"));
+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;
+ }
+}
- _make_dirty(); //skin needs to be updated, so update skeleton
+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;
- return skin_ref;
+ 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;
}
-// helper functions
-Transform Skeleton3D::bone_transform_to_world_transform(Transform p_bone_transform) {
- return get_global_transform() * p_bone_transform;
+// 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;
}
-Transform Skeleton3D::world_transform_to_bone_transform(Transform p_world_transform) {
- return get_global_transform().affine_inverse() * p_world_transform;
+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("get_bone_process_orders"), &Skeleton3D::get_bone_process_orders);
ClassDB::bind_method(D_METHOD("add_bone", "name"), &Skeleton3D::add_bone);
ClassDB::bind_method(D_METHOD("find_bone", "name"), &Skeleton3D::find_bone);
ClassDB::bind_method(D_METHOD("get_bone_name", "bone_idx"), &Skeleton3D::get_bone_name);
@@ -902,39 +1216,60 @@ void Skeleton3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("unparent_bone_and_rest", "bone_idx"), &Skeleton3D::unparent_bone_and_rest);
+ ClassDB::bind_method(D_METHOD("get_bone_children", "bone_idx"), &Skeleton3D::get_bone_children);
+ ClassDB::bind_method(D_METHOD("set_bone_children", "bone_idx", "bone_children"), &Skeleton3D::set_bone_children);
+ ClassDB::bind_method(D_METHOD("add_bone_child", "bone_idx", "child_bone_idx"), &Skeleton3D::add_bone_child);
+ ClassDB::bind_method(D_METHOD("remove_bone_child", "bone_idx", "child_bone_idx"), &Skeleton3D::remove_bone_child);
+
+ ClassDB::bind_method(D_METHOD("get_parentless_bones"), &Skeleton3D::get_parentless_bones);
+
ClassDB::bind_method(D_METHOD("get_bone_rest", "bone_idx"), &Skeleton3D::get_bone_rest);
ClassDB::bind_method(D_METHOD("set_bone_rest", "bone_idx", "rest"), &Skeleton3D::set_bone_rest);
+ ClassDB::bind_method(D_METHOD("get_bone_global_rest", "bone_idx"), &Skeleton3D::get_bone_global_rest);
+ ClassDB::bind_method(D_METHOD("create_skin_from_rest_transforms"), &Skeleton3D::create_skin_from_rest_transforms);
ClassDB::bind_method(D_METHOD("register_skin", "skin"), &Skeleton3D::register_skin);
ClassDB::bind_method(D_METHOD("localize_rests"), &Skeleton3D::localize_rests);
- ClassDB::bind_method(D_METHOD("set_bone_disable_rest", "bone_idx", "disable"), &Skeleton3D::set_bone_disable_rest);
- ClassDB::bind_method(D_METHOD("is_bone_rest_disabled", "bone_idx"), &Skeleton3D::is_bone_rest_disabled);
-
- ClassDB::bind_method(D_METHOD("bind_child_node_to_bone", "bone_idx", "node"), &Skeleton3D::bind_child_node_to_bone);
- ClassDB::bind_method(D_METHOD("unbind_child_node_from_bone", "bone_idx", "node"), &Skeleton3D::unbind_child_node_from_bone);
- ClassDB::bind_method(D_METHOD("get_bound_child_nodes_to_bone", "bone_idx"), &Skeleton3D::_get_bound_child_nodes_to_bone);
-
ClassDB::bind_method(D_METHOD("clear_bones"), &Skeleton3D::clear_bones);
ClassDB::bind_method(D_METHOD("get_bone_pose", "bone_idx"), &Skeleton3D::get_bone_pose);
- ClassDB::bind_method(D_METHOD("set_bone_pose", "bone_idx", "pose"), &Skeleton3D::set_bone_pose);
+ ClassDB::bind_method(D_METHOD("set_bone_pose_position", "bone_idx", "position"), &Skeleton3D::set_bone_pose_position);
+ ClassDB::bind_method(D_METHOD("set_bone_pose_rotation", "bone_idx", "rotation"), &Skeleton3D::set_bone_pose_rotation);
+ ClassDB::bind_method(D_METHOD("set_bone_pose_scale", "bone_idx", "scale"), &Skeleton3D::set_bone_pose_scale);
+
+ ClassDB::bind_method(D_METHOD("get_bone_pose_position", "bone_idx"), &Skeleton3D::get_bone_pose_position);
+ ClassDB::bind_method(D_METHOD("get_bone_pose_rotation", "bone_idx"), &Skeleton3D::get_bone_pose_rotation);
+ ClassDB::bind_method(D_METHOD("get_bone_pose_scale", "bone_idx"), &Skeleton3D::get_bone_pose_scale);
+
+ ClassDB::bind_method(D_METHOD("is_bone_enabled", "bone_idx"), &Skeleton3D::is_bone_enabled);
+ ClassDB::bind_method(D_METHOD("set_bone_enabled", "bone_idx", "enabled"), &Skeleton3D::set_bone_enabled, DEFVAL(true));
ClassDB::bind_method(D_METHOD("clear_bones_global_pose_override"), &Skeleton3D::clear_bones_global_pose_override);
ClassDB::bind_method(D_METHOD("set_bone_global_pose_override", "bone_idx", "pose", "amount", "persistent"), &Skeleton3D::set_bone_global_pose_override, DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("get_bone_global_pose_override", "bone_idx"), &Skeleton3D::get_bone_global_pose_override);
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("get_bone_custom_pose", "bone_idx"), &Skeleton3D::get_bone_custom_pose);
- ClassDB::bind_method(D_METHOD("set_bone_custom_pose", "bone_idx", "custom_pose"), &Skeleton3D::set_bone_custom_pose);
+ 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("bone_transform_to_world_transform", "bone_transform"), &Skeleton3D::bone_transform_to_world_transform);
- ClassDB::bind_method(D_METHOD("world_transform_to_bone_transform", "world_transform"), &Skeleton3D::world_transform_to_bone_transform);
+ 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);
-#ifndef _3D_DISABLED
+ // 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_animate_physical_bones"), &Skeleton3D::set_animate_physical_bones);
+ 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);
+
+ ClassDB::bind_method(D_METHOD("set_animate_physical_bones", "enabled"), &Skeleton3D::set_animate_physical_bones);
ClassDB::bind_method(D_METHOD("get_animate_physical_bones"), &Skeleton3D::get_animate_physical_bones);
ClassDB::bind_method(D_METHOD("physical_bones_stop_simulation"), &Skeleton3D::physical_bones_stop_simulation);
@@ -942,6 +1277,13 @@ 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);
+
+#ifndef _3D_DISABLED
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "show_rest_only"), "set_show_rest_only", "is_show_rest_only");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "animate_physical_bones"), "set_animate_physical_bones", "get_animate_physical_bones");
#endif // _3D_DISABLED
@@ -949,6 +1291,10 @@ void Skeleton3D::_bind_methods() {
ADD_SIGNAL(MethodInfo("pose_updated"));
#endif // TOOLS_ENABLED
+ ADD_SIGNAL(MethodInfo("bone_pose_changed", PropertyInfo(Variant::INT, "bone_idx")));
+ ADD_SIGNAL(MethodInfo("bone_enabled_changed", PropertyInfo(Variant::INT, "bone_idx")));
+ ADD_SIGNAL(MethodInfo("show_rest_only_changed"));
+
BIND_CONSTANT(NOTIFICATION_UPDATE_SKELETON);
}
@@ -956,7 +1302,7 @@ Skeleton3D::Skeleton3D() {
}
Skeleton3D::~Skeleton3D() {
- //some skins may remain bound
+ // Some skins may remain bound.
for (Set<SkinReference *>::Element *E = skin_bindings.front(); E; E = E->next()) {
E->get()->skeleton_node = nullptr;
}
diff --git a/scene/3d/skeleton_3d.h b/scene/3d/skeleton_3d.h
index 508cd7c329..ca706bea98 100644
--- a/scene/3d/skeleton_3d.h
+++ b/scene/3d/skeleton_3d.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -31,29 +31,26 @@
#ifndef SKELETON_3D_H
#define SKELETON_3D_H
-#include "core/templates/rid.h"
#include "scene/3d/node_3d.h"
+#include "scene/resources/skeleton_modification_3d.h"
#include "scene/resources/skin.h"
-#ifndef _3D_DISABLED
typedef int BoneId;
class PhysicalBone3D;
-#endif // _3D_DISABLED
-
class Skeleton3D;
-class SkinReference : public Reference {
- GDCLASS(SkinReference, Reference)
+class SkinReference : public RefCounted {
+ GDCLASS(SkinReference, RefCounted)
friend class Skeleton3D;
- Skeleton3D *skeleton_node;
+ Skeleton3D *skeleton_node = nullptr;
RID skeleton;
Ref<Skin> skin;
uint32_t bind_count = 0;
uint64_t skeleton_version = 0;
Vector<uint32_t> skin_bone_indices;
- uint32_t *skin_bone_indices_ptrs;
+ uint32_t *skin_bone_indices_ptrs = nullptr;
void _skin_changed();
protected:
@@ -65,6 +62,8 @@ public:
~SkinReference();
};
+class SkeletonModificationStack3D;
+
class Skeleton3D : public Node3D {
GDCLASS(Skeleton3D, Node3D);
@@ -74,30 +73,62 @@ private:
struct Bone {
String name;
- bool enabled = true;
- int parent = -1;
- int sort_index = 0; //used for re-sorting process order
+ bool enabled;
+ int parent;
- bool disable_rest = false;
- Transform rest;
+ Transform3D rest;
+ Transform3D global_rest;
- Transform pose;
- Transform pose_global;
- Transform pose_global_no_override;
+ _FORCE_INLINE_ void update_pose_cache() {
+ if (pose_cache_dirty) {
+ pose_cache.basis.set_quaternion_scale(pose_rotation, pose_scale);
+ pose_cache.origin = pose_position;
+ pose_cache_dirty = false;
+ }
+ }
+ bool pose_cache_dirty = true;
+ Transform3D pose_cache;
+ Vector3 pose_position;
+ Quaternion pose_rotation;
+ Vector3 pose_scale = Vector3(1, 1, 1);
- bool custom_pose_enable = false;
- Transform custom_pose;
+ Transform3D pose_global;
+ Transform3D pose_global_no_override;
- float global_pose_override_amount = 0.0;
+ real_t global_pose_override_amount = 0.0;
bool global_pose_override_reset = false;
- Transform global_pose_override;
+ Transform3D global_pose_override;
-#ifndef _3D_DISABLED
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;
+ global_pose_override_amount = 0;
+ global_pose_override_reset = false;
+#ifndef _3D_DISABLED
+ 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>();
- List<ObjectID> nodes_bound;
+ rest_bone_forward_vector = Vector3(0, 0, 0);
+ rest_bone_forward_axis = -1;
+ }
};
Set<SkinReference *> skin_bindings;
@@ -106,25 +137,17 @@ private:
bool animate_physical_bones = true;
Vector<Bone> bones;
- Vector<int> process_order;
- bool process_order_dirty = true;
+ bool process_order_dirty = false;
+
+ Vector<int> parentless_bones;
void _make_dirty();
bool dirty = false;
+ bool rest_dirty = false;
- uint64_t version = 1;
+ bool show_rest_only = false;
- // bind helpers
- Array _get_bound_child_nodes_to_bone(int p_bone) const {
- Array bound;
- List<Node *> children;
- get_bound_child_nodes_to_bone(p_bone, &children);
-
- for (int i = 0; i < children.size(); i++) {
- bound.push_back(children[i]);
- }
- return bound;
- }
+ uint64_t version = 1;
void _update_process_order();
@@ -132,10 +155,24 @@ protected:
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;
+ virtual void _validate_property(PropertyInfo &property) const override;
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
};
@@ -153,50 +190,80 @@ public:
void unparent_bone_and_rest(int p_bone);
- void set_bone_disable_rest(int p_bone, bool p_disable);
- bool is_bone_rest_disabled(int p_bone) const;
+ Vector<int> get_bone_children(int p_bone);
+ void set_bone_children(int p_bone, Vector<int> p_children);
+ void add_bone_child(int p_bone, int p_child);
+ void remove_bone_child(int p_bone, int p_child);
+ Vector<int> get_parentless_bones();
int get_bone_count() const;
- void set_bone_rest(int p_bone, const Transform &p_rest);
- Transform get_bone_rest(int p_bone) const;
- Transform get_bone_global_pose(int p_bone) const;
- Transform get_bone_global_pose_no_override(int p_bone) const;
-
- void clear_bones_global_pose_override();
- void set_bone_global_pose_override(int p_bone, const Transform &p_pose, float p_amount, bool p_persistent = false);
+ void set_bone_rest(int p_bone, const Transform3D &p_rest);
+ Transform3D get_bone_rest(int p_bone) const;
+ Transform3D get_bone_global_rest(int p_bone) const;
+ Transform3D get_bone_global_pose(int p_bone) const;
+ Transform3D get_bone_global_pose_no_override(int p_bone) const;
void set_bone_enabled(int p_bone, bool p_enabled);
bool is_bone_enabled(int p_bone) const;
- void bind_child_node_to_bone(int p_bone, Node *p_node);
- void unbind_child_node_from_bone(int p_bone, Node *p_node);
- void get_bound_child_nodes_to_bone(int p_bone, List<Node *> *p_bound) const;
-
+ void set_show_rest_only(bool p_enabled);
+ bool is_show_rest_only() const;
void clear_bones();
// posing api
- void set_bone_pose(int p_bone, const Transform &p_pose);
- Transform get_bone_pose(int p_bone) const;
+ void set_bone_pose_position(int p_bone, const Vector3 &p_position);
+ void set_bone_pose_rotation(int p_bone, const Quaternion &p_rotation);
+ void set_bone_pose_scale(int p_bone, const Vector3 &p_scale);
+
+ Transform3D get_bone_pose(int p_bone) const;
+
+ Vector3 get_bone_pose_position(int p_bone) const;
+ Quaternion get_bone_pose_rotation(int p_bone) const;
+ Vector3 get_bone_pose_scale(int p_bone) const;
- void set_bone_custom_pose(int p_bone, const Transform &p_custom_pose);
- Transform get_bone_custom_pose(int p_bone) const;
+ void clear_bones_global_pose_override();
+ 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
- int get_process_order(int p_idx);
- Vector<int> get_bone_process_orders();
+
+ Ref<Skin> create_skin_from_rest_transforms();
Ref<SkinReference> register_skin(const Ref<Skin> &p_skin);
+ void force_update_all_dirty_bones();
+ 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
- Transform bone_transform_to_world_transform(Transform p_transform);
- Transform world_transform_to_bone_transform(Transform p_transform);
+ 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_animate);
+ void set_animate_physical_bones(bool p_enabled);
bool get_animate_physical_bones() const;
void bind_physical_bone_to_bone(int p_bone, PhysicalBone3D *p_physical_bone);
@@ -215,7 +282,6 @@ public:
void physical_bones_start_simulation_on(const TypedArray<StringName> &p_bones);
void physical_bones_add_collision_exception(RID p_exception);
void physical_bones_remove_collision_exception(RID p_exception);
-#endif // _3D_DISABLED
public:
Skeleton3D();
diff --git a/scene/3d/skeleton_ik_3d.cpp b/scene/3d/skeleton_ik_3d.cpp
index bd1c202205..5e1f9d047f 100644
--- a/scene/3d/skeleton_ik_3d.cpp
+++ b/scene/3d/skeleton_ik_3d.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -28,10 +28,6 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-/**
- * @author AndreaCatania
- */
-
#include "skeleton_ik_3d.h"
#ifndef _3D_DISABLED
@@ -85,7 +81,7 @@ bool FabrikInverseKinematic::build_chain(Task *p_task, bool p_force_simple_chain
chain_sub_tip = p_task->skeleton->get_bone_parent(chain_sub_tip);
}
- BoneId middle_chain_item_id = (((float)sub_chain_size) * 0.5);
+ BoneId middle_chain_item_id = (BoneId)(sub_chain_size * 0.5);
// Build chain by reading chain ids in reverse order
// For each chain item id will be created a ChainItem if doesn't exists
@@ -99,7 +95,7 @@ bool FabrikInverseKinematic::build_chain(Task *p_task, bool p_force_simple_chain
child_ci->current_pos = child_ci->initial_transform.origin;
if (child_ci->parent_item) {
- child_ci->length = (child_ci->current_pos - child_ci->parent_item->current_pos).length();
+ child_ci->length = child_ci->parent_item->current_pos.distance_to(child_ci->current_pos);
}
}
@@ -129,7 +125,7 @@ bool FabrikInverseKinematic::build_chain(Task *p_task, bool p_force_simple_chain
return true;
}
-void FabrikInverseKinematic::solve_simple(Task *p_task, bool p_solve_magnet) {
+void FabrikInverseKinematic::solve_simple(Task *p_task, bool p_solve_magnet, Vector3 p_origin_pos) {
real_t distance_to_goal(1e4);
real_t previous_distance_to_goal(0);
int can_solve(p_task->max_iterations);
@@ -138,13 +134,13 @@ void FabrikInverseKinematic::solve_simple(Task *p_task, bool p_solve_magnet) {
--can_solve;
solve_simple_backwards(p_task->chain, p_solve_magnet);
- solve_simple_forwards(p_task->chain, p_solve_magnet);
+ solve_simple_forwards(p_task->chain, p_solve_magnet, p_origin_pos);
- distance_to_goal = (p_task->chain.tips[0].chain_item->current_pos - p_task->chain.tips[0].end_effector->goal_transform.origin).length();
+ distance_to_goal = p_task->chain.tips[0].end_effector->goal_transform.origin.distance_to(p_task->chain.tips[0].chain_item->current_pos);
}
}
-void FabrikInverseKinematic::solve_simple_backwards(Chain &r_chain, bool p_solve_magnet) {
+void FabrikInverseKinematic::solve_simple_backwards(const Chain &r_chain, bool p_solve_magnet) {
if (p_solve_magnet && !r_chain.middle_chain_item) {
return;
}
@@ -176,13 +172,13 @@ void FabrikInverseKinematic::solve_simple_backwards(Chain &r_chain, bool p_solve
}
}
-void FabrikInverseKinematic::solve_simple_forwards(Chain &r_chain, bool p_solve_magnet) {
+void FabrikInverseKinematic::solve_simple_forwards(Chain &r_chain, bool p_solve_magnet, Vector3 p_origin_pos) {
if (p_solve_magnet && !r_chain.middle_chain_item) {
return;
}
ChainItem *sub_chain_root(&r_chain.chain_root);
- Vector3 origin(r_chain.chain_root.initial_transform.origin);
+ Vector3 origin = p_origin_pos;
while (sub_chain_root) { // Reach the tip
sub_chain_root->current_pos = origin;
@@ -212,7 +208,7 @@ void FabrikInverseKinematic::solve_simple_forwards(Chain &r_chain, bool p_solve_
}
}
-FabrikInverseKinematic::Task *FabrikInverseKinematic::create_simple_task(Skeleton3D *p_sk, BoneId root_bone, BoneId tip_bone, const Transform &goal_transform) {
+FabrikInverseKinematic::Task *FabrikInverseKinematic::create_simple_task(Skeleton3D *p_sk, BoneId root_bone, BoneId tip_bone, const Transform3D &goal_transform) {
FabrikInverseKinematic::EndEffector ee;
ee.tip_bone = tip_bone;
@@ -236,17 +232,17 @@ void FabrikInverseKinematic::free_task(Task *p_task) {
}
}
-void FabrikInverseKinematic::set_goal(Task *p_task, const Transform &p_goal) {
+void FabrikInverseKinematic::set_goal(Task *p_task, const Transform3D &p_goal) {
p_task->goal_global_transform = p_goal;
}
-void FabrikInverseKinematic::make_goal(Task *p_task, const Transform &p_inverse_transf, real_t blending_delta) {
+void FabrikInverseKinematic::make_goal(Task *p_task, const Transform3D &p_inverse_transf, real_t blending_delta) {
if (blending_delta >= 0.99f) {
// Update the end_effector (local transform) without blending
p_task->end_effectors.write[0].goal_transform = p_inverse_transf * p_task->goal_global_transform;
} else {
// End effector in local transform
- const Transform end_effector_pose(p_task->skeleton->get_bone_global_pose_no_override(p_task->end_effectors[0].tip_bone));
+ const Transform3D end_effector_pose(p_task->skeleton->get_bone_global_pose_no_override(p_task->end_effectors[0].tip_bone));
// Update the end_effector (local transform) by blending with current pose
p_task->end_effectors.write[0].goal_transform = end_effector_pose.interpolate_with(p_inverse_transf * p_task->goal_global_transform, blending_delta);
@@ -273,29 +269,28 @@ void FabrikInverseKinematic::solve(Task *p_task, real_t blending_delta, bool ove
// Update the initial root transform so its synced with any animation changes
_update_chain(p_task->skeleton, &p_task->chain.chain_root);
+ p_task->skeleton->set_bone_global_pose_override(p_task->chain.chain_root.bone, Transform3D(), 0.0, false);
+ Vector3 origin_pos = p_task->skeleton->get_bone_global_pose(p_task->chain.chain_root.bone).origin;
+
make_goal(p_task, p_task->skeleton->get_global_transform().affine_inverse(), blending_delta);
if (p_use_magnet && p_task->chain.middle_chain_item) {
p_task->chain.magnet_position = p_task->chain.middle_chain_item->initial_transform.origin.lerp(p_magnet_position, blending_delta);
- solve_simple(p_task, true);
+ solve_simple(p_task, true, origin_pos);
}
- solve_simple(p_task, false);
+ solve_simple(p_task, false, origin_pos);
// Assign new bone position.
ChainItem *ci(&p_task->chain.chain_root);
while (ci) {
- Transform new_bone_pose(ci->initial_transform);
+ Transform3D new_bone_pose(ci->initial_transform);
new_bone_pose.origin = ci->current_pos;
if (!ci->children.is_empty()) {
- /// Rotate basis
- const Vector3 initial_ori((ci->children[0].initial_transform.origin - ci->initial_transform.origin).normalized());
- const Vector3 rot_axis(initial_ori.cross(ci->current_ori).normalized());
-
- if (rot_axis[0] != 0 && rot_axis[1] != 0 && rot_axis[2] != 0) {
- const real_t rot_angle(Math::acos(CLAMP(initial_ori.dot(ci->current_ori), -1, 1)));
- new_bone_pose.basis.rotate(rot_axis, rot_angle);
- }
+ p_task->skeleton->update_bone_rest_forward_vector(ci->bone);
+ Vector3 forward_vector = p_task->skeleton->get_bone_axis_forward_vector(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));
} else {
// Set target orientation to tip
@@ -352,6 +347,8 @@ void SkeletonIK3D::_validate_property(PropertyInfo &property) const {
property.hint_string = "";
}
}
+
+ Node::_validate_property(property);
}
void SkeletonIK3D::_bind_methods() {
@@ -394,7 +391,7 @@ void SkeletonIK3D::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::STRING_NAME, "root_bone"), "set_root_bone", "get_root_bone");
ADD_PROPERTY(PropertyInfo(Variant::STRING_NAME, "tip_bone"), "set_tip_bone", "get_tip_bone");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "interpolation", PROPERTY_HINT_RANGE, "0,1,0.001"), "set_interpolation", "get_interpolation");
- ADD_PROPERTY(PropertyInfo(Variant::TRANSFORM, "target"), "set_target_transform", "get_target_transform");
+ ADD_PROPERTY(PropertyInfo(Variant::TRANSFORM3D, "target"), "set_target_transform", "get_target_transform");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "override_tip_basis"), "set_override_tip_basis", "is_override_tip_basis");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_magnet"), "set_use_magnet", "is_using_magnet");
ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "magnet"), "set_magnet_position", "get_magnet_position");
@@ -410,14 +407,14 @@ void SkeletonIK3D::_notification(int p_what) {
set_process_priority(1);
reload_chain();
} break;
+
case NOTIFICATION_INTERNAL_PROCESS: {
if (target_node_override) {
reload_goal();
}
-
_solve_chain();
-
} break;
+
case NOTIFICATION_EXIT_TREE: {
reload_chain();
} break;
@@ -458,12 +455,12 @@ real_t SkeletonIK3D::get_interpolation() const {
return interpolation;
}
-void SkeletonIK3D::set_target_transform(const Transform &p_target) {
+void SkeletonIK3D::set_target_transform(const Transform3D &p_target) {
target = p_target;
reload_goal();
}
-const Transform &SkeletonIK3D::get_target_transform() const {
+const Transform3D &SkeletonIK3D::get_target_transform() const {
return target;
}
@@ -534,12 +531,12 @@ void SkeletonIK3D::stop() {
}
}
-Transform SkeletonIK3D::_get_target_transform() {
+Transform3D SkeletonIK3D::_get_target_transform() {
if (!target_node_override && !target_node_path_override.is_empty()) {
target_node_override = Object::cast_to<Node3D>(get_node(target_node_path_override));
}
- if (target_node_override) {
+ if (target_node_override && target_node_override->is_inside_tree()) {
return target_node_override->get_global_transform();
} else {
return target;
diff --git a/scene/3d/skeleton_ik_3d.h b/scene/3d/skeleton_ik_3d.h
index 9255e18b72..0f656187de 100644
--- a/scene/3d/skeleton_ik_3d.h
+++ b/scene/3d/skeleton_ik_3d.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -33,17 +33,12 @@
#ifndef _3D_DISABLED
-/**
- * @author AndreaCatania
- */
-
-#include "core/math/transform.h"
#include "scene/3d/skeleton_3d.h"
class FabrikInverseKinematic {
struct EndEffector {
BoneId tip_bone;
- Transform goal_transform;
+ Transform3D goal_transform;
};
struct ChainItem {
@@ -55,7 +50,7 @@ class FabrikInverseKinematic {
real_t length = 0.0;
/// Positions relative to root bone
- Transform initial_transform;
+ Transform3D initial_transform;
Vector3 current_pos;
// Direction from this bone to child
Vector3 current_ori;
@@ -97,7 +92,7 @@ public:
BoneId root_bone = -1;
Vector<EndEffector> end_effectors;
- Transform goal_global_transform;
+ Transform3D goal_global_transform;
Task() {}
};
@@ -106,17 +101,17 @@ private:
/// Init a chain that starts from the root to tip
static bool build_chain(Task *p_task, bool p_force_simple_chain = true);
- static void solve_simple(Task *p_task, bool p_solve_magnet);
+ static void solve_simple(Task *p_task, bool p_solve_magnet, Vector3 p_origin_pos);
/// Special solvers that solve only chains with one end effector
- static void solve_simple_backwards(Chain &r_chain, bool p_solve_magnet);
- static void solve_simple_forwards(Chain &r_chain, bool p_solve_magnet);
+ static void solve_simple_backwards(const Chain &r_chain, bool p_solve_magnet);
+ static void solve_simple_forwards(Chain &r_chain, bool p_solve_magnet, Vector3 p_origin_pos);
public:
- static Task *create_simple_task(Skeleton3D *p_sk, BoneId root_bone, BoneId tip_bone, const Transform &goal_transform);
+ static Task *create_simple_task(Skeleton3D *p_sk, BoneId root_bone, BoneId tip_bone, const Transform3D &goal_transform);
static void free_task(Task *p_task);
// The goal of chain should be always in local space
- static void set_goal(Task *p_task, const Transform &p_goal);
- static void make_goal(Task *p_task, const Transform &p_inverse_transf, real_t blending_delta);
+ static void set_goal(Task *p_task, const Transform3D &p_goal);
+ static void make_goal(Task *p_task, const Transform3D &p_inverse_transf, real_t blending_delta);
static void solve(Task *p_task, real_t blending_delta, bool override_tip_basis, bool p_use_magnet, const Vector3 &p_magnet_position);
static void _update_chain(const Skeleton3D *p_skeleton, ChainItem *p_chain_item);
@@ -128,7 +123,7 @@ class SkeletonIK3D : public Node {
StringName root_bone;
StringName tip_bone;
real_t interpolation = 1.0;
- Transform target;
+ Transform3D target;
NodePath target_node_path_override;
bool override_tip_basis = true;
bool use_magnet = false;
@@ -142,8 +137,7 @@ class SkeletonIK3D : public Node {
FabrikInverseKinematic::Task *task = nullptr;
protected:
- virtual void
- _validate_property(PropertyInfo &property) const override;
+ virtual void _validate_property(PropertyInfo &property) const override;
static void _bind_methods();
virtual void _notification(int p_what);
@@ -161,8 +155,8 @@ public:
void set_interpolation(real_t p_interpolation);
real_t get_interpolation() const;
- void set_target_transform(const Transform &p_target);
- const Transform &get_target_transform() const;
+ void set_target_transform(const Transform3D &p_target);
+ const Transform3D &get_target_transform() const;
void set_target_node(const NodePath &p_node);
NodePath get_target_node();
@@ -190,7 +184,7 @@ public:
void stop();
private:
- Transform _get_target_transform();
+ Transform3D _get_target_transform();
void reload_chain();
void reload_goal();
void _solve_chain();
diff --git a/scene/3d/soft_body_3d.cpp b/scene/3d/soft_dynamic_body_3d.cpp
index dc4deb0570..7d786a41bf 100644
--- a/scene/3d/soft_body_3d.cpp
+++ b/scene/3d/soft_dynamic_body_3d.cpp
@@ -1,12 +1,12 @@
/*************************************************************************/
-/* soft_body_3d.cpp */
+/* soft_dynamic_body_3d.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -28,19 +28,13 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#include "soft_body_3d.h"
+#include "soft_dynamic_body_3d.h"
-#include "core/object/class_db.h"
-#include "core/os/os.h"
-#include "core/templates/list.h"
-#include "core/templates/rid.h"
-#include "scene/3d/collision_object_3d.h"
#include "scene/3d/physics_body_3d.h"
-#include "scene/3d/skeleton_3d.h"
-SoftBodyRenderingServerHandler::SoftBodyRenderingServerHandler() {}
+SoftDynamicBodyRenderingServerHandler::SoftDynamicBodyRenderingServerHandler() {}
-void SoftBodyRenderingServerHandler::prepare(RID p_mesh, int p_surface) {
+void SoftDynamicBodyRenderingServerHandler::prepare(RID p_mesh, int p_surface) {
clear();
ERR_FAIL_COND(!p_mesh.is_valid());
@@ -62,7 +56,7 @@ void SoftBodyRenderingServerHandler::prepare(RID p_mesh, int p_surface) {
offset_normal = surface_offsets[RS::ARRAY_NORMAL];
}
-void SoftBodyRenderingServerHandler::clear() {
+void SoftDynamicBodyRenderingServerHandler::clear() {
buffer.resize(0);
stride = 0;
offset_vertices = 0;
@@ -72,49 +66,48 @@ void SoftBodyRenderingServerHandler::clear() {
mesh = RID();
}
-void SoftBodyRenderingServerHandler::open() {
+void SoftDynamicBodyRenderingServerHandler::open() {
write_buffer = buffer.ptrw();
}
-void SoftBodyRenderingServerHandler::close() {
+void SoftDynamicBodyRenderingServerHandler::close() {
write_buffer = nullptr;
}
-void SoftBodyRenderingServerHandler::commit_changes() {
- RS::get_singleton()->mesh_surface_update_region(mesh, surface, 0, buffer);
+void SoftDynamicBodyRenderingServerHandler::commit_changes() {
+ RS::get_singleton()->mesh_surface_update_vertex_region(mesh, surface, 0, buffer);
}
-void SoftBodyRenderingServerHandler::set_vertex(int p_vertex_id, const void *p_vector3) {
+void SoftDynamicBodyRenderingServerHandler::set_vertex(int p_vertex_id, const void *p_vector3) {
memcpy(&write_buffer[p_vertex_id * stride + offset_vertices], p_vector3, sizeof(float) * 3);
}
-void SoftBodyRenderingServerHandler::set_normal(int p_vertex_id, const void *p_vector3) {
+void SoftDynamicBodyRenderingServerHandler::set_normal(int p_vertex_id, const void *p_vector3) {
memcpy(&write_buffer[p_vertex_id * stride + offset_normal], p_vector3, sizeof(float) * 3);
}
-void SoftBodyRenderingServerHandler::set_aabb(const AABB &p_aabb) {
+void SoftDynamicBodyRenderingServerHandler::set_aabb(const AABB &p_aabb) {
RS::get_singleton()->mesh_set_custom_aabb(mesh, p_aabb);
}
-SoftBody3D::PinnedPoint::PinnedPoint() {
+SoftDynamicBody3D::PinnedPoint::PinnedPoint() {
}
-SoftBody3D::PinnedPoint::PinnedPoint(const PinnedPoint &obj_tocopy) {
+SoftDynamicBody3D::PinnedPoint::PinnedPoint(const PinnedPoint &obj_tocopy) {
point_index = obj_tocopy.point_index;
spatial_attachment_path = obj_tocopy.spatial_attachment_path;
spatial_attachment = obj_tocopy.spatial_attachment;
offset = obj_tocopy.offset;
}
-SoftBody3D::PinnedPoint &SoftBody3D::PinnedPoint::operator=(const PinnedPoint &obj) {
+void SoftDynamicBody3D::PinnedPoint::operator=(const PinnedPoint &obj) {
point_index = obj.point_index;
spatial_attachment_path = obj.spatial_attachment_path;
spatial_attachment = obj.spatial_attachment;
offset = obj.offset;
- return *this;
}
-void SoftBody3D::_update_pickable() {
+void SoftDynamicBody3D::_update_pickable() {
if (!is_inside_tree()) {
return;
}
@@ -122,7 +115,7 @@ void SoftBody3D::_update_pickable() {
PhysicsServer3D::get_singleton()->soft_body_set_ray_pickable(physics_rid, pickable);
}
-bool SoftBody3D::_set(const StringName &p_name, const Variant &p_value) {
+bool SoftDynamicBody3D::_set(const StringName &p_name, const Variant &p_value) {
String name = p_name;
String which = name.get_slicec('/', 0);
@@ -139,7 +132,7 @@ bool SoftBody3D::_set(const StringName &p_name, const Variant &p_value) {
return false;
}
-bool SoftBody3D::_get(const StringName &p_name, Variant &r_ret) const {
+bool SoftDynamicBody3D::_get(const StringName &p_name, Variant &r_ret) const {
String name = p_name;
String which = name.get_slicec('/', 0);
@@ -166,7 +159,7 @@ bool SoftBody3D::_get(const StringName &p_name, Variant &r_ret) const {
return false;
}
-void SoftBody3D::_get_property_list(List<PropertyInfo> *p_list) const {
+void SoftDynamicBody3D::_get_property_list(List<PropertyInfo> *p_list) const {
const int pinned_points_indices_size = pinned_points.size();
p_list->push_back(PropertyInfo(Variant::PACKED_INT32_ARRAY, "pinned_points"));
@@ -178,7 +171,7 @@ void SoftBody3D::_get_property_list(List<PropertyInfo> *p_list) const {
}
}
-bool SoftBody3D::_set_property_pinned_points_indices(const Array &p_indices) {
+bool SoftDynamicBody3D::_set_property_pinned_points_indices(const Array &p_indices) {
const int p_indices_size = p_indices.size();
{ // Remove the pined points on physics server that will be removed by resize
@@ -207,7 +200,7 @@ bool SoftBody3D::_set_property_pinned_points_indices(const Array &p_indices) {
return true;
}
-bool SoftBody3D::_set_property_pinned_points_attachment(int p_item, const String &p_what, const Variant &p_value) {
+bool SoftDynamicBody3D::_set_property_pinned_points_attachment(int p_item, const String &p_what, const Variant &p_value) {
if (pinned_points.size() <= p_item) {
return false;
}
@@ -226,7 +219,7 @@ bool SoftBody3D::_set_property_pinned_points_attachment(int p_item, const String
return true;
}
-bool SoftBody3D::_get_property_pinned_points(int p_item, const String &p_what, Variant &r_ret) const {
+bool SoftDynamicBody3D::_get_property_pinned_points(int p_item, const String &p_what, Variant &r_ret) const {
if (pinned_points.size() <= p_item) {
return false;
}
@@ -245,15 +238,7 @@ bool SoftBody3D::_get_property_pinned_points(int p_item, const String &p_what, V
return true;
}
-void SoftBody3D::_softbody_changed() {
- prepare_physics_server();
- _reset_points_offsets();
-#ifdef TOOLS_ENABLED
- update_configuration_warnings();
-#endif
-}
-
-void SoftBody3D::_notification(int p_what) {
+void SoftDynamicBody3D::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_ENTER_WORLD: {
if (Engine::get_singleton()->is_editor_hint()) {
@@ -264,14 +249,15 @@ void SoftBody3D::_notification(int p_what) {
RID space = get_world_3d()->get_space();
PhysicsServer3D::get_singleton()->soft_body_set_space(physics_rid, space);
- prepare_physics_server();
+ _prepare_physics_server();
} break;
+
case NOTIFICATION_READY: {
if (!parent_collision_ignore.is_empty()) {
add_collision_exception_with(get_node(parent_collision_ignore));
}
-
} break;
+
case NOTIFICATION_TRANSFORM_CHANGED: {
if (Engine::get_singleton()->is_editor_hint()) {
_reset_points_offsets();
@@ -283,73 +269,90 @@ void SoftBody3D::_notification(int p_what) {
set_notify_transform(false);
// Required to be top level with Transform at center of world in order to modify RenderingServer only to support custom Transform
set_as_top_level(true);
- set_transform(Transform());
+ set_transform(Transform3D());
set_notify_transform(true);
-
} break;
+
case NOTIFICATION_VISIBILITY_CHANGED: {
_update_pickable();
-
} break;
+
case NOTIFICATION_EXIT_WORLD: {
PhysicsServer3D::get_singleton()->soft_body_set_space(physics_rid, RID());
-
} break;
- }
-#ifdef TOOLS_ENABLED
+ case NOTIFICATION_DISABLED: {
+ if (is_inside_tree() && (disable_mode == DISABLE_MODE_REMOVE)) {
+ _prepare_physics_server();
+ }
+ } break;
- if (p_what == NOTIFICATION_LOCAL_TRANSFORM_CHANGED) {
- if (Engine::get_singleton()->is_editor_hint()) {
- update_configuration_warnings();
- }
- }
+ case NOTIFICATION_ENABLED: {
+ if (is_inside_tree() && (disable_mode == DISABLE_MODE_REMOVE)) {
+ _prepare_physics_server();
+ }
+ } break;
+#ifdef TOOLS_ENABLED
+ case NOTIFICATION_LOCAL_TRANSFORM_CHANGED: {
+ if (Engine::get_singleton()->is_editor_hint()) {
+ update_configuration_warnings();
+ }
+ } break;
#endif
+ }
}
-void SoftBody3D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("get_physics_rid"), &SoftBody3D::get_physics_rid);
+void SoftDynamicBody3D::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("get_physics_rid"), &SoftDynamicBody3D::get_physics_rid);
+
+ ClassDB::bind_method(D_METHOD("set_collision_mask", "collision_mask"), &SoftDynamicBody3D::set_collision_mask);
+ ClassDB::bind_method(D_METHOD("get_collision_mask"), &SoftDynamicBody3D::get_collision_mask);
+
+ ClassDB::bind_method(D_METHOD("set_collision_layer", "collision_layer"), &SoftDynamicBody3D::set_collision_layer);
+ ClassDB::bind_method(D_METHOD("get_collision_layer"), &SoftDynamicBody3D::get_collision_layer);
- ClassDB::bind_method(D_METHOD("set_collision_mask", "collision_mask"), &SoftBody3D::set_collision_mask);
- ClassDB::bind_method(D_METHOD("get_collision_mask"), &SoftBody3D::get_collision_mask);
+ ClassDB::bind_method(D_METHOD("set_collision_mask_value", "layer_number", "value"), &SoftDynamicBody3D::set_collision_mask_value);
+ ClassDB::bind_method(D_METHOD("get_collision_mask_value", "layer_number"), &SoftDynamicBody3D::get_collision_mask_value);
- ClassDB::bind_method(D_METHOD("set_collision_layer", "collision_layer"), &SoftBody3D::set_collision_layer);
- ClassDB::bind_method(D_METHOD("get_collision_layer"), &SoftBody3D::get_collision_layer);
+ ClassDB::bind_method(D_METHOD("set_collision_layer_value", "layer_number", "value"), &SoftDynamicBody3D::set_collision_layer_value);
+ ClassDB::bind_method(D_METHOD("get_collision_layer_value", "layer_number"), &SoftDynamicBody3D::get_collision_layer_value);
- ClassDB::bind_method(D_METHOD("set_collision_mask_bit", "bit", "value"), &SoftBody3D::set_collision_mask_bit);
- ClassDB::bind_method(D_METHOD("get_collision_mask_bit", "bit"), &SoftBody3D::get_collision_mask_bit);
+ ClassDB::bind_method(D_METHOD("set_parent_collision_ignore", "parent_collision_ignore"), &SoftDynamicBody3D::set_parent_collision_ignore);
+ ClassDB::bind_method(D_METHOD("get_parent_collision_ignore"), &SoftDynamicBody3D::get_parent_collision_ignore);
- ClassDB::bind_method(D_METHOD("set_collision_layer_bit", "bit", "value"), &SoftBody3D::set_collision_layer_bit);
- ClassDB::bind_method(D_METHOD("get_collision_layer_bit", "bit"), &SoftBody3D::get_collision_layer_bit);
+ ClassDB::bind_method(D_METHOD("set_disable_mode", "mode"), &SoftDynamicBody3D::set_disable_mode);
+ ClassDB::bind_method(D_METHOD("get_disable_mode"), &SoftDynamicBody3D::get_disable_mode);
- ClassDB::bind_method(D_METHOD("set_parent_collision_ignore", "parent_collision_ignore"), &SoftBody3D::set_parent_collision_ignore);
- ClassDB::bind_method(D_METHOD("get_parent_collision_ignore"), &SoftBody3D::get_parent_collision_ignore);
+ ClassDB::bind_method(D_METHOD("get_collision_exceptions"), &SoftDynamicBody3D::get_collision_exceptions);
+ ClassDB::bind_method(D_METHOD("add_collision_exception_with", "body"), &SoftDynamicBody3D::add_collision_exception_with);
+ ClassDB::bind_method(D_METHOD("remove_collision_exception_with", "body"), &SoftDynamicBody3D::remove_collision_exception_with);
- ClassDB::bind_method(D_METHOD("get_collision_exceptions"), &SoftBody3D::get_collision_exceptions);
- ClassDB::bind_method(D_METHOD("add_collision_exception_with", "body"), &SoftBody3D::add_collision_exception_with);
- ClassDB::bind_method(D_METHOD("remove_collision_exception_with", "body"), &SoftBody3D::remove_collision_exception_with);
+ ClassDB::bind_method(D_METHOD("set_simulation_precision", "simulation_precision"), &SoftDynamicBody3D::set_simulation_precision);
+ ClassDB::bind_method(D_METHOD("get_simulation_precision"), &SoftDynamicBody3D::get_simulation_precision);
- ClassDB::bind_method(D_METHOD("set_simulation_precision", "simulation_precision"), &SoftBody3D::set_simulation_precision);
- ClassDB::bind_method(D_METHOD("get_simulation_precision"), &SoftBody3D::get_simulation_precision);
+ ClassDB::bind_method(D_METHOD("set_total_mass", "mass"), &SoftDynamicBody3D::set_total_mass);
+ ClassDB::bind_method(D_METHOD("get_total_mass"), &SoftDynamicBody3D::get_total_mass);
- ClassDB::bind_method(D_METHOD("set_total_mass", "mass"), &SoftBody3D::set_total_mass);
- ClassDB::bind_method(D_METHOD("get_total_mass"), &SoftBody3D::get_total_mass);
+ ClassDB::bind_method(D_METHOD("set_linear_stiffness", "linear_stiffness"), &SoftDynamicBody3D::set_linear_stiffness);
+ ClassDB::bind_method(D_METHOD("get_linear_stiffness"), &SoftDynamicBody3D::get_linear_stiffness);
- ClassDB::bind_method(D_METHOD("set_linear_stiffness", "linear_stiffness"), &SoftBody3D::set_linear_stiffness);
- ClassDB::bind_method(D_METHOD("get_linear_stiffness"), &SoftBody3D::get_linear_stiffness);
+ ClassDB::bind_method(D_METHOD("set_pressure_coefficient", "pressure_coefficient"), &SoftDynamicBody3D::set_pressure_coefficient);
+ ClassDB::bind_method(D_METHOD("get_pressure_coefficient"), &SoftDynamicBody3D::get_pressure_coefficient);
- ClassDB::bind_method(D_METHOD("set_pressure_coefficient", "pressure_coefficient"), &SoftBody3D::set_pressure_coefficient);
- ClassDB::bind_method(D_METHOD("get_pressure_coefficient"), &SoftBody3D::get_pressure_coefficient);
+ ClassDB::bind_method(D_METHOD("set_damping_coefficient", "damping_coefficient"), &SoftDynamicBody3D::set_damping_coefficient);
+ ClassDB::bind_method(D_METHOD("get_damping_coefficient"), &SoftDynamicBody3D::get_damping_coefficient);
- ClassDB::bind_method(D_METHOD("set_damping_coefficient", "damping_coefficient"), &SoftBody3D::set_damping_coefficient);
- ClassDB::bind_method(D_METHOD("get_damping_coefficient"), &SoftBody3D::get_damping_coefficient);
+ ClassDB::bind_method(D_METHOD("set_drag_coefficient", "drag_coefficient"), &SoftDynamicBody3D::set_drag_coefficient);
+ ClassDB::bind_method(D_METHOD("get_drag_coefficient"), &SoftDynamicBody3D::get_drag_coefficient);
- ClassDB::bind_method(D_METHOD("set_drag_coefficient", "drag_coefficient"), &SoftBody3D::set_drag_coefficient);
- ClassDB::bind_method(D_METHOD("get_drag_coefficient"), &SoftBody3D::get_drag_coefficient);
+ ClassDB::bind_method(D_METHOD("get_point_transform", "point_index"), &SoftDynamicBody3D::get_point_transform);
- ClassDB::bind_method(D_METHOD("set_ray_pickable", "ray_pickable"), &SoftBody3D::set_ray_pickable);
- ClassDB::bind_method(D_METHOD("is_ray_pickable"), &SoftBody3D::is_ray_pickable);
+ ClassDB::bind_method(D_METHOD("set_point_pinned", "point_index", "pinned", "attachment_path"), &SoftDynamicBody3D::pin_point, DEFVAL(NodePath()));
+ ClassDB::bind_method(D_METHOD("is_point_pinned", "point_index"), &SoftDynamicBody3D::is_point_pinned);
+
+ ClassDB::bind_method(D_METHOD("set_ray_pickable", "ray_pickable"), &SoftDynamicBody3D::set_ray_pickable);
+ ClassDB::bind_method(D_METHOD("is_ray_pickable"), &SoftDynamicBody3D::is_ray_pickable);
ADD_GROUP("Collision", "collision_");
ADD_PROPERTY(PropertyInfo(Variant::INT, "collision_layer", PROPERTY_HINT_LAYERS_3D_PHYSICS), "set_collision_layer", "get_collision_layer");
@@ -364,24 +367,29 @@ void SoftBody3D::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "drag_coefficient", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_drag_coefficient", "get_drag_coefficient");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "ray_pickable"), "set_ray_pickable", "is_ray_pickable");
+
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "disable_mode", PROPERTY_HINT_ENUM, "Remove,KeepActive"), "set_disable_mode", "get_disable_mode");
+
+ BIND_ENUM_CONSTANT(DISABLE_MODE_REMOVE);
+ BIND_ENUM_CONSTANT(DISABLE_MODE_KEEP_ACTIVE);
}
-TypedArray<String> SoftBody3D::get_configuration_warnings() const {
+TypedArray<String> SoftDynamicBody3D::get_configuration_warnings() const {
TypedArray<String> warnings = Node::get_configuration_warnings();
- if (get_mesh().is_null()) {
- warnings.push_back(TTR("This body will be ignored until you set a mesh."));
+ if (mesh.is_null()) {
+ warnings.push_back(RTR("This body will be ignored until you set a mesh."));
}
- Transform t = get_transform();
- if ((ABS(t.basis.get_axis(0).length() - 1.0) > 0.05 || ABS(t.basis.get_axis(1).length() - 1.0) > 0.05 || ABS(t.basis.get_axis(2).length() - 1.0) > 0.05)) {
- warnings.push_back(TTR("Size changes to SoftBody3D will be overridden by the physics engine when running.\nChange the size in children collision shapes instead."));
+ 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 SoftDynamicBody3D will be overridden by the physics engine when running.\nChange the size in children collision shapes instead."));
}
return warnings;
}
-void SoftBody3D::_update_physics_server() {
+void SoftDynamicBody3D::_update_physics_server() {
if (!simulation_started) {
return;
}
@@ -397,161 +405,187 @@ void SoftBody3D::_update_physics_server() {
}
}
-void SoftBody3D::_draw_soft_mesh() {
- if (get_mesh().is_null()) {
+void SoftDynamicBody3D::_draw_soft_mesh() {
+ if (mesh.is_null()) {
return;
}
- if (!rendering_server_handler.is_ready()) {
- rendering_server_handler.prepare(get_mesh()->get_rid(), 0);
+ RID mesh_rid = mesh->get_rid();
+ if (owned_mesh != mesh_rid) {
+ _become_mesh_owner();
+ mesh_rid = mesh->get_rid();
+ PhysicsServer3D::get_singleton()->soft_body_set_mesh(physics_rid, mesh_rid);
+ }
+
+ if (!rendering_server_handler->is_ready(mesh_rid)) {
+ rendering_server_handler->prepare(mesh_rid, 0);
/// Necessary in order to render the mesh correctly (Soft body nodes are in global space)
simulation_started = true;
- call_deferred("set_as_top_level", true);
- call_deferred("set_transform", Transform());
+ call_deferred(SNAME("set_as_top_level"), true);
+ call_deferred(SNAME("set_transform"), Transform3D());
}
_update_physics_server();
- rendering_server_handler.open();
- PhysicsServer3D::get_singleton()->soft_body_update_rendering_server(physics_rid, &rendering_server_handler);
- rendering_server_handler.close();
+ rendering_server_handler->open();
+ PhysicsServer3D::get_singleton()->soft_body_update_rendering_server(physics_rid, rendering_server_handler);
+ rendering_server_handler->close();
- rendering_server_handler.commit_changes();
+ rendering_server_handler->commit_changes();
}
-void SoftBody3D::prepare_physics_server() {
+void SoftDynamicBody3D::_prepare_physics_server() {
+#ifdef TOOLS_ENABLED
if (Engine::get_singleton()->is_editor_hint()) {
- if (get_mesh().is_valid()) {
- PhysicsServer3D::get_singleton()->soft_body_set_mesh(physics_rid, get_mesh());
+ if (mesh.is_valid()) {
+ PhysicsServer3D::get_singleton()->soft_body_set_mesh(physics_rid, mesh->get_rid());
} else {
- PhysicsServer3D::get_singleton()->soft_body_set_mesh(physics_rid, nullptr);
+ PhysicsServer3D::get_singleton()->soft_body_set_mesh(physics_rid, RID());
}
return;
}
+#endif
- if (get_mesh().is_valid()) {
- become_mesh_owner();
- PhysicsServer3D::get_singleton()->soft_body_set_mesh(physics_rid, get_mesh());
- RS::get_singleton()->connect("frame_pre_draw", callable_mp(this, &SoftBody3D::_draw_soft_mesh));
+ if (mesh.is_valid() && (is_enabled() || (disable_mode != DISABLE_MODE_REMOVE))) {
+ RID mesh_rid = mesh->get_rid();
+ if (owned_mesh != mesh_rid) {
+ _become_mesh_owner();
+ mesh_rid = mesh->get_rid();
+ }
+ PhysicsServer3D::get_singleton()->soft_body_set_mesh(physics_rid, mesh_rid);
+ RS::get_singleton()->connect("frame_pre_draw", callable_mp(this, &SoftDynamicBody3D::_draw_soft_mesh));
} else {
- PhysicsServer3D::get_singleton()->soft_body_set_mesh(physics_rid, nullptr);
- if (RS::get_singleton()->is_connected("frame_pre_draw", callable_mp(this, &SoftBody3D::_draw_soft_mesh))) {
- RS::get_singleton()->disconnect("frame_pre_draw", callable_mp(this, &SoftBody3D::_draw_soft_mesh));
+ PhysicsServer3D::get_singleton()->soft_body_set_mesh(physics_rid, RID());
+ if (RS::get_singleton()->is_connected("frame_pre_draw", callable_mp(this, &SoftDynamicBody3D::_draw_soft_mesh))) {
+ RS::get_singleton()->disconnect("frame_pre_draw", callable_mp(this, &SoftDynamicBody3D::_draw_soft_mesh));
}
}
}
-void SoftBody3D::become_mesh_owner() {
- if (mesh.is_null()) {
- return;
- }
-
- if (!mesh_owner) {
- mesh_owner = true;
-
- Vector<Ref<Material>> copy_materials;
- copy_materials.append_array(surface_override_materials);
+void SoftDynamicBody3D::_become_mesh_owner() {
+ Vector<Ref<Material>> copy_materials;
+ copy_materials.append_array(surface_override_materials);
- ERR_FAIL_COND(!mesh->get_surface_count());
+ ERR_FAIL_COND(!mesh->get_surface_count());
- // Get current mesh array and create new mesh array with necessary flag for softbody
- Array surface_arrays = mesh->surface_get_arrays(0);
- Array surface_blend_arrays = mesh->surface_get_blend_shape_arrays(0);
- Dictionary surface_lods = mesh->surface_get_lods(0);
- uint32_t surface_format = mesh->surface_get_format(0);
+ // Get current mesh array and create new mesh array with necessary flag for SoftDynamicBody
+ Array surface_arrays = mesh->surface_get_arrays(0);
+ Array surface_blend_arrays = mesh->surface_get_blend_shape_arrays(0);
+ Dictionary surface_lods = mesh->surface_get_lods(0);
+ uint32_t surface_format = mesh->surface_get_format(0);
- surface_format |= Mesh::ARRAY_FLAG_USE_DYNAMIC_UPDATE;
+ surface_format |= Mesh::ARRAY_FLAG_USE_DYNAMIC_UPDATE;
- Ref<ArrayMesh> soft_mesh;
- soft_mesh.instance();
- soft_mesh->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, surface_arrays, surface_blend_arrays, surface_lods, surface_format);
- soft_mesh->surface_set_material(0, mesh->surface_get_material(0));
+ Ref<ArrayMesh> soft_mesh;
+ soft_mesh.instantiate();
+ soft_mesh->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, surface_arrays, surface_blend_arrays, surface_lods, surface_format);
+ soft_mesh->surface_set_material(0, mesh->surface_get_material(0));
- set_mesh(soft_mesh);
+ set_mesh(soft_mesh);
- for (int i = copy_materials.size() - 1; 0 <= i; --i) {
- set_surface_override_material(i, copy_materials[i]);
- }
+ for (int i = copy_materials.size() - 1; 0 <= i; --i) {
+ set_surface_override_material(i, copy_materials[i]);
}
+
+ owned_mesh = soft_mesh->get_rid();
}
-void SoftBody3D::set_collision_mask(uint32_t p_mask) {
+void SoftDynamicBody3D::set_collision_mask(uint32_t p_mask) {
collision_mask = p_mask;
PhysicsServer3D::get_singleton()->soft_body_set_collision_mask(physics_rid, p_mask);
}
-uint32_t SoftBody3D::get_collision_mask() const {
+uint32_t SoftDynamicBody3D::get_collision_mask() const {
return collision_mask;
}
-void SoftBody3D::set_collision_layer(uint32_t p_layer) {
+void SoftDynamicBody3D::set_collision_layer(uint32_t p_layer) {
collision_layer = p_layer;
PhysicsServer3D::get_singleton()->soft_body_set_collision_layer(physics_rid, p_layer);
}
-uint32_t SoftBody3D::get_collision_layer() const {
+uint32_t SoftDynamicBody3D::get_collision_layer() const {
return collision_layer;
}
-void SoftBody3D::set_collision_mask_bit(int p_bit, bool p_value) {
- ERR_FAIL_INDEX_MSG(p_bit, 32, "Collision mask bit must be between 0 and 31 inclusive.");
- uint32_t mask = get_collision_mask();
+void SoftDynamicBody3D::set_collision_layer_value(int p_layer_number, bool p_value) {
+ ERR_FAIL_COND_MSG(p_layer_number < 1, "Collision layer number must be between 1 and 32 inclusive.");
+ ERR_FAIL_COND_MSG(p_layer_number > 32, "Collision layer number must be between 1 and 32 inclusive.");
+ uint32_t collision_layer = get_collision_layer();
if (p_value) {
- mask |= 1 << p_bit;
+ collision_layer |= 1 << (p_layer_number - 1);
} else {
- mask &= ~(1 << p_bit);
+ collision_layer &= ~(1 << (p_layer_number - 1));
}
- set_collision_mask(mask);
+ set_collision_layer(collision_layer);
}
-bool SoftBody3D::get_collision_mask_bit(int p_bit) const {
- ERR_FAIL_INDEX_V_MSG(p_bit, 32, false, "Collision mask bit must be between 0 and 31 inclusive.");
- return get_collision_mask() & (1 << p_bit);
+bool SoftDynamicBody3D::get_collision_layer_value(int p_layer_number) const {
+ ERR_FAIL_COND_V_MSG(p_layer_number < 1, false, "Collision layer number must be between 1 and 32 inclusive.");
+ ERR_FAIL_COND_V_MSG(p_layer_number > 32, false, "Collision layer number must be between 1 and 32 inclusive.");
+ return get_collision_layer() & (1 << (p_layer_number - 1));
}
-void SoftBody3D::set_collision_layer_bit(int p_bit, bool p_value) {
- ERR_FAIL_INDEX_MSG(p_bit, 32, "Collision layer bit must be between 0 and 31 inclusive.");
- uint32_t layer = get_collision_layer();
+void SoftDynamicBody3D::set_collision_mask_value(int p_layer_number, bool p_value) {
+ ERR_FAIL_COND_MSG(p_layer_number < 1, "Collision layer number must be between 1 and 32 inclusive.");
+ ERR_FAIL_COND_MSG(p_layer_number > 32, "Collision layer number must be between 1 and 32 inclusive.");
+ uint32_t mask = get_collision_mask();
if (p_value) {
- layer |= 1 << p_bit;
+ mask |= 1 << (p_layer_number - 1);
} else {
- layer &= ~(1 << p_bit);
+ mask &= ~(1 << (p_layer_number - 1));
}
- set_collision_layer(layer);
+ set_collision_mask(mask);
}
-bool SoftBody3D::get_collision_layer_bit(int p_bit) const {
- ERR_FAIL_INDEX_V_MSG(p_bit, 32, false, "Collision layer bit must be between 0 and 31 inclusive.");
- return get_collision_layer() & (1 << p_bit);
+bool SoftDynamicBody3D::get_collision_mask_value(int p_layer_number) const {
+ ERR_FAIL_COND_V_MSG(p_layer_number < 1, false, "Collision layer number must be between 1 and 32 inclusive.");
+ ERR_FAIL_COND_V_MSG(p_layer_number > 32, false, "Collision layer number must be between 1 and 32 inclusive.");
+ return get_collision_mask() & (1 << (p_layer_number - 1));
}
-void SoftBody3D::set_parent_collision_ignore(const NodePath &p_parent_collision_ignore) {
+void SoftDynamicBody3D::set_disable_mode(DisableMode p_mode) {
+ if (disable_mode == p_mode) {
+ return;
+ }
+
+ disable_mode = p_mode;
+
+ if (mesh.is_valid() && is_inside_tree() && !is_enabled()) {
+ _prepare_physics_server();
+ }
+}
+
+SoftDynamicBody3D::DisableMode SoftDynamicBody3D::get_disable_mode() const {
+ return disable_mode;
+}
+
+void SoftDynamicBody3D::set_parent_collision_ignore(const NodePath &p_parent_collision_ignore) {
parent_collision_ignore = p_parent_collision_ignore;
}
-const NodePath &SoftBody3D::get_parent_collision_ignore() const {
+const NodePath &SoftDynamicBody3D::get_parent_collision_ignore() const {
return parent_collision_ignore;
}
-void SoftBody3D::set_pinned_points_indices(Vector<SoftBody3D::PinnedPoint> p_pinned_points_indices) {
+void SoftDynamicBody3D::set_pinned_points_indices(Vector<SoftDynamicBody3D::PinnedPoint> p_pinned_points_indices) {
pinned_points = p_pinned_points_indices;
for (int i = pinned_points.size() - 1; 0 <= i; --i) {
pin_point(p_pinned_points_indices[i].point_index, true);
}
}
-Vector<SoftBody3D::PinnedPoint> SoftBody3D::get_pinned_points_indices() {
+Vector<SoftDynamicBody3D::PinnedPoint> SoftDynamicBody3D::get_pinned_points_indices() {
return pinned_points;
}
-Array SoftBody3D::get_collision_exceptions() {
+Array SoftDynamicBody3D::get_collision_exceptions() {
List<RID> exceptions;
PhysicsServer3D::get_singleton()->soft_body_get_collision_exceptions(physics_rid, &exceptions);
Array ret;
- for (List<RID>::Element *E = exceptions.front(); E; E = E->next()) {
- RID body = E->get();
+ for (const RID &body : exceptions) {
ObjectID instance_id = PhysicsServer3D::get_singleton()->body_get_object_instance_id(body);
Object *obj = ObjectDB::get_instance(instance_id);
PhysicsBody3D *physics_body = Object::cast_to<PhysicsBody3D>(obj);
@@ -560,77 +594,77 @@ Array SoftBody3D::get_collision_exceptions() {
return ret;
}
-void SoftBody3D::add_collision_exception_with(Node *p_node) {
+void SoftDynamicBody3D::add_collision_exception_with(Node *p_node) {
ERR_FAIL_NULL(p_node);
CollisionObject3D *collision_object = Object::cast_to<CollisionObject3D>(p_node);
ERR_FAIL_COND_MSG(!collision_object, "Collision exception only works between two CollisionObject3Ds.");
PhysicsServer3D::get_singleton()->soft_body_add_collision_exception(physics_rid, collision_object->get_rid());
}
-void SoftBody3D::remove_collision_exception_with(Node *p_node) {
+void SoftDynamicBody3D::remove_collision_exception_with(Node *p_node) {
ERR_FAIL_NULL(p_node);
CollisionObject3D *collision_object = Object::cast_to<CollisionObject3D>(p_node);
ERR_FAIL_COND_MSG(!collision_object, "Collision exception only works between two CollisionObject3Ds.");
PhysicsServer3D::get_singleton()->soft_body_remove_collision_exception(physics_rid, collision_object->get_rid());
}
-int SoftBody3D::get_simulation_precision() {
+int SoftDynamicBody3D::get_simulation_precision() {
return PhysicsServer3D::get_singleton()->soft_body_get_simulation_precision(physics_rid);
}
-void SoftBody3D::set_simulation_precision(int p_simulation_precision) {
+void SoftDynamicBody3D::set_simulation_precision(int p_simulation_precision) {
PhysicsServer3D::get_singleton()->soft_body_set_simulation_precision(physics_rid, p_simulation_precision);
}
-real_t SoftBody3D::get_total_mass() {
+real_t SoftDynamicBody3D::get_total_mass() {
return PhysicsServer3D::get_singleton()->soft_body_get_total_mass(physics_rid);
}
-void SoftBody3D::set_total_mass(real_t p_total_mass) {
+void SoftDynamicBody3D::set_total_mass(real_t p_total_mass) {
PhysicsServer3D::get_singleton()->soft_body_set_total_mass(physics_rid, p_total_mass);
}
-void SoftBody3D::set_linear_stiffness(real_t p_linear_stiffness) {
+void SoftDynamicBody3D::set_linear_stiffness(real_t p_linear_stiffness) {
PhysicsServer3D::get_singleton()->soft_body_set_linear_stiffness(physics_rid, p_linear_stiffness);
}
-real_t SoftBody3D::get_linear_stiffness() {
+real_t SoftDynamicBody3D::get_linear_stiffness() {
return PhysicsServer3D::get_singleton()->soft_body_get_linear_stiffness(physics_rid);
}
-real_t SoftBody3D::get_pressure_coefficient() {
+real_t SoftDynamicBody3D::get_pressure_coefficient() {
return PhysicsServer3D::get_singleton()->soft_body_get_pressure_coefficient(physics_rid);
}
-void SoftBody3D::set_pressure_coefficient(real_t p_pressure_coefficient) {
+void SoftDynamicBody3D::set_pressure_coefficient(real_t p_pressure_coefficient) {
PhysicsServer3D::get_singleton()->soft_body_set_pressure_coefficient(physics_rid, p_pressure_coefficient);
}
-real_t SoftBody3D::get_damping_coefficient() {
+real_t SoftDynamicBody3D::get_damping_coefficient() {
return PhysicsServer3D::get_singleton()->soft_body_get_damping_coefficient(physics_rid);
}
-void SoftBody3D::set_damping_coefficient(real_t p_damping_coefficient) {
+void SoftDynamicBody3D::set_damping_coefficient(real_t p_damping_coefficient) {
PhysicsServer3D::get_singleton()->soft_body_set_damping_coefficient(physics_rid, p_damping_coefficient);
}
-real_t SoftBody3D::get_drag_coefficient() {
+real_t SoftDynamicBody3D::get_drag_coefficient() {
return PhysicsServer3D::get_singleton()->soft_body_get_drag_coefficient(physics_rid);
}
-void SoftBody3D::set_drag_coefficient(real_t p_drag_coefficient) {
+void SoftDynamicBody3D::set_drag_coefficient(real_t p_drag_coefficient) {
PhysicsServer3D::get_singleton()->soft_body_set_drag_coefficient(physics_rid, p_drag_coefficient);
}
-Vector3 SoftBody3D::get_point_transform(int p_point_index) {
+Vector3 SoftDynamicBody3D::get_point_transform(int p_point_index) {
return PhysicsServer3D::get_singleton()->soft_body_get_point_global_position(physics_rid, p_point_index);
}
-void SoftBody3D::pin_point_toggle(int p_point_index) {
+void SoftDynamicBody3D::pin_point_toggle(int p_point_index) {
pin_point(p_point_index, !(-1 != _has_pinned_point(p_point_index)));
}
-void SoftBody3D::pin_point(int p_point_index, bool pin, const NodePath &p_spatial_attachment_path) {
+void SoftDynamicBody3D::pin_point(int p_point_index, bool pin, const NodePath &p_spatial_attachment_path) {
_pin_point_on_physics_server(p_point_index, pin);
if (pin) {
_add_pinned_point(p_point_index, p_spatial_attachment_path);
@@ -639,41 +673,35 @@ void SoftBody3D::pin_point(int p_point_index, bool pin, const NodePath &p_spatia
}
}
-bool SoftBody3D::is_point_pinned(int p_point_index) const {
+bool SoftDynamicBody3D::is_point_pinned(int p_point_index) const {
return -1 != _has_pinned_point(p_point_index);
}
-void SoftBody3D::set_ray_pickable(bool p_ray_pickable) {
+void SoftDynamicBody3D::set_ray_pickable(bool p_ray_pickable) {
ray_pickable = p_ray_pickable;
_update_pickable();
}
-bool SoftBody3D::is_ray_pickable() const {
+bool SoftDynamicBody3D::is_ray_pickable() const {
return ray_pickable;
}
-SoftBody3D::SoftBody3D() :
+SoftDynamicBody3D::SoftDynamicBody3D() :
physics_rid(PhysicsServer3D::get_singleton()->soft_body_create()) {
+ rendering_server_handler = memnew(SoftDynamicBodyRenderingServerHandler);
PhysicsServer3D::get_singleton()->body_attach_object_instance_id(physics_rid, get_instance_id());
}
-SoftBody3D::~SoftBody3D() {
+SoftDynamicBody3D::~SoftDynamicBody3D() {
+ memdelete(rendering_server_handler);
PhysicsServer3D::get_singleton()->free(physics_rid);
}
-void SoftBody3D::reset_softbody_pin() {
- PhysicsServer3D::get_singleton()->soft_body_remove_all_pinned_points(physics_rid);
- const PinnedPoint *pps = pinned_points.ptr();
- for (int i = pinned_points.size() - 1; 0 < i; --i) {
- PhysicsServer3D::get_singleton()->soft_body_pin_point(physics_rid, pps[i].point_index, true);
- }
-}
-
-void SoftBody3D::_make_cache_dirty() {
+void SoftDynamicBody3D::_make_cache_dirty() {
pinned_points_cache_dirty = true;
}
-void SoftBody3D::_update_cache_pin_points_datas() {
+void SoftDynamicBody3D::_update_cache_pin_points_datas() {
if (!pinned_points_cache_dirty) {
return;
}
@@ -686,17 +714,17 @@ void SoftBody3D::_update_cache_pin_points_datas() {
w[i].spatial_attachment = Object::cast_to<Node3D>(get_node(w[i].spatial_attachment_path));
}
if (!w[i].spatial_attachment) {
- ERR_PRINT("Node3D node not defined in the pinned point, this is undefined behavior for SoftBody3D!");
+ ERR_PRINT("Node3D node not defined in the pinned point, this is undefined behavior for SoftDynamicBody3D!");
}
}
}
-void SoftBody3D::_pin_point_on_physics_server(int p_point_index, bool pin) {
+void SoftDynamicBody3D::_pin_point_on_physics_server(int p_point_index, bool pin) {
PhysicsServer3D::get_singleton()->soft_body_pin_point(physics_rid, p_point_index, pin);
}
-void SoftBody3D::_add_pinned_point(int p_point_index, const NodePath &p_spatial_attachment_path) {
- SoftBody3D::PinnedPoint *pinned_point;
+void SoftDynamicBody3D::_add_pinned_point(int p_point_index, const NodePath &p_spatial_attachment_path) {
+ SoftDynamicBody3D::PinnedPoint *pinned_point;
if (-1 == _get_pinned_point(p_point_index, pinned_point)) {
// Create new
PinnedPoint pp;
@@ -721,7 +749,7 @@ void SoftBody3D::_add_pinned_point(int p_point_index, const NodePath &p_spatial_
}
}
-void SoftBody3D::_reset_points_offsets() {
+void SoftDynamicBody3D::_reset_points_offsets() {
if (!Engine::get_singleton()->is_editor_hint()) {
return;
}
@@ -743,25 +771,25 @@ void SoftBody3D::_reset_points_offsets() {
}
}
-void SoftBody3D::_remove_pinned_point(int p_point_index) {
+void SoftDynamicBody3D::_remove_pinned_point(int p_point_index) {
const int id(_has_pinned_point(p_point_index));
if (-1 != id) {
- pinned_points.remove(id);
+ pinned_points.remove_at(id);
}
}
-int SoftBody3D::_get_pinned_point(int p_point_index, SoftBody3D::PinnedPoint *&r_point) const {
+int SoftDynamicBody3D::_get_pinned_point(int p_point_index, SoftDynamicBody3D::PinnedPoint *&r_point) const {
const int id = _has_pinned_point(p_point_index);
if (-1 == id) {
r_point = nullptr;
return -1;
} else {
- r_point = const_cast<SoftBody3D::PinnedPoint *>(&pinned_points.ptr()[id]);
+ r_point = const_cast<SoftDynamicBody3D::PinnedPoint *>(&pinned_points.ptr()[id]);
return id;
}
}
-int SoftBody3D::_has_pinned_point(int p_point_index) const {
+int SoftDynamicBody3D::_has_pinned_point(int p_point_index) const {
const PinnedPoint *r = pinned_points.ptr();
for (int i = pinned_points.size() - 1; 0 <= i; --i) {
if (p_point_index == r[i].point_index) {
diff --git a/scene/3d/soft_body_3d.h b/scene/3d/soft_dynamic_body_3d.h
index 0d0d39d48f..e11e5c73df 100644
--- a/scene/3d/soft_body_3d.h
+++ b/scene/3d/soft_dynamic_body_3d.h
@@ -1,12 +1,12 @@
/*************************************************************************/
-/* soft_body_3d.h */
+/* soft_dynamic_body_3d.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -28,16 +28,16 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#ifndef SOFT_PHYSICS_BODY_H
-#define SOFT_PHYSICS_BODY_H
+#ifndef SOFT_DYNAMIC_BODY_H
+#define SOFT_DYNAMIC_BODY_H
#include "scene/3d/mesh_instance_3d.h"
#include "servers/physics_server_3d.h"
-class SoftBody3D;
+class SoftDynamicBody3D;
-class SoftBodyRenderingServerHandler : public RenderingServerHandler {
- friend class SoftBody3D;
+class SoftDynamicBodyRenderingServerHandler : public PhysicsServer3DRenderingServerHandler {
+ friend class SoftDynamicBody3D;
RID mesh;
int surface = 0;
@@ -49,8 +49,8 @@ class SoftBodyRenderingServerHandler : public RenderingServerHandler {
uint8_t *write_buffer = nullptr;
private:
- SoftBodyRenderingServerHandler();
- bool is_ready() { return mesh.is_valid(); }
+ SoftDynamicBodyRenderingServerHandler();
+ bool is_ready(RID p_mesh_rid) const { return mesh.is_valid() && mesh == p_mesh_rid; }
void prepare(RID p_mesh_rid, int p_surface);
void clear();
void open();
@@ -63,10 +63,15 @@ public:
void set_aabb(const AABB &p_aabb) override;
};
-class SoftBody3D : public MeshInstance3D {
- GDCLASS(SoftBody3D, MeshInstance3D);
+class SoftDynamicBody3D : public MeshInstance3D {
+ GDCLASS(SoftDynamicBody3D, MeshInstance3D);
public:
+ enum DisableMode {
+ DISABLE_MODE_REMOVE,
+ DISABLE_MODE_KEEP_ACTIVE,
+ };
+
struct PinnedPoint {
int point_index = -1;
NodePath spatial_attachment_path;
@@ -75,15 +80,17 @@ public:
PinnedPoint();
PinnedPoint(const PinnedPoint &obj_tocopy);
- PinnedPoint &operator=(const PinnedPoint &obj);
+ void operator=(const PinnedPoint &obj);
};
private:
- SoftBodyRenderingServerHandler rendering_server_handler;
+ SoftDynamicBodyRenderingServerHandler *rendering_server_handler = nullptr;
RID physics_rid;
- bool mesh_owner = false;
+ DisableMode disable_mode = DISABLE_MODE_REMOVE;
+
+ RID owned_mesh;
uint32_t collision_mask = 1;
uint32_t collision_layer = 1;
NodePath parent_collision_ignore;
@@ -99,7 +106,11 @@ private:
void _update_pickable();
- void _softbody_changed();
+ void _update_physics_server();
+ void _draw_soft_mesh();
+
+ void _prepare_physics_server();
+ void _become_mesh_owner();
protected:
bool _set(const StringName &p_name, const Variant &p_value);
@@ -115,14 +126,7 @@ protected:
TypedArray<String> get_configuration_warnings() const override;
-protected:
- void _update_physics_server();
- void _draw_soft_mesh();
-
public:
- void prepare_physics_server();
- void become_mesh_owner();
-
RID get_physics_rid() const { return physics_rid; }
void set_collision_mask(uint32_t p_mask);
@@ -131,11 +135,14 @@ public:
void set_collision_layer(uint32_t p_layer);
uint32_t get_collision_layer() const;
- void set_collision_mask_bit(int p_bit, bool p_value);
- bool get_collision_mask_bit(int p_bit) const;
+ void set_collision_layer_value(int p_layer_number, bool p_value);
+ bool get_collision_layer_value(int p_layer_number) const;
- void set_collision_layer_bit(int p_bit, bool p_value);
- bool get_collision_layer_bit(int p_bit) const;
+ void set_collision_mask_value(int p_layer_number, bool p_value);
+ bool get_collision_mask_value(int p_layer_number) const;
+
+ void set_disable_mode(DisableMode p_mode);
+ DisableMode get_disable_mode() const;
void set_parent_collision_ignore(const NodePath &p_parent_collision_ignore);
const NodePath &get_parent_collision_ignore() const;
@@ -174,12 +181,10 @@ public:
void set_ray_pickable(bool p_ray_pickable);
bool is_ray_pickable() const;
- SoftBody3D();
- ~SoftBody3D();
+ SoftDynamicBody3D();
+ ~SoftDynamicBody3D();
private:
- void reset_softbody_pin();
-
void _make_cache_dirty();
void _update_cache_pin_points_datas();
@@ -192,4 +197,6 @@ private:
int _has_pinned_point(int p_point_index) const;
};
-#endif // SOFT_PHYSICS_BODY_H
+VARIANT_ENUM_CAST(SoftDynamicBody3D::DisableMode);
+
+#endif // SOFT_DYNAMIC_BODY_H
diff --git a/scene/3d/spring_arm_3d.cpp b/scene/3d/spring_arm_3d.cpp
index 9518b47696..230801bd52 100644
--- a/scene/3d/spring_arm_3d.cpp
+++ b/scene/3d/spring_arm_3d.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -30,26 +30,25 @@
#include "spring_arm_3d.h"
-#include "core/config/engine.h"
-#include "scene/3d/collision_object_3d.h"
-#include "scene/resources/sphere_shape_3d.h"
-#include "servers/physics_server_3d.h"
+#include "scene/3d/camera_3d.h"
void SpringArm3D::_notification(int p_what) {
switch (p_what) {
- case NOTIFICATION_ENTER_TREE:
+ case NOTIFICATION_ENTER_TREE: {
if (!Engine::get_singleton()->is_editor_hint()) {
set_physics_process_internal(true);
}
- break;
- case NOTIFICATION_EXIT_TREE:
+ } break;
+
+ case NOTIFICATION_EXIT_TREE: {
if (!Engine::get_singleton()->is_editor_hint()) {
set_physics_process_internal(false);
}
- break;
- case NOTIFICATION_INTERNAL_PHYSICS_PROCESS:
+ } break;
+
+ case NOTIFICATION_INTERNAL_PHYSICS_PROCESS: {
process_spring();
- break;
+ } break;
}
}
@@ -84,7 +83,7 @@ real_t SpringArm3D::get_length() const {
void SpringArm3D::set_length(real_t p_length) {
if (is_inside_tree() && (Engine::get_singleton()->is_editor_hint() || get_tree()->is_debugging_collisions_hint())) {
- update_gizmo();
+ update_gizmos();
}
spring_length = p_length;
@@ -138,29 +137,65 @@ void SpringArm3D::process_spring() {
Vector3 motion;
const Vector3 cast_direction(get_global_transform().basis.xform(Vector3(0, 0, 1)));
+ motion = Vector3(cast_direction * (spring_length));
+
if (shape.is_null()) {
- motion = Vector3(cast_direction * (spring_length));
- PhysicsDirectSpaceState3D::RayResult r;
- bool intersected = get_world_3d()->get_direct_space_state()->intersect_ray(get_global_transform().origin, get_global_transform().origin + motion, r, excluded_objects, mask);
- if (intersected) {
- real_t dist = get_global_transform().origin.distance_to(r.position);
- dist -= margin;
- motion_delta = dist / (spring_length);
+ Camera3D *camera = nullptr;
+ for (int i = get_child_count() - 1; 0 <= i; --i) {
+ camera = Object::cast_to<Camera3D>(get_child(i));
+ if (camera) {
+ break;
+ }
+ }
+
+ if (camera != nullptr) {
+ //use camera rotation, but spring arm position
+ Transform3D base_transform = camera->get_global_transform();
+ base_transform.origin = get_global_transform().origin;
+
+ PhysicsDirectSpaceState3D::ShapeParameters shape_params;
+ shape_params.shape_rid = camera->get_pyramid_shape_rid();
+ shape_params.transform = base_transform;
+ shape_params.motion = motion;
+ shape_params.exclude = excluded_objects;
+ shape_params.collision_mask = mask;
+
+ get_world_3d()->get_direct_space_state()->cast_motion(shape_params, motion_delta, motion_delta_unsafe);
+ } else {
+ PhysicsDirectSpaceState3D::RayParameters ray_params;
+ ray_params.from = get_global_transform().origin;
+ ray_params.to = get_global_transform().origin + motion;
+ ray_params.exclude = excluded_objects;
+ ray_params.collision_mask = mask;
+
+ PhysicsDirectSpaceState3D::RayResult r;
+ bool intersected = get_world_3d()->get_direct_space_state()->intersect_ray(ray_params, r);
+ if (intersected) {
+ real_t dist = get_global_transform().origin.distance_to(r.position);
+ dist -= margin;
+ motion_delta = dist / (spring_length);
+ }
}
} else {
- motion = Vector3(cast_direction * spring_length);
- get_world_3d()->get_direct_space_state()->cast_motion(shape->get_rid(), get_global_transform(), motion, 0, motion_delta, motion_delta_unsafe, excluded_objects, mask);
+ PhysicsDirectSpaceState3D::ShapeParameters shape_params;
+ shape_params.shape_rid = shape->get_rid();
+ shape_params.transform = get_global_transform();
+ shape_params.motion = motion;
+ shape_params.exclude = excluded_objects;
+ shape_params.collision_mask = mask;
+
+ get_world_3d()->get_direct_space_state()->cast_motion(shape_params, motion_delta, motion_delta_unsafe);
}
current_spring_length = spring_length * motion_delta;
- Transform childs_transform;
- childs_transform.origin = get_global_transform().origin + cast_direction * (spring_length * motion_delta);
+ Transform3D child_transform;
+ child_transform.origin = get_global_transform().origin + cast_direction * (spring_length * motion_delta);
for (int i = get_child_count() - 1; 0 <= i; --i) {
Node3D *child = Object::cast_to<Node3D>(get_child(i));
if (child) {
- childs_transform.basis = child->get_global_transform().basis;
- child->set_global_transform(childs_transform);
+ child_transform.basis = child->get_global_transform().basis;
+ child->set_global_transform(child_transform);
}
}
}
diff --git a/scene/3d/spring_arm_3d.h b/scene/3d/spring_arm_3d.h
index 63505ab9d3..b247ea1707 100644
--- a/scene/3d/spring_arm_3d.h
+++ b/scene/3d/spring_arm_3d.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
diff --git a/scene/3d/sprite_3d.cpp b/scene/3d/sprite_3d.cpp
index 33b8b488c6..8cb5081047 100644
--- a/scene/3d/sprite_3d.cpp
+++ b/scene/3d/sprite_3d.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -60,29 +60,31 @@ void SpriteBase3D::_propagate_color_changed() {
color_dirty = true;
_queue_update();
- for (List<SpriteBase3D *>::Element *E = children.front(); E; E = E->next()) {
- E->get()->_propagate_color_changed();
+ for (SpriteBase3D *&E : children) {
+ E->_propagate_color_changed();
}
}
void SpriteBase3D::_notification(int p_what) {
- if (p_what == NOTIFICATION_ENTER_TREE) {
- if (!pending_update) {
- _im_update();
- }
+ switch (p_what) {
+ case NOTIFICATION_ENTER_TREE: {
+ if (!pending_update) {
+ _im_update();
+ }
- parent_sprite = Object::cast_to<SpriteBase3D>(get_parent());
- if (parent_sprite) {
- pI = parent_sprite->children.push_back(this);
- }
- }
+ parent_sprite = Object::cast_to<SpriteBase3D>(get_parent());
+ if (parent_sprite) {
+ pI = parent_sprite->children.push_back(this);
+ }
+ } break;
- if (p_what == NOTIFICATION_EXIT_TREE) {
- if (parent_sprite) {
- parent_sprite->children.erase(pI);
- pI = nullptr;
- parent_sprite = nullptr;
- }
+ case NOTIFICATION_EXIT_TREE: {
+ if (parent_sprite) {
+ parent_sprite->children.erase(pI);
+ pI = nullptr;
+ parent_sprite = nullptr;
+ }
+ } break;
}
}
@@ -132,22 +134,23 @@ Color SpriteBase3D::get_modulate() const {
return modulate;
}
-void SpriteBase3D::set_pixel_size(float p_amount) {
- pixel_size = p_amount;
+void SpriteBase3D::set_render_priority(int p_priority) {
+ ERR_FAIL_COND(p_priority < RS::MATERIAL_RENDER_PRIORITY_MIN || p_priority > RS::MATERIAL_RENDER_PRIORITY_MAX);
+ render_priority = p_priority;
_queue_update();
}
-float SpriteBase3D::get_pixel_size() const {
- return pixel_size;
+int SpriteBase3D::get_render_priority() const {
+ return render_priority;
}
-void SpriteBase3D::set_opacity(float p_amount) {
- opacity = p_amount;
+void SpriteBase3D::set_pixel_size(real_t p_amount) {
+ pixel_size = p_amount;
_queue_update();
}
-float SpriteBase3D::get_opacity() const {
- return opacity;
+real_t SpriteBase3D::get_pixel_size() const {
+ return pixel_size;
}
void SpriteBase3D::set_axis(Vector3::Axis p_axis) {
@@ -164,6 +167,8 @@ void SpriteBase3D::_im_update() {
_draw();
pending_update = false;
+
+ //texture->draw_rect_region(ci,dst_rect,src_rect,modulate);
}
void SpriteBase3D::_queue_update() {
@@ -172,7 +177,7 @@ void SpriteBase3D::_queue_update() {
}
triangle_mesh.unref();
- update_gizmo();
+ update_gizmos();
pending_update = true;
call_deferred(SceneStringNames::get_singleton()->_im_update);
@@ -182,10 +187,6 @@ AABB SpriteBase3D::get_aabb() const {
return aabb;
}
-Vector<Face3> SpriteBase3D::get_faces(uint32_t p_usage_flags) const {
- return Vector<Face3>();
-}
-
Ref<TriangleMesh> SpriteBase3D::generate_triangle_mesh() const {
if (triangle_mesh.is_valid()) {
return triangle_mesh;
@@ -201,9 +202,10 @@ Ref<TriangleMesh> SpriteBase3D::generate_triangle_mesh() const {
return Ref<TriangleMesh>();
}
- float pixel_size = get_pixel_size();
+ real_t pixel_size = get_pixel_size();
Vector2 vertices[4] = {
+
(final_rect.position + Vector2(0, final_rect.size.y)) * pixel_size,
(final_rect.position + final_rect.size) * pixel_size,
(final_rect.position + Vector2(final_rect.size.x, 0)) * pixel_size,
@@ -276,6 +278,17 @@ StandardMaterial3D::BillboardMode SpriteBase3D::get_billboard_mode() const {
return billboard_mode;
}
+void SpriteBase3D::set_texture_filter(StandardMaterial3D::TextureFilter p_filter) {
+ if (texture_filter != p_filter) {
+ texture_filter = p_filter;
+ _queue_update();
+ }
+}
+
+StandardMaterial3D::TextureFilter SpriteBase3D::get_texture_filter() const {
+ return texture_filter;
+}
+
void SpriteBase3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_centered", "centered"), &SpriteBase3D::set_centered);
ClassDB::bind_method(D_METHOD("is_centered"), &SpriteBase3D::is_centered);
@@ -292,8 +305,8 @@ void SpriteBase3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_modulate", "modulate"), &SpriteBase3D::set_modulate);
ClassDB::bind_method(D_METHOD("get_modulate"), &SpriteBase3D::get_modulate);
- ClassDB::bind_method(D_METHOD("set_opacity", "opacity"), &SpriteBase3D::set_opacity);
- ClassDB::bind_method(D_METHOD("get_opacity"), &SpriteBase3D::get_opacity);
+ ClassDB::bind_method(D_METHOD("set_render_priority", "priority"), &SpriteBase3D::set_render_priority);
+ ClassDB::bind_method(D_METHOD("get_render_priority"), &SpriteBase3D::get_render_priority);
ClassDB::bind_method(D_METHOD("set_pixel_size", "pixel_size"), &SpriteBase3D::set_pixel_size);
ClassDB::bind_method(D_METHOD("get_pixel_size"), &SpriteBase3D::get_pixel_size);
@@ -310,15 +323,20 @@ void SpriteBase3D::_bind_methods() {
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);
+ ClassDB::bind_method(D_METHOD("set_texture_filter", "mode"), &SpriteBase3D::set_texture_filter);
+ ClassDB::bind_method(D_METHOD("get_texture_filter"), &SpriteBase3D::get_texture_filter);
+
ClassDB::bind_method(D_METHOD("get_item_rect"), &SpriteBase3D::get_item_rect);
ClassDB::bind_method(D_METHOD("generate_triangle_mesh"), &SpriteBase3D::generate_triangle_mesh);
+ ClassDB::bind_method(D_METHOD("_queue_update"), &SpriteBase3D::_queue_update);
+ ClassDB::bind_method(D_METHOD("_im_update"), &SpriteBase3D::_im_update);
+
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "centered"), "set_centered", "is_centered");
ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "offset"), "set_offset", "get_offset");
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");
ADD_PROPERTY(PropertyInfo(Variant::COLOR, "modulate"), "set_modulate", "get_modulate");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "opacity", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_opacity", "get_opacity");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "pixel_size", PROPERTY_HINT_RANGE, "0.0001,128,0.0001"), "set_pixel_size", "get_pixel_size");
ADD_PROPERTY(PropertyInfo(Variant::INT, "axis", PROPERTY_HINT_ENUM, "X-Axis,Y-Axis,Z-Axis"), "set_axis", "get_axis");
ADD_GROUP("Flags", "");
@@ -326,11 +344,17 @@ void SpriteBase3D::_bind_methods() {
ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "transparent"), "set_draw_flag", "get_draw_flag", FLAG_TRANSPARENT);
ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "shaded"), "set_draw_flag", "get_draw_flag", FLAG_SHADED);
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, "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");
BIND_ENUM_CONSTANT(FLAG_TRANSPARENT);
BIND_ENUM_CONSTANT(FLAG_SHADED);
BIND_ENUM_CONSTANT(FLAG_DOUBLE_SIDED);
+ BIND_ENUM_CONSTANT(FLAG_DISABLE_DEPTH_TEST);
+ BIND_ENUM_CONSTANT(FLAG_FIXED_SIZE);
BIND_ENUM_CONSTANT(FLAG_MAX);
BIND_ENUM_CONSTANT(ALPHA_CUT_DISABLED);
@@ -343,21 +367,89 @@ SpriteBase3D::SpriteBase3D() {
flags[i] = i == FLAG_TRANSPARENT || i == FLAG_DOUBLE_SIDED;
}
- immediate = RenderingServer::get_singleton()->immediate_create();
- set_base(immediate);
+ material = RenderingServer::get_singleton()->material_create();
+ // Set defaults for material, names need to match up those in StandardMaterial3D
+ RS::get_singleton()->material_set_param(material, "albedo", Color(1, 1, 1, 1));
+ RS::get_singleton()->material_set_param(material, "specular", 0.5);
+ RS::get_singleton()->material_set_param(material, "metallic", 0.0);
+ RS::get_singleton()->material_set_param(material, "roughness", 1.0);
+ RS::get_singleton()->material_set_param(material, "uv1_offset", Vector3(0, 0, 0));
+ 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.98);
+
+ mesh = RenderingServer::get_singleton()->mesh_create();
+
+ PackedVector3Array mesh_vertices;
+ PackedVector3Array mesh_normals;
+ PackedFloat32Array mesh_tangents;
+ PackedColorArray mesh_colors;
+ PackedVector2Array mesh_uvs;
+ PackedInt32Array indices;
+
+ mesh_vertices.resize(4);
+ mesh_normals.resize(4);
+ mesh_tangents.resize(16);
+ mesh_colors.resize(4);
+ mesh_uvs.resize(4);
+
+ // create basic mesh and store format information
+ for (int i = 0; i < 4; i++) {
+ mesh_normals.write[i] = Vector3(0.0, 0.0, 0.0);
+ mesh_tangents.write[i * 4 + 0] = 0.0;
+ mesh_tangents.write[i * 4 + 1] = 0.0;
+ mesh_tangents.write[i * 4 + 2] = 0.0;
+ mesh_tangents.write[i * 4 + 3] = 0.0;
+ mesh_colors.write[i] = Color(1.0, 1.0, 1.0, 1.0);
+ mesh_uvs.write[i] = Vector2(0.0, 0.0);
+ mesh_vertices.write[i] = Vector3(0.0, 0.0, 0.0);
+ }
+
+ indices.resize(6);
+ indices.write[0] = 0;
+ indices.write[1] = 1;
+ indices.write[2] = 2;
+ indices.write[3] = 0;
+ indices.write[4] = 2;
+ indices.write[5] = 3;
+
+ Array mesh_array;
+ mesh_array.resize(RS::ARRAY_MAX);
+ mesh_array[RS::ARRAY_VERTEX] = mesh_vertices;
+ mesh_array[RS::ARRAY_NORMAL] = mesh_normals;
+ mesh_array[RS::ARRAY_TANGENT] = mesh_tangents;
+ mesh_array[RS::ARRAY_COLOR] = mesh_colors;
+ mesh_array[RS::ARRAY_TEX_UV] = mesh_uvs;
+ mesh_array[RS::ARRAY_INDEX] = indices;
+
+ RS::SurfaceData sd;
+ RS::get_singleton()->mesh_create_surface_data_from_arrays(&sd, RS::PRIMITIVE_TRIANGLES, mesh_array);
+
+ mesh_surface_format = sd.format;
+ vertex_buffer = sd.vertex_data;
+ attribute_buffer = sd.attribute_data;
+
+ sd.material = material;
+
+ RS::get_singleton()->mesh_surface_make_offsets_from_format(sd.format, sd.vertex_count, sd.index_count, mesh_surface_offsets, vertex_stride, attrib_stride, skin_stride);
+ RS::get_singleton()->mesh_add_surface(mesh, sd);
+ set_base(mesh);
}
SpriteBase3D::~SpriteBase3D() {
- RenderingServer::get_singleton()->free(immediate);
+ RenderingServer::get_singleton()->free(mesh);
+ RenderingServer::get_singleton()->free(material);
}
///////////////////////////////////////////
void Sprite3D::_draw() {
- RID immediate = get_immediate();
-
- RS::get_singleton()->immediate_clear(immediate);
+ if (get_base() != get_mesh()) {
+ set_base(get_mesh());
+ }
if (!texture.is_valid()) {
+ set_base(RID());
return;
}
Vector2 tsize = texture->get_size();
@@ -366,7 +458,7 @@ void Sprite3D::_draw() {
}
Rect2 base_rect;
- if (region_enabled) {
+ if (region) {
base_rect = region_rect;
} else {
base_rect = Rect2(0, 0, texture->get_width(), texture->get_height());
@@ -394,11 +486,11 @@ void Sprite3D::_draw() {
}
Color color = _get_color_accum();
- color.a *= get_opacity();
- float pixel_size = get_pixel_size();
+ real_t pixel_size = get_pixel_size();
Vector2 vertices[4] = {
+
(final_rect.position + Vector2(0, final_rect.size.y)) * pixel_size,
(final_rect.position + final_rect.size) * pixel_size,
(final_rect.position + Vector2(final_rect.size.x, 0)) * pixel_size,
@@ -426,6 +518,7 @@ void Sprite3D::_draw() {
SWAP(uvs[0], uvs[1]);
SWAP(uvs[2], uvs[3]);
}
+
if (is_flipped_v()) {
SWAP(uvs[0], uvs[3]);
SWAP(uvs[1], uvs[2]);
@@ -442,11 +535,6 @@ void Sprite3D::_draw() {
tangent = Plane(1, 0, 0, 1);
}
- RID mat = StandardMaterial3D::get_material_rid_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);
- RS::get_singleton()->immediate_set_material(immediate, mat);
-
- RS::get_singleton()->immediate_begin(immediate, RS::PRIMITIVE_TRIANGLES, texture->get_rid());
-
int x_axis = ((axis + 1) % 3);
int y_axis = ((axis + 2) % 3);
@@ -466,31 +554,84 @@ void Sprite3D::_draw() {
AABB aabb;
- for (int i = 0; i < 6; i++) {
- static const int index[6] = { 0, 1, 2, 0, 2, 3 };
+ // Everything except position and UV is compressed
+ uint8_t *vertex_write_buffer = vertex_buffer.ptrw();
+ uint8_t *attribute_write_buffer = attribute_buffer.ptrw();
+
+ uint32_t v_normal;
+ {
+ Vector3 n = normal * Vector3(0.5, 0.5, 0.5) + Vector3(0.5, 0.5, 0.5);
+
+ 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;
+
+ v_normal = value;
+ }
+ uint32_t v_tangent;
+ {
+ Plane t = tangent;
+ 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;
+ }
+ v_tangent = value;
+ }
- RS::get_singleton()->immediate_normal(immediate, normal);
- RS::get_singleton()->immediate_tangent(immediate, tangent);
- RS::get_singleton()->immediate_color(immediate, color);
- RS::get_singleton()->immediate_uv(immediate, uvs[index[i]]);
+ uint8_t v_color[4] = {
+ uint8_t(CLAMP(color.r * 255.0, 0.0, 255.0)),
+ uint8_t(CLAMP(color.g * 255.0, 0.0, 255.0)),
+ uint8_t(CLAMP(color.b * 255.0, 0.0, 255.0)),
+ uint8_t(CLAMP(color.a * 255.0, 0.0, 255.0))
+ };
+ for (int i = 0; i < 4; i++) {
Vector3 vtx;
- vtx[x_axis] = vertices[index[i]][0];
- vtx[y_axis] = vertices[index[i]][1];
- RS::get_singleton()->immediate_vertex(immediate, vtx);
+ vtx[x_axis] = vertices[i][0];
+ vtx[y_axis] = vertices[i][1];
if (i == 0) {
aabb.position = vtx;
aabb.size = Vector3();
} else {
aabb.expand_to(vtx);
}
+
+ float v_uv[2] = { (float)uvs[i].x, (float)uvs[i].y };
+ memcpy(&attribute_write_buffer[i * attrib_stride + mesh_surface_offsets[RS::ARRAY_TEX_UV]], v_uv, 8);
+
+ float v_vertex[3] = { (float)vtx.x, (float)vtx.y, (float)vtx.z };
+
+ memcpy(&vertex_write_buffer[i * vertex_stride + mesh_surface_offsets[RS::ARRAY_VERTEX]], &v_vertex, sizeof(float) * 3);
+ memcpy(&vertex_write_buffer[i * vertex_stride + mesh_surface_offsets[RS::ARRAY_NORMAL]], &v_normal, 4);
+ memcpy(&vertex_write_buffer[i * vertex_stride + mesh_surface_offsets[RS::ARRAY_TANGENT]], &v_tangent, 4);
+ memcpy(&attribute_write_buffer[i * attrib_stride + mesh_surface_offsets[RS::ARRAY_COLOR]], v_color, 4);
}
+
+ RID mesh = get_mesh();
+ RS::get_singleton()->mesh_surface_update_vertex_region(mesh, 0, 0, vertex_buffer);
+ RS::get_singleton()->mesh_surface_update_attribute_region(mesh, 0, 0, attribute_buffer);
+
+ RS::get_singleton()->mesh_set_custom_aabb(mesh, aabb);
set_aabb(aabb);
- RS::get_singleton()->immediate_end(immediate);
-}
-void Sprite3D::_texture_changed() {
- _queue_update();
+ 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);
+ if (last_shader != shader_rid) {
+ RS::get_singleton()->material_set_shader(get_material(), shader_rid);
+ last_shader = shader_rid;
+ }
+ if (last_texture != texture->get_rid()) {
+ RS::get_singleton()->material_set_param(get_material(), "texture_albedo", texture->get_rid());
+ last_texture = texture->get_rid();
+ }
+ if (get_alpha_cut_mode() == ALPHA_CUT_DISABLED) {
+ RS::get_singleton()->material_set_render_priority(get_material(), get_render_priority());
+ RS::get_singleton()->mesh_surface_set_material(mesh, 0, get_material());
+ }
}
void Sprite3D::set_texture(const Ref<Texture2D> &p_texture) {
@@ -498,37 +639,37 @@ void Sprite3D::set_texture(const Ref<Texture2D> &p_texture) {
return;
}
if (texture.is_valid()) {
- texture->disconnect(CoreStringNames::get_singleton()->changed, callable_mp(this, &Sprite3D::_texture_changed));
+ texture->disconnect(CoreStringNames::get_singleton()->changed, Callable(this, "_queue_update"));
}
texture = p_texture;
if (texture.is_valid()) {
- texture->connect(CoreStringNames::get_singleton()->changed, callable_mp(this, &Sprite3D::_texture_changed));
+ texture->connect(CoreStringNames::get_singleton()->changed, Callable(this, "_queue_update"));
}
_queue_update();
+ emit_signal(SceneStringNames::get_singleton()->texture_changed);
}
Ref<Texture2D> Sprite3D::get_texture() const {
return texture;
}
-void Sprite3D::set_region_enabled(bool p_region_enabled) {
- if (p_region_enabled == region_enabled) {
+void Sprite3D::set_region_enabled(bool p_region) {
+ if (p_region == region) {
return;
}
- region_enabled = p_region_enabled;
+ region = p_region;
_queue_update();
- notify_property_list_changed();
}
bool Sprite3D::is_region_enabled() const {
- return region_enabled;
+ return region;
}
void Sprite3D::set_region_rect(const Rect2 &p_region_rect) {
bool changed = region_rect != p_region_rect;
region_rect = p_region_rect;
- if (region_enabled && changed) {
+ if (region && changed) {
_queue_update();
}
}
@@ -551,15 +692,15 @@ int Sprite3D::get_frame() const {
return frame;
}
-void Sprite3D::set_frame_coords(const Vector2 &p_coord) {
- ERR_FAIL_INDEX(int(p_coord.x), hframes);
- ERR_FAIL_INDEX(int(p_coord.y), vframes);
+void Sprite3D::set_frame_coords(const Vector2i &p_coord) {
+ ERR_FAIL_INDEX(p_coord.x, hframes);
+ ERR_FAIL_INDEX(p_coord.y, vframes);
- set_frame(int(p_coord.y) * hframes + int(p_coord.x));
+ set_frame(p_coord.y * hframes + p_coord.x);
}
-Vector2 Sprite3D::get_frame_coords() const {
- return Vector2(frame % hframes, frame / hframes);
+Vector2i Sprite3D::get_frame_coords() const {
+ return Vector2i(frame % hframes, frame / hframes);
}
void Sprite3D::set_vframes(int p_amount) {
@@ -588,14 +729,10 @@ Rect2 Sprite3D::get_item_rect() const {
if (texture.is_null()) {
return Rect2(0, 0, 1, 1);
}
- /*
- if (texture.is_null())
- return CanvasItem::get_item_rect();
- */
- Size2i s;
+ Size2 s;
- if (region_enabled) {
+ if (region) {
s = region_rect.size;
} else {
s = texture->get_size();
@@ -625,9 +762,7 @@ void Sprite3D::_validate_property(PropertyInfo &property) const {
property.usage |= PROPERTY_USAGE_KEYING_INCREMENTS;
}
- if (!region_enabled && property.name == "region_rect") {
- property.usage = PROPERTY_USAGE_NOEDITOR;
- }
+ SpriteBase3D::_validate_property(property);
}
void Sprite3D::_bind_methods() {
@@ -652,7 +787,7 @@ void Sprite3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_hframes", "hframes"), &Sprite3D::set_hframes);
ClassDB::bind_method(D_METHOD("get_hframes"), &Sprite3D::get_hframes);
- ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture2D"), "set_texture", "get_texture");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture");
ADD_GROUP("Animation", "");
ADD_PROPERTY(PropertyInfo(Variant::INT, "hframes", PROPERTY_HINT_RANGE, "1,16384,1"), "set_hframes", "get_hframes");
ADD_PROPERTY(PropertyInfo(Variant::INT, "vframes", PROPERTY_HINT_RANGE, "1,16384,1"), "set_vframes", "get_vframes");
@@ -663,20 +798,18 @@ void Sprite3D::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::RECT2, "region_rect"), "set_region_rect", "get_region_rect");
ADD_SIGNAL(MethodInfo("frame_changed"));
+ ADD_SIGNAL(MethodInfo("texture_changed"));
}
Sprite3D::Sprite3D() {
- region_enabled = false;
- frame = 0;
- vframes = 1;
- hframes = 1;
}
////////////////////////////////////////
void AnimatedSprite3D::_draw() {
- RID immediate = get_immediate();
- RS::get_singleton()->immediate_clear(immediate);
+ if (get_base() != get_mesh()) {
+ set_base(get_mesh());
+ }
if (frames.is_null()) {
return;
@@ -692,24 +825,23 @@ void AnimatedSprite3D::_draw() {
Ref<Texture2D> texture = frames->get_frame(animation, frame);
if (!texture.is_valid()) {
- return; //no texture no life
+ set_base(RID());
+ return; //no texuture no life
}
- Vector2 tsize = texture->get_size();
+ Size2 tsize = texture->get_size();
if (tsize.x == 0 || tsize.y == 0) {
return;
}
- Size2i s = tsize;
Rect2 src_rect;
-
- src_rect.size = s;
+ src_rect.size = tsize;
Point2 ofs = get_offset();
if (is_centered()) {
- ofs -= s / 2;
+ ofs -= tsize / 2;
}
- Rect2 dst_rect(ofs, s);
+ Rect2 dst_rect(ofs, tsize);
Rect2 final_rect;
Rect2 final_src_rect;
@@ -722,11 +854,11 @@ void AnimatedSprite3D::_draw() {
}
Color color = _get_color_accum();
- color.a *= get_opacity();
- float pixel_size = get_pixel_size();
+ real_t pixel_size = get_pixel_size();
Vector2 vertices[4] = {
+
(final_rect.position + Vector2(0, final_rect.size.y)) * pixel_size,
(final_rect.position + final_rect.size) * pixel_size,
(final_rect.position + Vector2(final_rect.size.x, 0)) * pixel_size,
@@ -770,12 +902,6 @@ void AnimatedSprite3D::_draw() {
tangent = Plane(1, 0, 0, -1);
}
- RID mat = StandardMaterial3D::get_material_rid_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);
-
- RS::get_singleton()->immediate_set_material(immediate, mat);
-
- RS::get_singleton()->immediate_begin(immediate, RS::PRIMITIVE_TRIANGLES, texture->get_rid());
-
int x_axis = ((axis + 1) % 3);
int y_axis = ((axis + 2) % 3);
@@ -795,30 +921,83 @@ void AnimatedSprite3D::_draw() {
AABB aabb;
- for (int i = 0; i < 6; i++) {
- static const int indices[6] = {
- 0, 1, 2,
- 0, 2, 3
- };
+ // Everything except position and UV is compressed
+ uint8_t *vertex_write_buffer = vertex_buffer.ptrw();
+ uint8_t *attribute_write_buffer = attribute_buffer.ptrw();
+
+ uint32_t v_normal;
+ {
+ Vector3 n = normal * Vector3(0.5, 0.5, 0.5) + Vector3(0.5, 0.5, 0.5);
+
+ 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;
+
+ v_normal = value;
+ }
+ uint32_t v_tangent;
+ {
+ Plane t = tangent;
+ 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;
+ }
+ v_tangent = value;
+ }
- RS::get_singleton()->immediate_normal(immediate, normal);
- RS::get_singleton()->immediate_tangent(immediate, tangent);
- RS::get_singleton()->immediate_color(immediate, color);
- RS::get_singleton()->immediate_uv(immediate, uvs[indices[i]]);
+ uint8_t v_color[4] = {
+ uint8_t(CLAMP(color.r * 255.0, 0.0, 255.0)),
+ uint8_t(CLAMP(color.g * 255.0, 0.0, 255.0)),
+ uint8_t(CLAMP(color.b * 255.0, 0.0, 255.0)),
+ uint8_t(CLAMP(color.a * 255.0, 0.0, 255.0))
+ };
+ for (int i = 0; i < 4; i++) {
Vector3 vtx;
- vtx[x_axis] = vertices[indices[i]][0];
- vtx[y_axis] = vertices[indices[i]][1];
- RS::get_singleton()->immediate_vertex(immediate, vtx);
+ vtx[x_axis] = vertices[i][0];
+ vtx[y_axis] = vertices[i][1];
if (i == 0) {
aabb.position = vtx;
aabb.size = Vector3();
} else {
aabb.expand_to(vtx);
}
+
+ float v_uv[2] = { (float)uvs[i].x, (float)uvs[i].y };
+ memcpy(&attribute_write_buffer[i * attrib_stride + mesh_surface_offsets[RS::ARRAY_TEX_UV]], v_uv, 8);
+
+ float v_vertex[3] = { (float)vtx.x, (float)vtx.y, (float)vtx.z };
+ memcpy(&vertex_write_buffer[i * vertex_stride + mesh_surface_offsets[RS::ARRAY_VERTEX]], &v_vertex, sizeof(float) * 3);
+ memcpy(&vertex_write_buffer[i * vertex_stride + mesh_surface_offsets[RS::ARRAY_NORMAL]], &v_normal, 4);
+ memcpy(&vertex_write_buffer[i * vertex_stride + mesh_surface_offsets[RS::ARRAY_TANGENT]], &v_tangent, 4);
+ memcpy(&attribute_write_buffer[i * attrib_stride + mesh_surface_offsets[RS::ARRAY_COLOR]], v_color, 4);
}
+
+ RID mesh = get_mesh();
+ RS::get_singleton()->mesh_surface_update_vertex_region(mesh, 0, 0, vertex_buffer);
+ RS::get_singleton()->mesh_surface_update_attribute_region(mesh, 0, 0, attribute_buffer);
+
+ RS::get_singleton()->mesh_set_custom_aabb(mesh, aabb);
set_aabb(aabb);
- RS::get_singleton()->immediate_end(immediate);
+
+ 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);
+ if (last_shader != shader_rid) {
+ RS::get_singleton()->material_set_shader(get_material(), shader_rid);
+ last_shader = shader_rid;
+ }
+ if (last_texture != texture->get_rid()) {
+ RS::get_singleton()->material_set_param(get_material(), "texture_albedo", texture->get_rid());
+ last_texture = texture->get_rid();
+ }
+ if (get_alpha_cut_mode() == ALPHA_CUT_DISABLED) {
+ RS::get_singleton()->material_set_render_priority(get_material(), get_render_priority());
+ RS::get_singleton()->mesh_surface_set_material(mesh, 0, get_material());
+ }
}
void AnimatedSprite3D::_validate_property(PropertyInfo &property) const {
@@ -845,7 +1024,7 @@ void AnimatedSprite3D::_validate_property(PropertyInfo &property) const {
}
if (!current_found) {
- if (property.hint_string == String()) {
+ if (property.hint_string.is_empty()) {
property.hint_string = String(animation);
} else {
property.hint_string = String(animation) + "," + property.hint_string;
@@ -860,6 +1039,8 @@ void AnimatedSprite3D::_validate_property(PropertyInfo &property) const {
}
property.usage |= PROPERTY_USAGE_KEYING_INCREMENTS;
}
+
+ SpriteBase3D::_validate_property(property);
}
void AnimatedSprite3D::_notification(int p_what) {
@@ -875,14 +1056,14 @@ void AnimatedSprite3D::_notification(int p_what) {
return;
}
- float speed = frames->get_animation_speed(animation);
- if (speed == 0) {
- return; //do nothing
- }
-
- float remaining = get_process_delta_time();
+ double remaining = get_process_delta_time();
while (remaining) {
+ double speed = frames->get_animation_speed(animation);
+ if (speed == 0) {
+ return; // Do nothing.
+ }
+
if (timeout <= 0) {
timeout = 1.0 / speed;
@@ -902,7 +1083,7 @@ void AnimatedSprite3D::_notification(int p_what) {
emit_signal(SceneStringNames::get_singleton()->frame_changed);
}
- float to_process = MIN(timeout, remaining);
+ double to_process = MIN(timeout, remaining);
remaining -= to_process;
timeout -= to_process;
}
@@ -912,11 +1093,11 @@ void AnimatedSprite3D::_notification(int p_what) {
void AnimatedSprite3D::set_sprite_frames(const Ref<SpriteFrames> &p_frames) {
if (frames.is_valid()) {
- frames->disconnect("changed", callable_mp(this, &AnimatedSprite3D::_res_changed));
+ frames->disconnect("changed", Callable(this, "_res_changed"));
}
frames = p_frames;
if (frames.is_valid()) {
- frames->connect("changed", callable_mp(this, &AnimatedSprite3D::_res_changed));
+ frames->connect("changed", Callable(this, "_res_changed"));
}
if (!frames.is_valid()) {
@@ -958,7 +1139,6 @@ void AnimatedSprite3D::set_frame(int p_frame) {
frame = p_frame;
_reset_timeout();
_queue_update();
-
emit_signal(SceneStringNames::get_singleton()->frame_changed);
}
@@ -978,7 +1158,7 @@ Rect2 AnimatedSprite3D::get_item_rect() const {
if (t.is_null()) {
return Rect2(0, 0, 1, 1);
}
- Size2i s = t->get_size();
+ Size2 s = t->get_size();
Point2 ofs = get_offset();
if (centered) {
@@ -1022,7 +1202,7 @@ void AnimatedSprite3D::stop() {
}
bool AnimatedSprite3D::is_playing() const {
- return is_processing();
+ return playing;
}
void AnimatedSprite3D::_reset_timeout() {
@@ -1059,15 +1239,25 @@ StringName AnimatedSprite3D::get_animation() const {
}
TypedArray<String> AnimatedSprite3D::get_configuration_warnings() const {
- TypedArray<String> warnings = Node::get_configuration_warnings();
-
+ TypedArray<String> warnings = SpriteBase3D::get_configuration_warnings();
if (frames.is_null()) {
- warnings.push_back(TTR("A SpriteFrames resource must be created or set in the \"Frames\" property in order for AnimatedSprite3D to display frames."));
+ warnings.push_back(RTR("A SpriteFrames resource must be created or set in the \"Frames\" property in order for AnimatedSprite3D to display frames."));
}
return warnings;
}
+void AnimatedSprite3D::get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const {
+ if (p_idx == 0 && p_function == "play" && frames.is_valid()) {
+ List<StringName> al;
+ frames->get_animation_list(&al);
+ for (const StringName &name : al) {
+ r_options->push_back(String(name).quote());
+ }
+ }
+ Node::get_argument_options(p_function, p_idx, r_options);
+}
+
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);
@@ -1085,11 +1275,13 @@ void AnimatedSprite3D::_bind_methods() {
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("_res_changed"), &AnimatedSprite3D::_res_changed);
+
ADD_SIGNAL(MethodInfo("frame_changed"));
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_NAME, "animation"), "set_animation", "get_animation");
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "animation"), "set_animation", "get_animation");
ADD_PROPERTY(PropertyInfo(Variant::INT, "frame"), "set_frame", "get_frame");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "playing"), "_set_playing", "_is_playing");
}
diff --git a/scene/3d/sprite_3d.h b/scene/3d/sprite_3d.h
index 5e47e66bcb..6ac85a7bbc 100644
--- a/scene/3d/sprite_3d.h
+++ b/scene/3d/sprite_3d.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -44,6 +44,8 @@ public:
FLAG_TRANSPARENT,
FLAG_SHADED,
FLAG_DOUBLE_SIDED,
+ FLAG_DISABLE_DEPTH_TEST,
+ FLAG_FIXED_SIZE,
FLAG_MAX
};
@@ -69,17 +71,19 @@ private:
bool vflip = false;
Color modulate = Color(1, 1, 1, 1);
- float opacity = 1.0;
+ int render_priority = 0;
Vector3::Axis axis = Vector3::AXIS_Z;
- float pixel_size = 0.01;
+ real_t pixel_size = 0.01;
AABB aabb;
- RID immediate;
+ RID mesh;
+ RID material;
- bool flags[FLAG_MAX];
+ bool flags[FLAG_MAX] = {};
AlphaCutMode alpha_cut = ALPHA_CUT_DISABLED;
StandardMaterial3D::BillboardMode billboard_mode = StandardMaterial3D::BILLBOARD_DISABLED;
+ StandardMaterial3D::TextureFilter texture_filter = StandardMaterial3D::TEXTURE_FILTER_LINEAR_WITH_MIPMAPS;
bool pending_update = false;
void _im_update();
@@ -91,7 +95,17 @@ protected:
static void _bind_methods();
virtual void _draw() = 0;
_FORCE_INLINE_ void set_aabb(const AABB &p_aabb) { aabb = p_aabb; }
- _FORCE_INLINE_ RID &get_immediate() { return immediate; }
+ _FORCE_INLINE_ RID &get_mesh() { return mesh; }
+ _FORCE_INLINE_ RID &get_material() { return material; }
+
+ uint32_t mesh_surface_offsets[RS::ARRAY_MAX];
+ PackedByteArray vertex_buffer;
+ PackedByteArray attribute_buffer;
+ uint32_t vertex_stride = 0;
+ uint32_t attrib_stride = 0;
+ uint32_t skin_stride = 0;
+ uint32_t mesh_surface_format = 0;
+
void _queue_update();
public:
@@ -107,20 +121,14 @@ public:
void set_flip_v(bool p_flip);
bool is_flipped_v() const;
- void set_region_enabled(bool p_region_enabled);
- bool is_region_enabled() const;
-
- void set_region_rect(const Rect2 &p_region_rect);
- Rect2 get_region_rect() const;
+ void set_render_priority(int p_priority);
+ int get_render_priority() const;
void set_modulate(const Color &p_color);
Color get_modulate() const;
- void set_opacity(float p_amount);
- float get_opacity() const;
-
- void set_pixel_size(float p_amount);
- float get_pixel_size() const;
+ void set_pixel_size(real_t p_amount);
+ real_t get_pixel_size() const;
void set_axis(Vector3::Axis p_axis);
Vector3::Axis get_axis() const;
@@ -130,13 +138,17 @@ public:
void set_alpha_cut_mode(AlphaCutMode p_mode);
AlphaCutMode get_alpha_cut_mode() const;
+
void set_billboard_mode(StandardMaterial3D::BillboardMode p_mode);
StandardMaterial3D::BillboardMode get_billboard_mode() const;
+ void set_texture_filter(StandardMaterial3D::TextureFilter p_filter);
+ StandardMaterial3D::TextureFilter get_texture_filter() const;
+
virtual Rect2 get_item_rect() const = 0;
virtual AABB get_aabb() const override;
- virtual Vector<Face3> get_faces(uint32_t p_usage_flags) const override;
+
Ref<TriangleMesh> generate_triangle_mesh() const;
SpriteBase3D();
@@ -147,15 +159,16 @@ class Sprite3D : public SpriteBase3D {
GDCLASS(Sprite3D, SpriteBase3D);
Ref<Texture2D> texture;
- bool region_enabled;
+ bool region = false;
Rect2 region_rect;
- int frame;
+ int frame = 0;
- int vframes;
- int hframes;
+ int vframes = 1;
+ int hframes = 1;
- void _texture_changed();
+ RID last_shader;
+ RID last_texture;
protected:
virtual void _draw() override;
@@ -167,7 +180,7 @@ public:
void set_texture(const Ref<Texture2D> &p_texture);
Ref<Texture2D> get_texture() const;
- void set_region_enabled(bool p_region_enabled);
+ void set_region_enabled(bool p_region);
bool is_region_enabled() const;
void set_region_rect(const Rect2 &p_region_rect);
@@ -176,8 +189,8 @@ public:
void set_frame(int p_frame);
int get_frame() const;
- void set_frame_coords(const Vector2 &p_coord);
- Vector2 get_frame_coords() const;
+ void set_frame_coords(const Vector2i &p_coord);
+ Vector2i get_frame_coords() const;
void set_vframes(int p_amount);
int get_vframes() const;
@@ -199,14 +212,9 @@ class AnimatedSprite3D : public SpriteBase3D {
StringName animation = "default";
int frame = 0;
- bool centered = true;
-
- float timeout = 0.0;
+ bool centered = false;
- bool hflip = true;
- bool vflip = true;
-
- Color modulate;
+ double timeout = 0.0;
void _res_changed();
@@ -214,6 +222,9 @@ class AnimatedSprite3D : public SpriteBase3D {
void _set_playing(bool p_playing);
bool _is_playing() const;
+ RID last_shader;
+ RID last_texture;
+
protected:
virtual void _draw() override;
static void _bind_methods();
@@ -236,10 +247,13 @@ public:
virtual Rect2 get_item_rect() const override;
- TypedArray<String> get_configuration_warnings() const override;
+ virtual TypedArray<String> get_configuration_warnings() const override;
+ virtual void get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const override;
+
AnimatedSprite3D();
};
VARIANT_ENUM_CAST(SpriteBase3D::DrawFlags);
VARIANT_ENUM_CAST(SpriteBase3D::AlphaCutMode);
+
#endif // SPRITE_3D_H
diff --git a/scene/3d/vehicle_body_3d.cpp b/scene/3d/vehicle_body_3d.cpp
index 9493f686c4..19c90cdeb5 100644
--- a/scene/3d/vehicle_body_3d.cpp
+++ b/scene/3d/vehicle_body_3d.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -40,7 +40,7 @@ public:
Vector3 m_0MinvJt;
Vector3 m_1MinvJt;
//Optimization: can be stored in the w/last component of one of the vectors
- real_t m_Adiag;
+ real_t m_Adiag = 0.0;
real_t getDiagonal() const { return m_Adiag; }
@@ -79,26 +79,29 @@ public:
};
void VehicleWheel3D::_notification(int p_what) {
- if (p_what == NOTIFICATION_ENTER_TREE) {
- VehicleBody3D *cb = Object::cast_to<VehicleBody3D>(get_parent());
- if (!cb) {
- return;
- }
- body = cb;
- local_xform = get_transform();
- cb->wheels.push_back(this);
-
- m_chassisConnectionPointCS = get_transform().origin;
- m_wheelDirectionCS = -get_transform().basis.get_axis(Vector3::AXIS_Y).normalized();
- m_wheelAxleCS = get_transform().basis.get_axis(Vector3::AXIS_X).normalized();
- }
- if (p_what == NOTIFICATION_EXIT_TREE) {
- VehicleBody3D *cb = Object::cast_to<VehicleBody3D>(get_parent());
- if (!cb) {
- return;
- }
- cb->wheels.erase(this);
- body = nullptr;
+ switch (p_what) {
+ case NOTIFICATION_ENTER_TREE: {
+ VehicleBody3D *cb = Object::cast_to<VehicleBody3D>(get_parent());
+ if (!cb) {
+ return;
+ }
+ body = cb;
+ local_xform = get_transform();
+ cb->wheels.push_back(this);
+
+ m_chassisConnectionPointCS = get_transform().origin;
+ m_wheelDirectionCS = -get_transform().basis.get_column(Vector3::AXIS_Y).normalized();
+ m_wheelAxleCS = get_transform().basis.get_column(Vector3::AXIS_X).normalized();
+ } break;
+
+ case NOTIFICATION_EXIT_TREE: {
+ VehicleBody3D *cb = Object::cast_to<VehicleBody3D>(get_parent());
+ if (!cb) {
+ return;
+ }
+ cb->wheels.erase(this);
+ body = nullptr;
+ } break;
}
}
@@ -106,22 +109,20 @@ TypedArray<String> VehicleWheel3D::get_configuration_warnings() const {
TypedArray<String> warnings = Node::get_configuration_warnings();
if (!Object::cast_to<VehicleBody3D>(get_parent())) {
- warnings.push_back(TTR("VehicleWheel3D serves to provide a wheel system to a VehicleBody3D. Please use it as a child of a VehicleBody3D."));
+ warnings.push_back(RTR("VehicleWheel3D serves to provide a wheel system to a VehicleBody3D. Please use it as a child of a VehicleBody3D."));
}
return warnings;
}
void VehicleWheel3D::_update(PhysicsDirectBodyState3D *s) {
- if (m_raycastInfo.m_isInContact)
-
- {
+ if (m_raycastInfo.m_isInContact) {
real_t project = m_raycastInfo.m_contactNormalWS.dot(m_raycastInfo.m_wheelDirectionWS);
Vector3 chassis_velocity_at_contactPoint;
Vector3 relpos = m_raycastInfo.m_contactPointWS - s->get_transform().origin;
chassis_velocity_at_contactPoint = s->get_linear_velocity() +
- (s->get_angular_velocity()).cross(relpos); // * mPos);
+ (s->get_angular_velocity()).cross(relpos); // * mPos);
real_t projVel = m_raycastInfo.m_contactNormalWS.dot(chassis_velocity_at_contactPoint);
if (project >= real_t(-0.1)) {
@@ -132,11 +133,7 @@ void VehicleWheel3D::_update(PhysicsDirectBodyState3D *s) {
m_suspensionRelativeVelocity = projVel * inv;
m_clippedInvContactDotSuspension = inv;
}
-
- }
-
- else // Not in contact : position wheel in a nice (rest length) position
- {
+ } else { // Not in contact : position wheel in a nice (rest length) position
m_raycastInfo.m_suspensionLength = m_suspensionRestLength;
m_suspensionRelativeVelocity = real_t(0.0);
m_raycastInfo.m_contactNormalWS = -m_raycastInfo.m_wheelDirectionWS;
@@ -146,7 +143,7 @@ void VehicleWheel3D::_update(PhysicsDirectBodyState3D *s) {
void VehicleWheel3D::set_radius(real_t p_radius) {
m_wheelRadius = p_radius;
- update_gizmo();
+ update_gizmos();
}
real_t VehicleWheel3D::get_radius() const {
@@ -155,7 +152,7 @@ real_t VehicleWheel3D::get_radius() const {
void VehicleWheel3D::set_suspension_rest_length(real_t p_length) {
m_suspensionRestLength = p_length;
- update_gizmo();
+ update_gizmos();
}
real_t VehicleWheel3D::get_suspension_rest_length() const {
@@ -222,6 +219,10 @@ bool VehicleWheel3D::is_in_contact() const {
return m_raycastInfo.m_isInContact;
}
+Node3D *VehicleWheel3D::get_contact_body() const {
+ return m_raycastInfo.m_groundObject;
+}
+
void VehicleWheel3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_radius", "length"), &VehicleWheel3D::set_radius);
ClassDB::bind_method(D_METHOD("get_radius"), &VehicleWheel3D::get_radius);
@@ -254,6 +255,7 @@ void VehicleWheel3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_friction_slip"), &VehicleWheel3D::get_friction_slip);
ClassDB::bind_method(D_METHOD("is_in_contact"), &VehicleWheel3D::is_in_contact);
+ ClassDB::bind_method(D_METHOD("get_contact_body"), &VehicleWheel3D::get_contact_body);
ClassDB::bind_method(D_METHOD("set_roll_influence", "roll_influence"), &VehicleWheel3D::set_roll_influence);
ClassDB::bind_method(D_METHOD("get_roll_influence"), &VehicleWheel3D::get_roll_influence);
@@ -272,7 +274,7 @@ void VehicleWheel3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_steering"), &VehicleWheel3D::get_steering);
ADD_GROUP("Per-Wheel Motion", "");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "engine_force", PROPERTY_HINT_RANGE, "0.00,1024.0,0.01,or_greater"), "set_engine_force", "get_engine_force");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "engine_force", PROPERTY_HINT_RANGE, "-1024,1024.0,0.01,or_greater"), "set_engine_force", "get_engine_force");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "brake", PROPERTY_HINT_RANGE, "0.0,1.0,0.01"), "set_brake", "get_brake");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "steering", PROPERTY_HINT_RANGE, "-180,180.0,0.01"), "set_steering", "get_steering");
ADD_GROUP("VehicleBody3D Motion", "");
@@ -346,7 +348,7 @@ VehicleWheel3D::VehicleWheel3D() {
void VehicleBody3D::_update_wheel_transform(VehicleWheel3D &wheel, PhysicsDirectBodyState3D *s) {
wheel.m_raycastInfo.m_isInContact = false;
- Transform chassisTrans = s->get_transform();
+ Transform3D chassisTrans = s->get_transform();
/*
if (interpolatedTransform && (getRigidBody()->getMotionState())) {
getRigidBody()->getMotionState()->getWorldTransform(chassisTrans);
@@ -404,9 +406,14 @@ real_t VehicleBody3D::_ray_cast(int p_idx, PhysicsDirectBodyState3D *s) {
PhysicsDirectSpaceState3D *ss = s->get_space_state();
- bool col = ss->intersect_ray(source, target, rr, exclude, get_collision_mask());
+ PhysicsDirectSpaceState3D::RayParameters ray_params;
+ ray_params.from = source;
+ ray_params.to = target;
+ ray_params.exclude = exclude;
+ ray_params.collision_mask = get_collision_mask();
wheel.m_raycastInfo.m_groundObject = nullptr;
+ bool col = ss->intersect_ray(ray_params, rr);
if (col) {
param = source.distance_to(rr.position) / source.distance_to(target);
@@ -441,7 +448,7 @@ real_t VehicleBody3D::_ray_cast(int p_idx, PhysicsDirectBodyState3D *s) {
//chassis_velocity_at_contactPoint = getRigidBody()->getVelocityInLocalPoint(relpos);
chassis_velocity_at_contactPoint = s->get_linear_velocity() +
- (s->get_angular_velocity()).cross(wheel.m_raycastInfo.m_contactPointWS - s->get_transform().origin); // * mPos);
+ (s->get_angular_velocity()).cross(wheel.m_raycastInfo.m_contactPointWS - s->get_transform().origin); // * mPos);
real_t projVel = wheel.m_raycastInfo.m_contactNormalWS.dot(chassis_velocity_at_contactPoint);
@@ -467,7 +474,7 @@ real_t VehicleBody3D::_ray_cast(int p_idx, PhysicsDirectBodyState3D *s) {
}
void VehicleBody3D::_update_suspension(PhysicsDirectBodyState3D *s) {
- real_t chassisMass = mass;
+ real_t chassisMass = get_mass();
for (int w_it = 0; w_it < wheels.size(); w_it++) {
VehicleWheel3D &wheel_info = *wheels[w_it];
@@ -555,7 +562,7 @@ void VehicleBody3D::_resolve_single_bilateral(PhysicsDirectBodyState3D *s, const
rel_pos2,
normal,
s->get_inverse_inertia_tensor().get_main_diagonal(),
- 1.0 / mass,
+ 1.0 / get_mass(),
b2invinertia,
b2invmass);
@@ -581,7 +588,7 @@ void VehicleBody3D::_resolve_single_bilateral(PhysicsDirectBodyState3D *s, const
#define ONLY_USE_LINEAR_MASS
#ifdef ONLY_USE_LINEAR_MASS
- real_t massTerm = real_t(1.) / ((1.0 / mass) + b2invmass);
+ real_t massTerm = real_t(1.) / ((1.0 / get_mass()) + b2invmass);
impulse = -contactDamping * rel_vel * massTerm;
#else
real_t velocityImpulse = -contactDamping * rel_vel * jacDiagABInv;
@@ -677,7 +684,7 @@ void VehicleBody3D::_update_friction(PhysicsDirectBodyState3D *s) {
Basis wheelBasis0 = wheelInfo.m_worldTransform.basis; //get_global_transform().basis;
- m_axle.write[i] = wheelBasis0.get_axis(Vector3::AXIS_X);
+ m_axle.write[i] = wheelBasis0.get_column(Vector3::AXIS_X);
//m_axle[i] = wheelInfo.m_raycastInfo.m_wheelAxleWS;
const Vector3 &surfNormalWS = wheelInfo.m_raycastInfo.m_contactNormalWS;
@@ -768,7 +775,7 @@ void VehicleBody3D::_update_friction(PhysicsDirectBodyState3D *s) {
VehicleWheel3D &wheelInfo = *wheels[wheel];
Vector3 rel_pos = wheelInfo.m_raycastInfo.m_contactPointWS -
- s->get_transform().origin;
+ s->get_transform().origin;
if (m_forwardImpulse[wheel] != real_t(0.)) {
s->apply_impulse(m_forwardWS[wheel] * (m_forwardImpulse[wheel]), rel_pos);
@@ -784,7 +791,7 @@ void VehicleBody3D::_update_friction(PhysicsDirectBodyState3D *s) {
Vector3 sideImp = m_axle[wheel] * m_sideImpulse[wheel];
#if defined ROLLING_INFLUENCE_FIX // fix. It only worked if car's up was along Y - VT.
- Vector3 vChassisWorldUp = s->get_transform().basis.transposed()[1]; //getRigidBody()->getCenterOfMassTransform().getBasis().getColumn(m_indexUpAxis);
+ Vector3 vChassisWorldUp = s->get_transform().basis.transposed()[1]; //getRigidBody()->getCenterOfMassTransform3D().getBasis().getColumn(m_indexUpAxis);
rel_pos -= vChassisWorldUp * (vChassisWorldUp.dot(rel_pos) * (1.f - wheelInfo.m_rollInfluence));
#else
rel_pos[1] *= wheelInfo.m_rollInfluence; //?
@@ -799,24 +806,21 @@ void VehicleBody3D::_update_friction(PhysicsDirectBodyState3D *s) {
}
}
-void VehicleBody3D::_direct_state_changed(Object *p_state) {
- RigidBody3D::_direct_state_changed(p_state);
-
- state = Object::cast_to<PhysicsDirectBodyState3D>(p_state);
- ERR_FAIL_NULL_MSG(state, "Method '_direct_state_changed' must receive a valid PhysicsDirectBodyState3D object as argument");
+void VehicleBody3D::_body_state_changed(PhysicsDirectBodyState3D *p_state) {
+ RigidDynamicBody3D::_body_state_changed(p_state);
- real_t step = state->get_step();
+ real_t step = p_state->get_step();
for (int i = 0; i < wheels.size(); i++) {
- _update_wheel(i, state);
+ _update_wheel(i, p_state);
}
for (int i = 0; i < wheels.size(); i++) {
- _ray_cast(i, state);
- wheels[i]->set_transform(state->get_transform().inverse() * wheels[i]->m_worldTransform);
+ _ray_cast(i, p_state);
+ wheels[i]->set_transform(p_state->get_transform().inverse() * wheels[i]->m_worldTransform);
}
- _update_suspension(state);
+ _update_suspension(p_state);
for (int i = 0; i < wheels.size(); i++) {
//apply suspension force
@@ -828,20 +832,20 @@ void VehicleBody3D::_direct_state_changed(Object *p_state) {
suspensionForce = wheel.m_maxSuspensionForce;
}
Vector3 impulse = wheel.m_raycastInfo.m_contactNormalWS * suspensionForce * step;
- Vector3 relative_position = wheel.m_raycastInfo.m_contactPointWS - state->get_transform().origin;
+ Vector3 relative_position = wheel.m_raycastInfo.m_contactPointWS - p_state->get_transform().origin;
- state->apply_impulse(impulse, relative_position);
+ p_state->apply_impulse(impulse, relative_position);
}
- _update_friction(state);
+ _update_friction(p_state);
for (int i = 0; i < wheels.size(); i++) {
VehicleWheel3D &wheel = *wheels[i];
- Vector3 relpos = wheel.m_raycastInfo.m_hardPointWS - state->get_transform().origin;
- Vector3 vel = state->get_linear_velocity() + (state->get_angular_velocity()).cross(relpos); // * mPos);
+ Vector3 relpos = wheel.m_raycastInfo.m_hardPointWS - p_state->get_transform().origin;
+ Vector3 vel = p_state->get_linear_velocity() + (p_state->get_angular_velocity()).cross(relpos); // * mPos);
if (wheel.m_raycastInfo.m_isInContact) {
- const Transform &chassisWorldTransform = state->get_transform();
+ const Transform3D &chassisWorldTransform = p_state->get_transform();
Vector3 fwd(
chassisWorldTransform.basis[0][Vector3::AXIS_Z],
@@ -861,8 +865,6 @@ void VehicleBody3D::_direct_state_changed(Object *p_state) {
wheel.m_deltaRotation *= real_t(0.99); //damping of rotation when not in contact
}
-
- state = nullptr;
}
void VehicleBody3D::set_engine_force(real_t p_engine_force) {
@@ -916,14 +918,12 @@ void VehicleBody3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_steering"), &VehicleBody3D::get_steering);
ADD_GROUP("Motion", "");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "engine_force", PROPERTY_HINT_RANGE, "0.00,1024.0,0.01,or_greater"), "set_engine_force", "get_engine_force");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "engine_force", PROPERTY_HINT_RANGE, "-1024,1024.0,0.01,or_greater"), "set_engine_force", "get_engine_force");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "brake", PROPERTY_HINT_RANGE, "0.0,1.0,0.01"), "set_brake", "get_brake");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "steering", PROPERTY_HINT_RANGE, "-180,180.0,0.01"), "set_steering", "get_steering");
}
VehicleBody3D::VehicleBody3D() {
exclude.insert(get_rid());
- //PhysicsServer3D::get_singleton()->body_set_force_integration_callback(get_rid(), callable_mp(this, &VehicleBody3D::_direct_state_changed));
-
set_mass(40);
}
diff --git a/scene/3d/vehicle_body_3d.h b/scene/3d/vehicle_body_3d.h
index 646071a363..d2371d819b 100644
--- a/scene/3d/vehicle_body_3d.h
+++ b/scene/3d/vehicle_body_3d.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -40,8 +40,8 @@ class VehicleWheel3D : public Node3D {
friend class VehicleBody3D;
- Transform m_worldTransform;
- Transform local_xform;
+ Transform3D m_worldTransform;
+ Transform3D local_xform;
bool engine_traction = false;
bool steers = false;
@@ -129,6 +129,8 @@ public:
bool is_in_contact() const;
+ Node3D *get_contact_body() const;
+
void set_roll_influence(real_t p_value);
real_t get_roll_influence() const;
@@ -150,8 +152,8 @@ public:
VehicleWheel3D();
};
-class VehicleBody3D : public RigidBody3D {
- GDCLASS(VehicleBody3D, RigidBody3D);
+class VehicleBody3D : public RigidDynamicBody3D {
+ GDCLASS(VehicleBody3D, RigidDynamicBody3D);
real_t engine_force = 0.0;
real_t brake = 0.0;
@@ -192,7 +194,8 @@ class VehicleBody3D : public RigidBody3D {
static void _bind_methods();
- void _direct_state_changed(Object *p_state) override;
+ static void _body_state_changed_callback(void *p_instance, PhysicsDirectBodyState3D *p_state);
+ virtual void _body_state_changed(PhysicsDirectBodyState3D *p_state) override;
public:
void set_engine_force(real_t p_engine_force);
diff --git a/scene/3d/velocity_tracker_3d.cpp b/scene/3d/velocity_tracker_3d.cpp
index 5b5cc06456..5bfe519440 100644
--- a/scene/3d/velocity_tracker_3d.cpp
+++ b/scene/3d/velocity_tracker_3d.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -29,7 +29,6 @@
/*************************************************************************/
#include "velocity_tracker_3d.h"
-#include "core/config/engine.h"
void VelocityTracker3D::set_track_physics_step(bool p_track_physics_step) {
physics_step = p_track_physics_step;
@@ -61,16 +60,16 @@ void VelocityTracker3D::update_position(const Vector3 &p_position) {
Vector3 VelocityTracker3D::get_tracked_linear_velocity() const {
Vector3 linear_velocity;
- float max_time = 1 / 5.0; //maximum time to interpolate a velocity
+ double max_time = 1 / 5.0; //maximum time to interpolate a velocity
Vector3 distance_accum;
- float time_accum = 0.0;
- float base_time = 0.0;
+ double time_accum = 0.0;
+ double base_time = 0.0;
if (position_history_len) {
if (physics_step) {
uint64_t base = Engine::get_singleton()->get_physics_frames();
- base_time = float(base - position_history[0].frame) / Engine::get_singleton()->get_iterations_per_second();
+ base_time = double(base - position_history[0].frame) / Engine::get_singleton()->get_physics_ticks_per_second();
} else {
uint64_t base = Engine::get_singleton()->get_frame_ticks();
base_time = double(base - position_history[0].frame) / 1000000.0;
@@ -78,12 +77,12 @@ Vector3 VelocityTracker3D::get_tracked_linear_velocity() const {
}
for (int i = 0; i < position_history_len - 1; i++) {
- float delta = 0.0;
+ double delta = 0.0;
uint64_t diff = position_history[i].frame - position_history[i + 1].frame;
Vector3 distance = position_history[i].position - position_history[i + 1].position;
if (physics_step) {
- delta = float(diff) / Engine::get_singleton()->get_iterations_per_second();
+ delta = double(diff) / Engine::get_singleton()->get_physics_ticks_per_second();
} else {
delta = double(diff) / 1000000.0;
}
diff --git a/scene/3d/velocity_tracker_3d.h b/scene/3d/velocity_tracker_3d.h
index e971f4755a..7fdcacc9c1 100644
--- a/scene/3d/velocity_tracker_3d.h
+++ b/scene/3d/velocity_tracker_3d.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -33,8 +33,8 @@
#include "scene/3d/node_3d.h"
-class VelocityTracker3D : public Reference {
- GDCLASS(VelocityTracker3D, Reference);
+class VelocityTracker3D : public RefCounted {
+ GDCLASS(VelocityTracker3D, RefCounted);
struct PositionHistory {
uint64_t frame = 0;
diff --git a/scene/3d/visibility_notifier_3d.cpp b/scene/3d/visibility_notifier_3d.cpp
deleted file mode 100644
index 471838b9d1..0000000000
--- a/scene/3d/visibility_notifier_3d.cpp
+++ /dev/null
@@ -1,253 +0,0 @@
-/*************************************************************************/
-/* visibility_notifier_3d.cpp */
-/*************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
-/* */
-/* Permission is hereby granted, free of charge, to any person obtaining */
-/* a copy of this software and associated documentation files (the */
-/* "Software"), to deal in the Software without restriction, including */
-/* without limitation the rights to use, copy, modify, merge, publish, */
-/* distribute, sublicense, and/or sell copies of the Software, and to */
-/* permit persons to whom the Software is furnished to do so, subject to */
-/* the following conditions: */
-/* */
-/* The above copyright notice and this permission notice shall be */
-/* included in all copies or substantial portions of the Software. */
-/* */
-/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
-/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
-/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
-/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
-/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
-/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
-/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
-/*************************************************************************/
-
-#include "visibility_notifier_3d.h"
-
-#include "core/config/engine.h"
-#include "scene/3d/camera_3d.h"
-#include "scene/3d/physics_body_3d.h"
-#include "scene/animation/animation_player.h"
-#include "scene/scene_string_names.h"
-
-void VisibilityNotifier3D::_enter_camera(Camera3D *p_camera) {
- ERR_FAIL_COND(cameras.has(p_camera));
- cameras.insert(p_camera);
- if (cameras.size() == 1) {
- emit_signal(SceneStringNames::get_singleton()->screen_entered);
- _screen_enter();
- }
-
- emit_signal(SceneStringNames::get_singleton()->camera_entered, p_camera);
-}
-
-void VisibilityNotifier3D::_exit_camera(Camera3D *p_camera) {
- ERR_FAIL_COND(!cameras.has(p_camera));
- cameras.erase(p_camera);
-
- emit_signal(SceneStringNames::get_singleton()->camera_exited, p_camera);
- if (cameras.size() == 0) {
- emit_signal(SceneStringNames::get_singleton()->screen_exited);
-
- _screen_exit();
- }
-}
-
-void VisibilityNotifier3D::set_aabb(const AABB &p_aabb) {
- if (aabb == p_aabb) {
- return;
- }
- aabb = p_aabb;
-
- if (is_inside_world()) {
- get_world_3d()->_update_notifier(this, get_global_transform().xform(aabb));
- }
-
- update_gizmo();
-}
-
-AABB VisibilityNotifier3D::get_aabb() const {
- return aabb;
-}
-
-void VisibilityNotifier3D::_notification(int p_what) {
- switch (p_what) {
- case NOTIFICATION_ENTER_WORLD: {
- world = get_world_3d();
- ERR_FAIL_COND(!world.is_valid());
- world->_register_notifier(this, get_global_transform().xform(aabb));
- } break;
- case NOTIFICATION_TRANSFORM_CHANGED: {
- world->_update_notifier(this, get_global_transform().xform(aabb));
- } break;
- case NOTIFICATION_EXIT_WORLD: {
- ERR_FAIL_COND(!world.is_valid());
- world->_remove_notifier(this);
- } break;
- }
-}
-
-bool VisibilityNotifier3D::is_on_screen() const {
- return cameras.size() != 0;
-}
-
-void VisibilityNotifier3D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_aabb", "rect"), &VisibilityNotifier3D::set_aabb);
- ClassDB::bind_method(D_METHOD("get_aabb"), &VisibilityNotifier3D::get_aabb);
- ClassDB::bind_method(D_METHOD("is_on_screen"), &VisibilityNotifier3D::is_on_screen);
-
- ADD_PROPERTY(PropertyInfo(Variant::AABB, "aabb"), "set_aabb", "get_aabb");
-
- ADD_SIGNAL(MethodInfo("camera_entered", PropertyInfo(Variant::OBJECT, "camera", PROPERTY_HINT_RESOURCE_TYPE, "Camera3D")));
- ADD_SIGNAL(MethodInfo("camera_exited", PropertyInfo(Variant::OBJECT, "camera", PROPERTY_HINT_RESOURCE_TYPE, "Camera3D")));
- ADD_SIGNAL(MethodInfo("screen_entered"));
- ADD_SIGNAL(MethodInfo("screen_exited"));
-}
-
-VisibilityNotifier3D::VisibilityNotifier3D() {
- set_notify_transform(true);
-}
-
-//////////////////////////////////////
-
-void VisibilityEnabler3D::_screen_enter() {
- for (Map<Node *, Variant>::Element *E = nodes.front(); E; E = E->next()) {
- _change_node_state(E->key(), true);
- }
-
- visible = true;
-}
-
-void VisibilityEnabler3D::_screen_exit() {
- for (Map<Node *, Variant>::Element *E = nodes.front(); E; E = E->next()) {
- _change_node_state(E->key(), false);
- }
-
- visible = false;
-}
-
-void VisibilityEnabler3D::_find_nodes(Node *p_node) {
- bool add = false;
- Variant meta;
-
- {
- RigidBody3D *rb = Object::cast_to<RigidBody3D>(p_node);
- if (rb && ((rb->get_mode() == RigidBody3D::MODE_CHARACTER || rb->get_mode() == RigidBody3D::MODE_RIGID))) {
- add = true;
- meta = rb->get_mode();
- }
- }
-
- {
- AnimationPlayer *ap = Object::cast_to<AnimationPlayer>(p_node);
- if (ap) {
- add = true;
- }
- }
-
- if (add) {
- p_node->connect(SceneStringNames::get_singleton()->tree_exiting, callable_mp(this, &VisibilityEnabler3D::_node_removed), varray(p_node), CONNECT_ONESHOT);
- nodes[p_node] = meta;
- _change_node_state(p_node, false);
- }
-
- for (int i = 0; i < p_node->get_child_count(); i++) {
- Node *c = p_node->get_child(i);
- if (c->get_filename() != String()) {
- continue; //skip, instance
- }
-
- _find_nodes(c);
- }
-}
-
-void VisibilityEnabler3D::_notification(int p_what) {
- if (p_what == NOTIFICATION_ENTER_TREE) {
- if (Engine::get_singleton()->is_editor_hint()) {
- return;
- }
-
- Node *from = this;
- //find where current scene starts
- while (from->get_parent() && from->get_filename() == String()) {
- from = from->get_parent();
- }
-
- _find_nodes(from);
- }
-
- if (p_what == NOTIFICATION_EXIT_TREE) {
- if (Engine::get_singleton()->is_editor_hint()) {
- return;
- }
-
- for (Map<Node *, Variant>::Element *E = nodes.front(); E; E = E->next()) {
- if (!visible) {
- _change_node_state(E->key(), true);
- }
- E->key()->disconnect(SceneStringNames::get_singleton()->tree_exiting, callable_mp(this, &VisibilityEnabler3D::_node_removed));
- }
-
- nodes.clear();
- }
-}
-
-void VisibilityEnabler3D::_change_node_state(Node *p_node, bool p_enabled) {
- ERR_FAIL_COND(!nodes.has(p_node));
-
- if (enabler[ENABLER_FREEZE_BODIES]) {
- RigidBody3D *rb = Object::cast_to<RigidBody3D>(p_node);
- if (rb) {
- rb->set_sleeping(!p_enabled);
- }
- }
-
- if (enabler[ENABLER_PAUSE_ANIMATIONS]) {
- AnimationPlayer *ap = Object::cast_to<AnimationPlayer>(p_node);
-
- if (ap) {
- ap->set_active(p_enabled);
- }
- }
-}
-
-void VisibilityEnabler3D::_node_removed(Node *p_node) {
- if (!visible) {
- _change_node_state(p_node, true);
- }
- nodes.erase(p_node);
-}
-
-void VisibilityEnabler3D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_enabler", "enabler", "enabled"), &VisibilityEnabler3D::set_enabler);
- ClassDB::bind_method(D_METHOD("is_enabler_enabled", "enabler"), &VisibilityEnabler3D::is_enabler_enabled);
-
- ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "pause_animations"), "set_enabler", "is_enabler_enabled", ENABLER_PAUSE_ANIMATIONS);
- ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "freeze_bodies"), "set_enabler", "is_enabler_enabled", ENABLER_FREEZE_BODIES);
-
- BIND_ENUM_CONSTANT(ENABLER_PAUSE_ANIMATIONS);
- BIND_ENUM_CONSTANT(ENABLER_FREEZE_BODIES);
- BIND_ENUM_CONSTANT(ENABLER_MAX);
-}
-
-void VisibilityEnabler3D::set_enabler(Enabler p_enabler, bool p_enable) {
- ERR_FAIL_INDEX(p_enabler, ENABLER_MAX);
- enabler[p_enabler] = p_enable;
-}
-
-bool VisibilityEnabler3D::is_enabler_enabled(Enabler p_enabler) const {
- ERR_FAIL_INDEX_V(p_enabler, ENABLER_MAX, false);
- return enabler[p_enabler];
-}
-
-VisibilityEnabler3D::VisibilityEnabler3D() {
- for (int i = 0; i < ENABLER_MAX; i++) {
- enabler[i] = true;
- }
-}
diff --git a/scene/3d/visible_on_screen_notifier_3d.cpp b/scene/3d/visible_on_screen_notifier_3d.cpp
new file mode 100644
index 0000000000..41cd604a4f
--- /dev/null
+++ b/scene/3d/visible_on_screen_notifier_3d.cpp
@@ -0,0 +1,200 @@
+/*************************************************************************/
+/* visible_on_screen_notifier_3d.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#include "visible_on_screen_notifier_3d.h"
+
+#include "scene/scene_string_names.h"
+
+void VisibleOnScreenNotifier3D::_visibility_enter() {
+ if (!is_inside_tree() || Engine::get_singleton()->is_editor_hint()) {
+ return;
+ }
+
+ on_screen = true;
+ emit_signal(SceneStringNames::get_singleton()->screen_entered);
+ _screen_enter();
+}
+void VisibleOnScreenNotifier3D::_visibility_exit() {
+ if (!is_inside_tree() || Engine::get_singleton()->is_editor_hint()) {
+ return;
+ }
+
+ on_screen = false;
+ emit_signal(SceneStringNames::get_singleton()->screen_exited);
+ _screen_exit();
+}
+
+void VisibleOnScreenNotifier3D::set_aabb(const AABB &p_aabb) {
+ if (aabb == p_aabb) {
+ return;
+ }
+ aabb = p_aabb;
+
+ RS::get_singleton()->visibility_notifier_set_aabb(get_base(), aabb);
+
+ update_gizmos();
+}
+
+AABB VisibleOnScreenNotifier3D::get_aabb() const {
+ return aabb;
+}
+
+bool VisibleOnScreenNotifier3D::is_on_screen() const {
+ return on_screen;
+}
+
+void VisibleOnScreenNotifier3D::_notification(int p_what) {
+ switch (p_what) {
+ case NOTIFICATION_ENTER_TREE:
+ case NOTIFICATION_EXIT_TREE: {
+ on_screen = false;
+ } break;
+ }
+}
+
+void VisibleOnScreenNotifier3D::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("set_aabb", "rect"), &VisibleOnScreenNotifier3D::set_aabb);
+ ClassDB::bind_method(D_METHOD("is_on_screen"), &VisibleOnScreenNotifier3D::is_on_screen);
+
+ ADD_PROPERTY(PropertyInfo(Variant::AABB, "aabb"), "set_aabb", "get_aabb");
+
+ ADD_SIGNAL(MethodInfo("screen_entered"));
+ ADD_SIGNAL(MethodInfo("screen_exited"));
+}
+
+VisibleOnScreenNotifier3D::VisibleOnScreenNotifier3D() {
+ RID notifier = RS::get_singleton()->visibility_notifier_create();
+ RS::get_singleton()->visibility_notifier_set_aabb(notifier, aabb);
+ RS::get_singleton()->visibility_notifier_set_callbacks(notifier, callable_mp(this, &VisibleOnScreenNotifier3D::_visibility_enter), callable_mp(this, &VisibleOnScreenNotifier3D::_visibility_exit));
+ set_base(notifier);
+}
+VisibleOnScreenNotifier3D::~VisibleOnScreenNotifier3D() {
+ RID base = get_base();
+ set_base(RID());
+ RS::get_singleton()->free(base);
+}
+
+//////////////////////////////////////
+
+void VisibleOnScreenEnabler3D::_screen_enter() {
+ _update_enable_mode(true);
+}
+
+void VisibleOnScreenEnabler3D::_screen_exit() {
+ _update_enable_mode(false);
+}
+
+void VisibleOnScreenEnabler3D::set_enable_mode(EnableMode p_mode) {
+ enable_mode = p_mode;
+ if (is_inside_tree()) {
+ _update_enable_mode(is_on_screen());
+ }
+}
+VisibleOnScreenEnabler3D::EnableMode VisibleOnScreenEnabler3D::get_enable_mode() {
+ return enable_mode;
+}
+
+void VisibleOnScreenEnabler3D::set_enable_node_path(NodePath p_path) {
+ if (enable_node_path == p_path) {
+ return;
+ }
+ enable_node_path = p_path;
+ if (is_inside_tree()) {
+ node_id = ObjectID();
+ Node *node = get_node(enable_node_path);
+ if (node) {
+ node_id = node->get_instance_id();
+ _update_enable_mode(is_on_screen());
+ }
+ }
+}
+NodePath VisibleOnScreenEnabler3D::get_enable_node_path() {
+ return enable_node_path;
+}
+
+void VisibleOnScreenEnabler3D::_update_enable_mode(bool p_enable) {
+ Node *node = static_cast<Node *>(ObjectDB::get_instance(node_id));
+ if (node) {
+ if (p_enable) {
+ switch (enable_mode) {
+ case ENABLE_MODE_INHERIT: {
+ node->set_process_mode(PROCESS_MODE_INHERIT);
+ } break;
+ case ENABLE_MODE_ALWAYS: {
+ node->set_process_mode(PROCESS_MODE_ALWAYS);
+ } break;
+ case ENABLE_MODE_WHEN_PAUSED: {
+ node->set_process_mode(PROCESS_MODE_WHEN_PAUSED);
+ } break;
+ }
+ } else {
+ node->set_process_mode(PROCESS_MODE_DISABLED);
+ }
+ }
+}
+void VisibleOnScreenEnabler3D::_notification(int p_what) {
+ switch (p_what) {
+ case NOTIFICATION_ENTER_TREE: {
+ if (Engine::get_singleton()->is_editor_hint()) {
+ return;
+ }
+
+ node_id = ObjectID();
+ Node *node = get_node(enable_node_path);
+ if (node) {
+ node_id = node->get_instance_id();
+ node->set_process_mode(PROCESS_MODE_DISABLED);
+ }
+ } break;
+
+ case NOTIFICATION_EXIT_TREE: {
+ node_id = ObjectID();
+ } break;
+ }
+}
+
+void VisibleOnScreenEnabler3D::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("set_enable_mode", "mode"), &VisibleOnScreenEnabler3D::set_enable_mode);
+ ClassDB::bind_method(D_METHOD("get_enable_mode"), &VisibleOnScreenEnabler3D::get_enable_mode);
+
+ ClassDB::bind_method(D_METHOD("set_enable_node_path", "path"), &VisibleOnScreenEnabler3D::set_enable_node_path);
+ ClassDB::bind_method(D_METHOD("get_enable_node_path"), &VisibleOnScreenEnabler3D::get_enable_node_path);
+
+ ADD_GROUP("Enabling", "enable_");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "enable_mode", PROPERTY_HINT_ENUM, "Inherit,Always,WhenPaused"), "set_enable_mode", "get_enable_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "enable_node_path"), "set_enable_node_path", "get_enable_node_path");
+
+ BIND_ENUM_CONSTANT(ENABLE_MODE_INHERIT);
+ BIND_ENUM_CONSTANT(ENABLE_MODE_ALWAYS);
+ BIND_ENUM_CONSTANT(ENABLE_MODE_WHEN_PAUSED);
+}
+
+VisibleOnScreenEnabler3D::VisibleOnScreenEnabler3D() {
+}
diff --git a/scene/3d/visibility_notifier_3d.h b/scene/3d/visible_on_screen_notifier_3d.h
index 9f7705067f..fe17f1e444 100644
--- a/scene/3d/visibility_notifier_3d.h
+++ b/scene/3d/visible_on_screen_notifier_3d.h
@@ -1,12 +1,12 @@
/*************************************************************************/
-/* visibility_notifier_3d.h */
+/* visible_on_screen_notifier_3d.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -28,74 +28,72 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#ifndef VISIBILITY_NOTIFIER_H
-#define VISIBILITY_NOTIFIER_H
+#ifndef VISIBLE_ON_SCREEN_NOTIFIER_3D_H
+#define VISIBLE_ON_SCREEN_NOTIFIER_3D_H
-#include "scene/3d/node_3d.h"
+#include "scene/3d/visual_instance_3d.h"
class World3D;
class Camera3D;
-class VisibilityNotifier3D : public Node3D {
- GDCLASS(VisibilityNotifier3D, Node3D);
-
- Ref<World3D> world;
- Set<Camera3D *> cameras;
+class VisibleOnScreenNotifier3D : public VisualInstance3D {
+ GDCLASS(VisibleOnScreenNotifier3D, VisualInstance3D);
AABB aabb = AABB(Vector3(-1, -1, -1), Vector3(2, 2, 2));
+private:
+ bool on_screen = false;
+ void _visibility_enter();
+ void _visibility_exit();
+
protected:
virtual void _screen_enter() {}
virtual void _screen_exit() {}
void _notification(int p_what);
static void _bind_methods();
- friend struct SpatialIndexer;
-
- void _enter_camera(Camera3D *p_camera);
- void _exit_camera(Camera3D *p_camera);
public:
void set_aabb(const AABB &p_aabb);
- AABB get_aabb() const;
+ virtual AABB get_aabb() const override;
bool is_on_screen() const;
- VisibilityNotifier3D();
+ VisibleOnScreenNotifier3D();
+ ~VisibleOnScreenNotifier3D();
};
-class VisibilityEnabler3D : public VisibilityNotifier3D {
- GDCLASS(VisibilityEnabler3D, VisibilityNotifier3D);
+class VisibleOnScreenEnabler3D : public VisibleOnScreenNotifier3D {
+ GDCLASS(VisibleOnScreenEnabler3D, VisibleOnScreenNotifier3D);
public:
- enum Enabler {
- ENABLER_PAUSE_ANIMATIONS,
- ENABLER_FREEZE_BODIES,
- ENABLER_MAX
+ enum EnableMode {
+ ENABLE_MODE_INHERIT,
+ ENABLE_MODE_ALWAYS,
+ ENABLE_MODE_WHEN_PAUSED,
};
protected:
+ ObjectID node_id;
virtual void _screen_enter() override;
virtual void _screen_exit() override;
- bool visible = false;
-
- void _find_nodes(Node *p_node);
-
- Map<Node *, Variant> nodes;
- void _node_removed(Node *p_node);
- bool enabler[ENABLER_MAX];
-
- void _change_node_state(Node *p_node, bool p_enabled);
+ EnableMode enable_mode = ENABLE_MODE_INHERIT;
+ NodePath enable_node_path = NodePath("..");
void _notification(int p_what);
static void _bind_methods();
+ void _update_enable_mode(bool p_enable);
+
public:
- void set_enabler(Enabler p_enabler, bool p_enable);
- bool is_enabler_enabled(Enabler p_enabler) const;
+ void set_enable_mode(EnableMode p_mode);
+ EnableMode get_enable_mode();
+
+ void set_enable_node_path(NodePath p_path);
+ NodePath get_enable_node_path();
- VisibilityEnabler3D();
+ VisibleOnScreenEnabler3D();
};
-VARIANT_ENUM_CAST(VisibilityEnabler3D::Enabler);
+VARIANT_ENUM_CAST(VisibleOnScreenEnabler3D::EnableMode);
#endif // VISIBILITY_NOTIFIER_H
diff --git a/scene/3d/visual_instance_3d.cpp b/scene/3d/visual_instance_3d.cpp
index d81b09b86c..669017c4b4 100644
--- a/scene/3d/visual_instance_3d.cpp
+++ b/scene/3d/visual_instance_3d.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -31,8 +31,14 @@
#include "visual_instance_3d.h"
#include "scene/scene_string_names.h"
-#include "servers/rendering_server.h"
-#include "skeleton_3d.h"
+
+AABB VisualInstance3D::get_aabb() const {
+ AABB ret;
+ if (GDVIRTUAL_CALL(_get_aabb, ret)) {
+ return ret;
+ }
+ return AABB();
+}
AABB VisualInstance3D::get_transformed_aabb() const {
return get_global_transform().xform(get_aabb());
@@ -49,27 +55,21 @@ void VisualInstance3D::_update_visibility() {
void VisualInstance3D::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_ENTER_WORLD: {
- // CHECK SKELETON => moving skeleton attaching logic to MeshInstance
- /*
- Skeleton *skeleton=Object::cast_to<Skeleton>(get_parent());
- if (skeleton)
- RenderingServer::get_singleton()->instance_attach_skeleton( instance, skeleton->get_skeleton() );
- */
ERR_FAIL_COND(get_world_3d().is_null());
RenderingServer::get_singleton()->instance_set_scenario(instance, get_world_3d()->get_scenario());
_update_visibility();
-
} break;
+
case NOTIFICATION_TRANSFORM_CHANGED: {
- Transform gt = get_global_transform();
+ Transform3D gt = get_global_transform();
RenderingServer::get_singleton()->instance_set_transform(instance, gt);
} break;
+
case NOTIFICATION_EXIT_WORLD: {
RenderingServer::get_singleton()->instance_set_scenario(instance, RID());
RenderingServer::get_singleton()->instance_attach_skeleton(instance, RID());
- //RS::get_singleton()->instance_geometry_set_baked_light_sampler(instance, RID() );
-
} break;
+
case NOTIFICATION_VISIBILITY_CHANGED: {
_update_visibility();
} break;
@@ -93,18 +93,22 @@ uint32_t VisualInstance3D::get_layer_mask() const {
return layers;
}
-void VisualInstance3D::set_layer_mask_bit(int p_layer, bool p_enable) {
- ERR_FAIL_INDEX(p_layer, 32);
- if (p_enable) {
- set_layer_mask(layers | (1 << p_layer));
+void VisualInstance3D::set_layer_mask_value(int p_layer_number, bool p_value) {
+ ERR_FAIL_COND_MSG(p_layer_number < 1, "Render layer number must be between 1 and 20 inclusive.");
+ ERR_FAIL_COND_MSG(p_layer_number > 20, "Render layer number must be between 1 and 20 inclusive.");
+ uint32_t mask = get_layer_mask();
+ if (p_value) {
+ mask |= 1 << (p_layer_number - 1);
} else {
- set_layer_mask(layers & (~(1 << p_layer)));
+ mask &= ~(1 << (p_layer_number - 1));
}
+ set_layer_mask(mask);
}
-bool VisualInstance3D::get_layer_mask_bit(int p_layer) const {
- ERR_FAIL_INDEX_V(p_layer, 32, false);
- return (layers & (1 << p_layer));
+bool VisualInstance3D::get_layer_mask_value(int p_layer_number) const {
+ ERR_FAIL_COND_V_MSG(p_layer_number < 1, false, "Render layer number must be between 1 and 20 inclusive.");
+ ERR_FAIL_COND_V_MSG(p_layer_number > 20, false, "Render layer number must be between 1 and 20 inclusive.");
+ return layers & (1 << (p_layer_number - 1));
}
void VisualInstance3D::_bind_methods() {
@@ -114,11 +118,12 @@ void VisualInstance3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_instance"), &VisualInstance3D::get_instance);
ClassDB::bind_method(D_METHOD("set_layer_mask", "mask"), &VisualInstance3D::set_layer_mask);
ClassDB::bind_method(D_METHOD("get_layer_mask"), &VisualInstance3D::get_layer_mask);
- ClassDB::bind_method(D_METHOD("set_layer_mask_bit", "layer", "enabled"), &VisualInstance3D::set_layer_mask_bit);
- ClassDB::bind_method(D_METHOD("get_layer_mask_bit", "layer"), &VisualInstance3D::get_layer_mask_bit);
+ ClassDB::bind_method(D_METHOD("set_layer_mask_value", "layer_number", "value"), &VisualInstance3D::set_layer_mask_value);
+ ClassDB::bind_method(D_METHOD("get_layer_mask_value", "layer_number"), &VisualInstance3D::get_layer_mask_value);
ClassDB::bind_method(D_METHOD("get_transformed_aabb"), &VisualInstance3D::get_transformed_aabb);
+ GDVIRTUAL_BIND(_get_aabb);
ADD_PROPERTY(PropertyInfo(Variant::INT, "layers", PROPERTY_HINT_LAYERS_3D_RENDER), "set_layer_mask", "get_layer_mask");
}
@@ -150,43 +155,72 @@ Ref<Material> GeometryInstance3D::get_material_override() const {
return material_override;
}
-void GeometryInstance3D::set_lod_min_distance(float p_dist) {
- lod_min_distance = p_dist;
- RS::get_singleton()->instance_geometry_set_draw_range(get_instance(), lod_min_distance, lod_max_distance, lod_min_hysteresis, lod_max_hysteresis);
+void GeometryInstance3D::set_material_overlay(const Ref<Material> &p_material) {
+ material_overlay = p_material;
+ RS::get_singleton()->instance_geometry_set_material_overlay(get_instance(), p_material.is_valid() ? p_material->get_rid() : RID());
+}
+
+Ref<Material> GeometryInstance3D::get_material_overlay() const {
+ return material_overlay;
+}
+
+void GeometryInstance3D::set_transparecy(float p_transparency) {
+ transparency = CLAMP(p_transparency, 0.0f, 1.0f);
+ RS::get_singleton()->instance_geometry_set_transparency(get_instance(), transparency);
+}
+
+float GeometryInstance3D::get_transparency() const {
+ return transparency;
+}
+
+void GeometryInstance3D::set_visibility_range_begin(float p_dist) {
+ visibility_range_begin = p_dist;
+ RS::get_singleton()->instance_geometry_set_visibility_range(get_instance(), visibility_range_begin, visibility_range_end, visibility_range_begin_margin, visibility_range_end_margin, (RS::VisibilityRangeFadeMode)visibility_range_fade_mode);
+ update_configuration_warnings();
+}
+
+float GeometryInstance3D::get_visibility_range_begin() const {
+ return visibility_range_begin;
}
-float GeometryInstance3D::get_lod_min_distance() const {
- return lod_min_distance;
+void GeometryInstance3D::set_visibility_range_end(float p_dist) {
+ visibility_range_end = p_dist;
+ RS::get_singleton()->instance_geometry_set_visibility_range(get_instance(), visibility_range_begin, visibility_range_end, visibility_range_begin_margin, visibility_range_end_margin, (RS::VisibilityRangeFadeMode)visibility_range_fade_mode);
+ update_configuration_warnings();
}
-void GeometryInstance3D::set_lod_max_distance(float p_dist) {
- lod_max_distance = p_dist;
- RS::get_singleton()->instance_geometry_set_draw_range(get_instance(), lod_min_distance, lod_max_distance, lod_min_hysteresis, lod_max_hysteresis);
+float GeometryInstance3D::get_visibility_range_end() const {
+ return visibility_range_end;
}
-float GeometryInstance3D::get_lod_max_distance() const {
- return lod_max_distance;
+void GeometryInstance3D::set_visibility_range_begin_margin(float p_dist) {
+ visibility_range_begin_margin = p_dist;
+ RS::get_singleton()->instance_geometry_set_visibility_range(get_instance(), visibility_range_begin, visibility_range_end, visibility_range_begin_margin, visibility_range_end_margin, (RS::VisibilityRangeFadeMode)visibility_range_fade_mode);
+ update_configuration_warnings();
}
-void GeometryInstance3D::set_lod_min_hysteresis(float p_dist) {
- lod_min_hysteresis = p_dist;
- RS::get_singleton()->instance_geometry_set_draw_range(get_instance(), lod_min_distance, lod_max_distance, lod_min_hysteresis, lod_max_hysteresis);
+float GeometryInstance3D::get_visibility_range_begin_margin() const {
+ return visibility_range_begin_margin;
}
-float GeometryInstance3D::get_lod_min_hysteresis() const {
- return lod_min_hysteresis;
+void GeometryInstance3D::set_visibility_range_end_margin(float p_dist) {
+ visibility_range_end_margin = p_dist;
+ RS::get_singleton()->instance_geometry_set_visibility_range(get_instance(), visibility_range_begin, visibility_range_end, visibility_range_begin_margin, visibility_range_end_margin, (RS::VisibilityRangeFadeMode)visibility_range_fade_mode);
+ update_configuration_warnings();
}
-void GeometryInstance3D::set_lod_max_hysteresis(float p_dist) {
- lod_max_hysteresis = p_dist;
- RS::get_singleton()->instance_geometry_set_draw_range(get_instance(), lod_min_distance, lod_max_distance, lod_min_hysteresis, lod_max_hysteresis);
+float GeometryInstance3D::get_visibility_range_end_margin() const {
+ return visibility_range_end_margin;
}
-float GeometryInstance3D::get_lod_max_hysteresis() const {
- return lod_max_hysteresis;
+void GeometryInstance3D::set_visibility_range_fade_mode(VisibilityRangeFadeMode p_mode) {
+ visibility_range_fade_mode = p_mode;
+ RS::get_singleton()->instance_geometry_set_visibility_range(get_instance(), visibility_range_begin, visibility_range_end, visibility_range_begin_margin, visibility_range_end_margin, (RS::VisibilityRangeFadeMode)visibility_range_fade_mode);
+ update_configuration_warnings();
}
-void GeometryInstance3D::_notification(int p_what) {
+GeometryInstance3D::VisibilityRangeFadeMode GeometryInstance3D::get_visibility_range_fade_mode() const {
+ return visibility_range_fade_mode;
}
const StringName *GeometryInstance3D::_instance_uniform_get_remap(const StringName p_name) const {
@@ -213,7 +247,7 @@ bool GeometryInstance3D::_set(const StringName &p_name, const Variant &p_value)
}
#ifndef DISABLE_DEPRECATED
if (p_name == SceneStringNames::get_singleton()->use_in_baked_light && bool(p_value)) {
- set_gi_mode(GI_MODE_BAKED);
+ set_gi_mode(GI_MODE_STATIC);
return true;
}
@@ -238,17 +272,16 @@ bool GeometryInstance3D::_get(const StringName &p_name, Variant &r_ret) const {
void GeometryInstance3D::_get_property_list(List<PropertyInfo> *p_list) const {
List<PropertyInfo> pinfo;
RS::get_singleton()->instance_geometry_get_shader_parameter_list(get_instance(), &pinfo);
- for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) {
- PropertyInfo pi = E->get();
+ for (PropertyInfo &pi : pinfo) {
bool has_def_value = false;
Variant def_value = RS::get_singleton()->instance_geometry_get_shader_parameter_default_value(get_instance(), pi.name);
if (def_value.get_type() != Variant::NIL) {
has_def_value = true;
}
if (instance_uniforms.has(pi.name)) {
- pi.usage = PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_STORAGE | (has_def_value ? (PROPERTY_USAGE_CHECKABLE | PROPERTY_USAGE_CHECKED) : 0);
+ pi.usage = PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_STORAGE | (has_def_value ? (PROPERTY_USAGE_CHECKABLE | PROPERTY_USAGE_CHECKED) : PROPERTY_USAGE_NONE);
} else {
- pi.usage = PROPERTY_USAGE_EDITOR | (has_def_value ? PROPERTY_USAGE_CHECKABLE : 0); //do not save if not changed
+ pi.usage = PROPERTY_USAGE_EDITOR | (has_def_value ? PROPERTY_USAGE_CHECKABLE : PROPERTY_USAGE_NONE); //do not save if not changed
}
pi.name = "shader_params/" + pi.name;
@@ -293,7 +326,12 @@ void GeometryInstance3D::set_shader_instance_uniform(const StringName &p_uniform
instance_uniforms.erase(p_value);
} else {
instance_uniforms[p_uniform] = p_value;
- RS::get_singleton()->instance_geometry_set_shader_parameter(get_instance(), p_uniform, p_value);
+ if (p_value.get_type() == Variant::OBJECT) {
+ RID tex_id = p_value;
+ RS::get_singleton()->instance_geometry_set_shader_parameter(get_instance(), p_uniform, tex_id);
+ } else {
+ RS::get_singleton()->instance_geometry_set_shader_parameter(get_instance(), p_uniform, p_value);
+ }
}
}
@@ -320,7 +358,7 @@ void GeometryInstance3D::set_gi_mode(GIMode p_mode) {
RS::get_singleton()->instance_geometry_set_flag(get_instance(), RS::INSTANCE_FLAG_USE_BAKED_LIGHT, false);
RS::get_singleton()->instance_geometry_set_flag(get_instance(), RS::INSTANCE_FLAG_USE_DYNAMIC_GI, false);
} break;
- case GI_MODE_BAKED: {
+ case GI_MODE_STATIC: {
RS::get_singleton()->instance_geometry_set_flag(get_instance(), RS::INSTANCE_FLAG_USE_BAKED_LIGHT, true);
RS::get_singleton()->instance_geometry_set_flag(get_instance(), RS::INSTANCE_FLAG_USE_DYNAMIC_GI, false);
@@ -347,27 +385,54 @@ bool GeometryInstance3D::is_ignoring_occlusion_culling() {
return ignore_occlusion_culling;
}
+TypedArray<String> GeometryInstance3D::get_configuration_warnings() const {
+ TypedArray<String> warnings = Node::get_configuration_warnings();
+
+ if (!Math::is_zero_approx(visibility_range_end) && visibility_range_end <= visibility_range_begin) {
+ warnings.push_back(RTR("The GeometryInstance3D visibility range's End distance is set to a non-zero value, but is lower than the Begin distance.\nThis means the GeometryInstance3D will never be visible.\nTo resolve this, set the End distance to 0 or to a value greater than the Begin distance."));
+ }
+
+ if ((visibility_range_fade_mode == VISIBILITY_RANGE_FADE_SELF || visibility_range_fade_mode == VISIBILITY_RANGE_FADE_DEPENDENCIES) && !Math::is_zero_approx(visibility_range_begin) && Math::is_zero_approx(visibility_range_begin_margin)) {
+ warnings.push_back(RTR("The GeometryInstance3D is configured to fade in smoothly over distance, but the fade transition distance is set to 0.\nTo resolve this, increase Visibility Range Begin Margin above 0."));
+ }
+
+ if ((visibility_range_fade_mode == VISIBILITY_RANGE_FADE_SELF || visibility_range_fade_mode == VISIBILITY_RANGE_FADE_DEPENDENCIES) && !Math::is_zero_approx(visibility_range_end) && Math::is_zero_approx(visibility_range_end_margin)) {
+ warnings.push_back(RTR("The GeometryInstance3D is configured to fade out smoothly over distance, but the fade transition distance is set to 0.\nTo resolve this, increase Visibility Range End Margin above 0."));
+ }
+
+ return warnings;
+}
+
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);
+ ClassDB::bind_method(D_METHOD("set_material_overlay", "material"), &GeometryInstance3D::set_material_overlay);
+ ClassDB::bind_method(D_METHOD("get_material_overlay"), &GeometryInstance3D::get_material_overlay);
+
ClassDB::bind_method(D_METHOD("set_cast_shadows_setting", "shadow_casting_setting"), &GeometryInstance3D::set_cast_shadows_setting);
ClassDB::bind_method(D_METHOD("get_cast_shadows_setting"), &GeometryInstance3D::get_cast_shadows_setting);
ClassDB::bind_method(D_METHOD("set_lod_bias", "bias"), &GeometryInstance3D::set_lod_bias);
ClassDB::bind_method(D_METHOD("get_lod_bias"), &GeometryInstance3D::get_lod_bias);
- ClassDB::bind_method(D_METHOD("set_lod_max_hysteresis", "mode"), &GeometryInstance3D::set_lod_max_hysteresis);
- ClassDB::bind_method(D_METHOD("get_lod_max_hysteresis"), &GeometryInstance3D::get_lod_max_hysteresis);
+ ClassDB::bind_method(D_METHOD("set_transparency", "transparency"), &GeometryInstance3D::set_transparecy);
+ ClassDB::bind_method(D_METHOD("get_transparency"), &GeometryInstance3D::get_transparency);
+
+ ClassDB::bind_method(D_METHOD("set_visibility_range_end_margin", "distance"), &GeometryInstance3D::set_visibility_range_end_margin);
+ ClassDB::bind_method(D_METHOD("get_visibility_range_end_margin"), &GeometryInstance3D::get_visibility_range_end_margin);
- ClassDB::bind_method(D_METHOD("set_lod_max_distance", "mode"), &GeometryInstance3D::set_lod_max_distance);
- ClassDB::bind_method(D_METHOD("get_lod_max_distance"), &GeometryInstance3D::get_lod_max_distance);
+ ClassDB::bind_method(D_METHOD("set_visibility_range_end", "distance"), &GeometryInstance3D::set_visibility_range_end);
+ ClassDB::bind_method(D_METHOD("get_visibility_range_end"), &GeometryInstance3D::get_visibility_range_end);
- ClassDB::bind_method(D_METHOD("set_lod_min_hysteresis", "mode"), &GeometryInstance3D::set_lod_min_hysteresis);
- ClassDB::bind_method(D_METHOD("get_lod_min_hysteresis"), &GeometryInstance3D::get_lod_min_hysteresis);
+ ClassDB::bind_method(D_METHOD("set_visibility_range_begin_margin", "distance"), &GeometryInstance3D::set_visibility_range_begin_margin);
+ ClassDB::bind_method(D_METHOD("get_visibility_range_begin_margin"), &GeometryInstance3D::get_visibility_range_begin_margin);
- ClassDB::bind_method(D_METHOD("set_lod_min_distance", "mode"), &GeometryInstance3D::set_lod_min_distance);
- ClassDB::bind_method(D_METHOD("get_lod_min_distance"), &GeometryInstance3D::get_lod_min_distance);
+ ClassDB::bind_method(D_METHOD("set_visibility_range_begin", "distance"), &GeometryInstance3D::set_visibility_range_begin);
+ ClassDB::bind_method(D_METHOD("get_visibility_range_begin"), &GeometryInstance3D::get_visibility_range_begin);
+
+ ClassDB::bind_method(D_METHOD("set_visibility_range_fade_mode", "mode"), &GeometryInstance3D::set_visibility_range_fade_mode);
+ ClassDB::bind_method(D_METHOD("get_visibility_range_fade_mode"), &GeometryInstance3D::get_visibility_range_fade_mode);
ClassDB::bind_method(D_METHOD("set_shader_instance_uniform", "uniform", "value"), &GeometryInstance3D::set_shader_instance_uniform);
ClassDB::bind_method(D_METHOD("get_shader_instance_uniform", "uniform"), &GeometryInstance3D::get_shader_instance_uniform);
@@ -389,21 +454,23 @@ void GeometryInstance3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_aabb"), &GeometryInstance3D::get_aabb);
ADD_GROUP("Geometry", "");
- ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "material_override", PROPERTY_HINT_RESOURCE_TYPE, "ShaderMaterial,StandardMaterial3D", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_DEFERRED_SET_RESOURCE), "set_material_override", "get_material_override");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "material_override", PROPERTY_HINT_RESOURCE_TYPE, "BaseMaterial3D,ShaderMaterial", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_DEFERRED_SET_RESOURCE), "set_material_override", "get_material_override");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "material_overlay", PROPERTY_HINT_RESOURCE_TYPE, "BaseMaterial3D,ShaderMaterial", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_DEFERRED_SET_RESOURCE), "set_material_overlay", "get_material_overlay");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "transparency", PROPERTY_HINT_RANGE, "0.0,1.0,0.01"), "set_transparency", "get_transparency");
ADD_PROPERTY(PropertyInfo(Variant::INT, "cast_shadow", PROPERTY_HINT_ENUM, "Off,On,Double-Sided,Shadows Only"), "set_cast_shadows_setting", "get_cast_shadows_setting");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "extra_cull_margin", PROPERTY_HINT_RANGE, "0,16384,0.01"), "set_extra_cull_margin", "get_extra_cull_margin");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "lod_bias", PROPERTY_HINT_RANGE, "0.001,128,0.001"), "set_lod_bias", "get_lod_bias");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "ignore_occlusion_culling"), "set_ignore_occlusion_culling", "is_ignoring_occlusion_culling");
ADD_GROUP("Global Illumination", "gi_");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "gi_mode", PROPERTY_HINT_ENUM, "Disabled,Baked,Dynamic"), "set_gi_mode", "get_gi_mode");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "gi_lightmap_scale", PROPERTY_HINT_ENUM, "1x,2x,4x,8x"), "set_lightmap_scale", "get_lightmap_scale");
-
- ADD_GROUP("LOD", "lod_");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "lod_min_distance", PROPERTY_HINT_RANGE, "0,32768,0.01"), "set_lod_min_distance", "get_lod_min_distance");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "lod_min_hysteresis", PROPERTY_HINT_RANGE, "0,32768,0.01"), "set_lod_min_hysteresis", "get_lod_min_hysteresis");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "lod_max_distance", PROPERTY_HINT_RANGE, "0,32768,0.01"), "set_lod_max_distance", "get_lod_max_distance");
- ADD_PROPERTY(PropertyInfo(Variant::INT, "lod_max_hysteresis", PROPERTY_HINT_RANGE, "0,32768,0.01"), "set_lod_max_hysteresis", "get_lod_max_hysteresis");
-
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "gi_mode", PROPERTY_HINT_ENUM, "Disabled,Static (VoxelGI/SDFGI/LightmapGI),Dynamic (VoxelGI only)"), "set_gi_mode", "get_gi_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "gi_lightmap_scale", PROPERTY_HINT_ENUM, String::utf8("1×,2×,4×,8×")), "set_lightmap_scale", "get_lightmap_scale");
+
+ ADD_GROUP("Visibility Range", "visibility_range_");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "visibility_range_begin", PROPERTY_HINT_RANGE, "0.0,4096.0,0.01"), "set_visibility_range_begin", "get_visibility_range_begin");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "visibility_range_begin_margin", PROPERTY_HINT_RANGE, "0.0,4096.0,0.01"), "set_visibility_range_begin_margin", "get_visibility_range_begin_margin");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "visibility_range_end", PROPERTY_HINT_RANGE, "0.0,4096.0,0.01"), "set_visibility_range_end", "get_visibility_range_end");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "visibility_range_end_margin", PROPERTY_HINT_RANGE, "0.0,4096.0,0.01"), "set_visibility_range_end_margin", "get_visibility_range_end_margin");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "visibility_range_fade_mode", PROPERTY_HINT_ENUM, "Disabled,Self,Dependencies"), "set_visibility_range_fade_mode", "get_visibility_range_fade_mode");
//ADD_SIGNAL( MethodInfo("visibility_changed"));
BIND_ENUM_CONSTANT(SHADOW_CASTING_SETTING_OFF);
@@ -412,7 +479,7 @@ void GeometryInstance3D::_bind_methods() {
BIND_ENUM_CONSTANT(SHADOW_CASTING_SETTING_SHADOWS_ONLY);
BIND_ENUM_CONSTANT(GI_MODE_DISABLED);
- BIND_ENUM_CONSTANT(GI_MODE_BAKED);
+ BIND_ENUM_CONSTANT(GI_MODE_STATIC);
BIND_ENUM_CONSTANT(GI_MODE_DYNAMIC);
BIND_ENUM_CONSTANT(LIGHTMAP_SCALE_1X);
@@ -420,6 +487,10 @@ void GeometryInstance3D::_bind_methods() {
BIND_ENUM_CONSTANT(LIGHTMAP_SCALE_4X);
BIND_ENUM_CONSTANT(LIGHTMAP_SCALE_8X);
BIND_ENUM_CONSTANT(LIGHTMAP_SCALE_MAX);
+
+ BIND_ENUM_CONSTANT(VISIBILITY_RANGE_FADE_DISABLED);
+ BIND_ENUM_CONSTANT(VISIBILITY_RANGE_FADE_SELF);
+ BIND_ENUM_CONSTANT(VISIBILITY_RANGE_FADE_DEPENDENCIES);
}
GeometryInstance3D::GeometryInstance3D() {
diff --git a/scene/3d/visual_instance_3d.h b/scene/3d/visual_instance_3d.h
index 68d29ef81e..f8fd4378fe 100644
--- a/scene/3d/visual_instance_3d.h
+++ b/scene/3d/visual_instance_3d.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -31,14 +31,10 @@
#ifndef VISUAL_INSTANCE_H
#define VISUAL_INSTANCE_H
-#include "core/math/face3.h"
-#include "core/templates/rid.h"
#include "scene/3d/node_3d.h"
-#include "scene/resources/material.h"
class VisualInstance3D : public Node3D {
GDCLASS(VisualInstance3D, Node3D);
- OBJ_CATEGORY("3D Visual Nodes");
RID base;
RID instance;
@@ -52,6 +48,7 @@ protected:
void _notification(int p_what);
static void _bind_methods();
+ GDVIRTUAL0RC(AABB, _get_aabb)
public:
enum GetFacesFlags {
FACES_SOLID = 1, // solid geometry
@@ -61,8 +58,7 @@ public:
};
RID get_instance() const;
- virtual AABB get_aabb() const = 0;
- virtual Vector<Face3> get_faces(uint32_t p_usage_flags) const = 0;
+ virtual AABB get_aabb() const;
virtual AABB get_transformed_aabb() const; // helper
@@ -72,8 +68,8 @@ public:
void set_layer_mask(uint32_t p_mask);
uint32_t get_layer_mask() const;
- void set_layer_mask_bit(int p_layer, bool p_enable);
- bool get_layer_mask_bit(int p_layer) const;
+ void set_layer_mask_value(int p_layer_number, bool p_enable);
+ bool get_layer_mask_value(int p_layer_number) const;
VisualInstance3D();
~VisualInstance3D();
@@ -92,7 +88,7 @@ public:
enum GIMode {
GI_MODE_DISABLED,
- GI_MODE_BAKED,
+ GI_MODE_STATIC,
GI_MODE_DYNAMIC
};
@@ -104,13 +100,24 @@ public:
LIGHTMAP_SCALE_MAX,
};
+ enum VisibilityRangeFadeMode {
+ VISIBILITY_RANGE_FADE_DISABLED = RS::VISIBILITY_RANGE_FADE_DISABLED,
+ VISIBILITY_RANGE_FADE_SELF = RS::VISIBILITY_RANGE_FADE_SELF,
+ VISIBILITY_RANGE_FADE_DEPENDENCIES = RS::VISIBILITY_RANGE_FADE_DEPENDENCIES,
+ };
+
private:
ShadowCastingSetting shadow_casting_setting = SHADOW_CASTING_SETTING_ON;
Ref<Material> material_override;
- float lod_min_distance = 0.0;
- float lod_max_distance = 0.0;
- float lod_min_hysteresis = 0.0;
- float lod_max_hysteresis = 0.0;
+ Ref<Material> material_overlay;
+
+ float visibility_range_begin = 0.0;
+ float visibility_range_end = 0.0;
+ float visibility_range_begin_margin = 0.0;
+ float visibility_range_end_margin = 0.0;
+ VisibilityRangeFadeMode visibility_range_fade_mode = VISIBILITY_RANGE_FADE_DISABLED;
+
+ float transparency = 0.0f;
float lod_bias = 1.0;
@@ -129,28 +136,36 @@ protected:
bool _get(const StringName &p_name, Variant &r_ret) const;
void _get_property_list(List<PropertyInfo> *p_list) const;
- void _notification(int p_what);
static void _bind_methods();
public:
void set_cast_shadows_setting(ShadowCastingSetting p_shadow_casting_setting);
ShadowCastingSetting get_cast_shadows_setting() const;
- void set_lod_min_distance(float p_dist);
- float get_lod_min_distance() const;
+ void set_transparecy(float p_transparency);
+ float get_transparency() const;
+
+ void set_visibility_range_begin(float p_dist);
+ float get_visibility_range_begin() const;
- void set_lod_max_distance(float p_dist);
- float get_lod_max_distance() const;
+ void set_visibility_range_end(float p_dist);
+ float get_visibility_range_end() const;
- void set_lod_min_hysteresis(float p_dist);
- float get_lod_min_hysteresis() const;
+ void set_visibility_range_begin_margin(float p_dist);
+ float get_visibility_range_begin_margin() const;
- void set_lod_max_hysteresis(float p_dist);
- float get_lod_max_hysteresis() const;
+ void set_visibility_range_end_margin(float p_dist);
+ float get_visibility_range_end_margin() const;
+
+ void set_visibility_range_fade_mode(VisibilityRangeFadeMode p_mode);
+ VisibilityRangeFadeMode get_visibility_range_fade_mode() const;
void set_material_override(const Ref<Material> &p_material);
Ref<Material> get_material_override() const;
+ void set_material_overlay(const Ref<Material> &p_material);
+ Ref<Material> get_material_overlay() const;
+
void set_extra_cull_margin(float p_margin);
float get_extra_cull_margin() const;
@@ -171,11 +186,13 @@ public:
void set_ignore_occlusion_culling(bool p_enabled);
bool is_ignoring_occlusion_culling();
+ TypedArray<String> get_configuration_warnings() const override;
GeometryInstance3D();
};
VARIANT_ENUM_CAST(GeometryInstance3D::ShadowCastingSetting);
VARIANT_ENUM_CAST(GeometryInstance3D::LightmapScale);
VARIANT_ENUM_CAST(GeometryInstance3D::GIMode);
+VARIANT_ENUM_CAST(GeometryInstance3D::VisibilityRangeFadeMode);
#endif
diff --git a/scene/3d/gi_probe.cpp b/scene/3d/voxel_gi.cpp
index 6505fb1ee8..29e495ce1b 100644
--- a/scene/3d/gi_probe.cpp
+++ b/scene/3d/voxel_gi.cpp
@@ -1,12 +1,12 @@
/*************************************************************************/
-/* gi_probe.cpp */
+/* voxel_gi.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -28,14 +28,13 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#include "gi_probe.h"
-
-#include "core/os/os.h"
+#include "voxel_gi.h"
#include "mesh_instance_3d.h"
+#include "multimesh_instance_3d.h"
#include "voxelizer.h"
-void GIProbeData::_set_data(const Dictionary &p_data) {
+void VoxelGIData::_set_data(const Dictionary &p_data) {
ERR_FAIL_COND(!p_data.has("bounds"));
ERR_FAIL_COND(!p_data.has("octree_size"));
ERR_FAIL_COND(!p_data.has("octree_cells"));
@@ -55,19 +54,19 @@ void GIProbeData::_set_data(const Dictionary &p_data) {
} else if (p_data.has("octree_df_png")) {
Vector<uint8_t> octree_df_png = p_data["octree_df_png"];
Ref<Image> img;
- img.instance();
+ img.instantiate();
Error err = img->load_png_from_buffer(octree_df_png);
ERR_FAIL_COND(err != OK);
ERR_FAIL_COND(img->get_format() != Image::FORMAT_L8);
octree_df = img->get_data();
}
Vector<int> octree_levels = p_data["level_counts"];
- Transform to_cell_xform = p_data["to_cell_xform"];
+ Transform3D to_cell_xform = p_data["to_cell_xform"];
allocate(to_cell_xform, bounds, octree_size, octree_cells, octree_data, octree_df, octree_levels);
}
-Dictionary GIProbeData::_get_data() const {
+Dictionary VoxelGIData::_get_data() const {
Dictionary d;
d["bounds"] = get_bounds();
Vector3i otsize = get_octree_size();
@@ -76,7 +75,7 @@ Dictionary GIProbeData::_get_data() const {
d["octree_data"] = get_data_cells();
if (otsize != Vector3i()) {
Ref<Image> img;
- img.instance();
+ img.instantiate();
img->create(otsize.x * otsize.y, otsize.z, false, Image::FORMAT_L8, get_distance_field());
Vector<uint8_t> df_png = img->save_png_to_buffer();
ERR_FAIL_COND_V(df_png.size() == 0, Dictionary());
@@ -90,213 +89,165 @@ Dictionary GIProbeData::_get_data() const {
return d;
}
-void GIProbeData::allocate(const Transform &p_to_cell_xform, const AABB &p_aabb, const Vector3 &p_octree_size, const Vector<uint8_t> &p_octree_cells, const Vector<uint8_t> &p_data_cells, const Vector<uint8_t> &p_distance_field, const Vector<int> &p_level_counts) {
- RS::get_singleton()->gi_probe_allocate_data(probe, p_to_cell_xform, p_aabb, p_octree_size, p_octree_cells, p_data_cells, p_distance_field, p_level_counts);
+void VoxelGIData::allocate(const Transform3D &p_to_cell_xform, const AABB &p_aabb, const Vector3 &p_octree_size, const Vector<uint8_t> &p_octree_cells, const Vector<uint8_t> &p_data_cells, const Vector<uint8_t> &p_distance_field, const Vector<int> &p_level_counts) {
+ RS::get_singleton()->voxel_gi_allocate_data(probe, p_to_cell_xform, p_aabb, p_octree_size, p_octree_cells, p_data_cells, p_distance_field, p_level_counts);
bounds = p_aabb;
to_cell_xform = p_to_cell_xform;
octree_size = p_octree_size;
}
-AABB GIProbeData::get_bounds() const {
+AABB VoxelGIData::get_bounds() const {
return bounds;
}
-Vector3 GIProbeData::get_octree_size() const {
+Vector3 VoxelGIData::get_octree_size() const {
return octree_size;
}
-Vector<uint8_t> GIProbeData::get_octree_cells() const {
- return RS::get_singleton()->gi_probe_get_octree_cells(probe);
+Vector<uint8_t> VoxelGIData::get_octree_cells() const {
+ return RS::get_singleton()->voxel_gi_get_octree_cells(probe);
}
-Vector<uint8_t> GIProbeData::get_data_cells() const {
- return RS::get_singleton()->gi_probe_get_data_cells(probe);
+Vector<uint8_t> VoxelGIData::get_data_cells() const {
+ return RS::get_singleton()->voxel_gi_get_data_cells(probe);
}
-Vector<uint8_t> GIProbeData::get_distance_field() const {
- return RS::get_singleton()->gi_probe_get_distance_field(probe);
+Vector<uint8_t> VoxelGIData::get_distance_field() const {
+ return RS::get_singleton()->voxel_gi_get_distance_field(probe);
}
-Vector<int> GIProbeData::get_level_counts() const {
- return RS::get_singleton()->gi_probe_get_level_counts(probe);
+Vector<int> VoxelGIData::get_level_counts() const {
+ return RS::get_singleton()->voxel_gi_get_level_counts(probe);
}
-Transform GIProbeData::get_to_cell_xform() const {
+Transform3D VoxelGIData::get_to_cell_xform() const {
return to_cell_xform;
}
-void GIProbeData::set_dynamic_range(float p_range) {
- RS::get_singleton()->gi_probe_set_dynamic_range(probe, p_range);
+void VoxelGIData::set_dynamic_range(float p_range) {
+ RS::get_singleton()->voxel_gi_set_dynamic_range(probe, p_range);
dynamic_range = p_range;
}
-float GIProbeData::get_dynamic_range() const {
+float VoxelGIData::get_dynamic_range() const {
return dynamic_range;
}
-void GIProbeData::set_propagation(float p_propagation) {
- RS::get_singleton()->gi_probe_set_propagation(probe, p_propagation);
+void VoxelGIData::set_propagation(float p_propagation) {
+ RS::get_singleton()->voxel_gi_set_propagation(probe, p_propagation);
propagation = p_propagation;
}
-float GIProbeData::get_propagation() const {
+float VoxelGIData::get_propagation() const {
return propagation;
}
-void GIProbeData::set_anisotropy_strength(float p_anisotropy_strength) {
- RS::get_singleton()->gi_probe_set_anisotropy_strength(probe, p_anisotropy_strength);
- anisotropy_strength = p_anisotropy_strength;
-}
-
-float GIProbeData::get_anisotropy_strength() const {
- return anisotropy_strength;
-}
-
-void GIProbeData::set_energy(float p_energy) {
- RS::get_singleton()->gi_probe_set_energy(probe, p_energy);
+void VoxelGIData::set_energy(float p_energy) {
+ RS::get_singleton()->voxel_gi_set_energy(probe, p_energy);
energy = p_energy;
}
-float GIProbeData::get_energy() const {
+float VoxelGIData::get_energy() const {
return energy;
}
-void GIProbeData::set_ao(float p_ao) {
- RS::get_singleton()->gi_probe_set_ao(probe, p_ao);
- ao = p_ao;
-}
-
-float GIProbeData::get_ao() const {
- return ao;
-}
-
-void GIProbeData::set_ao_size(float p_ao_size) {
- RS::get_singleton()->gi_probe_set_ao_size(probe, p_ao_size);
- ao_size = p_ao_size;
-}
-
-float GIProbeData::get_ao_size() const {
- return ao_size;
-}
-
-void GIProbeData::set_bias(float p_bias) {
- RS::get_singleton()->gi_probe_set_bias(probe, p_bias);
+void VoxelGIData::set_bias(float p_bias) {
+ RS::get_singleton()->voxel_gi_set_bias(probe, p_bias);
bias = p_bias;
}
-float GIProbeData::get_bias() const {
+float VoxelGIData::get_bias() const {
return bias;
}
-void GIProbeData::set_normal_bias(float p_normal_bias) {
- RS::get_singleton()->gi_probe_set_normal_bias(probe, p_normal_bias);
+void VoxelGIData::set_normal_bias(float p_normal_bias) {
+ RS::get_singleton()->voxel_gi_set_normal_bias(probe, p_normal_bias);
normal_bias = p_normal_bias;
}
-float GIProbeData::get_normal_bias() const {
+float VoxelGIData::get_normal_bias() const {
return normal_bias;
}
-void GIProbeData::set_interior(bool p_enable) {
- RS::get_singleton()->gi_probe_set_interior(probe, p_enable);
+void VoxelGIData::set_interior(bool p_enable) {
+ RS::get_singleton()->voxel_gi_set_interior(probe, p_enable);
interior = p_enable;
}
-bool GIProbeData::is_interior() const {
+bool VoxelGIData::is_interior() const {
return interior;
}
-void GIProbeData::set_use_two_bounces(bool p_enable) {
- RS::get_singleton()->gi_probe_set_use_two_bounces(probe, p_enable);
+void VoxelGIData::set_use_two_bounces(bool p_enable) {
+ RS::get_singleton()->voxel_gi_set_use_two_bounces(probe, p_enable);
use_two_bounces = p_enable;
}
-bool GIProbeData::is_using_two_bounces() const {
+bool VoxelGIData::is_using_two_bounces() const {
return use_two_bounces;
}
-RID GIProbeData::get_rid() const {
+RID VoxelGIData::get_rid() const {
return probe;
}
-void GIProbeData::_validate_property(PropertyInfo &property) const {
- if (property.name == "anisotropy_strength") {
- bool anisotropy_enabled = ProjectSettings::get_singleton()->get("rendering/global_illumination/gi_probes/anisotropic");
- if (!anisotropy_enabled) {
- property.usage = PROPERTY_USAGE_NOEDITOR;
- }
- }
-}
-
-void GIProbeData::_bind_methods() {
- ClassDB::bind_method(D_METHOD("allocate", "to_cell_xform", "aabb", "octree_size", "octree_cells", "data_cells", "distance_field", "level_counts"), &GIProbeData::allocate);
+void VoxelGIData::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("allocate", "to_cell_xform", "aabb", "octree_size", "octree_cells", "data_cells", "distance_field", "level_counts"), &VoxelGIData::allocate);
- ClassDB::bind_method(D_METHOD("get_bounds"), &GIProbeData::get_bounds);
- ClassDB::bind_method(D_METHOD("get_octree_size"), &GIProbeData::get_octree_size);
- ClassDB::bind_method(D_METHOD("get_to_cell_xform"), &GIProbeData::get_to_cell_xform);
- ClassDB::bind_method(D_METHOD("get_octree_cells"), &GIProbeData::get_octree_cells);
- ClassDB::bind_method(D_METHOD("get_data_cells"), &GIProbeData::get_data_cells);
- ClassDB::bind_method(D_METHOD("get_level_counts"), &GIProbeData::get_level_counts);
+ ClassDB::bind_method(D_METHOD("get_bounds"), &VoxelGIData::get_bounds);
+ ClassDB::bind_method(D_METHOD("get_octree_size"), &VoxelGIData::get_octree_size);
+ ClassDB::bind_method(D_METHOD("get_to_cell_xform"), &VoxelGIData::get_to_cell_xform);
+ ClassDB::bind_method(D_METHOD("get_octree_cells"), &VoxelGIData::get_octree_cells);
+ ClassDB::bind_method(D_METHOD("get_data_cells"), &VoxelGIData::get_data_cells);
+ ClassDB::bind_method(D_METHOD("get_level_counts"), &VoxelGIData::get_level_counts);
- ClassDB::bind_method(D_METHOD("set_dynamic_range", "dynamic_range"), &GIProbeData::set_dynamic_range);
- ClassDB::bind_method(D_METHOD("get_dynamic_range"), &GIProbeData::get_dynamic_range);
+ ClassDB::bind_method(D_METHOD("set_dynamic_range", "dynamic_range"), &VoxelGIData::set_dynamic_range);
+ ClassDB::bind_method(D_METHOD("get_dynamic_range"), &VoxelGIData::get_dynamic_range);
- ClassDB::bind_method(D_METHOD("set_energy", "energy"), &GIProbeData::set_energy);
- ClassDB::bind_method(D_METHOD("get_energy"), &GIProbeData::get_energy);
+ ClassDB::bind_method(D_METHOD("set_energy", "energy"), &VoxelGIData::set_energy);
+ ClassDB::bind_method(D_METHOD("get_energy"), &VoxelGIData::get_energy);
- ClassDB::bind_method(D_METHOD("set_bias", "bias"), &GIProbeData::set_bias);
- ClassDB::bind_method(D_METHOD("get_bias"), &GIProbeData::get_bias);
+ ClassDB::bind_method(D_METHOD("set_bias", "bias"), &VoxelGIData::set_bias);
+ ClassDB::bind_method(D_METHOD("get_bias"), &VoxelGIData::get_bias);
- ClassDB::bind_method(D_METHOD("set_normal_bias", "bias"), &GIProbeData::set_normal_bias);
- ClassDB::bind_method(D_METHOD("get_normal_bias"), &GIProbeData::get_normal_bias);
+ ClassDB::bind_method(D_METHOD("set_normal_bias", "bias"), &VoxelGIData::set_normal_bias);
+ ClassDB::bind_method(D_METHOD("get_normal_bias"), &VoxelGIData::get_normal_bias);
- ClassDB::bind_method(D_METHOD("set_propagation", "propagation"), &GIProbeData::set_propagation);
- ClassDB::bind_method(D_METHOD("get_propagation"), &GIProbeData::get_propagation);
+ ClassDB::bind_method(D_METHOD("set_propagation", "propagation"), &VoxelGIData::set_propagation);
+ ClassDB::bind_method(D_METHOD("get_propagation"), &VoxelGIData::get_propagation);
- ClassDB::bind_method(D_METHOD("set_anisotropy_strength", "strength"), &GIProbeData::set_anisotropy_strength);
- ClassDB::bind_method(D_METHOD("get_anisotropy_strength"), &GIProbeData::get_anisotropy_strength);
+ ClassDB::bind_method(D_METHOD("set_interior", "interior"), &VoxelGIData::set_interior);
+ ClassDB::bind_method(D_METHOD("is_interior"), &VoxelGIData::is_interior);
- ClassDB::bind_method(D_METHOD("set_ao", "ao"), &GIProbeData::set_ao);
- ClassDB::bind_method(D_METHOD("get_ao"), &GIProbeData::get_ao);
+ ClassDB::bind_method(D_METHOD("set_use_two_bounces", "enable"), &VoxelGIData::set_use_two_bounces);
+ ClassDB::bind_method(D_METHOD("is_using_two_bounces"), &VoxelGIData::is_using_two_bounces);
- ClassDB::bind_method(D_METHOD("set_ao_size", "strength"), &GIProbeData::set_ao_size);
- ClassDB::bind_method(D_METHOD("get_ao_size"), &GIProbeData::get_ao_size);
+ ClassDB::bind_method(D_METHOD("_set_data", "data"), &VoxelGIData::_set_data);
+ ClassDB::bind_method(D_METHOD("_get_data"), &VoxelGIData::_get_data);
- ClassDB::bind_method(D_METHOD("set_interior", "interior"), &GIProbeData::set_interior);
- ClassDB::bind_method(D_METHOD("is_interior"), &GIProbeData::is_interior);
+ ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "_data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL), "_set_data", "_get_data");
- ClassDB::bind_method(D_METHOD("set_use_two_bounces", "enable"), &GIProbeData::set_use_two_bounces);
- ClassDB::bind_method(D_METHOD("is_using_two_bounces"), &GIProbeData::is_using_two_bounces);
-
- ClassDB::bind_method(D_METHOD("_set_data", "data"), &GIProbeData::_set_data);
- ClassDB::bind_method(D_METHOD("_get_data"), &GIProbeData::_get_data);
-
- ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "_data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL), "_set_data", "_get_data");
-
- ADD_PROPERTY(PropertyInfo(Variant::INT, "dynamic_range", PROPERTY_HINT_RANGE, "0,8,0.01"), "set_dynamic_range", "get_dynamic_range");
+ ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "dynamic_range", PROPERTY_HINT_RANGE, "1,8,0.01"), "set_dynamic_range", "get_dynamic_range");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "energy", PROPERTY_HINT_RANGE, "0,64,0.01"), "set_energy", "get_energy");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "bias", PROPERTY_HINT_RANGE, "0,8,0.01"), "set_bias", "get_bias");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "normal_bias", PROPERTY_HINT_RANGE, "0,8,0.01"), "set_normal_bias", "get_normal_bias");
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "propagation", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_propagation", "get_propagation");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "anisotropy_strength", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_anisotropy_strength", "get_anisotropy_strength");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "ao", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_ao", "get_ao");
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "ao_size", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_ao_size", "get_ao_size");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_two_bounces"), "set_use_two_bounces", "is_using_two_bounces");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "interior"), "set_interior", "is_interior");
}
-GIProbeData::GIProbeData() {
- probe = RS::get_singleton()->gi_probe_create();
+VoxelGIData::VoxelGIData() {
+ probe = RS::get_singleton()->voxel_gi_create();
}
-GIProbeData::~GIProbeData() {
+VoxelGIData::~VoxelGIData() {
RS::get_singleton()->free(probe);
}
//////////////////////
//////////////////////
-void GIProbe::set_probe_data(const Ref<GIProbeData> &p_data) {
+void VoxelGI::set_probe_data(const Ref<VoxelGIData> &p_data) {
if (p_data.is_valid()) {
RS::get_singleton()->instance_set_base(get_instance(), p_data->get_rid());
} else {
@@ -306,37 +257,37 @@ void GIProbe::set_probe_data(const Ref<GIProbeData> &p_data) {
probe_data = p_data;
}
-Ref<GIProbeData> GIProbe::get_probe_data() const {
+Ref<VoxelGIData> VoxelGI::get_probe_data() const {
return probe_data;
}
-void GIProbe::set_subdiv(Subdiv p_subdiv) {
+void VoxelGI::set_subdiv(Subdiv p_subdiv) {
ERR_FAIL_INDEX(p_subdiv, SUBDIV_MAX);
subdiv = p_subdiv;
- update_gizmo();
+ update_gizmos();
}
-GIProbe::Subdiv GIProbe::get_subdiv() const {
+VoxelGI::Subdiv VoxelGI::get_subdiv() const {
return subdiv;
}
-void GIProbe::set_extents(const Vector3 &p_extents) {
+void VoxelGI::set_extents(const Vector3 &p_extents) {
extents = p_extents;
- update_gizmo();
+ update_gizmos();
}
-Vector3 GIProbe::get_extents() const {
+Vector3 VoxelGI::get_extents() const {
return extents;
}
-void GIProbe::_find_meshes(Node *p_at_node, List<PlotMesh> &plot_meshes) {
+void VoxelGI::_find_meshes(Node *p_at_node, List<PlotMesh> &plot_meshes) {
MeshInstance3D *mi = Object::cast_to<MeshInstance3D>(p_at_node);
- if (mi && mi->get_gi_mode() == GeometryInstance3D::GI_MODE_BAKED && mi->is_visible_in_tree()) {
+ if (mi && mi->get_gi_mode() == GeometryInstance3D::GI_MODE_STATIC && mi->is_visible_in_tree()) {
Ref<Mesh> mesh = mi->get_mesh();
if (mesh.is_valid()) {
AABB aabb = mesh->get_aabb();
- Transform xf = get_global_transform().affine_inverse() * mi->get_global_transform();
+ Transform3D xf = get_global_transform().affine_inverse() * mi->get_global_transform();
if (AABB(-extents, extents * 2).intersects(xf.xform(aabb))) {
PlotMesh pm;
@@ -356,7 +307,7 @@ void GIProbe::_find_meshes(Node *p_at_node, List<PlotMesh> &plot_meshes) {
if (s->is_visible_in_tree()) {
Array meshes = p_at_node->call("get_meshes");
for (int i = 0; i < meshes.size(); i += 2) {
- Transform mxf = meshes[i];
+ Transform3D mxf = meshes[i];
Ref<Mesh> mesh = meshes[i + 1];
if (!mesh.is_valid()) {
continue;
@@ -364,7 +315,7 @@ void GIProbe::_find_meshes(Node *p_at_node, List<PlotMesh> &plot_meshes) {
AABB aabb = mesh->get_aabb();
- Transform xf = get_global_transform().affine_inverse() * (s->get_global_transform() * mxf);
+ Transform3D xf = get_global_transform().affine_inverse() * (s->get_global_transform() * mxf);
if (AABB(-extents, extents * 2).intersects(xf.xform(aabb))) {
PlotMesh pm;
@@ -382,11 +333,11 @@ void GIProbe::_find_meshes(Node *p_at_node, List<PlotMesh> &plot_meshes) {
}
}
-GIProbe::BakeBeginFunc GIProbe::bake_begin_function = nullptr;
-GIProbe::BakeStepFunc GIProbe::bake_step_function = nullptr;
-GIProbe::BakeEndFunc GIProbe::bake_end_function = nullptr;
+VoxelGI::BakeBeginFunc VoxelGI::bake_begin_function = nullptr;
+VoxelGI::BakeStepFunc VoxelGI::bake_step_function = nullptr;
+VoxelGI::BakeEndFunc VoxelGI::bake_end_function = nullptr;
-Vector3i GIProbe::get_estimated_cell_size() const {
+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];
@@ -412,7 +363,7 @@ Vector3i GIProbe::get_estimated_cell_size() const {
return Vector3i(axis_cell_size[0], axis_cell_size[1], axis_cell_size[2]);
}
-void GIProbe::bake(Node *p_from_node, bool p_create_visual_debug) {
+void VoxelGI::bake(Node *p_from_node, bool p_create_visual_debug) {
static const int subdiv_value[SUBDIV_MAX] = { 6, 7, 8, 9 };
p_from_node = p_from_node ? p_from_node : get_parent();
@@ -432,14 +383,14 @@ void GIProbe::bake(Node *p_from_node, bool p_create_visual_debug) {
int pmc = 0;
- for (List<PlotMesh>::Element *E = mesh_list.front(); E; E = E->next()) {
+ for (PlotMesh &E : mesh_list) {
if (bake_step_function) {
bake_step_function(pmc, RTR("Plotting Meshes") + " " + itos(pmc) + "/" + itos(mesh_list.size()));
}
pmc++;
- baker.plot_mesh(E->get().local_xform, E->get().mesh, E->get().instance_materials, E->get().override_material);
+ baker.plot_mesh(E.local_xform, E.mesh, E.instance_materials, E.override_material);
}
if (bake_step_function) {
bake_step_function(pmc++, RTR("Finishing Plot"));
@@ -447,12 +398,12 @@ void GIProbe::bake(Node *p_from_node, bool p_create_visual_debug) {
baker.end_bake();
- //create the data for visual server
+ //create the data for rendering server
if (p_create_visual_debug) {
MultiMeshInstance3D *mmi = memnew(MultiMeshInstance3D);
mmi->set_multimesh(baker.create_debug_multimesh());
- add_child(mmi);
+ add_child(mmi, true);
#ifdef TOOLS_ENABLED
if (is_inside_tree() && get_tree()->get_edited_scene_root() == this) {
mmi->set_owner(this);
@@ -464,10 +415,10 @@ void GIProbe::bake(Node *p_from_node, bool p_create_visual_debug) {
#endif
} else {
- Ref<GIProbeData> probe_data = get_probe_data();
+ Ref<VoxelGIData> probe_data = get_probe_data();
if (probe_data.is_null()) {
- probe_data.instance();
+ probe_data.instantiate();
}
if (bake_step_function) {
@@ -476,7 +427,7 @@ void GIProbe::bake(Node *p_from_node, bool p_create_visual_debug) {
Vector<uint8_t> df = baker.get_sdf_3d_image();
- probe_data->allocate(baker.get_to_cell_space_xform(), AABB(-extents, extents * 2.0), baker.get_giprobe_octree_size(), baker.get_giprobe_octree_cells(), baker.get_giprobe_data_cells(), df, baker.get_giprobe_level_cell_count());
+ probe_data->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());
set_probe_data(probe_data);
#ifdef TOOLS_ENABLED
@@ -491,46 +442,42 @@ void GIProbe::bake(Node *p_from_node, bool p_create_visual_debug) {
notify_property_list_changed(); //bake property may have changed
}
-void GIProbe::_debug_bake() {
+void VoxelGI::_debug_bake() {
bake(nullptr, true);
}
-AABB GIProbe::get_aabb() const {
+AABB VoxelGI::get_aabb() const {
return AABB(-extents, extents * 2);
}
-Vector<Face3> GIProbe::get_faces(uint32_t p_usage_flags) const {
- return Vector<Face3>();
-}
-
-TypedArray<String> GIProbe::get_configuration_warnings() const {
+TypedArray<String> VoxelGI::get_configuration_warnings() const {
TypedArray<String> warnings = Node::get_configuration_warnings();
if (RenderingServer::get_singleton()->is_low_end()) {
- warnings.push_back(TTR("GIProbes are not supported by the GLES2 video driver.\nUse a BakedLightmap instead."));
+ warnings.push_back(RTR("VoxelGIs are not supported by the OpenGL video driver.\nUse a LightmapGI instead."));
} else if (probe_data.is_null()) {
- warnings.push_back(TTR("No GIProbe data set, so this node is disabled. Bake static objects to enable GI."));
+ warnings.push_back(RTR("No VoxelGI data set, so this node is disabled. Bake static objects to enable GI."));
}
return warnings;
}
-void GIProbe::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_probe_data", "data"), &GIProbe::set_probe_data);
- ClassDB::bind_method(D_METHOD("get_probe_data"), &GIProbe::get_probe_data);
+void VoxelGI::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("set_probe_data", "data"), &VoxelGI::set_probe_data);
+ ClassDB::bind_method(D_METHOD("get_probe_data"), &VoxelGI::get_probe_data);
- ClassDB::bind_method(D_METHOD("set_subdiv", "subdiv"), &GIProbe::set_subdiv);
- ClassDB::bind_method(D_METHOD("get_subdiv"), &GIProbe::get_subdiv);
+ 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"), &GIProbe::set_extents);
- ClassDB::bind_method(D_METHOD("get_extents"), &GIProbe::get_extents);
+ 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("bake", "from_node", "create_visual_debug"), &GIProbe::bake, DEFVAL(Variant()), DEFVAL(false));
- ClassDB::bind_method(D_METHOD("debug_bake"), &GIProbe::_debug_bake);
+ ClassDB::bind_method(D_METHOD("bake", "from_node", "create_visual_debug"), &VoxelGI::bake, DEFVAL(Variant()), DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("debug_bake"), &VoxelGI::_debug_bake);
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"), "set_extents", "get_extents");
- ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "data", PROPERTY_HINT_RESOURCE_TYPE, "GIProbeData", 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_DO_NOT_SHARE_ON_DUPLICATE), "set_probe_data", "get_probe_data");
BIND_ENUM_CONSTANT(SUBDIV_64);
BIND_ENUM_CONSTANT(SUBDIV_128);
@@ -539,11 +486,11 @@ void GIProbe::_bind_methods() {
BIND_ENUM_CONSTANT(SUBDIV_MAX);
}
-GIProbe::GIProbe() {
- gi_probe = RS::get_singleton()->gi_probe_create();
+VoxelGI::VoxelGI() {
+ voxel_gi = RS::get_singleton()->voxel_gi_create();
set_disable_scale(true);
}
-GIProbe::~GIProbe() {
- RS::get_singleton()->free(gi_probe);
+VoxelGI::~VoxelGI() {
+ RS::get_singleton()->free(voxel_gi);
}
diff --git a/scene/3d/gi_probe.h b/scene/3d/voxel_gi.h
index dac7dd3e17..e1a38dd7a0 100644
--- a/scene/3d/gi_probe.h
+++ b/scene/3d/voxel_gi.h
@@ -1,12 +1,12 @@
/*************************************************************************/
-/* gi_probe.h */
+/* voxel_gi.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -28,48 +28,43 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#ifndef GIPROBE_H
-#define GIPROBE_H
+#ifndef VOXEL_GI_H
+#define VOXEL_GI_H
-#include "multimesh_instance_3d.h"
#include "scene/3d/visual_instance_3d.h"
-class GIProbeData : public Resource {
- GDCLASS(GIProbeData, Resource);
+class VoxelGIData : public Resource {
+ GDCLASS(VoxelGIData, Resource);
RID probe;
void _set_data(const Dictionary &p_data);
Dictionary _get_data() const;
- Transform to_cell_xform;
+ Transform3D to_cell_xform;
AABB bounds;
Vector3 octree_size;
- float dynamic_range = 4.0;
+ float dynamic_range = 2.0;
float energy = 1.0;
float bias = 1.5;
float normal_bias = 0.0;
float propagation = 0.7;
- float anisotropy_strength = 0.5;
- float ao = 0.0;
- float ao_size = 0.5;
bool interior = false;
bool use_two_bounces = false;
protected:
static void _bind_methods();
- void _validate_property(PropertyInfo &property) const override;
public:
- void allocate(const Transform &p_to_cell_xform, const AABB &p_aabb, const Vector3 &p_octree_size, const Vector<uint8_t> &p_octree_cells, const Vector<uint8_t> &p_data_cells, const Vector<uint8_t> &p_distance_field, const Vector<int> &p_level_counts);
+ void allocate(const Transform3D &p_to_cell_xform, const AABB &p_aabb, const Vector3 &p_octree_size, const Vector<uint8_t> &p_octree_cells, const Vector<uint8_t> &p_data_cells, const Vector<uint8_t> &p_distance_field, const Vector<int> &p_level_counts);
AABB get_bounds() const;
Vector3 get_octree_size() const;
Vector<uint8_t> get_octree_cells() const;
Vector<uint8_t> get_data_cells() const;
Vector<uint8_t> get_distance_field() const;
Vector<int> get_level_counts() const;
- Transform get_to_cell_xform() const;
+ Transform3D get_to_cell_xform() const;
void set_dynamic_range(float p_range);
float get_dynamic_range() const;
@@ -77,15 +72,6 @@ public:
void set_propagation(float p_propagation);
float get_propagation() const;
- void set_anisotropy_strength(float p_anisotropy_strength);
- float get_anisotropy_strength() const;
-
- void set_ao(float p_ao);
- float get_ao() const;
-
- void set_ao_size(float p_ao_size);
- float get_ao_size() const;
-
void set_energy(float p_energy);
float get_energy() const;
@@ -103,12 +89,12 @@ public:
virtual RID get_rid() const override;
- GIProbeData();
- ~GIProbeData();
+ VoxelGIData();
+ ~VoxelGIData();
};
-class GIProbe : public VisualInstance3D {
- GDCLASS(GIProbe, VisualInstance3D);
+class VoxelGI : public VisualInstance3D {
+ GDCLASS(VoxelGI, VisualInstance3D);
public:
enum Subdiv {
@@ -125,9 +111,9 @@ public:
typedef void (*BakeEndFunc)();
private:
- Ref<GIProbeData> probe_data;
+ Ref<VoxelGIData> probe_data;
- RID gi_probe;
+ RID voxel_gi;
Subdiv subdiv = SUBDIV_128;
Vector3 extents = Vector3(10, 10, 10);
@@ -136,7 +122,7 @@ private:
Ref<Material> override_material;
Vector<Ref<Material>> instance_materials;
Ref<Mesh> mesh;
- Transform local_xform;
+ Transform3D local_xform;
};
void _find_meshes(Node *p_at_node, List<PlotMesh> &plot_meshes);
@@ -150,8 +136,8 @@ public:
static BakeStepFunc bake_step_function;
static BakeEndFunc bake_end_function;
- void set_probe_data(const Ref<GIProbeData> &p_data);
- Ref<GIProbeData> get_probe_data() const;
+ void set_probe_data(const Ref<VoxelGIData> &p_data);
+ Ref<VoxelGIData> get_probe_data() const;
void set_subdiv(Subdiv p_subdiv);
Subdiv get_subdiv() const;
@@ -163,14 +149,13 @@ public:
void bake(Node *p_from_node = nullptr, bool p_create_visual_debug = false);
virtual AABB get_aabb() const override;
- virtual Vector<Face3> get_faces(uint32_t p_usage_flags) const override;
TypedArray<String> get_configuration_warnings() const override;
- GIProbe();
- ~GIProbe();
+ VoxelGI();
+ ~VoxelGI();
};
-VARIANT_ENUM_CAST(GIProbe::Subdiv)
+VARIANT_ENUM_CAST(VoxelGI::Subdiv)
-#endif // GIPROBE_H
+#endif // VOXEL_GI_H
diff --git a/scene/3d/voxelizer.cpp b/scene/3d/voxelizer.cpp
index 1b9ce0201f..d6ac5ccf30 100644
--- a/scene/3d/voxelizer.cpp
+++ b/scene/3d/voxelizer.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -29,24 +29,19 @@
/*************************************************************************/
#include "voxelizer.h"
-#include "core/math/geometry_3d.h"
-#include "core/os/os.h"
-#include "core/os/threaded_array_processor.h"
-
-#include <stdlib.h>
static _FORCE_INLINE_ void get_uv_and_normal(const Vector3 &p_pos, const Vector3 *p_vtx, const Vector2 *p_uv, const Vector3 *p_normal, Vector2 &r_uv, Vector3 &r_normal) {
- if (p_pos.distance_squared_to(p_vtx[0]) < CMP_EPSILON2) {
+ if (p_pos.is_equal_approx(p_vtx[0])) {
r_uv = p_uv[0];
r_normal = p_normal[0];
return;
}
- if (p_pos.distance_squared_to(p_vtx[1]) < CMP_EPSILON2) {
+ if (p_pos.is_equal_approx(p_vtx[1])) {
r_uv = p_uv[1];
r_normal = p_normal[1];
return;
}
- if (p_pos.distance_squared_to(p_vtx[2]) < CMP_EPSILON2) {
+ if (p_pos.is_equal_approx(p_vtx[2])) {
r_uv = p_uv[2];
r_normal = p_normal[2];
return;
@@ -56,20 +51,20 @@ static _FORCE_INLINE_ void get_uv_and_normal(const Vector3 &p_pos, const Vector3
Vector3 v1 = p_vtx[2] - p_vtx[0];
Vector3 v2 = p_pos - p_vtx[0];
- float d00 = v0.dot(v0);
- float d01 = v0.dot(v1);
- float d11 = v1.dot(v1);
- float d20 = v2.dot(v0);
- float d21 = v2.dot(v1);
- float denom = (d00 * d11 - d01 * d01);
+ real_t d00 = v0.dot(v0);
+ real_t d01 = v0.dot(v1);
+ real_t d11 = v1.dot(v1);
+ real_t d20 = v2.dot(v0);
+ real_t d21 = v2.dot(v1);
+ real_t denom = (d00 * d11 - d01 * d01);
if (denom == 0) {
r_uv = p_uv[0];
r_normal = p_normal[0];
return;
}
- float v = (d11 * d20 - d01 * d21) / denom;
- float w = (d00 * d21 - d01 * d20) / denom;
- float u = 1.0f - v - w;
+ real_t v = (d11 * d20 - d01 * d21) / denom;
+ real_t w = (d00 * d21 - d01 * d20) / denom;
+ real_t u = 1.0f - v - w;
r_uv = p_uv[0] * u + p_uv[1] * v + p_uv[2] * w;
r_normal = (p_normal[0] * u + p_normal[1] * v + p_normal[2] * w).normalized();
@@ -81,7 +76,7 @@ void Voxelizer::_plot_face(int p_idx, int p_level, int p_x, int p_y, int p_z, co
//find best axis to map to, for scanning values
int closest_axis = 0;
- float closest_dot = 0;
+ real_t closest_dot = 0;
Plane plane = Plane(p_vtx[0], p_vtx[1], p_vtx[2]);
Vector3 normal = plane.normal;
@@ -89,7 +84,7 @@ void Voxelizer::_plot_face(int p_idx, int p_level, int p_x, int p_y, int p_z, co
for (int i = 0; i < 3; i++) {
Vector3 axis;
axis[i] = 1.0;
- float dot = ABS(normal.dot(axis));
+ real_t dot = ABS(normal.dot(axis));
if (i == 0 || dot > closest_dot) {
closest_axis = i;
closest_dot = dot;
@@ -103,8 +98,8 @@ void Voxelizer::_plot_face(int p_idx, int p_level, int p_x, int p_y, int p_z, co
Vector3 t2;
t2[(closest_axis + 2) % 3] = 1.0;
- t1 *= p_aabb.size[(closest_axis + 1) % 3] / float(color_scan_cell_width);
- t2 *= p_aabb.size[(closest_axis + 2) % 3] / float(color_scan_cell_width);
+ t1 *= p_aabb.size[(closest_axis + 1) % 3] / real_t(color_scan_cell_width);
+ t2 *= p_aabb.size[(closest_axis + 2) % 3] / real_t(color_scan_cell_width);
Color albedo_accum;
Color emission_accum;
@@ -114,10 +109,10 @@ void Voxelizer::_plot_face(int p_idx, int p_level, int p_x, int p_y, int p_z, co
//map to a grid average in the best axis for this face
for (int i = 0; i < color_scan_cell_width; i++) {
- Vector3 ofs_i = float(i) * t1;
+ Vector3 ofs_i = real_t(i) * t1;
for (int j = 0; j < color_scan_cell_width; j++) {
- Vector3 ofs_j = float(j) * t2;
+ Vector3 ofs_j = real_t(j) * t2;
Vector3 from = p_aabb.position + ofs_i + ofs_j;
Vector3 to = from + t1 + t2 + axis * p_aabb.size[closest_axis];
@@ -155,8 +150,8 @@ void Voxelizer::_plot_face(int p_idx, int p_level, int p_x, int p_y, int p_z, co
lnormal = normal;
}
- int uv_x = CLAMP(int(Math::fposmod(uv.x, 1.0f) * bake_texture_size), 0, bake_texture_size - 1);
- int uv_y = CLAMP(int(Math::fposmod(uv.y, 1.0f) * bake_texture_size), 0, bake_texture_size - 1);
+ int uv_x = CLAMP(int(Math::fposmod(uv.x, (real_t)1.0) * bake_texture_size), 0, bake_texture_size - 1);
+ int uv_y = CLAMP(int(Math::fposmod(uv.y, (real_t)1.0) * bake_texture_size), 0, bake_texture_size - 1);
int ofs = uv_y * bake_texture_size + uv_x;
albedo_accum.r += p_material.albedo[ofs].r;
@@ -178,7 +173,7 @@ void Voxelizer::_plot_face(int p_idx, int p_level, int p_x, int p_y, int p_z, co
//could not in any way get texture information.. so use closest point to center
Face3 f(p_vtx[0], p_vtx[1], p_vtx[2]);
- Vector3 inters = f.get_closest_point_to(p_aabb.position + p_aabb.size * 0.5);
+ Vector3 inters = f.get_closest_point_to(p_aabb.get_center());
Vector3 lnormal;
Vector2 uv;
@@ -187,8 +182,8 @@ void Voxelizer::_plot_face(int p_idx, int p_level, int p_x, int p_y, int p_z, co
lnormal = normal;
}
- int uv_x = CLAMP(Math::fposmod(uv.x, 1.0f) * bake_texture_size, 0, bake_texture_size - 1);
- int uv_y = CLAMP(Math::fposmod(uv.y, 1.0f) * bake_texture_size, 0, bake_texture_size - 1);
+ int uv_x = CLAMP(Math::fposmod(uv.x, (real_t)1.0) * bake_texture_size, 0, bake_texture_size - 1);
+ int uv_y = CLAMP(Math::fposmod(uv.y, (real_t)1.0) * bake_texture_size, 0, bake_texture_size - 1);
int ofs = uv_y * bake_texture_size + uv_x;
@@ -378,7 +373,7 @@ Voxelizer::MaterialCache Voxelizer::_get_material_cache(Ref<Material> p_material
return mc;
}
-void Voxelizer::plot_mesh(const Transform &p_xform, Ref<Mesh> &p_mesh, const Vector<Ref<Material>> &p_materials, const Ref<Material> &p_override_material) {
+void Voxelizer::plot_mesh(const Transform3D &p_xform, Ref<Mesh> &p_mesh, const Vector<Ref<Material>> &p_materials, const Ref<Material> &p_override_material) {
for (int i = 0; i < p_mesh->get_surface_count(); i++) {
if (p_mesh->surface_get_primitive_type(i) != Mesh::PRIMITIVE_TRIANGLES) {
continue; //only triangles
@@ -439,7 +434,7 @@ void Voxelizer::plot_mesh(const Transform &p_xform, Ref<Mesh> &p_mesh, const Vec
}
//test against original bounds
- if (!Geometry3D::triangle_box_overlap(original_bounds.position + original_bounds.size * 0.5, original_bounds.size * 0.5, vtxs)) {
+ if (!Geometry3D::triangle_box_overlap(original_bounds.get_center(), original_bounds.size * 0.5, vtxs)) {
continue;
}
//plot
@@ -471,7 +466,7 @@ void Voxelizer::plot_mesh(const Transform &p_xform, Ref<Mesh> &p_mesh, const Vec
}
//test against original bounds
- if (!Geometry3D::triangle_box_overlap(original_bounds.position + original_bounds.size * 0.5, original_bounds.size * 0.5, vtxs)) {
+ if (!Geometry3D::triangle_box_overlap(original_bounds.get_center(), original_bounds.size * 0.5, vtxs)) {
continue;
}
//plot face
@@ -623,7 +618,6 @@ void Voxelizer::begin_bake(int p_subdiv, const AABB &p_bounds) {
bake_cells.resize(1);
material_cache.clear();
- print_line("subdiv: " + itos(p_subdiv));
//find out the actual real bounds, power of 2, which gets the highest subdivision
po2_bounds = p_bounds;
int longest_axis = po2_bounds.get_longest_axis_index();
@@ -636,7 +630,7 @@ void Voxelizer::begin_bake(int p_subdiv, const AABB &p_bounds) {
}
axis_cell_size[i] = axis_cell_size[longest_axis];
- float axis_size = po2_bounds.size[longest_axis];
+ real_t axis_size = po2_bounds.size[longest_axis];
//shrink until fit subdiv
while (axis_size / 2.0 >= po2_bounds.size[i]) {
@@ -647,11 +641,11 @@ void Voxelizer::begin_bake(int p_subdiv, const AABB &p_bounds) {
po2_bounds.size[i] = po2_bounds.size[longest_axis];
}
- Transform to_bounds;
+ Transform3D to_bounds;
to_bounds.basis.scale(Vector3(po2_bounds.size[longest_axis], po2_bounds.size[longest_axis], po2_bounds.size[longest_axis]));
to_bounds.origin = po2_bounds.position;
- Transform to_grid;
+ Transform3D to_grid;
to_grid.basis.scale(Vector3(axis_cell_size[longest_axis], axis_cell_size[longest_axis], axis_cell_size[longest_axis]));
to_cell_space = to_grid * to_bounds.affine_inverse();
@@ -666,21 +660,21 @@ void Voxelizer::end_bake() {
_fixup_plot(0, 0);
}
-//create the data for visual server
+//create the data for rendering server
-int Voxelizer::get_gi_probe_octree_depth() const {
+int Voxelizer::get_voxel_gi_octree_depth() const {
return cell_subdiv;
}
-Vector3i Voxelizer::get_giprobe_octree_size() const {
+Vector3i Voxelizer::get_voxel_gi_octree_size() const {
return Vector3i(axis_cell_size[0], axis_cell_size[1], axis_cell_size[2]);
}
-int Voxelizer::get_giprobe_cell_count() const {
+int Voxelizer::get_voxel_gi_cell_count() const {
return bake_cells.size();
}
-Vector<uint8_t> Voxelizer::get_giprobe_octree_cells() const {
+Vector<uint8_t> Voxelizer::get_voxel_gi_octree_cells() const {
Vector<uint8_t> data;
data.resize((8 * 4) * bake_cells.size()); //8 uint32t values
{
@@ -700,7 +694,7 @@ Vector<uint8_t> Voxelizer::get_giprobe_octree_cells() const {
return data;
}
-Vector<uint8_t> Voxelizer::get_giprobe_data_cells() const {
+Vector<uint8_t> Voxelizer::get_voxel_gi_data_cells() const {
Vector<uint8_t> data;
data.resize((4 * 4) * bake_cells.size()); //8 uint32t values
{
@@ -755,7 +749,7 @@ Vector<uint8_t> Voxelizer::get_giprobe_data_cells() const {
return data;
}
-Vector<int> Voxelizer::get_giprobe_level_cell_count() const {
+Vector<int> Voxelizer::get_voxel_gi_level_cell_count() const {
uint32_t cell_count = bake_cells.size();
const Cell *cells = bake_cells.ptr();
Vector<int> level_count;
@@ -783,8 +777,8 @@ Vector<int> Voxelizer::get_giprobe_level_cell_count() const {
/* dt of 1d function using squared distance */
static void edt(float *f, int stride, int n) {
float *d = (float *)alloca(sizeof(float) * n + sizeof(int) * n + sizeof(float) * (n + 1));
- int *v = (int *)&(d[n]);
- float *z = (float *)&v[n];
+ int *v = reinterpret_cast<int *>(&(d[n]));
+ float *z = reinterpret_cast<float *>(&v[n]);
int k = 0;
v[0] = 0;
@@ -819,7 +813,7 @@ static void edt(float *f, int stride, int n) {
#undef square
Vector<uint8_t> Voxelizer::get_sdf_3d_image() const {
- Vector3i octree_size = get_giprobe_octree_size();
+ Vector3i octree_size = get_voxel_gi_octree_size();
uint32_t float_count = octree_size.x * octree_size.y * octree_size.z;
float *work_memory = memnew_arr(float, float_count);
@@ -878,7 +872,7 @@ Vector<uint8_t> Voxelizer::get_sdf_3d_image() const {
if (d == 0) {
w[i] = 0;
} else {
- w[i] = MIN(d, 254) + 1;
+ w[i] = MIN(d, 254u) + 1;
}
}
}
@@ -890,8 +884,8 @@ Vector<uint8_t> Voxelizer::get_sdf_3d_image() const {
void Voxelizer::_debug_mesh(int p_idx, int p_level, const AABB &p_aabb, Ref<MultiMesh> &p_multimesh, int &idx) {
if (p_level == cell_subdiv - 1) {
- Vector3 center = p_aabb.position + p_aabb.size * 0.5;
- Transform xform;
+ Vector3 center = p_aabb.get_center();
+ Transform3D xform;
xform.origin = center;
xform.basis.scale(p_aabb.size * 0.5);
p_multimesh->set_instance_transform(idx, xform);
@@ -931,14 +925,14 @@ void Voxelizer::_debug_mesh(int p_idx, int p_level, const AABB &p_aabb, Ref<Mult
Ref<MultiMesh> Voxelizer::create_debug_multimesh() {
Ref<MultiMesh> mm;
- mm.instance();
+ mm.instantiate();
mm->set_transform_format(MultiMesh::TRANSFORM_3D);
mm->set_use_colors(true);
mm->set_instance_count(leaf_voxel_count);
Ref<ArrayMesh> mesh;
- mesh.instance();
+ mesh.instantiate();
{
Array arr;
@@ -954,7 +948,7 @@ Ref<MultiMesh> Voxelizer::create_debug_multimesh() {
Vector3 face_points[4];
for (int j = 0; j < 4; j++) {
- float v[3];
+ real_t v[3];
v[0] = 1.0;
v[1] = 1 - 2 * ((j >> 1) & 1);
v[2] = v[1] * (1 - 2 * (j & 1));
@@ -985,7 +979,7 @@ Ref<MultiMesh> Voxelizer::create_debug_multimesh() {
{
Ref<StandardMaterial3D> fsm;
- fsm.instance();
+ fsm.instantiate();
fsm->set_flag(StandardMaterial3D::FLAG_SRGB_VERTEX_COLOR, true);
fsm->set_flag(StandardMaterial3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
fsm->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED);
@@ -1002,7 +996,7 @@ Ref<MultiMesh> Voxelizer::create_debug_multimesh() {
return mm;
}
-Transform Voxelizer::get_to_cell_space_xform() const {
+Transform3D Voxelizer::get_to_cell_space_xform() const {
return to_cell_space;
}
diff --git a/scene/3d/voxelizer.h b/scene/3d/voxelizer.h
index 87f949e7db..dc7569d17c 100644
--- a/scene/3d/voxelizer.h
+++ b/scene/3d/voxelizer.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -31,8 +31,6 @@
#ifndef VOXEL_LIGHT_BAKER_H
#define VOXEL_LIGHT_BAKER_H
-#include "core/math/vector3i.h"
-#include "scene/3d/mesh_instance_3d.h"
#include "scene/resources/multimesh.h"
class Voxelizer {
@@ -93,7 +91,7 @@ private:
AABB po2_bounds;
int axis_cell_size[3] = {};
- Transform to_cell_space;
+ Transform3D to_cell_space;
int color_scan_cell_width = 4;
int bake_texture_size = 128;
@@ -114,20 +112,20 @@ private:
public:
void begin_bake(int p_subdiv, const AABB &p_bounds);
- void plot_mesh(const Transform &p_xform, Ref<Mesh> &p_mesh, const Vector<Ref<Material>> &p_materials, const Ref<Material> &p_override_material);
+ void plot_mesh(const Transform3D &p_xform, Ref<Mesh> &p_mesh, const Vector<Ref<Material>> &p_materials, const Ref<Material> &p_override_material);
void end_bake();
- int get_gi_probe_octree_depth() const;
- Vector3i get_giprobe_octree_size() const;
- int get_giprobe_cell_count() const;
- Vector<uint8_t> get_giprobe_octree_cells() const;
- Vector<uint8_t> get_giprobe_data_cells() const;
- Vector<int> get_giprobe_level_cell_count() const;
+ int get_voxel_gi_octree_depth() const;
+ Vector3i get_voxel_gi_octree_size() const;
+ int get_voxel_gi_cell_count() const;
+ Vector<uint8_t> get_voxel_gi_octree_cells() const;
+ Vector<uint8_t> get_voxel_gi_data_cells() const;
+ Vector<int> get_voxel_gi_level_cell_count() const;
Vector<uint8_t> get_sdf_3d_image() const;
Ref<MultiMesh> create_debug_multimesh();
- Transform get_to_cell_space_xform() const;
+ Transform3D get_to_cell_space_xform() const;
Voxelizer();
};
diff --git a/scene/3d/world_environment.cpp b/scene/3d/world_environment.cpp
index 829ecc5ec2..f638644628 100644
--- a/scene/3d/world_environment.cpp
+++ b/scene/3d/world_environment.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -30,30 +30,36 @@
#include "world_environment.h"
+#include "scene/3d/node_3d.h"
#include "scene/main/window.h"
void WorldEnvironment::_notification(int p_what) {
- if (p_what == Node3D::NOTIFICATION_ENTER_WORLD || p_what == Node3D::NOTIFICATION_ENTER_TREE) {
- if (environment.is_valid()) {
- add_to_group("_world_environment_" + itos(get_viewport()->find_world_3d()->get_scenario().get_id()));
- _update_current_environment();
- }
-
- if (camera_effects.is_valid()) {
- add_to_group("_world_camera_effects_" + itos(get_viewport()->find_world_3d()->get_scenario().get_id()));
- _update_current_camera_effects();
- }
-
- } else if (p_what == Node3D::NOTIFICATION_EXIT_WORLD || p_what == Node3D::NOTIFICATION_EXIT_TREE) {
- if (environment.is_valid()) {
- remove_from_group("_world_environment_" + itos(get_viewport()->find_world_3d()->get_scenario().get_id()));
- _update_current_environment();
- }
-
- if (camera_effects.is_valid()) {
- remove_from_group("_world_camera_effects_" + itos(get_viewport()->find_world_3d()->get_scenario().get_id()));
- _update_current_camera_effects();
- }
+ switch (p_what) {
+ case Node3D::NOTIFICATION_ENTER_WORLD:
+ case Node3D::NOTIFICATION_ENTER_TREE: {
+ if (environment.is_valid()) {
+ add_to_group("_world_environment_" + itos(get_viewport()->find_world_3d()->get_scenario().get_id()));
+ _update_current_environment();
+ }
+
+ if (camera_effects.is_valid()) {
+ add_to_group("_world_camera_effects_" + itos(get_viewport()->find_world_3d()->get_scenario().get_id()));
+ _update_current_camera_effects();
+ }
+ } break;
+
+ case Node3D::NOTIFICATION_EXIT_WORLD:
+ case Node3D::NOTIFICATION_EXIT_TREE: {
+ if (environment.is_valid()) {
+ remove_from_group("_world_environment_" + itos(get_viewport()->find_world_3d()->get_scenario().get_id()));
+ _update_current_environment();
+ }
+
+ if (camera_effects.is_valid()) {
+ remove_from_group("_world_camera_effects_" + itos(get_viewport()->find_world_3d()->get_scenario().get_id()));
+ _update_current_camera_effects();
+ }
+ } break;
}
}
@@ -132,8 +138,8 @@ Ref<CameraEffects> WorldEnvironment::get_camera_effects() const {
TypedArray<String> WorldEnvironment::get_configuration_warnings() const {
TypedArray<String> warnings = Node::get_configuration_warnings();
- if (!environment.is_valid()) {
- warnings.push_back(TTR("WorldEnvironment requires its \"Environment\" property to contain an Environment to have a visible effect."));
+ if (!environment.is_valid() && !camera_effects.is_valid()) {
+ warnings.push_back(RTR("To have any visible effect, WorldEnvironment requires its \"Environment\" property to contain an Environment, its \"Camera Effects\" property to contain a CameraEffects resource, or both."));
}
if (!is_inside_tree()) {
@@ -145,7 +151,7 @@ TypedArray<String> WorldEnvironment::get_configuration_warnings() const {
}
if (camera_effects.is_valid() && get_viewport()->find_world_3d()->get_camera_effects() != camera_effects) {
- warnings.push_back(TTR("Only one WorldEnvironment is allowed per scene (or set of instanced scenes)."));
+ warnings.push_back(RTR("Only one WorldEnvironment is allowed per scene (or set of instantiated scenes)."));
}
return warnings;
diff --git a/scene/3d/world_environment.h b/scene/3d/world_environment.h
index 9e85982381..8dbb57364c 100644
--- a/scene/3d/world_environment.h
+++ b/scene/3d/world_environment.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -31,7 +31,7 @@
#ifndef SCENARIO_FX_H
#define SCENARIO_FX_H
-#include "scene/3d/node_3d.h"
+#include "scene/main/node.h"
#include "scene/resources/camera_effects.h"
#include "scene/resources/environment.h"
diff --git a/scene/3d/xr_nodes.cpp b/scene/3d/xr_nodes.cpp
index b5037f9be7..1dad6078b4 100644
--- a/scene/3d/xr_nodes.cpp
+++ b/scene/3d/xr_nodes.cpp
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -30,9 +30,9 @@
#include "xr_nodes.h"
-#include "core/input/input.h"
+#include "core/config/project_settings.h"
+#include "scene/main/viewport.h"
#include "servers/xr/xr_interface.h"
-#include "servers/xr_server.h"
////////////////////////////////////////////////////////////////////////////////////////////////////
@@ -44,16 +44,49 @@ void XRCamera3D::_notification(int p_what) {
if (origin != nullptr) {
origin->set_tracked_camera(this);
}
- }; break;
+ } break;
+
case NOTIFICATION_EXIT_TREE: {
// need to find our XROrigin3D parent and let it know we're no longer its camera!
XROrigin3D *origin = Object::cast_to<XROrigin3D>(get_parent());
- if (origin != nullptr) {
- origin->clear_tracked_camera_if(this);
+ if (origin != nullptr && origin->get_tracked_camera() == this) {
+ origin->set_tracked_camera(nullptr);
}
- }; break;
- };
-};
+ } break;
+ }
+}
+
+void XRCamera3D::_changed_tracker(const StringName p_tracker_name, int p_tracker_type) {
+ if (p_tracker_name == tracker_name) {
+ XRServer *xr_server = XRServer::get_singleton();
+ ERR_FAIL_NULL(xr_server);
+
+ tracker = xr_server->get_tracker(p_tracker_name);
+ if (tracker.is_valid()) {
+ tracker->connect("pose_changed", callable_mp(this, &XRCamera3D::_pose_changed));
+
+ Ref<XRPose> pose = tracker->get_pose(pose_name);
+ if (pose.is_valid()) {
+ set_transform(pose->get_adjusted_transform());
+ }
+ }
+ }
+}
+
+void XRCamera3D::_removed_tracker(const StringName p_tracker_name, int p_tracker_type) {
+ if (p_tracker_name == tracker_name) {
+ if (tracker.is_valid()) {
+ tracker->disconnect("pose_changed", callable_mp(this, &XRCamera3D::_pose_changed));
+ }
+ tracker.unref();
+ }
+}
+
+void XRCamera3D::_pose_changed(const Ref<XRPose> &p_pose) {
+ if (p_pose->get_name() == pose_name) {
+ set_transform(p_pose->get_adjusted_transform());
+ }
+}
TypedArray<String> XRCamera3D::get_configuration_warnings() const {
TypedArray<String> warnings = Node::get_configuration_warnings();
@@ -62,7 +95,7 @@ TypedArray<String> XRCamera3D::get_configuration_warnings() const {
// must be child node of XROrigin3D!
XROrigin3D *origin = Object::cast_to<XROrigin3D>(get_parent());
if (origin == nullptr) {
- warnings.push_back(TTR("XRCamera3D must have an XROrigin3D node as its parent."));
+ warnings.push_back(RTR("XRCamera3D must have an XROrigin3D node as its parent."));
};
}
@@ -86,7 +119,8 @@ Vector3 XRCamera3D::project_local_ray_normal(const Point2 &p_pos) const {
Vector2 cpos = get_viewport()->get_camera_coords(p_pos);
Vector3 ray;
- CameraMatrix cm = xr_interface->get_projection_for_eye(XRInterface::EYE_MONO, viewport_size.aspect(), get_near(), get_far());
+ // Just use the first view, if multiple views are supported this function has no good result
+ CameraMatrix cm = xr_interface->get_projection_for_view(0, viewport_size.aspect(), get_near(), get_far());
Vector2 screen_he = cm.get_viewport_half_extents();
ray = Vector3(((cpos.x / viewport_size.width) * 2.0 - 1.0) * screen_he.x, ((1.0 - (cpos.y / viewport_size.height)) * 2.0 - 1.0) * screen_he.y, -get_near()).normalized();
@@ -108,7 +142,8 @@ Point2 XRCamera3D::unproject_position(const Vector3 &p_pos) const {
Size2 viewport_size = get_viewport()->get_visible_rect().size;
- CameraMatrix cm = xr_interface->get_projection_for_eye(XRInterface::EYE_MONO, viewport_size.aspect(), get_near(), get_far());
+ // Just use the first view, if multiple views are supported this function has no good result
+ CameraMatrix cm = xr_interface->get_projection_for_view(0, viewport_size.aspect(), get_near(), get_far());
Plane p(get_camera_transform().xform_inv(p_pos), 1.0);
@@ -122,7 +157,7 @@ Point2 XRCamera3D::unproject_position(const Vector3 &p_pos) const {
return res;
};
-Vector3 XRCamera3D::project_position(const Point2 &p_point, float p_z_depth) const {
+Vector3 XRCamera3D::project_position(const Point2 &p_point, real_t p_z_depth) const {
// get our XRServer
XRServer *xr_server = XRServer::get_singleton();
ERR_FAIL_NULL_V(xr_server, Vector3());
@@ -137,7 +172,8 @@ Vector3 XRCamera3D::project_position(const Point2 &p_point, float p_z_depth) con
Size2 viewport_size = get_viewport()->get_visible_rect().size;
- CameraMatrix cm = xr_interface->get_projection_for_eye(XRInterface::EYE_MONO, viewport_size.aspect(), get_near(), get_far());
+ // Just use the first view, if multiple views are supported this function has no good result
+ CameraMatrix cm = xr_interface->get_projection_for_view(0, viewport_size.aspect(), get_near(), get_far());
Vector2 vp_he = cm.get_viewport_half_extents();
@@ -165,344 +201,385 @@ Vector<Plane> XRCamera3D::get_frustum() const {
ERR_FAIL_COND_V(!is_inside_world(), Vector<Plane>());
Size2 viewport_size = get_viewport()->get_visible_rect().size;
- CameraMatrix cm = xr_interface->get_projection_for_eye(XRInterface::EYE_MONO, viewport_size.aspect(), get_near(), get_far());
+ // TODO Just use the first view for now, this is mostly for debugging so we may look into using our combined projection here.
+ CameraMatrix cm = xr_interface->get_projection_for_view(0, viewport_size.aspect(), get_near(), get_far());
return cm.get_projection_planes(get_camera_transform());
};
-////////////////////////////////////////////////////////////////////////////////////////////////////
+XRCamera3D::XRCamera3D() {
+ XRServer *xr_server = XRServer::get_singleton();
+ ERR_FAIL_NULL(xr_server);
-void XRController3D::_notification(int p_what) {
- switch (p_what) {
- case NOTIFICATION_ENTER_TREE: {
- set_process_internal(true);
- }; break;
- case NOTIFICATION_EXIT_TREE: {
- set_process_internal(false);
- }; break;
- case NOTIFICATION_INTERNAL_PROCESS: {
- // get our XRServer
- XRServer *xr_server = XRServer::get_singleton();
- ERR_FAIL_NULL(xr_server);
-
- // find the tracker for our controller
- Ref<XRPositionalTracker> tracker = xr_server->find_by_type_and_id(XRServer::TRACKER_CONTROLLER, controller_id);
- if (!tracker.is_valid()) {
- // this controller is currently turned off
- is_active = false;
- button_states = 0;
- } else {
- is_active = true;
- set_transform(tracker->get_transform(true));
-
- int joy_id = tracker->get_joy_id();
- if (joy_id >= 0) {
- int mask = 1;
- // check button states
- for (int i = 0; i < 16; i++) {
- bool was_pressed = (button_states & mask) == mask;
- bool is_pressed = Input::get_singleton()->is_joy_button_pressed(joy_id, i);
-
- if (!was_pressed && is_pressed) {
- emit_signal("button_pressed", i);
- button_states += mask;
- } else if (was_pressed && !is_pressed) {
- emit_signal("button_released", i);
- button_states -= mask;
- };
-
- mask = mask << 1;
- };
-
- } else {
- button_states = 0;
- };
-
- // check for an updated mesh
- Ref<Mesh> trackerMesh = tracker->get_mesh();
- if (mesh != trackerMesh) {
- mesh = trackerMesh;
- emit_signal("mesh_updated", mesh);
- }
- };
- }; break;
- default:
- break;
- };
-};
+ xr_server->connect("tracker_added", callable_mp(this, &XRCamera3D::_changed_tracker));
+ xr_server->connect("tracker_updated", callable_mp(this, &XRCamera3D::_changed_tracker));
+ xr_server->connect("tracker_removed", callable_mp(this, &XRCamera3D::_removed_tracker));
+}
-void XRController3D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_controller_id", "controller_id"), &XRController3D::set_controller_id);
- ClassDB::bind_method(D_METHOD("get_controller_id"), &XRController3D::get_controller_id);
- ADD_PROPERTY(PropertyInfo(Variant::INT, "controller_id", PROPERTY_HINT_RANGE, "0,32,1"), "set_controller_id", "get_controller_id");
- ClassDB::bind_method(D_METHOD("get_controller_name"), &XRController3D::get_controller_name);
+XRCamera3D::~XRCamera3D() {
+ XRServer *xr_server = XRServer::get_singleton();
+ ERR_FAIL_NULL(xr_server);
- // passthroughs to information about our related joystick
- ClassDB::bind_method(D_METHOD("get_joystick_id"), &XRController3D::get_joystick_id);
- ClassDB::bind_method(D_METHOD("is_button_pressed", "button"), &XRController3D::is_button_pressed);
- ClassDB::bind_method(D_METHOD("get_joystick_axis", "axis"), &XRController3D::get_joystick_axis);
+ xr_server->disconnect("tracker_added", callable_mp(this, &XRCamera3D::_changed_tracker));
+ xr_server->disconnect("tracker_updated", callable_mp(this, &XRCamera3D::_changed_tracker));
+ xr_server->disconnect("tracker_removed", callable_mp(this, &XRCamera3D::_removed_tracker));
+}
- ClassDB::bind_method(D_METHOD("get_is_active"), &XRController3D::get_is_active);
- ClassDB::bind_method(D_METHOD("get_tracker_hand"), &XRController3D::get_tracker_hand);
+////////////////////////////////////////////////////////////////////////////////////////////////////
+// XRNode3D is a node that has it's transform updated by an XRPositionalTracker.
+// Note that trackers are only available in runtime and only after an XRInterface registers one.
+// So we bind by name and as long as a tracker isn't available, our node remains inactive.
- ClassDB::bind_method(D_METHOD("get_rumble"), &XRController3D::get_rumble);
- ClassDB::bind_method(D_METHOD("set_rumble", "rumble"), &XRController3D::set_rumble);
- ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "rumble", PROPERTY_HINT_RANGE, "0.0,1.0,0.01"), "set_rumble", "get_rumble");
- ADD_PROPERTY_DEFAULT("rumble", 0.0);
+void XRNode3D::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("set_tracker", "tracker_name"), &XRNode3D::set_tracker);
+ ClassDB::bind_method(D_METHOD("get_tracker"), &XRNode3D::get_tracker);
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "tracker", PROPERTY_HINT_ENUM_SUGGESTION), "set_tracker", "get_tracker");
- ClassDB::bind_method(D_METHOD("get_mesh"), &XRController3D::get_mesh);
+ ClassDB::bind_method(D_METHOD("set_pose_name", "pose"), &XRNode3D::set_pose_name);
+ ClassDB::bind_method(D_METHOD("get_pose_name"), &XRNode3D::get_pose_name);
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "pose", PROPERTY_HINT_ENUM_SUGGESTION), "set_pose_name", "get_pose_name");
- ADD_SIGNAL(MethodInfo("button_pressed", PropertyInfo(Variant::INT, "button")));
- ADD_SIGNAL(MethodInfo("button_released", PropertyInfo(Variant::INT, "button")));
- ADD_SIGNAL(MethodInfo("mesh_updated", PropertyInfo(Variant::OBJECT, "mesh", PROPERTY_HINT_RESOURCE_TYPE, "Mesh")));
+ ClassDB::bind_method(D_METHOD("get_is_active"), &XRNode3D::get_is_active);
+ ClassDB::bind_method(D_METHOD("get_has_tracking_data"), &XRNode3D::get_has_tracking_data);
+ ClassDB::bind_method(D_METHOD("get_pose"), &XRNode3D::get_pose);
+ ClassDB::bind_method(D_METHOD("trigger_haptic_pulse", "action_name", "frequency", "amplitude", "duration_sec", "delay_sec"), &XRNode3D::trigger_haptic_pulse);
};
-void XRController3D::set_controller_id(int p_controller_id) {
- // We don't check any bounds here, this controller may not yet be active and just be a place holder until it is.
- // Note that setting this to 0 means this node is not bound to a controller yet.
- controller_id = p_controller_id;
- update_configuration_warnings();
-};
+void XRNode3D::_validate_property(PropertyInfo &property) const {
+ XRServer *xr_server = XRServer::get_singleton();
+ ERR_FAIL_NULL(xr_server);
-int XRController3D::get_controller_id() const {
- return controller_id;
-};
+ if (property.name == "tracker") {
+ PackedStringArray names = xr_server->get_suggested_tracker_names();
+ String hint_string;
+ for (const String &name : names) {
+ hint_string += name + ",";
+ }
+ property.hint_string = hint_string;
+ } else if (property.name == "pose") {
+ PackedStringArray names = xr_server->get_suggested_pose_names(tracker_name);
+ String hint_string;
+ for (const String &name : names) {
+ hint_string += name + ",";
+ }
+ property.hint_string = hint_string;
+ }
-String XRController3D::get_controller_name() const {
- // get our XRServer
- XRServer *xr_server = XRServer::get_singleton();
- ERR_FAIL_NULL_V(xr_server, String());
+ Node3D::_validate_property(property);
+}
- Ref<XRPositionalTracker> tracker = xr_server->find_by_type_and_id(XRServer::TRACKER_CONTROLLER, controller_id);
- if (!tracker.is_valid()) {
- return String("Not connected");
- };
+void XRNode3D::set_tracker(const StringName p_tracker_name) {
+ if (tracker.is_valid() && tracker->get_tracker_name() == p_tracker_name) {
+ // didn't change
+ return;
+ }
- return tracker->get_tracker_name();
-};
+ // just in case
+ _unbind_tracker();
-int XRController3D::get_joystick_id() const {
- // get our XRServer
- XRServer *xr_server = XRServer::get_singleton();
- ERR_FAIL_NULL_V(xr_server, 0);
+ // copy the name
+ tracker_name = p_tracker_name;
+ pose_name = "default";
- Ref<XRPositionalTracker> tracker = xr_server->find_by_type_and_id(XRServer::TRACKER_CONTROLLER, controller_id);
- if (!tracker.is_valid()) {
- // No tracker? no joystick id... (0 is our first joystick)
- return -1;
- };
+ // see if it's already available
+ _bind_tracker();
- return tracker->get_joy_id();
-};
+ update_configuration_warnings();
+ notify_property_list_changed();
+}
-bool XRController3D::is_button_pressed(int p_button) const {
- int joy_id = get_joystick_id();
- if (joy_id == -1) {
- return false;
- };
+StringName XRNode3D::get_tracker() const {
+ return tracker_name;
+}
- return Input::get_singleton()->is_joy_button_pressed(joy_id, p_button);
-};
+void XRNode3D::set_pose_name(const StringName p_pose_name) {
+ pose_name = p_pose_name;
-float XRController3D::get_joystick_axis(int p_axis) const {
- int joy_id = get_joystick_id();
- if (joy_id == -1) {
- return 0.0;
- };
+ // Update pose if we are bound to a tracker with a valid pose
+ Ref<XRPose> pose = get_pose();
+ if (pose.is_valid()) {
+ set_transform(pose->get_adjusted_transform());
+ }
+}
- return Input::get_singleton()->get_joy_axis(joy_id, p_axis);
-};
+StringName XRNode3D::get_pose_name() const {
+ return pose_name;
+}
-real_t XRController3D::get_rumble() const {
- // get our XRServer
+bool XRNode3D::get_is_active() const {
+ if (tracker.is_null()) {
+ return false;
+ } else if (!tracker->has_pose(pose_name)) {
+ return false;
+ } else {
+ return true;
+ }
+}
+
+bool XRNode3D::get_has_tracking_data() const {
+ if (tracker.is_null()) {
+ return false;
+ } else if (!tracker->has_pose(pose_name)) {
+ return false;
+ } else {
+ return tracker->get_pose(pose_name)->get_has_tracking_data();
+ }
+}
+
+void XRNode3D::trigger_haptic_pulse(const String &p_action_name, double p_frequency, double p_amplitude, double p_duration_sec, double p_delay_sec) {
+ // TODO need to link trackers to the interface that registered them so we can call this on the correct interface.
+ // For now this works fine as in 99% of the cases we only have our primary interface active
XRServer *xr_server = XRServer::get_singleton();
- ERR_FAIL_NULL_V(xr_server, 0.0);
+ if (xr_server != nullptr) {
+ Ref<XRInterface> xr_interface = xr_server->get_primary_interface();
+ if (xr_interface.is_valid()) {
+ xr_interface->trigger_haptic_pulse(p_action_name, tracker_name, p_frequency, p_amplitude, p_duration_sec, p_delay_sec);
+ }
+ }
+}
- Ref<XRPositionalTracker> tracker = xr_server->find_by_type_and_id(XRServer::TRACKER_CONTROLLER, controller_id);
- if (!tracker.is_valid()) {
- return 0.0;
- };
+Ref<XRPose> XRNode3D::get_pose() {
+ if (tracker.is_valid()) {
+ return tracker->get_pose(pose_name);
+ } else {
+ return Ref<XRPose>();
+ }
+}
- return tracker->get_rumble();
-};
+void XRNode3D::_bind_tracker() {
+ ERR_FAIL_COND_MSG(tracker.is_valid(), "Unbind the current tracker first");
-void XRController3D::set_rumble(real_t p_rumble) {
- // get our XRServer
XRServer *xr_server = XRServer::get_singleton();
- ERR_FAIL_NULL(xr_server);
+ if (xr_server != nullptr) {
+ tracker = xr_server->get_tracker(tracker_name);
+ if (tracker.is_null()) {
+ // It is possible and valid if the tracker isn't available (yet), in this case we just exit
+ return;
+ }
+
+ tracker->connect("pose_changed", callable_mp(this, &XRNode3D::_pose_changed));
+
+ Ref<XRPose> pose = get_pose();
+ if (pose.is_valid()) {
+ set_transform(pose->get_adjusted_transform());
+ }
+ }
+}
- Ref<XRPositionalTracker> tracker = xr_server->find_by_type_and_id(XRServer::TRACKER_CONTROLLER, controller_id);
+void XRNode3D::_unbind_tracker() {
if (tracker.is_valid()) {
- tracker->set_rumble(p_rumble);
- };
-};
+ tracker->disconnect("pose_changed", callable_mp(this, &XRNode3D::_pose_changed));
-Ref<Mesh> XRController3D::get_mesh() const {
- return mesh;
+ tracker.unref();
+ }
}
-bool XRController3D::get_is_active() const {
- return is_active;
-};
+void XRNode3D::_changed_tracker(const StringName p_tracker_name, int p_tracker_type) {
+ if (p_tracker_name == p_tracker_name) {
+ // just in case unref our current tracker
+ _unbind_tracker();
-XRPositionalTracker::TrackerHand XRController3D::get_tracker_hand() const {
- // get our XRServer
+ // get our new tracker
+ _bind_tracker();
+ }
+}
+
+void XRNode3D::_removed_tracker(const StringName p_tracker_name, int p_tracker_type) {
+ if (p_tracker_name == p_tracker_name) {
+ // unref our tracker, it's no longer available
+ _unbind_tracker();
+ }
+}
+
+void XRNode3D::_pose_changed(const Ref<XRPose> &p_pose) {
+ if (p_pose.is_valid() && p_pose->get_name() == pose_name) {
+ set_transform(p_pose->get_adjusted_transform());
+ }
+}
+
+XRNode3D::XRNode3D() {
XRServer *xr_server = XRServer::get_singleton();
- ERR_FAIL_NULL_V(xr_server, XRPositionalTracker::TRACKER_HAND_UNKNOWN);
+ ERR_FAIL_NULL(xr_server);
- Ref<XRPositionalTracker> tracker = xr_server->find_by_type_and_id(XRServer::TRACKER_CONTROLLER, controller_id);
- if (!tracker.is_valid()) {
- return XRPositionalTracker::TRACKER_HAND_UNKNOWN;
- };
+ xr_server->connect("tracker_added", callable_mp(this, &XRNode3D::_changed_tracker));
+ xr_server->connect("tracker_updated", callable_mp(this, &XRNode3D::_changed_tracker));
+ xr_server->connect("tracker_removed", callable_mp(this, &XRNode3D::_removed_tracker));
+}
- return tracker->get_tracker_hand();
-};
+XRNode3D::~XRNode3D() {
+ _unbind_tracker();
+
+ XRServer *xr_server = XRServer::get_singleton();
+ ERR_FAIL_NULL(xr_server);
+
+ xr_server->disconnect("tracker_added", callable_mp(this, &XRNode3D::_changed_tracker));
+ xr_server->disconnect("tracker_updated", callable_mp(this, &XRNode3D::_changed_tracker));
+ xr_server->disconnect("tracker_removed", callable_mp(this, &XRNode3D::_removed_tracker));
+}
-TypedArray<String> XRController3D::get_configuration_warnings() const {
+TypedArray<String> XRNode3D::get_configuration_warnings() const {
TypedArray<String> warnings = Node::get_configuration_warnings();
if (is_visible() && is_inside_tree()) {
// must be child node of XROrigin!
XROrigin3D *origin = Object::cast_to<XROrigin3D>(get_parent());
if (origin == nullptr) {
- warnings.push_back(TTR("XRController3D must have an XROrigin3D node as its parent."));
+ warnings.push_back(RTR("XRController3D must have an XROrigin3D node as its parent."));
+ }
+
+ if (tracker_name == "") {
+ warnings.push_back(RTR("No tracker name is set."));
}
- if (controller_id == 0) {
- warnings.push_back(TTR("The controller ID must not be 0 or this controller won't be bound to an actual controller."));
+ if (pose_name == "") {
+ warnings.push_back(RTR("No pose is set."));
}
}
return warnings;
-};
+}
////////////////////////////////////////////////////////////////////////////////////////////////////
-void XRAnchor3D::_notification(int p_what) {
- switch (p_what) {
- case NOTIFICATION_ENTER_TREE: {
- set_process_internal(true);
- }; break;
- case NOTIFICATION_EXIT_TREE: {
- set_process_internal(false);
- }; break;
- case NOTIFICATION_INTERNAL_PROCESS: {
- // get our XRServer
- XRServer *xr_server = XRServer::get_singleton();
- ERR_FAIL_NULL(xr_server);
-
- // find the tracker for our anchor
- Ref<XRPositionalTracker> tracker = xr_server->find_by_type_and_id(XRServer::TRACKER_ANCHOR, anchor_id);
- if (!tracker.is_valid()) {
- // this anchor is currently not available
- is_active = false;
- } else {
- is_active = true;
- Transform transform;
-
- // we'll need our world_scale
- real_t world_scale = xr_server->get_world_scale();
-
- // get our info from our tracker
- transform.basis = tracker->get_orientation();
- transform.origin = tracker->get_position(); // <-- already adjusted to world scale
-
- // our basis is scaled to the size of the plane the anchor is tracking
- // extract the size from our basis and reset the scale
- size = transform.basis.get_scale() * world_scale;
- transform.basis.orthonormalize();
-
- // apply our reference frame and set our transform
- set_transform(xr_server->get_reference_frame() * transform);
-
- // check for an updated mesh
- Ref<Mesh> trackerMesh = tracker->get_mesh();
- if (mesh != trackerMesh) {
- mesh = trackerMesh;
- emit_signal("mesh_updated", mesh);
- }
- };
- }; break;
- default:
- break;
- };
-};
-
-void XRAnchor3D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_anchor_id", "anchor_id"), &XRAnchor3D::set_anchor_id);
- ClassDB::bind_method(D_METHOD("get_anchor_id"), &XRAnchor3D::get_anchor_id);
- ADD_PROPERTY(PropertyInfo(Variant::INT, "anchor_id", PROPERTY_HINT_RANGE, "0,32,1"), "set_anchor_id", "get_anchor_id");
- ClassDB::bind_method(D_METHOD("get_anchor_name"), &XRAnchor3D::get_anchor_name);
-
- ClassDB::bind_method(D_METHOD("get_is_active"), &XRAnchor3D::get_is_active);
- ClassDB::bind_method(D_METHOD("get_size"), &XRAnchor3D::get_size);
+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_plane"), &XRAnchor3D::get_plane);
+ ClassDB::bind_method(D_METHOD("get_tracker_hand"), &XRController3D::get_tracker_hand);
- ClassDB::bind_method(D_METHOD("get_mesh"), &XRAnchor3D::get_mesh);
- ADD_SIGNAL(MethodInfo("mesh_updated", PropertyInfo(Variant::OBJECT, "mesh", PROPERTY_HINT_RESOURCE_TYPE, "Mesh")));
+ 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")));
};
-void XRAnchor3D::set_anchor_id(int p_anchor_id) {
- // We don't check any bounds here, this anchor may not yet be active and just be a place holder until it is.
- // Note that setting this to 0 means this node is not bound to an anchor yet.
- anchor_id = p_anchor_id;
- update_configuration_warnings();
-};
+void XRController3D::_bind_tracker() {
+ XRNode3D::_bind_tracker();
+ if (tracker.is_valid()) {
+ // 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));
+ }
+}
-int XRAnchor3D::get_anchor_id() const {
- return anchor_id;
-};
+void XRController3D::_unbind_tracker() {
+ if (tracker.is_valid()) {
+ // 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));
+ }
-Vector3 XRAnchor3D::get_size() const {
- return size;
-};
+ XRNode3D::_unbind_tracker();
+}
-String XRAnchor3D::get_anchor_name() const {
- // get our XRServer
- XRServer *xr_server = XRServer::get_singleton();
- ERR_FAIL_NULL_V(xr_server, String());
+void XRController3D::_button_pressed(const String &p_name) {
+ // just pass it on...
+ emit_signal(SNAME("button_pressed"), p_name);
+}
- Ref<XRPositionalTracker> tracker = xr_server->find_by_type_and_id(XRServer::TRACKER_ANCHOR, anchor_id);
- if (!tracker.is_valid()) {
- return String("Not connected");
- };
+void XRController3D::_button_released(const String &p_name) {
+ // just pass it on...
+ emit_signal(SNAME("button_released"), p_name);
+}
- return tracker->get_tracker_name();
-};
+void XRController3D::_input_value_changed(const String &p_name, float p_value) {
+ // just pass it on...
+ emit_signal(SNAME("input_value_changed"), p_name, p_value);
+}
-bool XRAnchor3D::get_is_active() const {
- return is_active;
-};
+void XRController3D::_input_axis_changed(const String &p_name, Vector2 p_value) {
+ // just pass it on...
+ emit_signal(SNAME("input_axis_changed"), p_name, p_value);
+}
-TypedArray<String> XRAnchor3D::get_configuration_warnings() const {
- TypedArray<String> warnings = Node::get_configuration_warnings();
+bool XRController3D::is_button_pressed(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
+ bool pressed = tracker->get_input(p_name);
+ return pressed;
+ } else {
+ return false;
+ }
+}
- if (is_visible() && is_inside_tree()) {
- // must be child node of XROrigin3D!
- XROrigin3D *origin = Object::cast_to<XROrigin3D>(get_parent());
- if (origin == nullptr) {
- warnings.push_back(TTR("XRAnchor3D must have an XROrigin3D node as its parent."));
- }
+float XRController3D::get_value(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);
+ switch (input.get_type()) {
+ case Variant::BOOL: {
+ bool value = input;
+ return value ? 1.0 : 0.0;
+ } break;
+ case Variant::FLOAT: {
+ float value = input;
+ return value;
+ } break;
+ default:
+ return 0.0;
+ };
+ } else {
+ return 0.0;
+ }
+}
- if (anchor_id == 0) {
- warnings.push_back(TTR("The anchor ID must not be 0 or this anchor won't be bound to an actual anchor."));
+Vector2 XRController3D::get_axis(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);
+ switch (input.get_type()) {
+ case Variant::BOOL: {
+ bool value = input;
+ return Vector2(value ? 1.0 : 0.0, 0.0);
+ } break;
+ case Variant::FLOAT: {
+ float value = input;
+ return Vector2(value, 0.0);
+ } break;
+ case Variant::VECTOR2: {
+ Vector2 axis = input;
+ return axis;
+ }
+ default:
+ return Vector2();
}
+ } else {
+ return Vector2();
}
+}
- return warnings;
-};
+XRPositionalTracker::TrackerHand XRController3D::get_tracker_hand() const {
+ // get our XRServer
+ if (!tracker.is_valid()) {
+ return XRPositionalTracker::TRACKER_HAND_UNKNOWN;
+ }
+
+ return tracker->get_tracker_hand();
+}
+
+////////////////////////////////////////////////////////////////////////////////////////////////////
+
+void XRAnchor3D::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("get_size"), &XRAnchor3D::get_size);
+ ClassDB::bind_method(D_METHOD("get_plane"), &XRAnchor3D::get_plane);
+}
+
+Vector3 XRAnchor3D::get_size() const {
+ return size;
+}
Plane XRAnchor3D::get_plane() const {
- Vector3 location = get_translation();
+ Vector3 location = get_position();
Basis orientation = get_transform().basis;
- Plane plane(location, orientation.get_axis(1).normalized());
+ Plane plane(orientation.get_column(1).normalized(), location);
return plane;
-};
-
-Ref<Mesh> XRAnchor3D::get_mesh() const {
- return mesh;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
@@ -512,44 +589,47 @@ TypedArray<String> XROrigin3D::get_configuration_warnings() const {
if (is_visible() && is_inside_tree()) {
if (tracked_camera == nullptr) {
- warnings.push_back(TTR("XROrigin3D requires an XRCamera3D child node."));
+ warnings.push_back(RTR("XROrigin3D requires an XRCamera3D child node."));
}
}
+ bool xr_enabled = GLOBAL_GET("xr/shaders/enabled");
+ if (!xr_enabled) {
+ warnings.push_back(RTR("XR is not enabled in rendering project settings. Stereoscopic output is not supported unless this is enabled."));
+ }
+
return warnings;
-};
+}
void XROrigin3D::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_world_scale", "world_scale"), &XROrigin3D::set_world_scale);
ClassDB::bind_method(D_METHOD("get_world_scale"), &XROrigin3D::get_world_scale);
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "world_scale"), "set_world_scale", "get_world_scale");
-};
+}
void XROrigin3D::set_tracked_camera(XRCamera3D *p_tracked_camera) {
tracked_camera = p_tracked_camera;
-};
+}
-void XROrigin3D::clear_tracked_camera_if(XRCamera3D *p_tracked_camera) {
- if (tracked_camera == p_tracked_camera) {
- tracked_camera = nullptr;
- };
-};
+XRCamera3D *XROrigin3D::get_tracked_camera() const {
+ return tracked_camera;
+}
-float XROrigin3D::get_world_scale() const {
+real_t XROrigin3D::get_world_scale() const {
// get our XRServer
XRServer *xr_server = XRServer::get_singleton();
ERR_FAIL_NULL_V(xr_server, 1.0);
return xr_server->get_world_scale();
-};
+}
-void XROrigin3D::set_world_scale(float p_world_scale) {
+void XROrigin3D::set_world_scale(real_t p_world_scale) {
// get our XRServer
XRServer *xr_server = XRServer::get_singleton();
ERR_FAIL_NULL(xr_server);
xr_server->set_world_scale(p_world_scale);
-};
+}
void XROrigin3D::_notification(int p_what) {
// get our XRServer
@@ -559,10 +639,12 @@ void XROrigin3D::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
set_process_internal(true);
- }; break;
+ } break;
+
case NOTIFICATION_EXIT_TREE: {
set_process_internal(false);
- }; break;
+ } break;
+
case NOTIFICATION_INTERNAL_PROCESS: {
// set our world origin to our node transform
xr_server->set_world_origin(get_global_transform());
@@ -571,15 +653,13 @@ void XROrigin3D::_notification(int p_what) {
Ref<XRInterface> xr_interface = xr_server->get_primary_interface();
if (xr_interface.is_valid() && tracked_camera != nullptr) {
// get our positioning transform for our headset
- Transform t = xr_interface->get_transform_for_eye(XRInterface::EYE_MONO, Transform());
+ Transform3D t = xr_interface->get_camera_transform();
// now apply this to our camera
tracked_camera->set_transform(t);
- };
- }; break;
- default:
- break;
- };
+ }
+ } break;
+ }
// send our notification to all active XE interfaces, they may need to react to it also
for (int i = 0; i < xr_server->get_interface_count(); i++) {
@@ -588,4 +668,4 @@ void XROrigin3D::_notification(int p_what) {
interface->notification(p_what);
}
}
-};
+}
diff --git a/scene/3d/xr_nodes.h b/scene/3d/xr_nodes.h
index 90079f5fe9..3079e20dc7 100644
--- a/scene/3d/xr_nodes.h
+++ b/scene/3d/xr_nodes.h
@@ -5,8 +5,8 @@
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
+/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
@@ -32,73 +32,115 @@
#define XR_NODES_H
#include "scene/3d/camera_3d.h"
-#include "scene/3d/node_3d.h"
-#include "scene/resources/mesh.h"
#include "servers/xr/xr_positional_tracker.h"
-/**
- @author Bastiaan Olij <mux213@gmail.com>
-**/
-
/*
XRCamera is a subclass of camera which will register itself with its parent XROrigin and as a result is automatically positioned
*/
+
class XRCamera3D : public Camera3D {
GDCLASS(XRCamera3D, Camera3D);
protected:
+ // The name and pose for our HMD tracker is currently the only hardcoded bit.
+ // If we ever are able to support multiple HMDs we may need to make this settable.
+ StringName tracker_name = "head";
+ StringName pose_name = "default";
+ Ref<XRPositionalTracker> tracker;
+
void _notification(int p_what);
+ void _changed_tracker(const StringName p_tracker_name, int p_tracker_type);
+ void _removed_tracker(const StringName p_tracker_name, int p_tracker_type);
+ void _pose_changed(const Ref<XRPose> &p_pose);
+
public:
TypedArray<String> get_configuration_warnings() const override;
virtual Vector3 project_local_ray_normal(const Point2 &p_pos) const override;
virtual Point2 unproject_position(const Vector3 &p_pos) const override;
- virtual Vector3 project_position(const Point2 &p_point, float p_z_depth) const override;
+ virtual Vector3 project_position(const Point2 &p_point, real_t p_z_depth) const override;
virtual Vector<Plane> get_frustum() const override;
- XRCamera3D() {}
- ~XRCamera3D() {}
+ XRCamera3D();
+ ~XRCamera3D();
};
/*
- XRController3D is a helper node that automatically updates its position based on tracker data.
+ XRNode3D is a helper node that implements binding to a tracker.
It must be a child node of our XROrigin node
*/
-class XRController3D : public Node3D {
- GDCLASS(XRController3D, Node3D);
+class XRNode3D : public Node3D {
+ GDCLASS(XRNode3D, Node3D);
private:
- int controller_id = 1;
+ StringName tracker_name;
+ StringName pose_name = "default";
bool is_active = true;
- int button_states = 0;
- Ref<Mesh> mesh;
protected:
- void _notification(int p_what);
+ Ref<XRPositionalTracker> tracker;
+
static void _bind_methods();
-public:
- void set_controller_id(int p_controller_id);
- int get_controller_id() const;
- String get_controller_name() const;
+ virtual void _bind_tracker();
+ virtual void _unbind_tracker();
+ void _changed_tracker(const StringName p_tracker_name, int p_tracker_type);
+ void _removed_tracker(const StringName p_tracker_name, int p_tracker_type);
- int get_joystick_id() const;
- bool is_button_pressed(int p_button) const;
- float get_joystick_axis(int p_axis) const;
+ void _pose_changed(const Ref<XRPose> &p_pose);
+
+public:
+ virtual void _validate_property(PropertyInfo &property) const override;
+ void set_tracker(const StringName p_tracker_name);
+ StringName get_tracker() const;
- real_t get_rumble() const;
- void set_rumble(real_t p_rumble);
+ void set_pose_name(const StringName p_pose);
+ StringName get_pose_name() const;
bool get_is_active() const;
- XRPositionalTracker::TrackerHand get_tracker_hand() const;
+ bool get_has_tracking_data() const;
+
+ void trigger_haptic_pulse(const String &p_action_name, double p_frequency, double p_amplitude, double p_duration_sec, double p_delay_sec = 0);
- Ref<Mesh> get_mesh() const;
+ Ref<XRPose> get_pose();
TypedArray<String> get_configuration_warnings() const override;
+ XRNode3D();
+ ~XRNode3D();
+};
+
+/*
+ XRController3D is a helper node that automatically updates its position based on tracker data.
+
+ It must be a child node of our XROrigin node
+*/
+
+class XRController3D : public XRNode3D {
+ GDCLASS(XRController3D, XRNode3D);
+
+private:
+protected:
+ static void _bind_methods();
+
+ virtual void _bind_tracker() override;
+ virtual void _unbind_tracker() override;
+
+ 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);
+
+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;
+
+ XRPositionalTracker::TrackerHand get_tracker_hand() const;
+
XRController3D() {}
~XRController3D() {}
};
@@ -108,33 +150,19 @@ public:
It must be a child node of our XROrigin3D node
*/
-class XRAnchor3D : public Node3D {
- GDCLASS(XRAnchor3D, Node3D);
+class XRAnchor3D : public XRNode3D {
+ GDCLASS(XRAnchor3D, XRNode3D);
private:
- int anchor_id = 1;
- bool is_active = true;
Vector3 size;
- Ref<Mesh> mesh;
protected:
- void _notification(int p_what);
static void _bind_methods();
public:
- void set_anchor_id(int p_anchor_id);
- int get_anchor_id() const;
- String get_anchor_name() const;
-
- bool get_is_active() const;
Vector3 get_size() const;
-
Plane get_plane() const;
- Ref<Mesh> get_mesh() const;
-
- TypedArray<String> get_configuration_warnings() const override;
-
XRAnchor3D() {}
~XRAnchor3D() {}
};
@@ -147,6 +175,7 @@ public:
Our camera and controllers will always be child nodes and thus place relative to this origin point.
This node will automatically locate any camera child nodes and update its position while our XRController3D node will handle tracked controllers.
*/
+
class XROrigin3D : public Node3D {
GDCLASS(XROrigin3D, Node3D);
@@ -161,13 +190,13 @@ public:
TypedArray<String> get_configuration_warnings() const override;
void set_tracked_camera(XRCamera3D *p_tracked_camera);
- void clear_tracked_camera_if(XRCamera3D *p_tracked_camera);
+ XRCamera3D *get_tracked_camera() const;
- float get_world_scale() const;
- void set_world_scale(float p_world_scale);
+ real_t get_world_scale() const;
+ void set_world_scale(real_t p_world_scale);
XROrigin3D() {}
~XROrigin3D() {}
};
-#endif /* XR_NODES_H */
+#endif // XR_NODES_H