// Class definition for LineSegmentD import java.awt.*; import java.util.*; public class LineSegmentD { LSPointD p1, p2; int id; LineSegmentCollectionD collection; Vector intersections; public LSPointD getP1() { return p1; } public LSPointD getP2() { return p2; } public LineSegmentD(int anID, LineSegmentCollectionD theCollection) { id = anID; collection = theCollection; p1 = new LSPointD(); p2 = new LSPointD(); computeIntersections(); } public void updateLocation(LSPointD whichPoint, int x, int y) { whichPoint.setX(x); whichPoint.setY(y); computeIntersections(); } public LSPointD getHit(int x, int y) { if (p1.getHit(x, y) != null) return p1; if (p2.getHit(x, y) != null) return p2; return null; } public void paint(Graphics g) { g.drawLine(p1.getX(), p1.getY(), p2.getX(), p2.getY()); plotIntersections(g); } public void computeIntersections() { intersections = new Vector(); for (Enumeration segments = (collection.otherSegments(this)).elements(); segments.hasMoreElements();) { LineSegmentD aLineSeg = (LineSegmentD) segments.nextElement(); LSPointD p = segIntersection(aLineSeg); //System.out.println("Intersection of lines is: (" + p.getX() // + ", " + p.getY() + ")" ); if (p != null) intersections.addElement(p); } } private LSPointD segIntersection(LineSegmentD ls) { LSPointD p3 = ls.getP1(); LSPointD p4 = ls.getP2(); int x1 = p1.getX(); int y1 = p1.getY(); int x2 = p2.getX(); int y2 = p2.getY(); int x3 = p3.getX(); int y3 = p3.getY(); int x4 = p4.getX(); int y4 = p4.getY(); double d1 = (x1 * y2) - (x2 * y1); double d2 = (x3 * y4) - (x4 * y3); double d3 = ((x1 - x2) * (y3 - y4)) - ((x3 - x4) * (y1 - y2)); int x = (int) (((d1 * (x3 - x4)) - (d2 * (x1 - x2))) / d3); int y = (int) (((d1 * (y3 - y4)) - (d2 * (y1 - y2))) / d3); int minx1 = Math.min(x1, x2); if (x < minx1) return null; int maxx1 = Math.max(x1, x2); if (x > maxx1) return null; int miny1 = Math.min(y1, y2); if (y < miny1) return null; int maxy1 = Math.max(y1, y2); if (y > maxy1) return null; int minx2 = Math.min(x3, x4); if (x < minx2) return null; int maxx2 = Math.max(x3, x4); if (x > maxx2) return null; int miny2 = Math.min(y3, y4); if (y < miny2) return null; int maxy2 = Math.max(y3, y4); if (y > maxy2) return null; return new LSPointD(x, y); } private void plotIntersections(Graphics g) { for (Enumeration intPoints = intersections.elements(); intPoints.hasMoreElements();) { LSPointD p = (LSPointD) intPoints.nextElement(); int x = p.getX(); int y = p.getY(); int radius = 5; g.fillOval(x - radius, y - radius, 2 * radius, 2 * radius); } } }