16
Triangulación de Polígonos comp-420

Triangulación de Polígonos - cimat.mxalram/analisis_algo/05... · Ear clipping triangulation Una vez construida la lista inicial de vertices reflex y orejas, se eliminan las orejas

Embed Size (px)

Citation preview

Triangulación de Polígonoscomp-420

Triangulación de polígonos

Triangulación: descomposición de un polígono simple en triángulos.

Cualquier triangulación de un polígono simple con n vertices tiene n-2 triángulos.

El algoritmo más simple, llamado de corte de orejas (ear clipping) es de orden O(n2).

El método antes visto para particionar polígonos en partes monotonas es útil porque podemos triangularlas con complejidad O(n).

Ear clipping triangulationUna oreja de un polígono es un triángulo formado por tres vertices consecutivos dentro del cual no hay otro vértice del polígono.

El segmento de recta entre vi-1 e vi+1 se llama diagonal.

El vértice vi se llama punta de la oreja.

Un triángulo consiste en una sola oreja aunque se puede poner como punta de la oreja cualquiera de los tres vértices.

Un polígono de cuatro o más lados siempre tiene al menos dos orejas que no traslapan ( probado por G.H. Meisters, Polygons have ears, Amer. Math. Monthly). Esto sugiere un algoritmo recursivo para la triangulación.

Si podemos encontrar una oreja en un polígono con n≥4 vertices y removerla, tendremos un polígono de n-1 vertices y podemos repetir el proceso.

Una implementacion inmediata tomaría O(n3).

D. Eberly. Geometric Tools. (www.geometrictools.com)

Ear clipping triangulation

Almacenar el polígono como una lista doblemente ligada de manera a poder eliminar rapidamente las puntas de las orejas:

construir la lista toma O(n).

Iterar sobre los vertices para encontrar orejas.

para cada vértice vi y su triángulo correspondiente (vi-1, vi, vi+1) (el indexado es módulo n por lo que vn=v0 y v-1 = vn-1) probar todos los otros vértices para ver si hay alguno dentro del triángulo.

Si no hay ninguno dentro del triángulo es una oreja, si hay al menos uno no lo es.

D. Eberly. Geometric Tools. (www.geometrictools.com)

Ear clipping triangulationEs suficiente considerar solamente los vertices reflex para ver si estan contenidos en el triangulo.

vertice reflex - el ángulo interior formado entre las dos aristas que lo comparten es mayor a 180 grados.

vertex convex - el ángulo interior formado entre las dos aristas que lo comparten es menor a 180 grados.

La estructura de datos de polígono mantiene 4 listas doblemente ligadas simultáneamente:

los vertices del polígono en una lista ligada cíclica,

los vertices convex en una lista lineal,

los vertices reflex en una lista lineal,

las puntas de orejas en una lista ligada cíclica. D. Eberly. Geometric Tools. (www.geometrictools.com)

reflex

convex

Ear clipping triangulationUna vez construida la lista inicial de vertices reflex y orejas, se eliminan las orejas una a una.

si vi es una oreja que se elimina, la configuracion de la arista en los vertices adyacentes puede cambiar. Si el vertice adyacente es...

convexo es facil convencerse que va a seguir siendo convexo.

oreja, no se queda oreja necesariamente despues de eliminar a vi.

reflex, es posible que se vuelva convex o posiblemente oreja después de eliminar a vi.

Despues de eliminar a vi, si un vertice adyacente es convex, probar si es una oreja iterando sobre los vertices reflex y probando si estan contenidos en el triangulo de ese vertex. Hay O(n) orejas, hay que verificar O(n) veces por oreja. El proceso total de eliminación de orejas toma O(n2).

D. Eberly. Geometric Tools. (www.geometrictools.com)

Ear clipping triangulation

Vertices convex C = { 0, 1, 3, 4, 6, 9 }

Vertices reflex R = { 2, 5, 7, 8 }

Vertices oreja E = { 3, 4, 6, 9 }

D. Eberly. Geometric Tools. (www.geometrictools.com)

1

2

3

45

6

78

9

0

Ear clipping triangulationVertices convex C = { 0, 1, 3, 4, 6, 9 }

Vertices reflex R = { 2, 5, 7, 8 }

Vertices oreja E = { 3, 4, 6, 9 }

D. Eberly. Geometric Tools. (www.geometrictools.com)

1

2

3

45

6

78

9

0

Eliminar oreja 3 :

Primer triangulo en la triangulación T0 = ⟨ 2, 3, 4⟩.

