Class Octant

 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 /**
17  * Methods for computing and working with octants of the Cartesian plane
18  * Octants are numbered as follows:
19  * <pre>
20  *  \2|1/
21  * 3 \|/ 0
22  * ---+--
23  * 4 /|\ 7
24  *  /5|6\
25  * </pre>
26  * If line segments lie along a coordinate axis, the octant is the lower of the two
27  * possible values.
28  *
29  * @version 1.7
30  */
31 public class Octant {
32  
33   /**
34    * Returns the octant of a directed line segment (specified as x and y
35    * displacements, which cannot both be 0).
36    */
37   public static int octant(double dx, double dy)
38   {
39     if (dx == 0.0 && dy == 0.0)
40       throw new IllegalArgumentException("Cannot compute the octant for point ( "+ dx + ", " + dy + " )" );
41  
42     double adx = Math.abs(dx);
43     double ady = Math.abs(dy);
44  
45     if (dx >= 0) {
46       if (dy >= 0) {
47         if (adx >= ady)
48           return 0;
49         else
50           return 1;
51       }
52       else { // dy < 0
53         if (adx >= ady)
54           return 7;
55         else
56           return 6;
57       }
58     }
59     else { // dx < 0
60       if (dy >= 0) {
61         if (adx >= ady)
62           return 3;
63         else
64           return 2;
65       }
66       else { // dy < 0
67         if (adx >= ady)
68           return 4;
69         else
70           return 5;
71       }
72     }
73   }
74  
75   /**
76    * Returns the octant of a directed line segment from p0 to p1.
77    */
78   public static int octant(Coordinate p0, Coordinate p1)
79   {
80     double dx = p1.x - p0.x;
81     double dy = p1.y - p0.y;
82     if (dx == 0.0 && dy == 0.0)
83       throw new IllegalArgumentException("Cannot compute the octant for two identical points " + p0);
84     return octant(dx, dy);
85   }
86  
87   private Octant() {
88   }
89 }
90