View Javadoc
1   package org.opentrafficsim.road.network.lane;
2   
3   import static org.junit.Assert.assertEquals;
4   import static org.junit.Assert.assertFalse;
5   import static org.junit.Assert.assertNotNull;
6   import static org.junit.Assert.assertTrue;
7   
8   import java.awt.geom.Point2D;
9   import java.util.LinkedHashMap;
10  import java.util.Map;
11  
12  import javax.media.j3d.BoundingBox;
13  import javax.media.j3d.Bounds;
14  import javax.vecmath.Point3d;
15  
16  import nl.tudelft.simulation.language.d3.DirectedPoint;
17  
18  import org.djunits.unit.UNITS;
19  import org.djunits.value.vdouble.scalar.Length;
20  import org.djunits.value.vdouble.scalar.Speed;
21  import org.junit.Test;
22  import org.opentrafficsim.core.geometry.OTSLine3D;
23  import org.opentrafficsim.core.geometry.OTSPoint3D;
24  import org.opentrafficsim.core.gtu.GTUType;
25  import org.opentrafficsim.core.network.LateralDirectionality;
26  import org.opentrafficsim.core.network.LinkType;
27  import org.opentrafficsim.core.network.LongitudinalDirectionality;
28  import org.opentrafficsim.core.network.Node;
29  import org.opentrafficsim.core.network.OTSNode;
30  import org.opentrafficsim.road.network.lane.changing.LaneKeepingPolicy;
31  import org.opentrafficsim.road.network.lane.changing.OvertakingConditions;
32  
33  import com.vividsolutions.jts.geom.Coordinate;
34  import com.vividsolutions.jts.geom.Geometry;
35  import com.vividsolutions.jts.geom.GeometryFactory;
36  
37  /**
38   * Test the Lane class.
39   * <p>
40   * Copyright (c) 2013-2015 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
41   * BSD-style license. See <a href="http://opentrafficsim.org/docs/license.html">OpenTrafficSim License</a>.
42   * <p>
43   * $LastChangedDate: 2015-09-16 19:20:07 +0200 (Wed, 16 Sep 2015) $, @version $Revision: 1405 $, by $Author: averbraeck $,
44   * initial version 21 jan. 2015 <br>
45   * @author <a href="http://www.tudelft.nl/pknoppers">Peter Knoppers</a>
46   */
47  public class LaneTest implements UNITS
48  {
49      /**
50       * Test the constructor.
51       * @throws Exception when something goes wrong (should not happen)
52       */
53      @Test
54      public void laneConstructorTest() throws Exception
55      {
56          // First we need two Nodes
57          OTSNode nodeFrom = new OTSNode("A", new OTSPoint3D(0, 0, 0));
58          OTSNode nodeTo = new OTSNode("B", new OTSPoint3D(1000, 0, 0));
59          // Now we can make a Link
60          OTSPoint3D[] coordinates = new OTSPoint3D[2];
61          coordinates[0] = new OTSPoint3D(nodeFrom.getPoint().x, nodeFrom.getPoint().y, 0);
62          coordinates[1] = new OTSPoint3D(nodeTo.getPoint().x, nodeTo.getPoint().y, 0);
63          CrossSectionLink link =
64              new CrossSectionLink("A to B", nodeFrom, nodeTo, LinkType.ALL, new OTSLine3D(coordinates),
65                  LongitudinalDirectionality.DIR_PLUS, LaneKeepingPolicy.KEEP_RIGHT);
66          Length.Rel startLateralPos = new Length.Rel(2, METER);
67          Length.Rel endLateralPos = new Length.Rel(5, METER);
68          Length.Rel startWidth = new Length.Rel(3, METER);
69          Length.Rel endWidth = new Length.Rel(4, METER);
70          GTUType gtuTypeCar = GTUType.makeGTUType("Car");
71          GTUType gtuTypeTruck = GTUType.makeGTUType("Truck");
72          LaneType laneType = new LaneType("Car");
73          laneType.addCompatibility(gtuTypeCar);
74          laneType.addCompatibility(gtuTypeTruck);
75          Map<GTUType, LongitudinalDirectionality> directionalityMap = new LinkedHashMap<>();
76          directionalityMap.put(GTUType.ALL, LongitudinalDirectionality.DIR_PLUS);
77          Map<GTUType, Speed> speedMap = new LinkedHashMap<>();
78          speedMap.put(GTUType.ALL, new Speed(100, KM_PER_HOUR));
79          // Now we can construct a Lane
80          // FIXME what overtaking conditions do we ant to test in this unit test?
81          Lane lane =
82              new Lane(link, "lane", startLateralPos, endLateralPos, startWidth, endWidth, laneType, directionalityMap,
83                  speedMap, new OvertakingConditions.LeftAndRight());
84          // Verify the easy bits
85          assertEquals("PrevLanes should be empty", 0, lane.prevLanes(gtuTypeCar).size()); // this one caught a bug!
86          assertEquals("NextLanes should be empty", 0, lane.nextLanes(gtuTypeCar).size());
87          double approximateLengthOfContour =
88              2 * nodeFrom.getPoint().distanceSI(nodeTo.getPoint()) + startWidth.getSI() + endWidth.getSI();
89          assertEquals("Length of contour is approximately " + approximateLengthOfContour, approximateLengthOfContour,
90              lane.getContour().getLengthSI(), 0.1);
91          assertEquals("Directionality should be " + LongitudinalDirectionality.DIR_PLUS,
92              LongitudinalDirectionality.DIR_PLUS, lane.getDirectionality(GTUType.ALL));
93          assertEquals("SpeedLimit should be " + (new Speed(100, KM_PER_HOUR)), new Speed(100, KM_PER_HOUR), lane
94              .getSpeedLimit(GTUType.ALL));
95          assertEquals("There should be no GTUs on the lane", 0, lane.getGtuList().size());
96          assertEquals("LaneType should be " + laneType, laneType, lane.getLaneType());
97          for (int i = 0; i < 10; i++)
98          {
99              double expectedLateralCenterOffset =
100                 startLateralPos.getSI() + (endLateralPos.getSI() - startLateralPos.getSI()) * i / 10;
101             assertEquals(String.format("Lateral offset at %d%% should be %.3fm", 10 * i, expectedLateralCenterOffset),
102                 expectedLateralCenterOffset, lane.getLateralCenterPosition(i / 10.0).getSI(), 0.01);
103             Length.Rel longitudinalPosition = new Length.Rel(lane.getLength().getSI() * i / 10, METER);
104             assertEquals("Lateral offset at " + longitudinalPosition + " should be " + expectedLateralCenterOffset,
105                 expectedLateralCenterOffset, lane.getLateralCenterPosition(longitudinalPosition).getSI(), 0.01);
106             double expectedWidth = startWidth.getSI() + (endWidth.getSI() - startWidth.getSI()) * i / 10;
107             assertEquals(String.format("Width at %d%% should be %.3fm", 10 * i, expectedWidth), expectedWidth, lane
108                 .getWidth(i / 10.0).getSI(), 0.0001);
109             assertEquals("Width at " + longitudinalPosition + " should be " + expectedWidth, expectedWidth, lane
110                 .getWidth(longitudinalPosition).getSI(), 0.0001);
111             double expectedLeftOffset = expectedLateralCenterOffset - expectedWidth / 2;
112             // The next test caught a bug
113             assertEquals(String.format("Left edge at %d%% should be %.3fm", 10 * i, expectedLeftOffset),
114                 expectedLeftOffset, lane.getLateralBoundaryPosition(LateralDirectionality.LEFT, i / 10.0).getSI(),
115                 0.001);
116             assertEquals("Left edge at " + longitudinalPosition + " should be " + expectedLeftOffset,
117                 expectedLeftOffset, lane.getLateralBoundaryPosition(LateralDirectionality.LEFT, longitudinalPosition)
118                     .getSI(), 0.001);
119             double expectedRightOffset = expectedLateralCenterOffset + expectedWidth / 2;
120             assertEquals(String.format("Right edge at %d%% should be %.3fm", 10 * i, expectedRightOffset),
121                 expectedRightOffset, lane.getLateralBoundaryPosition(LateralDirectionality.RIGHT, i / 10.0).getSI(),
122                 0.001);
123             assertEquals("Right edge at " + longitudinalPosition + " should be " + expectedRightOffset,
124                 expectedRightOffset, lane.getLateralBoundaryPosition(LateralDirectionality.RIGHT, longitudinalPosition)
125                     .getSI(), 0.001);
126         }
127 
128         // Harder case; create a Link with form points along the way
129         // System.out.println("Constructing Link and Lane with one form point");
130         coordinates = new OTSPoint3D[3];
131         coordinates[0] = new OTSPoint3D(nodeFrom.getPoint().x, nodeFrom.getPoint().y, 0);
132         coordinates[1] = new OTSPoint3D(200, 100);
133         coordinates[2] = new OTSPoint3D(nodeTo.getPoint().x, nodeTo.getPoint().y, 0);
134         link =
135             new CrossSectionLink("A to B with Kink", nodeFrom, nodeTo, LinkType.ALL, new OTSLine3D(coordinates),
136                 LongitudinalDirectionality.DIR_PLUS, LaneKeepingPolicy.KEEP_RIGHT);
137         // FIXME what overtaking conditions do we ant to test in this unit test?
138         lane =
139             new Lane(link, "lane.1", startLateralPos, endLateralPos, startWidth, endWidth, laneType, directionalityMap,
140                 speedMap, new OvertakingConditions.LeftAndRight());
141         // Verify the easy bits
142         assertEquals("PrevLanes should be empty", 0, lane.prevLanes(gtuTypeCar).size());
143         assertEquals("NextLanes should be empty", 0, lane.nextLanes(gtuTypeCar).size());
144         approximateLengthOfContour =
145             2 * (coordinates[0].distanceSI(coordinates[1]) + coordinates[1].distanceSI(coordinates[2]))
146                 + startWidth.getSI() + endWidth.getSI();
147         assertEquals("Length of contour is approximately " + approximateLengthOfContour, approximateLengthOfContour,
148             lane.getContour().getLengthSI(), 4); // This lane takes a path that is about 3m longer
149         assertEquals("There should be no GTUs on the lane", 0, lane.getGtuList().size());
150         assertEquals("LaneType should be " + laneType, laneType, lane.getLaneType());
151         // System.out.println("Add another Lane at the inside of the corner in the design line");
152         Length.Rel startLateralPos2 = new Length.Rel(-8, METER);
153         Length.Rel endLateralPos2 = new Length.Rel(-5, METER);
154         // FIXME what overtaking conditions do we ant to test in this unit test?
155         Lane lane2 =
156             new Lane(link, "lane.2", startLateralPos2, endLateralPos2, startWidth, endWidth, laneType,
157                 directionalityMap, speedMap, new OvertakingConditions.LeftAndRight());
158         // Verify the easy bits
159         assertEquals("PrevLanes should be empty", 0, lane2.prevLanes(gtuTypeCar).size());
160         assertEquals("NextLanes should be empty", 0, lane2.nextLanes(gtuTypeCar).size());
161         approximateLengthOfContour =
162             2 * (coordinates[0].distanceSI(coordinates[1]) + coordinates[1].distanceSI(coordinates[2]))
163                 + startWidth.getSI() + endWidth.getSI();
164         assertEquals("Length of contour is approximately " + approximateLengthOfContour, approximateLengthOfContour,
165             lane2.getContour().getLengthSI(), 12); // This lane takes a path that is about 11 meters shorter
166         assertEquals("There should be no GTUs on the lane", 0, lane2.getGtuList().size());
167         assertEquals("LaneType should be " + laneType, laneType, lane2.getLaneType());
168     }
169 
170     /**
171      * Test that the contour of a constructed lane covers the expected area. Tests are only performed for straight lanes, but
172      * the orientation of the link and the offset of the lane from the link is varied in many ways.
173      * @throws Exception when something goes wrong (should not happen)
174      */
175     @Test
176     public void contourTest() throws Exception
177     {
178         final int[] startPositions = {0, 1, -1, 20, -20};
179         final double[] angles =
180             {0, Math.PI * 0.01, Math.PI / 3, Math.PI / 2, Math.PI * 2 / 3, Math.PI * 0.99, Math.PI, Math.PI * 1.01,
181                 Math.PI * 4 / 3, Math.PI * 3 / 2, Math.PI * 1.99, Math.PI * 2, Math.PI * (-0.2)};
182         LaneType laneType = new LaneType("Car");
183         Map<GTUType, LongitudinalDirectionality> directionalityMap = new LinkedHashMap<>();
184         directionalityMap.put(GTUType.ALL, LongitudinalDirectionality.DIR_PLUS);
185         Map<GTUType, Speed> speedMap = new LinkedHashMap<>();
186         speedMap.put(GTUType.ALL, new Speed(50, KM_PER_HOUR));
187         int laneNum = 0;
188         for (int xStart : startPositions)
189         {
190             for (int yStart : startPositions)
191             {
192                 for (double angle : angles)
193                 {
194                     OTSNode start = new OTSNode("start", new OTSPoint3D(xStart, yStart));
195                     double linkLength = 1000;
196                     double xEnd = xStart + linkLength * Math.cos(angle);
197                     double yEnd = yStart + linkLength * Math.sin(angle);
198                     OTSNode end = new OTSNode("end", new OTSPoint3D(xEnd, yEnd));
199                     OTSPoint3D[] coordinates = new OTSPoint3D[2];
200                     coordinates[0] = start.getPoint();
201                     coordinates[1] = end.getPoint();
202                     OTSLine3D line = new OTSLine3D(coordinates);
203                     CrossSectionLink link =
204                         new CrossSectionLink("A to B", start, end, LinkType.ALL, line,
205                             LongitudinalDirectionality.DIR_PLUS, LaneKeepingPolicy.KEEP_RIGHT);
206                     final int[] lateralOffsets = {-10, -3, -1, 0, 1, 3, 10};
207                     for (int startLateralOffset : lateralOffsets)
208                     {
209                         for (int endLateralOffset : lateralOffsets)
210                         {
211                             int startWidth = 4; // This one is not varied
212                             for (int endWidth : new int[]{2, 4, 6})
213                             {
214                                 // Now we can construct a Lane
215                                 // FIXME what overtaking conditions do we ant to test in this unit test?
216                                 Lane lane =
217                                     new Lane(link, "lane." + ++laneNum, new Length.Rel(startLateralOffset, METER),
218                                         new Length.Rel(endLateralOffset, METER), new Length.Rel(startWidth, METER),
219                                         new Length.Rel(endWidth, METER), laneType, directionalityMap, speedMap,
220                                         new OvertakingConditions.LeftAndRight());
221                                 final Geometry geometry = lane.getContour().getLineString();
222                                 assertNotNull("geometry of the lane should not be null", geometry);
223                                 // Verify a couple of points that should be inside the contour of the Lane
224                                 // One meter along the lane design line
225                                 checkInside(lane, 1, startLateralOffset, true);
226                                 // One meter before the end along the lane design line
227                                 checkInside(lane, link.getLength().getSI() - 1, endLateralOffset, true);
228                                 // One meter before the start of the lane along the lane design line
229                                 checkInside(lane, -1, startLateralOffset, false);
230                                 // One meter beyond the end of the lane along the lane design line
231                                 checkInside(lane, link.getLength().getSI() + 1, endLateralOffset, false);
232                                 // One meter along the lane design line, left outside the lane
233                                 checkInside(lane, 1, startLateralOffset - startWidth / 2 - 1, false);
234                                 // One meter along the lane design line, right outside the lane
235                                 checkInside(lane, 1, startLateralOffset + startWidth / 2 + 1, false);
236                                 // One meter before the end, left outside the lane
237                                 checkInside(lane, link.getLength().getSI() - 1, endLateralOffset - endWidth / 2 - 1,
238                                     false);
239                                 // One meter before the end, right outside the lane
240                                 checkInside(lane, link.getLength().getSI() - 1, endLateralOffset + endWidth / 2 + 1,
241                                     false);
242                                 // Check the result of getBounds.
243                                 DirectedPoint l = lane.getLocation();
244                                 Bounds bb = lane.getBounds();
245                                 // System.out.println("bb is " + bb);
246                                 // System.out.println("l is " + l.x + "," + l.y + "," + l.z);
247                                 // System.out.println("start is at " + start.getX() + ", " + start.getY());
248                                 // System.out.println("  end is at " + end.getX() + ", " + end.getY());
249                                 Point2D.Double[] cornerPoints = new Point2D.Double[4];
250                                 cornerPoints[0] =
251                                     new Point2D.Double(
252                                         xStart - (startLateralOffset + startWidth / 2) * Math.sin(angle), yStart
253                                             + (startLateralOffset + startWidth / 2) * Math.cos(angle));
254                                 cornerPoints[1] =
255                                     new Point2D.Double(
256                                         xStart - (startLateralOffset - startWidth / 2) * Math.sin(angle), yStart
257                                             + (startLateralOffset - startWidth / 2) * Math.cos(angle));
258                                 cornerPoints[2] =
259                                     new Point2D.Double(xEnd - (endLateralOffset + endWidth / 2) * Math.sin(angle), yEnd
260                                         + (endLateralOffset + endWidth / 2) * Math.cos(angle));
261                                 cornerPoints[3] =
262                                     new Point2D.Double(xEnd - (endLateralOffset - endWidth / 2) * Math.sin(angle), yEnd
263                                         + (endLateralOffset - endWidth / 2) * Math.cos(angle));
264                                 for (int i = 0; i < cornerPoints.length; i++)
265                                 {
266                                     // System.out.println("p" + i + ": " + cornerPoints[i].x + "," + cornerPoints[i].y);
267                                 }
268                                 double minX = cornerPoints[0].getX();
269                                 double maxX = cornerPoints[0].getX();
270                                 double minY = cornerPoints[0].getY();
271                                 double maxY = cornerPoints[0].getY();
272                                 for (int i = 1; i < cornerPoints.length; i++)
273                                 {
274                                     Point2D.Double p = cornerPoints[i];
275                                     minX = Math.min(minX, p.getX());
276                                     minY = Math.min(minY, p.getY());
277                                     maxX = Math.max(maxX, p.getX());
278                                     maxY = Math.max(maxY, p.getY());
279                                 }
280                                 Point3d bbLow = new Point3d();
281                                 ((BoundingBox) bb).getLower(bbLow);
282                                 Point3d bbHigh = new Point3d();
283                                 ((BoundingBox) bb).getUpper(bbHigh);
284                                 // System.out.println(" my bbox is " + minX + "," + minY + " - " + maxX + "," + maxY);
285                                 // System.out.println("the bbox is " + (bbLow.x + l.x) + "," + (bbLow.y + l.y) + " - "
286                                 // + (bbHigh.x + l.x) + "," + (bbHigh.y + l.y));
287                                 double boundsMinX = bbLow.x + l.x;
288                                 double boundsMinY = bbLow.y + l.y;
289                                 double boundsMaxX = bbHigh.x + l.x;
290                                 double boundsMaxY = bbHigh.y + l.y;
291                                 assertEquals("low x boundary", minX, boundsMinX, 0.1);
292                                 assertEquals("low y boundary", minY, boundsMinY, 0.1);
293                                 assertEquals("high x boundary", maxX, boundsMaxX, 0.1);
294                                 assertEquals("high y boundary", maxY, boundsMaxY, 0.1);
295                             }
296                         }
297                     }
298                 }
299             }
300         }
301     }
302 
303     /**
304      * Verify that a point at specified distance along and across from the design line of the parent Link of a Lane is inside
305      * c.q. outside the contour of a Lane. The test uses an implementation that is as independent as possible of the Geometry
306      * class methods.
307      * @param lane Lane; the lane
308      * @param longitudinal double; the longitudinal position along the design line of the parent Link of the Lane. This design
309      *            line is expected to be straight and the longitudinal position may be negative (indicating a point before the
310      *            start of the Link) and it may exceed the length of the Link (indicating a point beyond the end of the Link)
311      * @param lateral double; the lateral offset from the design line of the link (positive is left, negative is right)
312      * @param expectedResult boolean; true if the calling method expects the point to be within the contour of the Lane, false
313      *            if the calling method expects the point to be outside the contour of the Lane
314      */
315     private void checkInside(final Lane lane, final double longitudinal, final double lateral,
316         final boolean expectedResult)
317     {
318         CrossSectionLink parentLink = lane.getParentLink();
319         Node start = parentLink.getStartNode();
320         Node end = parentLink.getEndNode();
321         double startX = start.getPoint().x;
322         double startY = start.getPoint().y;
323         double endX = end.getPoint().x;
324         double endY = end.getPoint().y;
325         double length = Math.sqrt((endX - startX) * (endX - startX) + (endY - startY) * (endY - startY));
326         double ratio = longitudinal / length;
327         double designLineX = startX + (endX - startX) * ratio;
328         double designLineY = startY + (endY - startY) * ratio;
329         double lateralAngle = Math.atan2(endY - startY, endX - startX) + Math.PI / 2;
330         double px = designLineX + lateral * Math.cos(lateralAngle);
331         double py = designLineY + lateral * Math.sin(lateralAngle);
332         Geometry contour = lane.getContour().getLineString();
333         GeometryFactory factory = new GeometryFactory();
334         Geometry p = factory.createPoint(new Coordinate(px, py));
335         // CrossSectionElement.printCoordinates("contour: ", contour);
336         // System.out.println("p: " + p);
337         boolean result = contour.contains(p);
338         Coordinate[] polygon = contour.getCoordinates();
339         result = pointInsidePolygon(new Coordinate(px, py), polygon);
340         if (expectedResult)
341         {
342             assertTrue("Point at " + longitudinal + " along and " + lateral + " lateral is within lane", result);
343         }
344         else
345         {
346             assertFalse("Point at " + longitudinal + " along and " + lateral + " lateral is outside lane", result);
347         }
348     }
349 
350     /**
351      * Algorithm of W. Randolph Franklin http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html, found via
352      * stackoverflow.com: http://stackoverflow.com/questions/217578/point-in-polygon-aka-hit-test.
353      * @param point Coordinate; the point
354      * @param polygon OTSPoint3D[]; the polygon (last coordinate is allowed to be identical to the first, but his is not a
355      *            requirement)
356      * @return boolean; true if the point is inside the polygon; false if it is outside the polygon; if the point lies <b>on</b>
357      *         an vertex or edge of the polygon the result is (of course) undefined
358      */
359     private boolean pointInsidePolygon(Coordinate point, Coordinate[] polygon)
360     {
361         boolean result = false;
362         for (int i = 0, j = polygon.length - 1; i < polygon.length; j = i++)
363         {
364             if ((polygon[i].y > point.y) != (polygon[j].y > point.y)
365                 && point.x < (polygon[j].x - polygon[i].x) * (point.y - polygon[i].y) / (polygon[j].y - polygon[i].y)
366                     + polygon[i].x)
367             {
368                 result = !result;
369             }
370         }
371         return result;
372     }
373 
374 }