Algorithm for cutting mesh with the plane - c++

I'm trying to write an algorithm for cutting tessellated mesh with the given plane (plane defined with the point on the plane and unit normal vector). Also, this algorithm should triangulate all polygons and fill the hole after split.
I faced with a problem to find a polygon that lies on the plane (like the orange plane on the image)
I tried to process all edges of all triangles and find those that lies on the plane and stored them in an array. After that, I formed an array of vertices by searching next suitable edge.
Can someone explain an easier and faster way to find this polygon?
All vertices must be stored in CCW order.

Identify all edges that you cut by the indexes (or labels) of the endpoints. Make sure that every edge belongs to exactly two faces and is cut twice. Also make sure to orient the edge that results from the intersection consistently with the direction of the face normal.
Now the intersection edges form a chain that you can reconstruct by sorting: store the indexes of the endpoints separately, each with a link to the originating edge. After sorting on the indexes, the common vertices will appear in pairs in the sorted array. Using this structure, you can trace the polygon(s).
In the example below, from the faces aebf, bcgf, cdgh and dhea, you generate the edges ae-dh, bf-ae, cg-bf and dh-cg in some order. After splitting the endpoints and sorting, ae-, -ae, dh-, -dh, cg-, -cg, bf-, -bf, which generate the cycle ae-dh, dh-cg, cg-bf, bf-ae.

Related

How to distinguish between an inbound and an outbound edge of a polygon?

The basics of Weiler-Atherton Polygon Clipping algorithm are:
Start from the first edge which is going inside the clipping area.
When an edge of a candidate/subject polygon enters the clipping area, save the intersection point.
When an edge of a candidate/subject polygon exits the clipping area, save the intersection point and follow the clipping polygon.
How to distinguish between an inbound and an outbound edge of a polygon?
It seems like finding inbound edges invole another huge algorithm and thereby affects the efficiency of the algorithm.
Another question is, how can I find the first inbound intersection?
This answer seems to be shedding some light on the problem. But, sadly it doesn't work.
For example, if I reverse the direction of vectors, the angle is not negated.
https://www.wolframalpha.com/input/?i=angle+between+vector+%7B0%2C180%7D+%7B180%2C0%7D
https://www.wolframalpha.com/input/?i=angle+between+vector+%7B0%2C180%7D+%7B-180%2C0%7D
First, a reminder that the Weiler–Atherton algorithm uses polygons defined by vertices in a specific order, clockwise. In short, you test for edges going in or out by traversing the polygon clockwise. The first edge going in (and therefore the first inbound intersection) is simply the first edge you traverse which started outside the clipping area (see below).
Also, the algorithm is typically run in two phases. First find all intersections, these are added to a list of vertices for your polygons, inserted at the correct position. During this phase you would typically mark whether each vertex is within the other polygon. For the second phase, traverse the vertices to determine clipping polygons.
Lets try some examples. Take a triangle defined by vertices A,B,C, and a rectangle w,x,y,z. The triangle will be the clipping area, rectangle is the subject.
The list of points we have generated for the subject is therefore w,x,R,Q,y,z. The triangle list is now A,B,Q,C,R.
Starting at w, R is the first intersection, it is inbound because the previous point (x) is outside. The traversal of the area will be R,Q,C, and back to R(done).
The intersections are unlabeled here, but they will still be R and Q. The list of points we have generated for the subject is therefore w,x,R,y,Q,z. The triangle list is now A,B,C,Q,R.
The clipping traversal is R,y,Q, and R(done)
Let P and Q be two polygons. One can pick any vertex v of P in order to determine the position of v with respect to Q (i.e inside or outside it) via the ray casting algorithm (or any other algorithm that suits all the requirements of the problem).
You only need to determine the position of one such vertex v of P with respect to Q in this manner because the position of the other vertices of P can be inferred by iterating over the ordered set of vertices and intersection points of P.
Lets say v is outside Q. Then, by iterating over the ordered set of vertices and intersection points of P, the first intersection point one finds is laying on an entering edge. If v is inside Q, the first intersection point one finds is laying on an exiting edge. Keep in mind that one edge can be both entering and exiting, depending on the number of intersection points laying on it.
The idea behind the ray casting algorithm is simple, but one should pick vertex v of P if |V(P)|>=|V(Q)| and v of Q otherwise (in order to lower the impact the ray casting algorithm has on the overall performance, though not significantly).
You do not necessarily need to start at the first inbound intersection, this is fine when you are looking at the polygons drawn on a piece of paper and can drop your pen wherever you want, but as you noted would require more effort to find when coding it.
You just need to make sure you get all the intersections calculated for your two polygons first walking around the source polygons line segments checking for intersections with the clipping polygons line segments. At this point it does not matter whether it is inside or outside.
Once you have all the intersections and your two polygons points in order (I think I had two lists that could link to each other), walk around your source polygon point by point. If your first source polygon point is inside the clip polygon that is the first point of your solution polygon, if not the first point of your solution polygon is the first intersection with the clip polygon.
Once you have your first solution point each point from there is the next solution point. As you hit intersections you switch to the other polygon and carry on until you return back to your first solution point.
It has been a while since I have coded this, but if I remember correctly points that can catch you out are when polygons are entirely inside each other (in which case the contained one is your solution) and make sure you are prepared for more than one solution polygon if you have some odd polygon shapes.

