Eclipse SUMO - Simulation of Urban MObility
Loading...
Searching...
No Matches
MSPModel_JuPedSim.cpp
Go to the documentation of this file.
1/****************************************************************************/
2// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.dev/sumo
3// Copyright (C) 2014-2026 German Aerospace Center (DLR) and others.
4// This program and the accompanying materials are made available under the
5// terms of the Eclipse Public License 2.0 which is available at
6// https://www.eclipse.org/legal/epl-2.0/
7// This Source Code may also be made available under the following Secondary
8// Licenses when the conditions for such availability set forth in the Eclipse
9// Public License 2.0 are satisfied: GNU General Public License, version 2
10// or later which is available at
11// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html
12// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later
13/****************************************************************************/
21// The pedestrian following model that can instantiate different pedestrian models
22// that come with the JuPedSim third-party simulation framework.
23/****************************************************************************/
24
25#include <config.h>
26
27#include <algorithm>
28#include <fstream>
29#include <geos_c.h>
32#include <microsim/MSEdge.h>
33#include <microsim/MSLane.h>
34#include <microsim/MSLink.h>
42#include <libsumo/Helper.h>
43#include <utils/geom/Position.h>
47#include "MSPerson.h"
48#include "MSStageWalking.h"
49#include "MSPModel_JuPedSim.h"
50
51
52// #define DEBUG_GEOMETRY_GENERATION
53// #define DEBUG_GRPC_TIMING
54
55
62const std::string MSPModel_JuPedSim::PEDESTRIAN_NETWORK_ID = "jupedsim.pedestrian_network";
63const std::string MSPModel_JuPedSim::PEDESTRIAN_NETWORK_CARRIAGES_AND_RAMPS_ID = "jupedsim.pedestrian_network.carriages_and_ramps";
64
65const std::vector<MSPModel_JuPedSim::PState*> MSPModel_JuPedSim::noPedestrians;
66
67// ===========================================================================
68// method definitions
69// ===========================================================================
71 myStopWatch(10), myRNG("JuPedSim"), myNetwork(net), myShapeContainer(net->getShapeContainer()), myJPSDeltaT(string2time(oc.getString("pedestrian.jupedsim.step-length"))),
72 myExitTolerance(oc.getFloat("pedestrian.jupedsim.exit-tolerance")), myGEOSPedestrianNetworkLargestComponent(nullptr),
73 myHaveAdditionalWalkableAreas(false) {
75 myJPSModel = oc.getString("pedestrian.jupedsim.model");
76 if (myJPSModel.find("Model") == std::string::npos) {
77 // TODO warn about outdated model name
78 myJPSModel += "Model";
79 if (myJPSModel == "CollisionFreeSpeedV2Model") {
80 myJPSModel = "CollisionFreeSpeedModelV2";
81 }
82 }
83 std::string command;
84 std::string address = oc.getString("pedestrian.jupedsim.address");
85 // address = "localhost:50051"; // for debugging
86 if (address == "") {
87 const char* pythonEnv = getenv("PYTHON");
88 const std::string python = (pythonEnv == nullptr) ? "python" : pythonEnv;
89 const char* sumoHomeEnv = getenv("SUMO_HOME");
90 const std::string sumoHome = (sumoHomeEnv == nullptr) ? "." : sumoHomeEnv;
91 command = python + " " + sumoHome + "/tools/jupedsim_grpc/servicer.py";
92 if (oc.isSet("pedestrian.jupedsim.py")) {
93 command += " --debug " + oc.getString("pedestrian.jupedsim.py");
94 }
95 }
96 for (int i = 0; i < 2; i++) { // try twice: initial attempt + one restart
97 if (command != "") {
98#ifdef HAVE_BOOST
99 const std::string port = toString(tcpip::Socket::getFreeSocketPort());
100 myJuPedSimServer = std::unique_ptr<bp::child>(new bp::child(command + " --port " + port));
101 address = "localhost:" + port;
102#else
103 WRITE_WARNINGF(TL("No boost process support, you will need to start the JuPedSim server manually using %."), command);
104#endif
105 }
106
107 myGrpcChannel = grpc::CreateChannel(address, grpc::InsecureChannelCredentials());
108 if (myGrpcChannel->WaitForConnected(std::chrono::system_clock::now() + std::chrono::seconds(5))) {
109 WRITE_MESSAGEF(TL("Connected to JuPedSim gRPC server on '%'."), address);
110 break;
111 } else {
112 WRITE_WARNINGF(TL("Could not connect to JuPedSim gRPC server on '%' (will retry on demand)."), address);
113#ifdef HAVE_BOOST
114 if (myJuPedSimServer == nullptr || myJuPedSimServer->running()) {
115 break;
116 }
117#else
118 break;
119#endif
120 }
121 }
122 myGrpcStub = sumo_jupedsim_api::JuPedSimService::NewStub(myGrpcChannel);
123 initialize(oc);
125}
126
127
129 clearState();
130#ifdef HAVE_BOOST
131 if (myJuPedSimServer != nullptr) {
132 myJuPedSimServer->terminate();
133 }
134#endif
135
136 // TODO: clear simulation, operational model and geometries?
137
138 GEOSGeom_destroy(myGEOSPedestrianNetwork);
139 finishGEOS();
140#ifdef DEBUG_GRPC_TIMING
141 std::cout << myStopWatch[0].getTotal() / (1e6) << "ms, iteration: "
142 << myStopWatch[1].getTotal() / (1e6) << "ms, agent data retrieval: "
143 << myStopWatch[2].getTotal() / (1e6) << "ms, journey creation: "
144 << myStopWatch[3].getTotal() / (1e6) << "ms, insertion: "
145 << myStopWatch[4].getTotal() / (1e6) << "ms, removal: "
146 << myStopWatch[5].getTotal() / (1e6) << "ms, add waiting set: "
147 << myStopWatch[6].getTotal() / (1e6) << "ms, speed: "
148 << myStopWatch[7].getTotal() / (1e6) << "ms " << std::endl;
149#endif
150}
151
152
153void
155#ifdef DEBUG_GRPC_TIMING
156 myStopWatch[4].start();
157#endif
158 const MSVehicleType& type = state->getPerson()->getVehicleType();
159 sumo_jupedsim_api::CreateAgentRequest agentRequest;
160 agentRequest.set_simulation_id(myJPSSimulation);
161 agentRequest.set_agent_model_class(myJPSModel);
162 auto& agentParams = *agentRequest.mutable_agent_model_parameters()->mutable_fields();
163 agentParams["journey_id"].set_number_value(static_cast<double>(state->getJourneyId()));
164 agentParams["stage_id"].set_number_value(static_cast<double>(state->getStageId()));
165 agentParams["desired_speed"].set_number_value(state->getPerson()->getMaxSpeed());
166 if (myJPSModel != "GeneralizedCentrifugalForceModel") {
167 agentParams["radius"].set_number_value(getRadius(type));
168 }
169 google::protobuf::ListValue* position = agentParams["position"].mutable_list_value();
170 position->add_values()->set_number_value(p.x());
171 position->add_values()->set_number_value(p.y());
172 if (myJPSModel == "GeneralizedCentrifugalForceModel" || myJPSModel == "SocialForceModel") {
173 const double angle = state->getAngle(*state->getStage(), 0);
174 double orientation_x = 0.;
175 double orientation_y = 0.;
176 if (fabs(angle - M_PI / 2) < NUMERICAL_EPS) {
177 orientation_y = 1.;
178 } else if (fabs(angle + M_PI / 2) < NUMERICAL_EPS) {
179 orientation_y = -1.;
180 } else {
181 orientation_x = 1.;
182 orientation_y = tan(angle);
183 }
184 google::protobuf::ListValue* orientation = agentParams["orientation"].mutable_list_value();
185 orientation->add_values()->set_number_value(orientation_x);
186 orientation->add_values()->set_number_value(orientation_y);
187 }
188 grpc::ClientContext agentContext;
189 sumo_jupedsim_api::CreateAgentResponse agentResponse;
190 const grpc::Status agentStatus = myGrpcStub->CreateAgent(&agentContext, agentRequest, &agentResponse);
191 if (agentStatus.ok()) {
192 state->setAgentId(agentResponse.agent_id());
193 } else {
194 WRITE_WARNINGF(TL("Error while adding person '%' as JuPedSim agent: %"), state->getPerson()->getID(), agentStatus.error_message());
195 }
196#ifdef DEBUG_GRPC_TIMING
197 myStopWatch[4].stop();
198#endif
199}
200
201
203MSPModel_JuPedSim::addWaypoint(const std::string& agentID, WaypointDesc& waypoint, const MSStageMoving* const finalStage) {
204 // Unlike the previous implementation we do not need to set the transitions explicitly anymore,
205 // the intermediate JuPedSim GRPC service handles this for us.
206 const MSLane* const lane = std::get<1>(waypoint);
207 Position& coords = std::get<2>(waypoint);
208 double& dist = std::get<3>(waypoint);
209 sumo_jupedsim_api::AddWaypointStageRequest waypointRequest;
210 if (finalStage == nullptr) {
211 if (lane->isWalkingArea()) {
212 coords = lane->getShape().getCentroid();
213 dist = lane->getEdge().getWidth() / 2.;
214 } else {
215 coords = lane->getShape().positionAtOffset(lane->getEdge().getLength() / 2.);
216 dist = lane->getWidth() / 2.;
217 }
218 const auto& centerIt = myLaneCenters.find(lane);
219 if (centerIt != myLaneCenters.end()) {
220 return centerIt->second;
221 }
222 } else {
223 coords = lane->getShape().positionAtOffset(finalStage->getArrivalPos());
224 dist = finalStage->getDouble("jupedsim.waypoint.radius", myExitTolerance);
225 }
226 waypointRequest.mutable_point()->set_x(coords.x());
227 waypointRequest.mutable_point()->set_y(coords.y());
228 waypointRequest.set_distance(dist);
229 sumo_jupedsim_api::StageResponse waypointResponse = callGrpc(&sumo_jupedsim_api::JuPedSimService::Stub::AddWaypointStage, waypointRequest,
230 TLF("Error while adding waypoint for person '%': ", agentID), true);
231 if (waypointResponse.stage_id() != 0 && finalStage == nullptr) {
232 myLaneCenters[lane] = waypointResponse.stage_id();
233 }
234 return waypointResponse.stage_id();
235}
236
237
240 assert(person->getCurrentStageType() == MSStageType::WALKING);
241 const double radius = getRadius(person->getVehicleType());
242 Position departurePosition = Position::INVALID;
243 const MSLane* const departureLane = getSidewalk<MSEdge, MSLane>(stage->getRoute().front());
244 if (departureLane == nullptr) {
245 const char* error = TL("Person '%' could not find sidewalk on edge '%', time=%.");
246 if (OptionsCont::getOptions().getBool("ignore-route-errors")) {
247 WRITE_WARNINGF(error, person->getID(), person->getEdge()->getID(), time2string(SIMSTEP));
248 return nullptr;
249 } else {
250 throw ProcessError(TLF(error, person->getID(), person->getEdge()->getID(), time2string(SIMSTEP)));
251 }
252 }
253 // First real stage, stage 0 is waiting.
255 const MSEdge* const tripOrigin = person->getNextStage(-1)->getEdge();
256 if (tripOrigin->isTazConnector()) {
257 const SUMOPolygon* tazShape = myNetwork->getShapeContainer().getPolygons().get(tripOrigin->getParameter("taz"));
258 if (tazShape == nullptr) {
259 WRITE_WARNINGF(TL("FromTaz '%' for person '%' has no shape information."), tripOrigin->getParameter("taz"), person->getID());
260 } else {
261 const Boundary& bbox = tazShape->getShape().getBoxBoundary();
262 while (!tazShape->getShape().around(departurePosition)) {
263 // TODO: Optimize for speed if necessary or at least abort trying to find a point.
264 departurePosition.setx(RandHelper::rand(bbox.xmin(), bbox.xmax(), &myRNG));
265 departurePosition.sety(RandHelper::rand(bbox.ymin(), bbox.ymax(), &myRNG));
266 }
267 }
268 }
269 }
270 if (departurePosition == Position::INVALID) {
271 const double halfDepartureLaneWidth = departureLane->getWidth() / 2.0;
272 double departureRelativePositionY = stage->getDepartPosLat();
273 if (departureRelativePositionY == UNSPECIFIED_POS_LAT) {
274 departureRelativePositionY = 0.0;
275 }
276 if (departureRelativePositionY == MSPModel::RANDOM_POS_LAT) {
277 departureRelativePositionY = RandHelper::rand(-halfDepartureLaneWidth, halfDepartureLaneWidth, &myRNG);
278 }
279 departurePosition = departureLane->getShape().positionAtOffset(stage->getDepartPos() + radius + POSITION_EPS, -departureRelativePositionY); // Minus sign is here for legacy reasons.
280 }
281
282 std::vector<WaypointDesc> waypoints;
283 const MSEdge* prev = nullptr;
284 for (const MSEdge* const e : stage->getEdges()) {
285 const MSLane* const lane = getSidewalk<MSEdge, MSLane>(e);
286 JPS_StageId waitingStage = 0;
287 if (prev != nullptr) {
288 int dir = UNDEFINED_DIRECTION;
289 if (prev->getToJunction() == e->getFromJunction() || prev->getToJunction() == e->getToJunction()) {
290 dir = FORWARD;
291 } else if (prev->getFromJunction() == e->getFromJunction() || prev->getFromJunction() == e->getToJunction()) {
292 dir = BACKWARD;
293 }
294 if (dir != UNDEFINED_DIRECTION) {
295 ConstMSEdgeVector crossingRoute;
296 MSNet::getInstance()->getPedestrianRouter(0).compute(prev, e, 0, 0, stage->getMaxSpeed(person), 0,
297 dir == FORWARD ? prev->getToJunction() : prev->getFromJunction(),
298 person->getVTypeParameter(), crossingRoute, true);
299 const MSEdge* wa = nullptr;
300 for (const MSEdge* const ce : crossingRoute) {
301 if (ce->isCrossing()) {
302 const MSLane* const crossing = getSidewalk<MSEdge, MSLane>(ce);
303 auto crossingWait = myCrossingWaits.find(crossing);
304 if (crossingWait != myCrossingWaits.end()) {
305 if (waitingStage != 0 && wa != nullptr) {
306 // we already have a waiting stage we need an intermediate waypoint
307 waypoints.push_back({waitingStage, wa->getLanes()[0], {}, {}});
308 }
309 const MSLane* const prevLane = getSidewalk<MSEdge, MSLane>(prev);
310 const Position& startPos = dir == FORWARD ? prevLane->getShape().back() : prevLane->getShape().front();
311 // choose the waiting set closer to the lane "end"
312 if (crossing->getShape().front().distanceSquaredTo(startPos) < crossing->getShape().back().distanceSquaredTo(startPos)) {
313 if (crossingWait->second.first == 0) {
314 crossingWait->second.first = addWaitingSet(crossing, true);
315 }
316 waitingStage = crossingWait->second.first;
317 } else {
318 if (crossingWait->second.second == 0) {
319 crossingWait->second.second = addWaitingSet(crossing, false);
320 }
321 waitingStage = crossingWait->second.second;
322 }
323 } else {
324 throw ProcessError(TLF("No waiting set for crossing at %.", ce->getID()));
325 }
326 }
327 if (ce->isWalkingArea()) {
328 wa = ce;
329 }
330 }
331 }
332 }
333 waypoints.push_back({waitingStage, lane, {}, {}});
334 prev = e;
335 }
336 const JPS_StageId finalWait = std::get<0>(waypoints.back());
337 waypoints.pop_back(); // arrival waypoint comes later
338 if (!waypoints.empty()) {
339 waypoints.erase(waypoints.begin()); // departure edge also does not need a waypoint
340 }
341 waypoints.push_back({finalWait, getSidewalk<MSEdge, MSLane>(stage->getDestination()), {}, {}});
342
343#ifdef DEBUG_GRPC_TIMING
344 myStopWatch[3].start();
345#endif
346 sumo_jupedsim_api::AddJourneyRequest journeyRequest;
347 JPS_StageId startingStage = 0;
348 for (WaypointDesc& p : waypoints) {
349 const JPS_StageId waiting = std::get<0>(p);
350 if (waiting != 0) {
351 journeyRequest.add_stage_ids(waiting);
352 }
353 JPS_StageId waypoint = addWaypoint(person->getID(), p, &p == &waypoints.back() ? stage : nullptr);
354 if (waypoint == 0) {
355 return nullptr;
356 }
357 journeyRequest.add_stage_ids(waypoint);
358 if (startingStage == 0) {
359 startingStage = waiting != 0 ? waiting : waypoint;
360 }
361 }
362 const sumo_jupedsim_api::AddJourneyResponse journeyResponse = callGrpc(&sumo_jupedsim_api::JuPedSimService::Stub::AddJourney, journeyRequest,
363 TLF("Error while adding journey for agent '%': ", person->getID()));
364 const JPS_JourneyId journeyId = journeyResponse.journey_id();
365#ifdef DEBUG_GRPC_TIMING
366 myStopWatch[3].stop();
367#endif
368
369 PState* state = nullptr;
370 for (PState* const pstate : myPedestrianStates) { // TODO transform myPedestrianStates into a map for faster lookup
371 if (pstate->getPerson() == person) {
372 state = pstate;
373 break;
374 }
375 }
376 if (state == nullptr) {
377 state = new PState(static_cast<MSPerson*>(person), stage, journeyId, startingStage, waypoints);
378 state->setLanePosition(stage->getDepartPos() + radius + POSITION_EPS);
379 state->setPosition(departurePosition.x(), departurePosition.y());
380 state->setAngle(departureLane->getShape().rotationAtOffset(stage->getDepartPos()));
381 myPedestrianStates.push_back(state);
383 } else {
384 state->reinit(stage, journeyId, startingStage, waypoints);
385 }
386 if (state->isWaitingToEnter()) {
387 const Position p = state->getPosition(*state->getStage(), now);
388 tryPedestrianInsertion(state, p);
389 } else {
390 sumo_jupedsim_api::SwitchAgentJourneyRequest switchRequest;
391 switchRequest.set_agent_id(state->getAgentId());
392 switchRequest.set_journey_id(journeyId);
393 switchRequest.set_stage_id(startingStage);
394 callGrpc(&sumo_jupedsim_api::JuPedSimService::Stub::SwitchAgentJourney, switchRequest,
395 TLF("Error while switching journey for agent '%': ", person->getID()));
396 }
397 return state;
398}
399
400
401void
403 PState* pstate = static_cast<PState*>(state);
404 if (pstate->getLane() != nullptr) {
405 auto& peds = myActiveLanes[pstate->getLane()];
406 peds.erase(std::find(peds.begin(), peds.end(), pstate));
407 pstate->setLane(nullptr);
408 }
409 if (pstate->getStage() != nullptr) {
410 pstate->getStage()->setPState(nullptr); // we need to remove the old state reference to avoid double deletion
411 }
412 pstate->setStage(nullptr);
413}
414
415
418#ifdef DEBUG_GRPC_TIMING
419 myStopWatch[1].start();
420#endif
421 sumo_jupedsim_api::IterateRequest iterateRequest;
422 iterateRequest.set_count((int)(DELTA_T / myJPSDeltaT));
423 callGrpc(&sumo_jupedsim_api::JuPedSimService::Stub::Iterate, iterateRequest, TL("JuPedSim gRPC Iterate failed: "));
424#ifdef DEBUG_GRPC_TIMING
425 myStopWatch[1].stop();
426#endif
427
428#ifdef DEBUG_GRPC_TIMING
429 myStopWatch[2].start();
430#endif
431 sumo_jupedsim_api::GetCorePropertiesOfAllAgentsRequest propertiesRequest;
432 sumo_jupedsim_api::GetCorePropertiesOfAllAgentsResponse propertiesResponse =
433 callGrpc(&sumo_jupedsim_api::JuPedSimService::Stub::GetCorePropertiesOfAllAgents, propertiesRequest, TL("JuPedSim gRPC GetCorePropertiesOfAllAgents failed: "));
434 const auto& properties = propertiesResponse.properties();
435#ifdef DEBUG_GRPC_TIMING
436 myStopWatch[2].stop();
437#endif
438
439 for (auto stateIt = myPedestrianStates.begin(); stateIt != myPedestrianStates.end();) {
440 PState* const state = *stateIt;
441
442 if (state->isWaitingToEnter()) {
443 // insertion failed at first try so we retry with some noise
444 Position p = state->getPosition(*state->getStage(), time);
445 p.setx(p.x() + RandHelper::rand(-.5, .5, &myRNG)); // we do this separately to avoid evaluation order problems
446 p.sety(p.y() + RandHelper::rand(-.5, .5, &myRNG));
447 tryPedestrianInsertion(state, p);
448 ++stateIt;
449 continue;
450 }
451
452 MSPerson* const person = state->getPerson();
453 MSStageWalking* const stage = dynamic_cast<MSStageWalking*>(person->getCurrentStage());
454 if (stage == nullptr) {
455 // It seems we kept the state for another stage but the new stage is not a walk.
456 // So let's remove the state because after the new stage we will be elsewhere and need to be reinserted for JuPedSim anyway.
457 // We cannot check this earlier because when the old stage ends the next stage might not know yet whether it will be a walk.
458 registerArrived(state->getAgentId());
459 stateIt = myPedestrianStates.erase(stateIt);
460 continue;
461 }
462
463 // Updates the agent position.
464 const auto agentIt = properties.find(state->getAgentId());
465 if (agentIt == properties.end()) {
466 WRITE_WARNINGF(TL("JuPedSim gRPC unknown agent: %"), state->getAgentId());
467 continue;
468 }
469 const sumo_jupedsim_api::Point& pos = agentIt->second.position();
470 state->setPosition(pos.x(), pos.y());
471 const sumo_jupedsim_api::Point& orientation = agentIt->second.orientation();
472 state->setAngle(atan2(orientation.y(), orientation.x()));
473
474 // Find on which edge the pedestrian is, using route's forward-looking edges because of how moveToXY is written.
475 Position newPosition(pos.x(), pos.y());
476 ConstMSEdgeVector route = stage->getEdges();
477 const int routeIndex = (int)(stage->getRouteStep() - stage->getRoute().begin());
478 const double oldLanePos = state->getEdgePos(time);
479 ConstMSEdgeVector forwardRoute = ConstMSEdgeVector(route.begin() + routeIndex, route.end());
480 double bestDistance = std::numeric_limits<double>::max();
481 MSLane* candidateLane = nullptr;
482 double candidateLaneLongitudinalPosition = 0.0;
483 int routeOffset = 0;
484 const bool found = libsumo::Helper::moveToXYMap_matchingRoutePosition(newPosition, "",
485 forwardRoute, 0, person->getVClass(), true, bestDistance, &candidateLane, candidateLaneLongitudinalPosition, routeOffset);
486
487 if (found) {
488 if (candidateLane != state->getLane()) {
489 if (state->getLane() != nullptr) {
490 auto& peds = myActiveLanes[state->getLane()];
491 peds.erase(std::find(peds.begin(), peds.end(), state));
492 }
493 myActiveLanes[candidateLane].push_back(state);
494 state->setLane(candidateLane);
495 }
496 state->setLanePosition(candidateLaneLongitudinalPosition);
497 }
498
499 const MSEdge* const expectedEdge = stage->getEdge();
500 if (found && expectedEdge->isNormal() && candidateLane->getEdge().isNormal() && &candidateLane->getEdge() != expectedEdge) {
501 const bool arrived = stage->moveToNextEdge(person, time, 1, nullptr);
502 UNUSED_PARAMETER(arrived);
503 assert(!arrived); // The person has not arrived yet.
504 stage->activateEntryReminders(person);
505 // Adapt speed to lane's speed limit.
506 // TODO make this a bulk request
507 sumo_jupedsim_api::SetDesiredSpeedRequest desiredSpeedRequest;
508 auto speeds = desiredSpeedRequest.mutable_desired_speeds();
509 (*speeds)[state->getAgentId()] = MIN2(candidateLane->getSpeedLimit(), person->getMaxSpeed());
510#ifdef DEBUG_GRPC_TIMING
511 myStopWatch[7].start();
512#endif
513 callGrpc(&sumo_jupedsim_api::JuPedSimService::Stub::SetDesiredSpeedOfAgents, desiredSpeedRequest,
514 TLF("Error while setting desired speed for %: ", person->getID()));
515#ifdef DEBUG_GRPC_TIMING
516 myStopWatch[7].stop();
517#endif
518 }
519 const double speed = person->getSpeed();
520 for (int offset = 0; offset < 2; offset++) {
521 const WaypointDesc* const waypoint = state->getNextWaypoint(offset);
522 if (waypoint != nullptr && std::get<0>(*waypoint) != 0) {
523 const JPS_StageId waitingStage = std::get<0>(*waypoint);
524 auto& crossingState = myCrossings[waitingStage];
525 const MSLane* const crossing = crossingState.first;
526 const MSLink* link = crossing->getIncomingLanes().front().viaLink;
527 if (waitingStage == myCrossingWaits[crossing].second && link->getTLLogic() != nullptr) {
528 // we are walking backwards on a traffic light, there are different links to check
529 link = crossing->getLinkCont().front();
530 if (link->getTLLogic() == nullptr) {
531 link = crossing->getLogicalPredecessorLane()->getLinkTo(crossing);
532 }
533 }
534 // compare to and maybe adapt for MSPModel_Striping.cpp:1264
535 const double passingClearanceTime = person->getFloatParam("pedestrian.timegap-crossing");
536 const bool open = link->opened(time - DELTA_T, speed, speed, person->getVehicleType().getLength() + passingClearanceTime * speed,
537 person->getImpatience(), speed, 0, 0, nullptr, false, person);
538 if (open != crossingState.second) {
539 sumo_jupedsim_api::SetWaitingSetStateRequest waitingSetStateRequest;
540 waitingSetStateRequest.set_stage_id(waitingStage);
541 waitingSetStateRequest.set_state(open ? sumo_jupedsim_api::INACTIVE : sumo_jupedsim_api::ACTIVE);
542 callGrpc(&sumo_jupedsim_api::JuPedSimService::Stub::SetWaitingSetState, waitingSetStateRequest,
543 TLF("Error while setting waiting status for %:", crossing->getID()));
544 crossingState.second = open;
545 }
546 }
547 }
548 stage->activateMoveReminders(person, oldLanePos, state->getEdgePos(time), state->getSpeed(*stage));
549 // In the worst case during one SUMO step the person touches the waypoint radius and walks immediately into a different direction,
550 // but at some simstep it should have a maximum distance of v * delta_t / 2 to the waypoint circle.
551 const double slack = person->getMaxSpeed() * TS / 2. + POSITION_EPS;
552 if (newPosition.distanceTo2D(std::get<2>(*state->getNextWaypoint())) < std::get<3>(*state->getNextWaypoint()) + slack) {
553 // If near the last waypoint, remove the agent.
554 if (state->advanceNextWaypoint()) {
555 // TODO this only works if the final stage is actually a walk
556 const bool finalStage = person->getNumRemainingStages() == 1;
557 const JPS_AgentId agentID = state->getAgentId();
558 while (!stage->moveToNextEdge(person, time, 1, nullptr));
559 if (finalStage) {
560 registerArrived(agentID);
561 stateIt = myPedestrianStates.erase(stateIt);
562 continue;
563 }
564 }
565 }
566 ++stateIt;
567 }
568
569 // Remove pedestrians that are in a predefined area, at a predefined rate.
570 for (const auto& area : myAreas) {
571 sumo_jupedsim_api::GetAgentsInRegionRequest agentsRequest;
572 *agentsRequest.mutable_region() = area->areaBoundary;
573 const sumo_jupedsim_api::AgentIdsResponse agentsResponse = callGrpc(&sumo_jupedsim_api::JuPedSimService::Stub::GetAgentsInRegion,
574 agentsRequest, TL("Error while retrieving agents in area: "));
575 const int numAgents = agentsResponse.agent_ids_size();
576 if (numAgents == 0) {
577 continue;
578 }
579 if (area->areaType == "vanishing_area") {
580 const SUMOTime period = area->params.count("period") > 0 ? string2time(area->params.at("period")) : 1000;
581 const int nbrPeriodsCoveringTimestep = (int)ceil(TS / STEPS2TIME(period));
582 if (time - area->lastRemovalTime >= nbrPeriodsCoveringTimestep * period) {
583 for (int k = 0; k < MIN2(nbrPeriodsCoveringTimestep, numAgents); k++) {
584 const JPS_AgentId agentID = agentsResponse.agent_ids(k);
585 auto lambda = [agentID](const PState * const p) {
586 return p->getAgentId() == agentID;
587 };
588 std::vector<PState*>::const_iterator iterator = std::find_if(myPedestrianStates.begin(), myPedestrianStates.end(), lambda);
589 if (iterator != myPedestrianStates.end()) {
590 const PState* const state = *iterator;
591 MSPerson* const person = state->getPerson();
592 // Code below only works if the removal happens at the last stage.
593 const bool finalStage = person->getNumRemainingStages() == 1;
594 if (finalStage) {
595 WRITE_MESSAGEF(TL("Person '%' in vanishing area '%' was removed from the simulation."), person->getID(), area->id);
596 while (!state->getStage()->moveToNextEdge(person, time, 1, nullptr));
597 registerArrived(agentID);
598 myPedestrianStates.erase(iterator);
599 area->lastRemovalTime = time;
600 }
601 }
602 }
603 }
604 } else { // areaType == "influencer"
605 if (area->params.count("speed") == 0) {
606 continue;
607 }
608 const double newSpeed = StringUtils::toDouble(area->params.at("speed"));
609 sumo_jupedsim_api::SetDesiredSpeedRequest desiredSpeedRequest;
610 auto speeds = desiredSpeedRequest.mutable_desired_speeds();
611 for (int i = 0; i < numAgents; i++) {
612 (*speeds)[agentsResponse.agent_ids(i)] = newSpeed;
613 }
614 callGrpc(&sumo_jupedsim_api::JuPedSimService::Stub::SetDesiredSpeedOfAgents, desiredSpeedRequest,
615 TL("Error while setting desired speed for area: "));
616 }
617 }
618
619 // Add dynamically additional geometry from train carriages that are stopped.
620 const auto& stoppingPlaces = myNetwork->getStoppingPlaces(SumoXMLTag::SUMO_TAG_BUS_STOP);
621 std::vector<SUMOTrafficObject::NumericalID> allStoppedTrainIDs;
622 std::vector<const MSVehicle*> allStoppedTrains;
623 for (const auto& stop : stoppingPlaces) {
624 std::vector<const SUMOVehicle*> stoppedTrains = stop.second->getStoppedVehicles();
625 for (const SUMOVehicle* train : stoppedTrains) {
626 allStoppedTrainIDs.push_back(train->getNumericalID());
627 allStoppedTrains.push_back(dynamic_cast<const MSVehicle*>(train));
628 }
629 }
630 if (allStoppedTrainIDs != myAllStoppedTrainIDs) {
632 if (!allStoppedTrainIDs.empty()) {
633 std::vector<GEOSGeometry*> carriagePolygons;
634 std::vector<GEOSGeometry*> rampPolygons;
635 for (const MSVehicle* train : allStoppedTrains) {
636 if (train->getLeavingPersonNumber() > 0) {
637 const SUMOVTypeParameter& vTypeParam = train->getVehicleType().getParameter();
638 MSTrainHelper trainHelper = MSTrainHelper(train);
639 trainHelper.computeDoorPositions();
640 const std::vector<MSTrainHelper::Carriage*>& carriages = trainHelper.getCarriages();
641 for (const MSTrainHelper::Carriage* carriage : carriages) {
642 Position dir = carriage->front - carriage->back;
643 if (dir.length2D() == 0.0) {
644 continue;
645 }
646 dir.norm2D();
647 Position perp = Position(-dir.y(), dir.x());
648 // Create carriages geometry.
649 double p = trainHelper.getHalfWidth();
650 PositionVector carriageShape;
651 carriageShape.push_back(carriage->front + perp * p);
652 carriageShape.push_back(carriage->back + perp * p);
653 carriageShape.push_back(carriage->back - perp * p);
654 carriageShape.push_back(carriage->front - perp * p);
655 carriagePolygons.push_back(createGeometryFromShape(carriageShape));
656 // Create ramps geometry.
657 p += vTypeParam.maxPlatformDistance;
658 const double d = 0.5 * vTypeParam.carriageDoorWidth;
659 for (const Position& door : carriage->doorPositions) {
660 PositionVector rampShape;
661 rampShape.push_back(door - perp * p + dir * d);
662 rampShape.push_back(door - perp * p - dir * d);
663 rampShape.push_back(door + perp * p - dir * d);
664 rampShape.push_back(door + perp * p + dir * d);
665 rampPolygons.push_back(createGeometryFromShape(rampShape));
666 }
667 }
668 }
669 }
670 if (!carriagePolygons.empty()) {
671 GEOSGeometry* carriagesCollection = GEOSGeom_createCollection(GEOS_MULTIPOLYGON, carriagePolygons.data(), (unsigned int)carriagePolygons.size());
672 GEOSGeometry* rampsCollection = GEOSGeom_createCollection(GEOS_MULTIPOLYGON, rampPolygons.data(), (unsigned int)rampPolygons.size());
673 GEOSGeometry* carriagesAndRampsUnion = GEOSUnion(carriagesCollection, rampsCollection);
674 if (carriagesAndRampsUnion == nullptr) {
675 WRITE_WARNING(TL("Error while generating geometry for carriages."));
676 } else {
677 GEOSGeometry* pedestrianNetworkWithTrainsAndRamps = GEOSUnion(carriagesAndRampsUnion, myGEOSPedestrianNetworkLargestComponent);
678#ifdef DEBUG_GEOMETRY_GENERATION
679 //dumpGeometry(pedestrianNetworkWithTrainsAndRamps, "pedestrianNetworkWithTrainsAndRamps.wkt");
680#endif
681 int nbrComponents = 0;
682 double maxArea = 0.0;
683 double totalArea = 0.0;
684 const GEOSGeometry* pedestrianNetworkWithTrainsAndRampsLargestComponent = getLargestComponent(pedestrianNetworkWithTrainsAndRamps, nbrComponents, maxArea, totalArea);
685 if (nbrComponents > 1) {
686 WRITE_WARNINGF(TL("While generating geometry % connected components were detected, %% of total pedestrian area is covered by the largest."),
687 nbrComponents, maxArea / totalArea * 100.0, "%");
688 }
689#ifdef DEBUG_GEOMETRY_GENERATION
690 //dumpGeometry(pedestrianNetworkWithTrainsAndRampsLargestComponent, "pedestrianNetworkWithTrainsAndRamps.wkt");
691#endif
692 myJPSGeometryWithTrainsAndRamps = buildJPSGeometryFromGEOSGeometry(pedestrianNetworkWithTrainsAndRampsLargestComponent);
693 sumo_jupedsim_api::SwitchGeometryRequest switchRequest;
694 switchRequest.set_geometry_id(myJPSGeometryWithTrainsAndRamps);
695 callGrpc(&sumo_jupedsim_api::JuPedSimService::Stub::SwitchGeometry, switchRequest, TL("While switching to train geometry: "), true);
698 GEOSGeom_destroy(pedestrianNetworkWithTrainsAndRamps);
699 }
700 GEOSGeom_destroy(rampsCollection);
701 GEOSGeom_destroy(carriagesCollection);
702 }
703 } else {
705 sumo_jupedsim_api::SwitchGeometryRequest switchRequest;
706 switchRequest.set_geometry_id(myJPSGeometry);
707 callGrpc(&sumo_jupedsim_api::JuPedSimService::Stub::SwitchGeometry, switchRequest, TL("While switching to default geometry: "), true);
710 }
711 }
712 myAllStoppedTrainIDs = allStoppedTrainIDs;
713 }
714
715 return DELTA_T;
716}
717
718
721 sumo_jupedsim_api::RemoveAgentsRequest removeRequest;
722 removeRequest.add_agent_ids(agentID);
723#ifdef DEBUG_GRPC_TIMING
724 myStopWatch[5].start();
725#endif
726 callGrpc(&sumo_jupedsim_api::JuPedSimService::Stub::RemoveAgents, removeRequest, TL("Error while removing agent: "));
727#ifdef DEBUG_GRPC_TIMING
728 myStopWatch[5].stop();
729#endif
730}
731
732
737
738
739GEOSGeometry*
741 GEOSCoordSequence* coordinateSequence = convertToGEOSPoints(centerLine);
742 GEOSGeometry* lineString = GEOSGeom_createLineString(coordinateSequence);
743 GEOSGeometry* dilatedLineString = GEOSBufferWithStyle(lineString, width, GEOS_QUADRANT_SEGMENTS, capStyle, GEOSBUF_JOIN_ROUND, GEOS_MITRE_LIMIT);
744 GEOSGeom_destroy(lineString);
745 return dilatedLineString;
746}
747
748
749GEOSGeometry*
750MSPModel_JuPedSim::createGeometryFromShape(PositionVector shape, std::string junctionID, std::string shapeID, bool isInternalShape) {
751 // Corner case.
752 if (shape.size() == 1) {
753 WRITE_WARNINGF(TL("Polygon '%' at junction '%' will be skipped as it is just a point."), shapeID, junctionID);
754 return nullptr;
755 }
756 // Make sure the shape is closed.
757 if (shape.back() != shape.front()) {
758 shape.push_back(shape.front());
759 }
760 // Replace consecutive points that are equal with just one.
761 PositionVector cleanShape;
762 cleanShape.push_back(shape[0]);
763 PositionVector duplicates;
764 for (int i = 1; i < (int)shape.size(); i++) {
765 if (shape[i] != shape[i - 1]) {
766 cleanShape.push_back(shape[i]);
767 } else {
768 duplicates.push_back(shape[i]);
769 }
770 }
771 if (cleanShape.size() < shape.size()) {
772 WRITE_WARNINGF(TL("Polygon '%' at junction '%' had some equal consecutive points removed: %"), shapeID, junctionID, toString(duplicates, 9));
773 }
774 GEOSCoordSequence* coordinateSequence = convertToGEOSPoints(cleanShape);
775 GEOSGeometry* linearRing = GEOSGeom_createLinearRing(coordinateSequence);
776 GEOSGeometry* polygon = GEOSGeom_createPolygon(linearRing, nullptr, 0);
777
778 if (!GEOSisValid(polygon)) {
779 if (cleanShape.size() == 3) {
780 if (isInternalShape) {
781 WRITE_WARNINGF(TL("Polygon '%' at junction '%' has been dilated as it is just a segment."), shapeID, junctionID);
782 } else {
783 WRITE_WARNINGF(TL("Polygon '%' has been dilated as it is just a segment."), shapeID);
784 }
785 GEOSGeometry* lineString = GEOSGeom_createLineString(GEOSCoordSeq_clone(coordinateSequence));
786 GEOSGeom_destroy(polygon);
787 polygon = GEOSBufferWithStyle(lineString, GEOS_BUFFERED_SEGMENT_WIDTH, GEOS_QUADRANT_SEGMENTS, GEOSBUF_CAP_FLAT, GEOSBUF_JOIN_BEVEL, GEOS_MITRE_LIMIT);
788 GEOSGeom_destroy(lineString);
789 } else {
790 if (isInternalShape) {
791 WRITE_WARNINGF(TL("Polygon '%' at junction '%' has been replaced by its convex hull as it is not simple."), shapeID, junctionID);
792 GEOSGeometry* hull = GEOSConvexHull(polygon);
793 GEOSGeom_destroy(polygon);
794 polygon = GEOSBufferWithStyle(hull, POSITION_EPS, GEOS_QUADRANT_SEGMENTS, GEOSBUF_CAP_FLAT, GEOSBUF_JOIN_ROUND, GEOS_MITRE_LIMIT);;
795 } else {
796 WRITE_WARNINGF(TL("Polygon '%' at junction '%' will be skipped as it is not simple."), shapeID, junctionID);
797 polygon = nullptr;
798 }
799 }
800
801 return polygon;
802 }
803
804 // Some junctions need to be buffered a little so that edges are properly connected.
805 if (isInternalShape) {
806 polygon = GEOSBufferWithStyle(polygon, POSITION_EPS, GEOS_QUADRANT_SEGMENTS, GEOSBUF_CAP_FLAT, GEOSBUF_JOIN_ROUND, GEOS_MITRE_LIMIT);
807 }
808
809 return polygon;
810}
811
812
813static GEOSGeometry*
814checkGeometry(GEOSGeometry* old, GEOSGeometry* g) {
815 if (g == nullptr) {
816 throw ProcessError(TL("Simplification step failed."));
817 }
818 GEOSGeom_destroy(old);
819 return g;
820}
821
822
823static GEOSGeometry*
824simplifyMinDist(GEOSGeometry* g, double d, int maxIter) {
825 for (int i = 0; i < maxIter; i++) {
826 g = checkGeometry(g, GEOSTopologyPreserveSimplify(g, d / 2.));
827 /* flags = 0: make output valid, remove collapsed parts */
828 g = checkGeometry(g, GEOSGeom_setPrecision(g, d, 0));
829 double clearance;
830 GEOSMinimumClearance(g, &clearance);
831 if (clearance >= d) {
832 break;
833 }
834 g = checkGeometry(g, GEOSBufferWithStyle(g, -d / 2., 8, GEOSBUF_CAP_FLAT, GEOSBUF_JOIN_MITRE, 5.0));
835 g = checkGeometry(g, GEOSBufferWithStyle(g, d / 2., 8, GEOSBUF_CAP_FLAT, GEOSBUF_JOIN_MITRE, 5.0));
836 }
837 return g;
838}
839
840
841GEOSGeometry*
843 std::vector<GEOSGeometry*> walkableAreas;
844 for (const MSEdge* const edge : network->getEdgeControl().getEdges()) {
845 const MSLane* const lane = getSidewalk<MSEdge, MSLane>(edge);
846 if (lane != nullptr) {
847 GEOSGeometry* dilatedLane = nullptr;
848 if (edge->isWalkingArea()) {
849 dilatedLane = createGeometryFromShape(lane->getShape(), edge->getFromJunction()->getID(), edge->getID(), true);
850 } else if (edge->isCrossing()) {
851 const PositionVector* outlineShape = lane->getOutlineShape();
852 if (outlineShape != nullptr) {
853 // this is mainly to ensure that we have at least the "normal" crossing, see #15037
854 dilatedLane = createGeometryFromCenterLine(lane->getShape(), lane->getWidth() / 2.0, GEOSBUF_CAP_FLAT);
855 if (dilatedLane != nullptr) {
856 walkableAreas.push_back(dilatedLane);
857 }
858 dilatedLane = createGeometryFromShape(*outlineShape, edge->getFromJunction()->getID(), edge->getID(), true);
859 } else {
860 dilatedLane = createGeometryFromCenterLine(lane->getShape(), lane->getWidth() / 2.0, GEOSBUF_CAP_ROUND);
861 }
862 myCrossingWaits[lane] = {0, 0};
863 } else { // regular sidewalk
864 dilatedLane = createGeometryFromCenterLine(lane->getShape(), lane->getWidth() / 2.0 + POSITION_EPS, GEOSBUF_CAP_FLAT);
865 }
866 if (dilatedLane != nullptr) {
867 walkableAreas.push_back(dilatedLane);
868 }
869 }
870 }
871 for (const auto& junctionWithID : network->getJunctionControl()) {
872 const MSJunction* const junction = junctionWithID.second;
873 int pedEdgeCount = 0;
874 bool hasWalkingArea = false;
875 for (const ConstMSEdgeVector& edges : {
876 junction->getIncoming(), junction->getOutgoing()
877 }) {
878 for (const MSEdge* const edge : edges) {
879 if (edge->isWalkingArea()) {
880 hasWalkingArea = true;
881 break;
882 }
883 if (getSidewalk<MSEdge, MSLane>(edge) != nullptr) {
884 pedEdgeCount++;
885 }
886 }
887 if (hasWalkingArea) {
888 break;
889 }
890 }
891 if (!hasWalkingArea && pedEdgeCount > 1) {
892 // there is something to connect but no walking area, let's assume peds are allowed everywhere
893 GEOSGeometry* walkingAreaGeom = createGeometryFromShape(junction->getShape(), junction->getID(), junction->getID(), true);
894 if (walkingAreaGeom != nullptr) {
895 walkableAreas.push_back(walkingAreaGeom);
896 }
897 }
898 }
899
900 // Retrieve additional walkable areas and obstacles (walkable areas and obstacles in the sense of JuPedSim).
901 std::vector<GEOSGeometry*> additionalObstacles;
902 for (const auto& polygonWithID : myNetwork->getShapeContainer().getPolygons()) {
903 if (polygonWithID.second->getShapeType() == "jupedsim.walkable_area" || polygonWithID.second->getShapeType() == "taz") {
904 GEOSGeometry* walkableArea = createGeometryFromShape(polygonWithID.second->getShape(), std::string(""), polygonWithID.first);
905 if (walkableArea != nullptr) {
906 walkableAreas.push_back(walkableArea);
908 }
909 } else if (polygonWithID.second->getShapeType() == "jupedsim.obstacle") {
910 GEOSGeometry* additionalObstacle = createGeometryFromShape(polygonWithID.second->getShape(), std::string(""), polygonWithID.first);
911 if (additionalObstacle != nullptr) {
912 additionalObstacles.push_back(additionalObstacle);
913 }
914 }
915 }
916
917 // Take the union of all walkable areas.
918 GEOSGeometry* disjointWalkableAreas = GEOSGeom_createCollection(GEOS_MULTIPOLYGON, walkableAreas.data(), (unsigned int)walkableAreas.size());
919#ifdef DEBUG_GEOMETRY_GENERATION
920 // dumpGeometry(disjointWalkableAreas, "disjointWalkableAreas.wkt");
921#endif
922 GEOSGeometry* initialWalkableAreas = GEOSUnaryUnion(disjointWalkableAreas);
923#ifdef DEBUG_GEOMETRY_GENERATION
924 dumpGeometry(initialWalkableAreas, "initialWalkableAreas.wkt");
925#endif
926 GEOSGeom_destroy(disjointWalkableAreas);
927
928 // At last, remove additional obstacles from the merged walkable areas.
929 GEOSGeometry* disjointAdditionalObstacles = GEOSGeom_createCollection(GEOS_MULTIPOLYGON, additionalObstacles.data(), (unsigned int)additionalObstacles.size());
930#ifdef DEBUG_GEOMETRY_GENERATION
931 // dumpGeometry(disjointAdditionalObstacles, "disjointAdditionalObstacles.wkt");
932#endif
933 GEOSGeometry* additionalObstaclesUnion = GEOSUnaryUnion(disjointAdditionalObstacles); // Obstacles may overlap, e.g. if they were loaded from separate files.
934#ifdef DEBUG_GEOMETRY_GENERATION
935 dumpGeometry(additionalObstaclesUnion, "additionalObstaclesUnion.wkt");
936#endif
937 GEOSGeometry* finalWalkableAreas = GEOSDifference(initialWalkableAreas, additionalObstaclesUnion);
938#ifdef DEBUG_GEOMETRY_GENERATION
939 dumpGeometry(finalWalkableAreas, "finalWalkableAreas.wkt");
940#endif
941 GEOSGeom_destroy(initialWalkableAreas);
942 GEOSGeom_destroy(additionalObstaclesUnion);
943 GEOSGeom_destroy(disjointAdditionalObstacles);
944
945 if (!GEOSisSimple(finalWalkableAreas)) {
946 throw ProcessError(TL("Union of walkable areas minus union of obstacles is not a simple polygon."));
947 }
948
949 // TODO this does not simplify correctly for maxIter > 1 on the waypoints test network
950 // return simplifyMinDist(finalWalkableAreas, 0.03, 1);
951 return finalWalkableAreas;
952}
953
954
955GEOSCoordSequence*
957 GEOSCoordSequence* coordinateSequence = GEOSCoordSeq_create((unsigned int)shape.size(), 2);
958 for (int i = 0; i < (int)shape.size(); i++) {
959 GEOSCoordSeq_setX(coordinateSequence, i, shape[i].x());
960 GEOSCoordSeq_setY(coordinateSequence, i, shape[i].y());
961 }
962 return coordinateSequence;
963}
964
965
967MSPModel_JuPedSim::convertToSUMOPoints(const GEOSGeometry* geometry) {
968 PositionVector coordinateVector;
969 const GEOSCoordSequence* coordinateSequence = GEOSGeom_getCoordSeq(geometry);
970 unsigned int coordinateSequenceSize;
971 GEOSCoordSeq_getSize(coordinateSequence, &coordinateSequenceSize);
972 double x;
973 double y;
974 for (unsigned int i = 0; i < coordinateSequenceSize; i++) {
975 GEOSCoordSeq_getX(coordinateSequence, i, &x);
976 GEOSCoordSeq_getY(coordinateSequence, i, &y);
977 coordinateVector.push_back(Position(x, y));
978 }
979 return coordinateVector;
980}
981
982
983void
984MSPModel_JuPedSim::convertToJPSPoints(const GEOSGeometry* geometry, sumo_jupedsim_api::Polygon* into) {
985 const GEOSCoordSequence* coordinateSequence = GEOSGeom_getCoordSeq(geometry);
986 unsigned int coordinateSequenceSize;
987 GEOSCoordSeq_getSize(coordinateSequence, &coordinateSequenceSize);
988 double x;
989 double y;
990 // Remove the last point so that CGAL doesn't complain about the simplicity of the polygon downstream.
991 for (unsigned int i = 0; i < coordinateSequenceSize - 1; i++) {
992 GEOSCoordSeq_getX(coordinateSequence, i, &x);
993 GEOSCoordSeq_getY(coordinateSequence, i, &y);
994 sumo_jupedsim_api::Point* point = into->add_points();
995 point->set_x(x);
996 point->set_y(y);
997 }
998}
999
1000
1001double
1002MSPModel_JuPedSim::getLinearRingArea(const GEOSGeometry* linearRing) {
1003 double area;
1004 GEOSGeometry* linearRingAsPolygon = GEOSGeom_createPolygon(GEOSGeom_clone(linearRing), nullptr, 0);
1005 GEOSArea(linearRingAsPolygon, &area);
1006 GEOSGeom_destroy(linearRingAsPolygon);
1007 return area;
1008}
1009
1010
1011void
1012MSPModel_JuPedSim::removePolygonFromDrawing(const std::string& polygonId) {
1014}
1015
1016
1017void
1018MSPModel_JuPedSim::preparePolygonForDrawing(const GEOSGeometry* polygon, const std::string& polygonId, const RGBColor& color) {
1019 const GEOSGeometry* exterior = GEOSGetExteriorRing(polygon);
1020 bool added = myShapeContainer.addPolygon(polygonId, std::string("jupedsim.pedestrian_network"), color, 10.0, 0.0,
1021 std::string(), convertToSUMOPoints(exterior), false, true, 1.0);
1022 if (added) {
1023 std::vector<PositionVector> holes;
1024 int nbrInteriorRings = GEOSGetNumInteriorRings(polygon);
1025 if (nbrInteriorRings != -1) {
1026 for (int k = 0; k < nbrInteriorRings; k++) {
1027 const GEOSGeometry* linearRing = GEOSGetInteriorRingN(polygon, k);
1028 double area = getLinearRingArea(linearRing);
1029 if (area > GEOS_MIN_AREA) {
1030 holes.push_back(convertToSUMOPoints(linearRing));
1031 }
1032 }
1033 myShapeContainer.getPolygons().get(polygonId)->setHoles(holes);
1034 }
1035 }
1036}
1037
1038
1039const GEOSGeometry*
1040MSPModel_JuPedSim::getLargestComponent(const GEOSGeometry* polygon, int& nbrComponents, double& maxArea, double& totalArea) {
1041 nbrComponents = GEOSGetNumGeometries(polygon);
1042 const GEOSGeometry* largestComponent = nullptr;
1043 maxArea = 0.0;
1044 totalArea = 0.0;
1045 for (int i = 0; i < nbrComponents; i++) {
1046 const GEOSGeometry* componentPolygon = GEOSGetGeometryN(polygon, i);
1047 double area;
1048 GEOSArea(componentPolygon, &area);
1049 totalArea += area;
1050 if (area > maxArea) {
1051 maxArea = area;
1052 largestComponent = componentPolygon;
1053 }
1054 }
1055 return largestComponent;
1056}
1057
1058
1059int64_t
1061 sumo_jupedsim_api::CreateGeometryRequest geometryRequest;
1062 sumo_jupedsim_api::Polygon* boundary = geometryRequest.mutable_boundary();
1063
1064 // Handle the exterior polygon.
1065 const GEOSGeometry* exterior = GEOSGetExteriorRing(polygon);
1066 convertToJPSPoints(exterior, boundary);
1067
1068 // Handle the interior polygons (holes).
1069 int nbrInteriorRings = GEOSGetNumInteriorRings(polygon);
1070 if (nbrInteriorRings != -1) {
1071 for (int k = 0; k < nbrInteriorRings; k++) {
1072 const GEOSGeometry* linearRing = GEOSGetInteriorRingN(polygon, k);
1073 double area = getLinearRingArea(linearRing);
1074 if (area > GEOS_MIN_AREA) {
1075 sumo_jupedsim_api::Polygon* hole = geometryRequest.add_obstacles();
1076 convertToJPSPoints(linearRing, hole);
1077 }
1078 }
1079 }
1080 grpc::ClientContext geometryContext;
1081 sumo_jupedsim_api::CreateGeometryResponse geometryResponse;
1082 const grpc::Status geometryStatus = myGrpcStub->CreateGeometry(&geometryContext, geometryRequest, &geometryResponse);
1083 if (!geometryStatus.ok()) {
1084 WRITE_WARNINGF(TL("JuPedSim gRPC CreateGeometry failed: %"), geometryStatus.error_message());
1085 return -1;
1086 }
1087
1088 return geometryResponse.geometry_id();
1089}
1090
1091void
1092MSPModel_JuPedSim::dumpGeometry(const GEOSGeometry* polygon, const std::string& filename, bool useGeoCoordinates) {
1093 GEOSGeometry* polygonGeoCoordinates = nullptr;
1094 if (useGeoCoordinates) {
1095 const GEOSGeometry* exterior = GEOSGetExteriorRing(polygon);
1096 PositionVector exteriorPoints = convertToSUMOPoints(exterior);
1097 for (Position& position : exteriorPoints) {
1099 }
1100 const int nbrInteriorRings = GEOSGetNumInteriorRings(polygon);
1101 std::vector<GEOSGeometry*> holeRings;
1102 if (nbrInteriorRings != -1) {
1103 for (int k = 0; k < nbrInteriorRings; k++) {
1104 const GEOSGeometry* linearRing = GEOSGetInteriorRingN(polygon, k);
1105 PositionVector holePoints = convertToSUMOPoints(linearRing);
1106 for (Position& position : holePoints) {
1108 }
1109 GEOSCoordSequence* holeRingCoords = convertToGEOSPoints(holePoints);
1110 GEOSGeometry* holeRing = GEOSGeom_createLinearRing(holeRingCoords);
1111 holeRings.push_back(holeRing);
1112 }
1113 }
1114 GEOSCoordSequence* exteriorRingCoords = convertToGEOSPoints(exteriorPoints);
1115 GEOSGeometry* exteriorRing = GEOSGeom_createLinearRing(exteriorRingCoords);
1116 polygonGeoCoordinates = GEOSGeom_createPolygon(exteriorRing, holeRings.data(), nbrInteriorRings);
1117 }
1118 std::ofstream dumpFile;
1119 dumpFile.open(filename);
1120 GEOSWKTWriter* writer = GEOSWKTWriter_create();
1121 GEOSWKTWriter_setRoundingPrecision(writer, gPrecisionGeo);
1122 char* wkt = GEOSWKTWriter_write(writer, polygonGeoCoordinates == nullptr ? polygon : polygonGeoCoordinates);
1123 dumpFile << wkt << std::endl;
1124 dumpFile.close();
1125 GEOSFree(wkt);
1126 GEOSWKTWriter_destroy(writer);
1127 GEOSGeom_destroy(polygonGeoCoordinates);
1128}
1129
1130
1131double
1133 return 0.5 * MAX2(vehType.getLength(), vehType.getWidth());
1134}
1135
1136
1138MSPModel_JuPedSim::addWaitingSet(const MSLane* const crossing, const bool entry) {
1139 PositionVector shape = crossing->getShape();
1140 const double radius = getRadius(*MSNet::getInstance()->getVehicleControl().getVType(DEFAULT_PEDTYPE_ID, nullptr, true));
1141 shape.extrapolate2D((shape.length() + radius) / shape.length());
1142 const double offset = 2 * radius + POSITION_EPS;
1143 const double lonOffset = entry ? NUMERICAL_EPS : shape.length() - NUMERICAL_EPS;
1144 PositionVector pv;
1145 pv.push_back(shape.positionAtOffset(lonOffset));
1146 for (double latOff = offset; latOff < crossing->getWidth() / 2. - offset; latOff += offset) {
1147 PositionVector moved(shape);
1148 moved.move2side(latOff);
1149 pv.push_back(moved.positionAtOffset(lonOffset));
1150 moved.move2side(-2. * latOff);
1151 pv.push_back(moved.positionAtOffset(lonOffset));
1152 }
1153 if (entry && crossing->getIncomingLanes().size() == 1 && crossing->getIncomingLanes().front().lane->isWalkingArea()) {
1154 pv.push_back(crossing->getIncomingLanes().front().lane->getShape().getCentroid());
1155 }
1156 if (!entry && crossing->getLinkCont().size() == 1 && crossing->getLinkCont().front()->getLane()->isWalkingArea()) {
1157 pv.push_back(crossing->getLinkCont().front()->getLane()->getShape().getCentroid());
1158 }
1159
1160 sumo_jupedsim_api::AddWaitingSetStageRequest waitingSetRequest;
1161 for (const Position& p : pv) {
1162 GEOSCoordSequence* seq = GEOSCoordSeq_create(1, 2); // 1 point, 2 dimensions
1163 GEOSCoordSeq_setX(seq, 0, p.x());
1164 GEOSCoordSeq_setY(seq, 0, p.y());
1165 GEOSGeometry* geosPoint = GEOSGeom_createPoint(seq);
1166 if (GEOSContains(myGEOSPedestrianNetworkLargestComponent, geosPoint)) {
1167 sumo_jupedsim_api::Point* point = waitingSetRequest.add_points();
1168 point->set_x(p.x());
1169 point->set_y(p.y());
1170 } else {
1171 WRITE_WARNINGF("Waiting point %,% is not in the geometry for % on '%'.", p.x(), p.y(), entry ? "entry" : "exit", crossing->getID())
1172 }
1173 GEOSGeom_destroy(geosPoint);
1174 }
1175#ifdef DEBUG_GRPC_TIMING
1176 myStopWatch[6].start();
1177#endif
1178 auto waitingSetResponse = callGrpc(&sumo_jupedsim_api::JuPedSimService::Stub::AddWaitingSetStage, waitingSetRequest,
1179 TLF("Error while adding waiting set for % on '%':", entry ? "entry" : "exit", crossing->getID()));
1180#ifdef DEBUG_GRPC_TIMING
1181 myStopWatch[6].stop();
1182#endif
1183 JPS_StageId waitingStage = waitingSetResponse.stage_id();
1184
1185 sumo_jupedsim_api::SetWaitingSetStateRequest waitingSetStateRequest;
1186 waitingSetStateRequest.set_stage_id(waitingStage);
1187 waitingSetStateRequest.set_state(sumo_jupedsim_api::INACTIVE);
1188 callGrpc(&sumo_jupedsim_api::JuPedSimService::Stub::SetWaitingSetState, waitingSetStateRequest,
1189 TLF("Error while setting waiting status for % on '%':", entry ? "entry" : "exit", crossing->getID()));
1190
1191 myCrossings[waitingStage] = {crossing, true};
1192 return waitingStage;
1193}
1194
1195
1196void
1198 initGEOS(nullptr, nullptr);
1199 PROGRESS_BEGIN_MESSAGE("Generating initial JuPedSim geometry for pedestrian network");
1201 int nbrComponents = 0;
1202 double maxArea = 0.0;
1203 double totalArea = 0.0;
1205 if (nbrComponents > 1) {
1206 WRITE_WARNINGF(TL("While generating geometry % connected components were detected, %% of total pedestrian area is covered by the largest."),
1207 nbrComponents, maxArea / totalArea * 100.0, "%");
1208 }
1209#ifdef DEBUG_GEOMETRY_GENERATION
1210 dumpGeometry(myGEOSPedestrianNetworkLargestComponent, "pedestrianNetwork.wkt");
1211#endif
1212 const std::string filename = oc.getString("pedestrian.jupedsim.wkt");
1213 if (!filename.empty()) {
1214 dumpGeometry(myGEOSPedestrianNetworkLargestComponent, filename, oc.getBool("pedestrian.jupedsim.wkt.geo"));
1215 }
1216 // For the moment, only one connected component is supported.
1221
1222 double strengthGeometryRepulsion = oc.getFloat("pedestrian.jupedsim.strength-geometry-repulsion");
1223 double rangeGeometryRepulsion = oc.getFloat("pedestrian.jupedsim.range-geometry-repulsion");
1224 if (myJPSDeltaT == 20) {
1225 if (oc.isDefault("pedestrian.jupedsim.strength-geometry-repulsion") && oc.isDefault("pedestrian.jupedsim.range-geometry-repulsion")) {
1226 WRITE_MESSAGE(TL("Adapting geometry repulsion default values for jupedsim timestep of 0.02."));
1227 strengthGeometryRepulsion = 35.;
1228 rangeGeometryRepulsion = 0.019;
1229 }
1230 }
1231 sumo_jupedsim_api::CreateSimulationRequest simulationRequest;
1232 simulationRequest.set_geometry_id(myJPSGeometry);
1233 simulationRequest.set_model_class(myJPSModel);
1234 simulationRequest.set_delta_t(STEPS2TIME(myJPSDeltaT));
1235 // Default server side arguments for the models.
1236 // TODO: Better handling of this as this is still hard-coded for each model class.
1237 auto& modelParams = *simulationRequest.mutable_model_parameters()->mutable_fields();
1238 if (myJPSModel == "CollisionFreeSpeedModel") {
1239 modelParams["strength_neighbor_repulsion"].set_number_value(oc.getFloat("pedestrian.jupedsim.strength-neighbor-repulsion"));
1240 modelParams["range_neighbor_repulsion"].set_number_value(oc.getFloat("pedestrian.jupedsim.range-neighbor-repulsion"));
1241 modelParams["strength_geometry_repulsion"].set_number_value(strengthGeometryRepulsion);
1242 modelParams["range_geometry_repulsion"].set_number_value(rangeGeometryRepulsion);
1243 } else if (myJPSModel == "CollisionFreeSpeedModelV2") {
1244 // Empty - did not set any parameters in old implementation
1245 } else if (myJPSModel == "GeneralizedCentrifugalForceModel") {
1246 if (oc.isDefault("pedestrian.jupedsim.strength-neighbor-repulsion")) {
1247 modelParams["strength_neighbor_repulsion"].set_number_value(0.3);
1248 } else {
1249 modelParams["strength_neighbor_repulsion"].set_number_value(oc.getFloat("pedestrian.jupedsim.strength-neighbor-repulsion"));
1250 }
1251 if (oc.isDefault("pedestrian.jupedsim.strength-geometry-repulsion")) {
1252 strengthGeometryRepulsion = 0.2;
1253 }
1254 modelParams["strength_geometry_repulsion"].set_number_value(strengthGeometryRepulsion);
1255 } else if (myJPSModel == "SocialForceModel") {
1256 modelParams["body_force"].set_number_value(120000.0);
1257 modelParams["friction"].set_number_value(240000.0);
1258 }
1259 grpc::ClientContext simulationContext;
1260 sumo_jupedsim_api::CreateSimulationResponse simulationResponse;
1261 const grpc::Status simulationStatus = myGrpcStub->CreateSimulation(&simulationContext, simulationRequest, &simulationResponse);
1262 if (simulationStatus.ok()) {
1263 myJPSSimulation = simulationResponse.simulation_id();
1264 } else {
1265 throw ProcessError(TLF("JuPedSim gRPC CreateSimulation failed: %", simulationStatus.error_message()));
1266 }
1267 // Polygons that define vanishing areas aren't part of the regular JuPedSim geometry.
1268 for (const auto& polygonWithID : myNetwork->getShapeContainer().getPolygons()) {
1269 polygonChanged(polygonWithID.second, true, false);
1270 }
1272}
1273
1274
1275void
1276MSPModel_JuPedSim::polygonChanged(const SUMOPolygon* const poly, const bool added, const bool removed) {
1277 if (poly->getShapeType() == "jupedsim.vanishing_area" || poly->getShapeType() == "jupedsim.influencer") {
1278 SUMOTime lastRemovalTime = 0;
1279 if (!added) {
1280 for (auto areaIt = myAreas.begin(); areaIt != myAreas.end(); ++areaIt) {
1281 if (poly->getID() == (*areaIt)->id) {
1282 lastRemovalTime = (*areaIt)->lastRemovalTime;
1283 myAreas.erase(areaIt);
1284 break;
1285 }
1286 }
1287 }
1288 if (!removed) {
1289 sumo_jupedsim_api::Polygon areaBoundary;
1290 for (const Position& p : poly->getShape()) {
1291 sumo_jupedsim_api::Point* point = areaBoundary.add_points();
1292 point->set_x(p.x());
1293 point->set_y(p.y());
1294 }
1295 // // Make sure the shape is not repeating the first point.
1296 // if (areaBoundary.back().x == areaBoundary.front().x && areaBoundary.back().y == areaBoundary.front().y) {
1297 // areaBoundary.pop_back();
1298 // }
1299 const std::string type = StringTokenizer(poly->getShapeType(), ".").getVector()[1];
1300 myAreas.emplace_back(std::unique_ptr<AreaData>(new AreaData{poly->getID(), type, areaBoundary, poly->getParametersMap(), lastRemovalTime}));
1301 }
1302 }
1303}
1304
1305
1306// ===========================================================================
1307// MSPModel_Remote::PState method definitions
1308// ===========================================================================
1310 JPS_JourneyId journeyId, JPS_StageId stageId,
1311 const std::vector<WaypointDesc>& waypoints) :
1312 MSPModel_InteractingState(person, stage, nullptr),
1313 myJourneyId(journeyId), myStageId(stageId), myWaypoints(waypoints), myAgentId(0) {
1314 myDir = FORWARD;
1315}
1316
1317
1318void
1320 const std::vector<WaypointDesc>& waypoints) {
1321 if (myStage != nullptr) {
1322 myStage->setPState(nullptr); // we need to remove the old state reference to avoid double deletion
1323 }
1324 myStage = stage;
1325 myJourneyId = journeyId;
1326 myStageId = stageId;
1327 myWaypoints = waypoints;
1328}
1329
1330
1333
1334
1335void MSPModel_JuPedSim::PState::setPosition(const double x, const double y, const double z) {
1336 if (myRemoteXYPos != Position::INVALID) {
1337 mySpeed = myRemoteXYPos.distanceTo2D(Position(x, y, z)) / STEPS2TIME(DELTA_T);
1338 } else {
1339 mySpeed = 0.;
1340 }
1341 myRemoteXYPos.set(x, y, z);
1342}
1343
1344
1346 return stage.getNextRouteEdge();
1347}
1348
1349
1352 return offset < (int)myWaypoints.size() ? &myWaypoints[offset] : nullptr;
1353}
1354
1355
1356/****************************************************************************/
long long int SUMOTime
Definition GUI.h:36
std::vector< const MSEdge * > ConstMSEdgeVector
Definition MSEdge.h:75
static GEOSGeometry * checkGeometry(GEOSGeometry *old, GEOSGeometry *g)
static GEOSGeometry * simplifyMinDist(GEOSGeometry *g, double d, int maxIter)
#define WRITE_WARNINGF(...)
Definition MsgHandler.h:299
#define WRITE_MESSAGEF(...)
Definition MsgHandler.h:301
#define WRITE_MESSAGE(msg)
Definition MsgHandler.h:300
#define WRITE_WARNING(msg)
Definition MsgHandler.h:298
#define TL(string)
Definition MsgHandler.h:316
#define PROGRESS_DONE_MESSAGE()
Definition MsgHandler.h:303
#define TLF(string,...)
Definition MsgHandler.h:318
#define PROGRESS_BEGIN_MESSAGE(msg)
Definition MsgHandler.h:302
SUMOTime DELTA_T
Definition SUMOTime.cpp:39
SUMOTime string2time(const std::string &r)
convert string to SUMOTime
Definition SUMOTime.cpp:47
std::string time2string(SUMOTime t, bool humanReadable)
convert SUMOTime to string (independently of global format setting)
Definition SUMOTime.cpp:107
#define STEPS2TIME(x)
Definition SUMOTime.h:58
#define SIMSTEP
Definition SUMOTime.h:69
#define TS
Definition SUMOTime.h:45
const std::string DEFAULT_PEDTYPE_ID
@ RANDOM_LOCATION
The position may be chosen freely in a polygon defined by a taz.
@ SUMO_TAG_BUS_STOP
A bus stop.
int gPrecisionGeo
Definition StdDefs.cpp:29
const double SUMO_const_laneWidth
Definition StdDefs.h:52
T MIN2(T a, T b)
Definition StdDefs.h:80
T MAX2(T a, T b)
Definition StdDefs.h:86
std::string toString(const T &t, std::streamsize accuracy=gPrecision)
Definition ToString.h:57
A class that stores a 2D geometrical boundary.
Definition Boundary.h:39
double ymin() const
Returns minimum y-coordinate.
Definition Boundary.cpp:127
double xmin() const
Returns minimum x-coordinate.
Definition Boundary.cpp:115
double ymax() const
Returns maximum y-coordinate.
Definition Boundary.cpp:133
double xmax() const
Returns maximum x-coordinate.
Definition Boundary.cpp:121
static const GeoConvHelper & getFinal()
the coordinate transformation for writing the location element and for tracking the original coordina...
void cartesian2geo(Position &cartesian) const
Converts the given cartesian (shifted) position to its geo (lat/long) representation.
const MSEdgeVector & getEdges() const
Returns loaded edges.
A road/street connecting two junctions.
Definition MSEdge.h:78
const std::vector< MSLane * > & getLanes() const
Returns this edge's lanes.
Definition MSEdge.h:169
bool isNormal() const
return whether this edge is an internal edge
Definition MSEdge.h:265
const MSJunction * getToJunction() const
Definition MSEdge.h:428
double getLength() const
return the length of the edge
Definition MSEdge.h:695
const MSJunction * getFromJunction() const
Definition MSEdge.h:424
bool isTazConnector() const
Definition MSEdge.h:293
double getWidth() const
Returns the edges's width (sum over all lanes)
Definition MSEdge.h:666
virtual void addEvent(Command *operation, SUMOTime execTimeStep=-1)
Adds an Event.
The base class for an intersection.
Definition MSJunction.h:58
const ConstMSEdgeVector & getOutgoing() const
Definition MSJunction.h:114
const PositionVector & getShape() const
Returns this junction's shape.
Definition MSJunction.h:91
const ConstMSEdgeVector & getIncoming() const
Definition MSJunction.h:108
Representation of a lane in the micro simulation.
Definition MSLane.h:84
const MSLink * getLinkTo(const MSLane *const) const
returns the link to the given lane or nullptr, if it is not connected
Definition MSLane.cpp:2801
double getSpeedLimit() const
Returns the lane's maximum allowed speed.
Definition MSLane.h:602
bool isWalkingArea() const
Definition MSLane.cpp:2693
const std::vector< IncomingLaneInfo > & getIncomingLanes() const
Definition MSLane.h:984
MSLane * getLogicalPredecessorLane() const
get the most likely predecessor lane (sorted using by_connections_to_sorter). The result is cached in...
Definition MSLane.cpp:3271
virtual const PositionVector & getShape(bool) const
Definition MSLane.h:294
MSEdge & getEdge() const
Returns the lane's edge.
Definition MSLane.h:790
const PositionVector * getOutlineShape() const
Definition MSLane.h:1394
double getWidth() const
Returns the lane's width.
Definition MSLane.h:661
const std::vector< MSLink * > & getLinkCont() const
returns the container with all links !!!
Definition MSLane.h:750
The simulated network and simulation perfomer.
Definition MSNet.h:90
static MSNet * getInstance()
Returns the pointer to the unique instance of MSNet (singleton).
Definition MSNet.cpp:201
MSEventControl * getBeginOfTimestepEvents()
Returns the event control for events executed at the begin of a time step.
Definition MSNet.h:496
MSJunctionControl & getJunctionControl()
Returns the junctions control.
Definition MSNet.h:486
MSPedestrianRouter & getPedestrianRouter(int rngIndex, const Prohibitions &prohibited={}) const
Definition MSNet.cpp:1715
SUMOTime getCurrentTimeStep() const
Returns the current simulation step.
Definition MSNet.h:335
ShapeContainer & getShapeContainer()
Returns the shapes container.
Definition MSNet.h:526
MSEdgeControl & getEdgeControl()
Returns the edge control.
Definition MSNet.h:446
const NamedObjectCont< MSStoppingPlace * > & getStoppingPlaces(SumoXMLTag category) const
Definition MSNet.cpp:1578
ActiveLanes myActiveLanes
store of all lanes which have pedestrians on them
int myNumActivePedestrians
the total number of active pedestrians
Container for pedestrian state and individual position update function.
MSStageMoving * getStage() const
return the current stage
int myDir
the walking direction on the current lane (1 forward, -1 backward)
virtual double getAngle(const MSStageMoving &, SUMOTime) const
return the current orientation in degrees
double getEdgePos(SUMOTime) const
abstract methods inherited from MSTransportableStateAdapter
MSPerson * getPerson() const
return the represented person
bool isWaitingToEnter() const
whether the person still waits to entere the network
const MSLane * getLane() const
the current lane of the transportable
double getSpeed() const
return the current speed of the transportable, we need to be able to do this for vehicles as well,...
Holds pedestrian state and performs updates.
JPS_StageId getStageId() const
first stage of the journey
JPS_AgentId getAgentId() const
void setStage(MSStageMoving *const stage)
void setAgentId(JPS_AgentId id)
const MSPModel_JuPedSim::WaypointDesc * getNextWaypoint(const int offset=0) const
void setLanePosition(double lanePosition)
const MSEdge * getNextEdge(const MSStageMoving &stage) const override
return the list of internal edges if the transportable is on an intersection
JPS_JourneyId getJourneyId() const
PState(MSPerson *person, MSStageMoving *stage, JPS_JourneyId journeyId, JPS_StageId stageId, const std::vector< WaypointDesc > &waypoints)
void reinit(MSStageMoving *stage, JPS_JourneyId journeyId, JPS_StageId stageId, const std::vector< WaypointDesc > &waypoints)
Position getPosition(const MSStageMoving &, SUMOTime) const override
return the network coordinate of the transportable
void setPosition(const double x, const double y, const double z=0.)
int64_t buildJPSGeometryFromGEOSGeometry(const GEOSGeometry *polygon)
MSTransportableStateAdapter * add(MSTransportable *person, MSStageMoving *stage, SUMOTime now) override
register the given person as a pedestrian
void removePolygonFromDrawing(const std::string &polygonId)
const GEOSGeometry * myGEOSPedestrianNetworkLargestComponent
The GEOS polygon representing the largest (by area) connected component of the pedestrian network.
void preparePolygonForDrawing(const GEOSGeometry *polygon, const std::string &polygonId, const RGBColor &color)
static const RGBColor PEDESTRIAN_NETWORK_CARRIAGES_AND_RAMPS_COLOR
MSPModel_JuPedSim(const OptionsCont &oc, MSNet *net)
static const double GEOS_MITRE_LIMIT
const double myExitTolerance
Threshold to decide if a pedestrian has ended its journey or not.
std::vector< SUMOTrafficObject::NumericalID > myAllStoppedTrainIDs
Array of stopped trains, used to detect whether to add carriages and ramps to the geometry.
void registerArrived(const JPS_AgentId agentID)
static GEOSGeometry * createGeometryFromCenterLine(PositionVector centerLine, double width, int capStyle)
static PositionVector convertToSUMOPoints(const GEOSGeometry *geometry)
static const std::string PEDESTRIAN_NETWORK_CARRIAGES_AND_RAMPS_ID
static const RGBColor PEDESTRIAN_NETWORK_COLOR
static const std::string PEDESTRIAN_NETWORK_ID
std::map< const MSLane *, JPS_StageId, ComparatorNumericalIdLess > myLaneCenters
static GEOSGeometry * createGeometryFromShape(PositionVector shape, std::string junctionID=std::string(""), std::string shapeID=std::string(""), bool isInternalShape=false)
static GEOSCoordSequence * convertToGEOSPoints(PositionVector shape)
int64_t myJPSGeometry
The JPS polygon representing the largest connected component of the pedestrian network.
GEOSGeometry * myGEOSPedestrianNetwork
The GEOS polygon containing all computed connected components of the pedestrian network.
static void convertToJPSPoints(const GEOSGeometry *geometry, sumo_jupedsim_api::Polygon *into)
static void dumpGeometry(const GEOSGeometry *polygon, const std::string &filename, bool useGeoCoordinates=false)
std::map< const MSLane *, std::pair< JPS_StageId, JPS_StageId >, ComparatorNumericalIdLess > myCrossingWaits
const SUMOTime myJPSDeltaT
Timestep used in the JuPedSim simulator.
MSNet *const myNetwork
The network on which the simulation runs.
std::shared_ptr< grpc::Channel > myGrpcChannel
void polygonChanged(const SUMOPolygon *const poly, const bool added, const bool removed) override
static const double GEOS_MIN_AREA
void initialize(const OptionsCont &oc)
GEOSGeometry * buildPedestrianNetwork(MSNet *network)
void remove(MSTransportableStateAdapter *state) override
remove the specified person from the pedestrian simulation
std::vector< StopWatch< std::chrono::nanoseconds > > myStopWatch
std::vector< std::unique_ptr< AreaData > > myAreas
Array of special areas.
static double getLinearRingArea(const GEOSGeometry *linearRing)
std::unique_ptr< sumo_jupedsim_api::JuPedSimService::Stub > myGrpcStub
SumoRNG myRNG
The random number generator for fluctuations on insertion.
std::tuple< JPS_StageId, const MSLane *, Position, double > WaypointDesc
void clearState() override
Resets pedestrians when quick-loading state.
Response callGrpc(grpc::Status(sumo_jupedsim_api::JuPedSimService::Stub::*method)(grpc::ClientContext *, const Request &, Response *), Request &request, const std::string &what, const bool warnOnly=false)
ShapeContainer & myShapeContainer
The shape container used to add polygons to the rendering pipeline.
std::vector< PState * > myPedestrianStates
JPS_StageId addWaitingSet(const MSLane *const crossing, const bool entry)
int64_t myJPSGeometryWithTrainsAndRamps
The JPS polygon representing the largest connected component plus carriages and ramps.
static const int GEOS_QUADRANT_SEGMENTS
static const std::vector< MSPModel_JuPedSim::PState * > noPedestrians
static const GEOSGeometry * getLargestComponent(const GEOSGeometry *polygon, int &nbrComponents, double &maxArea, double &totalArea)
static double getRadius(const MSVehicleType &vehType)
JPS_StageId addWaypoint(const std::string &agentID, WaypointDesc &waypoint, const MSStageMoving *const finalStage)
void tryPedestrianInsertion(PState *state, const Position &p)
SUMOTime execute(SUMOTime time)
static const double GEOS_BUFFERED_SEGMENT_WIDTH
std::map< JPS_StageId, std::pair< const MSLane *, bool > > myCrossings
static const int BACKWARD
Definition MSPModel.h:55
static const int FORWARD
Definition MSPModel.h:54
static const double RANDOM_POS_LAT
magic value to encode randomized lateral offset for persons when starting a walk
Definition MSPModel.h:68
static const int UNDEFINED_DIRECTION
Definition MSPModel.h:56
static const double UNSPECIFIED_POS_LAT
the default lateral offset for persons when starting a walk
Definition MSPModel.h:65
double getImpatience() const
Definition MSPerson.cpp:245
const MSEdge * getDestination() const
returns the destination edge
Definition MSStage.cpp:65
virtual double getArrivalPos() const
Definition MSStage.h:97
virtual const MSEdge * getEdge() const
Returns the current edge.
Definition MSStage.cpp:71
virtual const MSEdge * getNextRouteEdge() const =0
ConstMSEdgeVector getEdges() const
the edges of the current stage
const std::vector< const MSEdge * > & getRoute() const
void setPState(MSTransportableStateAdapter *pstate)
double getDepartPosLat() const
const MSEdge * getEdge() const
Returns the current edge.
double getDepartPos() const
const std::vector< constMSEdge * >::iterator getRouteStep() const
virtual bool moveToNextEdge(MSTransportable *transportable, SUMOTime currentTime, int prevDir, MSEdge *nextInternal=nullptr, const bool isReplay=false)=0
move forward and return whether the transportable arrived
virtual double getMaxSpeed(const MSTransportable *const transportable=nullptr) const =0
the maximum speed of the transportable
bool moveToNextEdge(MSTransportable *person, SUMOTime currentTime, int prevDir, MSEdge *nextInternal=nullptr, const bool isReplay=false)
move forward and return whether the person arrived
void activateMoveReminders(MSTransportable *person, double oldPos, double newPos, double newSpeed)
void activateEntryReminders(MSTransportable *person, const bool isDepart=false)
add the move reminders for the current lane on entry
A class that helps computing positions of a train's carriages and additional structures.
void computeDoorPositions()
compute door positions on demand and fills the carriage structures
const std::vector< Carriage * > & getCarriages() const
double getHalfWidth() const
virtual double getSpeed() const override
the current speed of the transportable
MSStage * getNextStage(int offset) const
Return the next (or previous) stage denoted by the offset.
int getNumRemainingStages() const
Return the number of remaining stages (including the current)
MSStage * getCurrentStage() const
Return the current stage.
SUMOVehicleClass getVClass() const override
Returns the object's access class.
double getMaxSpeed() const override
Returns the maximum speed (the minimum of desired and physical maximum speed)
const SUMOVTypeParameter & getVTypeParameter() const override
Returns the object's "vehicle" type parameter.
int getCurrentStageIndex() const
Return the index of the current stage.
MSStageType getCurrentStageType() const
the current stage type of the transportable
const SUMOVehicleParameter & getParameter() const override
Returns the vehicle's parameter (including departure definition)
const MSVehicleType & getVehicleType() const override
Returns the object's "vehicle" type.
const MSEdge * getEdge() const override
Returns the current edge.
abstract base class for managing callbacks to retrieve various state information from the model
Definition MSPModel.h:159
Representation of a vehicle in the micro simulation.
Definition MSVehicle.h:77
The car-following model and parameter.
double getWidth() const
Get the width which vehicles of this class shall have when being drawn.
double getLength() const
Get vehicle's length [m].
const std::string & getID() const
Returns the id.
Definition Named.h:73
T get(const std::string &id) const
Retrieves an item.
A storage for options typed value containers)
Definition OptionsCont.h:92
bool isSet(const std::string &name, bool failOnNonExistant=true) const
Returns the information whether the named option is set.
double getFloat(const std::string &name) const
Returns the double-value of the named option (only for Option_Float)
std::string getString(const std::string &name) const
Returns the string-value of the named option (only for Option_String)
bool isDefault(const std::string &name) const
Returns the information whether the named option has still the default value.
bool getBool(const std::string &name) const
Returns the boolean-value of the named option (only for Option_Bool)
static OptionsCont & getOptions()
Retrieves the options.
double getDouble(const std::string &key, const double defaultValue) const
Returns the value for a given key converted to a double.
virtual const std::string getParameter(const std::string &key, const std::string defaultValue="") const
Returns the value for a given key.
const Parameterised::Map & getParametersMap() const
Returns the inner key/value map.
double compute(const E *from, const E *to, double departPos, double arrivalPos, double speed, SUMOTime msTime, const N *onlyNode, const SUMOVTypeParameter &pars, std::vector< const E * > &into, bool allEdges=false) const
Builds the route between the given edges using the minimum effort at the given time The definition of...
A point in 2D or 3D with translation and scaling methods.
Definition Position.h:37
void setx(double x)
set position x
Definition Position.h:67
static const Position INVALID
used to indicate that a position is valid
Definition Position.h:323
double distanceTo2D(const Position &p2) const
returns the euclidean distance in the x-y-plane
Definition Position.h:273
void norm2D()
Normalizes the given vector.
Definition Position.h:179
double x() const
Returns the x-position.
Definition Position.h:52
double length2D() const
Computes the length of the given vector neglecting the z coordinate.
Definition Position.h:174
void sety(double y)
set position y
Definition Position.h:72
double y() const
Returns the y-position.
Definition Position.h:57
A list of positions.
double length() const
Returns the length.
double rotationAtOffset(double pos) const
Returns the rotation at the given length.
Position positionAtOffset(double pos, double lateralOffset=0) const
Returns the position at the given length.
void move2side(double amount, double maxExtension=100)
move position vector to side using certain amount
Boundary getBoxBoundary() const
Returns a boundary enclosing this list of lines.
Position getCentroid() const
Returns the centroid (closes the polygon if unclosed)
void extrapolate2D(const double val, const bool onlyFirst=false)
extrapolate position vector in two dimensions (Z is ignored)
bool around(const Position &p, double offset=0) const
Returns the information whether the position vector describes a polygon lying around the given point.
static double rand(SumoRNG *rng=nullptr)
Returns a random real number in [0, 1)
const PositionVector & getShape() const
Returns the shape of the polygon.
virtual void setHoles(const std::vector< PositionVector > &holes)
Sets the holes of the polygon.
double getFloatParam(const std::string &paramName, const bool required=false, const double deflt=INVALID_DOUBLE, bool checkDist=true) const
Retrieve a floating point parameter for the traffic object.
Structure representing possible vehicle parameter.
double maxPlatformDistance
the maximum distance between platform and train
double carriageDoorWidth
the width of the carriage doors
Representation of a vehicle.
Definition SUMOVehicle.h:63
DepartPosDefinition departPosProcedure
Information how the vehicle shall choose the departure position.
void addShapeListener(ShapeListener *listener)
virtual bool removePolygon(const std::string &id, bool useLock=true)
Removes a polygon from the container.
const Polygons & getPolygons() const
Returns all polygons.
virtual bool addPolygon(const std::string &id, const std::string &type, const RGBColor &color, double layer, double angle, const std::string &imgFile, const PositionVector &shape, bool geo, bool fill, double lineWidth, bool ignorePruning=false, const std::string &name=Shape::DEFAULT_NAME)
Builds a polygon using the given values and adds it to the container.
const std::string & getShapeType() const
Returns the (abstract) type of the Shape.
Definition Shape.cpp:99
std::vector< std::string > getVector()
return vector of strings
static double toDouble(const std::string &sData)
converts a string into the double value described by it by calling the char-type converter
static void initRandGlobal(SumoRNG *which=nullptr)
Reads the given random number options and initialises the random number generator in accordance.
static bool moveToXYMap_matchingRoutePosition(const Position &pos, const std::string &origID, const ConstMSEdgeVector &currentRoute, int routeIndex, SUMOVehicleClass vClass, bool setLateralPos, double &bestDistance, MSLane **lane, double &lanePos, int &routeOffset)
Definition Helper.cpp:1781
static int getFreeSocketPort()
Returns an free port on the system.
Definition socket.cpp:118
#define UNUSED_PARAMETER(x)
#define M_PI
Definition odrSpiral.cpp:45
Structure that keeps data related to vanishing areas (and other types of areas).