Triangulación de un polígono monónoto

Sea un polígono monótono respecto a y con n vértices.

Suponemos que es estrictamente monótono (que no contiene aristas horizontales)

Siempre podemos ir hacia abajo al “caminar” en las fronteras izquierda o derecha del polígono a partir del vértice más alto de hasta el más bajo.

Podemos seguir a desde arriba hacia abajo en ambas cadenas en su frontera agregando diagonales cuando sea posible.

Este es un algoritmo glotón: conectamos la mayor parte de vértices posible con diagonales en cada iteración.

P

P

P

P

Triangulación de un polígono monónoto

El algoritmo maneja los vértices en orden decreciente de su coordenada y.

Se requiere una estructura auxiliar: una pila (stack)

Inicialmente, esta pila está vacía, luego contiene los vértices de que se han encontrado (al paso de la línea de barrido) pero que necesitan más diagonales.

Al manejar un vértice se le añaden tantas diagonales con los vértices de la pila como sea posible.

Estas diagonales dividen al polígono en triángulos.

El vértice más bajo será el que esté arriba en la pila.

P

Triangulación de un polígono monónoto

La porción de que no ha sido triangulada pero que se encuentra arriba del último vértice visitado tiene forma de embudo.

P

Chapter 3POLYGON TRIANGULATION

not contain horizontal edges. Thus we always go down when we walk on theleft or right boundary chain of P from the highest vertex of P to the lowestone. This is the property that makes triangulating a monotone polygon easy:we can work our way through P from top to bottom on both chains, addingdiagonals whenever this is possible. Next we describe the details of this greedytriangulation algorithm.

The algorithm handles the vertices in order of decreasing y-coordinate. If two

not yettriangulated

trianglessplit off

vertices have the same y-coordinate, then the leftmost one is handled first. Thealgorithm requires a stack S as auxiliary data structure. Initially the stack isempty; later it contains the vertices of P that have been encountered but maystill need more diagonals. When we handle a vertex we add as many diagonalsfrom this vertex to vertices on the stack as possible. These diagonals split offtriangles from P. The vertices that have been handled but not split off—thevertices on the stack—are on the boundary of the part of P that still needs to betriangulated. The lowest of these vertices, which is the one encountered last, ison top of the stack, the second lowest is second on the stack, and so on. Thepart of P that still needs to be triangulated, and lies above the last vertex thathas been encountered so far, has a particular shape: it looks like a funnel turnedupside down. One boundary of the funnel consists of a part of a single edge ofP, and the other boundary is a chain consisting of reflex vertices, that is, theinterior angle at these vertices is at least 180!. Only the highest vertex, which isat the bottom of the stack, is convex. This property remains true after we havehandled the next vertex. Hence, it is an invariant of the algorithm.

Now, let’s see which diagonals we can add when we handle the next vertex.We distinguish two cases: v j, the next vertex to be handled, lies on the samechain as the reflex vertices on the stack, or it lies on the opposite chain. If v j

v j

popped

pushed

popped andpushed

e

lies on the opposite chain, it must be the lower endpoint of the single edge ebounding the funnel. Due to the shape of the funnel, we can add diagonals fromv j to all vertices currently on the stack, except for the last one (that is, the oneat the bottom of the stack); the last vertex on the stack is the upper vertex of e,so it is already connected to v j. All these vertices are popped from the stack.The untriangulated part of the polygon above v j is bounded by the diagonalthat connects v j to the vertex previously on top of the stack and the edge of Pextending downward from this vertex, so it looks like a funnel and the invariantis preserved. This vertex and v j remain part of the not yet triangulated polygon,so they are pushed onto the stack.

The other case is when v j is on the same chain as the reflex vertices on thestack. This time we may not be able to draw diagonals from v j to all vertices onthe stack. Nevertheless, the ones to which we can connect v j are all consecutiveand they are on top of the stack, so we can proceed as follows. First, pop onevertex from the stack; this vertex is already connected to v j by an edge of P.Next, pop vertices from the stack and connect them to v j until we encounterone where this is not possible. Checking whether a diagonal can be drawn fromv j to a vertex vk on the stack can be done by looking at v j, vk, and the previousvertex that was popped. When we find a vertex to which we cannot connect v j,we push the last vertex that has been popped back onto the stack. This is either56

Una frontera del embudo consta de parte de una sola arista de .

La otra frontera es una cadena que consta de los vértices reflejo (reflex), es decir, aquellos cuyo ángulo interior es de al menos 180°.

