Simple 2D shape line. @author Ronald Brill
| 20 | * @author Ronald Brill |
| 21 | */ |
| 22 | public class Line2D implements Shape2D { |
| 23 | |
| 24 | private final double startX_; |
| 25 | private final double startY_; |
| 26 | private final double endX_; |
| 27 | private final double endY_; |
| 28 | private final boolean isVertical_; |
| 29 | |
| 30 | private final double slope_; |
| 31 | private final double yIntercept_; |
| 32 | |
| 33 | /** |
| 34 | * Ctor. |
| 35 | * @param start the start point |
| 36 | * @param end the end point |
| 37 | */ |
| 38 | public Line2D(final Point2D start, final Point2D end) { |
| 39 | this(start.getX(), start.getY(), end.getX(), end.getY()); |
| 40 | } |
| 41 | |
| 42 | /** |
| 43 | * Ctor. |
| 44 | * @param x1 the x value of the start point |
| 45 | * @param y1 the y value of the start point |
| 46 | * @param x2 the x value of the end point |
| 47 | * @param y2 the y value of the end point |
| 48 | */ |
| 49 | public Line2D(final double x1, final double y1, final double x2, final double y2) { |
| 50 | startX_ = x1; |
| 51 | startY_ = y1; |
| 52 | endX_ = x2; |
| 53 | endY_ = y2; |
| 54 | |
| 55 | isVertical_ = Math.abs(startX_ - endX_) < EPSILON; |
| 56 | if (isVertical_) { |
| 57 | slope_ = Double.NaN; |
| 58 | yIntercept_ = Double.NaN; |
| 59 | } |
| 60 | else { |
| 61 | // y = slope * x + b |
| 62 | slope_ = (endY_ - startY_) / (endX_ - startX_); |
| 63 | yIntercept_ = startY_ - slope_ * startX_; |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | /** |
| 68 | * @param line the line to intersect this with |
| 69 | * @return the intersection point of the two lines or null if they are parallel |
| 70 | */ |
| 71 | public Point2D intersect(final Line2D line) { |
| 72 | if (isVertical_ && line.isVertical_) { |
| 73 | return null; |
| 74 | } |
| 75 | |
| 76 | if (isVertical_ && !line.isVertical_) { |
| 77 | final double intersectY = line.slope_ * startX_ + line.yIntercept_; |
| 78 | return new Point2D(startX_, intersectY); |
| 79 | } |
nothing calls this directly
no outgoing calls
no test coverage detected
searching dependent graphs…