Find a set of points of a circle draped on a 3D height map - algorithm

I have a height map of NxN values.
I would like to find, given a point A (the red dot), whose x and y coordinates are given (and z is known from the data, so A is a vertex of the surface) a set of points that lie on the circumference of the circle with center in A and radius R that are a good approximation of a circular "cloth" (in grey) draped on the imaginary surface described by the data points.
The sampling, the reciprocal distances between the set of points that I am trying to find, doesn't need to be uniform, but still I would like to find at least all the points that are an intersection of the edges of the mesh with the circle at distance R from A.
How to find this set of points?
Is this a known problem?
(source: keplero.com)
-- edit
The assumption that Jan is using is right: the samples form a regular rectangular or square grid (in the X-Y plane) aligned with [0,0]. But I would like to take the displacement in the Z direction into account to compute the distance. you can see the height map as a terrain, and the algorithm I am looking for as the instructions to give to an explorer that, traveling just on paths of given latitude or longitude, mark the points that are at distance R from A. Walking distance, that is taking into account all the Z displacements done so far. The explorer climbs and go down in the valleys too.
The trivial algorithm for this would be something like this. We know that given R, the maximum displacement on the x and y axis corresponds to a completely flat surface. If there is no slope, the x,y points will all be in the bounding square Ax-R < x < Ax+r and Ay-R
At this point, it would start traveling to the close cells, since if the perimeter enters the edge of one cell of the grid, it also have to exit that cell.

I reckon this is going to be quite difficult to solve in an exact fashion, so I would suggest trying the straightforward approach of simulating the paths that your explorers would take on the surface.
Given your starting point A and a travel distance d, calculate a circle of points P on the XY plane that are d from A.
For each of the points p in P, intersect the line segment A-p with your grid so that you end up with a sequence of points where the explorer crosses from one grid square to the next, in the order that this would happen if the explorer were travelling from A. These points should then be given a z-coordinate by interpolation from your grid data.
You can thus advance through this point sequence and keep track of the distance travelled so far. Eventually the target distance will be reached - adjust p to be at this point.
P now contains the perimeter that you're looking for. Adjust the sample fidelity (size of P) according to your needs.

Just to clarify - You have a triangulated surface in 3d and, for a given starting vertex Vi in the mesh you would like to find the set of vertices U that are reachable via paths along the surface (i.e. geodesics) with length Li <= R.
One approach would be to transform this to a graph-based problem:
Form the weighted, undirected graph G(V,E), where V is the set of vertices in the triangulated surface mesh and E is the set of edges in this mesh. The edge weight should be the Euclidean (3d) length of each edge. This graph is a discrete distance map - the distance "along the surface" between each adjacent vertex in the mesh.
Run a variant of Dijkstra's algorithm from the starting vertex Vi, only expanding paths with length Li that satisfy the constraint Li <= R. The set of vertices visited U, will be those that can be reached by the shortest (geodesic) path with Li <= R.
The accuracy of this approach should be related to the resolution of the surface mesh - as long as the surface curvature within each element is not too high the Euclidean edge length should be a good approximation to the actual geodesic distance, if not, the surface mesh should be refined in that area.
Hope this helps.

Related

Fast 2D signed distance