Solo el vértice más alto (el más profundo en la pila) es convexo.

Esta propiedad se mantiene durante toda la ejecución del algoritmo (invariante).

P

¿Dónde agregar diagonales?Al manejar un vértice vj distinguimos entre dos casos.

vj se encuentra en la misma cadena que los vértices reflejo (dentro de la pila). Se puede triangular a los vértices inmediatamente superiores sobre la misma cadena.

vj se encuentra en la cadena opuesta a los vértices reflejo debe ser el vértice inferior de la arista frontera del embudo. Se pueden agregar diagonales a todos vértices de la pila excepto al último que ya estará conectado con vj.

Chapter 3POLYGON TRIANGULATION

not contain horizontal edges. Thus we always go down when we walk on theleft or right boundary chain of P from the highest vertex of P to the lowestone. This is the property that makes triangulating a monotone polygon easy:we can work our way through P from top to bottom on both chains, addingdiagonals whenever this is possible. Next we describe the details of this greedytriangulation algorithm.

The algorithm handles the vertices in order of decreasing y-coordinate. If two

not yettriangulated

trianglessplit off

vertices have the same y-coordinate, then the leftmost one is handled first. Thealgorithm requires a stack S as auxiliary data structure. Initially the stack isempty; later it contains the vertices of P that have been encountered but maystill need more diagonals. When we handle a vertex we add as many diagonalsfrom this vertex to vertices on the stack as possible. These diagonals split offtriangles from P. The vertices that have been handled but not split off—thevertices on the stack—are on the boundary of the part of P that still needs to betriangulated. The lowest of these vertices, which is the one encountered last, ison top of the stack, the second lowest is second on the stack, and so on. Thepart of P that still needs to be triangulated, and lies above the last vertex thathas been encountered so far, has a particular shape: it looks like a funnel turnedupside down. One boundary of the funnel consists of a part of a single edge ofP, and the other boundary is a chain consisting of reflex vertices, that is, theinterior angle at these vertices is at least 180!. Only the highest vertex, which isat the bottom of the stack, is convex. This property remains true after we havehandled the next vertex. Hence, it is an invariant of the algorithm.

Now, let’s see which diagonals we can add when we handle the next vertex.We distinguish two cases: v j, the next vertex to be handled, lies on the samechain as the reflex vertices on the stack, or it lies on the opposite chain. If v j

v j

popped

pushed

popped andpushed

e

lies on the opposite chain, it must be the lower endpoint of the single edge ebounding the funnel. Due to the shape of the funnel, we can add diagonals fromv j to all vertices currently on the stack, except for the last one (that is, the oneat the bottom of the stack); the last vertex on the stack is the upper vertex of e,so it is already connected to v j. All these vertices are popped from the stack.The untriangulated part of the polygon above v j is bounded by the diagonalthat connects v j to the vertex previously on top of the stack and the edge of Pextending downward from this vertex, so it looks like a funnel and the invariantis preserved. This vertex and v j remain part of the not yet triangulated polygon,so they are pushed onto the stack.

The other case is when v j is on the same chain as the reflex vertices on thestack. This time we may not be able to draw diagonals from v j to all vertices onthe stack. Nevertheless, the ones to which we can connect v j are all consecutiveand they are on top of the stack, so we can proceed as follows. First, pop onevertex from the stack; this vertex is already connected to v j by an edge of P.Next, pop vertices from the stack and connect them to v j until we encounterone where this is not possible. Checking whether a diagonal can be drawn fromv j to a vertex vk on the stack can be done by looking at v j, vk, and the previousvertex that was popped. When we find a vertex to which we cannot connect v j,we push the last vertex that has been popped back onto the stack. This is either56

Section 3.3TRIANGULATING A MONOTONEPOLYGON

the last vertex to which a diagonal was added or, if no diagonals have beenadded, it is the neighbor of v j on the boundary of P—see Figure 3.5. After this

pushed

v j

popped

pushed

v j

popped andpushed

popped andpushed

Figure 3.5Two cases when the next vertex is onthe same side as the reflex vertices onthe stack

has been done we push v j onto the stack. In both cases the invariant is restored:one side of the funnel is bounded by a part of a single edge, and the other sideis bounded by a chain of reflex vertices. We get the following algorithm. (Thealgorithm is actually similar to the convex hull algorithm of Chapter 1.)

Algorithm TRIANGULATEMONOTONEPOLYGON(P)Input. A strictly y-monotone polygon P stored in a doubly-connected edge

