Find the vertex in hull farthest away from a point
764741
def find_farthest(point, hull):
    ''''''
    d_start = np.sum((point-hull[0,:])**2)
    d_end = np.sum((point-hull[-1,:])**2)
    if d_start > d_end:
        # Go in the forward direction
        i = 1
        inc = 1
        term = hull.shape[0]
        d2_max = d_start
    else:
        # Go in the reverse direction
        i = hull.shape[0]-2
        inc = -1
        term = -1
        d2_max = d_end
    while i != term:
        d2 = np.sum((point - hull[i,:])**2)
        if d2 < d2_max:
            break
        i += inc
        d2_max = d2
    return i-inc
1373736
def bound(self, p1, p2=None):
    """"""
    r = Rect(p1, p2)
    return Point(min(max(self.x, r.l), r.r), min(max(self.y, r.t), r.b))
502616
def distance_from_point(self, pt):
        
        return np.linalg.norm(np.array(pt) - self.coords)
574341
def is_edge_not_excluding_vertices(self, other):
        """"""

        c_a = cos(self.angle)
        s_a = sin(self.angle)

        # Get min and max of other.

        other_x_min, other_x_max, other_y_min, other_y_max = other.get_bbox()

        self_x_diff = 0.5 * self.width
        self_y_diff = 0.5 * self.height

        if c_a > 0:
            if s_a > 0:
                return \
                    c_a * other_x_max + s_a * other_y_max < -self_x_diff or \
                    c_a * other_x_min + s_a * other_y_min >  self_x_diff or \
                    c_a * other_y_max - s_a * other_x_min < -self_y_diff or \
                    c_a * other_y_min - s_a * other_x_max >  self_y_diff

            else:  # s_a <= 0.0
                return \
                    c_a * other_x_max + s_a * other_y_min < -self_x_diff or \
                    c_a * other_x_min + s_a * other_y_max >  self_x_diff or \
                    c_a * other_y_max - s_a * other_x_max < -self_y_diff or \
                    c_a * other_y_min - s_a * other_x_min >  self_y_diff

        else:  # c_a <= 0.0
            if s_a > 0:
                return \
                    c_a * other_x_min + s_a * other_y_max < -self_x_diff or \
                    c_a * other_x_max + s_a * other_y_min >  self_x_diff or \
                    c_a * other_y_min - s_a * other_x_min < -self_y_diff or \
                    c_a * other_y_max - s_a * other_x_max >  self_y_diff

            else:  # s_a <= 0.0
                return \
                    c_a * other_x_min + s_a * other_y_min < -self_x_diff or \
                    c_a * other_x_max + s_a * other_y_max >  self_x_diff or \
                    c_a * other_y_min - s_a * other_x_max < -self_y_diff or \
                    c_a * other_y_max - s_a * other_x_min >  self_y_diff
827345
private void closestFarthestPoints(LineSegment2D_F32 a, LineSegment2D_F32 b)
	{
		dist[0] = a.a.distance2(b.a);
		dist[1] = a.a.distance2(b.b);
		dist[2] = a.b.distance2(b.a);
		dist[3] = a.b.distance2(b.b);

		// find the two points which are closest together and save which ones those are
		// for future reference
		farthestIndex = 0;
		float closest = dist[0];
		float farthest = dist[0];
		for( int i = 1; i < 4; i++ ) {
			float d = dist[i];
			if( d < closest ) {
				closest = d;
				closestIndex = i;
			}
			if( d > farthest ) {
				farthest = d;
				farthestIndex = i;
			}
		}
	}
1048504
def distance(self, other):
        """"""
        return math.acos(self._pos3d.dot(other.vector))