I need a way to compute the distance beetween a point and the bounding edge of a polygon.
If the point is outside the polygon, the distance will be posivite
If the point is inside the polygon, the distance will be negative
This is called SDF for Signed Distance Field/Function
The polygon itself is composed of multiple paths, can be concave, with holes, but not self intersecting, and with a lot of clockwise ordered points (10000+).
I've found some existing solutions, but they require to test the point against each polygon edge, which is not efficient enough.
Here is the visual result produced (green is positive, red is negative):
So I've tried the following:
Put the polygon edges in a quadtree
To compute the distance, find the closest edge to the point and change the sign depending on which side of the edge the point is.
Sadly, it doesn't works when the point is at the same distance of multiple edges, such as corners.
I've tried adding condition so a point is outside the polygon if it's on the exterior side of all the edges, but it doesn't solve the interior problem, and the other way around.
Can't wrap my head around it...
If anyone curious, the idea is to later use some shader to produce images like this :
EDIT
To clarify, here is a close up of the problem arising at corners :
For all the points in area A, the closest segment is S1, so no problem
For all the points in area E, the closest segment is S2, so no problem either
All points in area B, C and D are at the same distance of S1 and S2
Points in area B are on the exterior side of S1 and interior side of S2
Points in area D are on the interior side of S1 and exterior side of S2
Points in area C are on the exterior side of both segments
One might think that a point has to be on the interior side of both segments in order to be considered "in". It solves the problem for angles < 180°, but the problem is mirrored for angles > 180°
Worst, two or more corners can share the same position (like the four way corner in the low part of first image)...
I hope this solves your problem.
This is implemented in Python.
First, we use imageio to import the image as an array. We need to use a modified version of your image (I filled the interior region in white).
Then, we transform the RGBA matrix into a binary matrix with a 0 contour defining your interface (phi in the code snippet)
Here's phi from the snippet below (interior region value = +0.5, exterior region value = -0.5):
import imageio
import numpy as np
import matplotlib.pyplot as plt
import skfmm
# Load image
im = imageio.imread("0WmVI_filled.png")
ima = np.array(im)
# Differentiate the inside / outside region
phi = np.int64(np.any(ima[:, :, :3], axis = 2))
# The array will go from - 1 to 0. Add 0.5(arbitrary) so there 's a 0 contour.
phi = np.where(phi, 0, -1) + 0.5
# Show phi
plt.imshow(phi)
plt.xticks([])
plt.yticks([])
plt.colorbar()
plt.show()
# Compute signed distance
# dx = cell(pixel) size
sd = skfmm.distance(phi, dx = 1)
# Plot results
plt.imshow(sd)
plt.colorbar()
plt.show()
Finally, we use the scikit-fmm module to compute the signed distance.
Here's the resulting signed distance field:
For closed, non-intersecting and well oriented polygons, you can speed up the calculation of a signed distance field by limiting the work to feature extrusions based on this paper.
The closest point to a line lies within the edge extrusion as you have shown in your image (regions A and E). The closest feature for the points in B, C and D are not the edges but the vertex.
The algorithm is:
for each edge and vertex construct negative and positive extrusions
for each point, determine which extrusions they are in and find the smallest magnitude distance of the correct sign.
The work is reduced to a point-in-polygon test and distance calculations to lines and points. For reduced work, you can consider limited extrusions of the same size to define a thin shell where distance values are calculated. This seems the desired functionality for your halo shading example.
While you still have to iterate over all features, both extrusion types are always convex so you can have early exits from quad trees, half-plane tests and other optimisations, especially with limited extrusion distances.
The extrusions of edges are rectangles in the surface normal direction (negative normal for interior distances).
From 1:
The extrusions for vertices are wedges whose sides are the normals of the edges that meet at that vertex. Vertices have either positive or negative extrusions depending on the angle between the edges. Flat vertices will have no extrusions as the space is covered by the edge extrusions.
From 1:

Scale one polygon to touch another polygon

