CARLA
Loading...
Searching...
No Matches
Navigation.cpp
Go to the documentation of this file.
1// Copyright (c) 2026 Computer Vision Center (CVC) at the Universitat Autonoma
2// de Barcelona (UAB).
3//
4// This work is licensed under the terms of the MIT license.
5// For a copy, see <https://opensource.org/licenses/MIT>.
6
7#define _USE_MATH_DEFINES // to avoid undefined error of M_PI (bug in Visual
8 // Studio 2015 and 2017)
9#include <cmath>
10
11#include "carla/Logging.h"
14#include "carla/geom/Math.h"
15
16#include <algorithm>
17#include <iterator>
18#include <fstream>
19#include <mutex>
20
21namespace carla {
22namespace nav {
23
31
32 // these settings are the same than in RecastBuilder, so if you change the height of the agent,
33 // you should do the same in RecastBuilder
34 static const int MAX_POLYS = 256;
35 static const int MAX_AGENTS = 500;
36 static const int MAX_QUERY_SEARCH_NODES = 2048;
37 static const float AGENT_HEIGHT = 1.8f;
38 static const float AGENT_RADIUS = 0.3f;
39
40 static const float AGENT_UNBLOCK_DISTANCE = 0.5f;
42 static const float AGENT_UNBLOCK_TIME = 4.0f;
43 // Longest simulation time the crowd catches up in one update, and its largest Detour step.
44 static const double MAX_NAV_CATCH_UP = 1.0;
45 static const double MAX_NAV_STEP = 0.1;
46
47 static const float AREA_GRASS_COST = 1.0f;
48 static const float AREA_ROAD_COST = 10.0f;
49
50 // return a random float
51 static float frand() {
52 return static_cast<float>(rand()) / static_cast<float>(RAND_MAX);
53 }
54
56 // assign walker manager
58 }
59
61 _ready = false;
62 _time_to_unblock = 0.0f;
63 _mapped_walkers_id.clear();
64 _mapped_vehicles_id.clear();
65 _mapped_by_index.clear();
67 _yaw_walkers.clear();
68 _binary_mesh.clear();
69 dtFreeCrowd(_crowd);
70 dtFreeNavMeshQuery(_nav_query);
71 dtFreeNavMesh(_nav_mesh);
72 }
73
74 // reference to the simulator to access API functions
75 void Navigation::SetSimulator(std::weak_ptr<carla::client::detail::Simulator> simulator)
76 {
77 _simulator = simulator;
79 }
80
81 // set the seed to use with random numbers
82 void Navigation::SetSeed(unsigned int seed) {
83 srand(seed);
84 }
85
86 // load navigation data
87 bool Navigation::Load(const std::string &filename) {
88 std::ifstream f;
89 std::istream_iterator<uint8_t> start(f), end;
90
91 // read the whole file
92 f.open(filename, std::ios::binary);
93 if (!f.is_open()) {
94 return false;
95 }
96 std::vector<uint8_t> content(start, end);
97 f.close();
98
99 // parse the content
100 return Load(std::move(content));
101 }
102
103 // load navigation data from memory
104 bool Navigation::Load(std::vector<uint8_t> content) {
105 const int NAVMESHSET_MAGIC = 'M' << 24 | 'S' << 16 | 'E' << 8 | 'T'; // 'MSET';
106 const int NAVMESHSET_VERSION = 1;
107#pragma pack(push, 1)
108
109 struct NavMeshSetHeader {
110 int magic;
111 int version;
112 int num_tiles;
113 dtNavMeshParams params;
114 } header;
115 struct NavMeshTileHeader {
116 dtTileRef tile_ref;
117 int data_size;
118 };
119#pragma pack(pop)
120
121 // check size for header
122 if (content.size() < sizeof(header)) {
123 logging::log("Nav: failed loading binary");
124 return false;
125 }
126
127 // read the file header
128 unsigned long pos = 0;
129 memcpy(&header, &content[pos], sizeof(header));
130 pos += sizeof(header);
131
132 // check file magic and version
133 if (header.magic != NAVMESHSET_MAGIC || header.version != NAVMESHSET_VERSION) {
134 return false;
135 }
136
137 // allocate object
138 dtNavMesh *mesh = dtAllocNavMesh();
139 if (!mesh) {
140 return false;
141 }
142
143 // set number of tiles and origin
144 dtStatus status = mesh->init(&header.params);
145 if (dtStatusFailed(status)) {
146 return false;
147 }
148
149 // read the tiles data
150 for (int i = 0; i < header.num_tiles; ++i) {
151 NavMeshTileHeader tile_header;
152
153 // read the tile header
154 memcpy(&tile_header, &content[pos], sizeof(tile_header));
155 pos += sizeof(tile_header);
156 if (pos >= content.size()) {
157 dtFreeNavMesh(mesh);
158 return false;
159 }
160
161 // check for valid tile
162 if (!tile_header.tile_ref || !tile_header.data_size) {
163 break;
164 }
165
166 // allocate the buffer
167 char *data = static_cast<char *>(dtAlloc(static_cast<size_t>(tile_header.data_size), DT_ALLOC_PERM));
168 if (!data) {
169 break;
170 }
171
172 // read the tile
173 memcpy(data, &content[pos], static_cast<size_t>(tile_header.data_size));
174 pos += static_cast<unsigned long>(tile_header.data_size);
175 if (pos > content.size()) {
176 dtFree(data);
177 dtFreeNavMesh(mesh);
178 return false;
179 }
180
181 // add the tile data
182 mesh->addTile(reinterpret_cast<unsigned char *>(data), tile_header.data_size, DT_TILE_FREE_DATA,
183 tile_header.tile_ref, 0);
184 }
185
186 // exchange
187 dtFreeNavMesh(_nav_mesh);
188 _nav_mesh = mesh;
189
190 // prepare the query object
191 dtFreeNavMeshQuery(_nav_query);
192 _nav_query = dtAllocNavMeshQuery();
194
195 // copy
196 _binary_mesh = std::move(content);
197 _ready = true;
198
199 // create and init the crowd manager
200 CreateCrowd();
201
202 return true;
203 }
204
206
207 // check if all is ready
208 if (!_ready) {
209 return;
210 }
211
212 DEBUG_ASSERT(_crowd == nullptr);
213
214 // create and init
215 _crowd = dtAllocCrowd();
216 // these radius should be the maximum size of the vehicles (CarlaCola for Carla)
217 const float max_agent_radius = AGENT_RADIUS * 20;
218 if (!_crowd->init(MAX_AGENTS, max_agent_radius, _nav_mesh)) {
219 logging::log("Nav: failed to create crowd");
220 return;
221 }
222
223 // set different filters
224 // filter 0 can not walk on roads
225 _crowd->getEditableFilter(0)->setIncludeFlags(CARLA_TYPE_WALKABLE);
226 _crowd->getEditableFilter(0)->setExcludeFlags(CARLA_TYPE_ROAD);
227 _crowd->getEditableFilter(0)->setAreaCost(CARLA_AREA_ROAD, AREA_ROAD_COST);
228 _crowd->getEditableFilter(0)->setAreaCost(CARLA_AREA_GRASS, AREA_GRASS_COST);
229 // filter 1 can walk on roads
230 _crowd->getEditableFilter(1)->setIncludeFlags(CARLA_TYPE_WALKABLE);
231 _crowd->getEditableFilter(1)->setExcludeFlags(CARLA_TYPE_NONE);
232 _crowd->getEditableFilter(1)->setAreaCost(CARLA_AREA_ROAD, AREA_ROAD_COST);
233 _crowd->getEditableFilter(1)->setAreaCost(CARLA_AREA_GRASS, AREA_GRASS_COST);
234
235 // Setup local avoidance params to different qualities.
236 dtObstacleAvoidanceParams params;
237 // Use mostly default settings, copy from dtCrowd.
238 memcpy(&params, _crowd->getObstacleAvoidanceParams(0), sizeof(dtObstacleAvoidanceParams));
239
240 // Low (11)
241 params.velBias = 0.5f;
242 params.adaptiveDivs = 5;
243 params.adaptiveRings = 2;
244 params.adaptiveDepth = 1;
245 _crowd->setObstacleAvoidanceParams(0, &params);
246
247 // Medium (22)
248 params.velBias = 0.5f;
249 params.adaptiveDivs = 5;
250 params.adaptiveRings = 2;
251 params.adaptiveDepth = 2;
252 _crowd->setObstacleAvoidanceParams(1, &params);
253
254 // Good (45)
255 params.velBias = 0.5f;
256 params.adaptiveDivs = 7;
257 params.adaptiveRings = 2;
258 params.adaptiveDepth = 3;
259 _crowd->setObstacleAvoidanceParams(2, &params);
260
261 // High (66)
262 params.velBias = 0.5f;
263 params.adaptiveDivs = 7;
264 params.adaptiveRings = 3;
265 params.adaptiveDepth = 3;
266
267 _crowd->setObstacleAvoidanceParams(3, &params);
268 }
269
270 // return the path points to go from one position to another
273 dtQueryFilter * filter,
274 std::vector<carla::geom::Location> &path,
275 std::vector<unsigned char> &area) {
276 // path found
277 float straight_path[MAX_POLYS * 3];
278 unsigned char straight_path_flags[MAX_POLYS];
279 dtPolyRef straight_path_polys[MAX_POLYS];
280 int num_straight_path;
281 int straight_path_options = DT_STRAIGHTPATH_AREA_CROSSINGS;
282
283 // polys in path
284 dtPolyRef polys[MAX_POLYS];
285 int num_polys;
286
287 // check if all is ready
288 if (!_ready) {
289 return false;
290 }
291
292 DEBUG_ASSERT(_nav_query != nullptr);
293
294 // point extension
295 float poly_pick_ext[3];
296 poly_pick_ext[0] = 2;
297 poly_pick_ext[1] = 4;
298 poly_pick_ext[2] = 2;
299
300 // filter
301 dtQueryFilter filter2;
302 if (filter == nullptr) {
303 filter2.setAreaCost(CARLA_AREA_ROAD, AREA_ROAD_COST);
304 filter2.setAreaCost(CARLA_AREA_GRASS, AREA_GRASS_COST);
305 filter2.setIncludeFlags(CARLA_TYPE_WALKABLE);
306 filter2.setExcludeFlags(CARLA_TYPE_NONE);
307 filter = &filter2;
308 }
309
310 // set the points
311 dtPolyRef start_ref = 0;
312 dtPolyRef end_ref = 0;
313 float start_pos[3] = { from.x, from.z, from.y };
314 float end_pos[3] = { to.x, to.z, to.y };
315 {
316 // critical section, force single thread running this
317 std::scoped_lock<std::mutex> lock(_mutex);
318 _nav_query->findNearestPoly(start_pos, poly_pick_ext, filter, &start_ref, 0);
319 _nav_query->findNearestPoly(end_pos, poly_pick_ext, filter, &end_ref, 0);
320 }
321 if (!start_ref || !end_ref) {
322 return false;
323 }
324
325 {
326 // critical section, force single thread running this
327 std::scoped_lock<std::mutex> lock(_mutex);
328 // get the path of nodes
329 _nav_query->findPath(start_ref, end_ref, start_pos, end_pos, filter, polys, &num_polys, MAX_POLYS);
330 }
331
332 // get the path of points
333 num_straight_path = 0;
334 if (num_polys == 0) {
335 return false;
336 }
337
338 // in case of partial path, make sure the end point is clamped to the last
339 // polygon
340 float end_pos2[3];
341 dtVcopy(end_pos2, end_pos);
342 if (polys[num_polys - 1] != end_ref) {
343 // critical section, force single thread running this
344 std::scoped_lock<std::mutex> lock(_mutex);
345 _nav_query->closestPointOnPoly(polys[num_polys - 1], end_pos, end_pos2, 0);
346 }
347
348 // get the points
349 {
350 // critical section, force single thread running this
351 std::scoped_lock<std::mutex> lock(_mutex);
352 _nav_query->findStraightPath(start_pos, end_pos2, polys, num_polys,
353 straight_path, straight_path_flags,
354 straight_path_polys, &num_straight_path, MAX_POLYS, straight_path_options);
355 }
356
357 // copy the path to the output buffer
358 path.clear();
359 path.reserve(static_cast<unsigned long>(num_straight_path));
360 unsigned char area_type;
361 for (int i = 0, j = 0; j < num_straight_path; i += 3, ++j) {
362 // save coordinate for Unreal axis (x, z, y)
363 path.emplace_back(straight_path[i], straight_path[i + 2], straight_path[i + 1]);
364 // save area type
365 {
366 // critical section, force single thread running this
367 std::scoped_lock<std::mutex> lock(_mutex);
368 _nav_mesh->getPolyArea(straight_path_polys[j], &area_type);
369 }
370 area.emplace_back(area_type);
371 }
372
373 return true;
374 }
375
377 std::vector<carla::geom::Location> &path, std::vector<unsigned char> &area) {
378 // path found
379 float straight_path[MAX_POLYS * 3];
380 unsigned char straight_path_flags[MAX_POLYS];
381 dtPolyRef straight_path_polys[MAX_POLYS];
382 int num_straight_path = 0;
383 int straight_path_options = DT_STRAIGHTPATH_AREA_CROSSINGS;
384
385 // polys in path
386 dtPolyRef polys[MAX_POLYS];
387 int num_polys;
388
389 // check if all is ready
390 if (!_ready) {
391 return false;
392 }
393
394 DEBUG_ASSERT(_nav_query != nullptr);
395
396 // point extension
397 float poly_pick_ext[3] = {2,4,2};
398
399 // get current filter from agent
400 auto it = _mapped_walkers_id.find(id);
401 if (it == _mapped_walkers_id.end())
402 return false;
403
404 const dtQueryFilter *filter;
405 {
406 // critical section, force single thread running this
407 std::scoped_lock<std::mutex> lock(_mutex);
408 filter = _crowd->getFilter(_crowd->getAgent(it->second)->params.queryFilterType);
409 }
410
411 // set the points
412 dtPolyRef start_ref = 0;
413 dtPolyRef end_ref = 0;
414 float start_pos[3] = { from.x, from.z, from.y };
415 float end_pos[3] = { to.x, to.z, to.y };
416 {
417 // critical section, force single thread running this
418 std::scoped_lock<std::mutex> lock(_mutex);
419 _nav_query->findNearestPoly(start_pos, poly_pick_ext, filter, &start_ref, 0);
420 _nav_query->findNearestPoly(end_pos, poly_pick_ext, filter, &end_ref, 0);
421 }
422 if (!start_ref || !end_ref) {
423 return false;
424 }
425
426 // get the path of nodes
427 {
428 // critical section, force single thread running this
429 std::scoped_lock<std::mutex> lock(_mutex);
430 _nav_query->findPath(start_ref, end_ref, start_pos, end_pos, filter, polys, &num_polys, MAX_POLYS);
431 }
432
433 // get the path of points
434 if (num_polys == 0) {
435 return false;
436 }
437
438 // in case of partial path, make sure the end point is clamped to the last
439 // polygon
440 float end_pos2[3];
441 dtVcopy(end_pos2, end_pos);
442 if (polys[num_polys - 1] != end_ref) {
443 // critical section, force single thread running this
444 std::scoped_lock<std::mutex> lock(_mutex);
445 _nav_query->closestPointOnPoly(polys[num_polys - 1], end_pos, end_pos2, 0);
446 }
447
448 // get the points
449 {
450 // critical section, force single thread running this
451 std::scoped_lock<std::mutex> lock(_mutex);
452 _nav_query->findStraightPath(start_pos, end_pos2, polys, num_polys,
453 straight_path, straight_path_flags,
454 straight_path_polys, &num_straight_path, MAX_POLYS, straight_path_options);
455 }
456
457 // copy the path to the output buffer
458 path.clear();
459 path.reserve(static_cast<unsigned long>(num_straight_path));
460 unsigned char area_type;
461 for (int i = 0, j = 0; j < num_straight_path; i += 3, ++j) {
462 // save coordinate for Unreal axis (x, z, y)
463 path.emplace_back(straight_path[i], straight_path[i + 2], straight_path[i + 1]);
464 // save area type
465 {
466 // critical section, force single thread running this
467 std::scoped_lock<std::mutex> lock(_mutex);
468 _nav_mesh->getPolyArea(straight_path_polys[j], &area_type);
469 }
470 area.emplace_back(area_type);
471 }
472
473 return true;
474 }
475
476 // create a new walker in crowd
478 dtCrowdAgentParams params;
479
480 // check if all is ready
481 if (!_ready) {
482 return false;
483 }
484
485 DEBUG_ASSERT(_crowd != nullptr);
486
487 // set parameters
488 memset(&params, 0, sizeof(params));
489 params.radius = AGENT_RADIUS;
490 params.height = AGENT_HEIGHT;
491 params.maxAcceleration = 160.0f;
492 params.maxSpeed = 1.47f;
493 params.collisionQueryRange = 10;
494 params.obstacleAvoidanceType = 3;
495 params.separationWeight = 0.5f;
496
497 // set if the agent can cross roads or not
498 if (frand() <= _probability_crossing) {
499 params.queryFilterType = 1;
500 } else {
501 params.queryFilterType = 0;
502 }
503
504 // flags
505 params.updateFlags = 0;
506 params.updateFlags |= DT_CROWD_ANTICIPATE_TURNS;
507 params.updateFlags |= DT_CROWD_OBSTACLE_AVOIDANCE;
508 params.updateFlags |= DT_CROWD_SEPARATION;
509
510 // from Unreal coordinates (subtract half height to move pivot from center
511 // (unreal) to bottom (recast))
512 float point_from[3] = { from.x, from.z - (AGENT_HEIGHT / 2.0f), from.y };
513 // add walker
514 int index;
515 {
516 // critical section, force single thread running this
517 std::scoped_lock<std::mutex> lock(_mutex);
518 index = _crowd->addAgent(point_from, &params);
519 if (index == -1) {
520 return false;
521 }
522 }
523
524 // save the id
525 _mapped_walkers_id[id] = index;
526 _mapped_by_index[index] = id;
527
528 // init yaw
529 _yaw_walkers[id] = 0.0f;
530
531 // add walker for the route planning
533
534 return true;
535 }
536
537 // create a new vehicle in crowd to be avoided by walkers
539 namespace cg = carla::geom;
540 dtCrowdAgentParams params;
541
542 // check if all is ready
543 if (!_ready) {
544 return false;
545 }
546
547 DEBUG_ASSERT(_crowd != nullptr);
548
549 // get the bounding box extension plus some space around
550 float marge = 0.8f;
551 float hx = vehicle.bounding.extent.x + marge;
552 float hy = vehicle.bounding.extent.y + marge;
553 // define the 4 corners of the bounding box
554 cg::Vector3D box_corner1 {-hx, -hy, 0};
555 cg::Vector3D box_corner2 { hx + 0.2f, -hy, 0};
556 cg::Vector3D box_corner3 { hx + 0.2f, hy, 0};
557 cg::Vector3D box_corner4 {-hx, hy, 0};
558 // rotate the points
559 float angle = cg::Math::ToRadians(vehicle.transform.rotation.yaw);
560 box_corner1 = cg::Math::RotatePointOnOrigin2D(box_corner1, angle);
561 box_corner2 = cg::Math::RotatePointOnOrigin2D(box_corner2, angle);
562 box_corner3 = cg::Math::RotatePointOnOrigin2D(box_corner3, angle);
563 box_corner4 = cg::Math::RotatePointOnOrigin2D(box_corner4, angle);
564 // translate to world position
565 box_corner1 += vehicle.transform.location;
566 box_corner2 += vehicle.transform.location;
567 box_corner3 += vehicle.transform.location;
568 box_corner4 += vehicle.transform.location;
569
570 // check if this actor exists
571 auto it = _mapped_vehicles_id.find(vehicle.id);
572 if (it != _mapped_vehicles_id.end()) {
573 // get the index found
574 int index = it->second;
575 if (index != -1) {
576 // get the agent
577 dtCrowdAgent *agent;
578 {
579 // critical section, force single thread running this
580 std::scoped_lock<std::mutex> lock(_mutex);
581 agent = _crowd->getEditableAgent(index);
582 }
583 if (agent) {
584 // update its position
585 agent->npos[0] = vehicle.transform.location.x;
586 agent->npos[1] = vehicle.transform.location.z;
587 agent->npos[2] = vehicle.transform.location.y;
588 // update its oriented bounding box
589 agent->params.obb[0] = box_corner1.x;
590 agent->params.obb[1] = box_corner1.z;
591 agent->params.obb[2] = box_corner1.y;
592 agent->params.obb[3] = box_corner2.x;
593 agent->params.obb[4] = box_corner2.z;
594 agent->params.obb[5] = box_corner2.y;
595 agent->params.obb[6] = box_corner3.x;
596 agent->params.obb[7] = box_corner3.z;
597 agent->params.obb[8] = box_corner3.y;
598 agent->params.obb[9] = box_corner4.x;
599 agent->params.obb[10] = box_corner4.z;
600 agent->params.obb[11] = box_corner4.y;
601 }
602 return true;
603 }
604 }
605
606 // set parameters
607 memset(&params, 0, sizeof(params));
608 params.radius = 2;
609 params.height = AGENT_HEIGHT;
610 params.maxAcceleration = 0.0f;
611 params.maxSpeed = 1.47f;
612 params.collisionQueryRange = 0;
613 params.obstacleAvoidanceType = 0;
614 params.separationWeight = 100.0f;
615
616 // flags
617 params.updateFlags = 0;
618 params.updateFlags |= DT_CROWD_SEPARATION;
619
620 // update its oriented bounding box
621 // data: [x][y][z] [x][y][z] [x][y][z] [x][y][z]
622 params.useObb = true;
623 params.obb[0] = box_corner1.x;
624 params.obb[1] = box_corner1.z;
625 params.obb[2] = box_corner1.y;
626 params.obb[3] = box_corner2.x;
627 params.obb[4] = box_corner2.z;
628 params.obb[5] = box_corner2.y;
629 params.obb[6] = box_corner3.x;
630 params.obb[7] = box_corner3.z;
631 params.obb[8] = box_corner3.y;
632 params.obb[9] = box_corner4.x;
633 params.obb[10] = box_corner4.z;
634 params.obb[11] = box_corner4.y;
635
636 // from Unreal coordinates (vertical is Z) to Recast coordinates (vertical is Y)
637 float point_from[3] = { vehicle.transform.location.x,
638 vehicle.transform.location.z,
639 vehicle.transform.location.y };
640
641 // add walker
642 int index;
643 {
644 // critical section, force single thread running this
645 std::scoped_lock<std::mutex> lock(_mutex);
646 index = _crowd->addAgent(point_from, &params);
647 if (index == -1) {
648 logging::log("Vehicle agent not added to the crowd by some problem!");
649 return false;
650 }
651
652 // mark as valid
653 dtCrowdAgent *agent = _crowd->getEditableAgent(index);
654 if (agent) {
655 agent->state = DT_CROWDAGENT_STATE_WALKING;
656 }
657 }
658
659 // save the id
660 _mapped_vehicles_id[vehicle.id] = index;
661 _mapped_by_index[index] = vehicle.id;
662
663 return true;
664 }
665
666 // remove an agent
668
669 // check if all is ready
670 if (!_ready) {
671 return false;
672 }
673
674 DEBUG_ASSERT(_crowd != nullptr);
675
676 // get the internal walker index
677 auto it = _mapped_walkers_id.find(id);
678 if (it != _mapped_walkers_id.end()) {
679 // remove from crowd
680 {
681 // critical section, force single thread running this
682 std::scoped_lock<std::mutex> lock(_mutex);
683 _crowd->removeAgent(it->second);
684 }
686 // remove from mapping
687 _mapped_walkers_id.erase(it);
688 _mapped_by_index.erase(it->second);
689
690 return true;
691 }
692
693 // get the internal vehicle index
694 it = _mapped_vehicles_id.find(id);
695 if (it != _mapped_vehicles_id.end()) {
696 // remove from crowd
697 {
698 // critical section, force single thread running this
699 std::scoped_lock<std::mutex> lock(_mutex);
700 _crowd->removeAgent(it->second);
701 }
702 // remove from mapping
703 _mapped_vehicles_id.erase(it);
704 _mapped_by_index.erase(it->second);
705
706 return true;
707 }
708
709 return false;
710 }
711
712 // add/update/delete vehicles in crowd
713 bool Navigation::UpdateVehicles(std::vector<VehicleCollisionInfo> vehicles) {
714 std::unordered_set<carla::rpc::ActorId> updated;
715
716 // add all current mapped vehicles in the set
717 for (auto &&entry : _mapped_vehicles_id) {
718 updated.insert(entry.first);
719 }
720
721 // add all vehicles (if already exists, it gets updated only)
722 for (auto &&entry : vehicles) {
723 // try to add or update the vehicle
724 AddOrUpdateVehicle(entry);
725 // mark as updated (to avoid removing it in this frame)
726 updated.erase(entry.id);
727 }
728
729 // remove all vehicles not updated (they don't exist in this frame)
730 for (auto &&entry : updated) {
731 // remove agent not updated
732 RemoveAgent(entry);
733 }
734
735 return true;
736 }
737
738 // set new max speed
739 bool Navigation::SetWalkerMaxSpeed(ActorId id, float max_speed) {
740
741 // check if all is ready
742 if (!_ready) {
743 return false;
744 }
745
746 DEBUG_ASSERT(_crowd != nullptr);
747
748 // get the internal index
749 auto it = _mapped_walkers_id.find(id);
750 if (it == _mapped_walkers_id.end()) {
751 return false;
752 }
753
754 // get the agent
755 {
756 // critical section, force single thread running this
757 std::scoped_lock<std::mutex> lock(_mutex);
758 dtCrowdAgent *agent = _crowd->getEditableAgent(it->second);
759 if (agent) {
760 agent->params.maxSpeed = max_speed;
761 return true;
762 }
763 }
764
765 return false;
766 }
767
768 // set a new target point to go
770
771 // check if all is ready
772 if (!_ready) {
773 return false;
774 }
775
776 // get the internal index
777 auto it = _mapped_walkers_id.find(id);
778 if (it == _mapped_walkers_id.end()) {
779 return false;
780 }
781
782 return _walker_manager.SetWalkerRoute(id, to);
783 }
784
785 // set a new target point to go directly without events
787
788 // check if all is ready
789 if (!_ready) {
790 return false;
791 }
792
793 // get the internal index
794 auto it = _mapped_walkers_id.find(id);
795 if (it == _mapped_walkers_id.end()) {
796 return false;
797 }
798
799 return SetWalkerDirectTargetIndex(it->second, to);
800 }
801
802 // set a new target point to go directly without events
804
805 // check if all is ready
806 if (!_ready) {
807 return false;
808 }
809
810 DEBUG_ASSERT(_crowd != nullptr);
811 DEBUG_ASSERT(_nav_query != nullptr);
812
813 if (index == -1) {
814 return false;
815 }
816
817 // set target position
818 float point_to[3] = { to.x, to.z, to.y };
819 float nearest[3];
820 bool res;
821 {
822 // critical section, force single thread running this
823 std::scoped_lock<std::mutex> lock(_mutex);
824 const dtQueryFilter *filter = _crowd->getFilter(0);
825 dtPolyRef target_ref;
826 _nav_query->findNearestPoly(point_to, _crowd->getQueryHalfExtents(), filter, &target_ref, nearest);
827 if (!target_ref) {
828 return false;
829 }
830
831 res = _crowd->requestMoveTarget(index, target_ref, point_to);
832 }
833
834 return res;
835 }
836
837 // update all walkers in crowd
839
840 // check if all is ready
841 if (!_ready) {
842 return;
843 }
844
845 DEBUG_ASSERT(_crowd != nullptr);
846
847 // Advance by the simulation time since the last update: in asynchronous mode the client skips frames (#10255).
848 const auto &timestamp = state.GetTimestamp();
849 double dt = timestamp.delta_seconds;
850 if (_last_elapsed_seconds.has_value() && timestamp.elapsed_seconds >= *_last_elapsed_seconds) {
851 dt = timestamp.elapsed_seconds - *_last_elapsed_seconds;
852 }
853 _last_elapsed_seconds = timestamp.elapsed_seconds;
854 if (dt <= 0.0) {
855 return;
856 }
857 dt = std::min(dt, MAX_NAV_CATCH_UP);
858 _delta_seconds = dt;
859
860 // update crowd agents, in steps Detour handles well
861 for (double remaining = dt; remaining > 0.0; remaining -= MAX_NAV_STEP) {
862 // critical section, force single thread running this
863 std::scoped_lock<std::mutex> lock(_mutex);
864 _crowd->update(static_cast<float>(std::min(remaining, MAX_NAV_STEP)), nullptr);
865 }
866
867 // update the walkers route
869
870 // update the time to check for blocked agents
872
873 // check all active agents
874 int total_unblocked = 0;
875 int total_agents;
876 {
877 // critical section, force single thread running this
878 std::scoped_lock<std::mutex> lock(_mutex);
879 total_agents = _crowd->getAgentCount();
880 }
881 const dtCrowdAgent *ag;
882 for (int i = 0; i < total_agents; ++i) {
883 {
884 // critical section, force single thread running this
885 std::scoped_lock<std::mutex> lock(_mutex);
886 ag = _crowd->getAgent(i);
887 }
888
889 if (!ag->active || ag->paused || ag->dead) {
890 continue;
891 }
892
893 // check only pedestrians not paused, and no vehicles
894 if (!ag->params.useObb && !ag->paused) {
895 bool reset_target_pos = false;
896 bool use_same_filter = false;
897
898 // check for unblocking actors
900 // get the distance moved by each actor
902 carla::geom::Vector3D current = carla::geom::Vector3D(ag->npos[0], ag->npos[1], ag->npos[2]);
903 carla::geom::Vector3D distance = current - previous;
904 float d = distance.SquaredLength();
906 ++total_unblocked;
907 reset_target_pos = true;
908 use_same_filter = true;
909 }
910 // update with current position
911 _walkers_blocked_position[i] = current;
912
913 // check to assign a new target position
914 if (reset_target_pos) {
915 // set if the agent can cross roads or not
916 if (!use_same_filter) {
917 if (frand() <= _probability_crossing) {
918 SetAgentFilter(i, 1);
919 } else {
920 SetAgentFilter(i, 0);
921 }
922 }
923 // set a new random target
924 carla::geom::Location location;
925 GetRandomLocation(location, nullptr);
927 }
928 }
929 }
930 }
931
932 // check for resetting time
934 _time_to_unblock = 0.0f;
935 }
936 }
937
938 // get the walker current transform
940
941 // check if all is ready
942 if (!_ready) {
943 return false;
944 }
945
946 DEBUG_ASSERT(_crowd != nullptr);
947
948 // get the internal index
949 auto it = _mapped_walkers_id.find(id);
950 if (it == _mapped_walkers_id.end()) {
951 return false;
952 }
953
954 // get the index found
955 int index = it->second;
956 if (index == -1) {
957 return false;
958 }
959
960 // get the walker
961 const dtCrowdAgent *agent;
962 {
963 // critical section, force single thread running this
964 std::scoped_lock<std::mutex> lock(_mutex);
965 agent = _crowd->getAgent(index);
966 }
967
968 if (!agent->active) {
969 return false;
970 }
971
972 // set its position in Unreal coordinates
973 trans.location.x = agent->npos[0];
974 trans.location.y = agent->npos[2];
975 trans.location.z = agent->npos[1];
976
977 // set its rotation
978 float yaw;
979 float speed = 0.0f;
980 float min = 0.1f;
981 if (agent->vel[0] < -min || agent->vel[0] > min ||
982 agent->vel[2] < -min || agent->vel[2] > min) {
983 yaw = atan2f(agent->vel[2], agent->vel[0]) * (180.0f / static_cast<float>(M_PI));
984 speed = sqrtf(agent->vel[0] * agent->vel[0] + agent->vel[1] * agent->vel[1] + agent->vel[2] * agent->vel[2]);
985 } else {
986 yaw = atan2f(agent->dvel[2], agent->dvel[0]) * (180.0f / static_cast<float>(M_PI));
987 speed = sqrtf(agent->dvel[0] * agent->dvel[0] + agent->dvel[1] * agent->dvel[1] + agent->dvel[2] * agent->dvel[2]);
988 }
989
990 // interpolate current and target angle
991 float shortest_angle = fmod(yaw - _yaw_walkers[id] + 540.0f, 360.0f) - 180.0f;
992 float per = (speed / 1.5f);
993 if (per > 1.0f) per = 1.0f;
994 float rotation_speed = per * 6.0f;
995 trans.rotation.yaw = _yaw_walkers[id] +
996 (shortest_angle * std::min(1.0f, rotation_speed * static_cast<float>(_delta_seconds)));
997 _yaw_walkers[id] = trans.rotation.yaw;
998
999 return true;
1000 }
1001
1002 // get the walker current location
1004
1005 // check if all is ready
1006 if (!_ready) {
1007 return false;
1008 }
1009
1010 DEBUG_ASSERT(_crowd != nullptr);
1011
1012 // get the internal index
1013 auto it = _mapped_walkers_id.find(id);
1014 if (it == _mapped_walkers_id.end()) {
1015 return false;
1016 }
1017
1018 // get the index found
1019 int index = it->second;
1020 if (index == -1) {
1021 return false;
1022 }
1023
1024 // get the walker
1025 const dtCrowdAgent *agent;
1026 {
1027 // critical section, force single thread running this
1028 std::scoped_lock<std::mutex> lock(_mutex);
1029 agent = _crowd->getAgent(index);
1030 }
1031
1032 if (!agent->active) {
1033 return false;
1034 }
1035
1036 // set its position in Unreal coordinates
1037 location.x = agent->npos[0];
1038 location.y = agent->npos[2];
1039 location.z = agent->npos[1];
1040
1041 return true;
1042 }
1043
1045
1046 // check if all is ready
1047 if (!_ready) {
1048 return 0.0f;
1049 }
1050
1051 DEBUG_ASSERT(_crowd != nullptr);
1052
1053 // get the internal index
1054 auto it = _mapped_walkers_id.find(id);
1055 if (it == _mapped_walkers_id.end()) {
1056 return 0.0f;
1057 }
1058
1059 // get the index found
1060 int index = it->second;
1061 if (index == -1) {
1062 return 0.0f;
1063 }
1064
1065 // get the walker
1066 const dtCrowdAgent *agent;
1067 {
1068 // critical section, force single thread running this
1069 std::scoped_lock<std::mutex> lock(_mutex);
1070 agent = _crowd->getAgent(index);
1071 }
1072
1073 return sqrt(agent->vel[0] * agent->vel[0] + agent->vel[1] * agent->vel[1] + agent->vel[2] *
1074 agent->vel[2]);
1075 }
1076
1077 // get a random location for navigation
1078 bool Navigation::GetRandomLocation(carla::geom::Location &location, dtQueryFilter * filter) const {
1079
1080 // check if all is ready
1081 if (!_ready) {
1082 return false;
1083 }
1084
1085 DEBUG_ASSERT(_nav_query != nullptr);
1086
1087 // filter
1088 dtQueryFilter filter2;
1089 if (filter == nullptr) {
1090 filter2.setIncludeFlags(CARLA_TYPE_SIDEWALK);
1091 filter2.setExcludeFlags(CARLA_TYPE_NONE);
1092 filter = &filter2;
1093 }
1094
1095 // we will try up to 10 rounds, otherwise we failed to find a good location
1096 dtPolyRef random_ref { 0 };
1097 float point[3] { 0.0f, 0.0f, 0.0f };
1098 int rounds = 10;
1099 {
1100 dtStatus status;
1101 // critical section, force single thread running this
1102 std::scoped_lock<std::mutex> lock(_mutex);
1103 do {
1104 status = _nav_query->findRandomPoint(filter, frand, &random_ref, point);
1105 // set the location in Unreal coords
1106 if (status == DT_SUCCESS) {
1107 location.x = point[0];
1108 location.y = point[2];
1109 location.z = point[1];
1110 }
1111 --rounds;
1112 } while (status != DT_SUCCESS && rounds > 0);
1113 }
1114
1115 return (rounds > 0);
1116 }
1117
1118 // assign a filter index to an agent
1119 void Navigation::SetAgentFilter(int agent_index, int filter_index)
1120 {
1121 // get the walker
1122 dtCrowdAgent *agent;
1123 {
1124 // critical section, force single thread running this
1125 std::scoped_lock<std::mutex> lock(_mutex);
1126 agent = _crowd->getEditableAgent(agent_index);
1127 }
1128 agent->params.queryFilterType = static_cast<unsigned char>(filter_index);
1129 }
1130
1131 // set the probability that an agent could cross the roads in its path following
1132 // percentage of 0.0f means no pedestrian can cross roads
1133 // percentage of 0.5f means 50% of all pedestrians can cross roads
1134 // percentage of 1.0f means all pedestrians can cross roads if needed
1136 {
1137 _probability_crossing = percentage;
1138 }
1139
1140 // set an agent as paused for the crowd
1141 void Navigation::PauseAgent(ActorId id, bool pause) {
1142 // check if all is ready
1143 if (!_ready) {
1144 return;
1145 }
1146
1147 DEBUG_ASSERT(_crowd != nullptr);
1148
1149 // get the internal index
1150 auto it = _mapped_walkers_id.find(id);
1151 if (it == _mapped_walkers_id.end()) {
1152 return;
1153 }
1154
1155 // get the index found
1156 int index = it->second;
1157 if (index == -1) {
1158 return;
1159 }
1160
1161 // get the walker
1162 dtCrowdAgent *agent;
1163 {
1164 // critical section, force single thread running this
1165 std::scoped_lock<std::mutex> lock(_mutex);
1166 agent = _crowd->getEditableAgent(index);
1167 }
1168
1169 // mark
1170 agent->paused = pause;
1171 }
1172
1173 bool Navigation::HasVehicleNear(ActorId id, float distance, carla::geom::Location direction) {
1174 // get the internal index (walker or vehicle)
1175 auto it = _mapped_walkers_id.find(id);
1176 if (it == _mapped_walkers_id.end()) {
1177 it = _mapped_vehicles_id.find(id);
1178 if (it == _mapped_vehicles_id.end()) {
1179 return false;
1180 }
1181 }
1182
1183 float dir[3] = { direction.x, direction.z, direction.y };
1184 bool result;
1185 {
1186 // critical section, force single thread running this
1187 std::scoped_lock<std::mutex> lock(_mutex);
1188 result = _crowd->hasVehicleNear(it->second, distance * distance, dir, false);
1189 }
1190 return result;
1191 }
1192
1193 /// make agent look at some location
1195 // get the internal index (walker or vehicle)
1196 auto it = _mapped_walkers_id.find(id);
1197 if (it == _mapped_walkers_id.end()) {
1198 it = _mapped_vehicles_id.find(id);
1199 if (it == _mapped_vehicles_id.end()) {
1200 return false;
1201 }
1202 }
1203
1204 dtCrowdAgent *agent;
1205 {
1206 // critical section, force single thread running this
1207 std::scoped_lock<std::mutex> lock(_mutex);
1208 agent = _crowd->getEditableAgent(it->second);
1209 }
1210
1211 // get the position
1212 float x = (location.x - agent->npos[0]) * 0.0001f;
1213 float y = (location.y - agent->npos[2]) * 0.0001f;
1214 float z = (location.z - agent->npos[1]) * 0.0001f;
1215
1216 // set its velocity
1217 agent->vel[0] = x;
1218 agent->vel[2] = y;
1219 agent->vel[1] = z;
1220 agent->nvel[0] = x;
1221 agent->nvel[2] = y;
1222 agent->nvel[1] = z;
1223 agent->dvel[0] = x;
1224 agent->dvel[2] = y;
1225 agent->dvel[1] = z;
1226
1227 return true;
1228 }
1229
1230 bool Navigation::IsWalkerAlive(ActorId id, bool &alive) {
1231 // check if all is ready
1232 if (!_ready) {
1233 return false;
1234 }
1235
1236 DEBUG_ASSERT(_crowd != nullptr);
1237
1238 // get the internal index
1239 auto it = _mapped_walkers_id.find(id);
1240 if (it == _mapped_walkers_id.end()) {
1241 return false;
1242 }
1243
1244 // get the index found
1245 int index = it->second;
1246 if (index == -1) {
1247 return false;
1248 }
1249
1250 // get the walker
1251 const dtCrowdAgent *agent;
1252 {
1253 // critical section, force single thread running this
1254 std::scoped_lock<std::mutex> lock(_mutex);
1255 agent = _crowd->getAgent(index);
1256 }
1257
1258 // mark
1259 alive = !agent->dead;
1260
1261 return true;
1262 }
1263
1264} // namespace nav
1265} // namespace carla
#define DEBUG_ASSERT(predicate)
Definition Debug.h:66
double min(double v1, double v2)
Definition Simplify.h:285
Represents the state of all the actors of an episode at a given frame.
const auto & GetTimestamp() const
Vector3D extent
Half the size of the BoundingBox in local space.
static constexpr T ToRadians(T deg)
Definition Math.h:43
static Vector3D RotatePointOnOrigin2D(Vector3D p, float angle)
Definition Math.cpp:111
A rigid transform in CARLA's / Unreal's left-handed frame: x forward, y right, z up,...
bool SetWalkerMaxSpeed(ActorId id, float max_speed)
set new max speed
void UpdateCrowd(const client::detail::EpisodeState &state)
update all walkers in crowd
bool GetPath(carla::geom::Location from, carla::geom::Location to, dtQueryFilter *filter, std::vector< carla::geom::Location > &path, std::vector< unsigned char > &area)
return the path points to go from one position to another
void SetAgentFilter(int agent_index, int filter_index)
assign a filter index to an agent
std::unordered_map< ActorId, int > _mapped_vehicles_id
Definition Navigation.h:137
std::unordered_map< ActorId, int > _mapped_walkers_id
mapping Id
Definition Navigation.h:136
bool RemoveAgent(ActorId id)
remove an agent
std::weak_ptr< carla::client::detail::Simulator > _simulator
Definition Navigation.h:149
bool GetWalkerPosition(ActorId id, carla::geom::Location &location)
get the walker current location
float GetWalkerSpeed(ActorId id)
get the walker current transform
bool Load(const std::string &filename)
load navigation data
bool SetWalkerTarget(ActorId id, carla::geom::Location to)
set a new target point to go through a route with events
void SetSeed(unsigned int seed)
set the seed to use with random numbers
dtNavMesh * _nav_mesh
meshes
Definition Navigation.h:131
bool UpdateVehicles(std::vector< VehicleCollisionInfo > vehicles)
add/update/delete vehicles in crowd
std::unordered_map< int, ActorId > _mapped_by_index
Definition Navigation.h:139
bool SetWalkerDirectTarget(ActorId id, carla::geom::Location to)
bool SetWalkerLookAt(ActorId id, carla::geom::Location location)
make agent look at some location
void PauseAgent(ActorId id, bool pause)
set an agent as paused for the crowd
bool HasVehicleNear(ActorId id, float distance, carla::geom::Location direction)
return if the agent has a vehicle near (as neighbour)
bool GetWalkerTransform(ActorId id, carla::geom::Transform &trans)
get the walker current transform
bool GetRandomLocation(carla::geom::Location &location, dtQueryFilter *filter=nullptr) const
get a random location for navigation
bool IsWalkerAlive(ActorId id, bool &alive)
return if the agent has been killed by a vehicle
WalkerManager _walker_manager
walker manager for the route planning with events
Definition Navigation.h:147
bool GetAgentRoute(ActorId id, carla::geom::Location from, carla::geom::Location to, std::vector< carla::geom::Location > &path, std::vector< unsigned char > &area)
void SetPedestriansCrossFactor(float percentage)
set the probability that an agent could cross the roads in its path following
std::unordered_map< ActorId, float > _yaw_walkers
store walkers yaw angle from previous tick
Definition Navigation.h:141
dtCrowd * _crowd
crowd
Definition Navigation.h:134
std::optional< double > _last_elapsed_seconds
Simulation time of the snapshot the crowd last advanced to; unset before the first update.
Definition Navigation.h:129
bool AddWalker(ActorId id, carla::geom::Location from)
create a new walker
std::vector< uint8_t > _binary_mesh
Definition Navigation.h:126
bool SetWalkerDirectTargetIndex(int index, carla::geom::Location to)
void SetSimulator(std::weak_ptr< carla::client::detail::Simulator > simulator)
reference to the simulator to access API functions
dtNavMeshQuery * _nav_query
Definition Navigation.h:132
void CreateCrowd(void)
create the crowd object
bool AddOrUpdateVehicle(VehicleCollisionInfo &vehicle)
create a new vehicle in crowd to be avoided by walkers
std::unordered_map< int, carla::geom::Vector3D > _walkers_blocked_position
saves the position of each actor at intervals and check if any is blocked
Definition Navigation.h:143
bool RemoveWalker(ActorId id)
remove a walker route
bool AddWalker(ActorId id)
create a new walker route
void SetSimulator(std::weak_ptr< carla::client::detail::Simulator > simulator)
reference to the simulator to access API functions
bool Update(double delta)
update all routes
void SetNav(Navigation *nav)
assign the navigation module
bool SetWalkerRoute(ActorId id)
set a new route from its current position
@ DT_CROWD_OPTIMIZE_TOPO
@ DT_CROWD_OBSTACLE_AVOIDANCE
@ DT_CROWD_SEPARATION
@ DT_CROWD_OPTIMIZE_VIS
@ DT_CROWD_ANTICIPATE_TURNS
@ CARLA_AREA_GRASS
Definition Navigation.h:33
@ CARLA_AREA_ROAD
Definition Navigation.h:32
static const float AREA_ROAD_COST
static float frand()
@ CARLA_TYPE_WALKABLE
Definition Navigation.h:45
@ CARLA_TYPE_SIDEWALK
Definition Navigation.h:39
@ CARLA_TYPE_NONE
Definition Navigation.h:38
@ CARLA_TYPE_ROAD
Definition Navigation.h:41
static const float AGENT_UNBLOCK_TIME
static const float AGENT_RADIUS
static const float AGENT_HEIGHT
static const float AGENT_UNBLOCK_DISTANCE_SQUARED
static const double MAX_NAV_STEP
static const int MAX_AGENTS
static const double MAX_NAV_CATCH_UP
static const int MAX_POLYS
static const int MAX_QUERY_SEARCH_NODES
static const float AGENT_UNBLOCK_DISTANCE
static const float AREA_GRASS_COST
This file contains definitions of common data structures used in traffic manager.
rpc::ActorId ActorId
Definition ActorId.h:18
constexpr float SquaredLength() const
struct to send info about vehicles to the crowd
Definition Navigation.h:49
carla::geom::BoundingBox bounding
Definition Navigation.h:52
carla::geom::Transform transform
Definition Navigation.h:51