Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
godotengine
GitHub Repository: godotengine/godot
Path: blob/master/modules/navigation_3d/3d/nav_mesh_queries_3d.cpp
10278 views
1
/**************************************************************************/
2
/* nav_mesh_queries_3d.cpp */
3
/**************************************************************************/
4
/* This file is part of: */
5
/* GODOT ENGINE */
6
/* https://godotengine.org */
7
/**************************************************************************/
8
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
9
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
10
/* */
11
/* Permission is hereby granted, free of charge, to any person obtaining */
12
/* a copy of this software and associated documentation files (the */
13
/* "Software"), to deal in the Software without restriction, including */
14
/* without limitation the rights to use, copy, modify, merge, publish, */
15
/* distribute, sublicense, and/or sell copies of the Software, and to */
16
/* permit persons to whom the Software is furnished to do so, subject to */
17
/* the following conditions: */
18
/* */
19
/* The above copyright notice and this permission notice shall be */
20
/* included in all copies or substantial portions of the Software. */
21
/* */
22
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
23
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
24
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
25
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
26
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
27
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
28
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
29
/**************************************************************************/
30
31
#include "nav_mesh_queries_3d.h"
32
33
#include "../nav_base_3d.h"
34
#include "../nav_map_3d.h"
35
#include "nav_region_iteration_3d.h"
36
37
#include "core/math/geometry_2d.h"
38
#include "core/math/geometry_3d.h"
39
#include "servers/navigation/navigation_utilities.h"
40
41
using namespace Nav3D;
42
43
#define THREE_POINTS_CROSS_PRODUCT(m_a, m_b, m_c) (((m_c) - (m_a)).cross((m_b) - (m_a)))
44
45
bool NavMeshQueries3D::emit_callback(const Callable &p_callback) {
46
ERR_FAIL_COND_V(!p_callback.is_valid(), false);
47
48
Callable::CallError ce;
49
Variant result;
50
p_callback.callp(nullptr, 0, result, ce);
51
52
return ce.error == Callable::CallError::CALL_OK;
53
}
54
55
Vector3 NavMeshQueries3D::polygons_get_random_point(const LocalVector<Polygon> &p_polygons, uint32_t p_navigation_layers, bool p_uniformly) {
56
const LocalVector<Polygon> &region_polygons = p_polygons;
57
58
if (region_polygons.is_empty()) {
59
return Vector3();
60
}
61
62
if (p_uniformly) {
63
real_t accumulated_area = 0;
64
RBMap<real_t, uint32_t> region_area_map;
65
66
for (uint32_t rp_index = 0; rp_index < region_polygons.size(); rp_index++) {
67
const Polygon &region_polygon = region_polygons[rp_index];
68
real_t polyon_area = region_polygon.surface_area;
69
70
if (polyon_area == 0.0) {
71
continue;
72
}
73
region_area_map[accumulated_area] = rp_index;
74
accumulated_area += polyon_area;
75
}
76
if (region_area_map.is_empty() || accumulated_area == 0) {
77
// All polygons have no real surface / no area.
78
return Vector3();
79
}
80
81
real_t region_area_map_pos = Math::random(real_t(0), accumulated_area);
82
83
RBMap<real_t, uint32_t>::Iterator region_E = region_area_map.find_closest(region_area_map_pos);
84
ERR_FAIL_COND_V(!region_E, Vector3());
85
uint32_t rrp_polygon_index = region_E->value;
86
ERR_FAIL_UNSIGNED_INDEX_V(rrp_polygon_index, region_polygons.size(), Vector3());
87
88
const Polygon &rr_polygon = region_polygons[rrp_polygon_index];
89
90
real_t accumulated_polygon_area = 0;
91
RBMap<real_t, uint32_t> polygon_area_map;
92
93
for (uint32_t rpp_index = 2; rpp_index < rr_polygon.vertices.size(); rpp_index++) {
94
real_t face_area = Face3(rr_polygon.vertices[0], rr_polygon.vertices[rpp_index - 1], rr_polygon.vertices[rpp_index]).get_area();
95
96
if (face_area == 0.0) {
97
continue;
98
}
99
polygon_area_map[accumulated_polygon_area] = rpp_index;
100
accumulated_polygon_area += face_area;
101
}
102
if (polygon_area_map.is_empty() || accumulated_polygon_area == 0) {
103
// All faces have no real surface / no area.
104
return Vector3();
105
}
106
107
real_t polygon_area_map_pos = Math::random(real_t(0), accumulated_polygon_area);
108
109
RBMap<real_t, uint32_t>::Iterator polygon_E = polygon_area_map.find_closest(polygon_area_map_pos);
110
ERR_FAIL_COND_V(!polygon_E, Vector3());
111
uint32_t rrp_face_index = polygon_E->value;
112
ERR_FAIL_UNSIGNED_INDEX_V(rrp_face_index, rr_polygon.vertices.size(), Vector3());
113
114
const Face3 face(rr_polygon.vertices[0], rr_polygon.vertices[rrp_face_index - 1], rr_polygon.vertices[rrp_face_index]);
115
116
Vector3 face_random_position = face.get_random_point_inside();
117
return face_random_position;
118
119
} else {
120
uint32_t rrp_polygon_index = Math::random(int(0), region_polygons.size() - 1);
121
122
const Polygon &rr_polygon = region_polygons[rrp_polygon_index];
123
124
uint32_t rrp_face_index = Math::random(int(2), rr_polygon.vertices.size() - 1);
125
126
const Face3 face(rr_polygon.vertices[0], rr_polygon.vertices[rrp_face_index - 1], rr_polygon.vertices[rrp_face_index]);
127
128
Vector3 face_random_position = face.get_random_point_inside();
129
return face_random_position;
130
}
131
}
132
133
void NavMeshQueries3D::_query_task_push_back_point_with_metadata(NavMeshPathQueryTask3D &p_query_task, const Vector3 &p_point, const Polygon *p_point_polygon) {
134
if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_TYPES)) {
135
p_query_task.path_meta_point_types.push_back(p_point_polygon->owner->get_type());
136
}
137
138
if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_RIDS)) {
139
p_query_task.path_meta_point_rids.push_back(p_point_polygon->owner->get_self());
140
}
141
142
if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_OWNERS)) {
143
p_query_task.path_meta_point_owners.push_back(p_point_polygon->owner->get_owner_id());
144
}
145
146
p_query_task.path_points.push_back(p_point);
147
}
148
149
void NavMeshQueries3D::map_query_path(NavMap3D *map, const Ref<NavigationPathQueryParameters3D> &p_query_parameters, Ref<NavigationPathQueryResult3D> p_query_result, const Callable &p_callback) {
150
ERR_FAIL_NULL(map);
151
ERR_FAIL_COND(p_query_parameters.is_null());
152
ERR_FAIL_COND(p_query_result.is_null());
153
154
using namespace NavigationUtilities;
155
156
NavMeshQueries3D::NavMeshPathQueryTask3D query_task;
157
query_task.start_position = p_query_parameters->get_start_position();
158
query_task.target_position = p_query_parameters->get_target_position();
159
query_task.navigation_layers = p_query_parameters->get_navigation_layers();
160
query_task.callback = p_callback;
161
162
const TypedArray<RID> &_excluded_regions = p_query_parameters->get_excluded_regions();
163
const TypedArray<RID> &_included_regions = p_query_parameters->get_included_regions();
164
165
uint32_t _excluded_region_count = _excluded_regions.size();
166
uint32_t _included_region_count = _included_regions.size();
167
168
query_task.exclude_regions = _excluded_region_count > 0;
169
query_task.include_regions = _included_region_count > 0;
170
171
if (query_task.exclude_regions) {
172
query_task.excluded_regions.resize(_excluded_region_count);
173
for (uint32_t i = 0; i < _excluded_region_count; i++) {
174
query_task.excluded_regions[i] = _excluded_regions[i];
175
}
176
}
177
178
if (query_task.include_regions) {
179
query_task.included_regions.resize(_included_region_count);
180
for (uint32_t i = 0; i < _included_region_count; i++) {
181
query_task.included_regions[i] = _included_regions[i];
182
}
183
}
184
185
switch (p_query_parameters->get_pathfinding_algorithm()) {
186
case NavigationPathQueryParameters3D::PathfindingAlgorithm::PATHFINDING_ALGORITHM_ASTAR: {
187
query_task.pathfinding_algorithm = PathfindingAlgorithm::PATHFINDING_ALGORITHM_ASTAR;
188
} break;
189
default: {
190
WARN_PRINT("No match for used PathfindingAlgorithm - fallback to default");
191
query_task.pathfinding_algorithm = PathfindingAlgorithm::PATHFINDING_ALGORITHM_ASTAR;
192
} break;
193
}
194
195
switch (p_query_parameters->get_path_postprocessing()) {
196
case NavigationPathQueryParameters3D::PathPostProcessing::PATH_POSTPROCESSING_CORRIDORFUNNEL: {
197
query_task.path_postprocessing = PathPostProcessing::PATH_POSTPROCESSING_CORRIDORFUNNEL;
198
} break;
199
case NavigationPathQueryParameters3D::PathPostProcessing::PATH_POSTPROCESSING_EDGECENTERED: {
200
query_task.path_postprocessing = PathPostProcessing::PATH_POSTPROCESSING_EDGECENTERED;
201
} break;
202
case NavigationPathQueryParameters3D::PathPostProcessing::PATH_POSTPROCESSING_NONE: {
203
query_task.path_postprocessing = PathPostProcessing::PATH_POSTPROCESSING_NONE;
204
} break;
205
default: {
206
WARN_PRINT("No match for used PathPostProcessing - fallback to default");
207
query_task.path_postprocessing = PathPostProcessing::PATH_POSTPROCESSING_CORRIDORFUNNEL;
208
} break;
209
}
210
211
query_task.metadata_flags = (int64_t)p_query_parameters->get_metadata_flags();
212
query_task.simplify_path = p_query_parameters->get_simplify_path();
213
query_task.simplify_epsilon = p_query_parameters->get_simplify_epsilon();
214
query_task.path_return_max_length = p_query_parameters->get_path_return_max_length();
215
query_task.path_return_max_radius = p_query_parameters->get_path_return_max_radius();
216
query_task.path_search_max_polygons = p_query_parameters->get_path_search_max_polygons();
217
query_task.path_search_max_distance = p_query_parameters->get_path_search_max_distance();
218
query_task.status = NavMeshPathQueryTask3D::TaskStatus::QUERY_STARTED;
219
220
map->query_path(query_task);
221
222
p_query_result->set_data(
223
query_task.path_points,
224
query_task.path_meta_point_types,
225
query_task.path_meta_point_rids,
226
query_task.path_meta_point_owners);
227
p_query_result->set_path_length(query_task.path_length);
228
229
if (query_task.callback.is_valid()) {
230
if (emit_callback(query_task.callback)) {
231
query_task.status = NavMeshPathQueryTask3D::TaskStatus::CALLBACK_DISPATCHED;
232
} else {
233
query_task.status = NavMeshPathQueryTask3D::TaskStatus::CALLBACK_FAILED;
234
}
235
}
236
}
237
238
void NavMeshQueries3D::_query_task_find_start_end_positions(NavMeshPathQueryTask3D &p_query_task, const NavMapIteration3D &p_map_iteration) {
239
real_t begin_d = FLT_MAX;
240
real_t end_d = FLT_MAX;
241
242
const LocalVector<Ref<NavRegionIteration3D>> &regions = p_map_iteration.region_iterations;
243
244
for (const Ref<NavRegionIteration3D> &region : regions) {
245
if (!_query_task_is_connection_owner_usable(p_query_task, region.ptr())) {
246
continue;
247
}
248
249
// Find the initial poly and the end poly on this map.
250
for (const Polygon &p : region->get_navmesh_polygons()) {
251
// Only consider the polygon if it in a region with compatible layers.
252
if ((p_query_task.navigation_layers & p.owner->get_navigation_layers()) == 0) {
253
continue;
254
}
255
256
// For each face check the distance between the origin/destination.
257
for (uint32_t point_id = 2; point_id < p.vertices.size(); point_id++) {
258
const Face3 face(p.vertices[0], p.vertices[point_id - 1], p.vertices[point_id]);
259
260
Vector3 point = face.get_closest_point_to(p_query_task.start_position);
261
real_t distance_to_point = point.distance_to(p_query_task.start_position);
262
if (distance_to_point < begin_d) {
263
begin_d = distance_to_point;
264
p_query_task.begin_polygon = &p;
265
p_query_task.begin_position = point;
266
}
267
268
point = face.get_closest_point_to(p_query_task.target_position);
269
distance_to_point = point.distance_to(p_query_task.target_position);
270
if (distance_to_point < end_d) {
271
end_d = distance_to_point;
272
p_query_task.end_polygon = &p;
273
p_query_task.end_position = point;
274
}
275
}
276
}
277
}
278
}
279
280
void NavMeshQueries3D::_query_task_search_polygon_connections(NavMeshPathQueryTask3D &p_query_task, const Connection &p_connection, uint32_t p_least_cost_id, const NavigationPoly &p_least_cost_poly, real_t p_poly_enter_cost, const Vector3 &p_end_point) {
281
const NavBaseIteration3D *connection_owner = p_connection.polygon->owner;
282
ERR_FAIL_NULL(connection_owner);
283
const bool owner_is_usable = _query_task_is_connection_owner_usable(p_query_task, connection_owner);
284
if (!owner_is_usable) {
285
return;
286
}
287
288
Heap<NavigationPoly *, NavPolyTravelCostGreaterThan, NavPolyHeapIndexer>
289
&traversable_polys = p_query_task.path_query_slot->traversable_polys;
290
LocalVector<NavigationPoly> &navigation_polys = p_query_task.path_query_slot->path_corridor;
291
292
real_t poly_travel_cost = p_least_cost_poly.poly->owner->get_travel_cost();
293
294
Vector3 new_entry = Geometry3D::get_closest_point_to_segment(p_least_cost_poly.entry, p_connection.pathway_start, p_connection.pathway_end);
295
real_t new_traveled_distance = p_least_cost_poly.entry.distance_to(new_entry) * poly_travel_cost + p_poly_enter_cost + p_least_cost_poly.traveled_distance;
296
297
// Check if the neighbor polygon has already been processed.
298
NavigationPoly &neighbor_poly = navigation_polys[p_query_task.path_query_slot->poly_to_id[p_connection.polygon]];
299
if (new_traveled_distance < neighbor_poly.traveled_distance) {
300
// Add the polygon to the heap of polygons to traverse next.
301
neighbor_poly.back_navigation_poly_id = p_least_cost_id;
302
neighbor_poly.back_navigation_edge = p_connection.edge;
303
neighbor_poly.back_navigation_edge_pathway_start = p_connection.pathway_start;
304
neighbor_poly.back_navigation_edge_pathway_end = p_connection.pathway_end;
305
neighbor_poly.traveled_distance = new_traveled_distance;
306
neighbor_poly.distance_to_destination =
307
new_entry.distance_to(p_end_point) *
308
connection_owner->get_travel_cost();
309
neighbor_poly.entry = new_entry;
310
311
if (neighbor_poly.traversable_poly_index != traversable_polys.INVALID_INDEX) {
312
traversable_polys.shift(neighbor_poly.traversable_poly_index);
313
} else {
314
neighbor_poly.poly = p_connection.polygon;
315
traversable_polys.push(&neighbor_poly);
316
}
317
}
318
}
319
320
void NavMeshQueries3D::_query_task_build_path_corridor(NavMeshPathQueryTask3D &p_query_task, const NavMapIteration3D &p_map_iteration) {
321
const Vector3 p_target_position = p_query_task.target_position;
322
const Polygon *begin_poly = p_query_task.begin_polygon;
323
const Polygon *end_poly = p_query_task.end_polygon;
324
Vector3 begin_point = p_query_task.begin_position;
325
Vector3 end_point = p_query_task.end_position;
326
327
// Heap of polygons to travel next.
328
Heap<NavigationPoly *, NavPolyTravelCostGreaterThan, NavPolyHeapIndexer>
329
&traversable_polys = p_query_task.path_query_slot->traversable_polys;
330
traversable_polys.clear();
331
332
LocalVector<NavigationPoly> &navigation_polys = p_query_task.path_query_slot->path_corridor;
333
for (NavigationPoly &polygon : navigation_polys) {
334
polygon.reset();
335
}
336
337
// Initialize the matching navigation polygon.
338
NavigationPoly &begin_navigation_poly = navigation_polys[p_query_task.path_query_slot->poly_to_id[begin_poly]];
339
begin_navigation_poly.poly = begin_poly;
340
begin_navigation_poly.entry = begin_point;
341
begin_navigation_poly.back_navigation_edge_pathway_start = begin_point;
342
begin_navigation_poly.back_navigation_edge_pathway_end = begin_point;
343
begin_navigation_poly.traveled_distance = 0.f;
344
345
// This is an implementation of the A* algorithm.
346
uint32_t least_cost_id = p_query_task.path_query_slot->poly_to_id[begin_poly];
347
bool found_route = false;
348
349
const Polygon *reachable_end = nullptr;
350
real_t distance_to_reachable_end = FLT_MAX;
351
bool is_reachable = true;
352
real_t poly_enter_cost = 0.0;
353
354
const HashMap<const NavBaseIteration3D *, LocalVector<LocalVector<Nav3D::Connection>>> &navbases_polygons_external_connections = p_map_iteration.navbases_polygons_external_connections;
355
356
// True if we reached the max polygon search count or distance from the begin position.
357
bool path_search_max_reached = false;
358
359
const float path_search_max_distance_sqr = p_query_task.path_search_max_distance * p_query_task.path_search_max_distance;
360
bool has_path_search_max_distance = path_search_max_distance_sqr > 0.0;
361
362
int processed_polygon_count = 0;
363
bool has_path_search_max_polygons = p_query_task.path_search_max_polygons > 0;
364
365
bool has_path_search_max = p_query_task.path_search_max_polygons > 0 || path_search_max_distance_sqr > 0.0;
366
367
while (true) {
368
const NavigationPoly &least_cost_poly = navigation_polys[least_cost_id];
369
370
const NavBaseIteration3D *least_cost_navbase = least_cost_poly.poly->owner;
371
372
processed_polygon_count += 1;
373
374
const uint32_t navbase_local_polygon_id = least_cost_poly.poly->id;
375
const LocalVector<LocalVector<Connection>> &navbase_polygons_to_connections = least_cost_poly.poly->owner->get_internal_connections();
376
377
if (navbase_polygons_to_connections.size() > 0) {
378
const LocalVector<Connection> &polygon_connections = navbase_polygons_to_connections[navbase_local_polygon_id];
379
380
for (const Connection &connection : polygon_connections) {
381
_query_task_search_polygon_connections(p_query_task, connection, least_cost_id, least_cost_poly, poly_enter_cost, end_point);
382
}
383
}
384
385
// Search region external navmesh polygon connections, aka connections to other regions created by outline edge merge or links.
386
for (const Connection &connection : navbases_polygons_external_connections[least_cost_navbase][navbase_local_polygon_id]) {
387
_query_task_search_polygon_connections(p_query_task, connection, least_cost_id, least_cost_poly, poly_enter_cost, end_point);
388
}
389
390
if (has_path_search_max && !path_search_max_reached) {
391
if (has_path_search_max_polygons && processed_polygon_count >= p_query_task.path_search_max_polygons) {
392
path_search_max_reached = true;
393
traversable_polys.clear();
394
} else if (has_path_search_max_distance && begin_point.distance_squared_to(least_cost_poly.entry) > path_search_max_distance_sqr) {
395
path_search_max_reached = true;
396
traversable_polys.clear();
397
}
398
}
399
400
poly_enter_cost = 0;
401
// When the heap of traversable polygons is empty at this point it means the end polygon is
402
// unreachable.
403
if (traversable_polys.is_empty()) {
404
// Thus use the further reachable polygon
405
ERR_BREAK_MSG(is_reachable == false, "It's not expect to not find the most reachable polygons");
406
is_reachable = false;
407
if (reachable_end == nullptr) {
408
// The path is not found and there is not a way out.
409
break;
410
}
411
412
// Set as end point the furthest reachable point.
413
end_poly = reachable_end;
414
real_t end_d = FLT_MAX;
415
416
for (uint32_t point_id = 2; point_id < end_poly->vertices.size(); point_id++) {
417
Face3 f(end_poly->vertices[0], end_poly->vertices[point_id - 1], end_poly->vertices[point_id]);
418
Vector3 spoint = f.get_closest_point_to(p_target_position);
419
real_t dpoint = spoint.distance_squared_to(p_target_position);
420
if (dpoint < end_d) {
421
end_point = spoint;
422
end_d = dpoint;
423
}
424
}
425
426
// Search all faces of start polygon as well.
427
bool closest_point_on_start_poly = false;
428
429
for (uint32_t point_id = 2; point_id < begin_poly->vertices.size(); point_id++) {
430
Face3 f(begin_poly->vertices[0], begin_poly->vertices[point_id - 1], begin_poly->vertices[point_id]);
431
Vector3 spoint = f.get_closest_point_to(p_target_position);
432
real_t dpoint = spoint.distance_squared_to(p_target_position);
433
if (dpoint < end_d) {
434
end_point = spoint;
435
end_d = dpoint;
436
closest_point_on_start_poly = true;
437
}
438
}
439
440
if (closest_point_on_start_poly) {
441
// No point to run PostProcessing when start and end convex polygon is the same.
442
p_query_task.path_clear();
443
444
_query_task_push_back_point_with_metadata(p_query_task, begin_point, begin_poly);
445
_query_task_push_back_point_with_metadata(p_query_task, end_point, begin_poly);
446
p_query_task.status = NavMeshPathQueryTask3D::TaskStatus::QUERY_FINISHED;
447
return;
448
}
449
450
for (NavigationPoly &nav_poly : navigation_polys) {
451
nav_poly.poly = nullptr;
452
nav_poly.traveled_distance = FLT_MAX;
453
}
454
uint32_t _bp_id = p_query_task.path_query_slot->poly_to_id[begin_poly];
455
navigation_polys[_bp_id].poly = begin_poly;
456
navigation_polys[_bp_id].traveled_distance = 0;
457
least_cost_id = _bp_id;
458
reachable_end = nullptr;
459
} else {
460
// Pop the polygon with the lowest travel cost from the heap of traversable polygons.
461
least_cost_id = p_query_task.path_query_slot->poly_to_id[traversable_polys.pop()->poly];
462
463
// Store the farthest reachable end polygon in case our goal is not reachable.
464
if (is_reachable) {
465
real_t distance = navigation_polys[least_cost_id].entry.distance_squared_to(p_target_position);
466
if (distance_to_reachable_end > distance) {
467
distance_to_reachable_end = distance;
468
reachable_end = navigation_polys[least_cost_id].poly;
469
}
470
}
471
472
// Check if we reached the end
473
if (navigation_polys[least_cost_id].poly == end_poly) {
474
found_route = true;
475
break;
476
}
477
478
if (navigation_polys[least_cost_id].poly->owner->get_self() != least_cost_poly.poly->owner->get_self()) {
479
ERR_FAIL_NULL(least_cost_poly.poly->owner);
480
poly_enter_cost = least_cost_poly.poly->owner->get_enter_cost();
481
}
482
}
483
}
484
485
// We did not find a route but we have both a start polygon and an end polygon at this point.
486
// Usually this happens because there was not a single external or internal connected edge, e.g. our start polygon is an isolated, single convex polygon.
487
if (!found_route) {
488
real_t end_d = FLT_MAX;
489
// Search all faces of the start polygon for the closest point to our target position.
490
491
for (uint32_t point_id = 2; point_id < begin_poly->vertices.size(); point_id++) {
492
Face3 f(begin_poly->vertices[0], begin_poly->vertices[point_id - 1], begin_poly->vertices[point_id]);
493
Vector3 spoint = f.get_closest_point_to(p_target_position);
494
real_t dpoint = spoint.distance_squared_to(p_target_position);
495
if (dpoint < end_d) {
496
end_point = spoint;
497
end_d = dpoint;
498
}
499
}
500
501
p_query_task.path_clear();
502
503
_query_task_push_back_point_with_metadata(p_query_task, begin_point, begin_poly);
504
_query_task_push_back_point_with_metadata(p_query_task, end_point, begin_poly);
505
p_query_task.status = NavMeshPathQueryTask3D::TaskStatus::QUERY_FINISHED;
506
} else {
507
p_query_task.end_position = end_point;
508
p_query_task.end_polygon = end_poly;
509
p_query_task.begin_position = begin_point;
510
p_query_task.begin_polygon = begin_poly;
511
p_query_task.least_cost_id = least_cost_id;
512
}
513
}
514
515
void NavMeshQueries3D::query_task_map_iteration_get_path(NavMeshPathQueryTask3D &p_query_task, const NavMapIteration3D &p_map_iteration) {
516
p_query_task.path_clear();
517
518
_query_task_find_start_end_positions(p_query_task, p_map_iteration);
519
520
// Check for trivial cases.
521
if (!p_query_task.begin_polygon || !p_query_task.end_polygon) {
522
p_query_task.status = NavMeshPathQueryTask3D::TaskStatus::QUERY_FINISHED;
523
return;
524
}
525
if (p_query_task.begin_polygon == p_query_task.end_polygon) {
526
p_query_task.path_clear();
527
_query_task_push_back_point_with_metadata(p_query_task, p_query_task.begin_position, p_query_task.begin_polygon);
528
_query_task_push_back_point_with_metadata(p_query_task, p_query_task.end_position, p_query_task.end_polygon);
529
_query_task_process_path_result_limits(p_query_task);
530
p_query_task.status = NavMeshPathQueryTask3D::TaskStatus::QUERY_FINISHED;
531
return;
532
}
533
534
_query_task_build_path_corridor(p_query_task, p_map_iteration);
535
536
if (p_query_task.status == NavMeshPathQueryTask3D::TaskStatus::QUERY_FINISHED || p_query_task.status == NavMeshPathQueryTask3D::TaskStatus::QUERY_FAILED) {
537
_query_task_process_path_result_limits(p_query_task);
538
return;
539
}
540
541
// Post-Process path.
542
switch (p_query_task.path_postprocessing) {
543
case PathPostProcessing::PATH_POSTPROCESSING_CORRIDORFUNNEL: {
544
_query_task_post_process_corridorfunnel(p_query_task);
545
} break;
546
case PathPostProcessing::PATH_POSTPROCESSING_EDGECENTERED: {
547
_query_task_post_process_edgecentered(p_query_task);
548
} break;
549
case PathPostProcessing::PATH_POSTPROCESSING_NONE: {
550
_query_task_post_process_nopostprocessing(p_query_task);
551
} break;
552
default: {
553
WARN_PRINT("No match for used PathPostProcessing - fallback to default");
554
_query_task_post_process_corridorfunnel(p_query_task);
555
} break;
556
}
557
558
p_query_task.path_reverse();
559
560
if (p_query_task.simplify_path) {
561
_query_task_simplified_path_points(p_query_task);
562
}
563
564
_query_task_process_path_result_limits(p_query_task);
565
566
#ifdef DEBUG_ENABLED
567
// Ensure post conditions as path meta arrays if used MUST match in array size with the path points.
568
if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_TYPES)) {
569
DEV_ASSERT(p_query_task.path_points.size() == p_query_task.path_meta_point_types.size());
570
}
571
572
if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_RIDS)) {
573
DEV_ASSERT(p_query_task.path_points.size() == p_query_task.path_meta_point_rids.size());
574
}
575
576
if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_OWNERS)) {
577
DEV_ASSERT(p_query_task.path_points.size() == p_query_task.path_meta_point_owners.size());
578
}
579
#endif // DEBUG_ENABLED
580
581
p_query_task.status = NavMeshPathQueryTask3D::TaskStatus::QUERY_FINISHED;
582
}
583
584
float NavMeshQueries3D::_calculate_path_length(const LocalVector<Vector3> &p_path, uint32_t p_start_index, uint32_t p_end_index) {
585
const uint32_t path_size = p_path.size();
586
if (path_size < 2) {
587
return 0.0;
588
}
589
590
ERR_FAIL_COND_V(p_start_index >= p_end_index, 0.0);
591
ERR_FAIL_COND_V(p_start_index >= path_size - 1, 0.0);
592
ERR_FAIL_COND_V(p_end_index >= path_size, 0.0);
593
594
const Vector3 *path_ptr = p_path.ptr();
595
596
float path_length = 0.0;
597
598
for (uint32_t i = p_start_index; i < p_end_index; i++) {
599
const Vector3 &vertex1 = path_ptr[i];
600
const Vector3 &vertex2 = path_ptr[i + 1];
601
float edge_length = vertex1.distance_to(vertex2);
602
path_length += edge_length;
603
}
604
605
return path_length;
606
}
607
608
void NavMeshQueries3D::_query_task_process_path_result_limits(NavMeshPathQueryTask3D &p_query_task) {
609
if (p_query_task.path_points.size() < 2) {
610
return;
611
}
612
613
bool check_max_length = p_query_task.path_return_max_length > 0.0;
614
bool check_max_radius = p_query_task.path_return_max_radius > 0.0;
615
616
if (!check_max_length && !check_max_radius) {
617
p_query_task.path_length = _calculate_path_length(p_query_task.path_points, 0, p_query_task.path_points.size() - 1);
618
return;
619
}
620
621
LocalVector<Vector3> &path = p_query_task.path_points;
622
623
const float max_length = p_query_task.path_return_max_length;
624
const float max_radius = p_query_task.path_return_max_radius;
625
const float max_radius_sqr = max_radius * max_radius;
626
627
const Vector3 &start_pos = path[0];
628
629
float accumulated_path_length = 0.0;
630
631
Vector3 *path_ptrw = path.ptr();
632
633
uint32_t path_max_size = path.size();
634
bool path_max_reached = false;
635
636
for (uint32_t i = 0; i < path.size() - 1; i++) {
637
uint32_t next_index = i + 1;
638
const Vector3 &vertex1 = path_ptrw[i];
639
Vector3 &vertex2 = path_ptrw[next_index];
640
641
float edge_length = (vertex2 - vertex1).length();
642
643
if (check_max_radius && start_pos.distance_squared_to(vertex2) > max_radius_sqr) {
644
// Path point segment goes over max radius, clip it.
645
Vector3 intersect_positon, intersect_normal;
646
bool intersected = Geometry3D::segment_intersects_sphere(vertex2, vertex1, start_pos, max_radius, &intersect_positon, &intersect_normal);
647
if (intersected) {
648
edge_length = (intersect_positon - vertex1).length();
649
650
path_ptrw[next_index] = intersect_positon;
651
path_max_size = next_index + 1;
652
path_max_reached = true;
653
}
654
}
655
656
if (check_max_length && accumulated_path_length + edge_length > max_length) {
657
// Path point segment goes over max length, clip it.
658
edge_length = max_length - accumulated_path_length;
659
Vector3 edge_direction = vertex1.direction_to(vertex2);
660
661
path_ptrw[next_index] = vertex1 + (edge_direction * edge_length);
662
path_max_size = next_index + 1;
663
664
p_query_task.path_length = accumulated_path_length + edge_length;
665
path_max_reached = true;
666
}
667
668
accumulated_path_length += edge_length;
669
670
if (path_max_reached) {
671
break;
672
}
673
}
674
675
p_query_task.path_length = accumulated_path_length;
676
677
if (path_max_size < path.size()) {
678
p_query_task.path_points.resize(path_max_size);
679
680
if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_TYPES)) {
681
p_query_task.path_meta_point_types.resize(path_max_size);
682
}
683
684
if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_RIDS)) {
685
p_query_task.path_meta_point_rids.resize(path_max_size);
686
}
687
688
if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_OWNERS)) {
689
p_query_task.path_meta_point_owners.resize(path_max_size);
690
}
691
}
692
}
693
694
void NavMeshQueries3D::_query_task_simplified_path_points(NavMeshPathQueryTask3D &p_query_task) {
695
if (!p_query_task.simplify_path || p_query_task.path_points.size() <= 2) {
696
return;
697
}
698
699
const LocalVector<uint32_t> &simplified_path_indices = NavMeshQueries3D::get_simplified_path_indices(p_query_task.path_points, p_query_task.simplify_epsilon);
700
701
uint32_t index_count = simplified_path_indices.size();
702
703
{
704
Vector3 *points_ptr = p_query_task.path_points.ptr();
705
for (uint32_t i = 0; i < index_count; i++) {
706
points_ptr[i] = points_ptr[simplified_path_indices[i]];
707
}
708
p_query_task.path_points.resize(index_count);
709
}
710
711
if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_TYPES)) {
712
int32_t *types_ptr = p_query_task.path_meta_point_types.ptr();
713
for (uint32_t i = 0; i < index_count; i++) {
714
types_ptr[i] = types_ptr[simplified_path_indices[i]];
715
}
716
p_query_task.path_meta_point_types.resize(index_count);
717
}
718
719
if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_RIDS)) {
720
RID *rids_ptr = p_query_task.path_meta_point_rids.ptr();
721
for (uint32_t i = 0; i < index_count; i++) {
722
rids_ptr[i] = rids_ptr[simplified_path_indices[i]];
723
}
724
p_query_task.path_meta_point_rids.resize(index_count);
725
}
726
727
if (p_query_task.metadata_flags.has_flag(PathMetadataFlags::PATH_INCLUDE_OWNERS)) {
728
int64_t *owners_ptr = p_query_task.path_meta_point_owners.ptr();
729
for (uint32_t i = 0; i < index_count; i++) {
730
owners_ptr[i] = owners_ptr[simplified_path_indices[i]];
731
}
732
p_query_task.path_meta_point_owners.resize(index_count);
733
}
734
}
735
736
void NavMeshQueries3D::_query_task_post_process_corridorfunnel(NavMeshPathQueryTask3D &p_query_task) {
737
Vector3 end_point = p_query_task.end_position;
738
const Polygon *end_poly = p_query_task.end_polygon;
739
Vector3 begin_point = p_query_task.begin_position;
740
const Polygon *begin_poly = p_query_task.begin_polygon;
741
uint32_t least_cost_id = p_query_task.least_cost_id;
742
LocalVector<NavigationPoly> &navigation_polys = p_query_task.path_query_slot->path_corridor;
743
Vector3 p_map_up = p_query_task.map_up;
744
745
// Set the apex poly/point to the end point
746
NavigationPoly *apex_poly = &navigation_polys[least_cost_id];
747
748
const Vector3 back_edge_closest_point = Geometry3D::get_closest_point_to_segment(end_point, apex_poly->back_navigation_edge_pathway_start, apex_poly->back_navigation_edge_pathway_end);
749
if (end_point.is_equal_approx(back_edge_closest_point)) {
750
// The end point is basically on top of the last crossed edge, funneling around the corners would at best do nothing.
751
// At worst it would add an unwanted path point before the last point due to precision issues so skip to the next polygon.
752
if (apex_poly->back_navigation_poly_id != -1) {
753
apex_poly = &navigation_polys[apex_poly->back_navigation_poly_id];
754
}
755
}
756
757
Vector3 apex_point = end_point;
758
759
NavigationPoly *left_poly = apex_poly;
760
Vector3 left_portal = apex_point;
761
NavigationPoly *right_poly = apex_poly;
762
Vector3 right_portal = apex_point;
763
764
NavigationPoly *p = apex_poly;
765
766
_query_task_push_back_point_with_metadata(p_query_task, end_point, end_poly);
767
768
while (p) {
769
// Set left and right points of the pathway between polygons.
770
Vector3 left = p->back_navigation_edge_pathway_start;
771
Vector3 right = p->back_navigation_edge_pathway_end;
772
if (THREE_POINTS_CROSS_PRODUCT(apex_point, left, right).dot(p_map_up) < 0) {
773
SWAP(left, right);
774
}
775
776
bool skip = false;
777
if (THREE_POINTS_CROSS_PRODUCT(apex_point, left_portal, left).dot(p_map_up) >= 0) {
778
//process
779
if (left_portal == apex_point || THREE_POINTS_CROSS_PRODUCT(apex_point, left, right_portal).dot(p_map_up) > 0) {
780
left_poly = p;
781
left_portal = left;
782
} else {
783
_query_task_clip_path(p_query_task, apex_poly, right_portal, right_poly);
784
785
apex_point = right_portal;
786
p = right_poly;
787
left_poly = p;
788
apex_poly = p;
789
left_portal = apex_point;
790
right_portal = apex_point;
791
792
_query_task_push_back_point_with_metadata(p_query_task, apex_point, apex_poly->poly);
793
skip = true;
794
}
795
}
796
797
if (!skip && THREE_POINTS_CROSS_PRODUCT(apex_point, right_portal, right).dot(p_map_up) <= 0) {
798
//process
799
if (right_portal == apex_point || THREE_POINTS_CROSS_PRODUCT(apex_point, right, left_portal).dot(p_map_up) < 0) {
800
right_poly = p;
801
right_portal = right;
802
} else {
803
_query_task_clip_path(p_query_task, apex_poly, left_portal, left_poly);
804
805
apex_point = left_portal;
806
p = left_poly;
807
right_poly = p;
808
apex_poly = p;
809
right_portal = apex_point;
810
left_portal = apex_point;
811
812
_query_task_push_back_point_with_metadata(p_query_task, apex_point, apex_poly->poly);
813
}
814
}
815
816
// Go to the previous polygon.
817
if (p->back_navigation_poly_id != -1) {
818
p = &navigation_polys[p->back_navigation_poly_id];
819
} else {
820
// The end
821
p = nullptr;
822
}
823
}
824
825
// If the last point is not the begin point, add it to the list.
826
if (p_query_task.path_points[p_query_task.path_points.size() - 1] != begin_point) {
827
_query_task_push_back_point_with_metadata(p_query_task, begin_point, begin_poly);
828
}
829
}
830
831
void NavMeshQueries3D::_query_task_post_process_edgecentered(NavMeshPathQueryTask3D &p_query_task) {
832
Vector3 end_point = p_query_task.end_position;
833
const Polygon *end_poly = p_query_task.end_polygon;
834
Vector3 begin_point = p_query_task.begin_position;
835
const Polygon *begin_poly = p_query_task.begin_polygon;
836
uint32_t least_cost_id = p_query_task.least_cost_id;
837
LocalVector<NavigationPoly> &navigation_polys = p_query_task.path_query_slot->path_corridor;
838
839
_query_task_push_back_point_with_metadata(p_query_task, end_point, end_poly);
840
841
// Add mid points
842
int np_id = least_cost_id;
843
while (np_id != -1 && navigation_polys[np_id].back_navigation_poly_id != -1) {
844
if (navigation_polys[np_id].back_navigation_edge != -1) {
845
int prev = navigation_polys[np_id].back_navigation_edge;
846
int prev_n = (navigation_polys[np_id].back_navigation_edge + 1) % navigation_polys[np_id].poly->vertices.size();
847
Vector3 point = (navigation_polys[np_id].poly->vertices[prev] + navigation_polys[np_id].poly->vertices[prev_n]) * 0.5;
848
849
_query_task_push_back_point_with_metadata(p_query_task, point, navigation_polys[np_id].poly);
850
} else {
851
_query_task_push_back_point_with_metadata(p_query_task, navigation_polys[np_id].entry, navigation_polys[np_id].poly);
852
}
853
854
np_id = navigation_polys[np_id].back_navigation_poly_id;
855
}
856
857
_query_task_push_back_point_with_metadata(p_query_task, begin_point, begin_poly);
858
}
859
860
void NavMeshQueries3D::_query_task_post_process_nopostprocessing(NavMeshPathQueryTask3D &p_query_task) {
861
Vector3 end_point = p_query_task.end_position;
862
const Polygon *end_poly = p_query_task.end_polygon;
863
Vector3 begin_point = p_query_task.begin_position;
864
const Polygon *begin_poly = p_query_task.begin_polygon;
865
uint32_t least_cost_id = p_query_task.least_cost_id;
866
LocalVector<NavigationPoly> &navigation_polys = p_query_task.path_query_slot->path_corridor;
867
868
_query_task_push_back_point_with_metadata(p_query_task, end_point, end_poly);
869
870
// Add mid points
871
int np_id = least_cost_id;
872
while (np_id != -1 && navigation_polys[np_id].back_navigation_poly_id != -1) {
873
_query_task_push_back_point_with_metadata(p_query_task, navigation_polys[np_id].entry, navigation_polys[np_id].poly);
874
875
np_id = navigation_polys[np_id].back_navigation_poly_id;
876
}
877
878
_query_task_push_back_point_with_metadata(p_query_task, begin_point, begin_poly);
879
}
880
881
Vector3 NavMeshQueries3D::map_iteration_get_closest_point_to_segment(const NavMapIteration3D &p_map_iteration, const Vector3 &p_from, const Vector3 &p_to, const bool p_use_collision) {
882
bool use_collision = p_use_collision;
883
Vector3 closest_point;
884
real_t closest_point_distance = FLT_MAX;
885
886
const LocalVector<Ref<NavRegionIteration3D>> &regions = p_map_iteration.region_iterations;
887
for (const Ref<NavRegionIteration3D> &region : regions) {
888
for (const Polygon &polygon : region->get_navmesh_polygons()) {
889
// For each face check the distance to the segment.
890
for (uint32_t point_id = 2; point_id < polygon.vertices.size(); point_id += 1) {
891
const Face3 face(polygon.vertices[0], polygon.vertices[point_id - 1], polygon.vertices[point_id]);
892
Vector3 intersection_point;
893
if (face.intersects_segment(p_from, p_to, &intersection_point)) {
894
const real_t d = p_from.distance_to(intersection_point);
895
if (!use_collision) {
896
closest_point = intersection_point;
897
use_collision = true;
898
closest_point_distance = d;
899
} else if (closest_point_distance > d) {
900
closest_point = intersection_point;
901
closest_point_distance = d;
902
}
903
}
904
// If segment does not itersect face, check the distance from segment's endpoints.
905
else if (!use_collision) {
906
const Vector3 p_from_closest = face.get_closest_point_to(p_from);
907
const real_t d_p_from = p_from.distance_to(p_from_closest);
908
if (closest_point_distance > d_p_from) {
909
closest_point = p_from_closest;
910
closest_point_distance = d_p_from;
911
}
912
913
const Vector3 p_to_closest = face.get_closest_point_to(p_to);
914
const real_t d_p_to = p_to.distance_to(p_to_closest);
915
if (closest_point_distance > d_p_to) {
916
closest_point = p_to_closest;
917
closest_point_distance = d_p_to;
918
}
919
}
920
}
921
// Finally, check for a case when shortest distance is between some point located on a face's edge and some point located on a line segment.
922
if (!use_collision) {
923
for (uint32_t point_id = 0; point_id < polygon.vertices.size(); point_id += 1) {
924
Vector3 a, b;
925
926
Geometry3D::get_closest_points_between_segments(
927
p_from,
928
p_to,
929
polygon.vertices[point_id],
930
polygon.vertices[(point_id + 1) % polygon.vertices.size()],
931
a,
932
b);
933
934
const real_t d = a.distance_to(b);
935
if (d < closest_point_distance) {
936
closest_point_distance = d;
937
closest_point = b;
938
}
939
}
940
}
941
}
942
}
943
944
return closest_point;
945
}
946
947
Vector3 NavMeshQueries3D::map_iteration_get_closest_point(const NavMapIteration3D &p_map_iteration, const Vector3 &p_point) {
948
ClosestPointQueryResult cp = map_iteration_get_closest_point_info(p_map_iteration, p_point);
949
return cp.point;
950
}
951
952
Vector3 NavMeshQueries3D::map_iteration_get_closest_point_normal(const NavMapIteration3D &p_map_iteration, const Vector3 &p_point) {
953
ClosestPointQueryResult cp = map_iteration_get_closest_point_info(p_map_iteration, p_point);
954
return cp.normal;
955
}
956
957
RID NavMeshQueries3D::map_iteration_get_closest_point_owner(const NavMapIteration3D &p_map_iteration, const Vector3 &p_point) {
958
ClosestPointQueryResult cp = map_iteration_get_closest_point_info(p_map_iteration, p_point);
959
return cp.owner;
960
}
961
962
ClosestPointQueryResult NavMeshQueries3D::map_iteration_get_closest_point_info(const NavMapIteration3D &p_map_iteration, const Vector3 &p_point) {
963
ClosestPointQueryResult result;
964
real_t closest_point_distance_squared = FLT_MAX;
965
966
const LocalVector<Ref<NavRegionIteration3D>> &regions = p_map_iteration.region_iterations;
967
for (const Ref<NavRegionIteration3D> &region : regions) {
968
for (const Polygon &polygon : region->get_navmesh_polygons()) {
969
Vector3 plane_normal = (polygon.vertices[1] - polygon.vertices[0]).cross(polygon.vertices[2] - polygon.vertices[0]);
970
Vector3 closest_on_polygon;
971
real_t closest = FLT_MAX;
972
bool inside = true;
973
Vector3 previous = polygon.vertices[polygon.vertices.size() - 1];
974
for (uint32_t point_id = 0; point_id < polygon.vertices.size(); ++point_id) {
975
Vector3 edge = polygon.vertices[point_id] - previous;
976
Vector3 to_point = p_point - previous;
977
Vector3 edge_to_point_pormal = edge.cross(to_point);
978
bool clockwise = edge_to_point_pormal.dot(plane_normal) > 0;
979
// If we are not clockwise, the point will never be inside the polygon and so the closest point will be on an edge.
980
if (!clockwise) {
981
inside = false;
982
real_t point_projected_on_edge = edge.dot(to_point);
983
real_t edge_square = edge.length_squared();
984
985
if (point_projected_on_edge > edge_square) {
986
real_t distance = polygon.vertices[point_id].distance_squared_to(p_point);
987
if (distance < closest) {
988
closest_on_polygon = polygon.vertices[point_id];
989
closest = distance;
990
}
991
} else if (point_projected_on_edge < 0.f) {
992
real_t distance = previous.distance_squared_to(p_point);
993
if (distance < closest) {
994
closest_on_polygon = previous;
995
closest = distance;
996
}
997
} else {
998
// If we project on this edge, this will be the closest point.
999
real_t percent = point_projected_on_edge / edge_square;
1000
closest_on_polygon = previous + percent * edge;
1001
break;
1002
}
1003
}
1004
previous = polygon.vertices[point_id];
1005
}
1006
1007
if (inside) {
1008
Vector3 plane_normalized = plane_normal.normalized();
1009
real_t distance = plane_normalized.dot(p_point - polygon.vertices[0]);
1010
real_t distance_squared = distance * distance;
1011
if (distance_squared < closest_point_distance_squared) {
1012
closest_point_distance_squared = distance_squared;
1013
result.point = p_point - plane_normalized * distance;
1014
result.normal = plane_normal;
1015
result.owner = polygon.owner->get_self();
1016
1017
if (Math::is_zero_approx(distance)) {
1018
break;
1019
}
1020
}
1021
} else {
1022
real_t distance = closest_on_polygon.distance_squared_to(p_point);
1023
if (distance < closest_point_distance_squared) {
1024
closest_point_distance_squared = distance;
1025
result.point = closest_on_polygon;
1026
result.normal = plane_normal;
1027
result.owner = polygon.owner->get_self();
1028
}
1029
}
1030
}
1031
}
1032
1033
return result;
1034
}
1035
1036
Vector3 NavMeshQueries3D::map_iteration_get_random_point(const NavMapIteration3D &p_map_iteration, uint32_t p_navigation_layers, bool p_uniformly) {
1037
if (p_map_iteration.region_iterations.is_empty()) {
1038
return Vector3();
1039
}
1040
1041
LocalVector<uint32_t> accessible_regions;
1042
accessible_regions.reserve(p_map_iteration.region_iterations.size());
1043
1044
for (uint32_t i = 0; i < p_map_iteration.region_iterations.size(); i++) {
1045
const Ref<NavRegionIteration3D> &region = p_map_iteration.region_iterations[i];
1046
if (!region->get_enabled() || (p_navigation_layers & region->get_navigation_layers()) == 0) {
1047
continue;
1048
}
1049
accessible_regions.push_back(i);
1050
}
1051
1052
if (accessible_regions.is_empty()) {
1053
// All existing region polygons are disabled.
1054
return Vector3();
1055
}
1056
1057
if (p_uniformly) {
1058
real_t accumulated_region_surface_area = 0;
1059
RBMap<real_t, uint32_t> accessible_regions_area_map;
1060
1061
for (uint32_t accessible_region_index = 0; accessible_region_index < accessible_regions.size(); accessible_region_index++) {
1062
const Ref<NavRegionIteration3D> &region = p_map_iteration.region_iterations[accessible_regions[accessible_region_index]];
1063
1064
real_t region_surface_area = region->surface_area;
1065
1066
if (region_surface_area == 0.0f) {
1067
continue;
1068
}
1069
1070
accessible_regions_area_map[accumulated_region_surface_area] = accessible_region_index;
1071
accumulated_region_surface_area += region_surface_area;
1072
}
1073
if (accessible_regions_area_map.is_empty() || accumulated_region_surface_area == 0) {
1074
// All faces have no real surface / no area.
1075
return Vector3();
1076
}
1077
1078
real_t random_accessible_regions_area_map = Math::random(real_t(0), accumulated_region_surface_area);
1079
1080
RBMap<real_t, uint32_t>::Iterator E = accessible_regions_area_map.find_closest(random_accessible_regions_area_map);
1081
ERR_FAIL_COND_V(!E, Vector3());
1082
uint32_t random_region_index = E->value;
1083
ERR_FAIL_UNSIGNED_INDEX_V(random_region_index, accessible_regions.size(), Vector3());
1084
1085
const Ref<NavRegionIteration3D> &random_region = p_map_iteration.region_iterations[accessible_regions[random_region_index]];
1086
1087
return NavMeshQueries3D::polygons_get_random_point(random_region->navmesh_polygons, p_navigation_layers, p_uniformly);
1088
1089
} else {
1090
uint32_t random_region_index = Math::random(int(0), accessible_regions.size() - 1);
1091
1092
const Ref<NavRegionIteration3D> &random_region = p_map_iteration.region_iterations[accessible_regions[random_region_index]];
1093
1094
return NavMeshQueries3D::polygons_get_random_point(random_region->navmesh_polygons, p_navigation_layers, p_uniformly);
1095
}
1096
}
1097
1098
Vector3 NavMeshQueries3D::polygons_get_closest_point_to_segment(const LocalVector<Polygon> &p_polygons, const Vector3 &p_from, const Vector3 &p_to, const bool p_use_collision) {
1099
bool use_collision = p_use_collision;
1100
Vector3 closest_point;
1101
real_t closest_point_distance = FLT_MAX;
1102
1103
for (const Polygon &polygon : p_polygons) {
1104
// For each face check the distance to the segment.
1105
for (uint32_t point_id = 2; point_id < polygon.vertices.size(); point_id += 1) {
1106
const Face3 face(polygon.vertices[0], polygon.vertices[point_id - 1], polygon.vertices[point_id]);
1107
Vector3 intersection_point;
1108
if (face.intersects_segment(p_from, p_to, &intersection_point)) {
1109
const real_t d = p_from.distance_to(intersection_point);
1110
if (!use_collision) {
1111
closest_point = intersection_point;
1112
use_collision = true;
1113
closest_point_distance = d;
1114
} else if (closest_point_distance > d) {
1115
closest_point = intersection_point;
1116
closest_point_distance = d;
1117
}
1118
}
1119
// If segment does not itersect face, check the distance from segment's endpoints.
1120
else if (!use_collision) {
1121
const Vector3 p_from_closest = face.get_closest_point_to(p_from);
1122
const real_t d_p_from = p_from.distance_to(p_from_closest);
1123
if (closest_point_distance > d_p_from) {
1124
closest_point = p_from_closest;
1125
closest_point_distance = d_p_from;
1126
}
1127
1128
const Vector3 p_to_closest = face.get_closest_point_to(p_to);
1129
const real_t d_p_to = p_to.distance_to(p_to_closest);
1130
if (closest_point_distance > d_p_to) {
1131
closest_point = p_to_closest;
1132
closest_point_distance = d_p_to;
1133
}
1134
}
1135
}
1136
// Finally, check for a case when shortest distance is between some point located on a face's edge and some point located on a line segment.
1137
if (!use_collision) {
1138
for (uint32_t point_id = 0; point_id < polygon.vertices.size(); point_id += 1) {
1139
Vector3 a, b;
1140
1141
Geometry3D::get_closest_points_between_segments(
1142
p_from,
1143
p_to,
1144
polygon.vertices[point_id],
1145
polygon.vertices[(point_id + 1) % polygon.vertices.size()],
1146
a,
1147
b);
1148
1149
const real_t d = a.distance_to(b);
1150
if (d < closest_point_distance) {
1151
closest_point_distance = d;
1152
closest_point = b;
1153
}
1154
}
1155
}
1156
}
1157
1158
return closest_point;
1159
}
1160
1161
Vector3 NavMeshQueries3D::polygons_get_closest_point(const LocalVector<Polygon> &p_polygons, const Vector3 &p_point) {
1162
ClosestPointQueryResult cp = polygons_get_closest_point_info(p_polygons, p_point);
1163
return cp.point;
1164
}
1165
1166
Vector3 NavMeshQueries3D::polygons_get_closest_point_normal(const LocalVector<Polygon> &p_polygons, const Vector3 &p_point) {
1167
ClosestPointQueryResult cp = polygons_get_closest_point_info(p_polygons, p_point);
1168
return cp.normal;
1169
}
1170
1171
ClosestPointQueryResult NavMeshQueries3D::polygons_get_closest_point_info(const LocalVector<Polygon> &p_polygons, const Vector3 &p_point) {
1172
ClosestPointQueryResult result;
1173
real_t closest_point_distance_squared = FLT_MAX;
1174
1175
for (const Polygon &polygon : p_polygons) {
1176
Vector3 plane_normal = (polygon.vertices[1] - polygon.vertices[0]).cross(polygon.vertices[2] - polygon.vertices[0]);
1177
Vector3 closest_on_polygon;
1178
real_t closest = FLT_MAX;
1179
bool inside = true;
1180
Vector3 previous = polygon.vertices[polygon.vertices.size() - 1];
1181
for (uint32_t point_id = 0; point_id < polygon.vertices.size(); ++point_id) {
1182
Vector3 edge = polygon.vertices[point_id] - previous;
1183
Vector3 to_point = p_point - previous;
1184
Vector3 edge_to_point_pormal = edge.cross(to_point);
1185
bool clockwise = edge_to_point_pormal.dot(plane_normal) > 0;
1186
// If we are not clockwise, the point will never be inside the polygon and so the closest point will be on an edge.
1187
if (!clockwise) {
1188
inside = false;
1189
real_t point_projected_on_edge = edge.dot(to_point);
1190
real_t edge_square = edge.length_squared();
1191
1192
if (point_projected_on_edge > edge_square) {
1193
real_t distance = polygon.vertices[point_id].distance_squared_to(p_point);
1194
if (distance < closest) {
1195
closest_on_polygon = polygon.vertices[point_id];
1196
closest = distance;
1197
}
1198
} else if (point_projected_on_edge < 0.f) {
1199
real_t distance = previous.distance_squared_to(p_point);
1200
if (distance < closest) {
1201
closest_on_polygon = previous;
1202
closest = distance;
1203
}
1204
} else {
1205
// If we project on this edge, this will be the closest point.
1206
real_t percent = point_projected_on_edge / edge_square;
1207
closest_on_polygon = previous + percent * edge;
1208
break;
1209
}
1210
}
1211
previous = polygon.vertices[point_id];
1212
}
1213
1214
if (inside) {
1215
Vector3 plane_normalized = plane_normal.normalized();
1216
real_t distance = plane_normalized.dot(p_point - polygon.vertices[0]);
1217
real_t distance_squared = distance * distance;
1218
if (distance_squared < closest_point_distance_squared) {
1219
closest_point_distance_squared = distance_squared;
1220
result.point = p_point - plane_normalized * distance;
1221
result.normal = plane_normal;
1222
result.owner = polygon.owner->get_self();
1223
1224
if (Math::is_zero_approx(distance)) {
1225
break;
1226
}
1227
}
1228
} else {
1229
real_t distance = closest_on_polygon.distance_squared_to(p_point);
1230
if (distance < closest_point_distance_squared) {
1231
closest_point_distance_squared = distance;
1232
result.point = closest_on_polygon;
1233
result.normal = plane_normal;
1234
result.owner = polygon.owner->get_self();
1235
}
1236
}
1237
}
1238
1239
return result;
1240
}
1241
1242
RID NavMeshQueries3D::polygons_get_closest_point_owner(const LocalVector<Polygon> &p_polygons, const Vector3 &p_point) {
1243
ClosestPointQueryResult cp = polygons_get_closest_point_info(p_polygons, p_point);
1244
return cp.owner;
1245
}
1246
1247
void NavMeshQueries3D::_query_task_clip_path(NavMeshPathQueryTask3D &p_query_task, const NavigationPoly *from_poly, const Vector3 &p_to_point, const NavigationPoly *p_to_poly) {
1248
Vector3 from = p_query_task.path_points[p_query_task.path_points.size() - 1];
1249
const LocalVector<NavigationPoly> &p_navigation_polys = p_query_task.path_query_slot->path_corridor;
1250
const Vector3 p_map_up = p_query_task.map_up;
1251
1252
if (from.is_equal_approx(p_to_point)) {
1253
return;
1254
}
1255
1256
Plane cut_plane;
1257
cut_plane.normal = (from - p_to_point).cross(p_map_up);
1258
if (cut_plane.normal == Vector3()) {
1259
return;
1260
}
1261
cut_plane.normal.normalize();
1262
cut_plane.d = cut_plane.normal.dot(from);
1263
1264
while (from_poly != p_to_poly) {
1265
Vector3 pathway_start = from_poly->back_navigation_edge_pathway_start;
1266
Vector3 pathway_end = from_poly->back_navigation_edge_pathway_end;
1267
1268
ERR_FAIL_COND(from_poly->back_navigation_poly_id == -1);
1269
from_poly = &p_navigation_polys[from_poly->back_navigation_poly_id];
1270
1271
if (!pathway_start.is_equal_approx(pathway_end)) {
1272
Vector3 inters;
1273
if (cut_plane.intersects_segment(pathway_start, pathway_end, &inters)) {
1274
if (!inters.is_equal_approx(p_to_point) && !inters.is_equal_approx(p_query_task.path_points[p_query_task.path_points.size() - 1])) {
1275
_query_task_push_back_point_with_metadata(p_query_task, inters, from_poly->poly);
1276
}
1277
}
1278
}
1279
}
1280
}
1281
1282
bool NavMeshQueries3D::_query_task_is_connection_owner_usable(const NavMeshPathQueryTask3D &p_query_task, const NavBaseIteration3D *p_owner) {
1283
ERR_FAIL_NULL_V(p_owner, false);
1284
1285
bool owner_usable = true;
1286
1287
if (!p_owner->get_enabled()) {
1288
owner_usable = false;
1289
return owner_usable;
1290
}
1291
1292
if ((p_query_task.navigation_layers & p_owner->get_navigation_layers()) == 0) {
1293
// Not usable. No matching bit between task filter bitmask and owner bitmask.
1294
owner_usable = false;
1295
return owner_usable;
1296
}
1297
1298
if (p_query_task.exclude_regions || p_query_task.include_regions) {
1299
switch (p_owner->get_type()) {
1300
case NavigationUtilities::PathSegmentType::PATH_SEGMENT_TYPE_REGION: {
1301
if (p_query_task.exclude_regions && p_query_task.excluded_regions.has(p_owner->get_self())) {
1302
// Not usable. Exclude region filter is active and this region is excluded.
1303
owner_usable = false;
1304
} else if (p_query_task.include_regions && !p_query_task.included_regions.has(p_owner->get_self())) {
1305
// Not usable. Include region filter is active and this region is not included.
1306
owner_usable = false;
1307
}
1308
} break;
1309
case NavigationUtilities::PathSegmentType::PATH_SEGMENT_TYPE_LINK: {
1310
const LocalVector<Polygon> &link_polygons = p_owner->get_navmesh_polygons();
1311
if (link_polygons.size() != 2) {
1312
// Not usable. Whatever this is, it is not a valid connected link.
1313
owner_usable = false;
1314
} else {
1315
const RID link_start_region = link_polygons[0].owner->get_self();
1316
const RID link_end_region = link_polygons[1].owner->get_self();
1317
if (p_query_task.exclude_regions && (p_query_task.excluded_regions.has(link_start_region) || p_query_task.excluded_regions.has(link_end_region))) {
1318
// Not usable. Exclude region filter is active and at least one region of the link is excluded.
1319
owner_usable = false;
1320
}
1321
if (p_query_task.include_regions && (!p_query_task.included_regions.has(link_start_region) || !p_query_task.excluded_regions.has(link_end_region))) {
1322
// Not usable. Include region filter is active and not both regions of the links are included.
1323
owner_usable = false;
1324
}
1325
}
1326
} break;
1327
}
1328
}
1329
1330
return owner_usable;
1331
}
1332
1333
LocalVector<uint32_t> NavMeshQueries3D::get_simplified_path_indices(const LocalVector<Vector3> &p_path, real_t p_epsilon) {
1334
p_epsilon = MAX(0.0, p_epsilon);
1335
real_t squared_epsilon = p_epsilon * p_epsilon;
1336
1337
LocalVector<uint32_t> simplified_path_indices;
1338
simplified_path_indices.reserve(p_path.size());
1339
simplified_path_indices.push_back(0);
1340
simplify_path_segment(0, p_path.size() - 1, p_path, squared_epsilon, simplified_path_indices);
1341
simplified_path_indices.push_back(p_path.size() - 1);
1342
1343
return simplified_path_indices;
1344
}
1345
1346
void NavMeshQueries3D::simplify_path_segment(int p_start_inx, int p_end_inx, const LocalVector<Vector3> &p_points, real_t p_epsilon, LocalVector<uint32_t> &r_simplified_path_indices) {
1347
const Vector3 path_segment_a = p_points[p_start_inx];
1348
const Vector3 path_segment_b = p_points[p_end_inx];
1349
1350
real_t point_max_distance = 0.0;
1351
int point_max_index = 0;
1352
1353
for (int i = p_start_inx; i < p_end_inx; i++) {
1354
const Vector3 &checked_point = p_points[i];
1355
1356
const Vector3 closest_point = Geometry3D::get_closest_point_to_segment(checked_point, path_segment_a, path_segment_b);
1357
real_t distance_squared = closest_point.distance_squared_to(checked_point);
1358
1359
if (distance_squared > point_max_distance) {
1360
point_max_index = i;
1361
point_max_distance = distance_squared;
1362
}
1363
}
1364
1365
if (point_max_distance > p_epsilon) {
1366
simplify_path_segment(p_start_inx, point_max_index, p_points, p_epsilon, r_simplified_path_indices);
1367
r_simplified_path_indices.push_back(point_max_index);
1368
simplify_path_segment(point_max_index, p_end_inx, p_points, p_epsilon, r_simplified_path_indices);
1369
}
1370
}
1371
1372