Eclipse SUMO - Simulation of Urban MObility
Loading...
Searching...
No Matches
MSPModel_JuPedSim_legacy.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>
30#include <jupedsim/jupedsim.h>
32#include <microsim/MSEdge.h>
33#include <microsim/MSLane.h>
34#include <microsim/MSLink.h>
41#include <libsumo/Helper.h>
42#include <utils/geom/Position.h>
46#include "MSPerson.h"
47#include "MSStageWalking.h"
49
50
51// #define DEBUG_GEOMETRY_GENERATION
52
53
60const std::string MSPModel_JuPedSim_legacy::PEDESTRIAN_NETWORK_ID = "jupedsim.pedestrian_network";
61const std::string MSPModel_JuPedSim_legacy::PEDESTRIAN_NETWORK_CARRIAGES_AND_RAMPS_ID = "jupedsim.pedestrian_network.carriages_and_ramps";
62
63const std::vector<MSPModel_JuPedSim_legacy::PState*> MSPModel_JuPedSim_legacy::noPedestrians;
64
65// ===========================================================================
66// method definitions
67// ===========================================================================
69 myRNG("JuPedSim_legacy"), myNetwork(net), myShapeContainer(net->getShapeContainer()), myJPSDeltaT(string2time(oc.getString("pedestrian.jupedsim.step-length"))),
70 myExitTolerance(oc.getFloat("pedestrian.jupedsim.exit-tolerance")), myGEOSPedestrianNetworkLargestComponent(nullptr),
71 myHaveAdditionalWalkableAreas(false) {
73 const std::string model = oc.getString("pedestrian.jupedsim.model");
74 if (model == "CollisionFreeSpeed" || model == "CollisionFreeSpeedModel") {
76 } else if (model == "CollisionFreeSpeedV2" || model == "CollisionFreeSpeedModelV2") {
78 } else if (model == "GeneralizedCentrifugalForce" || model == "GeneralizedCentrifugalForceModel") {
80 } else if (model == "SocialForce" || model == "SocialForceModel") {
82 } else {
83 throw ProcessError(TLF("Unknown JuPedSim model '%'.", model));
84 }
85 initialize(oc);
87}
88
89
91 clearState();
92 if (myPythonScript != nullptr) {
93 (*myPythonScript) << "while simulation.agent_count() > 0 and simulation.iteration_count() < 160 * 100: simulation.iterate()\n";
94 }
95
96 JPS_Simulation_Free(myJPSSimulation);
97 JPS_OperationalModel_Free(myJPSOperationalModel);
98 JPS_Geometry_Free(myJPSGeometry);
99 if (myJPSGeometryWithTrainsAndRamps != nullptr) {
100 JPS_Geometry_Free(myJPSGeometryWithTrainsAndRamps);
101 }
102
103 GEOSGeom_destroy(myGEOSPedestrianNetwork);
104 finishGEOS();
105}
106
107
108void
110 const MSVehicleType& type = state->getPerson()->getVehicleType();
111
112 const double angle = state->getAngle(*state->getStage(), 0);
113 JPS_Point orientation;
114 if (fabs(angle - M_PI / 2) < NUMERICAL_EPS) {
115 orientation = JPS_Point{0., 1.};
116 } else if (fabs(angle + M_PI / 2) < NUMERICAL_EPS) {
117 orientation = JPS_Point{0., -1.};
118 } else {
119 orientation = JPS_Point{1., tan(angle)};
120 }
121
122 JPS_AgentId agentId = 0;
123 JPS_ErrorMessage message = nullptr;
124
125 switch (myJPSModel) {
127 JPS_CollisionFreeSpeedModelAgentParameters agentParameters{};
128 agentParameters.position = {p.x(), p.y()};
129 agentParameters.journeyId = state->getJourneyId();
130 agentParameters.stageId = state->getStageId();
131 agentParameters.v0 = state->getPerson()->getMaxSpeed();
132 agentParameters.radius = getRadius(type);
133 agentId = JPS_Simulation_AddCollisionFreeSpeedModelAgent(myJPSSimulation, agentParameters, &message);
134 break;
135 }
137 JPS_CollisionFreeSpeedModelV2AgentParameters agentParameters{};
138 agentParameters.position = {p.x(), p.y()};
139 agentParameters.journeyId = state->getJourneyId();
140 agentParameters.stageId = state->getStageId();
141 agentParameters.v0 = state->getPerson()->getMaxSpeed();
142 agentParameters.radius = getRadius(type);
143 agentId = JPS_Simulation_AddCollisionFreeSpeedModelV2Agent(myJPSSimulation, agentParameters, &message);
144 break;
145 }
147 JPS_GeneralizedCentrifugalForceModelAgentParameters agentParameters{};
148 agentParameters.position = {p.x(), p.y()};
149 agentParameters.orientation = orientation;
150 agentParameters.journeyId = state->getJourneyId();
151 agentParameters.stageId = state->getStageId();
152 agentParameters.v0 = state->getPerson()->getMaxSpeed();
153 agentId = JPS_Simulation_AddGeneralizedCentrifugalForceModelAgent(myJPSSimulation, agentParameters, &message);
154 break;
155 }
157 JPS_SocialForceModelAgentParameters agentParameters{};
158 agentParameters.position = {p.x(), p.y()};
159 agentParameters.orientation = orientation;
160 agentParameters.journeyId = state->getJourneyId();
161 agentParameters.stageId = state->getStageId();
162 agentParameters.desiredSpeed = state->getPerson()->getMaxSpeed();
163 agentParameters.radius = getRadius(type);
164 agentId = JPS_Simulation_AddSocialForceModelAgent(myJPSSimulation, agentParameters, &message);
165 break;
166 }
167 }
168 if (message != nullptr) {
169 WRITE_WARNINGF(TL("Error while adding person '%' as JuPedSim agent: %"), state->getPerson()->getID(), JPS_ErrorMessage_GetMessage(message));
170 JPS_ErrorMessage_Free(message);
171 } else {
172 state->setAgentId(agentId);
173 }
174}
175
176
177bool
178MSPModel_JuPedSim_legacy::addStage(JPS_JourneyDescription journey, JPS_StageId& predecessor, const std::string& agentID, const JPS_StageId stage) {
179 JPS_ErrorMessage message = nullptr;
180 if (predecessor != 0) {
181 const JPS_Transition transition = JPS_Transition_CreateFixedTransition(stage, &message);
182 if (message != nullptr) {
183 WRITE_WARNINGF(TL("Error while creating fixed transition for person '%': %"), agentID, JPS_ErrorMessage_GetMessage(message));
184 JPS_ErrorMessage_Free(message);
185 return false;
186 }
187 JPS_JourneyDescription_SetTransitionForStage(journey, predecessor, transition, &message);
188 if (message != nullptr) {
189 WRITE_WARNINGF(TL("Error while setting transition for person '%': %"), agentID, JPS_ErrorMessage_GetMessage(message));
190 JPS_ErrorMessage_Free(message);
191 return false;
192 }
193 JPS_Transition_Free(transition);
194 }
195 JPS_JourneyDescription_AddStage(journey, stage);
196 predecessor = stage;
197 return true;
198}
199
200
201bool
202MSPModel_JuPedSim_legacy::addWaypoint(JPS_JourneyDescription journey, JPS_StageId& predecessor, const std::string& agentID, const WaypointDesc& waypoint) {
203 JPS_ErrorMessage message = nullptr;
204 const Position& coords = std::get<1>(waypoint);
205 const JPS_StageId waypointId = JPS_Simulation_AddStageWaypoint(myJPSSimulation, {coords.x(), coords.y()},
206 std::get<2>(waypoint), &message);
207 if (message != nullptr) {
208 WRITE_WARNINGF(TL("Error while adding waypoint for person '%': %"), agentID, JPS_ErrorMessage_GetMessage(message));
209 JPS_ErrorMessage_Free(message);
210 return false;
211 }
212 const JPS_StageId waiting = std::get<0>(waypoint);
213 if (waiting != 0) {
214 if (myPythonScript != nullptr) {
215 (*myPythonScript) << "journey.add(" << waiting << ")\n";
216 if (predecessor != 0) {
217 (*myPythonScript) << "journey.set_transition_for_stage(" << predecessor << ", jps.Transition.create_fixed_transition(" << waiting << "))\n";
218 }
219 }
220 if (!addStage(journey, predecessor, agentID, waiting)) {
221 return false;
222 }
223 }
224 if (myPythonScript != nullptr) {
225 (*myPythonScript) << "ws = simulation.add_waypoint_stage((" << coords.x() << "," << coords.y() << "), " << std::get<2>(waypoint) << ")\n"
226 "journey.add(ws)\n";
227 if (predecessor != 0) {
228 (*myPythonScript) << "journey.set_transition_for_stage(" << predecessor << ", jps.Transition.create_fixed_transition(ws))\n";
229 }
230 }
231 if (!addStage(journey, predecessor, agentID, waypointId)) {
232 return false;
233 }
234 return true;
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]->getShape().getCentroid(), wa->getWidth() / 2.});
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->getShape().positionAtOffset(e->getLength() / 2.), lane->getWidth() / 2.});
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 const MSLane* const arrivalLane = getSidewalk<MSEdge, MSLane>(stage->getDestination());
342 const Position arrivalPosition = arrivalLane->getShape().positionAtOffset(stage->getArrivalPos());
343 waypoints.push_back({finalWait, arrivalPosition, stage->getDouble("jupedsim.waypoint.radius", myExitTolerance)});
344
345 JPS_JourneyDescription journeyDesc = JPS_JourneyDescription_Create();
346 if (myPythonScript != nullptr) {
347 (*myPythonScript) << "\njourney = jps.JourneyDescription()\n";
348 }
349 JPS_StageId startingStage = 0;
350 JPS_StageId predecessor = 0;
351 for (const auto& p : waypoints) {
352 if (!addWaypoint(journeyDesc, predecessor, person->getID(), p)) {
353 JPS_JourneyDescription_Free(journeyDesc);
354 return nullptr;
355 }
356 if (startingStage == 0) {
357 startingStage = std::get<0>(waypoints.front()) == 0 ? predecessor : std::get<0>(waypoints.front());
358 }
359 }
360 JPS_ErrorMessage message = nullptr;
361 JPS_JourneyId journeyId = JPS_Simulation_AddJourney(myJPSSimulation, journeyDesc, &message);
362 JPS_JourneyDescription_Free(journeyDesc);
363 if (message != nullptr) {
364 WRITE_WARNINGF(TL("Error while adding a journey for person '%': %"), person->getID(), JPS_ErrorMessage_GetMessage(message));
365 JPS_ErrorMessage_Free(message);
366 return nullptr;
367 }
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 if (myPythonScript != nullptr) {
390 (*myPythonScript) << "journey_id = simulation.add_journey(journey)\n"
391 "simulation.add_agent(jps.CollisionFreeSpeedModelAgentParameters(journey_id=journey_id,stage_id="
392 << startingStage << ",position=(" << departurePosition.x() << "," << departurePosition.y()
393 << "),radius=" << getRadius(person->getVehicleType()) << ",v0=" << person->getMaxSpeed() << "))\n";
394 }
395 } else {
396 JPS_Simulation_SwitchAgentJourney(myJPSSimulation, state->getAgentId(), journeyId, startingStage, &message);
397 if (message != nullptr) {
398 WRITE_WARNINGF(TL("Error while switching to a new journey for person '%': %"), person->getID(), JPS_ErrorMessage_GetMessage(message));
399 JPS_ErrorMessage_Free(message);
400 return nullptr;
401 }
402 }
403 return state;
404}
405
406
407void
409 PState* pstate = static_cast<PState*>(state);
410 if (pstate->getLane() != nullptr) {
411 auto& peds = myActiveLanes[pstate->getLane()];
412 peds.erase(std::find(peds.begin(), peds.end(), pstate));
413 pstate->setLane(nullptr);
414 }
415 if (pstate->getStage() != nullptr) {
416 pstate->getStage()->setPState(nullptr); // we need to remove the old state reference to avoid double deletion
417 }
418 pstate->setStage(nullptr);
419}
420
421
424 const int nbrIterations = (int)(DELTA_T / myJPSDeltaT);
425 JPS_ErrorMessage message = nullptr;
426 for (int i = 0; i < nbrIterations; ++i) {
427 // Perform one JuPedSim iteration.
428 bool ok = JPS_Simulation_Iterate(myJPSSimulation, &message);
429 if (!ok) {
430 WRITE_ERRORF(TL("Error during iteration %: %"), i, JPS_ErrorMessage_GetMessage(message));
431 }
432 }
433
434 // Update the state of all pedestrians.
435 // If necessary, this could be done more often in the loop above but the more precise positions are probably never visible.
436 // If it is needed for model correctness (precise stopping / arrivals) we should rather reduce SUMO's step-length.
437 for (auto stateIt = myPedestrianStates.begin(); stateIt != myPedestrianStates.end();) {
438 PState* const state = *stateIt;
439
440 if (state->isWaitingToEnter()) {
441 // insertion failed at first try so we retry with some noise
442 Position p = state->getPosition(*state->getStage(), time);
443 p.setx(p.x() + RandHelper::rand(-.5, .5, &myRNG)); // we do this separately to avoid evaluation order problems
444 p.sety(p.y() + RandHelper::rand(-.5, .5, &myRNG));
445 tryPedestrianInsertion(state, p);
446 ++stateIt;
447 continue;
448 }
449
450 MSPerson* const person = state->getPerson();
451 MSStageWalking* const stage = dynamic_cast<MSStageWalking*>(person->getCurrentStage());
452 if (stage == nullptr) {
453 // It seems we kept the state for another stage but the new stage is not a walk.
454 // So let's remove the state because after the new stage we will be elsewhere and need to be reinserted for JuPedSim anyway.
455 // We cannot check this earlier because when the old stage ends the next stage might not know yet whether it will be a walk.
456 registerArrived(state->getAgentId());
457 stateIt = myPedestrianStates.erase(stateIt);
458 continue;
459 }
460
461 // Updates the agent position.
462 const JPS_Agent agent = JPS_Simulation_GetAgent(myJPSSimulation, state->getAgentId(), nullptr);
463 const JPS_Point position = JPS_Agent_GetPosition(agent);
464 state->setPosition(position.x, position.y);
465
466 // Updates the agent direction.
467 const JPS_Point orientation = JPS_Agent_GetOrientation(agent);
468 state->setAngle(atan2(orientation.y, orientation.x));
469
470 // Find on which edge the pedestrian is, using route's forward-looking edges because of how moveToXY is written.
471 Position newPosition(position.x, position.y);
472 ConstMSEdgeVector route = stage->getEdges();
473 const int routeIndex = (int)(stage->getRouteStep() - stage->getRoute().begin());
474 const double oldLanePos = state->getEdgePos(time);
475 ConstMSEdgeVector forwardRoute = ConstMSEdgeVector(route.begin() + routeIndex, route.end());
476 double bestDistance = std::numeric_limits<double>::max();
477 MSLane* candidateLane = nullptr;
478 double candidateLaneLongitudinalPosition = 0.0;
479 int routeOffset = 0;
480 const bool found = libsumo::Helper::moveToXYMap_matchingRoutePosition(newPosition, "",
481 forwardRoute, 0, person->getVClass(), true, bestDistance, &candidateLane, candidateLaneLongitudinalPosition, routeOffset);
482
483 if (found) {
484 if (candidateLane != state->getLane()) {
485 if (state->getLane() != nullptr) {
486 auto& peds = myActiveLanes[state->getLane()];
487 peds.erase(std::find(peds.begin(), peds.end(), state));
488 }
489 myActiveLanes[candidateLane].push_back(state);
490 state->setLane(candidateLane);
491 }
492 state->setLanePosition(candidateLaneLongitudinalPosition);
493 }
494
495 const MSEdge* const expectedEdge = stage->getEdge();
496 if (found && expectedEdge->isNormal() && candidateLane->getEdge().isNormal() && &candidateLane->getEdge() != expectedEdge) {
497 const bool arrived = stage->moveToNextEdge(person, time, 1, nullptr);
498 UNUSED_PARAMETER(arrived);
499 assert(!arrived); // The person has not arrived yet.
500 stage->activateEntryReminders(person);
501 // Adapt speed to lane's speed limit.
502 const double newMaxSpeed = MIN2(candidateLane->getSpeedLimit(), person->getMaxSpeed());
503 switch (myJPSModel) {
505 JPS_CollisionFreeSpeedModelState modelState = JPS_Agent_GetCollisionFreeSpeedModelState(agent, nullptr);
506 if (newMaxSpeed != JPS_CollisionFreeSpeedModelState_GetV0(modelState)) {
507 JPS_CollisionFreeSpeedModelState_SetV0(modelState, newMaxSpeed);
508 }
509 break;
510 }
512 JPS_CollisionFreeSpeedModelV2State modelState = JPS_Agent_GetCollisionFreeSpeedModelV2State(agent, nullptr);
513 if (newMaxSpeed != JPS_CollisionFreeSpeedModelV2State_GetV0(modelState)) {
514 JPS_CollisionFreeSpeedModelV2State_SetV0(modelState, newMaxSpeed);
515 }
516 break;
517 }
519 JPS_GeneralizedCentrifugalForceModelState modelState = JPS_Agent_GetGeneralizedCentrifugalForceModelState(agent, nullptr);
520 if (newMaxSpeed != JPS_GeneralizedCentrifugalForceModelState_GetV0(modelState)) {
521 JPS_GeneralizedCentrifugalForceModelState_SetV0(modelState, newMaxSpeed);
522 }
523 break;
524 }
526 JPS_SocialForceModelState modelState = JPS_Agent_GetSocialForceModelState(agent, nullptr);
527 if (newMaxSpeed != JPS_SocialForceModelState_GetDesiredSpeed(modelState)) {
528 JPS_SocialForceModelState_SetDesiredSpeed(modelState, newMaxSpeed);
529 }
530 break;
531 }
532 }
533 }
534 const double speed = person->getSpeed();
535 for (int offset = 0; offset < 2; offset++) {
536 const WaypointDesc* const waypoint = state->getNextWaypoint(offset);
537 if (waypoint != nullptr && std::get<0>(*waypoint) != 0) {
538 const JPS_StageId waitingStage = std::get<0>(*waypoint);
539 const MSLane* const crossing = myCrossings[waitingStage];
540 const MSLink* link = crossing->getIncomingLanes().front().viaLink;
541 if (waitingStage == myCrossingWaits[crossing].second && link->getTLLogic() != nullptr) {
542 // we are walking backwards on a traffic light, there are different links to check
543 link = crossing->getLinkCont().front();
544 if (link->getTLLogic() == nullptr) {
545 link = crossing->getLogicalPredecessorLane()->getLinkTo(crossing);
546 }
547 }
548 // compare to and maybe adapt for MSPModel_Striping.cpp:1264
549 const double passingClearanceTime = person->getFloatParam("pedestrian.timegap-crossing");
550 const bool open = link->opened(time - DELTA_T, speed, speed, person->getVehicleType().getLength() + passingClearanceTime * speed,
551 person->getImpatience(), speed, 0, 0, nullptr, false, person);
552 const auto proxy = JPS_Simulation_GetWaitingSetProxy(myJPSSimulation, waitingStage, &message);
553 JPS_WaitingSetProxy_SetWaitingSetState(proxy, open ? JPS_WaitingSet_Inactive : JPS_WaitingSet_Active);
554 }
555 }
556 stage->activateMoveReminders(person, oldLanePos, state->getEdgePos(time), state->getSpeed(*stage));
557 // In the worst case during one SUMO step the person touches the waypoint radius and walks immediately into a different direction,
558 // but at some simstep it should have a maximum distance of v * delta_t / 2 to the waypoint circle.
559 const double slack = person->getMaxSpeed() * TS / 2. + POSITION_EPS;
560 if (newPosition.distanceTo2D(std::get<1>(*state->getNextWaypoint())) < std::get<2>(*state->getNextWaypoint()) + slack) {
561 // If near the last waypoint, remove the agent.
562 if (state->advanceNextWaypoint()) {
563 // TODO this only works if the final stage is actually a walk
564 const bool finalStage = person->getNumRemainingStages() == 1;
565 const JPS_AgentId agentID = state->getAgentId();
566 while (!stage->moveToNextEdge(person, time, 1, nullptr));
567 if (finalStage) {
568 registerArrived(agentID);
569 stateIt = myPedestrianStates.erase(stateIt);
570 continue;
571 }
572 }
573 }
574 ++stateIt;
575 }
576
577 // Remove pedestrians that are in a predefined area, at a predefined rate.
578 for (const auto& area : myAreas) {
579 const std::vector<JPS_Point>& areaBoundary = area->areaBoundary;
580 JPS_AgentIdIterator agentsInArea = JPS_Simulation_AgentsInPolygon(myJPSSimulation, areaBoundary.data(), areaBoundary.size());
581 if (area->areaType == "vanishing_area") {
582 const SUMOTime period = area->params.count("period") > 0 ? string2time(area->params.at("period")) : 1000;
583 const int nbrPeriodsCoveringTimestep = (int)ceil(TS / STEPS2TIME(period));
584 if (time - area->lastRemovalTime >= nbrPeriodsCoveringTimestep * period) {
585 for (int k = 0; k < nbrPeriodsCoveringTimestep; k++) {
586 const JPS_AgentId agentID = JPS_AgentIdIterator_Next(agentsInArea);
587 if (agentID != 0) {
588 auto lambda = [agentID](const PState * const p) {
589 return p->getAgentId() == agentID;
590 };
591 std::vector<PState*>::const_iterator iterator = std::find_if(myPedestrianStates.begin(), myPedestrianStates.end(), lambda);
592 if (iterator != myPedestrianStates.end()) {
593 const PState* const state = *iterator;
594 MSPerson* const person = state->getPerson();
595 // Code below only works if the removal happens at the last stage.
596 const bool finalStage = person->getNumRemainingStages() == 1;
597 if (finalStage) {
598 WRITE_MESSAGEF(TL("Person '%' in vanishing area '%' was removed from the simulation."), person->getID(), area->id);
599 while (!state->getStage()->moveToNextEdge(person, time, 1, nullptr));
600 registerArrived(agentID);
601 myPedestrianStates.erase(iterator);
602 area->lastRemovalTime = time;
603 }
604 }
605 }
606 }
607 }
608 } else { // areaType == "influencer"
609 for (JPS_AgentId agentID = JPS_AgentIdIterator_Next(agentsInArea); agentID != 0; agentID = JPS_AgentIdIterator_Next(agentsInArea)) {
610 if (area->params.count("speed") > 0) {
611 const JPS_Agent agent = JPS_Simulation_GetAgent(myJPSSimulation, agentID, nullptr);
612 const double newMaxSpeed = StringUtils::toDouble(area->params.at("speed"));
613 switch (myJPSModel) {
615 JPS_CollisionFreeSpeedModelState modelState = JPS_Agent_GetCollisionFreeSpeedModelState(agent, nullptr);
616 if (newMaxSpeed != JPS_CollisionFreeSpeedModelState_GetV0(modelState)) {
617 JPS_CollisionFreeSpeedModelState_SetV0(modelState, newMaxSpeed);
618 }
619 break;
620 }
622 JPS_CollisionFreeSpeedModelV2State modelState = JPS_Agent_GetCollisionFreeSpeedModelV2State(agent, nullptr);
623 if (newMaxSpeed != JPS_CollisionFreeSpeedModelV2State_GetV0(modelState)) {
624 JPS_CollisionFreeSpeedModelV2State_SetV0(modelState, newMaxSpeed);
625 }
626 break;
627 }
629 JPS_GeneralizedCentrifugalForceModelState modelState = JPS_Agent_GetGeneralizedCentrifugalForceModelState(agent, nullptr);
630 if (newMaxSpeed != JPS_GeneralizedCentrifugalForceModelState_GetV0(modelState)) {
631 JPS_GeneralizedCentrifugalForceModelState_SetV0(modelState, newMaxSpeed);
632 }
633 break;
634 }
636 JPS_SocialForceModelState modelState = JPS_Agent_GetSocialForceModelState(agent, nullptr);
637 if (newMaxSpeed != JPS_SocialForceModelState_GetDesiredSpeed(modelState)) {
638 JPS_SocialForceModelState_SetDesiredSpeed(modelState, newMaxSpeed);
639 }
640 break;
641 }
642 }
643 }
644 }
645 }
646 JPS_AgentIdIterator_Free(agentsInArea);
647 }
648
649 // Add dynamically additional geometry from train carriages that are stopped.
650 const auto& stoppingPlaces = myNetwork->getStoppingPlaces(SumoXMLTag::SUMO_TAG_BUS_STOP);
651 std::vector<SUMOTrafficObject::NumericalID> allStoppedTrainIDs;
652 std::vector<const MSVehicle*> allStoppedTrains;
653 for (const auto& stop : stoppingPlaces) {
654 std::vector<const SUMOVehicle*> stoppedTrains = stop.second->getStoppedVehicles();
655 for (const SUMOVehicle* train : stoppedTrains) {
656 allStoppedTrainIDs.push_back(train->getNumericalID());
657 allStoppedTrains.push_back(dynamic_cast<const MSVehicle*>(train));
658 }
659 }
660 if (allStoppedTrainIDs != myAllStoppedTrainIDs) {
662 if (!allStoppedTrainIDs.empty()) {
663 std::vector<GEOSGeometry*> carriagePolygons;
664 std::vector<GEOSGeometry*> rampPolygons;
665 for (const MSVehicle* train : allStoppedTrains) {
666 if (train->getLeavingPersonNumber() > 0) {
667 const SUMOVTypeParameter& vTypeParam = train->getVehicleType().getParameter();
668 MSTrainHelper trainHelper = MSTrainHelper(train);
669 trainHelper.computeDoorPositions();
670 const std::vector<MSTrainHelper::Carriage*>& carriages = trainHelper.getCarriages();
671 for (const MSTrainHelper::Carriage* carriage : carriages) {
672 Position dir = carriage->front - carriage->back;
673 if (dir.length2D() == 0.0) {
674 continue;
675 }
676 dir.norm2D();
677 Position perp = Position(-dir.y(), dir.x());
678 // Create carriages geometry.
679 double p = trainHelper.getHalfWidth();
680 PositionVector carriageShape;
681 carriageShape.push_back(carriage->front + perp * p);
682 carriageShape.push_back(carriage->back + perp * p);
683 carriageShape.push_back(carriage->back - perp * p);
684 carriageShape.push_back(carriage->front - perp * p);
685 carriagePolygons.push_back(createGeometryFromShape(carriageShape));
686 // Create ramps geometry.
687 p += vTypeParam.maxPlatformDistance;
688 const double d = 0.5 * vTypeParam.carriageDoorWidth;
689 for (const Position& door : carriage->doorPositions) {
690 PositionVector rampShape;
691 rampShape.push_back(door - perp * p + dir * d);
692 rampShape.push_back(door - perp * p - dir * d);
693 rampShape.push_back(door + perp * p - dir * d);
694 rampShape.push_back(door + perp * p + dir * d);
695 rampPolygons.push_back(createGeometryFromShape(rampShape));
696 }
697 }
698 }
699 }
700 if (!carriagePolygons.empty()) {
701 GEOSGeometry* carriagesCollection = GEOSGeom_createCollection(GEOS_MULTIPOLYGON, carriagePolygons.data(), (unsigned int)carriagePolygons.size());
702 GEOSGeometry* rampsCollection = GEOSGeom_createCollection(GEOS_MULTIPOLYGON, rampPolygons.data(), (unsigned int)rampPolygons.size());
703 GEOSGeometry* carriagesAndRampsUnion = GEOSUnion(carriagesCollection, rampsCollection);
704 if (carriagesAndRampsUnion == nullptr) {
705 WRITE_WARNING(TL("Error while generating geometry for carriages."));
706 } else {
707 GEOSGeometry* pedestrianNetworkWithTrainsAndRamps = GEOSUnion(carriagesAndRampsUnion, myGEOSPedestrianNetworkLargestComponent);
708#ifdef DEBUG_GEOMETRY_GENERATION
709 //dumpGeometry(pedestrianNetworkWithTrainsAndRamps, "pedestrianNetworkWithTrainsAndRamps.wkt");
710#endif
711 int nbrComponents = 0;
712 double maxArea = 0.0;
713 double totalArea = 0.0;
714 const GEOSGeometry* pedestrianNetworkWithTrainsAndRampsLargestComponent = getLargestComponent(pedestrianNetworkWithTrainsAndRamps, nbrComponents, maxArea, totalArea);
715 if (nbrComponents > 1) {
716 WRITE_WARNINGF(TL("While generating geometry % connected components were detected, %% of total pedestrian area is covered by the largest."),
717 nbrComponents, maxArea / totalArea * 100.0, "%");
718 }
719#ifdef DEBUG_GEOMETRY_GENERATION
720 //dumpGeometry(pedestrianNetworkWithTrainsAndRampsLargestComponent, "pedestrianNetworkWithTrainsAndRamps.wkt");
721#endif
722 myJPSGeometryWithTrainsAndRamps = buildJPSGeometryFromGEOSGeometry(pedestrianNetworkWithTrainsAndRampsLargestComponent);
723 const bool ok = JPS_Simulation_SwitchGeometry(myJPSSimulation, myJPSGeometryWithTrainsAndRamps, nullptr, &message);
724 if (!ok) {
725 WRITE_WARNINGF(TL("While switching to train geometry: %"), JPS_ErrorMessage_GetMessage(message));
726 }
729 GEOSGeom_destroy(pedestrianNetworkWithTrainsAndRamps);
730 }
731 GEOSGeom_destroy(rampsCollection);
732 GEOSGeom_destroy(carriagesCollection);
733 }
734 } else {
735 if (myJPSGeometryWithTrainsAndRamps != nullptr) {
736 const bool ok = JPS_Simulation_SwitchGeometry(myJPSSimulation, myJPSGeometry, nullptr, &message);
737 if (!ok) {
738 WRITE_WARNINGF(TL("While switching to default geometry: %"), JPS_ErrorMessage_GetMessage(message));
739 }
742 }
743 }
744 myAllStoppedTrainIDs = allStoppedTrainIDs;
745 }
746
747 JPS_ErrorMessage_Free(message);
748
749 return DELTA_T;
750}
751
752
753void MSPModel_JuPedSim_legacy::registerArrived(const JPS_AgentId agentID) {
755 JPS_Simulation_MarkAgentForRemoval(myJPSSimulation, agentID, nullptr);
756}
757
758
763
764
765GEOSGeometry*
767 GEOSCoordSequence* coordinateSequence = convertToGEOSPoints(centerLine);
768 GEOSGeometry* lineString = GEOSGeom_createLineString(coordinateSequence);
769 GEOSGeometry* dilatedLineString = GEOSBufferWithStyle(lineString, width, GEOS_QUADRANT_SEGMENTS, capStyle, GEOSBUF_JOIN_ROUND, GEOS_MITRE_LIMIT);
770 GEOSGeom_destroy(lineString);
771 return dilatedLineString;
772}
773
774
775GEOSGeometry*
776MSPModel_JuPedSim_legacy::createGeometryFromShape(PositionVector shape, std::string junctionID, std::string shapeID, bool isInternalShape) {
777 // Corner case.
778 if (shape.size() == 1) {
779 WRITE_WARNINGF(TL("Polygon '%' at junction '%' will be skipped as it is just a point."), shapeID, junctionID);
780 return nullptr;
781 }
782 // Make sure the shape is closed.
783 if (shape.back() != shape.front()) {
784 shape.push_back(shape.front());
785 }
786 // Replace consecutive points that are equal with just one.
787 PositionVector cleanShape;
788 cleanShape.push_back(shape[0]);
789 PositionVector duplicates;
790 for (int i = 1; i < (int)shape.size(); i++) {
791 if (shape[i] != shape[i - 1]) {
792 cleanShape.push_back(shape[i]);
793 } else {
794 duplicates.push_back(shape[i]);
795 }
796 }
797 if (cleanShape.size() < shape.size()) {
798 WRITE_WARNINGF(TL("Polygon '%' at junction '%' had some equal consecutive points removed: %"), shapeID, junctionID, toString(duplicates, 9));
799 }
800 GEOSCoordSequence* coordinateSequence = convertToGEOSPoints(cleanShape);
801 GEOSGeometry* linearRing = GEOSGeom_createLinearRing(coordinateSequence);
802 GEOSGeometry* polygon = GEOSGeom_createPolygon(linearRing, nullptr, 0);
803
804 if (!GEOSisValid(polygon)) {
805 if (cleanShape.size() == 3) {
806 if (isInternalShape) {
807 WRITE_WARNINGF(TL("Polygon '%' at junction '%' has been dilated as it is just a segment."), shapeID, junctionID);
808 } else {
809 WRITE_WARNINGF(TL("Polygon '%' has been dilated as it is just a segment."), shapeID);
810 }
811 GEOSGeometry* lineString = GEOSGeom_createLineString(GEOSCoordSeq_clone(coordinateSequence));
812 GEOSGeom_destroy(polygon);
813 polygon = GEOSBufferWithStyle(lineString, GEOS_BUFFERED_SEGMENT_WIDTH, GEOS_QUADRANT_SEGMENTS, GEOSBUF_CAP_FLAT, GEOSBUF_JOIN_BEVEL, GEOS_MITRE_LIMIT);
814 GEOSGeom_destroy(lineString);
815 } else {
816 if (isInternalShape) {
817 WRITE_WARNINGF(TL("Polygon '%' at junction '%' has been replaced by its convex hull as it is not simple."), shapeID, junctionID);
818 GEOSGeometry* hull = GEOSConvexHull(polygon);
819 GEOSGeom_destroy(polygon);
820 polygon = GEOSBufferWithStyle(hull, POSITION_EPS, GEOS_QUADRANT_SEGMENTS, GEOSBUF_CAP_FLAT, GEOSBUF_JOIN_ROUND, GEOS_MITRE_LIMIT);;
821 } else {
822 WRITE_WARNINGF(TL("Polygon '%' at junction '%' will be skipped as it is not simple."), shapeID, junctionID);
823 polygon = nullptr;
824 }
825 }
826
827 return polygon;
828 }
829
830 // Some junctions need to be buffered a little so that edges are properly connected.
831 if (isInternalShape) {
832 polygon = GEOSBufferWithStyle(polygon, POSITION_EPS, GEOS_QUADRANT_SEGMENTS, GEOSBUF_CAP_FLAT, GEOSBUF_JOIN_ROUND, GEOS_MITRE_LIMIT);
833 }
834
835 return polygon;
836}
837
838
839GEOSGeometry*
841 std::vector<GEOSGeometry*> walkableAreas;
842 for (const MSEdge* const edge : network->getEdgeControl().getEdges()) {
843 const MSLane* const lane = getSidewalk<MSEdge, MSLane>(edge);
844 if (lane != nullptr) {
845 GEOSGeometry* dilatedLane = nullptr;
846 if (edge->isWalkingArea()) {
847 dilatedLane = createGeometryFromShape(lane->getShape(), edge->getFromJunction()->getID(), edge->getID(), true);
848 } else if (edge->isCrossing()) {
849 const PositionVector* outlineShape = lane->getOutlineShape();
850 if (outlineShape != nullptr) {
851 // this is mainly to ensure that we have at least the "normal" crossing, see #15037
852 dilatedLane = createGeometryFromCenterLine(lane->getShape(), lane->getWidth() / 2.0, GEOSBUF_CAP_FLAT);
853 if (dilatedLane != nullptr) {
854 walkableAreas.push_back(dilatedLane);
855 }
856 dilatedLane = createGeometryFromShape(*outlineShape, edge->getFromJunction()->getID(), edge->getID(), true);
857 } else {
858 dilatedLane = createGeometryFromCenterLine(lane->getShape(), lane->getWidth() / 2.0, GEOSBUF_CAP_ROUND);
859 }
860 myCrossingWaits[lane] = {0, 0};
861 } else { // regular sidewalk
862 dilatedLane = createGeometryFromCenterLine(lane->getShape(), lane->getWidth() / 2.0 + POSITION_EPS, GEOSBUF_CAP_FLAT);
863 }
864 if (dilatedLane != nullptr) {
865 walkableAreas.push_back(dilatedLane);
866 }
867 }
868 }
869 for (const auto& junctionWithID : network->getJunctionControl()) {
870 const MSJunction* const junction = junctionWithID.second;
871 int pedEdgeCount = 0;
872 bool hasWalkingArea = false;
873 for (const ConstMSEdgeVector& edges : {
874 junction->getIncoming(), junction->getOutgoing()
875 }) {
876 for (const MSEdge* const edge : edges) {
877 if (edge->isWalkingArea()) {
878 hasWalkingArea = true;
879 break;
880 }
881 if (getSidewalk<MSEdge, MSLane>(edge) != nullptr) {
882 pedEdgeCount++;
883 }
884 }
885 if (hasWalkingArea) {
886 break;
887 }
888 }
889 if (!hasWalkingArea && pedEdgeCount > 1) {
890 // there is something to connect but no walking area, let's assume peds are allowed everywhere
891 GEOSGeometry* walkingAreaGeom = createGeometryFromShape(junction->getShape(), junction->getID(), junction->getID(), true);
892 if (walkingAreaGeom != nullptr) {
893 walkableAreas.push_back(walkingAreaGeom);
894 }
895 }
896 }
897
898 // Retrieve additional walkable areas and obstacles (walkable areas and obstacles in the sense of JuPedSim).
899 std::vector<GEOSGeometry*> additionalObstacles;
900 for (const auto& polygonWithID : myNetwork->getShapeContainer().getPolygons()) {
901 if (polygonWithID.second->getShapeType() == "jupedsim.walkable_area" || polygonWithID.second->getShapeType() == "taz") {
902 GEOSGeometry* walkableArea = createGeometryFromShape(polygonWithID.second->getShape(), std::string(""), polygonWithID.first);
903 if (walkableArea != nullptr) {
904 walkableAreas.push_back(walkableArea);
906 }
907 } else if (polygonWithID.second->getShapeType() == "jupedsim.obstacle") {
908 GEOSGeometry* additionalObstacle = createGeometryFromShape(polygonWithID.second->getShape(), std::string(""), polygonWithID.first);
909 if (additionalObstacle != nullptr) {
910 additionalObstacles.push_back(additionalObstacle);
911 }
912 }
913 }
914
915 // Take the union of all walkable areas.
916 GEOSGeometry* disjointWalkableAreas = GEOSGeom_createCollection(GEOS_MULTIPOLYGON, walkableAreas.data(), (unsigned int)walkableAreas.size());
917#ifdef DEBUG_GEOMETRY_GENERATION
918 // dumpGeometry(disjointWalkableAreas, "disjointWalkableAreas.wkt");
919#endif
920 GEOSGeometry* initialWalkableAreas = GEOSUnaryUnion(disjointWalkableAreas);
921#ifdef DEBUG_GEOMETRY_GENERATION
922 dumpGeometry(initialWalkableAreas, "initialWalkableAreas.wkt");
923#endif
924 GEOSGeom_destroy(disjointWalkableAreas);
925
926 // At last, remove additional obstacles from the merged walkable areas.
927 GEOSGeometry* disjointAdditionalObstacles = GEOSGeom_createCollection(GEOS_MULTIPOLYGON, additionalObstacles.data(), (unsigned int)additionalObstacles.size());
928#ifdef DEBUG_GEOMETRY_GENERATION
929 // dumpGeometry(disjointAdditionalObstacles, "disjointAdditionalObstacles.wkt");
930#endif
931 GEOSGeometry* additionalObstaclesUnion = GEOSUnaryUnion(disjointAdditionalObstacles); // Obstacles may overlap, e.g. if they were loaded from separate files.
932#ifdef DEBUG_GEOMETRY_GENERATION
933 dumpGeometry(additionalObstaclesUnion, "additionalObstaclesUnion.wkt");
934#endif
935 GEOSGeometry* finalWalkableAreas = GEOSDifference(initialWalkableAreas, additionalObstaclesUnion);
936#ifdef DEBUG_GEOMETRY_GENERATION
937 dumpGeometry(finalWalkableAreas, "finalWalkableAreas.wkt");
938#endif
939 GEOSGeom_destroy(initialWalkableAreas);
940 GEOSGeom_destroy(additionalObstaclesUnion);
941 GEOSGeom_destroy(disjointAdditionalObstacles);
942
943 if (!GEOSisSimple(finalWalkableAreas)) {
944 throw ProcessError(TL("Union of walkable areas minus union of obstacles is not a simple polygon."));
945 }
946
947 return finalWalkableAreas;
948}
949
950
951GEOSCoordSequence*
953 GEOSCoordSequence* coordinateSequence = GEOSCoordSeq_create((unsigned int)shape.size(), 2);
954 for (int i = 0; i < (int)shape.size(); i++) {
955 GEOSCoordSeq_setX(coordinateSequence, i, shape[i].x());
956 GEOSCoordSeq_setY(coordinateSequence, i, shape[i].y());
957 }
958 return coordinateSequence;
959}
960
961
964 PositionVector coordinateVector;
965 const GEOSCoordSequence* coordinateSequence = GEOSGeom_getCoordSeq(geometry);
966 unsigned int coordinateSequenceSize;
967 GEOSCoordSeq_getSize(coordinateSequence, &coordinateSequenceSize);
968 double x;
969 double y;
970 for (unsigned int i = 0; i < coordinateSequenceSize; i++) {
971 GEOSCoordSeq_getX(coordinateSequence, i, &x);
972 GEOSCoordSeq_getY(coordinateSequence, i, &y);
973 coordinateVector.push_back(Position(x, y));
974 }
975 return coordinateVector;
976}
977
978
979std::vector<JPS_Point>
980MSPModel_JuPedSim_legacy::convertToJPSPoints(const GEOSGeometry* geometry) {
981 std::vector<JPS_Point> pointVector;
982 const GEOSCoordSequence* coordinateSequence = GEOSGeom_getCoordSeq(geometry);
983 unsigned int coordinateSequenceSize;
984 GEOSCoordSeq_getSize(coordinateSequence, &coordinateSequenceSize);
985 double x;
986 double y;
987 // Remove the last point so that CGAL doesn't complain about the simplicity of the polygon downstream.
988 for (unsigned int i = 0; i < coordinateSequenceSize - 1; i++) {
989 GEOSCoordSeq_getX(coordinateSequence, i, &x);
990 GEOSCoordSeq_getY(coordinateSequence, i, &y);
991 pointVector.push_back({x, y});
992 }
993 return pointVector;
994}
995
996
997double
998MSPModel_JuPedSim_legacy::getLinearRingArea(const GEOSGeometry* linearRing) {
999 double area;
1000 GEOSGeometry* linearRingAsPolygon = GEOSGeom_createPolygon(GEOSGeom_clone(linearRing), nullptr, 0);
1001 GEOSArea(linearRingAsPolygon, &area);
1002 GEOSGeom_destroy(linearRingAsPolygon);
1003 return area;
1004}
1005
1006
1007void
1010}
1011
1012
1013void
1014MSPModel_JuPedSim_legacy::preparePolygonForDrawing(const GEOSGeometry* polygon, const std::string& polygonId, const RGBColor& color) {
1015 const GEOSGeometry* exterior = GEOSGetExteriorRing(polygon);
1016 bool added = myShapeContainer.addPolygon(polygonId, std::string("jupedsim.pedestrian_network"), color, 10.0, 0.0,
1017 std::string(), convertToSUMOPoints(exterior), false, true, 1.0);
1018 if (added) {
1019 std::vector<PositionVector> holes;
1020 int nbrInteriorRings = GEOSGetNumInteriorRings(polygon);
1021 if (nbrInteriorRings != -1) {
1022 for (int k = 0; k < nbrInteriorRings; k++) {
1023 const GEOSGeometry* linearRing = GEOSGetInteriorRingN(polygon, k);
1024 double area = getLinearRingArea(linearRing);
1025 if (area > GEOS_MIN_AREA) {
1026 holes.push_back(convertToSUMOPoints(linearRing));
1027 }
1028 }
1029 myShapeContainer.getPolygons().get(polygonId)->setHoles(holes);
1030 }
1031 }
1032}
1033
1034
1035const GEOSGeometry*
1036MSPModel_JuPedSim_legacy::getLargestComponent(const GEOSGeometry* polygon, int& nbrComponents, double& maxArea, double& totalArea) {
1037 nbrComponents = GEOSGetNumGeometries(polygon);
1038 const GEOSGeometry* largestComponent = nullptr;
1039 maxArea = 0.0;
1040 totalArea = 0.0;
1041 for (int i = 0; i < nbrComponents; i++) {
1042 const GEOSGeometry* componentPolygon = GEOSGetGeometryN(polygon, i);
1043 double area;
1044 GEOSArea(componentPolygon, &area);
1045 totalArea += area;
1046 if (area > maxArea) {
1047 maxArea = area;
1048 largestComponent = componentPolygon;
1049 }
1050 }
1051 return largestComponent;
1052}
1053
1054
1055JPS_Geometry
1057 JPS_GeometryBuilder geometryBuilder = JPS_GeometryBuilder_Create();
1058
1059 // Handle the exterior polygon.
1060 const GEOSGeometry* exterior = GEOSGetExteriorRing(polygon);
1061 std::vector<JPS_Point> exteriorCoordinates = convertToJPSPoints(exterior);
1062 JPS_GeometryBuilder_AddAccessibleArea(geometryBuilder, exteriorCoordinates.data(), exteriorCoordinates.size());
1063
1064 // Handle the interior polygons (holes).
1065 int nbrInteriorRings = GEOSGetNumInteriorRings(polygon);
1066 if (nbrInteriorRings != -1) {
1067 for (int k = 0; k < nbrInteriorRings; k++) {
1068 const GEOSGeometry* linearRing = GEOSGetInteriorRingN(polygon, k);
1069 double area = getLinearRingArea(linearRing);
1070 if (area > GEOS_MIN_AREA) {
1071 std::vector<JPS_Point> holeCoordinates = convertToJPSPoints(linearRing);
1072 JPS_GeometryBuilder_ExcludeFromAccessibleArea(geometryBuilder, holeCoordinates.data(), holeCoordinates.size());
1073 }
1074 }
1075 }
1076
1077 JPS_ErrorMessage message = nullptr;
1078 JPS_Geometry geometry = JPS_GeometryBuilder_Build(geometryBuilder, &message);
1079 if (geometry == nullptr) {
1080 const std::string error = TLF("Error while generating geometry: %", JPS_ErrorMessage_GetMessage(message));
1081 JPS_ErrorMessage_Free(message);
1082 throw ProcessError(error);
1083 }
1084 JPS_GeometryBuilder_Free(geometryBuilder);
1085 return geometry;
1086}
1087
1088
1089void
1090MSPModel_JuPedSim_legacy::dumpGeometry(const GEOSGeometry* polygon, const std::string& filename, bool useGeoCoordinates) {
1091 GEOSGeometry* polygonGeoCoordinates = nullptr;
1092 if (useGeoCoordinates) {
1093 const GEOSGeometry* exterior = GEOSGetExteriorRing(polygon);
1094 PositionVector exteriorPoints = convertToSUMOPoints(exterior);
1095 for (Position& position : exteriorPoints) {
1097 }
1098 const int nbrInteriorRings = GEOSGetNumInteriorRings(polygon);
1099 std::vector<GEOSGeometry*> holeRings;
1100 if (nbrInteriorRings != -1) {
1101 for (int k = 0; k < nbrInteriorRings; k++) {
1102 const GEOSGeometry* linearRing = GEOSGetInteriorRingN(polygon, k);
1103 PositionVector holePoints = convertToSUMOPoints(linearRing);
1104 for (Position& position : holePoints) {
1106 }
1107 GEOSCoordSequence* holeRingCoords = convertToGEOSPoints(holePoints);
1108 GEOSGeometry* holeRing = GEOSGeom_createLinearRing(holeRingCoords);
1109 holeRings.push_back(holeRing);
1110 }
1111 }
1112 GEOSCoordSequence* exteriorRingCoords = convertToGEOSPoints(exteriorPoints);
1113 GEOSGeometry* exteriorRing = GEOSGeom_createLinearRing(exteriorRingCoords);
1114 polygonGeoCoordinates = GEOSGeom_createPolygon(exteriorRing, holeRings.data(), nbrInteriorRings);
1115 }
1116 std::ofstream dumpFile;
1117 dumpFile.open(filename);
1118 GEOSWKTWriter* writer = GEOSWKTWriter_create();
1119 GEOSWKTWriter_setRoundingPrecision(writer, gPrecisionGeo);
1120 char* wkt = GEOSWKTWriter_write(writer, polygonGeoCoordinates == nullptr ? polygon : polygonGeoCoordinates);
1121 dumpFile << wkt << std::endl;
1122 dumpFile.close();
1123 GEOSFree(wkt);
1124 GEOSWKTWriter_destroy(writer);
1125 GEOSGeom_destroy(polygonGeoCoordinates);
1126}
1127
1128
1129double
1131 return 0.5 * MAX2(vehType.getLength(), vehType.getWidth());
1132}
1133
1134
1135JPS_StageId
1136MSPModel_JuPedSim_legacy::addWaitingSet(const MSLane* const crossing, const bool entry) {
1137 JPS_ErrorMessage message = nullptr;
1138 JPS_StageId waitingStage = 0;
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 std::vector<JPS_Point> points;
1160 for (const Position& p : pv) {
1161 GEOSCoordSequence* seq = GEOSCoordSeq_create(1, 2); // 1 point, 2 dimensions
1162 GEOSCoordSeq_setX(seq, 0, p.x());
1163 GEOSCoordSeq_setY(seq, 0, p.y());
1164 GEOSGeometry* point = GEOSGeom_createPoint(seq);
1165 if (GEOSContains(myGEOSPedestrianNetworkLargestComponent, point)) {
1166 points.push_back({p.x(), p.y()});
1167 } else {
1168 WRITE_WARNINGF("Waiting point %,% is not in the geometry for % on '%'.", p.x(), p.y(), entry ? "entry" : "exit", crossing->getID())
1169 }
1170 GEOSGeom_destroy(point);
1171 }
1172 waitingStage = JPS_Simulation_AddStageWaitingSet(myJPSSimulation, points.data(), points.size(), &message);
1173 if (message != nullptr) {
1174 const std::string error = TLF("Error while adding waiting set for % on '%': %",
1175 entry ? "entry" : "exit", crossing->getID(), JPS_ErrorMessage_GetMessage(message));
1176 JPS_ErrorMessage_Free(message);
1177 throw ProcessError(error);
1178 }
1179 const auto proxy = JPS_Simulation_GetWaitingSetProxy(myJPSSimulation, waitingStage, &message);
1180 JPS_WaitingSetProxy_SetWaitingSetState(proxy, JPS_WaitingSet_Inactive);
1181 myCrossings[waitingStage] = crossing;
1182 if (myPythonScript != nullptr) {
1183 (*myPythonScript) << "ws = simulation.add_waiting_set_stage([";
1184 for (const JPS_Point& p : points) {
1185 (*myPythonScript) << "(" << p.x << "," << p.y << "),";
1186 }
1187 (*myPythonScript) << "])\nsimulation.get_stage(ws).state = jps.stages.WaitingSetState.INACTIVE\n";
1188 }
1189 return waitingStage;
1190}
1191
1192
1193void
1195 initGEOS(nullptr, nullptr);
1196 PROGRESS_BEGIN_MESSAGE("Generating initial JuPedSim geometry for pedestrian network");
1198 int nbrComponents = 0;
1199 double maxArea = 0.0;
1200 double totalArea = 0.0;
1202 if (nbrComponents > 1) {
1203 WRITE_WARNINGF(TL("While generating geometry % connected components were detected, %% of total pedestrian area is covered by the largest."),
1204 nbrComponents, maxArea / totalArea * 100.0, "%");
1205 }
1206#ifdef DEBUG_GEOMETRY_GENERATION
1207 dumpGeometry(myGEOSPedestrianNetworkLargestComponent, "pedestrianNetwork.wkt");
1208#endif
1209 const std::string filename = oc.getString("pedestrian.jupedsim.wkt");
1210 if (!filename.empty()) {
1211 dumpGeometry(myGEOSPedestrianNetworkLargestComponent, filename, oc.getBool("pedestrian.jupedsim.wkt.geo"));
1212 }
1213 // For the moment, only one connected component is supported.
1218 JPS_ErrorMessage message = nullptr;
1219
1220 double strengthGeometryRepulsion = oc.getFloat("pedestrian.jupedsim.strength-geometry-repulsion");
1221 double rangeGeometryRepulsion = oc.getFloat("pedestrian.jupedsim.range-geometry-repulsion");
1222 if (myJPSDeltaT == 20) {
1223 if (oc.isDefault("pedestrian.jupedsim.strength-geometry-repulsion") && oc.isDefault("pedestrian.jupedsim.range-geometry-repulsion")) {
1224 WRITE_MESSAGE(TL("Adapting geometry repulsion default values for jupedsim timestep of 0.02."));
1225 strengthGeometryRepulsion = 35.;
1226 rangeGeometryRepulsion = 0.019;
1227 }
1228 }
1229
1230 switch (myJPSModel) {
1232 JPS_CollisionFreeSpeedModelBuilder modelBuilder = JPS_CollisionFreeSpeedModelBuilder_Create(
1233 oc.getFloat("pedestrian.jupedsim.strength-neighbor-repulsion"),
1234 oc.getFloat("pedestrian.jupedsim.range-neighbor-repulsion"),
1235 strengthGeometryRepulsion,
1236 rangeGeometryRepulsion);
1237 myJPSOperationalModel = JPS_CollisionFreeSpeedModelBuilder_Build(modelBuilder, &message);
1238 JPS_CollisionFreeSpeedModelBuilder_Free(modelBuilder);
1239 break;
1240 }
1242 JPS_CollisionFreeSpeedModelV2Builder modelBuilder = JPS_CollisionFreeSpeedModelV2Builder_Create();
1243 myJPSOperationalModel = JPS_CollisionFreeSpeedModelV2Builder_Build(modelBuilder, &message);
1244 JPS_CollisionFreeSpeedModelV2Builder_Free(modelBuilder);
1245 break;
1246 }
1248 if (oc.isDefault("pedestrian.jupedsim.strength-geometry-repulsion")) {
1249 strengthGeometryRepulsion = 0.2;
1250 }
1251 JPS_GeneralizedCentrifugalForceModelBuilder modelBuilder = JPS_GeneralizedCentrifugalForceModelBuilder_Create(
1252 oc.isDefault("pedestrian.jupedsim.strength-neighbor-repulsion") ? 0.3 : oc.getFloat("pedestrian.jupedsim.strength-neighbor-repulsion"),
1253 strengthGeometryRepulsion,
1254 2.0,
1255 2.0,
1256 0.1,
1257 0.1,
1258 9.0,
1259 3.0);
1260 myJPSOperationalModel = JPS_GeneralizedCentrifugalForceModelBuilder_Build(modelBuilder, &message);
1261 JPS_GeneralizedCentrifugalForceModelBuilder_Free(modelBuilder);
1262 break;
1263 }
1265 JPS_SocialForceModelBuilder modelBuilder = JPS_SocialForceModelBuilder_Create(120000.0, 240000.0);
1266 myJPSOperationalModel = JPS_SocialForceModelBuilder_Build(modelBuilder, &message);
1267 JPS_SocialForceModelBuilder_Free(modelBuilder);
1268 break;
1269 }
1270 }
1271
1272 if (myJPSOperationalModel == nullptr) {
1273 const std::string error = TLF("Error creating the pedestrian model: %", JPS_ErrorMessage_GetMessage(message));
1274 JPS_ErrorMessage_Free(message);
1275 throw ProcessError(error);
1276 }
1277 myJPSSimulation = JPS_Simulation_Create(myJPSOperationalModel, myJPSGeometry, STEPS2TIME(myJPSDeltaT), &message);
1278 if (myJPSSimulation == nullptr) {
1279 const std::string error = TLF("Error creating the simulation: %", JPS_ErrorMessage_GetMessage(message));
1280 JPS_ErrorMessage_Free(message);
1281 throw ProcessError(error);
1282 }
1283 // Polygons that define vanishing areas aren't part of the regular JuPedSim geometry.
1284 for (const auto& polygonWithID : myNetwork->getShapeContainer().getPolygons()) {
1285 polygonChanged(polygonWithID.second, true, false);
1286 }
1287 if (OptionsCont::createDeviceByOption("pedestrian.jupedsim.py")) {
1288 myPythonScript = &OptionsCont::getDeviceByOption("pedestrian.jupedsim.py");
1290 (*myPythonScript) << "import jupedsim as jps\nimport shapely\n\n"
1291 "with open('" << filename << "') as f: geom = shapely.from_wkt(f.read())\n"
1292 "simulation = jps.Simulation(dt=" << STEPS2TIME(myJPSDeltaT) << ", model=jps.CollisionFreeSpeedModel(), geometry=geom,\n"
1293 "trajectory_writer=jps.SqliteTrajectoryWriter(output_file='out.sql'))\n";
1294 }
1296}
1297
1298
1299void
1300MSPModel_JuPedSim_legacy::polygonChanged(const SUMOPolygon* const poly, const bool added, const bool removed) {
1301 if (poly->getShapeType() == "jupedsim.vanishing_area" || poly->getShapeType() == "jupedsim.influencer") {
1302 SUMOTime lastRemovalTime = 0;
1303 if (!added) {
1304 for (auto areaIt = myAreas.begin(); areaIt != myAreas.end(); ++areaIt) {
1305 if (poly->getID() == (*areaIt)->id) {
1306 lastRemovalTime = (*areaIt)->lastRemovalTime;
1307 myAreas.erase(areaIt);
1308 break;
1309 }
1310 }
1311 }
1312 if (!removed) {
1313 std::vector<JPS_Point> areaBoundary;
1314 for (const Position& p : poly->getShape()) {
1315 areaBoundary.push_back({p.x(), p.y()});
1316 }
1317 // Make sure the shape is not repeating the first point.
1318 if (areaBoundary.back().x == areaBoundary.front().x && areaBoundary.back().y == areaBoundary.front().y) {
1319 areaBoundary.pop_back();
1320 }
1321 const std::string type = StringTokenizer(poly->getShapeType(), ".").getVector()[1];
1322 myAreas.emplace_back(std::unique_ptr<AreaData>(new AreaData{poly->getID(), type, areaBoundary, poly->getParametersMap(), lastRemovalTime}));
1323 }
1324 }
1325}
1326
1327
1328// ===========================================================================
1329// MSPModel_Remote::PState method definitions
1330// ===========================================================================
1332 JPS_JourneyId journeyId, JPS_StageId stageId,
1333 const std::vector<WaypointDesc>& waypoints) :
1334 MSPModel_InteractingState(person, stage, nullptr),
1335 myJourneyId(journeyId), myStageId(stageId), myWaypoints(waypoints), myAgentId(0) {
1336 myDir = FORWARD;
1337}
1338
1339
1340void
1341MSPModel_JuPedSim_legacy::PState::reinit(MSStageMoving* stage, JPS_JourneyId journeyId, JPS_StageId stageId,
1342 const std::vector<WaypointDesc>& waypoints) {
1343 if (myStage != nullptr) {
1344 myStage->setPState(nullptr); // we need to remove the old state reference to avoid double deletion
1345 }
1346 myStage = stage;
1347 myJourneyId = journeyId;
1348 myStageId = stageId;
1349 myWaypoints = waypoints;
1350}
1351
1352
1355
1356
1357void MSPModel_JuPedSim_legacy::PState::setPosition(const double x, const double y, const double z) {
1358 if (myRemoteXYPos != Position::INVALID) {
1359 mySpeed = myRemoteXYPos.distanceTo2D(Position(x, y, z)) / STEPS2TIME(DELTA_T);
1360 } else {
1361 mySpeed = 0.;
1362 }
1363 myRemoteXYPos.set(x, y, z);
1364}
1365
1366
1368 return stage.getNextRouteEdge();
1369}
1370
1371
1374 return offset < (int)myWaypoints.size() ? &myWaypoints[offset] : nullptr;
1375}
1376
1377
1378/****************************************************************************/
long long int SUMOTime
Definition GUI.h:36
std::vector< const MSEdge * > ConstMSEdgeVector
Definition MSEdge.h:75
#define WRITE_WARNINGF(...)
Definition MsgHandler.h:299
#define WRITE_MESSAGEF(...)
Definition MsgHandler.h:301
#define WRITE_ERRORF(...)
Definition MsgHandler.h:308
#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
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
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.
void reinit(MSStageMoving *stage, JPS_JourneyId journeyId, JPS_StageId stageId, const std::vector< WaypointDesc > &waypoints)
const MSPModel_JuPedSim_legacy::WaypointDesc * getNextWaypoint(const int offset=0) const
const MSEdge * getNextEdge(const MSStageMoving &stage) const override
return the list of internal edges if the transportable is on an intersection
void setStage(MSStageMoving *const stage)
void setPosition(const double x, const double y, const double z=0.)
JPS_StageId getStageId() const
first stage of the journey
Position getPosition(const MSStageMoving &, SUMOTime) const override
return the network coordinate of the transportable
PState(MSPerson *person, MSStageMoving *stage, JPS_JourneyId journeyId, JPS_StageId stageId, const std::vector< WaypointDesc > &waypoints)
void polygonChanged(const SUMOPolygon *const poly, const bool added, const bool removed) override
JPS_Geometry myJPSGeometryWithTrainsAndRamps
The JPS polygon representing the largest connected component plus carriages and ramps.
JPS_Geometry myJPSGeometry
The JPS polygon representing the largest connected component of the pedestrian network.
static const RGBColor PEDESTRIAN_NETWORK_CARRIAGES_AND_RAMPS_COLOR
void initialize(const OptionsCont &oc)
void clearState() override
Resets pedestrians when quick-loading state.
static JPS_Geometry buildJPSGeometryFromGEOSGeometry(const GEOSGeometry *polygon)
static GEOSCoordSequence * convertToGEOSPoints(PositionVector shape)
static PositionVector convertToSUMOPoints(const GEOSGeometry *geometry)
static double getRadius(const MSVehicleType &vehType)
static const double GEOS_BUFFERED_SEGMENT_WIDTH
GEOSGeometry * buildPedestrianNetwork(MSNet *network)
void registerArrived(const JPS_AgentId agentID)
static void dumpGeometry(const GEOSGeometry *polygon, const std::string &filename, bool useGeoCoordinates=false)
void preparePolygonForDrawing(const GEOSGeometry *polygon, const std::string &polygonId, const RGBColor &color)
std::map< const MSLane *, std::pair< JPS_StageId, JPS_StageId >, ComparatorNumericalIdLess > myCrossingWaits
const SUMOTime myJPSDeltaT
Timestep used in the JuPedSim simulator.
bool addWaypoint(JPS_JourneyDescription journey, JPS_StageId &predecessor, const std::string &agentID, const WaypointDesc &waypoint)
GEOSGeometry * myGEOSPedestrianNetwork
The GEOS polygon containing all computed connected components of the pedestrian network.
JPS_StageId addWaitingSet(const MSLane *const crossing, const bool entry)
MSNet *const myNetwork
The network on which the simulation runs.
void removePolygonFromDrawing(const std::string &polygonId)
JPS_OperationalModel myJPSOperationalModel
static const GEOSGeometry * getLargestComponent(const GEOSGeometry *polygon, int &nbrComponents, double &maxArea, double &totalArea)
static const std::vector< MSPModel_JuPedSim_legacy::PState * > noPedestrians
void tryPedestrianInsertion(PState *state, const Position &p)
static GEOSGeometry * createGeometryFromCenterLine(PositionVector centerLine, double width, int capStyle)
MSTransportableStateAdapter * add(MSTransportable *person, MSStageMoving *stage, SUMOTime now) override
register the given person as a pedestrian
MSPModel_JuPedSim_legacy(const OptionsCont &oc, MSNet *net)
static std::vector< JPS_Point > convertToJPSPoints(const GEOSGeometry *geometry)
ShapeContainer & myShapeContainer
The shape container used to add polygons to the rendering pipeline.
std::vector< std::unique_ptr< AreaData > > myAreas
Array of special areas.
void remove(MSTransportableStateAdapter *state) override
remove the specified person from the pedestrian simulation
bool addStage(JPS_JourneyDescription journey, JPS_StageId &predecessor, const std::string &agentID, const JPS_StageId stage)
static double getLinearRingArea(const GEOSGeometry *linearRing)
std::vector< SUMOTrafficObject::NumericalID > myAllStoppedTrainIDs
Array of stopped trains, used to detect whether to add carriages and ramps to the geometry.
static const std::string PEDESTRIAN_NETWORK_CARRIAGES_AND_RAMPS_ID
static GEOSGeometry * createGeometryFromShape(PositionVector shape, std::string junctionID=std::string(""), std::string shapeID=std::string(""), bool isInternalShape=false)
std::vector< PState * > myPedestrianStates
SumoRNG myRNG
The random number generator for fluctuations on insertion.
static const std::string PEDESTRIAN_NETWORK_ID
const double myExitTolerance
Threshold to decide if a pedestrian has ended its journey or not.
std::map< JPS_StageId, const MSLane * > myCrossings
const GEOSGeometry * myGEOSPedestrianNetworkLargestComponent
The GEOS polygon representing the largest (by area) connected component of the pedestrian network.
static const RGBColor PEDESTRIAN_NETWORK_COLOR
std::tuple< JPS_StageId, Position, double > WaypointDesc
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
double getFloat(const std::string &name) const
Returns the double-value of the named option (only for Option_Float)
static OutputDevice & getDeviceByOption(const std::string &name)
Returns the device described by the option.
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.
static bool createDeviceByOption(const std::string &optionName, const std::string &rootElement="", const std::string &schemaFile="", const int maximumDepth=2)
Creates the device using the output definition stored in the named option.
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.
void setPrecision(int precision=gPrecision)
Sets the precision or resets it to default.
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.
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
#define UNUSED_PARAMETER(x)
#define M_PI
Definition odrSpiral.cpp:45
Structure that keeps data related to vanishing areas (and other types of areas).