Path: blob/master/scene/2d/physics/shape_cast_2d.cpp
10278 views
/**************************************************************************/1/* shape_cast_2d.cpp */2/**************************************************************************/3/* This file is part of: */4/* GODOT ENGINE */5/* https://godotengine.org */6/**************************************************************************/7/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */8/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */9/* */10/* Permission is hereby granted, free of charge, to any person obtaining */11/* a copy of this software and associated documentation files (the */12/* "Software"), to deal in the Software without restriction, including */13/* without limitation the rights to use, copy, modify, merge, publish, */14/* distribute, sublicense, and/or sell copies of the Software, and to */15/* permit persons to whom the Software is furnished to do so, subject to */16/* the following conditions: */17/* */18/* The above copyright notice and this permission notice shall be */19/* included in all copies or substantial portions of the Software. */20/* */21/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */22/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */23/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */24/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */25/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */26/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */27/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */28/**************************************************************************/2930#include "shape_cast_2d.h"3132#include "core/config/engine.h"33#include "scene/2d/physics/collision_object_2d.h"34#include "scene/resources/world_2d.h"35#include "servers/physics_server_2d.h"3637void ShapeCast2D::set_target_position(const Vector2 &p_point) {38target_position = p_point;39if (is_inside_tree() && (Engine::get_singleton()->is_editor_hint() || get_tree()->is_debugging_collisions_hint())) {40queue_redraw();41}42}4344Vector2 ShapeCast2D::get_target_position() const {45return target_position;46}4748void ShapeCast2D::set_margin(real_t p_margin) {49margin = p_margin;50}5152real_t ShapeCast2D::get_margin() const {53return margin;54}5556void ShapeCast2D::set_max_results(int p_max_results) {57max_results = p_max_results;58}5960int ShapeCast2D::get_max_results() const {61return max_results;62}6364void ShapeCast2D::set_collision_mask(uint32_t p_mask) {65collision_mask = p_mask;66}6768uint32_t ShapeCast2D::get_collision_mask() const {69return collision_mask;70}7172void ShapeCast2D::set_collision_mask_value(int p_layer_number, bool p_value) {73ERR_FAIL_COND_MSG(p_layer_number < 1, "Collision layer number must be between 1 and 32 inclusive.");74ERR_FAIL_COND_MSG(p_layer_number > 32, "Collision layer number must be between 1 and 32 inclusive.");75uint32_t mask = get_collision_mask();76if (p_value) {77mask |= 1 << (p_layer_number - 1);78} else {79mask &= ~(1 << (p_layer_number - 1));80}81set_collision_mask(mask);82}8384bool ShapeCast2D::get_collision_mask_value(int p_layer_number) const {85ERR_FAIL_COND_V_MSG(p_layer_number < 1, false, "Collision layer number must be between 1 and 32 inclusive.");86ERR_FAIL_COND_V_MSG(p_layer_number > 32, false, "Collision layer number must be between 1 and 32 inclusive.");87return get_collision_mask() & (1 << (p_layer_number - 1));88}8990int ShapeCast2D::get_collision_count() const {91return result.size();92}9394bool ShapeCast2D::is_colliding() const {95return collided;96}9798Object *ShapeCast2D::get_collider(int p_idx) const {99ERR_FAIL_INDEX_V_MSG(p_idx, result.size(), nullptr, "No collider found.");100101if (result[p_idx].collider_id.is_null()) {102return nullptr;103}104return ObjectDB::get_instance(result[p_idx].collider_id);105}106107RID ShapeCast2D::get_collider_rid(int p_idx) const {108ERR_FAIL_INDEX_V_MSG(p_idx, result.size(), RID(), "No collider RID found.");109return result[p_idx].rid;110}111112int ShapeCast2D::get_collider_shape(int p_idx) const {113ERR_FAIL_INDEX_V_MSG(p_idx, result.size(), -1, "No collider shape found.");114return result[p_idx].shape;115}116117Vector2 ShapeCast2D::get_collision_point(int p_idx) const {118ERR_FAIL_INDEX_V_MSG(p_idx, result.size(), Vector2(), "No collision point found.");119return result[p_idx].point;120}121122Vector2 ShapeCast2D::get_collision_normal(int p_idx) const {123ERR_FAIL_INDEX_V_MSG(p_idx, result.size(), Vector2(), "No collision normal found.");124return result[p_idx].normal;125}126127real_t ShapeCast2D::get_closest_collision_safe_fraction() const {128return collision_safe_fraction;129}130131real_t ShapeCast2D::get_closest_collision_unsafe_fraction() const {132return collision_unsafe_fraction;133}134135void ShapeCast2D::set_enabled(bool p_enabled) {136enabled = p_enabled;137queue_redraw();138if (is_inside_tree() && !Engine::get_singleton()->is_editor_hint()) {139set_physics_process_internal(p_enabled);140}141if (!p_enabled) {142collided = false;143}144}145146bool ShapeCast2D::is_enabled() const {147return enabled;148}149150void ShapeCast2D::set_shape(const Ref<Shape2D> &p_shape) {151if (p_shape == shape) {152return;153}154if (shape.is_valid()) {155shape->disconnect_changed(callable_mp(this, &ShapeCast2D::_shape_changed));156}157shape = p_shape;158if (shape.is_valid()) {159shape->connect_changed(callable_mp(this, &ShapeCast2D::_shape_changed));160shape_rid = shape->get_rid();161}162163update_configuration_warnings();164queue_redraw();165}166167Ref<Shape2D> ShapeCast2D::get_shape() const {168return shape;169}170171void ShapeCast2D::set_exclude_parent_body(bool p_exclude_parent_body) {172if (exclude_parent_body == p_exclude_parent_body) {173return;174}175exclude_parent_body = p_exclude_parent_body;176177if (!is_inside_tree()) {178return;179}180if (Object::cast_to<CollisionObject2D>(get_parent())) {181if (exclude_parent_body) {182exclude.insert(Object::cast_to<CollisionObject2D>(get_parent())->get_rid());183} else {184exclude.erase(Object::cast_to<CollisionObject2D>(get_parent())->get_rid());185}186}187}188189bool ShapeCast2D::get_exclude_parent_body() const {190return exclude_parent_body;191}192193void ShapeCast2D::_shape_changed() {194queue_redraw();195}196197void ShapeCast2D::_notification(int p_what) {198switch (p_what) {199case NOTIFICATION_ENTER_TREE: {200if (enabled && !Engine::get_singleton()->is_editor_hint()) {201set_physics_process_internal(true);202} else {203set_physics_process_internal(false);204}205if (Object::cast_to<CollisionObject2D>(get_parent())) {206if (exclude_parent_body) {207exclude.insert(Object::cast_to<CollisionObject2D>(get_parent())->get_rid());208} else {209exclude.erase(Object::cast_to<CollisionObject2D>(get_parent())->get_rid());210}211}212} break;213214case NOTIFICATION_EXIT_TREE: {215if (enabled) {216set_physics_process_internal(false);217}218} break;219220case NOTIFICATION_DRAW: {221#ifdef TOOLS_ENABLED222ERR_FAIL_COND(!is_inside_tree());223if (!Engine::get_singleton()->is_editor_hint() && !get_tree()->is_debugging_collisions_hint()) {224break;225}226if (shape.is_null()) {227break;228}229Color draw_col = collided ? Color(1.0, 0.01, 0) : get_tree()->get_debug_collisions_color();230if (!enabled) {231float g = draw_col.get_v();232draw_col.r = g;233draw_col.g = g;234draw_col.b = g;235}236// Draw continuous chain of shapes along the cast.237const int steps = MAX(2, target_position.length() / shape->get_rect().get_size().length() * 4);238for (int i = 0; i <= steps; ++i) {239Vector2 t = (real_t(i) / steps) * target_position;240draw_set_transform(t, 0.0, Size2(1, 1));241shape->draw(get_canvas_item(), draw_col);242}243draw_set_transform(Vector2(), 0.0, Size2(1, 1));244245// Draw an arrow indicating where the ShapeCast is pointing to.246if (target_position != Vector2()) {247const real_t max_arrow_size = 6;248const real_t line_width = 1.4;249bool no_line = target_position.length() < line_width;250real_t arrow_size = CLAMP(target_position.length() * 2 / 3, line_width, max_arrow_size);251252if (no_line) {253arrow_size = target_position.length();254} else {255draw_line(Vector2(), target_position - target_position.normalized() * arrow_size, draw_col, line_width);256}257258Transform2D xf;259xf.rotate(target_position.angle());260xf.translate_local(Vector2(no_line ? 0 : target_position.length() - arrow_size, 0));261262Vector<Vector2> pts = {263xf.xform(Vector2(arrow_size, 0)),264xf.xform(Vector2(0, 0.5 * arrow_size)),265xf.xform(Vector2(0, -0.5 * arrow_size))266};267268Vector<Color> cols = { draw_col, draw_col, draw_col };269270draw_primitive(pts, cols, Vector<Vector2>());271}272#endif273} break;274275case NOTIFICATION_INTERNAL_PHYSICS_PROCESS: {276if (!enabled) {277break;278}279_update_shapecast_state();280} break;281}282}283284void ShapeCast2D::_update_shapecast_state() {285result.clear();286287ERR_FAIL_COND_MSG(shape.is_null(), "Invalid shape.");288289Ref<World2D> w2d = get_world_2d();290ERR_FAIL_COND(w2d.is_null());291292PhysicsDirectSpaceState2D *dss = PhysicsServer2D::get_singleton()->space_get_direct_state(w2d->get_space());293ERR_FAIL_NULL(dss);294295Transform2D gt = get_global_transform();296297PhysicsDirectSpaceState2D::ShapeParameters params;298params.shape_rid = shape_rid;299params.transform = gt;300params.motion = gt.basis_xform(target_position);301params.margin = margin;302params.exclude = exclude;303params.collision_mask = collision_mask;304params.collide_with_bodies = collide_with_bodies;305params.collide_with_areas = collide_with_areas;306307collision_safe_fraction = 0.0;308collision_unsafe_fraction = 0.0;309310bool prev_collision_state = collided;311312if (target_position != Vector2()) {313dss->cast_motion(params, collision_safe_fraction, collision_unsafe_fraction);314if (collision_unsafe_fraction < 1.0) {315// Move shape transform to the point of impact,316// so we can collect contact info at that point.317gt.set_origin(gt.get_origin() + params.motion * (collision_unsafe_fraction + CMP_EPSILON));318params.transform = gt;319}320}321// Regardless of whether the shape is stuck or it's moved along322// the motion vector, we'll only consider static collisions from now on.323params.motion = Vector2();324325bool intersected = true;326while (intersected && result.size() < max_results) {327PhysicsDirectSpaceState2D::ShapeRestInfo info;328intersected = dss->rest_info(params, &info);329if (intersected) {330result.push_back(info);331params.exclude.insert(info.rid);332}333}334collided = !result.is_empty();335336if (prev_collision_state != collided) {337queue_redraw();338}339}340341void ShapeCast2D::force_shapecast_update() {342_update_shapecast_state();343}344345void ShapeCast2D::add_exception_rid(const RID &p_rid) {346exclude.insert(p_rid);347}348349void ShapeCast2D::add_exception(const CollisionObject2D *p_node) {350ERR_FAIL_NULL_MSG(p_node, "The passed Node must be an instance of CollisionObject2D.");351add_exception_rid(p_node->get_rid());352}353354void ShapeCast2D::remove_exception_rid(const RID &p_rid) {355exclude.erase(p_rid);356}357358void ShapeCast2D::remove_exception(const CollisionObject2D *p_node) {359ERR_FAIL_NULL_MSG(p_node, "The passed Node must be an instance of CollisionObject2D.");360remove_exception_rid(p_node->get_rid());361}362363void ShapeCast2D::clear_exceptions() {364exclude.clear();365}366367void ShapeCast2D::set_collide_with_areas(bool p_clip) {368collide_with_areas = p_clip;369}370371bool ShapeCast2D::is_collide_with_areas_enabled() const {372return collide_with_areas;373}374375void ShapeCast2D::set_collide_with_bodies(bool p_clip) {376collide_with_bodies = p_clip;377}378379bool ShapeCast2D::is_collide_with_bodies_enabled() const {380return collide_with_bodies;381}382383Array ShapeCast2D::get_collision_result() const {384Array ret;385386for (int i = 0; i < result.size(); ++i) {387const PhysicsDirectSpaceState2D::ShapeRestInfo &sri = result[i];388389Dictionary col;390col["point"] = sri.point;391col["normal"] = sri.normal;392col["rid"] = sri.rid;393col["collider"] = ObjectDB::get_instance(sri.collider_id);394col["collider_id"] = sri.collider_id;395col["shape"] = sri.shape;396col["linear_velocity"] = sri.linear_velocity;397398ret.push_back(col);399}400return ret;401}402403PackedStringArray ShapeCast2D::get_configuration_warnings() const {404PackedStringArray warnings = Node2D::get_configuration_warnings();405406if (shape.is_null()) {407warnings.push_back(RTR("This node cannot interact with other objects unless a Shape2D is assigned."));408}409return warnings;410}411412void ShapeCast2D::_bind_methods() {413ClassDB::bind_method(D_METHOD("set_enabled", "enabled"), &ShapeCast2D::set_enabled);414ClassDB::bind_method(D_METHOD("is_enabled"), &ShapeCast2D::is_enabled);415416ClassDB::bind_method(D_METHOD("set_shape", "shape"), &ShapeCast2D::set_shape);417ClassDB::bind_method(D_METHOD("get_shape"), &ShapeCast2D::get_shape);418419ClassDB::bind_method(D_METHOD("set_target_position", "local_point"), &ShapeCast2D::set_target_position);420ClassDB::bind_method(D_METHOD("get_target_position"), &ShapeCast2D::get_target_position);421422ClassDB::bind_method(D_METHOD("set_margin", "margin"), &ShapeCast2D::set_margin);423ClassDB::bind_method(D_METHOD("get_margin"), &ShapeCast2D::get_margin);424425ClassDB::bind_method(D_METHOD("set_max_results", "max_results"), &ShapeCast2D::set_max_results);426ClassDB::bind_method(D_METHOD("get_max_results"), &ShapeCast2D::get_max_results);427428ClassDB::bind_method(D_METHOD("is_colliding"), &ShapeCast2D::is_colliding);429ClassDB::bind_method(D_METHOD("get_collision_count"), &ShapeCast2D::get_collision_count);430431ClassDB::bind_method(D_METHOD("force_shapecast_update"), &ShapeCast2D::force_shapecast_update);432433ClassDB::bind_method(D_METHOD("get_collider", "index"), &ShapeCast2D::get_collider);434ClassDB::bind_method(D_METHOD("get_collider_rid", "index"), &ShapeCast2D::get_collider_rid);435ClassDB::bind_method(D_METHOD("get_collider_shape", "index"), &ShapeCast2D::get_collider_shape);436ClassDB::bind_method(D_METHOD("get_collision_point", "index"), &ShapeCast2D::get_collision_point);437ClassDB::bind_method(D_METHOD("get_collision_normal", "index"), &ShapeCast2D::get_collision_normal);438439ClassDB::bind_method(D_METHOD("get_closest_collision_safe_fraction"), &ShapeCast2D::get_closest_collision_safe_fraction);440ClassDB::bind_method(D_METHOD("get_closest_collision_unsafe_fraction"), &ShapeCast2D::get_closest_collision_unsafe_fraction);441442ClassDB::bind_method(D_METHOD("add_exception_rid", "rid"), &ShapeCast2D::add_exception_rid);443ClassDB::bind_method(D_METHOD("add_exception", "node"), &ShapeCast2D::add_exception);444445ClassDB::bind_method(D_METHOD("remove_exception_rid", "rid"), &ShapeCast2D::remove_exception_rid);446ClassDB::bind_method(D_METHOD("remove_exception", "node"), &ShapeCast2D::remove_exception);447448ClassDB::bind_method(D_METHOD("clear_exceptions"), &ShapeCast2D::clear_exceptions);449450ClassDB::bind_method(D_METHOD("set_collision_mask", "mask"), &ShapeCast2D::set_collision_mask);451ClassDB::bind_method(D_METHOD("get_collision_mask"), &ShapeCast2D::get_collision_mask);452453ClassDB::bind_method(D_METHOD("set_collision_mask_value", "layer_number", "value"), &ShapeCast2D::set_collision_mask_value);454ClassDB::bind_method(D_METHOD("get_collision_mask_value", "layer_number"), &ShapeCast2D::get_collision_mask_value);455456ClassDB::bind_method(D_METHOD("set_exclude_parent_body", "mask"), &ShapeCast2D::set_exclude_parent_body);457ClassDB::bind_method(D_METHOD("get_exclude_parent_body"), &ShapeCast2D::get_exclude_parent_body);458459ClassDB::bind_method(D_METHOD("set_collide_with_areas", "enable"), &ShapeCast2D::set_collide_with_areas);460ClassDB::bind_method(D_METHOD("is_collide_with_areas_enabled"), &ShapeCast2D::is_collide_with_areas_enabled);461462ClassDB::bind_method(D_METHOD("set_collide_with_bodies", "enable"), &ShapeCast2D::set_collide_with_bodies);463ClassDB::bind_method(D_METHOD("is_collide_with_bodies_enabled"), &ShapeCast2D::is_collide_with_bodies_enabled);464465ClassDB::bind_method(D_METHOD("get_collision_result"), &ShapeCast2D::get_collision_result);466467ADD_PROPERTY(PropertyInfo(Variant::BOOL, "enabled"), "set_enabled", "is_enabled");468ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "shape", PROPERTY_HINT_RESOURCE_TYPE, "Shape2D"), "set_shape", "get_shape");469ADD_PROPERTY(PropertyInfo(Variant::BOOL, "exclude_parent"), "set_exclude_parent_body", "get_exclude_parent_body");470ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "target_position", PROPERTY_HINT_NONE, "suffix:px"), "set_target_position", "get_target_position");471ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "margin", PROPERTY_HINT_RANGE, "0,100,0.01,suffix:px"), "set_margin", "get_margin");472ADD_PROPERTY(PropertyInfo(Variant::INT, "max_results"), "set_max_results", "get_max_results");473ADD_PROPERTY(PropertyInfo(Variant::INT, "collision_mask", PROPERTY_HINT_LAYERS_2D_PHYSICS), "set_collision_mask", "get_collision_mask");474ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "collision_result", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "", "get_collision_result");475ADD_GROUP("Collide With", "collide_with");476ADD_PROPERTY(PropertyInfo(Variant::BOOL, "collide_with_areas"), "set_collide_with_areas", "is_collide_with_areas_enabled");477ADD_PROPERTY(PropertyInfo(Variant::BOOL, "collide_with_bodies"), "set_collide_with_bodies", "is_collide_with_bodies_enabled");478}479480ShapeCast2D::ShapeCast2D() {481set_hide_clip_children(true);482}483484485