Path: blob/master/scene/2d/navigation/navigation_obstacle_2d.cpp
9904 views
/**************************************************************************/1/* navigation_obstacle_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 "navigation_obstacle_2d.h"3132#include "core/math/geometry_2d.h"33#include "scene/resources/2d/navigation_mesh_source_geometry_data_2d.h"34#include "scene/resources/2d/navigation_polygon.h"35#include "scene/resources/world_2d.h"36#include "servers/navigation_server_2d.h"3738Callable NavigationObstacle2D::_navmesh_source_geometry_parsing_callback;39RID NavigationObstacle2D::_navmesh_source_geometry_parser;4041void NavigationObstacle2D::_bind_methods() {42ClassDB::bind_method(D_METHOD("get_rid"), &NavigationObstacle2D::get_rid);4344ClassDB::bind_method(D_METHOD("set_avoidance_enabled", "enabled"), &NavigationObstacle2D::set_avoidance_enabled);45ClassDB::bind_method(D_METHOD("get_avoidance_enabled"), &NavigationObstacle2D::get_avoidance_enabled);4647ClassDB::bind_method(D_METHOD("set_navigation_map", "navigation_map"), &NavigationObstacle2D::set_navigation_map);48ClassDB::bind_method(D_METHOD("get_navigation_map"), &NavigationObstacle2D::get_navigation_map);4950ClassDB::bind_method(D_METHOD("set_radius", "radius"), &NavigationObstacle2D::set_radius);51ClassDB::bind_method(D_METHOD("get_radius"), &NavigationObstacle2D::get_radius);5253ClassDB::bind_method(D_METHOD("set_velocity", "velocity"), &NavigationObstacle2D::set_velocity);54ClassDB::bind_method(D_METHOD("get_velocity"), &NavigationObstacle2D::get_velocity);5556ClassDB::bind_method(D_METHOD("set_vertices", "vertices"), &NavigationObstacle2D::set_vertices);57ClassDB::bind_method(D_METHOD("get_vertices"), &NavigationObstacle2D::get_vertices);5859ClassDB::bind_method(D_METHOD("set_avoidance_layers", "layers"), &NavigationObstacle2D::set_avoidance_layers);60ClassDB::bind_method(D_METHOD("get_avoidance_layers"), &NavigationObstacle2D::get_avoidance_layers);6162ClassDB::bind_method(D_METHOD("set_avoidance_layer_value", "layer_number", "value"), &NavigationObstacle2D::set_avoidance_layer_value);63ClassDB::bind_method(D_METHOD("get_avoidance_layer_value", "layer_number"), &NavigationObstacle2D::get_avoidance_layer_value);6465ClassDB::bind_method(D_METHOD("set_affect_navigation_mesh", "enabled"), &NavigationObstacle2D::set_affect_navigation_mesh);66ClassDB::bind_method(D_METHOD("get_affect_navigation_mesh"), &NavigationObstacle2D::get_affect_navigation_mesh);6768ClassDB::bind_method(D_METHOD("set_carve_navigation_mesh", "enabled"), &NavigationObstacle2D::set_carve_navigation_mesh);69ClassDB::bind_method(D_METHOD("get_carve_navigation_mesh"), &NavigationObstacle2D::get_carve_navigation_mesh);7071ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "radius", PROPERTY_HINT_RANGE, "0.0,500,0.01,suffix:px"), "set_radius", "get_radius");72ADD_PROPERTY(PropertyInfo(Variant::PACKED_VECTOR2_ARRAY, "vertices"), "set_vertices", "get_vertices");73ADD_GROUP("NavigationMesh", "");74ADD_PROPERTY(PropertyInfo(Variant::BOOL, "affect_navigation_mesh"), "set_affect_navigation_mesh", "get_affect_navigation_mesh");75ADD_PROPERTY(PropertyInfo(Variant::BOOL, "carve_navigation_mesh"), "set_carve_navigation_mesh", "get_carve_navigation_mesh");76ADD_GROUP("Avoidance", "");77ADD_PROPERTY(PropertyInfo(Variant::BOOL, "avoidance_enabled"), "set_avoidance_enabled", "get_avoidance_enabled");78ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "velocity", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "set_velocity", "get_velocity");79ADD_PROPERTY(PropertyInfo(Variant::INT, "avoidance_layers", PROPERTY_HINT_LAYERS_AVOIDANCE), "set_avoidance_layers", "get_avoidance_layers");80}8182void NavigationObstacle2D::_notification(int p_what) {83switch (p_what) {84case NOTIFICATION_POST_ENTER_TREE: {85if (map_override.is_valid()) {86_update_map(map_override);87} else if (is_inside_tree()) {88_update_map(get_world_2d()->get_navigation_map());89} else {90_update_map(RID());91}92previous_transform = get_global_transform();93// need to trigger map controlled agent assignment somehow for the fake_agent since obstacles use no callback like regular agents94NavigationServer2D::get_singleton()->obstacle_set_avoidance_enabled(obstacle, avoidance_enabled);95_update_transform();96set_physics_process_internal(true);97#ifdef DEBUG_ENABLED98RS::get_singleton()->canvas_item_set_parent(debug_canvas_item, get_world_2d()->get_canvas());99#endif // DEBUG_ENABLED100} break;101102case NOTIFICATION_EXIT_TREE: {103set_physics_process_internal(false);104_update_map(RID());105#ifdef DEBUG_ENABLED106RS::get_singleton()->canvas_item_set_parent(debug_canvas_item, RID());107#endif // DEBUG_ENABLED108} break;109110case NOTIFICATION_SUSPENDED:111case NOTIFICATION_PAUSED: {112if (!can_process()) {113map_before_pause = map_current;114_update_map(RID());115} else if (can_process() && !(map_before_pause == RID())) {116_update_map(map_before_pause);117map_before_pause = RID();118}119NavigationServer2D::get_singleton()->obstacle_set_paused(obstacle, !can_process());120} break;121122case NOTIFICATION_UNSUSPENDED: {123if (get_tree()->is_paused()) {124break;125}126[[fallthrough]];127}128129case NOTIFICATION_UNPAUSED: {130if (!can_process()) {131map_before_pause = map_current;132_update_map(RID());133} else if (can_process() && !(map_before_pause == RID())) {134_update_map(map_before_pause);135map_before_pause = RID();136}137NavigationServer2D::get_singleton()->obstacle_set_paused(obstacle, !can_process());138} break;139140case NOTIFICATION_VISIBILITY_CHANGED: {141#ifdef DEBUG_ENABLED142RS::get_singleton()->canvas_item_set_visible(debug_canvas_item, is_visible_in_tree());143#endif // DEBUG_ENABLED144} break;145146case NOTIFICATION_INTERNAL_PHYSICS_PROCESS: {147if (is_inside_tree()) {148_update_transform();149150if (velocity_submitted) {151velocity_submitted = false;152// only update if there is a noticeable change, else the rvo agent preferred velocity stays the same153if (!previous_velocity.is_equal_approx(velocity)) {154NavigationServer2D::get_singleton()->obstacle_set_velocity(obstacle, velocity);155}156previous_velocity = velocity;157}158}159} break;160161case NOTIFICATION_DRAW: {162#ifdef DEBUG_ENABLED163if (is_inside_tree()) {164bool is_debug_enabled = false;165if (Engine::get_singleton()->is_editor_hint()) {166is_debug_enabled = true;167} else if (NavigationServer2D::get_singleton()->get_debug_enabled() && NavigationServer2D::get_singleton()->get_debug_avoidance_enabled()) {168is_debug_enabled = true;169}170171if (is_debug_enabled) {172RS::get_singleton()->canvas_item_clear(debug_canvas_item);173RS::get_singleton()->canvas_item_set_transform(debug_canvas_item, Transform2D());174_update_fake_agent_radius_debug();175_update_static_obstacle_debug();176}177}178#endif // DEBUG_ENABLED179} break;180}181}182183NavigationObstacle2D::NavigationObstacle2D() {184obstacle = NavigationServer2D::get_singleton()->obstacle_create();185186NavigationServer2D::get_singleton()->obstacle_set_radius(obstacle, radius);187NavigationServer2D::get_singleton()->obstacle_set_vertices(obstacle, vertices);188NavigationServer2D::get_singleton()->obstacle_set_avoidance_layers(obstacle, avoidance_layers);189NavigationServer2D::get_singleton()->obstacle_set_avoidance_enabled(obstacle, avoidance_enabled);190191#ifdef DEBUG_ENABLED192debug_canvas_item = RenderingServer::get_singleton()->canvas_item_create();193debug_mesh_rid = RenderingServer::get_singleton()->mesh_create();194#endif // DEBUG_ENABLED195}196197NavigationObstacle2D::~NavigationObstacle2D() {198ERR_FAIL_NULL(NavigationServer2D::get_singleton());199200NavigationServer2D::get_singleton()->free(obstacle);201obstacle = RID();202203#ifdef DEBUG_ENABLED204if (debug_mesh_rid.is_valid()) {205RenderingServer::get_singleton()->free(debug_mesh_rid);206debug_mesh_rid = RID();207}208if (debug_canvas_item.is_valid()) {209RenderingServer::get_singleton()->free(debug_canvas_item);210debug_canvas_item = RID();211}212#endif // DEBUG_ENABLED213}214215void NavigationObstacle2D::set_vertices(const Vector<Vector2> &p_vertices) {216vertices = p_vertices;217218vertices_are_clockwise = !Geometry2D::is_polygon_clockwise(vertices); // Geometry2D is inverted.219vertices_are_valid = !Geometry2D::triangulate_polygon(vertices).is_empty();220221const Transform2D node_transform = is_inside_tree() ? get_global_transform() : Transform2D();222NavigationServer2D::get_singleton()->obstacle_set_vertices(obstacle, node_transform.xform(vertices));223#ifdef DEBUG_ENABLED224queue_redraw();225#endif // DEBUG_ENABLED226}227228void NavigationObstacle2D::set_navigation_map(RID p_navigation_map) {229if (map_override == p_navigation_map) {230return;231}232map_override = p_navigation_map;233_update_map(map_override);234}235236RID NavigationObstacle2D::get_navigation_map() const {237if (map_override.is_valid()) {238return map_override;239} else if (is_inside_tree()) {240return get_world_2d()->get_navigation_map();241}242return RID();243}244245void NavigationObstacle2D::set_radius(real_t p_radius) {246ERR_FAIL_COND_MSG(p_radius < 0.0, "Radius must be positive.");247if (Math::is_equal_approx(radius, p_radius)) {248return;249}250251radius = p_radius;252253const Vector2 safe_scale = (is_inside_tree() ? get_global_scale() : get_scale()).abs().maxf(0.001);254NavigationServer2D::get_singleton()->obstacle_set_radius(obstacle, safe_scale[safe_scale.max_axis_index()] * radius);255#ifdef DEBUG_ENABLED256queue_redraw();257#endif // DEBUG_ENABLED258}259260void NavigationObstacle2D::set_avoidance_layers(uint32_t p_layers) {261if (avoidance_layers == p_layers) {262return;263}264avoidance_layers = p_layers;265NavigationServer2D::get_singleton()->obstacle_set_avoidance_layers(obstacle, avoidance_layers);266}267268uint32_t NavigationObstacle2D::get_avoidance_layers() const {269return avoidance_layers;270}271272void NavigationObstacle2D::set_avoidance_layer_value(int p_layer_number, bool p_value) {273ERR_FAIL_COND_MSG(p_layer_number < 1, "Avoidance layer number must be between 1 and 32 inclusive.");274ERR_FAIL_COND_MSG(p_layer_number > 32, "Avoidance layer number must be between 1 and 32 inclusive.");275uint32_t avoidance_layers_new = get_avoidance_layers();276if (p_value) {277avoidance_layers_new |= 1 << (p_layer_number - 1);278} else {279avoidance_layers_new &= ~(1 << (p_layer_number - 1));280}281set_avoidance_layers(avoidance_layers_new);282}283284bool NavigationObstacle2D::get_avoidance_layer_value(int p_layer_number) const {285ERR_FAIL_COND_V_MSG(p_layer_number < 1, false, "Avoidance layer number must be between 1 and 32 inclusive.");286ERR_FAIL_COND_V_MSG(p_layer_number > 32, false, "Avoidance layer number must be between 1 and 32 inclusive.");287return get_avoidance_layers() & (1 << (p_layer_number - 1));288}289290void NavigationObstacle2D::set_avoidance_enabled(bool p_enabled) {291if (avoidance_enabled == p_enabled) {292return;293}294295avoidance_enabled = p_enabled;296NavigationServer2D::get_singleton()->obstacle_set_avoidance_enabled(obstacle, avoidance_enabled);297#ifdef DEBUG_ENABLED298queue_redraw();299#endif // DEBUG_ENABLED300}301302bool NavigationObstacle2D::get_avoidance_enabled() const {303return avoidance_enabled;304}305306void NavigationObstacle2D::set_velocity(const Vector2 p_velocity) {307velocity = p_velocity;308velocity_submitted = true;309}310311void NavigationObstacle2D::set_affect_navigation_mesh(bool p_enabled) {312affect_navigation_mesh = p_enabled;313}314315bool NavigationObstacle2D::get_affect_navigation_mesh() const {316return affect_navigation_mesh;317}318319void NavigationObstacle2D::set_carve_navigation_mesh(bool p_enabled) {320carve_navigation_mesh = p_enabled;321}322323bool NavigationObstacle2D::get_carve_navigation_mesh() const {324return carve_navigation_mesh;325}326327PackedStringArray NavigationObstacle2D::get_configuration_warnings() const {328PackedStringArray warnings = Node2D::get_configuration_warnings();329330const Vector2 global_scale = get_global_scale();331if (global_scale.x < 0.001 || global_scale.y < 0.001) {332warnings.push_back(RTR("NavigationObstacle2D does not support negative or zero scaling."));333}334335if (radius > 0.0 && !get_global_transform().is_conformal()) {336warnings.push_back(RTR("The agent radius can only be scaled uniformly. The largest value along the two axes of the global scale will be used to scale the radius. This value may change in unexpected ways when the node is rotated."));337}338339if (radius > 0.0 && get_global_skew() != 0.0) {340warnings.push_back(RTR("Skew has no effect on the agent radius."));341}342343return warnings;344}345346void NavigationObstacle2D::navmesh_parse_init() {347ERR_FAIL_NULL(NavigationServer2D::get_singleton());348if (!_navmesh_source_geometry_parser.is_valid()) {349_navmesh_source_geometry_parsing_callback = callable_mp_static(&NavigationObstacle2D::navmesh_parse_source_geometry);350_navmesh_source_geometry_parser = NavigationServer2D::get_singleton()->source_geometry_parser_create();351NavigationServer2D::get_singleton()->source_geometry_parser_set_callback(_navmesh_source_geometry_parser, _navmesh_source_geometry_parsing_callback);352}353}354355void NavigationObstacle2D::navmesh_parse_source_geometry(const Ref<NavigationPolygon> &p_navigation_mesh, Ref<NavigationMeshSourceGeometryData2D> p_source_geometry_data, Node *p_node) {356NavigationObstacle2D *obstacle = Object::cast_to<NavigationObstacle2D>(p_node);357358if (obstacle == nullptr) {359return;360}361362if (!obstacle->get_affect_navigation_mesh()) {363return;364}365366const Vector2 safe_scale = obstacle->get_global_scale().abs().maxf(0.001);367const float obstacle_radius = obstacle->get_radius();368369if (obstacle_radius > 0.0) {370// Radius defined obstacle should be uniformly scaled from obstacle basis max scale axis.371const float scaling_max_value = safe_scale[safe_scale.max_axis_index()];372const Vector2 uniform_max_scale = Vector2(scaling_max_value, scaling_max_value);373const Transform2D obstacle_circle_transform = p_source_geometry_data->root_node_transform * Transform2D(obstacle->get_global_rotation(), uniform_max_scale, 0.0, obstacle->get_global_position());374375Vector<Vector2> obstruction_circle_vertices;376377// The point of this is that the moving obstacle can make a simple hole in the navigation mesh and affect the pathfinding.378// Without, navigation paths can go directly through the middle of the obstacle and conflict with the avoidance to get agents stuck.379// No place for excessive "round" detail here. Every additional edge adds a high cost for something that needs to be quick, not pretty.380static const int circle_points = 12;381382obstruction_circle_vertices.resize(circle_points);383Vector2 *circle_vertices_ptrw = obstruction_circle_vertices.ptrw();384const real_t circle_point_step = Math::TAU / circle_points;385386for (int i = 0; i < circle_points; i++) {387const float angle = i * circle_point_step;388circle_vertices_ptrw[i] = obstacle_circle_transform.xform(Vector2(Math::cos(angle) * obstacle_radius, Math::sin(angle) * obstacle_radius));389}390391p_source_geometry_data->add_projected_obstruction(obstruction_circle_vertices, obstacle->get_carve_navigation_mesh());392}393394// Obstacles are projected to the xz-plane, so only rotation around the y-axis can be taken into account.395const Transform2D node_xform = p_source_geometry_data->root_node_transform * obstacle->get_global_transform();396397const Vector<Vector2> &obstacle_vertices = obstacle->get_vertices();398399if (obstacle_vertices.is_empty()) {400return;401}402403Vector<Vector2> obstruction_shape_vertices;404obstruction_shape_vertices.resize(obstacle_vertices.size());405406const Vector2 *obstacle_vertices_ptr = obstacle_vertices.ptr();407Vector2 *obstruction_shape_vertices_ptrw = obstruction_shape_vertices.ptrw();408409for (int i = 0; i < obstacle_vertices.size(); i++) {410obstruction_shape_vertices_ptrw[i] = node_xform.xform(obstacle_vertices_ptr[i]);411}412p_source_geometry_data->add_projected_obstruction(obstruction_shape_vertices, obstacle->get_carve_navigation_mesh());413}414415void NavigationObstacle2D::_update_map(RID p_map) {416map_current = p_map;417NavigationServer2D::get_singleton()->obstacle_set_map(obstacle, p_map);418}419420void NavigationObstacle2D::_update_position(const Vector2 p_position) {421NavigationServer2D::get_singleton()->obstacle_set_position(obstacle, p_position);422#ifdef DEBUG_ENABLED423queue_redraw();424#endif // DEBUG_ENABLED425}426427void NavigationObstacle2D::_update_transform() {428_update_position(get_global_position());429// Prevent non-positive or non-uniform scaling of dynamic obstacle radius.430const Vector2 safe_scale = get_global_scale().abs().maxf(0.001);431const float scaling_max_value = safe_scale[safe_scale.max_axis_index()];432NavigationServer2D::get_singleton()->obstacle_set_radius(obstacle, scaling_max_value * radius);433NavigationServer2D::get_singleton()->obstacle_set_vertices(obstacle, get_global_transform().translated(-get_global_position()).xform(vertices));434#ifdef DEBUG_ENABLED435queue_redraw();436#endif // DEBUG_ENABLED437}438439#ifdef DEBUG_ENABLED440void NavigationObstacle2D::_update_fake_agent_radius_debug() {441if (radius > 0.0 && NavigationServer2D::get_singleton()->get_debug_navigation_avoidance_enable_obstacles_radius()) {442Color debug_radius_color = NavigationServer2D::get_singleton()->get_debug_navigation_avoidance_obstacles_radius_color();443// Prevent non-positive scaling.444const Vector2 safe_scale = get_global_scale().abs().maxf(0.001);445// Agent radius is a scalar value and does not support non-uniform scaling, choose the largest axis.446const float scaling_max_value = safe_scale[safe_scale.max_axis_index()];447RS::get_singleton()->canvas_item_add_circle(debug_canvas_item, get_global_position(), scaling_max_value * radius, debug_radius_color);448}449}450#endif // DEBUG_ENABLED451452#ifdef DEBUG_ENABLED453void NavigationObstacle2D::_update_static_obstacle_debug() {454if (get_vertices().size() < 3) {455return;456}457458if (!NavigationServer2D::get_singleton()->get_debug_navigation_avoidance_enable_obstacles_static()) {459return;460}461462RenderingServer *rs = RenderingServer::get_singleton();463464rs->mesh_clear(debug_mesh_rid);465466const int vertex_count = vertices.size();467468Vector<Vector2> edge_vertex_array;469edge_vertex_array.resize(vertex_count * 4);470471Vector2 *edge_vertex_array_ptrw = edge_vertex_array.ptrw();472473int vertex_index = 0;474475for (int i = 0; i < vertex_count; i++) {476Vector2 point = vertices[i];477Vector2 next_point = vertices[(i + 1) % vertex_count];478479Vector2 direction = next_point.direction_to(point);480Vector2 arrow_dir = -direction.orthogonal();481Vector2 edge_middle = point + ((next_point - point) * 0.5);482483edge_vertex_array_ptrw[vertex_index++] = edge_middle;484edge_vertex_array_ptrw[vertex_index++] = edge_middle + (arrow_dir * 10.0);485486edge_vertex_array_ptrw[vertex_index++] = point;487edge_vertex_array_ptrw[vertex_index++] = next_point;488}489490Color debug_static_obstacle_edge_color;491492if (are_vertices_valid()) {493debug_static_obstacle_edge_color = NavigationServer2D::get_singleton()->get_debug_navigation_avoidance_static_obstacle_pushout_edge_color();494} else {495debug_static_obstacle_edge_color = NavigationServer2D::get_singleton()->get_debug_navigation_avoidance_static_obstacle_pushin_edge_color();496}497498Vector<Color> line_color_array;499line_color_array.resize(edge_vertex_array.size());500line_color_array.fill(debug_static_obstacle_edge_color);501502Array edge_mesh_array;503edge_mesh_array.resize(Mesh::ARRAY_MAX);504edge_mesh_array[Mesh::ARRAY_VERTEX] = edge_vertex_array;505edge_mesh_array[Mesh::ARRAY_COLOR] = line_color_array;506507rs->mesh_add_surface_from_arrays(debug_mesh_rid, RS::PRIMITIVE_LINES, edge_mesh_array, Array(), Dictionary(), RS::ARRAY_FLAG_USE_2D_VERTICES);508509rs->canvas_item_add_mesh(debug_canvas_item, debug_mesh_rid, get_global_transform());510}511#endif // DEBUG_ENABLED512513514