001/** 002 * 003 */ 004package icy.type.point; 005 006import java.awt.geom.Point2D; 007import java.util.List; 008 009/** 010 * Utilities for Point2D class. 011 * 012 * @author Stephane 013 */ 014public class Point2DUtil 015{ 016 /** 017 * Test if the 2 specified points are <code>connected</code>.<br> 018 * Points are considered connected if max(deltaX, deltaY) <= 1 019 */ 020 public static boolean areConnected(Point2D p1, Point2D p2) 021 { 022 return Math.max(Math.abs(p2.getX() - p1.getX()), Math.abs(p2.getY() - p1.getY())) <= 1; 023 } 024 025 /** 026 * Returns the L1 distance between 2 points 027 */ 028 public static double getL1Distance(Point2D p1, Point2D p2) 029 { 030 return Math.abs(p2.getX() - p1.getX()) + Math.abs(p2.getY() - p1.getY()); 031 } 032 033 /** 034 * Returns the square of the distance between 2 points. 035 */ 036 public static double getSquareDistance(Point2D pt1, Point2D pt2) 037 { 038 double px = pt2.getX() - pt1.getX(); 039 double py = pt2.getY() - pt1.getY(); 040 return (px * px) + (py * py); 041 } 042 043 /** 044 * Returns the distance between 2 points. 045 */ 046 public static double getDistance(Point2D pt1, Point2D pt2) 047 { 048 return Math.sqrt(getSquareDistance(pt1, pt2)); 049 } 050 051 /** 052 * Returns the distance between 2 points using specified scale factor for x/y dimension. 053 */ 054 public static double getDistance(Point2D pt1, Point2D pt2, double factorX, double factorY) 055 { 056 double px = (pt2.getX() - pt1.getX()) * factorX; 057 double py = (pt2.getY() - pt1.getY()) * factorY; 058 return Math.sqrt(px * px + py * py); 059 } 060 061 /** 062 * Returns the total distance of the specified list of points. 063 */ 064 public static double getTotalDistance(List<Point2D> points, double factorX, double factorY, boolean connectLastPoint) 065 { 066 final int size = points.size(); 067 double result = 0d; 068 069 if (size > 1) 070 { 071 for (int i = 0; i < size - 1; i++) 072 result += getDistance(points.get(i), points.get(i + 1), factorX, factorY); 073 074 // add last to first point distance 075 if (connectLastPoint) 076 result += getDistance(points.get(size - 1), points.get(0), factorX, factorY); 077 } 078 079 return result; 080 } 081}