I'm looking to scale one concave polygon (specifically, applying a scaling affine transformation relative to the shape's centroid position to both axes) such that it intersects/touches another concave polygon. The polygons are each defined by a set of coordinates.
The illustration below shows an iterative approach: gradually scaling the polygon until the distance between the nearest points of the two polygons equals zero (I'm using the JTS library's DistanceOp.nearestPoints() for this).
Is there an non-iterative way to do this? A way to produce the required scaling factor immediately, without iteratively scaling and checking?
I see it like this:
The top triangle is the one to be scaled and the bottom is the one to touch. Let define some therms first. Let the scaled polygon (top) be A and the bottom be B Let the center of scaling be P0 (red point inside A) There are 2 cases (left and right). For both obtaining the touch point/edge (blue stuff in both A,B) position in both A and B is enough to compute the scale.
edge of A touch vertex of B (left)
simply cast ray from P0 through each vertex of A and then for each edge of A compute the perpendicular distance between selected edge of A and vertex of B that is inside the pie slice (two ray cast through the selected edge of A endpoints. Remember the closest one.
Vertex of A touch edge or vertex of B (right)
simply cast ray from P0 through each vertex of A and find closest intersection point with B (distance to P0).
So now we have a list of possible touch and we need to select the one that touches with smallest scale. So we need for each such touch know distance between P0 and selected vertex or edge (call it da) and distance between P0 and touch point in B (let call it db). From there applying scale changed da and we want da = db so:
da' = da*scale = db
scale = db/da
In some cases edge of A can touch edge of B however this case is handled by both #1,#2 because either edge of B is completely inside edge of A so the vertexes of B hit there too or the edge of B intersects ray and again the intersection is the same.
You can "unroll" both shapes around the scaling center, i.e. convert to (distance, azimuth) coordinates. Both shapes can be decomposed in (possibly overlapping) sectors, and by a sorting/merging process, you can find the portions of sectors where a single edge of both polygons face each other. The smallest of all ratios of the distances to the endpoints will give you the solution. After the vertices are sorted, the merging process is linear in the total number of vertices.

How do I determine label offset so the label is always on the outside of a polygon?

I'm have some vertices of a polygon with labels on them. I want to place the labels so that they are always on the outside of the polygon. So in the image above, all of the labels are fine except for #3 and #4, which I want to be on the bottom, outside of the polygon. So generally, how do I determine, for a particular vertex, how to offset it such that it's outside the polygon?
Since you do not show any code of your own, I will just state some ideas. If you want more details including code, show more effort of your own then ask.
I'll assume here that the polygon is assumed to be a simple polygon--one that does not intersect itself. If a polygon does intersect itself, the definition of its "inside" is not so straightforward and there are multiple definitions of the inside. I will not assume that the polygon is convex--all the interior angles are less than 180°. (That would allow an easier answer.) I'll also assume that you want the center of your label to be outside the polygon but will allow a corner or small part of the label to be inside.
First, traverse the polygon and find its "winding angle," the amount the direction angle changes during the traversal. If the polygon is simple, the angle will be either +180° or -180°. One of those means you traversed the polygon clockwise, the other one means counter-clockwise. (Which is which depends on your coordinate system: Cartesian or graphing or other.)
Then traverse the polygon again. Now that you know the direction of the polygon, at each vertex you can find whether the exterior angle goes clockwise or counterclockwise from the entering segment. Find that direction and the size of the angle, then move half that angle in that direction. Move a given distance from the vertex along that angle, and you have the position of the center of your label.
That should work well for the vast majority of polygons. In some edge cases for non-convex polygons, that location moved away from the polygon into another part of the polygon. You then reduce the distance the label is from its vertex until the label moves back into the polygon's outside.
I gave an answer to a related question: How do I efficiently determine if a polygon is convex, non-convex or complex?.
On every vertex, the incoming and outgoing edges form an angle that covers some sector. You can place the label at some distance along the bisector of this angle. You find the direction vector of the bisector by adding two unit vectors originating from the vertex in the directions of the edges.
Finding the correct bisector side requires some care. In the first place, you need to orient the polygon, i.e. check if it is clockwise or counterclockwise. This is simply done by computing the area with the shoelace formula and testing the sign.
Then, if I am right, you can test the area of triangle formed by the two edges and compare its sign to that of the whole polygon. This tells you if the angle is convex or reflex, and you know the proper side. For a convex polygon, the side is always negative for a vector computed as above.
Maybe follow something like this: First, make sure the polygon does not self-intersect, see the previous answers. Then, let the polygon be counter-clockwise oriented and represented by an array (a 2 by n+2 matrix) of its vertices (the vertices are traversed in counter-clockwise order)
double P[n+2][2] = {{pxn, pyn}, {px1, py1}, {px2, py2}, ..., {pxn, pyn}, {px1, py1}};
double Label_position[n][2];
void generate_labels(const double (&P)[n+2][2], double (&Label_position)[n][2]){
double v1[2];
double v2[2];
for(j = 1, j <= n, j = j+1) {
v1[0] = P[j][0] - P[j-1][0];
v1[1] = P[j][1] - P[j-1][1];
v2[0] = P[j+1][0] - P[j][0];
v2[1] = P[j+1][1] - P[j][1];
v1 = normalize(v1);
v2 = normalize(v2);
t = add_vectors(v1, v2);
t = normalize(t);
Label_position[j][0] = t[1] + P[j][0];
Label_position[j][1] = - t[0] + P[j][1];
}
}
This function generates the coordinates of the points at the tips of the unit angle bisector vectors pointing in the exterior of the polygon (see Yves Daoust's answer and the picture he has generated).

How to find a ray that intersects a polygon minimum times?

Let P be a simple, but not necessarily convex, polygon and q an arbitrary
point not necessarily in P.
Design an efficient algorithm to find a line segment originating from q that intersects the minimum number of edges of P.
If q is your point in the space of 2D, we can write q(x,y). We know that a polyhedron have the edges(E), vertices(V) and faces(F) which all of this terms are related with the formula V - E + F = 2 from the Euler's theorem but the problem turns out to be easier since it is for a polygon.
So the plain is to find an edge and calcule the direction vector of the point q(x,y) to the center of the edge, doing this (and if the polygon is convex) we are sure that this line segment will only goes through one edge of P.
The calculation will need a little of linear algebra, but it is not that difficult, for example:
1 - Find the distance from a line to a point (so we can find the closest edge to use in this problem):
2 - Also, a good idea would be to find the point on this line which is closest to (x0,y0) has coordinates:
Where the equation of the line is ax + by + c = 0 and the (x0,y0) is an arbitrary point not necessarily in P.
So, now we can find the point k(x,y) on the line that is closest to the initial point q(x0,y0), doing |q-k| = d. Where d is the distance that we just calculate. After that you already have everything that you need to find a line segment originating from q that intersects the minimum number of edges of P.
Some places where you can study and find more about this topic:
Wiki
mathwords
Think of doing this on a map, so you can think of directions like North, South, East, West, and bearings.
If you have a ray going in a particular direction from q out to infinity, whether it intersects a line between points A and B depends only on the bearing of the ray, and the bearings from q to A and B: if the bearing of the ray is within the range spanned by the bearing from q to A and the bearing from q to B, taking this in the direction of the line, then the ray will intersect the line.
So you can reduce this to a simpler problem. Imagine that all the points are in a circle around q, and the lines are arcs of this circle. Now you need to find a point on this circle which is overlapped by the minimum number of arcs. You will also make life very much easier if you divide each arc that spans 0 degrees into two at 0, cutting e.g. an arc from 320 degrees round to 40 degrees into one from 320 degrees to 360=0 degrees, and one from 0 degrees to 40 degrees.
Good candidate points for this are points just clockwise of each point in the circle. Now order each arc so that it is from a low angle to a high angle, sort the arcs by low angle, and work through them in order, incrementing a counter when you see the start of an arc, and decrementing it when you see the end of an arc (you don't need to worry about arcs that wrap across 0=360 degrees because you have just made sure that there aren't any). The point you want to find is the one associated with the smallest value of the counter.
Taking q as the origin of the coordinates, compute the polar arguments of the vertices. This is done in linear time.
Then every edge spans an interval of angles. To handle the wraparound, you can split the intervals that cross the 360° border.
You turned the problem in an instance of 1D intervals overlap. This is readily solved in O(N Log(N)) time.

Largest circle inside a non-convex polygon

How can I find the largest circle that can fit inside a concave polygon?
A brute force algorithm is OK as long as it can handle polygons with ~50 vertices in real-time.
The key to solving this problem is first making an observation: the center of the largest circle that will fit inside an arbitrary polygon is the point that is:
Inside the polygon; and
Furthest from any point on the edges of the polygon.
Why? Because every point on the edge of a circle is equidistant from that center. By definition, the largest circle will have the largest radius and will touch the polygon on at least two points so if you find the point inside furthest from the polygon you've found the center of the circle.
This problem appears in geography and is solved iteratively to any arbitrary precision. Its called the Poles of Inaccessibility problem. See Poles of Inaccessibility: A Calculation Algorithm for the Remotest Places on Earth.
The basic algorithm works like this:
Define R as a rectilinear region from (xmin,ymin) to (xmax,ymax);
Divide R into an arbitrary number of points. The paper uses 21 as a heuristic (meaning divide the height and width by 20);
Clip any points that are outside the polygon;
For the remainder find the point that is furthest from any point on the edge;
From that point define a new R with smaller intervals and bounds and repeat from step 2 to get to any arbitrary precision answer. The paper reduces R by a factor of the square root of 2.
One note, How to test if a point is inside the polygon or not: The simplest solution to this part of the problem is to cast a ray to the right of the point. If it crosses an odd number of edges, it's within the polygon. If it's an even number, it's outside.
Also, as far as testing the distance to any edge there are two cases you need to consider:
The point is perpendicular to a point on that edge (within the bounds of the two vertices); or
It isn't.
(2) is easy. The distance to the edge is the minimum of the distances to the two vertices. For (1), the closest point on that edge will be the point that intersects the edge at a 90 degree angle starting from the point you're testing. See Distance of a Point to a Ray or Segment.
In case anyone is looking for a practical implementation, I designed a faster algorithm that solves this problem for a given precision and made it a JavaScript library. It's similar to the iterative grid algorithm described by #cletus, but it's guaranteed to obtain global optimum, and is also 20-40 times faster in practice.
Check it out: https://github.com/mapbox/polylabel
An O(n log(n)) algorithm:
Construct the Voronoi Diagram of the edges in P. This can be done with, for example, Fortunes algorithm.
For Voronoi nodes (points equidistant to three or more edges) inside P;
Find the node with the maximum distance to edges in P. This node is the centre of the maximum inscribed circle.
Summary: In theory, this can be done in O(n) time. In practice you can do it in O(n log n) time.
Generalized Voronoi diagrams.
If you consider the vertices and edges of the polygon as a set of sites and tessellate the interior into the "nearest neighbor cells" then you get the so-called (generalized) Voronoi diagram. The Voronoi diagram consists of nodes and edges connecting them. The clearance of a node is the distance to its defining polygon faces.
(Here the polygon even has holes; the principle still works.)
The key observation now is that the center of the maximum inscribed circle touches three faces (vertices or edges) of the polygon, and no other face can be closer. So the center has to lie on a Voronoi node, i.e, the node with the largest clearance.
In the example above the node that marks the center of the maximum inscribed circle touches two edges and a vertex of the polygon.
The medial axis, by the way, is the Voronoi diagram with those Voronoi edges removed that emanate from reflex vertices. Hence, the center of the maximum inscribed circle also lies on the medial axis.
Source: A blog article of mine that deals with generalizations of maximum inscribed circles at some point. There you can find more on Voronoi diagrams and their relation to maximum inscribed circles.
Algorithms & implementations.
You could actually compute the Voronoi diagram. A worst-case O(n log n) algorithm for points and segments is given by Fortune, A sweepline algorithm for Voronoi diagrams, SoCG'86. Held published the software package Vroni with an expected O(n log n) time complexity, which actually computes the maximum inscribed circle, too. And there seems to be an implementation in boost, too.
For simple polygons (i.e., without holes) a time-optimal algorithm that runs in O(n) time is due to Chin et al., Finding the Medial Axis of a Simple Polygon in Linear Time, 1999.
Brute force.
However, as you stated that you are fine with a brute-force algorithm: What about simply trying out all triplets of sites (vertices and edges). For each triplet you find candidate Voronoi nodes, i.e., equidistant loci to the three sites and check whether any other site would intersect the candidate maximum inscribed circle. If there is an intersection you dismiss the candidate. Take the greatest you can find over all triplets.
See chapter 3 in my Master thesis about more details on computing equidistant loci for three sites.
I implemented a piece of python code based on cv2 to get the maximum/largest inscribed circle inside mask/polygon/contours. It supports non-convex/hollow shape.
import cv2
import numpy as np
def get_test_mask():
# Create an image
r = 100
mask = np.zeros((4 * r, 4 * r), dtype=np.uint8)
# Create a sequence of points to make a contour
vert = [None] * 6
vert[0] = (3 * r // 2, int(1.34 * r))
vert[1] = (1 * r, 2 * r)
vert[2] = (3 * r // 2, int(2.866 * r))
vert[3] = (5 * r // 2, int(2.866 * r))
vert[4] = (3 * r, 2 * r)
vert[5] = (5 * r // 2, int(1.34 * r))
# Draw it in mask
for i in range(6):
cv2.line(mask, vert[i], vert[(i + 1) % 6], (255), 63)
return mask
mask = get_test_mask()
"""
Get the maximum/largest inscribed circle inside mask/polygon/contours.
Support non-convex/hollow shape
"""
dist_map = cv2.distanceTransform(mask, cv2.DIST_L2, cv2.DIST_MASK_PRECISE)
_, radius, _, center = cv2.minMaxLoc(dist_map)
result = cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR)
cv2.circle(result, tuple(center), int(radius), (0, 0, 255), 2, cv2.LINE_8, 0)
# minEnclosingCircle directly by cv2
contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[-2:]
center2, radius2 = cv2.minEnclosingCircle(np.concatenate(contours, 0))
cv2.circle(result, (int(center2[0]), int(center2[1])), int(radius2), (0, 255, 0,), 2)
cv2.imshow("mask", mask)
cv2.imshow("result", result)
cv2.waitKey(0)
Red circle is max inscribed circle
Source: https://gist.github.com/DIYer22/f82dc329b27c2766b21bec4a563703cc
I used Straight Skeletons to place an image inside a polygon with three steps:
Find the straight skeleton using the Straight Skeleton algorithm (pic 1)
Base on the straight skeleton, find the largest circle (pic 2)
Draw the image inside that circle (pic 3)
Try it at: https://smartdiagram.com/simple-infographics-3d-charts-2/
An O(n log X) algorithm, where X depends on the precision you want.
Binary search for largest radius R for a circle:
At each iteration, for a given radius r, push each edge E, "inward" by R, to get E'. For each edge E', define half-plane H as the set of all points "inside" the the polygon (using E' as the boundary). Now, compute the intersection of all these half-planes E', which could be done in O(n) time. If the intersection is non-empty, then if you draw a circle with radius r using any point in the intersection as the center, it will be inside the given polygon.

Resources