1247440
void findVertexNeighbors(Vertex target  , List<ChessboardCorner> corners ) {
//		if( target.index == 18 ) {
//			System.out.println("Vertex Neighbors "+target.index);
//		}

		ChessboardCorner targetCorner = corners.get(target.index);
		// distance is Euclidean squared
		double maxDist = Double.MAX_VALUE==maxNeighborDistance?maxNeighborDistance:maxNeighborDistance*maxNeighborDistance;
		nnSearch.findNearest(corners.get(target.index),maxDist,maxNeighbors,nnResults);

		// storage distances here to find median distance of closest neighbors
		distanceTmp.reset();

		for (int i = 0; i < nnResults.size; i++) {
			NnData<ChessboardCorner> r = nnResults.get(i);
			if( r.index == target.index) continue;

			distanceTmp.add( r.distance );

			double oriDiff = UtilAngle.distHalf( targetCorner.orientation , r.point.orientation );

			Edge edge = edges.grow();
			boolean parallel;
			if( oriDiff <= orientationTol) { // see if it's parallel
				parallel = true;
			} else if( Math.abs(oriDiff-Math.PI/2.0) <= orientationTol) { // see if it's perpendicular
				parallel = false;
			} else {
				edges.removeTail();
				continue;
			}

			// Use the relative angles of orientation and direction to prune more obviously bad matches
			double dx = r.point.x - targetCorner.x;
			double dy = r.point.y - targetCorner.y;

			edge.distance = Math.sqrt(r.distance);
			edge.dst = vertexes.get(r.index);
			edge.direction = Math.atan2(dy,dx);

			double direction180 = UtilAngle.boundHalf(edge.direction);
			double directionDiff = UtilAngle.distHalf(direction180,r.point.orientation);
			boolean remove;
			EdgeSet edgeSet;
			if( parallel ) {
				// test to see if direction and orientation are aligned or off by 90 degrees
				remove = directionDiff > 2* directionTol && Math.abs(directionDiff-Math.PI/2.0) > 2* directionTol;
				edgeSet = target.parallel;
			} else {
				// should be at 45 degree angle
				remove = Math.abs(directionDiff-Math.PI/4.0) > 2* directionTol;
				edgeSet = target.perpendicular;
			}

			if( remove ) {
				edges.removeTail();
				continue;
			}

			edgeSet.add(edge);
		}

		// Compute the distance of the closest neighbors. This is used later on to identify ambiguous corners.
		// If it's a graph corner there should be at least 3 right next to the node.
		if( distanceTmp.size == 0 ) {
			target.neighborDistance = 0;
		} else {
			sorter.sort(distanceTmp.data, distanceTmp.size);
			int idx = Math.min(3,distanceTmp.size-1);
			target.neighborDistance = Math.sqrt(distanceTmp.data[idx]); // NN distance is Euclidean squared
		}
	}
759911
static int findCornerSeed(List<Point2D_I32> contour ) {
		Point2D_I32 a = contour.get(0);

		int best = -1;
		double bestDistance = -Double.MAX_VALUE;

		for (int i = 1; i < contour.size(); i++) {
			Point2D_I32 b = contour.get(i);

			double d = distanceSq(a,b);
			if( d > bestDistance ) {
				bestDistance = d;
				best = i;
			}
		}

		return best;
	}
1105164
def nearest_point(x, y, pts, mode='random'):
    
    dists = (pts.T[0] - x) ** 2 + (pts.T[1] - y) ** 2
    fx = dists.argmin()
    mindist = dists[fx]
    other_fx = np.where(mindist == dists)[0]
    if len(other_fx) > 0:
        if mode == 'random':
            np.random.shuffle(other_fx)
            fx = other_fx[0]
        if mode == 'all':
            fx = other_fx
        if mode == 'first':
            fx = fx
    return fx, mindist
770593
function( hull ){

            var scratch = Physics.scratchpad()
                ,transl = scratch.transform()
                ,verts = this.vertices = []
                ;

            if ( !Physics.geometry.isPolygonConvex( hull ) ){
                throw ERROR_NOT_CONVEX;
            }

            transl.setRotation( 0 );
            transl.setTranslation( Physics.geometry.getPolygonCentroid( hull ).negate() );

            // translate each vertex so that the centroid is at the origin
            // then add the vertex as a vector to this.vertices
            for ( var i = 0, l = hull.length; i < l; ++i ){

                verts.push( new Physics.vector( hull[ i ] ).translate( transl ) );
            }

            this._area = Physics.geometry.getPolygonArea( verts );
            this._aabb = false;
            return scratch.done(this);
        }
161035
def convex_hull(self):
        
        if self._faces is None:
            if self._vertices is None:
                return None
            self.triangulate()
        return self._convex_hull
