View Javadoc
1   package org.opentrafficsim.core.gtu;
2   
3   import java.awt.Color;
4   
5   import org.djunits.unit.TimeUnit;
6   import org.djunits.value.vdouble.scalar.Acceleration;
7   import org.djunits.value.vdouble.scalar.Duration;
8   import org.djunits.value.vdouble.scalar.Length;
9   import org.djunits.value.vdouble.scalar.Speed;
10  import org.djunits.value.vdouble.scalar.Time;
11  import org.opentrafficsim.core.dsol.OTSDEVSSimulatorInterface;
12  import org.opentrafficsim.core.dsol.OTSSimTimeDouble;
13  import org.opentrafficsim.core.geometry.OTSGeometryException;
14  import org.opentrafficsim.core.geometry.OTSLine3D;
15  import org.opentrafficsim.core.geometry.OTSPoint3D;
16  import org.opentrafficsim.core.gtu.animation.IDGTUColorer;
17  import org.opentrafficsim.core.gtu.behavioralcharacteristics.ParameterException;
18  import org.opentrafficsim.core.gtu.plan.operational.OperationalPlan;
19  import org.opentrafficsim.core.gtu.plan.operational.OperationalPlanBuilder;
20  import org.opentrafficsim.core.gtu.plan.operational.OperationalPlanException;
21  import org.opentrafficsim.core.gtu.plan.strategical.StrategicalPlanner;
22  import org.opentrafficsim.core.gtu.plan.tactical.TacticalPlanner;
23  import org.opentrafficsim.core.idgenerator.IdGenerator;
24  import org.opentrafficsim.core.network.NetworkException;
25  import org.opentrafficsim.core.perception.PerceivableContext;
26  
27  import nl.tudelft.simulation.dsol.SimRuntimeException;
28  import nl.tudelft.simulation.dsol.formalisms.eventscheduling.SimEvent;
29  import nl.tudelft.simulation.event.EventProducer;
30  import nl.tudelft.simulation.language.Throw;
31  import nl.tudelft.simulation.language.d3.DirectedPoint;
32  
33  /**
34   * Implements the basic functionalities of any GTU: the ability to move on 3D-space according to a plan.
35   * <p>
36   * Copyright (c) 2013-2016 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
37   * BSD-style license. See <a href="http://opentrafficsim.org/docs/license.html">OpenTrafficSim License</a>.
38   * <p>
39   * @version $Revision: 2441 $, $LastChangedDate: 2016-11-02 11:22:48 +0100 (Wed, 02 Nov 2016) $, by $Author: averbraeck $,
40   *          initial version Oct 22, 2014 <br>
41   * @author <a href="http://www.tbm.tudelft.nl/averbraeck">Alexander Verbraeck</a>
42   * @author <a href="http://www.tudelft.nl/pknoppers">Peter Knoppers</a>
43   */
44  public abstract class AbstractGTU extends EventProducer implements GTU
45  {
46      /** */
47      private static final long serialVersionUID = 20140822L;
48  
49      /** The id of the GTU. */
50      private final String id;
51  
52      /** unique number of the GTU. */
53      private final int uniqueNumber;
54  
55      /** the unique number counter. */
56      private static int staticUNIQUENUMBER = 0;
57  
58      /** The type of GTU, e.g. TruckType, CarType, BusType. */
59      private final GTUType gtuType;
60  
61      /** The simulator to schedule activities on. */
62      private final OTSDEVSSimulatorInterface simulator;
63  
64      /** The maximum acceleration. */
65      private Acceleration maximumAcceleration;
66  
67      /** The maximum deceleration, stored as a negative number. */
68      private Acceleration maximumDeceleration;
69  
70      /**
71       * The odometer which measures how much distance have we covered between instantiation and the last completed operational
72       * plan. In order to get a complete odometer reading, the progress of the current plan execution has to be added to this
73       * value.
74       */
75      private Length odometer;
76  
77      /** The strategical planner that can instantiate tactical planners to determine mid-term decisions. */
78      private StrategicalPlanner strategicalPlanner;
79  
80      /** The tactical planner that can generate an operational plan. */
81      private TacticalPlanner tacticalPlanner = null;
82  
83      /** The current operational plan, which provides a short-term movement over time. */
84      private OperationalPlan operationalPlan = null;
85  
86      /** The next move event as scheduled on the simulator, can be used for interrupting the current move. */
87      private SimEvent<OTSSimTimeDouble> nextMoveEvent;
88  
89      /** The model in which this GTU is registered. */
90      private PerceivableContext perceivableContext;
91  
92      /** Turn indicator status. */
93      private TurnIndicatorStatus turnIndicatorStatus = TurnIndicatorStatus.NOTPRESENT;
94  
95      /** Is this GTU destroyed? */
96      private boolean destroyed = false;
97  
98      /** The cached base color. */
99      private Color baseColor = null;
100 
101     /**
102      * @param id String; the id of the GTU
103      * @param gtuType GTUType; the type of GTU, e.g. TruckType, CarType, BusType
104      * @param simulator OTSDEVSSimulatorInterface; the simulator to schedule plan changes on
105      * @param perceivableContext PerceivableContext; the perceivable context in which this GTU will be registered
106      * @throws GTUException when the preconditions of the constructor are not met
107      */
108     @SuppressWarnings("checkstyle:parameternumber")
109     public AbstractGTU(final String id, final GTUType gtuType, final OTSDEVSSimulatorInterface simulator,
110             final PerceivableContext perceivableContext) throws GTUException
111     {
112         Throw.when(id == null, GTUException.class, "id is null");
113         Throw.when(gtuType == null, GTUException.class, "gtuType is null");
114         Throw.when(gtuType.equals(GTUType.NONE), GTUException.class, "gtuType of an actual GTU cannot be GTUType.NONE");
115         Throw.when(gtuType.equals(GTUType.ALL), GTUException.class, "gtuType of an actual GTU cannot be GTUType.ALL");
116         Throw.when(perceivableContext == null, GTUException.class, "perceivableContext is null for GTU with id %s", id);
117         Throw.when(perceivableContext.containsGtuId(id), GTUException.class,
118                 "GTU with id %s already registered in perceivableContext %s", id, perceivableContext.getId());
119         Throw.when(simulator == null, GTUException.class, "simulator is null for GTU with id %s", id);
120 
121         this.id = id;
122         this.uniqueNumber = ++staticUNIQUENUMBER;
123         this.gtuType = gtuType;
124         this.simulator = simulator;
125         this.odometer = Length.ZERO;
126         this.perceivableContext = perceivableContext;
127         this.perceivableContext.addGTU(this);
128     }
129 
130     /**
131      * @param idGenerator IdGenerator; the generator that will produce a unique id of the GTU
132      * @param gtuType GTUType; the type of GTU, e.g. TruckType, CarType, BusType
133      * @param simulator OTSDEVSSimulatorInterface; the simulator to schedule plan changes on
134      * @param perceivableContext PerceivableContext; the perceivable context in which this GTU will be registered
135      * @throws GTUException when the preconditions of the constructor are not met
136      */
137     @SuppressWarnings("checkstyle:parameternumber")
138     public AbstractGTU(final IdGenerator idGenerator, final GTUType gtuType, final OTSDEVSSimulatorInterface simulator,
139             final PerceivableContext perceivableContext) throws GTUException
140     {
141         this(generateId(idGenerator), gtuType, simulator, perceivableContext);
142     }
143 
144     /**
145      * Initialize the GTU at a location and speed, and give it a mission to fulfill through the strategical planner.
146      * @param strategicalPlanner StrategicalPlanner; the strategical planner responsible for the overall 'mission' of the GTU,
147      *            usually indicating where it needs to go. It operates by instantiating tactical planners to do the work.
148      * @param initialLocation DirectedPoint; the initial location (and direction) of the GTU
149      * @param initialSpeed Speed; the initial speed of the GTU
150      * @throws SimRuntimeException when scheduling after the first move fails
151      * @throws GTUException when the preconditions of the parameters are not met or when the construction of the original
152      *             waiting path fails
153      */
154     @SuppressWarnings({ "checkstyle:hiddenfield", "hiding" })
155     public final void init(final StrategicalPlanner strategicalPlanner, final DirectedPoint initialLocation,
156             final Speed initialSpeed) throws SimRuntimeException, GTUException
157     {
158         Throw.when(strategicalPlanner == null, GTUException.class, "strategicalPlanner is null for GTU with id %s", this.id);
159         Throw.whenNull(initialLocation, "Initial location of GTU cannot be null");
160         Throw.when(Double.isNaN(initialLocation.x) || Double.isNaN(initialLocation.y) || Double.isNaN(initialLocation.z),
161                 GTUException.class, "initialLocation %s invalid for GTU with id %s", initialLocation, this.id);
162         Throw.when(initialSpeed == null, GTUException.class, "initialSpeed is null for GTU with id %s", this.id);
163         Throw.when(!getId().equals(strategicalPlanner.getGtu().getId()), GTUException.class,
164                 "GTU %s is initialized with a strategical planner for GTU %s", getId(), strategicalPlanner.getGtu().getId());
165 
166         this.strategicalPlanner = strategicalPlanner;
167         Time now = this.simulator.getSimulatorTime().getTime();
168 
169         // Give the GTU a 1 micrometer long operational plan, or a stand-still plan, so the first move will work
170         DirectedPoint p = initialLocation;
171         try
172         {
173             if (initialSpeed.si < OperationalPlan.DRIFTING_SPEED_SI)
174             {
175                 this.operationalPlan = new OperationalPlan(this, p, now, new Duration(1E-6, TimeUnit.SECOND));
176             }
177             else
178             {
179                 OTSPoint3D p2 = new OTSPoint3D(p.x + 1E-6 * Math.cos(p.getRotZ()), p.y + 1E-6 * Math.sin(p.getRotZ()), p.z);
180                 OTSLine3D path = new OTSLine3D(new OTSPoint3D(p), p2);
181                 this.operationalPlan = OperationalPlanBuilder.buildConstantSpeedPlan(this, path, now, initialSpeed);
182             }
183 
184             fireTimedEvent(GTU.INIT_EVENT, new Object[] { getId(), initialLocation, getLength(), getWidth(), getBaseColor() },
185                     now);
186 
187             // if ("114".equals(getId()))
188             // {
189             // System.out.println("komt ie");
190             // }
191             // and do the real move
192             move(initialLocation);
193         }
194         catch (OperationalPlanException | OTSGeometryException | NetworkException | ParameterException exception)
195         {
196             throw new GTUException("Failed to create OperationalPlan for GTU " + this.id, exception);
197         }
198     }
199 
200     /**
201      * Generate an id, but check first that we have a valid IdGenerator.
202      * @param idGenerator IdGenerator; the generator that will produce a unique id of the GTU
203      * @return a (hopefully unique) Id of the GTU
204      * @throws GTUException when the idGenerator is null
205      */
206     private static String generateId(final IdGenerator idGenerator) throws GTUException
207     {
208         Throw.when(idGenerator == null, GTUException.class, "AbstractGTU.<init>: idGenerator is null");
209         return idGenerator.nextId();
210     }
211 
212     /**
213      * Destructor. Don't forget to call with super.destroy() from any override to avoid memory leaks in the network.
214      */
215     @SuppressWarnings("checkstyle:designforextension")
216     public void destroy()
217     {
218         fireTimedEvent(GTU.DESTROY_EVENT, new Object[] { getId(), getLocation(), getOdometer() },
219                 this.simulator.getSimulatorTime());
220 
221         // cancel the next move
222         if (this.nextMoveEvent != null)
223         {
224             this.simulator.cancelEvent(this.nextMoveEvent);
225             this.nextMoveEvent = null;
226         }
227 
228         this.perceivableContext.removeGTU(this);
229         this.destroyed = true;
230     }
231 
232     /**
233      * Move from the current location according to an operational plan to a location that will bring us nearer to reaching the
234      * location provided by the strategical planner. <br>
235      * This method can be overridden to carry out specific behavior during the execution of the plan (e.g., scheduling of
236      * triggers, entering or leaving lanes, etc.). Please bear in mind that the call to super.move() is essential, and that one
237      * has to take care to handle the situation that the plan gets interrupted.
238      * @param fromLocation the last known location (initial location, or end location of the previous operational plan)
239      * @throws SimRuntimeException when scheduling of the next move fails
240      * @throws OperationalPlanException when there is a problem creating a good path for the GTU
241      * @throws GTUException when there is a problem with the state of the GTU when planning a path
242      * @throws NetworkException in case of a problem with the network, e.g., a dead end where it is not expected
243      * @throws ParameterException in there is a parameter problem
244      */
245     @SuppressWarnings("checkstyle:designforextension")
246     protected void move(final DirectedPoint fromLocation)
247             throws SimRuntimeException, OperationalPlanException, GTUException, NetworkException, ParameterException
248     {
249         Time now = this.simulator.getSimulatorTime().getTime();
250 
251         // Add the odometer distance from the currently running operational plan.
252         // Because a plan can be interrupted, we explicitly calculate the covered distance till 'now'
253         if (this.operationalPlan != null)
254         {
255             this.odometer = this.odometer.plus(this.operationalPlan.getTraveledDistance(now));
256         }
257 
258         // Do we have an operational plan?
259         // TODO discuss when a new tactical planner may be needed
260         if (this.tacticalPlanner == null)
261         {
262             // Tell the strategical planner to provide a tactical planner
263             this.tacticalPlanner = this.strategicalPlanner.generateTacticalPlanner();
264         }
265         this.operationalPlan = this.tacticalPlanner.generateOperationalPlan(now, fromLocation);
266 
267         // schedule the next move at the end of the current operational plan
268         // store the event, so it can be cancelled in case the plan has to be interrupted and changed halfway
269         this.nextMoveEvent = new SimEvent<>(new OTSSimTimeDouble(now.plus(this.operationalPlan.getTotalDuration())), this, this,
270                 "move", new Object[] { this.operationalPlan.getEndLocation() });
271         this.simulator.scheduleEvent(this.nextMoveEvent);
272 
273         fireTimedEvent(GTU.MOVE_EVENT,
274                 new Object[] { getId(), fromLocation, getSpeed(), getAcceleration(), getTurnIndicatorStatus(), getOdometer() },
275                 this.simulator.getSimulatorTime());
276     }
277 
278     /**
279      * Interrupt the move and ask for a new plan. This method can be overridden to carry out the bookkeeping needed when the
280      * current plan gets interrupted.
281      * @throws OperationalPlanException when there was a problem retrieving the location from the running plan
282      * @throws SimRuntimeException when scheduling of the next move fails
283      * @throws OperationalPlanException when there is a problem creating a good path for the GTU
284      * @throws GTUException when there is a problem with the state of the GTU when planning a path
285      * @throws NetworkException in case of a problem with the network, e.g., unreachability of a certain point
286      * @throws ParameterException when there is a problem with a parameter
287      */
288     @SuppressWarnings("checkstyle:designforextension")
289     protected void interruptMove()
290             throws SimRuntimeException, OperationalPlanException, GTUException, NetworkException, ParameterException
291     {
292         this.simulator.cancelEvent(this.nextMoveEvent);
293         move(this.operationalPlan.getLocation(this.simulator.getSimulatorTime().getTime()));
294     }
295 
296     /** {@inheritDoc} */
297     @Override
298     public final String getId()
299     {
300         return this.id;
301     }
302 
303     /** {@inheritDoc} */
304     @SuppressWarnings("checkstyle:designforextension")
305     @Override
306     public GTUType getGTUType()
307     {
308         return this.gtuType;
309     }
310 
311     /** {@inheritDoc} */
312     @Override
313     public final RelativePosition getReference()
314     {
315         return RelativePosition.REFERENCE_POSITION;
316     }
317 
318     /**
319      * @return simulator the simulator to schedule plan changes on
320      */
321     public final OTSDEVSSimulatorInterface getSimulator()
322     {
323         return this.simulator;
324     }
325 
326     /**
327      * @return strategicalPlanner the planner responsible for the overall 'mission' of the GTU, usually indicating where it
328      *         needs to go. It operates by instantiating tactical planners to do the work.
329      */
330     @SuppressWarnings("checkstyle:designforextension")
331     public StrategicalPlanner getStrategicalPlanner()
332     {
333         return this.strategicalPlanner;
334     }
335 
336     /**
337      * @return tacticalPlanner the tactical planner that can generate an operational plan
338      */
339     @SuppressWarnings("checkstyle:designforextension")
340     public TacticalPlanner getTacticalPlanner()
341     {
342         // TODO discuss when a new tactical planner may be needed
343         if (null == this.tacticalPlanner)
344         {
345             this.tacticalPlanner = this.strategicalPlanner.generateTacticalPlanner();
346         }
347         return this.tacticalPlanner;
348     }
349 
350     /**
351      * @return operationalPlan the current operational plan, which provides a short-term movement over time
352      */
353     public final OperationalPlan getOperationalPlan()
354     {
355         return this.operationalPlan;
356     }
357 
358     /** {@inheritDoc} */
359     @Override
360     public final Length getOdometer()
361     {
362         if (this.operationalPlan == null)
363         {
364             return this.odometer;
365         }
366         try
367         {
368             return this.odometer.plus(this.operationalPlan.getTraveledDistance(this.simulator.getSimulatorTime().getTime()));
369         }
370         catch (OperationalPlanException ope)
371         {
372             return this.odometer;
373         }
374     }
375 
376     /** {@inheritDoc} */
377     @Override
378     public final Speed getSpeed()
379     {
380         if (this.operationalPlan == null)
381         {
382             return Speed.ZERO;
383         }
384         try
385         {
386             return this.operationalPlan.getSpeed(this.simulator.getSimulatorTime().getTime());
387         }
388         catch (OperationalPlanException ope)
389         {
390             // this should not happen at all...
391             throw new RuntimeException("getSpeed() could not derive a valid speed for the current operationalPlan", ope);
392         }
393     }
394 
395     /** {@inheritDoc} */
396     @Override
397     public final Acceleration getAcceleration()
398     {
399         if (this.operationalPlan == null)
400         {
401             return Acceleration.ZERO;
402         }
403         try
404         {
405             return this.operationalPlan.getAcceleration(this.simulator.getSimulatorTime().getTime());
406         }
407         catch (OperationalPlanException ope)
408         {
409             // this should not happen at all...
410             throw new RuntimeException(
411                     "getAcceleration() could not derive a valid acceleration for the current operationalPlan", ope);
412         }
413     }
414 
415     /**
416      * @return maximumAcceleration
417      */
418     public final Acceleration getMaximumAcceleration()
419     {
420         return this.maximumAcceleration;
421     }
422 
423     /**
424      * @param maximumAcceleration set maximumAcceleration
425      */
426     public final void setMaximumAcceleration(final Acceleration maximumAcceleration)
427     {
428         if (maximumAcceleration.le(Acceleration.ZERO))
429         {
430             throw new RuntimeException("Maximum acceleration of GTU " + this.id + " set to value <= 0");
431         }
432         this.maximumAcceleration = maximumAcceleration;
433     }
434 
435     /**
436      * @return maximumDeceleration
437      */
438     public final Acceleration getMaximumDeceleration()
439     {
440         return this.maximumDeceleration;
441     }
442 
443     /**
444      * @param maximumDeceleration set maximumDeceleration, stored as a negative number
445      */
446     public final void setMaximumDeceleration(final Acceleration maximumDeceleration)
447     {
448         if (maximumDeceleration.ge(Acceleration.ZERO))
449         {
450             throw new RuntimeException("Maximum deceleration of GTU " + this.id + " set to value >= 0");
451         }
452         this.maximumDeceleration = maximumDeceleration;
453     }
454 
455     /** {@inheritDoc} */
456     @Override
457     @SuppressWarnings("checkstyle:designforextension")
458     public DirectedPoint getLocation()
459     {
460         if (this.operationalPlan == null)
461         {
462             System.err.println(
463                     "No operational plan for GTU " + this.id + " at t=" + this.getSimulator().getSimulatorTime().getTime());
464             return new DirectedPoint(0, 0, 0);
465         }
466         try
467         {
468             return this.operationalPlan.getLocation(this.simulator.getSimulatorTime().getTime());
469         }
470         catch (OperationalPlanException exception)
471         {
472             return new DirectedPoint(0, 0, 0);
473         }
474     }
475 
476     /** {@inheritDoc} */
477     @Override
478     public final TurnIndicatorStatus getTurnIndicatorStatus()
479     {
480         return this.turnIndicatorStatus;
481     }
482 
483     /** {@inheritDoc} */
484     @Override
485     public final void setTurnIndicatorStatus(final TurnIndicatorStatus turnIndicatorStatus)
486     {
487         this.turnIndicatorStatus = turnIndicatorStatus;
488     }
489 
490     /** {@inheritDoc} */
491     @Override
492     @SuppressWarnings("checkstyle:designforextension")
493     public Color getBaseColor()
494     {
495         if (this.baseColor == null)
496         {
497             this.baseColor = IDGTUColorer.LEGEND.get(this.uniqueNumber % IDGTUColorer.LEGEND.size()).getColor();
498         }
499         return this.baseColor;
500     }
501 
502     /**
503      * @return whether the GTU is destroyed, for the animation.
504      */
505     public final boolean isDestroyed()
506     {
507         return this.destroyed;
508     }
509 
510     /**
511      * @return perceivableContext
512      */
513     public final PerceivableContext getPerceivableContext()
514     {
515         return this.perceivableContext;
516     }
517 
518 }