04 Polygon BooLeans

Embed Size (px)

Citation preview

  • 8/12/2019 04 Polygon BooLeans

    1/17

    Comput & GraphicsVoI. 13, No 2, pp 167-183, 1989Printed in Great Britain

    0091-8493/89 $3.00 + .00 1989 Maxwell Pergamon Macmillan plc

    Technical Section

    AN ALGORITHM FOR COMPUTING THE UNION,

    INTERSECTION OR DIFFERENCE OF TWO POLYGONSAVRAHAM MARGALIT

    Computer Vision Laboratory, Center for Automation Research, University of Maryland,College Park, MD 20742

    and

    GARY D.KNOTTDepartment of Computer Science, University of Maryland, College Park, MD 20742

    Abstract-An algorithm for set operations on pairs of polygons is presented. The algorithm uses a boundaryrepresentation for the input and output polygons. Its domain includes simple polygons as well as polygonswith dangling edges, vertices of degree greater than 2, and holes within the area of the polygon. A partialproof of the correctness of the algorithm is given as well as an analysis of its complexity. The implementationthat is described is table-driven. It is facilitated by the use of efficient data structures. Implementation issues

    such as numerical accuracy are also discussed and sample results of its execution are demonstrated.

    1. INTRODUCTION

    Union, intersection, and difference set-theoretic op-erations on polygons have been extensively studied be-cause an efficient algorithm for performing these tasksis very useful for CAD/CAM systems as well as forcomputer graphics packages. A good algorithm for thecase of convex polygons is known[ l], but it is moredifficult to develop a general efficient algorithm for anytwo simplepolygons.

    There are two main approaches to design algorithmsfor set operations on polygons. One is based on the

    divide and conquer paradigm and the other is basedon direct manipulation of the boundary line segmentsthat construct the polygon. Using the divide and con-quer idea, the two main approaches to perform setoperation on polygons are based on constructive solidgeometry (CSG)[3] and on quadtrees[4].

    In the CSG method a polygon (as every other solid)is represented as a CSG tree. A CSG tree is a binarytree whose leaf nodes represent pre-definedprimitiveshapes (such as triangles, squares, etc.) and an internalnode represents the result of a boolean operation be-tween its left and right CSG sub-trees. A boolean setoperation on two polygons is decomposed recursivelyinto boolean operations on the primitive shapes. In the

    quadtree method, the plane containing each polygonis divided recursively into quadrants containing frag-ments of the plane. A boolean set operation on twopolygons is done by traversing the quadtrees of thepolygons and looking for the common parts in nodesrepresenting the same quadrants in the plane. Bothmethods have been used in algorithms for set-theoreticoperations on polygons[3, 5-8].

    The CSG method can only handle polygons that aredecomposed into the pre-defined primitives and thusmay be limited. The quadtree method is limited in itsaccuracy since the maximal depth of the tree isbounded so that the input polygons cannot be repre-

    sented precisely. These problems have been addressedin the literature[6, 8, 13] but there are many special

    cases, the correctness of the algorithms is difficult toprove and a precise worst case complexity analysis issimilarly difficult. Actually, correctness proofs andcomplexity analysis are not presented in the literature.

    Algorithms using the other approach of directboundary elements manipulation are summarized be-low. Algorithms that weave the output polygons bytraversing the input polygons and retaining only thedesired output are presented by Weiler[12], and East-man and Yessios[15]. Weiler presented an interestingmethod using a graph representation along with local

    and history information of the vertices. This entailsvery complicated data structures and methods to ma-nipulate them. Weiler does not discuss implementationissues.

    Nievergelt and Preparata[ 17] have presented an al-gorithm which is an extension of theplane sweepal-gorithm[ 1]. Although the asymptotic complexity of thisalgorithm is it requires that complex datastructures be maintained along with methods to ma-nipulate them. The authors do not discuss how to im-plement the algorithm.

    Putnam and Subrahmanyam[9] have presented analgorithm to perform boolean operations on n-dimen-sional objects. This algorithm is very general. The au-

    thors do not discuss any implementation details andit is difficult to see how to implement it.

    As we can see, although there are many algorithmsfor the task of performing set operations on polygons,they are either not very practical or they are incapableof dealing with complicated cases. Rigorous proofs ofcorrectness are not given in any of the papers, and veryimportant implementation issues are hardly discussed.Also, none of these algorithms can work in practicewithout attention to numerical accuracy issues, andthis important detail is not generally discussed. Mostof the algorithms are for simple regular polygons andcannot perform on more complex non-regular poly-

    gons. Handling more complex polygons can be useful,and it is relatively difficult to do correctly.

    167

  • 8/12/2019 04 Polygon BooLeans

    2/17

    32 AVRAHAM MARGALIT and GARY D. KNOTT

    In this paper we present a new algorithm for setoperations between polygons, discuss its implemen-tation, partially prove its correctness, and give crudebounds on its complexity, The algorithm uses a simpleboundary representation which is natural for many

    graphics applications. It uses only two linked lists andone hash table, and it can handle complicated non-regular polygons as its input and output. We also dis-cuss the issue of precise numerical methods andtheir use.

    point, and if each pair of consecutive edges share ex-actly one point[1].

    The boundary of a one-sided polygon consists of asingle point. The boundary of a two-sided polygonconsists of a single line segment whose two oppositely

    directed forms are the two edges of the polygon, andwhose end-points are the two vertices. One-sided andtwo-sided polygons are called irreducible degeneratepolygons.

    The class of irreducible degenerate polygons togetherwith the class of simple polygons make up the class of

    A simple polygon has a clockwiseorientation if itsvertices are ordered in a clockwise order. A precisedefinition ofclockwiseorientation can be given in termsof the signed area of a polygon. If the polygons verticeshave the opposite order, the polygon has a counter-clockwiseorientation. Thus if a simple polygon

    has a clockwise orientation, the reverse simple polygon

    has a counterclockwise orientation. An irreducibledegenerate polygon D is both clockwise and counter-clockwise oriented, and either of these orientations canbe specified to be the principal orientation of D in anyparticular context.

    Let A point p is in the interior ofif there exists a neighborhood of p that is

    contained within O. A pointp is in the exteriorofif there exists a neighborhood of p that is

    contained within A point p belongs to theclosureof if every neighborhood ofp

    contains a point of O. A point p is on the boundaryofif every neighborhood ofp containspoints from int(O)and ext(O).A set Ois regularif O=clos(int(O)).Intuitively, a regularset in has nodangling points or edges and no subregions of zeroarea.

    According to the Jordan Curve Theorem, a simplepolygon, taken as a closed non-self-intersecting curvein the E2plane, divides the plane into three regions,the boundaryregion, the insideregion or interior,andthe outsideregion or exterior. The polygon itself istaken as the closed set consisting of the union of theinside region and the boundary. Either the interiororthe exterioris of infinite area and the complementaryregion is of finite area. We shall denote the finite arearegion of a simplepolygonP byFAR(P). The finitearea region of an irreducible degenerate polygon willbe defined to be the empty set with this under-standing, an irreducible degenerate polygon also hasdisjoint interior, exterior and boundary sets whoseunion is

    We divide simple polygons into two types: islandsand holes.An island-typesimple polygon has an in-terior with a finite area and an infinite area exterior.A hole-type simple polygon has a finite area exteriorand an infinite area interior. We also follow the con-vention that if a simple polygon has a certain orien-

    tation and type, a second simple polygon with the op-posite orientation is regarded as of the opposite type

    2. DEFlNlTIONS irreduciblepolygons.2.1 Points and lines in the plane

    We are concerned with objects in two-dimensionalEuclidean space, Apointain is an ordered pair(x,y) wherex andy are real numbers representing theright-handed Cartesian X-axis and Y-axis coordinates.A point in may also be regarded as a vector startingat the origin, (0, 0), and ending at the point.

    Given two distinct points, andin E2, the directed line

    is the line that passesthrough a andb in the direction from a towardsb.Thedirected line-segment segment(a, b) = { (x, y) : (x, y)

    is the segment of theline between a andb in that order.

    A point can be to the east of a directed linewhich is imagined to be pointing north: it can

    be to the west of the line, or it can lie on the line.Define for apoint and the line c is to the east of

    if F 0, and it

    lies on if F = 0.Two lines and can be parallel or they

    can intersect. When they intersect they havea commonpoint and there are unique valuest and s which satisfythe equation Two linesegmentssegment(a,b) andsegment(c,d) intersect ifvalues of t and s exist which satisfy the above equationsuch that

    Apolyline sequence ofdirected line segments is anordered list of line segments where the second endpointof each line segment is equal to the first endpoint ofthe next line segment in the list. A closed polyline se-quence is one such that the second endpoint of the lastline segment is equal to the first endpoint of the firstline segment in the sequence. Each directed line seg-ment must have a positive length, except that the singleline segment of a one-member closed polyline sequenceis a degenerate line segment of length 0.

    2.2 Polygons in the planeThe boundary of the n-sided polygon

    in the plane is the closed polyline se-quence ofn directed line segments

    wherefor The npoints of thepolygon are its vertices,while the line segments are itsedges.

    A polygon is simpleif it has at least two distinctvertices, if no pair of nonconsecutive edges share a

  • 8/12/2019 04 Polygon BooLeans

    3/17

    An algorithm for pairs of polygons 33

    Let us define an edgefragment ofa polygon to be apossibly degenerate (a degenerate edge fragmentis asingle point) sub-segment of an original edge such thateach one of its two endpoints is either an original vertexor an intersection point of two edges. A polygon is

    orientableif1. Any two of its edges are either disjoint or collinear,

    or intersect at a point that is an endpoint Of at leastone of the edges.

    2. The set of its edge fragments creates a vertex-com-pletepolygon whose vertices are the original verticesalong with the intersection points between edges ofthe original polygon.

    with respect to the first polygon. For example, a coun-terclockwise simple polygon is regarded as a hole withrespect to a clockwise island simple polygon.

    We now define several more classes of polygons.A polygon is vertex-complete if:

    1. Any pair of its edges either are disjoint, or intersectat endpoints, or are identical as sets.

    2. The set of its edges can be partitioned into subsetsof single closed polyline sequences where each suchpartition subset, taken as a closed polyline sequence,is an irreducible polygon. These irreducible poly-gons are called theminimal componentparts of theoriginal polygon. For every pair of distinctirreduc-

    polygons, either theirfinite area regionsare disjointor thefinite area regionof one of them is nestedwithin thefinite area regionof the other. In the firstcase, where if both parts

    and A, are not included within thefinite area

    then both and must have the same orientation.In the second case, where then

    if there is no irreducible part such that

    opposite orientations.

    This definition means that a vertex-completepolygonis built of theseirreducible minimal componentparts.It cannot have crossing edges, but it can have coincidentvertices and collinear edges and many closed sequencesof edges as long as they obey the second rule above.

    The class of vertex-complete polygons which have

    one or more irreducible degenerate minimal compo-nent parts constitutes the class ofdegeneratepolygons.

    We can represent a vertex-completepolygon as aforest where each tree in the forest is an inclusion tree.A node in such a tree represents anirreduciblepart.There is an edge between two nodes and if

    and there isno irreducible partsuch that Each tree

    of the forest represents a maximal disjoint componentof the associated polygon.

    Using this forest-of-inclusion-trees representation,we can define thefinite area region of avertex-completepolygonP. SupposeP corresponds to the for-

    est of inclusion trees Let be oneof the trees of the forest which has k levels. Thenis defined as the vertex-complete finite area

    regionassociated with the root of the tree, where thevertex-complete finite area region associated with anarbitrary node N in the tree is defined recursively asfollows: If the node N is a leaf then isdefinedasN sfinite area regionFAR(N);otherwiseis defined as where theare the sons of nodeN in the tree Finally,FAR(P)

    The orientation of a vertex-completepolygonP isthe same as the orientation of any one of its maximalcomponent parts represented by the inclusion trees

    where a with mustbe chosen if possible.

    ibleparts, and where and are simple Any orientablepolygon can be converted into a ver-tex-completepolygon by introducing additional ver-tices. The finitearea regionof such a converted polygon

    is then taken as the finite area region of the original

    orientable polygon.Finally, a polygon is convex if its interior is its finite

    adjacent pairs of its vertices lies in the interior of thepolygon, and a polygon is simple-convex if it is simpleandconvex.

    hierarchies:

    polygons, and

    vertex-complete polygonsvertex-complete polygons orientable polygons

    and

    regular vertex-complete polygons regular orientablepolygons orientable polygons.

    The domain of our algorithm is the class of vertex-complete polygons. Examples of polygons of differentclasses are given in Fig. 1.

    2.3 Set operations between polygons

    set operations on A and B as follows:

    region of some other irreducible part of the polygon,area region,and ifthe line segment between any non-

    then and must haveThe above classes of polygons form the following

    LetA and B be two polygons in We define the

    In our definition of vertex-completeand orientablepolygons we allow polygons with coincident verticesand overlapping edges, i.e., edges like

    and where andThere are situations where these types of polygons arenot desirable. Thus we wish to optionally produce reg-ularpolygons as output, since, by the definition ofreg-ular sets, regular polygons do not have overlappingand dangling edges or coincident vertices[3, 8]. Theoperation of finding a polygons regularparts (deletingall the coincident vertices, dangling edges and zero-area sub-regions) is called regularization[5]. However,

    it is not certain that the result of a set operation ontwo regular polygons is another regular polygon. This

  • 8/12/2019 04 Polygon BooLeans

    4/17

    Fig. 1. Polygons of different classes in the polygon hierarchy. (a) simpletonvex polygon. (b) simple polygon.(c) regular vertex-complete polygon. (d) vertex-complete polygon. (e) orientable polygon. (f) general

    polygon.

    is the motivation for defining the regular set opera-tions[3,5]:

    polygonP.These three sets of edge fragments of Q aredenoted by and As in [9],theset ofboundaryedge fragments, can be furtherpartitioned into two parts which are the boundary edgefragments ofQ that are directed in the same directionas the boundary edge fragments of P, and the boundaryedge fragments of Q that are directed in the oppositedirection to the boundary edge fragments of P.These

    division enables us to construct only regular resultpolygons when required by not using the edge frag-ments in the set

    The classified edge fragments are stored in a datastructure that allows fast searching and deletion op-

    erations. Then each result polygon is constructed, itsvertices are put in the output array and its edge frag-ments are deleted from the data structure so as to pre-pare for constructing the next result polygon. Each re-sult polygon is constructed by successively searchingfor a next continuing edge fragment until the searchfinds an edge fragment which has a second endpointthat is being visited for the second time. At this point,a result polygon has been found.

    This algorithm is simple and efficient. We use a hashtable in a novel way, along with other simple datastructures. The elementary manipulation of these datastructures is efficient so that the time and space com-plexity are reduced. The algorithm does not have tohandle a large number of special cases and thereforeit can easily be seen to work on every pair of vertex-

    for which the operation's result is a regular polygon, sets are denoted by and This finer

    3. THE ALGORITHM FOR SET OPERATIONS

    Our algorithm for set operations on polygons hastwo main stages. The first stage is the classification of

    the line segments of the input polygons and the secondstage is the construction of the result polygons.

    The algorithm first classifies the original vertices ofeach polygon to be inside, outsideor on theboundaryof the other polygon. Then it finds all the intersectionpoints between edges of the two polygons. For eachpolygon, the original vertices along with the intersectionpoints are stored in a data structure such that each twoneighboring points define an original edge or a part ofan original edge of a result polygon (or, as we call them,edge fragments).

    The algorithm then classifies the edge fragments ofone polygon to be inside, outside or on theboundaryof the other polygon. This classification is given in [5]where the set of edge fragments of a polygon Q is di-vided into these three subsets with respect to a reference

    34 AVRAHAMMARGALITand GARYD. KNOTT

  • 8/12/2019 04 Polygon BooLeans

    5/17

    An algorithm for pairs of polygons 35

    sified as a boundary point and inserted into boththe vertex rings A V and BV in the proper places. Ifthe intersection is along a common line segment,the two endpoints of the common segment are clas-sified asboundary points and inserted into the twovertex rings in the right places.

    However, the vertex ring insertion process insertsa new point only ifthis point does not exist or existsonly once in the vertex ring. Thus a vertex can ap-pear twice in sequence in a vertex ring, but no morecopies will be stored. This allows the non-regularintersection of two polygons which intersect at justa single vertex to be correctly computed. Every twoneighboring points in the vertex data structuresrepresent an edge fragment which is a part of, or isequal to, an edge in the original polygon.

    Each edge fragment belonging to one polygon is

    now classified to be inside, outside, or on theboundary of the other polygon. An edge fragmentis defined to be inside if at least one of its endpointsis an inside vertex, or the two endpoints are bound-ary vertices but all the other points of the edge frag-ment are inside points (in this latter case it is enoughto check if an internal point of the edge fragmentis inside the other polygon). An edge fragment isdefined to be outside if at least one of its endpointsis an outside vertex, or the two endpoints areboundary vertices but all the other points of theedge fragment are outside points (in this latter caseit is enough to check if an internal point of the edgefragment is outside the other polygon). An edgefragment is a boundary fragment if all of its pointsare on the boundary of the other polygon.

    Select the edge fragments from among the total setof edge fragments of both polygons, which are givenimplicitly in their respective vertex rings, as requiredto construct the result polygons. The required edgefragments to be selected depend on the specified setoperation and the polygon types. These selectededge fragments are stored in an edge fragments table,EF. Each selected edge fragment from a given poly-gon is stored only once in the edge fragments table.

    In the selection process the inside or outside edge

    fragments of both polygons are selected accordingto the operation and the two polygon types as sum-marized in Table 2. In this table there is a row foreach combination of polygon types and a column

    complete polygons, even those with vertices of degreemore than two or with collinear edges.

    3.1 General description of the algorithm

    The algorithm we use to solve the problem of com-puting the result of a set operation on two polygonsgetsas its input an operation code which specifieswhether union, intersection or set difference is desired,an indicator. code specifying .whether regular resultpolygons are required, and two vertex-complete poly-gon arrays, A and B, along with their types (island orhole).The algorithm constructs a set of irreducible re-sult polygons along with their types in the outputarray C.

    If regular output is not desired, various result poly-gons may be degenerate. A degenerate polygon is apoint or a line segment given by oppositely directedoverlapping edges. A point can be the result of a setintersection operation on two polygons, for examplethe intersection of two polygons that touch only at onevertex.

    1. Normalize the orientations of the input polygons.

    4. Classify the edge fragments.

    The algorithm has six steps:

    Find the relative orientation of the two input poly-gonsA and B, and change the orientation of polygonB if necessary, according to the operation and thepolygon types as summarized in Table 1.This stepis needed because we do not require an islandpoly-gon to be represented by a specific onentation(clockwise for example), but it is required that ahole polygon be represented by the opposite ori-entation to an island polygon.

    2. Classify and insert the vertices.Classify the original vertices of each polygon as towhether they are inside, outside, or on the boundaryof the other polygon. Insert the classified verticesof the two input polygons, A and E, in the two vertexrings,AVand BVrespectively. The vertex rings arecircular linked lists in which vertex points appearin sequence so that each two adjacent points definean edge fragment.

    For each edge of one polygon find all the edges ofthe other polygon it intersects with and calculate

    all those intersection points. When two edges in-tersect they can intersect at a point, or they canoverlap along a common line segment. If the inter-section is at a point, this intersection point is clas-

    5 . Select and organize the edgefragments.

    3. Find and insert the intersection points.

    Table 1. Mutual orientation of the input polygons according to the operation and the polygon types.

  • 8/12/2019 04 Polygon BooLeans

    6/17

    36 AVRAHAM MARGALIT and GARY D. KNOTT

    Table 2. Type of edge fragments to select according to the operation and the input polygon types.

    for each set operation between polygonA and poly- tions are presented along with the particulargon B. In each column, the required types of edge boundary edge fragments to select for each set op-fragments of both polygons are specified. eration.

    Particular boundary edge fragments are selected Degenerate single point boundary edge fragmentsaccording to the situation of all matching boundary are selected only when a non-regular form of outputedge fragments of both polygonsA and B. Note that is permitted and only if the degenerate edge frag-if there is a boundary edge fragment of polygon A, ment has no adjacent edge fragment. If it has no

    there must be at least one exactly overlapping adjacent edge fragment, it is an isolated point andboundary edge fragment of polygon B which may not a degenerate point in a closed polyline sequence,have the same or opposite direction. We present so it hasto be reported as a non-regular part of thethe possible boundary edge fragment situations in output.Table 3. In this table, for each combination ofpoly- The selected edge fragments are organized in thegon types and specified regular or non-regular form data structure, EF, in a manner that allows findingof output, all the boundary edge fragments situa- all the edge fragments which start with a given point

    Table 3. Boundary edge fragments to select according to the operation, polygon types, and regular outputrequirements.

  • 8/12/2019 04 Polygon BooLeans

    7/17

    An algorithm for pairs of polygons 37

    The procedurepolygonoperationuses the followingand that allows any specified edge fragment to bedeleted. We shall discuss later several options forthe implementation of this data structure.

    To construct each result polygon, we arbitrarily

    choose one edge fragment from the EFtable andthen successively choose an arbitrary edge fragmentwhose first endpoint matches the second endpoint

    of the previously chosen edge fragment. This processcontinues until an edge fragment is chosen whosesecond endpoint is now visited a second time (anirreducible polygon has now been found). Then thesuccessive vertices of the polygon that was foundare transferred in sequence to the output array asa single polygon and the corresponding edge frag-

    ments are deleted from the EF table whereuponanother result polygon may be sought.

    By using this method we form the greatest pos-

    sequence of edges is regarded as a result polygon.The type of each obtained result polygon is foundusing Table 4. This is a table of indicators which

    sub-procedures and tables:

    procedurepoint) returns Trueif the two line segmentsSegmentl

    and intersect and returns Falseotherwise.If the two line segments intersect, their intersectionpoint is found in Point.

    procedure finds andreturns whether the pointPointis inside, outsideoron the boundaryof the polygon Polygon.The pro-cedure checks, for every edge of the polygon, if thepoint is on the edge, and if not, whether the edgeintersects with a ray that begins at the point and isdirected in the X-axis direction. Ifthe point is on theedge, the procedure returns boundary.If the edgeintersects with the ray, except at the edgeslowerendpoint, a counter is incremented. When all edges

    counter is an odd number or outsideif the counteris an even number.Procedure inserts into the

    6 . Construct the result polygons and find their types.

    sible number of result polygons, since every closed are checked, the procedure returns inside if the

    specify whether the type of an output polygon is ofthe same type or the opposite type as of polygonA,

    vertex ring,DSV, the point Pointwith the type Typeifthis point is not already inDSV, The possible types

    when both Aand Bhave the same orientation. If

    AandBhave the opposite orientations, the orien-

    is specified in the table.

    are: inside, outside or boundary.

    Procedure inserts an edge

    not already there. If regular output result polygonsare required and a non-boundary edge fragment isto be inserted, the procedure checks whether thesame edge fragment with the opposite direction isalready inEF. If so, it does not insert the edge frag-

    ment and it deletes the existing edge fragment withthe opposite direction from the edge fragments table.Procedure deletes an edge frag-ment from the edge fragments table.Procedure searches and returnsfrom the edge fragments table an edge fragmentwhose first endpoint is Point.Procedure searches and returnsthe index of an edge fragment in the edge fragmentstable that contains the edge fragmentFragment.Procedure organizes the edge fragmentstable to allow fast search and deletion operations.

    returns clockwise

    if the polygon Polygon has a clockwise orientationand returns counterclockwise if the orientation iscounterclockwise. This procedure finds the vertex

    tation ofthe output polygon is the opposite of what fragment into the edge fragments table,EF, if it is

    3.2 Procedural description of the algorithm

    We can describe the algorithm as a procedurepoly-gonoperation. The procedure takes as its input two ar-

    rays,AandB,that include the vertices of the two poly-gons, the two polygon types, and an op-eration code, and a regularity indicator, Reg,and produces one output array, Out,which includesthe vertices of the result polygons.

    The input arrays contain the two input polygonswhere each polygon is represented as a sequence of the(x,y) coordinates of its distinct vertices (and it is knownthat the first and last vertices are connected by an edge).The polygon type can be island orhole,the operationto be performed is intersection, unionor differenceand the regularity code indicates if the output poly-gons should be regularor not. In the output array,

    each result polygon is represented as in the inputarrays, with multiple result polygons separated by amarker row.

    Table 4. Output polygon type for a given operation and given input polygon types

  • 8/12/2019 04 Polygon BooLeans

    8/17

    38 AVRAHAMMARGALITand GARYD. KNOTT

    with the minimum X value and compares the slopesof the two edges attached to this vertex in order tofind the orientation.Procedure changes theorientation of the polygon Polygon.

    Table contains indicators which specifywhether the two input polygons should have the sameor oppositeorientations according to the operationand the polygon types (Table 1).Table

    contains the type of edge frag-ments, besides the boundary line fragments, to beselected for insertion into the line fragments tableaccording to the operation and the polygon types(Table 2).Table

    contains indicatorswhich specifies how many boundary edge fragments

    are to be selected given the edge fragments situationfor regular and non-regular operations. The table isaccording to the operation and the polygon types(Table 3).Table

    contains indicators which specifywhether the type of an output result polygon is thesame as or the opposite of the type of polygon Awhen both have the same orientation. If they havethe opposite orientations, the orientation of the resultpolygon is the opposite of what is written in the table.The table is arranged according to the operation andthe polygon types (Table 4).

  • 8/12/2019 04 Polygon BooLeans

    9/17

    An algorithm for pairs of polygons 39

    from polygon A, polygon B or both. When both bitsare set, the edge fragment is a boundary edge frag-ment of both polygons.

    5. Two bits to store the edge fragment's type (inside,outside,or boundary)of the edge fragment whose

    first endpoint is in the current entry.6. An index that is used in the construction of theresult polygons to point to the next hash table entryused in the current attempt to construct a result

    polygon.

    Insertion of an edge fragment is done first by findingan entry, for the second endpoint in the hash table(if it does not exist in the table, it is inserted). Thenwe find an entry for the first endpoint (if it does notexist in the table, or if it exists but its successor indexis not - 1then a new entry for is made). Then thesuccessor index in is set to point to A singlepoint edge fragment is inserted as one entry in the

    table where the successor index to the second endpointpoints to the entry itself.

    Deletion of an edge fragment is implemented bysetting to -1 the successor index field in the entry ofthe first endpoint of the edge fragment.

    Searching for an edge fragment is done by usinglinear open addressing hashing for an entry with theedge fragments first endpoint coordinates. If such anentry is found, the successor index field is checked forthe second endpoint of the edge fragment. If the suc-cessor index field is not - 1, the edge fragment is found.If the successor index field is - 1, then the linear searchcontinues until it is determined that no such point is

    stored.All the boundaryedge fragments of both polygons

    are inserted into the edge fragments table, EF, fromthe two vertex ringsA VandBV. Then, for each bound-

    aryedge fragment for which one or more exactly over-lapping edge fragments exist, the boundary situation

    is checked and some or all of these edge fragments aredeleted, if necessary, according to Table 3.

    When EF is implemented as a sorted table, this re-gularization process can & done by sorting the EFtable after the insertion of the edge fragments of thefirst polygon, A, and then using binary search for thecheck discussed above, when inserting the edge frag-ments of the second polygon,B. After appending the

    admissible edge fragments fromB,the wholeEFarrayis sorted again.

    When EF is implemented as a hash table, the edgefragments ofA are inserted one-by-one with the hashinginsertion procedure. Then, when the edge fragmentsof B are inserted, the search for oppositely directededge fragments is done by hashing. The admissible edgefragments ofB are inserted by hashing as soon as theyare encountered.

    In case a non-regular output is permitted, the pro-cedure may produce output result polygons which areline-segment polygons (like a polygon whose edges are

    and and/or single-

    point polygons (like a polygon whose edge isalong with any regular result polygons.

    3.3Implementation details

    In this section we describe the data structures andmethods used in implementing the procedure for setoperations on polygons.

    The procedure uses two linked lists, AV and BV,

    one array, EF, and three static control tables as itsinternal data structures.

    The two linked lists are the vertex rings. They areused to store the vertices and intersection points ofeach polygon in sequential order, so that all edge frag-merits are defined by two adjacent vertex ring entries.The insertion of the original vertices of a polygon isdone by linking them together into the linked list intheir Original order (including the link between the lastVertex and the first one). The insertion of each inter-section point is then done by moving along the linkedlist between the two original endpoints of the inter-sected edge and looking for the right place to insert thenew intersection point according to the coordinates of

    the new point, the coordinates of the existing pointsand the edge direction.

    We have imlemented the EF table, which issearched to construct the result polygons, using twodifferent methods. In the first methodEF is built as asorted table. Each new edge fragment is inserted intothe next available space in the array and subsequentlythe array is sorted. The search method used within thissorted EFtable is binary search. Deletion of an edgefragment is handled by using one bit in each entry oftheEFtable to mark the entry as deletedor not deleted.This is done to avoid physical deletions that could re-quire moving a lot of the entries.

    In the second method, the EF table is built as anopen addressing hash table of edge fragments. An entryin the hash table represents an endpoint of an edgefragment and contains the following fields:

    1. A bit to indicate whether the entry is free or used.2. The coordinates of an endpoint of the edge frag-

    ment.3. A successor index to the hash table entry that con-

    tains the coordinates of the second endpoint of theedge fragment. If this successor index is - 1, thecurrent entry represents the terminating endpointof an edge fragment and does not itself representthe first endpoint of an edge fragment.

    4. Two bits to indicate whether the edge fragmentwhose first endpoint is in the current entry comes

  • 8/12/2019 04 Polygon BooLeans

    10/17

    40 AVRAHAMMARGALITand GARYD. KNOTT

    The algorithm as presented is designed to take theclass of vertex-complete polygons as its input. It cannothandle general orientable polygons because when itsearches for the next vertex of a result polygon it de-pends on the fact that any two overlapping edge frag-

    ments must be identical as sets. This assumption holdsin the case of vertex-complete polygons but fails fororientable polygons since edges of the same polygoncan touch (as in Fig. 1) but the algorithm does notcompute and use these intersection points. This situ-ation is shown in Fig. 2 where polygon

    is orientable but not vertex-complete and

    ment(a, b)with polygon A . Consider computing AB. In the edge fragments selection process the edge

    fragment segment(a, b) is selected from the vertex ringof polygon A, and edge fragments segment(a, d ) andsegment(d, b)are selected from the vertex ring of poly-gon B after the intersection point d has been intro-duced. The intersection result of A and B is polygonA. Although the correct output is constructed, extraedge fragments have been introduced which do notform a cycle. Thus, either edge fragment segment(a,b) or edge fragment segment(d, b)has no continuation,and this causes the algorithm to fail.

    One way to extend the domain of the algorithm toorientablepolygons is to have a preprocessing stepwhere each polygon is checked for whether edges in-tersect each other. Intersection points, if found, areinserted as vertices of the polygon. This preprocessingreduces all orientable polygons to vertex-completepolygons which can be handled by our algorithm.

    Our implementation is crucially dependent on theaccuracy of the numerical calculations involved at threekey points:

    1. Determining if a point is inside, outsideor on theboundaryof a polygon must be done absolutelycorrectly. This requires accurate numerical calcu-lation to distinguish between the boundarysituationand the insideor outsidesituation.

    2. The decision as to whether an intersection pointexists between two edges must be absolutely correct.

    3. The calculation of the (x, y) value of an intersectionpoint should be very accurate to avoid possible non-orientable result polygons. We cannot absolutely

    avoid non-orientable result polygons, but a test canbe programmed which will detect such polygons.

    There are surprisingly many situations where ordi-nary floating point arithmetic is not good enough toachieve the required accuracy. We have used intervaland multiprecision arithmetic subroutines to overcomethe first two decision- problems[10]. The use of these

    cases when many of the vertices of one polygon are onthe boundary of the other polygon. This increase inrunning time is the price we pay for the accuracy ofthe result. Although the third problem can be solvedby using the same approach, it seems to be costly and

    rarely required.

    polygonB =polygon[a, b, f, g]shares the edge seg-subroutines increases the running time, especially in

    4. ANALYSISOF THE ALGORITHM

    4.1 Correctness proof of the algorithmIn this section we prove the correctness of the al-

    gorithm by proving the correctness of its two stages.The first stage is the classification of the line segmentsof the input polygons and the second stage is the con-struction of the result polygons. Since the second stageuses the output of the first stage as its input and sincewe assume that the inputs to the algorithm are twovertex-complete polygons, we can be sure of the cor-rectness of the output by proving the correctness of

    each stage. We prove the correctness for intersectionof two vertex-complete islandpolygons. The proofs forother operations and other combinations of polygontypes are similar.

    Definition1. Given two vertex-complete islandpolygonsA andB, anedge fragmentis defined to be a sub-seg-ment of an original edge ofA orB such that each of itstwo endpoints is either an original vertex ofA orB, oran intersection point of edges of these two polygons andsuch that no vertices or intersection points occur in theinterior of the sub-segment.

    Theorem1. Given twovertex-complete islandpolygonsA and B, an edgefragment, f, of one of these polygons

    is also an edge of an intersection result polygon R ifand only if it is aboundaryedge fragment or it is aninside edge fragment. In case regular result polygonsare required, aboundary edge fragment f is an edge ofan intersection result polygonR if and only if there isno other edge fragment with the same endpoints butwith opposite direction in both polygons.

    Proof:

    We prove by contradiction that an edge of an in-tersection result polygonRis a boundaryor an insideedge fragment of A or B. Suppose there is an outsideedge fragment as an edge of an intersection result poly-gon. This means that there exists at least one point p

    R such thatP A andP B, but this contradictsthe definition of

    Fig. 2. Intersection of two orientable polygons that share anedge.

  • 8/12/2019 04 Polygon BooLeans

    11/17

    An algorithm for pairs of polygons 41

    sumption that both A and B are identically ori-ented.

    Theorem 2.Given two identically oriented vertex-com-plete islandpolygonsA andB, the set of all theirinside

    and boundary edge fragments can be partitioned intoedge-disjoint non-self-intersecting cycles of edge frag-ments where no two cycles share an edgefragment.

    Proof:

    Define a polyline sequence of edge fragments as anordered list of edge fragments where the second end-point of each edge fragment is equal to the first end -point of the next edge fragment in the list. We willprove the theorem by showing that every maximal se-quence ofinsideand boundaryedge fragments mustform a cycle of edge fragments and that these cyclesare edge-disjoint.

    We first show that every maximal sequence of insideand boundaryedge fragments must form a cycle. Sup-pose this is not true, so there is a maximal sequenceof edge fragments that does not form a cycle. ByLemma 1 we know that everyinsideor boundary edgefragment has a continuation so this sequence must beinfinite. But the number of edge fragments is finite, sosuch a sequence cannot exist.

    Therefore, we see that every maximal sequence ofinsideand boundaryedge fragments forms a cycle. Ifthe cycle includes all the edge fragments of the se-quence, we are done. If the cycle does not include allthe edge fragments of the sequence, then we are leftwith a leading path of edge fragments, and we must

    show that this leading path has a continuation whichis edge-disjoint from the cycle; then we can ensure thatanother cycle will be formed if the remaining sequenceof edge fragments is continued using the successivecontinuation edge fragments of the leading path. Wewill show that the leading path has a continuation byconsidering all the possible cases.

    In Fig. 3 we show the four different cases for a leadingpath and a cycle. The solid lines represent edge frag-ments that are originally from polygon A and thedashed lines represent edge fragments that are originallyfrom polygonB. In the figure, edge fragment (a, b) isthe leading path while the sequence

    is the cycle. In Fig. 3(a) and 3(b), vertex b has anindegreeof two. That means that polygon A is notsimpleand thatb is a touching point of two edge-dis-

    joint parts of polygonA.Now, if a vertex-completepolygonA consists of two

    edgedisjoint parts with some common vertices, theresult of the intersection of sucha polygon with anotherpolygonB can be considered as the union of the in-tersection results of the edge-disjoint cycles ofA withB. Thus, we can consider these two intersection s u bproblems separately. This reduction process may bereiterated until both parts of Aare irreducibleparts.Thus, we may assume we have the base case wherepolygonA is formed from exactly two irreducible parts.

    In Fig. 3c, since edge fragment (a,b) isoriginally aninsideor a boundaryedge fragment of polygonA , there

    We prove by contradiction that a boundary or aninsideedge fragment ofA orB is an edge in the inter-section result polygon R. Suppose there is aboundaryor an insideedge fragment ofA that is not an edge inthe result polygon R. This means that there is a point

    This contra-dicts the definition of

    Now we prove by contradiction that theboundaryedge fragments that contribute to a regular intersectionresult polygon are those that appear only in one direc-tion. From the previous part of the proof we know thatevery boundaryedge fragment of A and B appears ina possibly non-regular result polygonR. So if a bound-aryedge fragment appears twice in both directions, itcontributes two opposite directed edges to a resultpolygon. Such a result polygon is not a regular polygonsince it includes overlapping edges. Thus, the edgefragments that contribute to a regular result polygon

    cannotbe

    those that appear in both directions; theymust be those that appear only in one direction.

    Lemma 1. Given two vertex-complete island identicallyoriented input polygonsA and B,for everyinside orboundary edge fragment selected for con-structing an intersection result polygon, there is a con-tinuation edge fragment which is an inputedge fragment or aboundary edge fragment.

    Proof:

    We prove this lemma by considering all the possibleinsideor boundaryedge fragments.Case 1: is an insideedge fragment.

    In thiscas e is either aninsidepoint or a boundarypoint. If is an insidepoint, it is an original vertex ofone ofthe polygons (suppose, without loss of generality,it is an original vertex of polygon A ) so there is anoriginal edge ofA , such that at least a part ofit is insideB. Thus, there is a continuation edge frag-ment, that is a part of edge where

    is either or is a point on the edge that isan intersection point between and an edge ofpolygonB.

    If pi is a boundarypoint let us assume, without lossof generality, that is an edge fragment that isoriginally from polygonA . If is an original vertex of

    polygonA and the next edge fragment ofA is insideor on the boundary of polygonB, we are done. If thenext edge fragment ofA is outsideof polygonB oris an intersection point, there is a part of the edge ofpolygonB that is on that is insidepolygonA , sothere is an edge fragment that is originally from polygonB, that can continue edge fragmentCase 2: is a boundaryedge fragment.Inthiscase is an edge fragment of bothA andB. If A and B continue to have the same boundary,

    is a boundaryedge fragment that continuesIf after point one of the polygons,A orB,

    goes inside the other one, there is an inside contin-uation edge fragment. If after point both the poly-

    gons go outside each other, then the two polygons haveopposite orientations, and this contradicts the as-

  • 8/12/2019 04 Polygon BooLeans

    12/17

    42 AVRAHAMMARGALITand GARYD. KNOTT

    (c) (d)Fig. 3. The four possibilities of a cycle of edge fragments and its leading path.

    must be a closed sequence of edges of polygon B that tex-completepolygon in Section 2.2). Thus we maysurround it. If this closed sequence includes edge frag- assume, without loss of generality, that either (1): thements (c,b) and (b, d) there is a continuation of the sequence comes from polygon Aleading path (a, b) that is originally from polygon A. and the sequence comes fromThis is because (c, b) and (b, d) are also insideor polygon B, or (2): the sequenceboundaryedge fragments, and for this to be so, there comes from polygon A and the sequence

    must be an edge fragment (b, e),originally from poly- comes from polygon B, where and egon A, that is insideor on the boundaryof polygon B.If the closed sequence of edges of polygon B does not First suppose (1) holds. Since both polygons A andinclude edge fragments (c,b) and (b, d), this means B are identically oriented, let us look at point c withthat polygon B is not simpleand thatb is the touching respect to polygon B and point dwith respect to poly-point of two edge-disjoint parts of polygon B.As men- gon A. Point c can be outsideB and then point d cantioned before, we can reduce this case to that where be insideA, but if point c is insideB then point dpolygon B is composed of just twoirreduciblepans. cannot be insideA. Thus, the situation of both c and

    In Fig. 3d, since both (a,b) and (b, d) areinsideor d being insidepoints is impossible and since all theon the boundaryof polygon B, there must be a closed edge fragments are insideor boundaryedge fragmentssequence of edges of polygon B that surround it. If this and this contradicts the assumption that twoclosed sequence includes edge fragment (c,b), there is cycles share edge fragment (a,b) .a continuation of the leading path (a,b) that is origi- Now suppose (2) holds. Since both polygons A andnally from polygon B. If the closed sequence of edges B are identically oriented, let us look at point dwithof polygon B does not include edge fragment (c, b), respect to polygon Band point cwith respect to polygonthat means that polygon B is not simple and thatb is A. Point c can be outsideA and then point d can bethe touching point of two edgedisjoint parts ofpolygon insideB, but if point c is insideA then point dcannotB. As mentioned before, we can reduce this case to be insideB. Thus, the situation of both c and d beingthat where polygon B is composed of just two irreduc- insidepoints is impossible, and since all the edge frag-ibleparts. ments areinsideor boundaryedge fragments and

    Now we show that the cycles are edge-disjoint. If all d, this contradicts the assumption that two cycles sharethe edge fragments form one cycle, we are done. 0th - edge fragment(a, b).erwise, suppose there are two cycles that share an edge

    Theorem 3.The algorithmfor intersection between twofragment. We show this situation in Fig. 4. The edgeidentically orientedvertex-complete islandpolygonsAfragment (a, b) is shared by the two cycles. If all theand B is correct.edge fragments in the figure come originally from one

    polygon, this polygon is not vertex-completesince by Proof:

    our assumption it cannot be partitioned into closed In Theorem 1we have proved that the edge fragmentssequences of edge fragments (see the definition of ver- that are selected to form the result are exactly those

  • 8/12/2019 04 Polygon BooLeans

    13/17

    An algorithm for pairs of polygons 43

    Fig. 4. The two possibilities for two cycles of edge fragments to share an edge fragment.

    needed to construct the result polygons. In Theorem2 we have proved that given the set of selected edgefragments, the construction process produces the set

    of the result polygons.

    4.2 Complexity analysis of the algorithm

    In this section we analyze the worst case time andspace complexity of the sorted table version of the al-gorithm presented for computing the intersection oftwo polygons A and B. Let and be the numberof vertices (and edges) in polygon A and polygon Brespectively and let be the number of intersectionpoints between edges of A and B. Note that can beas large as The time complexity of each stepin the algorithm is summarized below.

    ment. In this case the cost is at most steps.The same is true for polygon Bedge fragments. Thusthe total cost of this step is of

    5 . Selecting the result edge fragments is done in timeproportional to the number of edge fragments which

    is The cost of organizing the resultedge fragments for later searching depends on theorganization method. Since we give here a worstcase analysis, we shall not discuss the hash tablemethod since, although it is the better method withrespect to the average case complexity, it has aninferior worst case cost. For a sorted array organi-zation, the complexity is the sorting complexity andthus the total cost is

    also depends on the organization method we choose

    for the edge fragments. For the sorted table method,

    is so the total cost of this stepis

    Using each estimate above, we can see that the total

    1. Finding the orientation of each polygon requires 6. The complexity of constructing the result polygonsvisiting each vertex in each polygon so the total costof this step is

    steps and classifying each vertex of polygon B isdone in steps. Inserting each classified vertexpoint into the associated vertex ring requiressteps so the total cost of this step is

    3. Finding all the intersection points between the edgesof A and the edges of B in the way we have presentedhere is done in steps. Inserting each in-tersection point into the associated vertex ring re-quires steps at most. Thus the total cost ofthis step is

    4. Classifying each edge fragment is done in stepsif one of its endpoints is an original vertex ofA orB. The worst case for an edge fragment of polygon

    A is when its two endpoints are boundarypointsand the edge fragment is not aboundaryedge frag-

    2. Classifyingeach vertex of polygon A is done in

    the cost of the binary search for each edge fragment

    worst case time-cost of the algorithm is

    The space used by the algorithm consists of two ver-tex rings, one of size and the other of size

    and one edge fragment table of size

    So the total amount of space required is

  • 8/12/2019 04 Polygon BooLeans

    14/17

    44 AVRAHAM MARGALIT and GARY D. KNOTT

    By using modifications discussed below, an elabo-rated algorithm whose overall time cost is

    can be obtained.

    4.3Improvements to the algorithmIn this section we discuss some theoretical, but pos-

    sibly impractical, improvements to the algorithm. Wecan see in the previous section that the largest contri-butions to the worst case time complexity come fromthe cost of two steps of the algorithm:

    Finding the intersection points of the edges of the

    ring, continuing from point v, until a boundarypoint is found, assign all the edges visited to beinsideedge fragments, and go to (4).

    3. If all the points in the vertex ring, AV, are nowvisited, quit. Otherwise follow the points in the A Vring, continuing from point v, until a boundarypoint is found, and assign all the edges visited to beoutsideedge fragments.

    4. If all the points in the vertex ring, AV, are nowvisited, quit. Otherwise continue to follow the pointsin the A V ring until all points are visited or untilthis step is exited while checking the edges in the

    boundary points and they lie on one edge of B, theyform a boundary edge fragment. If one point, u, isa boundarypoint that is an intersection point ofedges and and if this intersectionpoint isnot an endpoint of and if the next point,

    w,is to the eastof then classify the edge fragment(u,w ) as aninsideedge fragment and go to (2). Ifthe next point, w, is to the westof then classifythe edge fragment (u,w)asan outsideedge fragmentand go to (3). In case the first point, u, is an endpointof b,we have to check whether the second point isto theeastor westof both and and take intoconsideration the angle between . Weandsummarize the rules in Table 5 . If the edge fragmentis seen to be an insideedge fragment, classify it assuch and go to (2). If the edge fragment is seen tobe an outsideedge fragment, classify it as such andgo to (3).

    We present Fig. 5 to help clarify the meaning ofangles that are greater or less than 180.

    In step (1) the algorithm visits once, in the worstcase, each node of the vertex ring AV. In steps (2)-(4)

    A V. For each edge fragment in A Vit checks if the edge

    of polygon B.Thus, this classification algorithm re-quires time.

    two polygons and inserting them into the vertex reference polygon B. If two adjacent points arerings.Classifying the edge fragments as inside, outside,orboundaryedge fragments.

    For the first of these problems, we can theoreticallyuse the algorithm sketched by Mairson and Stolfi[ 11]

    to find the intersection points. Given two sets of linesegments A and B, consisting of and noninter-secting segments respectively, this algorithm finds allthe intersection points of segments of A with seg-ments ofB in time.Now, to handle the insertions, we can put the inter-section points in a temporary array, sort the array ac-cording to the coordinates of the endpoints and thedirection of the original edge, and then form the vertexring by traversing the sorted array. This insertion sub-computation will take time.

    For the second problem we can use an algorithm toclassify the edge fragments in which we first find the

    intersection points and insert them into the vertex rings,and then classify the edge fragments using the infor-mation that intersection points are boundarypoints.We present here a brief description of this classification

    reference polygon B. In the case of a counterclockwise

    as follows:

    1. Choose from the vertex ring, A V, an original vertex,v , that is not aboundary point, and find if it is an

    to (2) and if it is an outsidepoint go to (3). If thereis no such vertex v(i.e., all the vertices of polygon

    A are boundarypoints) choose one vertex v

    of Aand go to (4).2. If all the points in the vertex ring, A V, are now

    visited, quit. Otherwise follow the points in the A V

    algorithm for a clockwise oriented polygon A and a the algorithm visits once each node of the vertex ring

    polygon the algorithm is similar. The algorithm goes fragment is to the east or the west of at most two edges

    insideor anoutsidepoint. If it is aninsidepoint go 5. CONCLUSIONSAs mentioned before, algorithms for set operations

    on polygons usually have two main stages: edge clas-

    sification and output polygon construction.A common approach to the classification problemis the use of a divide and conquer paradigm along withvertex neighborhood information[5,8] in order to

    Table 5.The rules when the first point of edge fragment (u, w) is an endpoint of

  • 8/12/2019 04 Polygon BooLeans

    15/17

    An algorithm for pairs of polygons 45

    structures. ACM Comput. Surveys16(2), 187-260 (June1984).

    5. R. B. Tilove, Set membership classification: A unifiedapproach to geometric intersection problems. IEEE

    Trans. Comp. C-29( 10), 874-883 (October 1980).6. D. Ayala, P. Brunet, R. Juan and I. Navazo, Object rep-

    resentation by means of non-minimal division quadtreesand octrees. ACM Trans. Graphics 4( 1),41-59 (January1985).

    7. G. M. Hunter, Operation on images using quadtrees.IEEE Trans. Pattern Analysis and Machine Intelligence

    8. G. Vanecek, Jr. and D. S. Nau, Computing geometricboolean operations by input directed decomposition,University of Maryland, TR 1762 (1987).

    9. L. K. Putnam and P. A. Subrahmanyam, Boolean op -erations on n-dimensional objects. IEEE Comput.Graphics and Applications 6(6), 43 - 51 (June 1986).

    10. G. D. Knott and E. D. Jou, A program to determinewhether two line segments intersect, University of Mary-

    land, TR 1884 (1987).11. H. G. Mairson and J. Stolfi, Reporting line segment in -tersections in the plane, Technical Report, Departmentof Computer Science, Stanford University, (1983).

    12. K. Weiler, Polygon comparison using graph representa -tion, SIGGRAPH 80 Proceedings, 10 - 18 (1980).

    13. M. Mantyla, Boolean operations of 2- manifolds throughvertex neighborhood classification. ACM Trans. Graphics5( 1), 1-29 (January 1986),

    14. M. Mantyla, Introduction to Solid Modeling, ComputerScience Press, Rockville, MD (1987).

    15. C. M. Eastman and C. J. Yessios, An efficient algorithmfor finding the union, intersection, and difference of spatialdomains, Technical Report 3 1, Institute of PhysicalPlanning, Carnegie - Mellon University (1972).

    16. C. M. Hoffmann, J . E. Hopcroft and M. S. Karasick,Robust set operations on polyhedral solids, Technical

    Report 87-875, Department of Computer Science, CornellUniversity (1987).

    for intersecting geometric figures. Commun. of the ACMvol. 25(10), 739 - 747 (October 1982).

    1(2), 145 - 153 (April 1979).

    Fig. 5. Clockwise oriented polygon with angles < 180 atpoints a, b, d, e and angle > 180 at point c.

    classify an edge of one polygon as being inside, outsideor on theboundaryof the other polygon, The lineseg-ment classification of the first stage and vertex neigh-borhood information are then used to perform theconstruction of the result polygons.

    The use of vertex neighborhood information seemsto require complex data structures and associated spaceto store the information. Moreover, just as with Ouralgorithm, without absolutely accurate determination

    of line segment intersections, such algorithms cannot

    determination, the proof of correctness of such algo-rithms can be difficult since there are often many spe-cial cases to deal with and it can be difficult to show

    neighborhood information is even more complicated

    whose vertices might have a degree greater than 2.We have presented here a robust algorithm, which

    is not based on checking a large number of specialcases. It can handle the class of vertex-completepoly-gons as input, which properly includes the elementary

    simple polygons. Its space requirements are relativelymodest, and its worst case time complexity is not bad,although it can be improved in theory.

    be guaranteed correct. Even with accurate intersection 17. J. Nievergelt and F. P. Preparata, Plane-sweep algorithms

    that all these cases are handled properly. Handling the APPENDIX A EXPERIMENTAL RESULTSIn this appendix we present some results of set operations

    between polygons produced by our program. Examples are

    the algorithm can deal with. In Fig. 6we see two star shapesas polygonA in (a) and polygon Bi n (b),and the result poly-gonso f in (c), in (d), in (e), andin (f) in Figs. 7-9 we show polygonA in (a), polygonB in(b), and the regular result polygons ofand are shaded in (c), (d), (e), and (f) respectively. Fig.

    7 is special because the two polygons have the same set ofvertices. In Fig. 8we present an example where polygonA ismade of three irreducible parts and two of its vertices lie onedges of polygon B. In this case absolute numerical accuracyis crucial to obtain the correct results. In Fig. 9 a vertex-com-

    plete polygon with three holes and collinear edges is presentedand we see that the correct regular results are obtained.

    In Figs. 10-12 we show polygon A in (a), polygon B in (b),and the regularresults polygonsof and

    are shaded in (c), (e), (g), and (i) respectively, and thenon-regularresult polygons of and

    are shown in (d), (f), (h), and (j)respectively. In Fig. 10we show how the algorithm handles collinear overlappingedgesof the input polygonsA and B. We can also see a degeneratesingle point result polygon in Fig. 10(d). in Figs. 1 1.and 12we show two other cases where the regular and non-regularresults are different.

    when one tries to work with vertex-complete polygons shown that present some of the kinds of complex cases that

    REFERENCES

    1. F. P. Preparata and M. I. Shamos. Computational Ge-ometry, An Introduction, Springer-Verlag. New York(1985).

    2. A. V. Aho, J. E. Hopcroft and J. D. Ullman, The Designand Analysis of Computer Algorithms,Addison-Wesley,Reading, MA (1974).

    3. A. A. G. Requicha and H. B. Voelcker, Boolean operationsin solid modeling-boundary evaluation and merging al-gorithms. Proc. IEEE 73( 1), 30-44 (January 1985).

    4. H. Samet, The quadtree and related hierarchical data

  • 8/12/2019 04 Polygon BooLeans

    16/17

    46 AVRAHAMMARGALITand GARYD. KNOTT

  • 8/12/2019 04 Polygon BooLeans

    17/17

    An algorithm for pairs of polygons 47