Algorithm for smoothing edges of an open 3D mesh

I have a 3D mesh which represents a surface with some rough boundaries which I would like to smooth:
I am using a half edge data structure for storing the geometry so I can easily iterate over the boundary edges, vertices and faces. I can also quite easily determine whether a given pair of edges is a convex/concave using a dot and cross product.
What would be the best approach for smoothing the edges out, so they form a continuous, curvy line, rather then the sharp pattern seen in the pictures?
compute angle between two neighboring faces
I call it ada as abs delta angle. If it is bigger then threshold it means this point is edge. You can compute it as max of all angles between all edge lines. In 2D it looks like this:
in 3D mesh there is more then 2 lines per point so you have to check all combinations and select the biggest one
ada=max(abs(acos(n(i).n(j)))
where n(i),n(j) are normal vectors of neighboring faces where i != j
identify problematic zones
so find points where ada > threshold and create a list of these points
filter this list
if this point is too far from any other (distance>threshold) then remove it from list to preserve geometric shape
smooth points
you have to tweak this step to match your needs I would do this:
find a group of points in the list which are close together and apply some averaging geometric or numeric on them for example:
pnt(i)=0.5*pnt(i)+0.25*pnt(i-1)+0.25*pnt(i+1)
this can be applied repetitive
blue and red dots are original points, green dots are smoothed points

Operation on polygon - how to sort found vertices

I have two concave polygons on input represented as two vectors of points. I want to do some polygon operation on it - union, intersection and difference. I found intersection points between these polygons and insert them into the right place in each polygon. Then I give an information about its position (Inner - it is inside the other polygon, Outer - it is outside the other polygon, Intersection - point, where two edges of polygons intersects) to each vertex. Now I know which points create the union of these polygons (Outer and Intersection) etc., but I need to know how to sort them to the right order. In case of the intersection operation I need to divide these sorted points into the right number of sets, because the result of intersection could be more than one polygon.
I am using C++, but I don't need necessarily the code, I only want to need how to sort these final polygon points. And I don't want to use any library for these operations because I already have my own functions and want to use them.
I looked at this question How to intersect two polygons? and also some others but none of them is solving final sorting of points.
I also read this article http://www.gvu.gatech.edu/~jarek/graphics/papers/04PolygonBooleansMargalit.pdf , but I probably don't get it.
Any help would be appreciated.
If you follow all my recommendations from my comments:
Distinguish between intersection and touching points
Keep a link between the two equivalents of the intersection points in the two polygons
The solution for the union will be:
Consider only outer, touching and intersection points
Make sure the points in the two polygons are ordered in different direction (one of the sets is in clockwise direction, the other one in counter-clockwise)
Start from random point in any of the two polygons.
For every vertex in any of the two polygons keep if you have visited it
Every time you encounter an intersection point keep on traversing from the next to follow point in the other polygon after the equivalent of the intersection point.
If you come back to the point you started from this closes one of the components of the join of the two polygons. If not all vertices were traversed repeat the whole of it from any unvisited vertex.
In the end calculate the area of all the polygons you have found. The largest in area will be the real union. The rest will be holes in the union.
The solution for the join will be:
Consider only inner and intersection points
Make sure the points in the two polygons are ordered in the same direction
Start from random point in any of the two polygons.
For every vertex in any of the two polygons keep if you have visited it
Every time you encounter an intersection point keep on traversing from the next to follow point in the other polygon after the equivalent of the intersection point.
If you come back to the point you started from this closes one of the components of the join of the two polygons. If not all vertices were traversed repeat the whole of it from any unvisited vertex.
EDIT: As I already mentioned, I have the god feeling my approach with the polygon orientation needs to be revised. However, when searching through the web I found a description of algorithm that might do the work for you: The Vatti clipping algorithm
EDIT2 One more article describing such clipping algorithm.

What is the algorithm behind the gluTess functions?

I'm asking this question out of curiosity, having first tried to implement such an algorithm before using GLU's for performance reasons.
I've looked into common algorithms (Delaunay, Ear Clipping are often mentioned), but I can't seem to understand how GLU does its job so well all the time.
Do any of you have interesting papers or articles on that subjects?
There are some notes alongside the source:
This is only a very brief overview. There is quite a bit of
additional documentation in the source code itself.
Goals of robust tesselation
The tesselation algorithm is fundamentally a 2D algorithm. We
initially project all data into a plane; our goal is to robustly
tesselate the projected data. The same topological tesselation is
then applied to the input data.
Topologically, the output should always be a tesselation. If the
input is even slightly non-planar, then some triangles will
necessarily be back-facing when viewed from some angles, but the goal
is to minimize this effect.
The algorithm needs some capability of cleaning up the input data as
well as the numerical errors in its own calculations. One way to do
this is to specify a tolerance as defined above, and clean up the
input and output during the line sweep process. At the very least,
the algorithm must handle coincident vertices, vertices incident to an
edge, and coincident edges.
Phases of the algorithm
Find the polygon normal N.
Project the vertex data onto a plane. It does not need to be perpendicular to the normal, eg. we can project onto the plane
perpendicular to the coordinate axis whose dot product with N is
largest.
Using a line-sweep algorithm, partition the plane into x-monotone regions. Any vertical line intersects an x-monotone region in at
most one interval.
Triangulate the x-monotone regions.
Group the triangles into strips and fans.
Finding the normal vector
A common way to find a polygon normal is to compute the signed area
when the polygon is projected along the three coordinate axes. We
can't do this, since contours can have zero area without being
degenerate (eg. a bowtie).
We fit a plane to the vertex data, ignoring how they are connected
into contours. Ideally this would be a least-squares fit; however for
our purpose the accuracy of the normal is not important. Instead we
find three vertices which are widely separated, and compute the normal
to the triangle they form. The vertices are chosen so that the
triangle has an area at least 1/sqrt(3) times the largest area of any
triangle formed using the input vertices.
The contours do affect the orientation of the normal; after computing
the normal, we check that the sum of the signed contour areas is
non-negative, and reverse the normal if necessary.
Projecting the vertices
We project the vertices onto a plane perpendicular to one of the three
coordinate axes. This helps numerical accuracy by removing a
transformation step between the original input data and the data
processed by the algorithm. The projection also compresses the input
data; the 2D distance between vertices after projection may be smaller
than the original 2D distance. However by choosing the coordinate
axis whose dot product with the normal is greatest, the compression
factor is at most 1/sqrt(3).
Even though the accuracy of the normal is not that important (since
we are projecting perpendicular to a coordinate axis anyway), the
robustness of the computation is important. For example, if there are many vertices which lie almost along a line, and one vertex V
which is well-separated from the line, then our normal computation
should involve V otherwise the results will be garbage.
The advantage of projecting perpendicular to the polygon normal is
that computed intersection points will be as close as possible to
their ideal locations. To get this behavior, define TRUE_PROJECT.
The Line Sweep
There are three data structures: the mesh, the event queue, and the
edge dictionary.
The mesh is a "quad-edge" data structure which records the topology of
the current decomposition; for details see the include file "mesh.h".
The event queue simply holds all vertices (both original and computed
ones), organized so that we can quickly extract the vertex with the
minimum x-coord (and among those, the one with the minimum y-coord).
The edge dictionary describes the current intersection of the sweep
line with the regions of the polygon. This is just an ordering of the
edges which intersect the sweep line, sorted by their current order of
intersection. For each pair of edges, we store some information about
the monotone region between them -- these are call "active regions"
(since they are crossed by the current sweep line).
The basic algorithm is to sweep from left to right, processing each
vertex. The processed portion of the mesh (left of the sweep line) is
a planar decomposition. As we cross each vertex, we update the mesh
and the edge dictionary, then we check any newly adjacent pairs of
edges to see if they intersect.
A vertex can have any number of edges. Vertices with many edges can
be created as vertices are merged and intersection points are
computed. For unprocessed vertices (right of the sweep line), these
edges are in no particular order around the vertex; for processed
vertices, the topological ordering should match the geometric
ordering.
The vertex processing happens in two phases: first we process are the
left-going edges (all these edges are currently in the edge
dictionary). This involves:
deleting the left-going edges from the dictionary;
relinking the mesh if necessary, so that the order of these edges around the event vertex matches the order in the dictionary;
marking any terminated regions (regions which lie between two left-going edges) as either "inside" or "outside" according to
their winding number.
When there are no left-going edges, and the event vertex is in an
"interior" region, we need to add an edge (to split the region into
monotone pieces). To do this we simply join the event vertex to the
rightmost left endpoint of the upper or lower edge of the containing
region.
Then we process the right-going edges. This involves:
inserting the edges in the edge dictionary;
computing the winding number of any newly created active regions. We can compute this incrementally using the winding of each edge
that we cross as we walk through the dictionary.
relinking the mesh if necessary, so that the order of these edges around the event vertex matches the order in the dictionary;
checking any newly adjacent edges for intersection and/or merging.
If there are no right-going edges, again we need to add one to split
the containing region into monotone pieces. In our case it is most
convenient to add an edge to the leftmost right endpoint of either
containing edge; however we may need to change this later (see the
code for details).
Invariants
These are the most important invariants maintained during the sweep.
We define a function VertLeq(v1,v2) which defines the order in which
vertices cross the sweep line, and a function EdgeLeq(e1,e2; loc)
which says whether e1 is below e2 at the sweep event location "loc".
This function is defined only at sweep event locations which lie
between the rightmost left endpoint of {e1,e2}, and the leftmost right
endpoint of {e1,e2}.
Invariants for the Edge Dictionary.
Each pair of adjacent edges e2=Succ(e1) satisfies EdgeLeq(e1,e2) at any valid location of the sweep event.
If EdgeLeq(e2,e1) as well (at any valid sweep event), then e1 and e2 share a common endpoint.
For each e in the dictionary, e->Dst has been processed but not e->Org.
Each edge e satisfies VertLeq(e->Dst,event) && VertLeq(event,e->Org) where "event" is the current sweep line
event.
No edge e has zero length.
No two edges have identical left and right endpoints. Invariants for the Mesh (the processed portion).
The portion of the mesh left of the sweep line is a planar graph, ie. there is some way to embed it in the plane.
No processed edge has zero length.
No two processed vertices have identical coordinates.
Each "inside" region is monotone, ie. can be broken into two chains of monotonically increasing vertices according to VertLeq(v1,v2)
a non-invariant: these chains may intersect (slightly) due to
numerical errors, but this does not affect the algorithm's operation.
Invariants for the Sweep.
If a vertex has any left-going edges, then these must be in the edge dictionary at the time the vertex is processed.
If an edge is marked "fixUpperEdge" (it is a temporary edge introduced by ConnectRightVertex), then it is the only right-going
edge from its associated vertex. (This says that these edges exist
only when it is necessary.)
Robustness
The key to the robustness of the algorithm is maintaining the
invariants above, especially the correct ordering of the edge
dictionary. We achieve this by:
Writing the numerical computations for maximum precision rather
than maximum speed.
Making no assumptions at all about the results of the edge
intersection calculations -- for sufficiently degenerate inputs,
the computed location is not much better than a random number.
When numerical errors violate the invariants, restore them
by making topological changes when necessary (ie. relinking
the mesh structure).
Triangulation and Grouping
We finish the line sweep before doing any triangulation. This is
because even after a monotone region is complete, there can be further
changes to its vertex data because of further vertex merging.
After triangulating all monotone regions, we want to group the
triangles into fans and strips. We do this using a greedy approach.
The triangulation itself is not optimized to reduce the number of
primitives; we just try to get a reasonable decomposition of the
computed triangulation.

Check which mesh element is inside the original polygons

I have a set of non-overlapping polygons. These polygons can share nodes, edges, but strictly no overlapping.
Now, I am going to mesh them using Constrainted Delaunay Triangulation (CDT) technique. I can get the mesh without problem.
My problem is, after the mesh, I want to know which mesh element belongs to which original polygon. MY current approach is to compute the centroid for each mesh element, and check which of the original polygon this centroid falls into. But I don't like this approach as it is very computationally intensive.
Is there any efficient ways to do this ( in terms of Big O the runtime)? My projects involve tens of thousands of polygons and I don't want the speed to slow down.
Edit: Make sure that all the vertices in a mesh element share a common face is not going to work, because there are cases where the all the vertices can have more than one common face, as below ( the dotted line forms a mesh element whose vertices have 2 common faces):
I can think of two options, both somehow mentioned :
Maintain the information in your points/vertices. See this other related question.
Recompute the information the way you did, locating each mesh element centroid in the original polygon, but this can be optimized by using a spatial_sort, and locating them sequentially in your input polygon (using the previous result as hint for starting the next point location).
What about labeling each of your original vertices with a polygon id (or several, I guess, since polys can share vertices). Then, if I understand DT correctly, you can look at the three verts in a given triangle in the mesh and see if they share a common label, if so, that mesh came from the labeled polygon.
As Mikeb says label all your original vertices with a polygon id.
Since you want the one that's inside the polygon, just make sure you only go clockwise around the polygons, this makes sure that if the points overlap for two polygons you get the one facing the correct direction.
I would expect this approach to remain close to O(n) where n represents number of points as each triangle can at only have one or two polygons that overlap all three points.
Create a new graph G(V,E) in the following way. For every mesh create a node in V. For every dashed edge create an edge in E that connects the two corresponding meshes. Don't map solid edges into edges in E.
Run ConnectedComponents(G).
Every mesh will be labeled with a label (with 1-to-1 correspondence to polygons.)
Maybe you can call CDT separately for each polygon, and label the triangles with their polygon after each call.