Freeform cutting/cropping (with C # code implementation)

Source: Internet
Author: User
Tags dashed line

The implementation of the main reference is published in the 2003 Software Journal of "an effective polygon clipping algorithm" (Liu Yongqui, Gao Yun, Huangyu) This paper, the use of the theory and algorithms are mostly based on this article, the paper explained in detail, and extracted some important theories in the paper to summarize. In addition, a tentative analysis of some cases that can not be dealt with in the thesis is also carried out.

Polygon clipping is used to crop out a clipped polygon (also known as a solid polygon, which is represented by s) in a portion of a window (also known as a clipping polygon, followed by C). The resulting polygon of the crop is composed of the boundary of the solid polygon in the clipping polygon and the boundary of the clipping polygon within the solid polygon. See

Figure 1

The following article will describe the cropping process in this diagram, which is more representative than the original paper, the most important is the C1, the graph in the paper, the cut polygon is not in the solid polygon point. Therefore, the first time to see people tend to mistakenly think that the cut polygon and the intersection of the list has no effect.

, the cut polygon and the solid polygon are C1C2C3C4 and S1S2S3S4S5 respectively (because two polygons need to be the same direction, need to reverse the cut polygon is c1c4c3c2, this inverse is also conditional, the first intersection must remain unchanged, see the code implementation), The result we're going to get is c1-i6->i3-i4->i5 (-C1) and S4->i1-i2 (->S4), which use "-" to represent the edges of the cut polygon in the solid polygon, Represents the edge of a solid polygon in a cut polygon)

The implementation of the algorithm is divided into three stages:

Phase 1: Calculates the first intersection, and determines whether two polygons are aligned with each other by the first intersection of the two polygons, and if they are different, the cut polygon is reversed to make the two polygon directions consistent.

Phase 2: Use each edge of the solid polygon to cut the clipping polygon sequentially and insert the intersection in the correct order into the list of two polygons.

Phase 3: Traverse the list of intersections to get the final result.

This article will follow these 3 steps to introduce the relevant implementation points and the main methods in the code. At the end of the article, we also mention some special cases.

Stage 1

Phase 1 To determine whether the 2 polygon is the same direction (the importance of the same direction in the following description), one of the important point is to seek the intersection of cutting, of course, the intersection in the second stage is also very important, here is the second phase of the intersection of the introduction is no longer introduced.

(Note: There are many ways to judge whether a polygon is clockwise or counterclockwise, the C # code in this article will use the method in the original paper)

The method described in the original paper is based on a theorem:

theorem 1: If the edges of the two intersecting polygons have the same orientation (both clockwise or counterclockwise), then the intersection of one polygon is the point of origin and the other polygon must be out point.

If the direction of the two polygons is the same, when one of the polygons is given a point or out point, the ingress and egress of the other polygon is determined. In this way, it is only necessary to mark the intersection of one polygon on the other polygon. From another polygon angle of view of the opposite sex.

Judging whether the two polygons are in the same direction, it is necessary to judge the intersection. The same intersection has different ingress and egress properties for two polygons, and two polygons are in the same direction; otherwise, two polygons are in opposite directions.

the decision of intersection entrance and exit (excludes tangents from intersecting polygons at vertices or coincident with one edge of a polygon). )

When a line is cut into a polygon, the first point that intersects the polygon is necessarily an in point, and the second point must be an out point, so that the in and out points loop appears.

When the edge of a polygon cuts another polygon, the ingress and egress of all intersections on the polygon alternately occur.

The above analysis shows that one of the key operations in the entire implementation process is to find the segment (in Phase 1, the intersection of the line and polygon) and the intersection of the polygon (that is, with the line cut polygon). And in this process to determine the intersection of the cut polygon access.

Finding intersections

Here is a description of the method of intersection in the original paper named error-cut change method. This method is implemented based on the X-value of the intersection of the two straight lines after the error-tangent transformation, simplifying the intersection by changing the tangent to a straight line with a slope of 0. Suppose the cut segment is (X1,Y1), (X2,y2), the cut polygon is composed of V1, V2 ... vn. The intersection process can be described as follows:

1. The slope d,d is the slope of the tangent , Will (X1,y1), (x2,y2) according to the slope of the change can be obtained a horizontal line, we set the horizontal line for the Y=YC, there are the following groups of equations:

Bring in available, have

Description, the original paper said here need X1<X2 (see Code implementation know X1=X2 X1>X2 are special processing). X1≠x2 and Y1≠y2 also need to be satisfied, when the x1=x2 that the tangent is a vertical line, should be cut in the vertical direction, first seek the intersection of the coordinates y. If the y1=y2 is not the wrong cutting process, cut directly with the tangent. The x1<x2 is guaranteed to ensure that the intersection inserts the solid polygon in the correct order.

Is an example, the black line is the line before the wrong cut, the Green line is the wrong cut line, the solid line is tangent, the dashed line is a cut on the polygon lines:

Figure 2

2. Change the y-coordinate of each point VI (XI, Yi) on the polygon by the formula to get Yi ':

3. The x-coordinate of the intersection of each edge ((Xi,yi '), (Xi+1,yi+1 ')) and tangent of the polygon after the wrong cut is IXJ:

For example in the previous illustration, xi+1 can be ix=6.8 with XI .

Then, the iy can be obtained by the inverse-error-cut, the formula:

So

After calculation, iy=4.6. Final coordinate system Image:

Figure 3

There is a particular concern in polygon cutting, where the vertex of a polygon falls on the edge of another polygon. This situation affects the access and exit judgment of the intersection, which can lead to incorrect results. This overlap of points with edges can be handled in the process of using lines to cut polygons. We discuss in several situations:

1. The tangent point falls on one edge of the polygon

This can be a good indication of the situation:

Figure 4

When computed, we find that the X-value IX of the intersection coordinate occurs when the maximum or minimum value of the tangent's coordinate x is equal.

This is the case for the following two sets of polygons:

Figure 5

If the second case is not considered, we simply ignore the point where the X-value IX of these coordinates is equal to the maximum or minimum value of the tangent's coordinate x, which is not counted at the intersection (neither the real and the imaginary intersections), i.e. we assume that the point does not intersect. However, this processing does not apply to the second case, we need to know this particular intersection of the ingress and egress to determine whether to encounter this intersection along the solid polygon or cut polygons continue to move forward.

In this case, only the intersection of the X-value IX of the coordinates and the maximum or minimum value of the tangent's coordinate x is equal to the actual intersection.

2. A point on the polygon edge falls on the tangent

As shown in the following:

Figure 6

This occurs when the Y-value of the coordinates of the point of the split polygon is equal to the YC when the error-cut calculation is made. Because the edges of the cut polygons do not have to calculate the intersection of the intersections (of course, the two polygon direction is an exception, that is, to determine the direction of two polygons need to select a generalized intersection), just ignore the edges of this polygon, do not take them with the tangent to calculate the intersection (this intersection can be ignored).

If you use the above method, you can correctly handle:

Figure 7

3. The case of side overlap

The processing of the above two cases, because we do not change the coordinates of the polygon nodes, so will not have a wrong effect on the final result, is an acceptable solution. For the case of two polygons with side coincident (except for two polygon nodes coincident, this problem is said), such as two polygons (where the solid polygon is a solid line, the dashed lines are cut polygons, the following example is the same), through the above method can be handled correctly, and do not need to deliberately judge the coincidence, We can use it as a special case for Scenario 2:

Figure 8

4. When the present case 1 and 2 occur simultaneously, it is coincident with the Polygon node, which is shown in the coordinate system as follows:

Figure 9

See 2 Typical examples of this situation:

Figure 10

For the treatment of this situation, when the wrong tangent of the point of the polygon after the coordinates of the Y value equals the YC, and the intersection of the coordinates of the X-value is exactly equal to the x-coordinate of the tangent endpoint, that is, when the current situation, we pick a point on the edge of the polygon to think it has an intersection, and another point Or do you use an example to solve

If you are using I1I2 to cut the edges of the polygon c1c2, C2C3, ... We assume that if the 2nd of the Polygon Edge (for C1C2,C2C3 2nd is C2,C3, and also the 1th effect is the same), we think that there is a real intersection at 4 o'clock. Even with I1i2 cut c1c2, we think there is an intersection that uses I1I2 to cut c2c3 when they have no intersection according to the above rules. This way, the situation is handled correctly.

As a result, the above introduction, for a variety of intersection calculation can be processed, and then in an even odd order to mark in and out of the sex is also very easy. Let's look at the second stage.

Stage 2

The method described above has been able to get the intersection and intersection of the entrance and exit. And according to the entrance and exit to determine the direction of two polygons, for different directions, you need to reverse one of the polygons. The following is another focus of the entire algorithm, the process of clipping polygons with the edges of a solid polygon and inserting intersections into a linked list of two polygons.

1. First, the cut polygon and the solid polygon are connected to the following two linked lists (the previous article has been processed in the same direction).

Figure 11

2. Use each edge of the solid polygon s to cut and cut the polygon C in turn, and insert the intersection point into the solid polygon s and cut polygon C linked list, which simultaneously marks the intersection entity polygon for the cut polygon's access.

When starting execution, cutting polygon C with S1S5 cutting will produce I6, I3 two intersections, which can be inserted sequentially using the location relationships of the x-coordinates of S1, I6, I3, and S5. In this way, each edge in S is cut C and inserted into the linked list, resulting in the following model:

Figure 12

The following figure can be used to better see the case of each of the linked lists (note that the intersection of intersections is opposite to each other, which is also the main feature of Polygon co-direction):

Figure 13

This completes the cut and the intersection is inserted to enter Phase 3.

Stage 3

With the above two linked lists, traverse the solid polygon and crop polygon linked lists to get the output polygon linked list. The traversal process starts with an intersection of the solid polygons for the clipping polygon into points (requires used of 0). As the first such intersection is I6.

From this point to the next intersection in the Entity Polygon list (must be an out point, for the point I3 in the graph) all the points on the solid polygons are the result polygons (the following illustration shows the process of generating results with a red arrow, that is, along the nexts direction of I6, Forward in the direction indicated by the solid triangular arrow in the diagram). In addition, each traversal of a node or intersection of its used is set to 1, the same.

Since I3 is an out point of a solid polygon for cropping a multilateral line, the following procedure cannot continue along the edge of the solid polygon, it is necessary to move to the direction of the clipping polygon (that is, along the Next2 direction of the I3, corresponding to the triangular arrow direction in the diagram), Until the next intersection is encountered (this intersection must be the point of the solid polygon to the clipping polygon). (It is mentioned in this paper that because the nextc direction of the I3 is a clipping polygon with respect to the point of the solid polygon, so continue along the nextc direction, precisely because of the two polygons, because the theorem 1, it is necessary to ensure that the nextc direction of the clipping polygon is relative to the solid polygon in the point, so this is the importance of two polygons in the same direction . ) to add these point sequences to the output polygon.

Repeat this process (that is, encountered in the point along the Nexts walk, encountered a point along the NEXTC walk, in addition, note that the main process encountered vertex (whether it is solid polygons, or clipping polygons), Must follow its next step) until it encounters the intersection of the current result polygon starting point (for example, I6). This outputs a result polygon.

At the end of the processing, if there is an intersection of used 0 in the linked list of the solid polygon, there are other result polygons. Locate the first used to 0, and then continue with the procedure described above to get the remaining result polygons. Until all used for 1 end.

Demonstrates the process of connecting points:

Figure 14

Another version:

Figure 15

This will give you a result.

In this paper, the algorithm is implemented to support the general polygon, including but not limited to concave polygons, and after simple modification can also find the polygon and or poor, there is a certain range of applications. In the process of outputting a polygon, when the input point (solid polygon relative to the cut polygon) is encountered along the direction of the cut polygon (that is, the nextc direction of the intersection), and the direction of the solid polygon (i.e. the nexts direction of the intersection) is encountered when the point (solid polygon is relative to the cut polygon), the polygon "and "。

To get the "difference" of the polygon, just make the two-polygon start Phase 2 o'clock opposite (that is, the intersection requires the same polygon direction, the difference set needs the opposite direction).

For the cutting of polygon with holes, a way of thinking is given in this paper, but the concrete implementation is too complex, there is no realization. Interested children's shoes to study it yourself. The basic principle is to keep the outer edge of the empty polygon and the cutting polygon consistent, the inner edge and the outer side of the opposite direction, so that the inside edge and cut polygon cutting, the intersection of the entrance and exit can be maintained correctly.

Since the algorithm used in this article needs to traverse the polygon linked list from the intersection, it is required that the cut polygon and the solid polygon must have an actual intersection (different from the imaginary focus, that is, the extension line of one polygon edge and the intersection of the other polygon).

The following supplement discusses the next two polygons that do not actually intersect.

First look at a few groups of examples:

Figure 16

In this case, the concave polygon can still be processed and will not be supported by the following scenario. In several cases, (a) after cutting, the resulting polygon is a cut polygon. and (b) The result of the cut is a solid polygon. for (c), the result is empty.

After the process of cutting a multilateral line using the edge tangent of the solid polygon, if the number of intersections is 0, the occurrence is indicated. The following methods can be used for the distinction of these three cases:

Take a point in the cut polygon, if it is within the solid polygon (a)

Take a point in the solid polygon, if it is within the cut polygon (b)

If neither of these cases is true (c)

This judgment applies to the nesting of the following, but also the presence of edges coincident (need to be judged if the point is also counted inside the polygon at the edge of the polygon). It also relies on the assumption that if the two polygon edges coincide they do not have an intersection:

Figure 17

One problem here is that if a polygon is nested in another polygon, how to judge the nesting. Since one polygon is nested within another polygon, any vertex of the polygon is inside another polygon. So the question of whether a polygon contains another polygon can be turned into whether a polygon contains a point.

There is a classic way to judge whether a point is in a polygon or not, from this point to a ray in any direction (the code implementation is the right horizontal ray, the simplest to implement), if the ray and polygon have an odd number of intersections, the point is inside the polygon, and conversely (including no intersection), the point is outside the polygon. The specific visible Code implementation section.

Code implementation:

Using the method described in the original paper to determine whether the two multi-deformation is the same direction and get the first intersection point should be completed at the same time, but I do not write in a single cut that makes up the list and can determine the direction of access/polygon code, Therefore, the following implementation of the determination of the direction of the cut and the composition of the chain table cut phase separation (that is, Phase 1 and Phase 2 of the first intersection calculated 2 times, the first is only used for direction of judgment).

Data structures used by the algorithm

The algorithm uses 2 linked lists to represent cut polygons and solid polygons, respectively.

Data structures where nodes/intersections are:

public abstract class vertexbase{    public double x {  get; set; }    public double y { get; set; }     public string name { get; set; }    public  void setxy (double x, double y)     {         X = x;        Y = y;     }    public point topoint ()     {         return new point (x, y);     }}public  class Vertex : VertexBase{    [DebuggerNonUserCode]     public vertex (double x, double y)     {         x = x;        Y = y;    }     public VertexBase Next { get; set; }}public class  intersection : vertexbase{    [debuggernonusercode]     Public intersection (double x, double y)     {         X = x;        Y = y;     }    public CrossInOut CrossDi { get; set;  }    public bool Used { get; set; }     public VertexBase NextS { get; set; }    public  vertexbase nextc { get; set; }}

Next in vertex is used to represent a reference to the next node or intersection (possibly vertex or intersection), and Nexts and NEXTC in intersection store a reference to the intersection in the S-linked list and the next node or intersection in the C-linked list, respectively. The used in intersection records the output of this intersection, and CROSSDI represents the in and out of the S polygon at the intersection with respect to the C polygon.

The ArbitraryPolygonCut.cs file in the solution contains the code for the core of the algorithm (the reason for this is not listing the code, followed by GitHub links, download it yourself), where

List<list<vertexbase>> Cut (list<vertexbase> ListS, list<vertexbase> ListC)

is the main entry function of the algorithm, the comment inside contains a few stages of the identification, phase one of the main cutting and determining the direction of the function is:

tuple<crossinout, int, bool> CUTBYLINEFORCROSSDI (vertexbase v1, vertexbase v2, list<vertexbase> List, BOOL withidx, int line2idx = 0)

The functions of phase two cutting and linking nodes are:

List<intersection> Cutbyline (Vertex s1, Vertex S2, linkedlist<vertexbase> LINKC)

The above 2 cutting functions also have 2 vertical end-of-function functions, which are used to handle the case where the tangent is perpendicular.

For completely disjoint situations, use the

List<vertexbase> Processnocross (list<vertexbase> ListS, list<vertexbase> ListC)

function to handle, which invokes the

BOOL Isvertexinpolygon (Vertexbase V, list<vertexbase> List)

To determine whether a point is within a polygon.

The code comes with a test program with a partially saved test graphic (a. Cut ending file) that contains several cases covered in the document. You can also test by creating your own graphics from the program.

Finally, put a diagram:

Code Download:

Github

Code can be used in any project, but this implementation of the test is not perfect for production scenarios please test again. If the document is for publication, please indicate the source.

Reprint this article please keep the link.

Freeform cutting/cropping (with C # code implementation)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.