737469
function (bounds, vertex, next, orthogonal)
	{
		var x = bounds.x;
		var y = bounds.y;
		var w = bounds.width;
		var h = bounds.height;
		
		var cx = x + w / 2;
		var cy = y + h / 2;

		var px = next.x;
		var py = next.y;

		// Special case for intersecting the diamond's corners
		if (cx == px)
		{
			if (cy > py)
			{
				return new mxPoint(cx, y); // top
			}
			else
			{
				return new mxPoint(cx, y + h); // bottom
			}
		}
		else if (cy == py)
		{
			if (cx > px)
			{
				return new mxPoint(x, cy); // left
			}
			else
			{
				return new mxPoint(x + w, cy); // right
			}
		}
		
		var tx = cx;
		var ty = cy;
		
		if (orthogonal)
		{
			if (px >= x && px <= x + w)
			{
				tx = px;
			}
			else if (py >= y && py <= y + h)
			{
				ty = py;
			}
		}
		
		// In which quadrant will the intersection be?
		// set the slope and offset of the border line accordingly
		if (px < cx)
		{
			if (py < cy)
			{
				return mxUtils.intersection(px, py, tx, ty, cx, y, x, cy);
			}
			else
			{
				return mxUtils.intersection(px, py, tx, ty, cx, y + h, x, cy);
			}
		}
		else if (py < cy)
		{
			return mxUtils.intersection(px, py, tx, ty, cx, y, x + w, cy);
		}
		else
		{
			return mxUtils.intersection(px, py, tx, ty, cx, y + h, x + w, cy);
		}
	}
344981
public Result<float[]> closestPointOnPolyBoundary(long ref, float[] pos) {

        Result<Tupple2<MeshTile, Poly>> tileAndPoly = m_nav.getTileAndPolyByRef(ref);
        if (tileAndPoly.failed()) {
            return Result.of(tileAndPoly.status, tileAndPoly.message);
        }
        MeshTile tile = tileAndPoly.result.first;
        Poly poly = tileAndPoly.result.second;
        if (tile == null) {
            return Result.invalidParam("Invalid tile");
        }

        if (Objects.isNull(pos) || !vIsFinite(pos)) {
            return Result.invalidParam();
        }
        // Collect vertices.
        float[] verts = new float[m_nav.getMaxVertsPerPoly() * 3];
        float[] edged = new float[m_nav.getMaxVertsPerPoly()];
        float[] edget = new float[m_nav.getMaxVertsPerPoly()];
        int nv = poly.vertCount;
        for (int i = 0; i < nv; ++i) {
            System.arraycopy(tile.data.verts, poly.verts[i] * 3, verts, i * 3, 3);
        }

        float[] closest;
        if (distancePtPolyEdgesSqr(pos, verts, nv, edged, edget)) {
            closest = vCopy(pos);
        } else {
            // Point is outside the polygon, dtClamp to nearest edge.
            float dmin = edged[0];
            int imin = 0;
            for (int i = 1; i < nv; ++i) {
                if (edged[i] < dmin) {
                    dmin = edged[i];
                    imin = i;
                }
            }
            int va = imin * 3;
            int vb = ((imin + 1) % nv) * 3;
            closest = vLerp(verts, va, vb, edget[imin]);
        }
        return Result.success(closest);
    }
428508
def furthest_distance_to(self, position: Union[Unit, Point2, Point3]) -> Union[int, float]:
        
        assert self.exists
        if isinstance(position, Unit):
            position = position.position
        return position.distance_to_furthest([u.position for u in self])
792009
def distance_to(self, *args):
        """"""
        if not len(args) > 0:
            raise ValueError("at least one parameter must be given")

        x = args[0]
        if len(args) > 1:
            unit = args[1]
        else:
            unit = "px"
        u = {"px": (1.,1.), "in": (1.,72.), "cm": (2.54, 72.),
             "mm": (25.4, 72.)}
        f = u[unit][0] / u[unit][1]
        if type(x) is Point:
            return abs(self - x) * f

# from here on, x is a rectangle
# as a safeguard, make a finite copy of it
        r = Rect(x.top_left, x.top_left)
        r = r | x.bottom_right
        if self in r:
            return 0.0
        if self.x > r.x1:
            if self.y >= r.y1:
                return self.distance_to(r.bottom_right, unit)
            elif self.y <= r.y0:
                return self.distance_to(r.top_right, unit)
            else:
                return (self.x - r.x1) * f
        elif r.x0 <= self.x <= r.x1:
            if self.y >= r.y1:
                return (self.y - r.y1) * f
            else:
                return (r.y0 - self.y) * f
        else:
            if self.y >= r.y1:
                return self.distance_to(r.bottom_left, unit)
            elif self.y <= r.y0:
                return self.distance_to(r.top_left, unit)
            else:
                return (r.x0 - self.x) * f
1090546
def closestDirectDistance(arr, ksize=30, dtype=np.uint16):
    '''
    
    '''

    out = np.zeros_like(arr, dtype=dtype)
    _calc(out, arr, ksize)
    return out
206201
function getPointProps(svg) {
            let mousePos = d3Selection.mouse(svg);

            mousePos[0] -= margin.left;
            mousePos[1] -= margin.top;

            return {
                closestPoint: voronoi.find(mousePos[0], mousePos[1]),
                mousePos
            };
        }