list D.Output. A triangulation of P stored in the doubly-connected edge list D.1. Merge the vertices on the left chain and the vertices on the right chain of P

into one sequence, sorted on decreasing y-coordinate. If two vertices havethe same y-coordinate, then the leftmost one comes first. Let u1, . . . ,undenote the sorted sequence.

2. Initialize an empty stack S, and push u1 and u2 onto it.3. for j ! 3 to n"14. do if u j and the vertex on top of S are on different chains5. then Pop all vertices from S.6. Insert into D a diagonal from u j to each popped vertex,

except the last one.7. Push u j"1 and u j onto S.8. else Pop one vertex from S.9. Pop the other vertices from S as long as the diagonals from

u j to them are inside P. Insert these diagonals into D. Pushthe last vertex that has been popped back onto S.

10. Push u j onto S.11. Add diagonals from un to all stack vertices except the first and the last one.

How much time does the algorithm take? Step 1 takes linear time and Step 2takes constant time. The for-loop is executed n"3 times, and one executionmay take linear time. But at every execution of the for-loop at most two verticesare pushed. Hence, the total number of pushes, including the two in Step 2, isbounded by 2n"4. Because the number of pops cannot exceed the number ofpushes, the total time for all executions of the for-loop is O(n). The last step of 57

Triangulación de un polígono monónoto

Section 3.3TRIANGULATING A MONOTONEPOLYGON

the last vertex to which a diagonal was added or, if no diagonals have beenadded, it is the neighbor of v j on the boundary of P—see Figure 3.5. After this

pushed

v j

popped

pushed

v j

popped andpushed

popped andpushed

Figure 3.5Two cases when the next vertex is onthe same side as the reflex vertices onthe stack

has been done we push v j onto the stack. In both cases the invariant is restored:one side of the funnel is bounded by a part of a single edge, and the other sideis bounded by a chain of reflex vertices. We get the following algorithm. (Thealgorithm is actually similar to the convex hull algorithm of Chapter 1.)

Algorithm TRIANGULATEMONOTONEPOLYGON(P)Input. A strictly y-monotone polygon P stored in a doubly-connected edge

list D.Output. A triangulation of P stored in the doubly-connected edge list D.1. Merge the vertices on the left chain and the vertices on the right chain of P

into one sequence, sorted on decreasing y-coordinate. If two vertices havethe same y-coordinate, then the leftmost one comes first. Let u1, . . . ,undenote the sorted sequence.

2. Initialize an empty stack S, and push u1 and u2 onto it.3. for j ! 3 to n"14. do if u j and the vertex on top of S are on different chains5. then Pop all vertices from S.6. Insert into D a diagonal from u j to each popped vertex,

except the last one.7. Push u j"1 and u j onto S.8. else Pop one vertex from S.9. Pop the other vertices from S as long as the diagonals from

u j to them are inside P. Insert these diagonals into D. Pushthe last vertex that has been popped back onto S.

10. Push u j onto S.11. Add diagonals from un to all stack vertices except the first and the last one.

How much time does the algorithm take? Step 1 takes linear time and Step 2takes constant time. The for-loop is executed n"3 times, and one executionmay take linear time. But at every execution of the for-loop at most two verticesare pushed. Hence, the total number of pushes, including the two in Step 2, isbounded by 2n"4. Because the number of pops cannot exceed the number ofpushes, the total time for all executions of the for-loop is O(n). The last step of 57

0

1

2

3

4

5

6

7

89 10

11

1213

14 15

16

1718

19

2021

22

23

24

0

1

2

3

4

5

6

7

89 10

11

1213

14 15

16

1718

19

2021

22

23

24

0

1

2

3

4

5

6

7

89 10

11

1213

14 15

16

1718

19

2021

22

23

24

0

1

2

3

4

5

6

7

89 10

11

1213 14 15

16

1718

19

2021

22

23

24

0

1

2

3

4

5

6

7

89 10

11

1213 14 15

16

1718

19

2021

22

23

24

Triangulación de un polígono monónoto

El paso 1 toma tiempo lineal

El paso 2 toma tiempo constante

El ciclo for se ejecuta n-3 veces, una ejecución puede tomar tiempo lineal.

En cada ejecución del ciclo for se insertan a lo más dos vértices en el stack, entonces el número total de inserciones en el algoritmo está acotado por 2n-4.

Como el número de operaciones pop no puede exceder el número de operaciones push, el tiempo total de ejecuciones para el ciclo for es O(n).

El último paso del algoritmo toma a lo más tiempo lineal.

El algoritmo se ejecuta en O(n).