Class SegmentPointComparator

 1 /*
 2  * Copyright (c) 2016 Vivid Solutions.
 3  *
 4  * All rights reserved. This program and the accompanying materials
 5  * are made available under the terms of the Eclipse Public License 2.0
 6  * and Eclipse Distribution License v. 1.0 which accompanies this distribution.
 7  * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v20.html
 8  * and the Eclipse Distribution License is available at
 9  *
10  * http://www.eclipse.org/org/documents/edl-v10.php.
11  */
12  
13 package org.locationtech.jts.noding;
14  
15 import org.locationtech.jts.geom.Coordinate;
16 import org.locationtech.jts.util.Assert;
17  
18 /**
19  * Implements a robust method of comparing the relative position of two
20  * points along the same segment.
21  * The coordinates are assumed to lie "near" the segment.
22  * This means that this algorithm will only return correct results
23  * if the input coordinates
24  * have the same precision and correspond to rounded values
25  * of exact coordinates lying on the segment.
26  *
27  * @version 1.7
28  */
29 public class SegmentPointComparator {
30  
31   /**
32    * Compares two {@link Coordinate}s for their relative position along a segment
33    * lying in the specified {@link Octant}.
34    *
35    * @return -1 node0 occurs first;
36    * 0 the two nodes are equal;
37    * 1 node1 occurs first
38    */
39   public static int compare(int octant, Coordinate p0, Coordinate p1)
40   {
41     // nodes can only be equal if their coordinates are equal
42     if (p0.equals2D(p1)) return 0;
43  
44     int xSign = relativeSign(p0.x, p1.x);
45     int ySign = relativeSign(p0.y, p1.y);
46  
47     switch (octant) {
48       case 0return compareValue(xSign, ySign);
49       case 1return compareValue(ySign, xSign);
50       case 2return compareValue(ySign, -xSign);
51       case 3return compareValue(-xSign, ySign);
52       case 4return compareValue(-xSign, -ySign);
53       case 5return compareValue(-ySign, -xSign);
54       case 6return compareValue(-ySign, xSign);
55       case 7return compareValue(xSign, -ySign);
56     }
57     Assert.shouldNeverReachHere("invalid octant value");
58     return 0;
59   }
60  
61   public static int relativeSign(double x0, double x1)
62   {
63     if (x0 < x1) return -1;
64     if (x0 > x1) return 1;
65     return 0;
66   }
67  
68   private static int compareValue(int compareSign0, int compareSign1)
69   {
70     if (compareSign0 < 0return -1;
71     if (compareSign0 > 0return 1;
72     if (compareSign1 < 0return -1;
73     if (compareSign1 > 0return 1;
74     return 0;
75  
76   }
77 }
78