Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
godotengine
GitHub Repository: godotengine/godot
Path: blob/master/modules/navigation_2d/2d/nav_map_builder_2d.cpp
10278 views
1
/**************************************************************************/
2
/* nav_map_builder_2d.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_map_builder_2d.h"
32
33
#include "../nav_link_2d.h"
34
#include "../nav_map_2d.h"
35
#include "../nav_region_2d.h"
36
#include "../triangle2.h"
37
#include "nav_map_iteration_2d.h"
38
#include "nav_region_iteration_2d.h"
39
40
using namespace Nav2D;
41
42
PointKey NavMapBuilder2D::get_point_key(const Vector2 &p_pos, const Vector2 &p_cell_size) {
43
const int x = static_cast<int>(Math::floor(p_pos.x / p_cell_size.x));
44
const int y = static_cast<int>(Math::floor(p_pos.y / p_cell_size.y));
45
46
PointKey p;
47
p.key = 0;
48
p.x = x;
49
p.y = y;
50
return p;
51
}
52
53
void NavMapBuilder2D::build_navmap_iteration(NavMapIterationBuild2D &r_build) {
54
PerformanceData &performance_data = r_build.performance_data;
55
56
performance_data.pm_polygon_count = 0;
57
performance_data.pm_edge_count = 0;
58
performance_data.pm_edge_merge_count = 0;
59
performance_data.pm_edge_connection_count = 0;
60
performance_data.pm_edge_free_count = 0;
61
62
_build_step_gather_region_polygons(r_build);
63
64
_build_step_find_edge_connection_pairs(r_build);
65
66
_build_step_merge_edge_connection_pairs(r_build);
67
68
_build_step_edge_connection_margin_connections(r_build);
69
70
_build_step_navlink_connections(r_build);
71
72
_build_update_map_iteration(r_build);
73
}
74
75
void NavMapBuilder2D::_build_step_gather_region_polygons(NavMapIterationBuild2D &r_build) {
76
PerformanceData &performance_data = r_build.performance_data;
77
NavMapIteration2D *map_iteration = r_build.map_iteration;
78
79
const LocalVector<Ref<NavRegionIteration2D>> &regions = map_iteration->region_iterations;
80
HashMap<const NavBaseIteration2D *, LocalVector<Connection>> &region_external_connections = map_iteration->external_region_connections;
81
82
map_iteration->navbases_polygons_external_connections.clear();
83
84
// Remove regions connections.
85
region_external_connections.clear();
86
87
// Copy all region polygons in the map.
88
int polygon_count = 0;
89
for (const Ref<NavRegionIteration2D> &region : regions) {
90
const uint32_t polygons_size = region->navmesh_polygons.size();
91
polygon_count += polygons_size;
92
93
region_external_connections[region.ptr()] = LocalVector<Connection>();
94
map_iteration->navbases_polygons_external_connections[region.ptr()] = LocalVector<LocalVector<Connection>>();
95
map_iteration->navbases_polygons_external_connections[region.ptr()].resize(polygons_size);
96
}
97
98
performance_data.pm_polygon_count = polygon_count;
99
r_build.polygon_count = polygon_count;
100
}
101
102
void NavMapBuilder2D::_build_step_find_edge_connection_pairs(NavMapIterationBuild2D &r_build) {
103
PerformanceData &performance_data = r_build.performance_data;
104
NavMapIteration2D *map_iteration = r_build.map_iteration;
105
int polygon_count = r_build.polygon_count;
106
107
HashMap<EdgeKey, EdgeConnectionPair, EdgeKey> &connection_pairs_map = r_build.iter_connection_pairs_map;
108
109
// Group all edges per key.
110
connection_pairs_map.clear();
111
connection_pairs_map.reserve(polygon_count);
112
int free_edges_count = 0; // How many ConnectionPairs have only one Connection.
113
114
for (const Ref<NavRegionIteration2D> &region : map_iteration->region_iterations) {
115
for (const ConnectableEdge &connectable_edge : region->get_external_edges()) {
116
const EdgeKey &ek = connectable_edge.ek;
117
118
HashMap<EdgeKey, EdgeConnectionPair, EdgeKey>::Iterator pair_it = connection_pairs_map.find(ek);
119
if (!pair_it) {
120
pair_it = connection_pairs_map.insert(ek, EdgeConnectionPair());
121
performance_data.pm_edge_count += 1;
122
++free_edges_count;
123
}
124
EdgeConnectionPair &pair = pair_it->value;
125
if (pair.size < 2) {
126
// Add the polygon/edge tuple to this key.
127
Connection new_connection;
128
new_connection.polygon = &region->navmesh_polygons[connectable_edge.polygon_index];
129
new_connection.edge = connectable_edge.edge;
130
new_connection.pathway_start = connectable_edge.pathway_start;
131
new_connection.pathway_end = connectable_edge.pathway_end;
132
133
pair.connections[pair.size] = new_connection;
134
++pair.size;
135
if (pair.size == 2) {
136
--free_edges_count;
137
}
138
139
} else {
140
// The edge is already connected with another edge, skip.
141
ERR_PRINT_ONCE("Navigation map synchronization error. Attempted to merge a navigation mesh polygon edge with another already-merged edge. This is usually caused by crossing edges, overlapping polygons, or a mismatch of the NavigationMesh / NavigationPolygon baked 'cell_size' and navigation map 'cell_size'. If you're certain none of above is the case, change 'navigation/2d/merge_rasterizer_cell_scale' to 0.001.");
142
}
143
}
144
}
145
146
r_build.free_edge_count = free_edges_count;
147
}
148
149
void NavMapBuilder2D::_build_step_merge_edge_connection_pairs(NavMapIterationBuild2D &r_build) {
150
PerformanceData &performance_data = r_build.performance_data;
151
152
HashMap<EdgeKey, EdgeConnectionPair, EdgeKey> &connection_pairs_map = r_build.iter_connection_pairs_map;
153
LocalVector<Connection> &free_edges = r_build.iter_free_edges;
154
int free_edges_count = r_build.free_edge_count;
155
bool use_edge_connections = r_build.use_edge_connections;
156
157
free_edges.clear();
158
free_edges.reserve(free_edges_count);
159
160
NavMapIteration2D *map_iteration = r_build.map_iteration;
161
162
HashMap<const NavBaseIteration2D *, LocalVector<LocalVector<Nav2D::Connection>>> &navbases_polygons_external_connections = map_iteration->navbases_polygons_external_connections;
163
164
for (const KeyValue<EdgeKey, EdgeConnectionPair> &pair_it : connection_pairs_map) {
165
const EdgeConnectionPair &pair = pair_it.value;
166
if (pair.size == 2) {
167
// Connect edge that are shared in different polygons.
168
const Connection &c1 = pair.connections[0];
169
const Connection &c2 = pair.connections[1];
170
171
navbases_polygons_external_connections[c1.polygon->owner][c1.polygon->id].push_back(c2);
172
navbases_polygons_external_connections[c2.polygon->owner][c2.polygon->id].push_back(c1);
173
performance_data.pm_edge_connection_count += 1;
174
175
} else {
176
CRASH_COND_MSG(pair.size != 1, vformat("Number of connection != 1. Found: %d", pair.size));
177
if (use_edge_connections && pair.connections[0].polygon->owner->get_use_edge_connections()) {
178
free_edges.push_back(pair.connections[0]);
179
}
180
}
181
}
182
}
183
184
void NavMapBuilder2D::_build_step_edge_connection_margin_connections(NavMapIterationBuild2D &r_build) {
185
PerformanceData &performance_data = r_build.performance_data;
186
NavMapIteration2D *map_iteration = r_build.map_iteration;
187
188
real_t edge_connection_margin = r_build.edge_connection_margin;
189
190
LocalVector<Connection> &free_edges = r_build.iter_free_edges;
191
HashMap<const NavBaseIteration2D *, LocalVector<Connection>> &region_external_connections = map_iteration->external_region_connections;
192
193
HashMap<const NavBaseIteration2D *, LocalVector<LocalVector<Nav2D::Connection>>> &navbases_polygons_external_connections = map_iteration->navbases_polygons_external_connections;
194
195
// Find the compatible near edges.
196
//
197
// Note:
198
// Considering that the edges must be compatible (for obvious reasons)
199
// to be connected, create new polygons to remove that small gap is
200
// not really useful and would result in wasteful computation during
201
// connection, integration and path finding.
202
performance_data.pm_edge_free_count = free_edges.size();
203
204
const real_t edge_connection_margin_squared = edge_connection_margin * edge_connection_margin;
205
206
for (uint32_t i = 0; i < free_edges.size(); i++) {
207
const Connection &free_edge = free_edges[i];
208
const Vector2 &edge_p1 = free_edge.pathway_start;
209
const Vector2 &edge_p2 = free_edge.pathway_end;
210
211
for (uint32_t j = 0; j < free_edges.size(); j++) {
212
const Connection &other_edge = free_edges[j];
213
if (i == j || free_edge.polygon->owner == other_edge.polygon->owner) {
214
continue;
215
}
216
217
const Vector2 &other_edge_p1 = other_edge.pathway_start;
218
const Vector2 &other_edge_p2 = other_edge.pathway_end;
219
220
// Compute the projection of the opposite edge on the current one
221
Vector2 edge_vector = edge_p2 - edge_p1;
222
real_t projected_p1_ratio = edge_vector.dot(other_edge_p1 - edge_p1) / (edge_vector.length_squared());
223
real_t projected_p2_ratio = edge_vector.dot(other_edge_p2 - edge_p1) / (edge_vector.length_squared());
224
if ((projected_p1_ratio < 0.0 && projected_p2_ratio < 0.0) || (projected_p1_ratio > 1.0 && projected_p2_ratio > 1.0)) {
225
continue;
226
}
227
228
// Check if the two edges are close to each other enough and compute a pathway between the two regions.
229
Vector2 self1 = edge_vector * CLAMP(projected_p1_ratio, 0.0, 1.0) + edge_p1;
230
Vector2 other1;
231
if (projected_p1_ratio >= 0.0 && projected_p1_ratio <= 1.0) {
232
other1 = other_edge_p1;
233
} else {
234
other1 = other_edge_p1.lerp(other_edge_p2, (1.0 - projected_p1_ratio) / (projected_p2_ratio - projected_p1_ratio));
235
}
236
if (other1.distance_squared_to(self1) > edge_connection_margin_squared) {
237
continue;
238
}
239
240
Vector2 self2 = edge_vector * CLAMP(projected_p2_ratio, 0.0, 1.0) + edge_p1;
241
Vector2 other2;
242
if (projected_p2_ratio >= 0.0 && projected_p2_ratio <= 1.0) {
243
other2 = other_edge_p2;
244
} else {
245
other2 = other_edge_p1.lerp(other_edge_p2, (0.0 - projected_p1_ratio) / (projected_p2_ratio - projected_p1_ratio));
246
}
247
if (other2.distance_squared_to(self2) > edge_connection_margin_squared) {
248
continue;
249
}
250
251
// The edges can now be connected.
252
Connection new_connection = other_edge;
253
new_connection.pathway_start = (self1 + other1) / 2.0;
254
new_connection.pathway_end = (self2 + other2) / 2.0;
255
//free_edge.polygon->connections.push_back(new_connection);
256
257
// Add the connection to the region_connection map.
258
region_external_connections[free_edge.polygon->owner].push_back(new_connection);
259
navbases_polygons_external_connections[free_edge.polygon->owner][free_edge.polygon->id].push_back(new_connection);
260
performance_data.pm_edge_connection_count += 1;
261
}
262
}
263
}
264
265
void NavMapBuilder2D::_build_step_navlink_connections(NavMapIterationBuild2D &r_build) {
266
NavMapIteration2D *map_iteration = r_build.map_iteration;
267
268
real_t link_connection_radius = r_build.link_connection_radius;
269
270
const LocalVector<Ref<NavLinkIteration2D>> &links = map_iteration->link_iterations;
271
272
int polygon_count = r_build.polygon_count;
273
274
real_t link_connection_radius_sqr = link_connection_radius * link_connection_radius;
275
276
HashMap<const NavBaseIteration2D *, LocalVector<LocalVector<Nav2D::Connection>>> &navbases_polygons_external_connections = map_iteration->navbases_polygons_external_connections;
277
LocalVector<Nav2D::Polygon> &navlink_polygons = map_iteration->navlink_polygons;
278
navlink_polygons.clear();
279
navlink_polygons.resize(links.size());
280
uint32_t navlink_index = 0;
281
282
// Search for polygons within range of a nav link.
283
for (const Ref<NavLinkIteration2D> &link : links) {
284
polygon_count++;
285
Polygon &new_polygon = navlink_polygons[navlink_index++];
286
287
new_polygon.id = 0;
288
new_polygon.owner = link.ptr();
289
290
const Vector2 link_start_pos = link->get_start_position();
291
const Vector2 link_end_pos = link->get_end_position();
292
293
Polygon *closest_start_polygon = nullptr;
294
real_t closest_start_sqr_dist = link_connection_radius_sqr;
295
Vector2 closest_start_point;
296
297
Polygon *closest_end_polygon = nullptr;
298
real_t closest_end_sqr_dist = link_connection_radius_sqr;
299
Vector2 closest_end_point;
300
301
for (const Ref<NavRegionIteration2D> &region : map_iteration->region_iterations) {
302
Rect2 region_bounds = region->get_bounds().grow(link_connection_radius);
303
if (!region_bounds.has_point(link_start_pos) && !region_bounds.has_point(link_end_pos)) {
304
continue;
305
}
306
307
for (Polygon &polyon : region->navmesh_polygons) {
308
for (uint32_t point_id = 2; point_id < polyon.vertices.size(); point_id += 1) {
309
const Triangle2 triangle(polyon.vertices[0], polyon.vertices[point_id - 1], polyon.vertices[point_id]);
310
311
{
312
const Vector2 start_point = triangle.get_closest_point_to(link_start_pos);
313
const real_t sqr_dist = start_point.distance_squared_to(link_start_pos);
314
315
// Pick the polygon that is within our radius and is closer than anything we've seen yet.
316
if (sqr_dist < closest_start_sqr_dist) {
317
closest_start_sqr_dist = sqr_dist;
318
closest_start_point = start_point;
319
closest_start_polygon = &polyon;
320
}
321
}
322
323
{
324
const Vector2 end_point = triangle.get_closest_point_to(link_end_pos);
325
const real_t sqr_dist = end_point.distance_squared_to(link_end_pos);
326
327
// Pick the polygon that is within our radius and is closer than anything we've seen yet.
328
if (sqr_dist < closest_end_sqr_dist) {
329
closest_end_sqr_dist = sqr_dist;
330
closest_end_point = end_point;
331
closest_end_polygon = &polyon;
332
}
333
}
334
}
335
}
336
}
337
338
// If we have both a start and end point, then create a synthetic polygon to route through.
339
if (closest_start_polygon && closest_end_polygon) {
340
new_polygon.vertices.resize(4);
341
342
// Build a set of vertices that create a thin polygon going from the start to the end point.
343
new_polygon.vertices[0] = closest_start_point;
344
new_polygon.vertices[1] = closest_start_point;
345
new_polygon.vertices[2] = closest_end_point;
346
new_polygon.vertices[3] = closest_end_point;
347
348
// Setup connections to go forward in the link.
349
{
350
Connection entry_connection;
351
entry_connection.polygon = &new_polygon;
352
entry_connection.edge = -1;
353
entry_connection.pathway_start = new_polygon.vertices[0];
354
entry_connection.pathway_end = new_polygon.vertices[1];
355
navbases_polygons_external_connections[closest_start_polygon->owner][closest_start_polygon->id].push_back(entry_connection);
356
357
Connection exit_connection;
358
exit_connection.polygon = closest_end_polygon;
359
exit_connection.edge = -1;
360
exit_connection.pathway_start = new_polygon.vertices[2];
361
exit_connection.pathway_end = new_polygon.vertices[3];
362
navbases_polygons_external_connections[link.ptr()].push_back(LocalVector<Nav2D::Connection>());
363
navbases_polygons_external_connections[link.ptr()][new_polygon.id].push_back(exit_connection);
364
}
365
366
// If the link is bi-directional, create connections from the end to the start.
367
if (link->is_bidirectional()) {
368
Connection entry_connection;
369
entry_connection.polygon = &new_polygon;
370
entry_connection.edge = -1;
371
entry_connection.pathway_start = new_polygon.vertices[2];
372
entry_connection.pathway_end = new_polygon.vertices[3];
373
navbases_polygons_external_connections[closest_end_polygon->owner][closest_end_polygon->id].push_back(entry_connection);
374
375
Connection exit_connection;
376
exit_connection.polygon = closest_start_polygon;
377
exit_connection.edge = -1;
378
exit_connection.pathway_start = new_polygon.vertices[0];
379
exit_connection.pathway_end = new_polygon.vertices[1];
380
navbases_polygons_external_connections[link.ptr()].push_back(LocalVector<Nav2D::Connection>());
381
navbases_polygons_external_connections[link.ptr()][new_polygon.id].push_back(exit_connection);
382
}
383
}
384
}
385
386
r_build.polygon_count = polygon_count;
387
}
388
389
void NavMapBuilder2D::_build_update_map_iteration(NavMapIterationBuild2D &r_build) {
390
NavMapIteration2D *map_iteration = r_build.map_iteration;
391
392
map_iteration->navmesh_polygon_count = r_build.polygon_count;
393
394
uint32_t navmesh_polygon_count = r_build.polygon_count;
395
uint32_t total_polygon_count = navmesh_polygon_count;
396
397
map_iteration->path_query_slots_mutex.lock();
398
for (NavMeshQueries2D::PathQuerySlot &p_path_query_slot : map_iteration->path_query_slots) {
399
p_path_query_slot.traversable_polys.clear();
400
p_path_query_slot.traversable_polys.reserve(navmesh_polygon_count * 0.25);
401
p_path_query_slot.path_corridor.clear();
402
403
p_path_query_slot.path_corridor.resize(total_polygon_count);
404
405
p_path_query_slot.poly_to_id.clear();
406
p_path_query_slot.poly_to_id.reserve(total_polygon_count);
407
408
int polygon_id = 0;
409
for (Ref<NavRegionIteration2D> &region : map_iteration->region_iterations) {
410
for (const Polygon &polygon : region->navmesh_polygons) {
411
p_path_query_slot.poly_to_id[&polygon] = polygon_id;
412
polygon_id++;
413
}
414
}
415
416
for (const Polygon &polygon : map_iteration->navlink_polygons) {
417
p_path_query_slot.poly_to_id[&polygon] = polygon_id;
418
polygon_id++;
419
}
420
421
DEV_ASSERT(p_path_query_slot.path_corridor.size() == p_path_query_slot.poly_to_id.size());
422
}
423
424
map_iteration->path_query_slots_mutex.unlock();
425
}
426
427