1 /*
2  * SGI FREE SOFTWARE LICENSE B (Version 2.0, Sept. 18, 2008)
3  * Copyright (C) 1991-2000 Silicon Graphics, Inc. All Rights Reserved.
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice including the dates of first publication and
13  * either this permission notice or a reference to
14  * http://oss.sgi.com/projects/FreeB/
15  * shall be included in all copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
18  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20  * SILICON GRAPHICS, INC. BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
21  * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
22  * OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23  * SOFTWARE.
24  *
25  * Except as contained in this notice, the name of Silicon Graphics, Inc.
26  * shall not be used in advertising or otherwise to promote the sale, use or
27  * other dealings in this Software without prior written authorization from
28  * Silicon Graphics, Inc.
29  */
30 /*
31 ** Author: Eric Veach, July 1994.
32 **
33 */
34 
35 #include <assert.h>
36 #include <stddef.h>
37 #include <setjmp.h>		/* longjmp */
38 #include <limits.h>		/* LONG_MAX */
39 
40 #include "mesh.h"
41 #include "geom.h"
42 #include "tess.h"
43 #include "dict.h"
44 #include "priorityq.h"
45 #include "memalloc.h"
46 #include "sweep.h"
47 
48 #ifndef TRUE
49 #define TRUE 1
50 #endif
51 #ifndef FALSE
52 #define FALSE 0
53 #endif
54 
55 #ifdef FOR_TRITE_TEST_PROGRAM
56 extern void DebugEvent( GLUtesselator *tess );
57 #else
58 #define DebugEvent( tess )
59 #endif
60 
61 /*
62  * Invariants for the Edge Dictionary.
63  * - each pair of adjacent edges e2=Succ(e1) satisfies EdgeLeq(e1,e2)
64  *   at any valid location of the sweep event
65  * - if EdgeLeq(e2,e1) as well (at any valid sweep event), then e1 and e2
66  *   share a common endpoint
67  * - for each e, e->Dst has been processed, but not e->Org
68  * - each edge e satisfies VertLeq(e->Dst,event) && VertLeq(event,e->Org)
69  *   where "event" is the current sweep line event.
70  * - no edge e has zero length
71  *
72  * Invariants for the Mesh (the processed portion).
73  * - the portion of the mesh left of the sweep line is a planar graph,
74  *   ie. there is *some* way to embed it in the plane
75  * - no processed edge has zero length
76  * - no two processed vertices have identical coordinates
77  * - each "inside" region is monotone, ie. can be broken into two chains
78  *   of monotonically increasing vertices according to VertLeq(v1,v2)
79  *   - a non-invariant: these chains may intersect (very slightly)
80  *
81  * Invariants for the Sweep.
82  * - if none of the edges incident to the event vertex have an activeRegion
83  *   (ie. none of these edges are in the edge dictionary), then the vertex
84  *   has only right-going edges.
85  * - if an edge is marked "fixUpperEdge" (it is a temporary edge introduced
86  *   by ConnectRightVertex), then it is the only right-going edge from
87  *   its associated vertex.  (This says that these edges exist only
88  *   when it is necessary.)
89  */
90 
91 #undef	MAX
92 #undef	MIN
93 #define MAX(x,y)	((x) >= (y) ? (x) : (y))
94 #define MIN(x,y)	((x) <= (y) ? (x) : (y))
95 
96 /* When we merge two edges into one, we need to compute the combined
97  * winding of the new edge.
98  */
99 #define AddWinding(eDst,eSrc)	(eDst->winding += eSrc->winding, \
100                                  eDst->Sym->winding += eSrc->Sym->winding)
101 
102 static void SweepEvent( GLUtesselator *tess, GLUvertex *vEvent );
103 static void WalkDirtyRegions( GLUtesselator *tess, ActiveRegion *regUp );
104 static int CheckForRightSplice( GLUtesselator *tess, ActiveRegion *regUp );
105 
EdgeLeq(GLUtesselator * tess,ActiveRegion * reg1,ActiveRegion * reg2)106 static int EdgeLeq( GLUtesselator *tess, ActiveRegion *reg1,
107 		    ActiveRegion *reg2 )
108 /*
109  * Both edges must be directed from right to left (this is the canonical
110  * direction for the upper edge of each region).
111  *
112  * The strategy is to evaluate a "t" value for each edge at the
113  * current sweep line position, given by tess->event.  The calculations
114  * are designed to be very stable, but of course they are not perfect.
115  *
116  * Special case: if both edge destinations are at the sweep event,
117  * we sort the edges by slope (they would otherwise compare equally).
118  */
119 {
120   GLUvertex *event = tess->event;
121   GLUhalfEdge *e1, *e2;
122   GLdouble t1, t2;
123 
124   e1 = reg1->eUp;
125   e2 = reg2->eUp;
126 
127   if( e1->Dst == event ) {
128     if( e2->Dst == event ) {
129       /* Two edges right of the sweep line which meet at the sweep event.
130        * Sort them by slope.
131        */
132       if( VertLeq( e1->Org, e2->Org )) {
133 	return EdgeSign( e2->Dst, e1->Org, e2->Org ) <= 0;
134       }
135       return EdgeSign( e1->Dst, e2->Org, e1->Org ) >= 0;
136     }
137     return EdgeSign( e2->Dst, event, e2->Org ) <= 0;
138   }
139   if( e2->Dst == event ) {
140     return EdgeSign( e1->Dst, event, e1->Org ) >= 0;
141   }
142 
143   /* General case - compute signed distance *from* e1, e2 to event */
144   t1 = EdgeEval( e1->Dst, event, e1->Org );
145   t2 = EdgeEval( e2->Dst, event, e2->Org );
146   return (t1 >= t2);
147 }
148 
149 
DeleteRegion(GLUtesselator * tess,ActiveRegion * reg)150 static void DeleteRegion( GLUtesselator *tess, ActiveRegion *reg )
151 {
152   if( reg->fixUpperEdge ) {
153     /* It was created with zero winding number, so it better be
154      * deleted with zero winding number (ie. it better not get merged
155      * with a real edge).
156      */
157     assert( reg->eUp->winding == 0 );
158   }
159   reg->eUp->activeRegion = NULL;
160   dictDelete( tess->dict, reg->nodeUp ); /* __gl_dictListDelete */
161   memFree( reg );
162 }
163 
164 
FixUpperEdge(ActiveRegion * reg,GLUhalfEdge * newEdge)165 static int FixUpperEdge( ActiveRegion *reg, GLUhalfEdge *newEdge )
166 /*
167  * Replace an upper edge which needs fixing (see ConnectRightVertex).
168  */
169 {
170   assert( reg->fixUpperEdge );
171   if ( !__gl_meshDelete( reg->eUp ) ) return 0;
172   reg->fixUpperEdge = FALSE;
173   reg->eUp = newEdge;
174   newEdge->activeRegion = reg;
175 
176   return 1;
177 }
178 
TopLeftRegion(ActiveRegion * reg)179 static ActiveRegion *TopLeftRegion( ActiveRegion *reg )
180 {
181   GLUvertex *org = reg->eUp->Org;
182   GLUhalfEdge *e;
183 
184   /* Find the region above the uppermost edge with the same origin */
185   do {
186     reg = RegionAbove( reg );
187   } while( reg->eUp->Org == org );
188 
189   /* If the edge above was a temporary edge introduced by ConnectRightVertex,
190    * now is the time to fix it.
191    */
192   if( reg->fixUpperEdge ) {
193     e = __gl_meshConnect( RegionBelow(reg)->eUp->Sym, reg->eUp->Lnext );
194     if (e == NULL) return NULL;
195     if ( !FixUpperEdge( reg, e ) ) return NULL;
196     reg = RegionAbove( reg );
197   }
198   return reg;
199 }
200 
TopRightRegion(ActiveRegion * reg)201 static ActiveRegion *TopRightRegion( ActiveRegion *reg )
202 {
203   GLUvertex *dst = reg->eUp->Dst;
204 
205   /* Find the region above the uppermost edge with the same destination */
206   do {
207     reg = RegionAbove( reg );
208   } while( reg->eUp->Dst == dst );
209   return reg;
210 }
211 
AddRegionBelow(GLUtesselator * tess,ActiveRegion * regAbove,GLUhalfEdge * eNewUp)212 static ActiveRegion *AddRegionBelow( GLUtesselator *tess,
213 				     ActiveRegion *regAbove,
214 				     GLUhalfEdge *eNewUp )
215 /*
216  * Add a new active region to the sweep line, *somewhere* below "regAbove"
217  * (according to where the new edge belongs in the sweep-line dictionary).
218  * The upper edge of the new region will be "eNewUp".
219  * Winding number and "inside" flag are not updated.
220  */
221 {
222   ActiveRegion *regNew = (ActiveRegion *)memAlloc( sizeof( ActiveRegion ));
223   if (regNew == NULL) longjmp(tess->env,1);
224 
225   regNew->eUp = eNewUp;
226   /* __gl_dictListInsertBefore */
227   regNew->nodeUp = dictInsertBefore( tess->dict, regAbove->nodeUp, regNew );
228   if (regNew->nodeUp == NULL) longjmp(tess->env,1);
229   regNew->fixUpperEdge = FALSE;
230   regNew->sentinel = FALSE;
231   regNew->dirty = FALSE;
232 
233   eNewUp->activeRegion = regNew;
234   return regNew;
235 }
236 
IsWindingInside(GLUtesselator * tess,int n)237 static GLboolean IsWindingInside( GLUtesselator *tess, int n )
238 {
239   switch( tess->windingRule ) {
240   case GLU_TESS_WINDING_ODD:
241     return (n & 1);
242   case GLU_TESS_WINDING_NONZERO:
243     return (n != 0);
244   case GLU_TESS_WINDING_POSITIVE:
245     return (n > 0);
246   case GLU_TESS_WINDING_NEGATIVE:
247     return (n < 0);
248   case GLU_TESS_WINDING_ABS_GEQ_TWO:
249     return (n >= 2) || (n <= -2);
250   }
251   /*LINTED*/
252   assert( FALSE );
253   /*NOTREACHED*/
254   return GL_FALSE;  /* avoid compiler complaints */
255 }
256 
257 
ComputeWinding(GLUtesselator * tess,ActiveRegion * reg)258 static void ComputeWinding( GLUtesselator *tess, ActiveRegion *reg )
259 {
260   reg->windingNumber = RegionAbove(reg)->windingNumber + reg->eUp->winding;
261   reg->inside = IsWindingInside( tess, reg->windingNumber );
262 }
263 
264 
FinishRegion(GLUtesselator * tess,ActiveRegion * reg)265 static void FinishRegion( GLUtesselator *tess, ActiveRegion *reg )
266 /*
267  * Delete a region from the sweep line.  This happens when the upper
268  * and lower chains of a region meet (at a vertex on the sweep line).
269  * The "inside" flag is copied to the appropriate mesh face (we could
270  * not do this before -- since the structure of the mesh is always
271  * changing, this face may not have even existed until now).
272  */
273 {
274   GLUhalfEdge *e = reg->eUp;
275   GLUface *f = e->Lface;
276 
277   f->inside = reg->inside;
278   f->anEdge = e;   /* optimization for __gl_meshTessellateMonoRegion() */
279   DeleteRegion( tess, reg );
280 }
281 
282 
FinishLeftRegions(GLUtesselator * tess,ActiveRegion * regFirst,ActiveRegion * regLast)283 static GLUhalfEdge *FinishLeftRegions( GLUtesselator *tess,
284 	       ActiveRegion *regFirst, ActiveRegion *regLast )
285 /*
286  * We are given a vertex with one or more left-going edges.  All affected
287  * edges should be in the edge dictionary.  Starting at regFirst->eUp,
288  * we walk down deleting all regions where both edges have the same
289  * origin vOrg.  At the same time we copy the "inside" flag from the
290  * active region to the face, since at this point each face will belong
291  * to at most one region (this was not necessarily true until this point
292  * in the sweep).  The walk stops at the region above regLast; if regLast
293  * is NULL we walk as far as possible.	At the same time we relink the
294  * mesh if necessary, so that the ordering of edges around vOrg is the
295  * same as in the dictionary.
296  */
297 {
298   ActiveRegion *reg, *regPrev;
299   GLUhalfEdge *e, *ePrev;
300 
301   regPrev = regFirst;
302   ePrev = regFirst->eUp;
303   while( regPrev != regLast ) {
304     regPrev->fixUpperEdge = FALSE;	/* placement was OK */
305     reg = RegionBelow( regPrev );
306     e = reg->eUp;
307     if( e->Org != ePrev->Org ) {
308       if( ! reg->fixUpperEdge ) {
309 	/* Remove the last left-going edge.  Even though there are no further
310 	 * edges in the dictionary with this origin, there may be further
311 	 * such edges in the mesh (if we are adding left edges to a vertex
312 	 * that has already been processed).  Thus it is important to call
313 	 * FinishRegion rather than just DeleteRegion.
314 	 */
315 	FinishRegion( tess, regPrev );
316 	break;
317       }
318       /* If the edge below was a temporary edge introduced by
319        * ConnectRightVertex, now is the time to fix it.
320        */
321       e = __gl_meshConnect( ePrev->Lprev, e->Sym );
322       if (e == NULL) longjmp(tess->env,1);
323       if ( !FixUpperEdge( reg, e ) ) longjmp(tess->env,1);
324     }
325 
326     /* Relink edges so that ePrev->Onext == e */
327     if( ePrev->Onext != e ) {
328       if ( !__gl_meshSplice( e->Oprev, e ) ) longjmp(tess->env,1);
329       if ( !__gl_meshSplice( ePrev, e ) ) longjmp(tess->env,1);
330     }
331     FinishRegion( tess, regPrev );	/* may change reg->eUp */
332     ePrev = reg->eUp;
333     regPrev = reg;
334   }
335   return ePrev;
336 }
337 
338 
AddRightEdges(GLUtesselator * tess,ActiveRegion * regUp,GLUhalfEdge * eFirst,GLUhalfEdge * eLast,GLUhalfEdge * eTopLeft,GLboolean cleanUp)339 static void AddRightEdges( GLUtesselator *tess, ActiveRegion *regUp,
340        GLUhalfEdge *eFirst, GLUhalfEdge *eLast, GLUhalfEdge *eTopLeft,
341        GLboolean cleanUp )
342 /*
343  * Purpose: insert right-going edges into the edge dictionary, and update
344  * winding numbers and mesh connectivity appropriately.  All right-going
345  * edges share a common origin vOrg.  Edges are inserted CCW starting at
346  * eFirst; the last edge inserted is eLast->Oprev.  If vOrg has any
347  * left-going edges already processed, then eTopLeft must be the edge
348  * such that an imaginary upward vertical segment from vOrg would be
349  * contained between eTopLeft->Oprev and eTopLeft; otherwise eTopLeft
350  * should be NULL.
351  */
352 {
353   ActiveRegion *reg, *regPrev;
354   GLUhalfEdge *e, *ePrev;
355   int firstTime = TRUE;
356 
357   /* Insert the new right-going edges in the dictionary */
358   e = eFirst;
359   do {
360     assert( VertLeq( e->Org, e->Dst ));
361     AddRegionBelow( tess, regUp, e->Sym );
362     e = e->Onext;
363   } while ( e != eLast );
364 
365   /* Walk *all* right-going edges from e->Org, in the dictionary order,
366    * updating the winding numbers of each region, and re-linking the mesh
367    * edges to match the dictionary ordering (if necessary).
368    */
369   if( eTopLeft == NULL ) {
370     eTopLeft = RegionBelow( regUp )->eUp->Rprev;
371   }
372   regPrev = regUp;
373   ePrev = eTopLeft;
374   for( ;; ) {
375     reg = RegionBelow( regPrev );
376     e = reg->eUp->Sym;
377     if( e->Org != ePrev->Org ) break;
378 
379     if( e->Onext != ePrev ) {
380       /* Unlink e from its current position, and relink below ePrev */
381       if ( !__gl_meshSplice( e->Oprev, e ) ) longjmp(tess->env,1);
382       if ( !__gl_meshSplice( ePrev->Oprev, e ) ) longjmp(tess->env,1);
383     }
384     /* Compute the winding number and "inside" flag for the new regions */
385     reg->windingNumber = regPrev->windingNumber - e->winding;
386     reg->inside = IsWindingInside( tess, reg->windingNumber );
387 
388     /* Check for two outgoing edges with same slope -- process these
389      * before any intersection tests (see example in __gl_computeInterior).
390      */
391     regPrev->dirty = TRUE;
392     if( ! firstTime && CheckForRightSplice( tess, regPrev )) {
393       AddWinding( e, ePrev );
394       DeleteRegion( tess, regPrev );
395       if ( !__gl_meshDelete( ePrev ) ) longjmp(tess->env,1);
396     }
397     firstTime = FALSE;
398     regPrev = reg;
399     ePrev = e;
400   }
401   regPrev->dirty = TRUE;
402   assert( regPrev->windingNumber - e->winding == reg->windingNumber );
403 
404   if( cleanUp ) {
405     /* Check for intersections between newly adjacent edges. */
406     WalkDirtyRegions( tess, regPrev );
407   }
408 }
409 
410 
CallCombine(GLUtesselator * tess,GLUvertex * isect,void * data[4],GLfloat weights[4],int needed)411 static void CallCombine( GLUtesselator *tess, GLUvertex *isect,
412 			 void *data[4], GLfloat weights[4], int needed )
413 {
414   GLdouble coords[3];
415 
416   /* Copy coord data in case the callback changes it. */
417   coords[0] = isect->coords[0];
418   coords[1] = isect->coords[1];
419   coords[2] = isect->coords[2];
420 
421   isect->data = NULL;
422   CALL_COMBINE_OR_COMBINE_DATA( coords, data, weights, &isect->data );
423   if( isect->data == NULL ) {
424     if( ! needed ) {
425       isect->data = data[0];
426     } else if( ! tess->fatalError ) {
427       /* The only way fatal error is when two edges are found to intersect,
428        * but the user has not provided the callback necessary to handle
429        * generated intersection points.
430        */
431       CALL_ERROR_OR_ERROR_DATA( GLU_TESS_NEED_COMBINE_CALLBACK );
432       tess->fatalError = TRUE;
433     }
434   }
435 }
436 
SpliceMergeVertices(GLUtesselator * tess,GLUhalfEdge * e1,GLUhalfEdge * e2)437 static void SpliceMergeVertices( GLUtesselator *tess, GLUhalfEdge *e1,
438 				 GLUhalfEdge *e2 )
439 /*
440  * Two vertices with idential coordinates are combined into one.
441  * e1->Org is kept, while e2->Org is discarded.
442  */
443 {
444   void *data[4] = { NULL, NULL, NULL, NULL };
445   GLfloat weights[4] = { 0.5, 0.5, 0.0, 0.0 };
446 
447   data[0] = e1->Org->data;
448   data[1] = e2->Org->data;
449   CallCombine( tess, e1->Org, data, weights, FALSE );
450   if ( !__gl_meshSplice( e1, e2 ) ) longjmp(tess->env,1);
451 }
452 
VertexWeights(GLUvertex * isect,GLUvertex * org,GLUvertex * dst,GLfloat * weights)453 static void VertexWeights( GLUvertex *isect, GLUvertex *org, GLUvertex *dst,
454 			   GLfloat *weights )
455 /*
456  * Find some weights which describe how the intersection vertex is
457  * a linear combination of "org" and "dest".  Each of the two edges
458  * which generated "isect" is allocated 50% of the weight; each edge
459  * splits the weight between its org and dst according to the
460  * relative distance to "isect".
461  */
462 {
463   GLdouble t1 = VertL1dist( org, isect );
464   GLdouble t2 = VertL1dist( dst, isect );
465 
466   weights[0] = 0.5 * t2 / (t1 + t2);
467   weights[1] = 0.5 * t1 / (t1 + t2);
468   isect->coords[0] += weights[0]*org->coords[0] + weights[1]*dst->coords[0];
469   isect->coords[1] += weights[0]*org->coords[1] + weights[1]*dst->coords[1];
470   isect->coords[2] += weights[0]*org->coords[2] + weights[1]*dst->coords[2];
471 }
472 
473 
GetIntersectData(GLUtesselator * tess,GLUvertex * isect,GLUvertex * orgUp,GLUvertex * dstUp,GLUvertex * orgLo,GLUvertex * dstLo)474 static void GetIntersectData( GLUtesselator *tess, GLUvertex *isect,
475        GLUvertex *orgUp, GLUvertex *dstUp,
476        GLUvertex *orgLo, GLUvertex *dstLo )
477 /*
478  * We've computed a new intersection point, now we need a "data" pointer
479  * from the user so that we can refer to this new vertex in the
480  * rendering callbacks.
481  */
482 {
483   void *data[4];
484   GLfloat weights[4];
485 
486   data[0] = orgUp->data;
487   data[1] = dstUp->data;
488   data[2] = orgLo->data;
489   data[3] = dstLo->data;
490 
491   isect->coords[0] = isect->coords[1] = isect->coords[2] = 0;
492   VertexWeights( isect, orgUp, dstUp, &weights[0] );
493   VertexWeights( isect, orgLo, dstLo, &weights[2] );
494 
495   CallCombine( tess, isect, data, weights, TRUE );
496 }
497 
CheckForRightSplice(GLUtesselator * tess,ActiveRegion * regUp)498 static int CheckForRightSplice( GLUtesselator *tess, ActiveRegion *regUp )
499 /*
500  * Check the upper and lower edge of "regUp", to make sure that the
501  * eUp->Org is above eLo, or eLo->Org is below eUp (depending on which
502  * origin is leftmost).
503  *
504  * The main purpose is to splice right-going edges with the same
505  * dest vertex and nearly identical slopes (ie. we can't distinguish
506  * the slopes numerically).  However the splicing can also help us
507  * to recover from numerical errors.  For example, suppose at one
508  * point we checked eUp and eLo, and decided that eUp->Org is barely
509  * above eLo.  Then later, we split eLo into two edges (eg. from
510  * a splice operation like this one).  This can change the result of
511  * our test so that now eUp->Org is incident to eLo, or barely below it.
512  * We must correct this condition to maintain the dictionary invariants.
513  *
514  * One possibility is to check these edges for intersection again
515  * (ie. CheckForIntersect).  This is what we do if possible.  However
516  * CheckForIntersect requires that tess->event lies between eUp and eLo,
517  * so that it has something to fall back on when the intersection
518  * calculation gives us an unusable answer.  So, for those cases where
519  * we can't check for intersection, this routine fixes the problem
520  * by just splicing the offending vertex into the other edge.
521  * This is a guaranteed solution, no matter how degenerate things get.
522  * Basically this is a combinatorial solution to a numerical problem.
523  */
524 {
525   ActiveRegion *regLo = RegionBelow(regUp);
526   GLUhalfEdge *eUp = regUp->eUp;
527   GLUhalfEdge *eLo = regLo->eUp;
528 
529   if( VertLeq( eUp->Org, eLo->Org )) {
530     if( EdgeSign( eLo->Dst, eUp->Org, eLo->Org ) > 0 ) return FALSE;
531 
532     /* eUp->Org appears to be below eLo */
533     if( ! VertEq( eUp->Org, eLo->Org )) {
534       /* Splice eUp->Org into eLo */
535       if ( __gl_meshSplitEdge( eLo->Sym ) == NULL) longjmp(tess->env,1);
536       if ( !__gl_meshSplice( eUp, eLo->Oprev ) ) longjmp(tess->env,1);
537       regUp->dirty = regLo->dirty = TRUE;
538 
539     } else if( eUp->Org != eLo->Org ) {
540       /* merge the two vertices, discarding eUp->Org */
541       pqDelete( tess->pq, eUp->Org->pqHandle ); /* __gl_pqSortDelete */
542       SpliceMergeVertices( tess, eLo->Oprev, eUp );
543     }
544   } else {
545     if( EdgeSign( eUp->Dst, eLo->Org, eUp->Org ) < 0 ) return FALSE;
546 
547     /* eLo->Org appears to be above eUp, so splice eLo->Org into eUp */
548     RegionAbove(regUp)->dirty = regUp->dirty = TRUE;
549     if (__gl_meshSplitEdge( eUp->Sym ) == NULL) longjmp(tess->env,1);
550     if ( !__gl_meshSplice( eLo->Oprev, eUp ) ) longjmp(tess->env,1);
551   }
552   return TRUE;
553 }
554 
CheckForLeftSplice(GLUtesselator * tess,ActiveRegion * regUp)555 static int CheckForLeftSplice( GLUtesselator *tess, ActiveRegion *regUp )
556 /*
557  * Check the upper and lower edge of "regUp", to make sure that the
558  * eUp->Dst is above eLo, or eLo->Dst is below eUp (depending on which
559  * destination is rightmost).
560  *
561  * Theoretically, this should always be true.  However, splitting an edge
562  * into two pieces can change the results of previous tests.  For example,
563  * suppose at one point we checked eUp and eLo, and decided that eUp->Dst
564  * is barely above eLo.  Then later, we split eLo into two edges (eg. from
565  * a splice operation like this one).  This can change the result of
566  * the test so that now eUp->Dst is incident to eLo, or barely below it.
567  * We must correct this condition to maintain the dictionary invariants
568  * (otherwise new edges might get inserted in the wrong place in the
569  * dictionary, and bad stuff will happen).
570  *
571  * We fix the problem by just splicing the offending vertex into the
572  * other edge.
573  */
574 {
575   ActiveRegion *regLo = RegionBelow(regUp);
576   GLUhalfEdge *eUp = regUp->eUp;
577   GLUhalfEdge *eLo = regLo->eUp;
578   GLUhalfEdge *e;
579 
580   assert( ! VertEq( eUp->Dst, eLo->Dst ));
581 
582   if( VertLeq( eUp->Dst, eLo->Dst )) {
583     if( EdgeSign( eUp->Dst, eLo->Dst, eUp->Org ) < 0 ) return FALSE;
584 
585     /* eLo->Dst is above eUp, so splice eLo->Dst into eUp */
586     RegionAbove(regUp)->dirty = regUp->dirty = TRUE;
587     e = __gl_meshSplitEdge( eUp );
588     if (e == NULL) longjmp(tess->env,1);
589     if ( !__gl_meshSplice( eLo->Sym, e ) ) longjmp(tess->env,1);
590     e->Lface->inside = regUp->inside;
591   } else {
592     if( EdgeSign( eLo->Dst, eUp->Dst, eLo->Org ) > 0 ) return FALSE;
593 
594     /* eUp->Dst is below eLo, so splice eUp->Dst into eLo */
595     regUp->dirty = regLo->dirty = TRUE;
596     e = __gl_meshSplitEdge( eLo );
597     if (e == NULL) longjmp(tess->env,1);
598     if ( !__gl_meshSplice( eUp->Lnext, eLo->Sym ) ) longjmp(tess->env,1);
599     e->Rface->inside = regUp->inside;
600   }
601   return TRUE;
602 }
603 
604 
CheckForIntersect(GLUtesselator * tess,ActiveRegion * regUp)605 static int CheckForIntersect( GLUtesselator *tess, ActiveRegion *regUp )
606 /*
607  * Check the upper and lower edges of the given region to see if
608  * they intersect.  If so, create the intersection and add it
609  * to the data structures.
610  *
611  * Returns TRUE if adding the new intersection resulted in a recursive
612  * call to AddRightEdges(); in this case all "dirty" regions have been
613  * checked for intersections, and possibly regUp has been deleted.
614  */
615 {
616   ActiveRegion *regLo = RegionBelow(regUp);
617   GLUhalfEdge *eUp = regUp->eUp;
618   GLUhalfEdge *eLo = regLo->eUp;
619   GLUvertex *orgUp = eUp->Org;
620   GLUvertex *orgLo = eLo->Org;
621   GLUvertex *dstUp = eUp->Dst;
622   GLUvertex *dstLo = eLo->Dst;
623   GLdouble tMinUp, tMaxLo;
624   GLUvertex isect, *orgMin;
625   GLUhalfEdge *e;
626 
627   assert( ! VertEq( dstLo, dstUp ));
628   assert( EdgeSign( dstUp, tess->event, orgUp ) <= 0 );
629   assert( EdgeSign( dstLo, tess->event, orgLo ) >= 0 );
630   assert( orgUp != tess->event && orgLo != tess->event );
631   assert( ! regUp->fixUpperEdge && ! regLo->fixUpperEdge );
632 
633   if( orgUp == orgLo ) return FALSE;	/* right endpoints are the same */
634 
635   tMinUp = MIN( orgUp->t, dstUp->t );
636   tMaxLo = MAX( orgLo->t, dstLo->t );
637   if( tMinUp > tMaxLo ) return FALSE;	/* t ranges do not overlap */
638 
639   if( VertLeq( orgUp, orgLo )) {
640     if( EdgeSign( dstLo, orgUp, orgLo ) > 0 ) return FALSE;
641   } else {
642     if( EdgeSign( dstUp, orgLo, orgUp ) < 0 ) return FALSE;
643   }
644 
645   /* At this point the edges intersect, at least marginally */
646   DebugEvent( tess );
647 
648   __gl_edgeIntersect( dstUp, orgUp, dstLo, orgLo, &isect );
649   /* The following properties are guaranteed: */
650   assert( MIN( orgUp->t, dstUp->t ) <= isect.t );
651   assert( isect.t <= MAX( orgLo->t, dstLo->t ));
652   assert( MIN( dstLo->s, dstUp->s ) <= isect.s );
653   assert( isect.s <= MAX( orgLo->s, orgUp->s ));
654 
655   if( VertLeq( &isect, tess->event )) {
656     /* The intersection point lies slightly to the left of the sweep line,
657      * so move it until it''s slightly to the right of the sweep line.
658      * (If we had perfect numerical precision, this would never happen
659      * in the first place).  The easiest and safest thing to do is
660      * replace the intersection by tess->event.
661      */
662     isect.s = tess->event->s;
663     isect.t = tess->event->t;
664   }
665   /* Similarly, if the computed intersection lies to the right of the
666    * rightmost origin (which should rarely happen), it can cause
667    * unbelievable inefficiency on sufficiently degenerate inputs.
668    * (If you have the test program, try running test54.d with the
669    * "X zoom" option turned on).
670    */
671   orgMin = VertLeq( orgUp, orgLo ) ? orgUp : orgLo;
672   if( VertLeq( orgMin, &isect )) {
673     isect.s = orgMin->s;
674     isect.t = orgMin->t;
675   }
676 
677   if( VertEq( &isect, orgUp ) || VertEq( &isect, orgLo )) {
678     /* Easy case -- intersection at one of the right endpoints */
679     (void) CheckForRightSplice( tess, regUp );
680     return FALSE;
681   }
682 
683   if(	 (! VertEq( dstUp, tess->event )
684 	  && EdgeSign( dstUp, tess->event, &isect ) >= 0)
685       || (! VertEq( dstLo, tess->event )
686 	  && EdgeSign( dstLo, tess->event, &isect ) <= 0 ))
687   {
688     /* Very unusual -- the new upper or lower edge would pass on the
689      * wrong side of the sweep event, or through it.  This can happen
690      * due to very small numerical errors in the intersection calculation.
691      */
692     if( dstLo == tess->event ) {
693       /* Splice dstLo into eUp, and process the new region(s) */
694       if (__gl_meshSplitEdge( eUp->Sym ) == NULL) longjmp(tess->env,1);
695       if ( !__gl_meshSplice( eLo->Sym, eUp ) ) longjmp(tess->env,1);
696       regUp = TopLeftRegion( regUp );
697       if (regUp == NULL) longjmp(tess->env,1);
698       eUp = RegionBelow(regUp)->eUp;
699       FinishLeftRegions( tess, RegionBelow(regUp), regLo );
700       AddRightEdges( tess, regUp, eUp->Oprev, eUp, eUp, TRUE );
701       return TRUE;
702     }
703     if( dstUp == tess->event ) {
704       /* Splice dstUp into eLo, and process the new region(s) */
705       if (__gl_meshSplitEdge( eLo->Sym ) == NULL) longjmp(tess->env,1);
706       if ( !__gl_meshSplice( eUp->Lnext, eLo->Oprev ) ) longjmp(tess->env,1);
707       regLo = regUp;
708       regUp = TopRightRegion( regUp );
709       e = RegionBelow(regUp)->eUp->Rprev;
710       regLo->eUp = eLo->Oprev;
711       eLo = FinishLeftRegions( tess, regLo, NULL );
712       AddRightEdges( tess, regUp, eLo->Onext, eUp->Rprev, e, TRUE );
713       return TRUE;
714     }
715     /* Special case: called from ConnectRightVertex.  If either
716      * edge passes on the wrong side of tess->event, split it
717      * (and wait for ConnectRightVertex to splice it appropriately).
718      */
719     if( EdgeSign( dstUp, tess->event, &isect ) >= 0 ) {
720       RegionAbove(regUp)->dirty = regUp->dirty = TRUE;
721       if (__gl_meshSplitEdge( eUp->Sym ) == NULL) longjmp(tess->env,1);
722       eUp->Org->s = tess->event->s;
723       eUp->Org->t = tess->event->t;
724     }
725     if( EdgeSign( dstLo, tess->event, &isect ) <= 0 ) {
726       regUp->dirty = regLo->dirty = TRUE;
727       if (__gl_meshSplitEdge( eLo->Sym ) == NULL) longjmp(tess->env,1);
728       eLo->Org->s = tess->event->s;
729       eLo->Org->t = tess->event->t;
730     }
731     /* leave the rest for ConnectRightVertex */
732     return FALSE;
733   }
734 
735   /* General case -- split both edges, splice into new vertex.
736    * When we do the splice operation, the order of the arguments is
737    * arbitrary as far as correctness goes.  However, when the operation
738    * creates a new face, the work done is proportional to the size of
739    * the new face.  We expect the faces in the processed part of
740    * the mesh (ie. eUp->Lface) to be smaller than the faces in the
741    * unprocessed original contours (which will be eLo->Oprev->Lface).
742    */
743   if (__gl_meshSplitEdge( eUp->Sym ) == NULL) longjmp(tess->env,1);
744   if (__gl_meshSplitEdge( eLo->Sym ) == NULL) longjmp(tess->env,1);
745   if ( !__gl_meshSplice( eLo->Oprev, eUp ) ) longjmp(tess->env,1);
746   eUp->Org->s = isect.s;
747   eUp->Org->t = isect.t;
748   eUp->Org->pqHandle = pqInsert( tess->pq, eUp->Org ); /* __gl_pqSortInsert */
749   if (eUp->Org->pqHandle == LONG_MAX) {
750      pqDeletePriorityQ(tess->pq);	/* __gl_pqSortDeletePriorityQ */
751      tess->pq = NULL;
752      longjmp(tess->env,1);
753   }
754   GetIntersectData( tess, eUp->Org, orgUp, dstUp, orgLo, dstLo );
755   RegionAbove(regUp)->dirty = regUp->dirty = regLo->dirty = TRUE;
756   return FALSE;
757 }
758 
WalkDirtyRegions(GLUtesselator * tess,ActiveRegion * regUp)759 static void WalkDirtyRegions( GLUtesselator *tess, ActiveRegion *regUp )
760 /*
761  * When the upper or lower edge of any region changes, the region is
762  * marked "dirty".  This routine walks through all the dirty regions
763  * and makes sure that the dictionary invariants are satisfied
764  * (see the comments at the beginning of this file).  Of course
765  * new dirty regions can be created as we make changes to restore
766  * the invariants.
767  */
768 {
769   ActiveRegion *regLo = RegionBelow(regUp);
770   GLUhalfEdge *eUp, *eLo;
771 
772   for( ;; ) {
773     /* Find the lowest dirty region (we walk from the bottom up). */
774     while( regLo->dirty ) {
775       regUp = regLo;
776       regLo = RegionBelow(regLo);
777     }
778     if( ! regUp->dirty ) {
779       regLo = regUp;
780       regUp = RegionAbove( regUp );
781       if( regUp == NULL || ! regUp->dirty ) {
782 	/* We've walked all the dirty regions */
783 	return;
784       }
785     }
786     regUp->dirty = FALSE;
787     eUp = regUp->eUp;
788     eLo = regLo->eUp;
789 
790     if( eUp->Dst != eLo->Dst ) {
791       /* Check that the edge ordering is obeyed at the Dst vertices. */
792       if( CheckForLeftSplice( tess, regUp )) {
793 
794 	/* If the upper or lower edge was marked fixUpperEdge, then
795 	 * we no longer need it (since these edges are needed only for
796 	 * vertices which otherwise have no right-going edges).
797 	 */
798 	if( regLo->fixUpperEdge ) {
799 	  DeleteRegion( tess, regLo );
800 	  if ( !__gl_meshDelete( eLo ) ) longjmp(tess->env,1);
801 	  regLo = RegionBelow( regUp );
802 	  eLo = regLo->eUp;
803 	} else if( regUp->fixUpperEdge ) {
804 	  DeleteRegion( tess, regUp );
805 	  if ( !__gl_meshDelete( eUp ) ) longjmp(tess->env,1);
806 	  regUp = RegionAbove( regLo );
807 	  eUp = regUp->eUp;
808 	}
809       }
810     }
811     if( eUp->Org != eLo->Org ) {
812       if(    eUp->Dst != eLo->Dst
813 	  && ! regUp->fixUpperEdge && ! regLo->fixUpperEdge
814 	  && (eUp->Dst == tess->event || eLo->Dst == tess->event) )
815       {
816 	/* When all else fails in CheckForIntersect(), it uses tess->event
817 	 * as the intersection location.  To make this possible, it requires
818 	 * that tess->event lie between the upper and lower edges, and also
819 	 * that neither of these is marked fixUpperEdge (since in the worst
820 	 * case it might splice one of these edges into tess->event, and
821 	 * violate the invariant that fixable edges are the only right-going
822 	 * edge from their associated vertex).
823 	 */
824 	if( CheckForIntersect( tess, regUp )) {
825 	  /* WalkDirtyRegions() was called recursively; we're done */
826 	  return;
827 	}
828       } else {
829 	/* Even though we can't use CheckForIntersect(), the Org vertices
830 	 * may violate the dictionary edge ordering.  Check and correct this.
831 	 */
832 	(void) CheckForRightSplice( tess, regUp );
833       }
834     }
835     if( eUp->Org == eLo->Org && eUp->Dst == eLo->Dst ) {
836       /* A degenerate loop consisting of only two edges -- delete it. */
837       AddWinding( eLo, eUp );
838       DeleteRegion( tess, regUp );
839       if ( !__gl_meshDelete( eUp ) ) longjmp(tess->env,1);
840       regUp = RegionAbove( regLo );
841     }
842   }
843 }
844 
845 
ConnectRightVertex(GLUtesselator * tess,ActiveRegion * regUp,GLUhalfEdge * eBottomLeft)846 static void ConnectRightVertex( GLUtesselator *tess, ActiveRegion *regUp,
847 				GLUhalfEdge *eBottomLeft )
848 /*
849  * Purpose: connect a "right" vertex vEvent (one where all edges go left)
850  * to the unprocessed portion of the mesh.  Since there are no right-going
851  * edges, two regions (one above vEvent and one below) are being merged
852  * into one.  "regUp" is the upper of these two regions.
853  *
854  * There are two reasons for doing this (adding a right-going edge):
855  *  - if the two regions being merged are "inside", we must add an edge
856  *    to keep them separated (the combined region would not be monotone).
857  *  - in any case, we must leave some record of vEvent in the dictionary,
858  *    so that we can merge vEvent with features that we have not seen yet.
859  *    For example, maybe there is a vertical edge which passes just to
860  *    the right of vEvent; we would like to splice vEvent into this edge.
861  *
862  * However, we don't want to connect vEvent to just any vertex.  We don''t
863  * want the new edge to cross any other edges; otherwise we will create
864  * intersection vertices even when the input data had no self-intersections.
865  * (This is a bad thing; if the user's input data has no intersections,
866  * we don't want to generate any false intersections ourselves.)
867  *
868  * Our eventual goal is to connect vEvent to the leftmost unprocessed
869  * vertex of the combined region (the union of regUp and regLo).
870  * But because of unseen vertices with all right-going edges, and also
871  * new vertices which may be created by edge intersections, we don''t
872  * know where that leftmost unprocessed vertex is.  In the meantime, we
873  * connect vEvent to the closest vertex of either chain, and mark the region
874  * as "fixUpperEdge".  This flag says to delete and reconnect this edge
875  * to the next processed vertex on the boundary of the combined region.
876  * Quite possibly the vertex we connected to will turn out to be the
877  * closest one, in which case we won''t need to make any changes.
878  */
879 {
880   GLUhalfEdge *eNew;
881   GLUhalfEdge *eTopLeft = eBottomLeft->Onext;
882   ActiveRegion *regLo = RegionBelow(regUp);
883   GLUhalfEdge *eUp = regUp->eUp;
884   GLUhalfEdge *eLo = regLo->eUp;
885   int degenerate = FALSE;
886 
887   if( eUp->Dst != eLo->Dst ) {
888     (void) CheckForIntersect( tess, regUp );
889   }
890 
891   /* Possible new degeneracies: upper or lower edge of regUp may pass
892    * through vEvent, or may coincide with new intersection vertex
893    */
894   if( VertEq( eUp->Org, tess->event )) {
895     if ( !__gl_meshSplice( eTopLeft->Oprev, eUp ) ) longjmp(tess->env,1);
896     regUp = TopLeftRegion( regUp );
897     if (regUp == NULL) longjmp(tess->env,1);
898     eTopLeft = RegionBelow( regUp )->eUp;
899     FinishLeftRegions( tess, RegionBelow(regUp), regLo );
900     degenerate = TRUE;
901   }
902   if( VertEq( eLo->Org, tess->event )) {
903     if ( !__gl_meshSplice( eBottomLeft, eLo->Oprev ) ) longjmp(tess->env,1);
904     eBottomLeft = FinishLeftRegions( tess, regLo, NULL );
905     degenerate = TRUE;
906   }
907   if( degenerate ) {
908     AddRightEdges( tess, regUp, eBottomLeft->Onext, eTopLeft, eTopLeft, TRUE );
909     return;
910   }
911 
912   /* Non-degenerate situation -- need to add a temporary, fixable edge.
913    * Connect to the closer of eLo->Org, eUp->Org.
914    */
915   if( VertLeq( eLo->Org, eUp->Org )) {
916     eNew = eLo->Oprev;
917   } else {
918     eNew = eUp;
919   }
920   eNew = __gl_meshConnect( eBottomLeft->Lprev, eNew );
921   if (eNew == NULL) longjmp(tess->env,1);
922 
923   /* Prevent cleanup, otherwise eNew might disappear before we've even
924    * had a chance to mark it as a temporary edge.
925    */
926   AddRightEdges( tess, regUp, eNew, eNew->Onext, eNew->Onext, FALSE );
927   eNew->Sym->activeRegion->fixUpperEdge = TRUE;
928   WalkDirtyRegions( tess, regUp );
929 }
930 
931 /* Because vertices at exactly the same location are merged together
932  * before we process the sweep event, some degenerate cases can't occur.
933  * However if someone eventually makes the modifications required to
934  * merge features which are close together, the cases below marked
935  * TOLERANCE_NONZERO will be useful.  They were debugged before the
936  * code to merge identical vertices in the main loop was added.
937  */
938 #define TOLERANCE_NONZERO	FALSE
939 
ConnectLeftDegenerate(GLUtesselator * tess,ActiveRegion * regUp,GLUvertex * vEvent)940 static void ConnectLeftDegenerate( GLUtesselator *tess,
941 				   ActiveRegion *regUp, GLUvertex *vEvent )
942 /*
943  * The event vertex lies exacty on an already-processed edge or vertex.
944  * Adding the new vertex involves splicing it into the already-processed
945  * part of the mesh.
946  */
947 {
948   GLUhalfEdge *e, *eTopLeft, *eTopRight, *eLast;
949   ActiveRegion *reg;
950 
951   e = regUp->eUp;
952   if( VertEq( e->Org, vEvent )) {
953     /* e->Org is an unprocessed vertex - just combine them, and wait
954      * for e->Org to be pulled from the queue
955      */
956     assert( TOLERANCE_NONZERO );
957     SpliceMergeVertices( tess, e, vEvent->anEdge );
958     return;
959   }
960 
961   if( ! VertEq( e->Dst, vEvent )) {
962     /* General case -- splice vEvent into edge e which passes through it */
963     if (__gl_meshSplitEdge( e->Sym ) == NULL) longjmp(tess->env,1);
964     if( regUp->fixUpperEdge ) {
965       /* This edge was fixable -- delete unused portion of original edge */
966       if ( !__gl_meshDelete( e->Onext ) ) longjmp(tess->env,1);
967       regUp->fixUpperEdge = FALSE;
968     }
969     if ( !__gl_meshSplice( vEvent->anEdge, e ) ) longjmp(tess->env,1);
970     SweepEvent( tess, vEvent ); /* recurse */
971     return;
972   }
973 
974   /* vEvent coincides with e->Dst, which has already been processed.
975    * Splice in the additional right-going edges.
976    */
977   assert( TOLERANCE_NONZERO );
978   regUp = TopRightRegion( regUp );
979   reg = RegionBelow( regUp );
980   eTopRight = reg->eUp->Sym;
981   eTopLeft = eLast = eTopRight->Onext;
982   if( reg->fixUpperEdge ) {
983     /* Here e->Dst has only a single fixable edge going right.
984      * We can delete it since now we have some real right-going edges.
985      */
986     assert( eTopLeft != eTopRight );   /* there are some left edges too */
987     DeleteRegion( tess, reg );
988     if ( !__gl_meshDelete( eTopRight ) ) longjmp(tess->env,1);
989     eTopRight = eTopLeft->Oprev;
990   }
991   if ( !__gl_meshSplice( vEvent->anEdge, eTopRight ) ) longjmp(tess->env,1);
992   if( ! EdgeGoesLeft( eTopLeft )) {
993     /* e->Dst had no left-going edges -- indicate this to AddRightEdges() */
994     eTopLeft = NULL;
995   }
996   AddRightEdges( tess, regUp, eTopRight->Onext, eLast, eTopLeft, TRUE );
997 }
998 
999 
ConnectLeftVertex(GLUtesselator * tess,GLUvertex * vEvent)1000 static void ConnectLeftVertex( GLUtesselator *tess, GLUvertex *vEvent )
1001 /*
1002  * Purpose: connect a "left" vertex (one where both edges go right)
1003  * to the processed portion of the mesh.  Let R be the active region
1004  * containing vEvent, and let U and L be the upper and lower edge
1005  * chains of R.  There are two possibilities:
1006  *
1007  * - the normal case: split R into two regions, by connecting vEvent to
1008  *   the rightmost vertex of U or L lying to the left of the sweep line
1009  *
1010  * - the degenerate case: if vEvent is close enough to U or L, we
1011  *   merge vEvent into that edge chain.  The subcases are:
1012  *	- merging with the rightmost vertex of U or L
1013  *	- merging with the active edge of U or L
1014  *	- merging with an already-processed portion of U or L
1015  */
1016 {
1017   ActiveRegion *regUp, *regLo, *reg;
1018   GLUhalfEdge *eUp, *eLo, *eNew;
1019   ActiveRegion tmp;
1020 
1021   /* assert( vEvent->anEdge->Onext->Onext == vEvent->anEdge ); */
1022 
1023   /* Get a pointer to the active region containing vEvent */
1024   tmp.eUp = vEvent->anEdge->Sym;
1025   /* __GL_DICTLISTKEY */ /* __gl_dictListSearch */
1026   regUp = (ActiveRegion *)dictKey( dictSearch( tess->dict, &tmp ));
1027   regLo = RegionBelow( regUp );
1028   eUp = regUp->eUp;
1029   eLo = regLo->eUp;
1030 
1031   /* Try merging with U or L first */
1032   if( EdgeSign( eUp->Dst, vEvent, eUp->Org ) == 0 ) {
1033     ConnectLeftDegenerate( tess, regUp, vEvent );
1034     return;
1035   }
1036 
1037   /* Connect vEvent to rightmost processed vertex of either chain.
1038    * e->Dst is the vertex that we will connect to vEvent.
1039    */
1040   reg = VertLeq( eLo->Dst, eUp->Dst ) ? regUp : regLo;
1041 
1042   if( regUp->inside || reg->fixUpperEdge) {
1043     if( reg == regUp ) {
1044       eNew = __gl_meshConnect( vEvent->anEdge->Sym, eUp->Lnext );
1045       if (eNew == NULL) longjmp(tess->env,1);
1046     } else {
1047       GLUhalfEdge *tempHalfEdge= __gl_meshConnect( eLo->Dnext, vEvent->anEdge);
1048       if (tempHalfEdge == NULL) longjmp(tess->env,1);
1049 
1050       eNew = tempHalfEdge->Sym;
1051     }
1052     if( reg->fixUpperEdge ) {
1053       if ( !FixUpperEdge( reg, eNew ) ) longjmp(tess->env,1);
1054     } else {
1055       ComputeWinding( tess, AddRegionBelow( tess, regUp, eNew ));
1056     }
1057     SweepEvent( tess, vEvent );
1058   } else {
1059     /* The new vertex is in a region which does not belong to the polygon.
1060      * We don''t need to connect this vertex to the rest of the mesh.
1061      */
1062     AddRightEdges( tess, regUp, vEvent->anEdge, vEvent->anEdge, NULL, TRUE );
1063   }
1064 }
1065 
1066 
SweepEvent(GLUtesselator * tess,GLUvertex * vEvent)1067 static void SweepEvent( GLUtesselator *tess, GLUvertex *vEvent )
1068 /*
1069  * Does everything necessary when the sweep line crosses a vertex.
1070  * Updates the mesh and the edge dictionary.
1071  */
1072 {
1073   ActiveRegion *regUp, *reg;
1074   GLUhalfEdge *e, *eTopLeft, *eBottomLeft;
1075 
1076   tess->event = vEvent; 	/* for access in EdgeLeq() */
1077   DebugEvent( tess );
1078 
1079   /* Check if this vertex is the right endpoint of an edge that is
1080    * already in the dictionary.  In this case we don't need to waste
1081    * time searching for the location to insert new edges.
1082    */
1083   e = vEvent->anEdge;
1084   while( e->activeRegion == NULL ) {
1085     e = e->Onext;
1086     if( e == vEvent->anEdge ) {
1087       /* All edges go right -- not incident to any processed edges */
1088       ConnectLeftVertex( tess, vEvent );
1089       return;
1090     }
1091   }
1092 
1093   /* Processing consists of two phases: first we "finish" all the
1094    * active regions where both the upper and lower edges terminate
1095    * at vEvent (ie. vEvent is closing off these regions).
1096    * We mark these faces "inside" or "outside" the polygon according
1097    * to their winding number, and delete the edges from the dictionary.
1098    * This takes care of all the left-going edges from vEvent.
1099    */
1100   regUp = TopLeftRegion( e->activeRegion );
1101   if (regUp == NULL) longjmp(tess->env,1);
1102   reg = RegionBelow( regUp );
1103   eTopLeft = reg->eUp;
1104   eBottomLeft = FinishLeftRegions( tess, reg, NULL );
1105 
1106   /* Next we process all the right-going edges from vEvent.  This
1107    * involves adding the edges to the dictionary, and creating the
1108    * associated "active regions" which record information about the
1109    * regions between adjacent dictionary edges.
1110    */
1111   if( eBottomLeft->Onext == eTopLeft ) {
1112     /* No right-going edges -- add a temporary "fixable" edge */
1113     ConnectRightVertex( tess, regUp, eBottomLeft );
1114   } else {
1115     AddRightEdges( tess, regUp, eBottomLeft->Onext, eTopLeft, eTopLeft, TRUE );
1116   }
1117 }
1118 
1119 
1120 /* Make the sentinel coordinates big enough that they will never be
1121  * merged with real input features.  (Even with the largest possible
1122  * input contour and the maximum tolerance of 1.0, no merging will be
1123  * done with coordinates larger than 3 * GLU_TESS_MAX_COORD).
1124  */
1125 #define SENTINEL_COORD	(4 * GLU_TESS_MAX_COORD)
1126 
AddSentinel(GLUtesselator * tess,GLdouble t)1127 static void AddSentinel( GLUtesselator *tess, GLdouble t )
1128 /*
1129  * We add two sentinel edges above and below all other edges,
1130  * to avoid special cases at the top and bottom.
1131  */
1132 {
1133   GLUhalfEdge *e;
1134   ActiveRegion *reg = (ActiveRegion *)memAlloc( sizeof( ActiveRegion ));
1135   if (reg == NULL) longjmp(tess->env,1);
1136 
1137   e = __gl_meshMakeEdge( tess->mesh );
1138   if (e == NULL) longjmp(tess->env,1);
1139 
1140   e->Org->s = SENTINEL_COORD;
1141   e->Org->t = t;
1142   e->Dst->s = -SENTINEL_COORD;
1143   e->Dst->t = t;
1144   tess->event = e->Dst; 	/* initialize it */
1145 
1146   reg->eUp = e;
1147   reg->windingNumber = 0;
1148   reg->inside = FALSE;
1149   reg->fixUpperEdge = FALSE;
1150   reg->sentinel = TRUE;
1151   reg->dirty = FALSE;
1152   reg->nodeUp = dictInsert( tess->dict, reg ); /* __gl_dictListInsertBefore */
1153   if (reg->nodeUp == NULL) longjmp(tess->env,1);
1154 }
1155 
1156 
InitEdgeDict(GLUtesselator * tess)1157 static void InitEdgeDict( GLUtesselator *tess )
1158 /*
1159  * We maintain an ordering of edge intersections with the sweep line.
1160  * This order is maintained in a dynamic dictionary.
1161  */
1162 {
1163   /* __gl_dictListNewDict */
1164   tess->dict = dictNewDict( tess, (int (*)(void *, DictKey, DictKey)) EdgeLeq );
1165   if (tess->dict == NULL) longjmp(tess->env,1);
1166 
1167   AddSentinel( tess, -SENTINEL_COORD );
1168   AddSentinel( tess, SENTINEL_COORD );
1169 }
1170 
1171 
DoneEdgeDict(GLUtesselator * tess)1172 static void DoneEdgeDict( GLUtesselator *tess )
1173 {
1174   ActiveRegion *reg;
1175 #ifndef NDEBUG
1176   int fixedEdges = 0;
1177 #endif
1178 
1179   /* __GL_DICTLISTKEY */ /* __GL_DICTLISTMIN */
1180   while( (reg = (ActiveRegion *)dictKey( dictMin( tess->dict ))) != NULL ) {
1181     /*
1182      * At the end of all processing, the dictionary should contain
1183      * only the two sentinel edges, plus at most one "fixable" edge
1184      * created by ConnectRightVertex().
1185      */
1186     if( ! reg->sentinel ) {
1187       assert( reg->fixUpperEdge );
1188       assert( ++fixedEdges == 1 );
1189     }
1190     assert( reg->windingNumber == 0 );
1191     DeleteRegion( tess, reg );
1192 /*    __gl_meshDelete( reg->eUp );*/
1193   }
1194   dictDeleteDict( tess->dict ); /* __gl_dictListDeleteDict */
1195 }
1196 
1197 
RemoveDegenerateEdges(GLUtesselator * tess)1198 static void RemoveDegenerateEdges( GLUtesselator *tess )
1199 /*
1200  * Remove zero-length edges, and contours with fewer than 3 vertices.
1201  */
1202 {
1203   GLUhalfEdge *e, *eNext, *eLnext;
1204   GLUhalfEdge *eHead = &tess->mesh->eHead;
1205 
1206   /*LINTED*/
1207   for( e = eHead->next; e != eHead; e = eNext ) {
1208     eNext = e->next;
1209     eLnext = e->Lnext;
1210 
1211     if( VertEq( e->Org, e->Dst ) && e->Lnext->Lnext != e ) {
1212       /* Zero-length edge, contour has at least 3 edges */
1213 
1214       SpliceMergeVertices( tess, eLnext, e );	/* deletes e->Org */
1215       if ( !__gl_meshDelete( e ) ) longjmp(tess->env,1); /* e is a self-loop */
1216       e = eLnext;
1217       eLnext = e->Lnext;
1218     }
1219     if( eLnext->Lnext == e ) {
1220       /* Degenerate contour (one or two edges) */
1221 
1222       if( eLnext != e ) {
1223 	if( eLnext == eNext || eLnext == eNext->Sym ) { eNext = eNext->next; }
1224 	if ( !__gl_meshDelete( eLnext ) ) longjmp(tess->env,1);
1225       }
1226       if( e == eNext || e == eNext->Sym ) { eNext = eNext->next; }
1227       if ( !__gl_meshDelete( e ) ) longjmp(tess->env,1);
1228     }
1229   }
1230 }
1231 
InitPriorityQ(GLUtesselator * tess)1232 static int InitPriorityQ( GLUtesselator *tess )
1233 /*
1234  * Insert all vertices into the priority queue which determines the
1235  * order in which vertices cross the sweep line.
1236  */
1237 {
1238   PriorityQ *pq;
1239   GLUvertex *v, *vHead;
1240 
1241   /* __gl_pqSortNewPriorityQ */
1242   pq = tess->pq = pqNewPriorityQ( (int (*)(PQkey, PQkey)) __gl_vertLeq );
1243   if (pq == NULL) return 0;
1244 
1245   vHead = &tess->mesh->vHead;
1246   for( v = vHead->next; v != vHead; v = v->next ) {
1247     v->pqHandle = pqInsert( pq, v ); /* __gl_pqSortInsert */
1248     if (v->pqHandle == LONG_MAX) break;
1249   }
1250   if (v != vHead || !pqInit( pq ) ) { /* __gl_pqSortInit */
1251     pqDeletePriorityQ(tess->pq);	/* __gl_pqSortDeletePriorityQ */
1252     tess->pq = NULL;
1253     return 0;
1254   }
1255 
1256   return 1;
1257 }
1258 
1259 
DonePriorityQ(GLUtesselator * tess)1260 static void DonePriorityQ( GLUtesselator *tess )
1261 {
1262   pqDeletePriorityQ( tess->pq ); /* __gl_pqSortDeletePriorityQ */
1263 }
1264 
1265 
RemoveDegenerateFaces(GLUmesh * mesh)1266 static int RemoveDegenerateFaces( GLUmesh *mesh )
1267 /*
1268  * Delete any degenerate faces with only two edges.  WalkDirtyRegions()
1269  * will catch almost all of these, but it won't catch degenerate faces
1270  * produced by splice operations on already-processed edges.
1271  * The two places this can happen are in FinishLeftRegions(), when
1272  * we splice in a "temporary" edge produced by ConnectRightVertex(),
1273  * and in CheckForLeftSplice(), where we splice already-processed
1274  * edges to ensure that our dictionary invariants are not violated
1275  * by numerical errors.
1276  *
1277  * In both these cases it is *very* dangerous to delete the offending
1278  * edge at the time, since one of the routines further up the stack
1279  * will sometimes be keeping a pointer to that edge.
1280  */
1281 {
1282   GLUface *f, *fNext;
1283   GLUhalfEdge *e;
1284 
1285   /*LINTED*/
1286   for( f = mesh->fHead.next; f != &mesh->fHead; f = fNext ) {
1287     fNext = f->next;
1288     e = f->anEdge;
1289     assert( e->Lnext != e );
1290 
1291     if( e->Lnext->Lnext == e ) {
1292       /* A face with only two edges */
1293       AddWinding( e->Onext, e );
1294       if ( !__gl_meshDelete( e ) ) return 0;
1295     }
1296   }
1297   return 1;
1298 }
1299 
__gl_computeInterior(GLUtesselator * tess)1300 int __gl_computeInterior( GLUtesselator *tess )
1301 /*
1302  * __gl_computeInterior( tess ) computes the planar arrangement specified
1303  * by the given contours, and further subdivides this arrangement
1304  * into regions.  Each region is marked "inside" if it belongs
1305  * to the polygon, according to the rule given by tess->windingRule.
1306  * Each interior region is guaranteed be monotone.
1307  */
1308 {
1309   GLUvertex *v, *vNext;
1310 
1311   tess->fatalError = FALSE;
1312 
1313   /* Each vertex defines an event for our sweep line.  Start by inserting
1314    * all the vertices in a priority queue.  Events are processed in
1315    * lexicographic order, ie.
1316    *
1317    *	e1 < e2  iff  e1.x < e2.x || (e1.x == e2.x && e1.y < e2.y)
1318    */
1319   RemoveDegenerateEdges( tess );
1320   if ( !InitPriorityQ( tess ) ) return 0; /* if error */
1321   InitEdgeDict( tess );
1322 
1323   /* __gl_pqSortExtractMin */
1324   while( (v = (GLUvertex *)pqExtractMin( tess->pq )) != NULL ) {
1325     for( ;; ) {
1326       vNext = (GLUvertex *)pqMinimum( tess->pq ); /* __gl_pqSortMinimum */
1327       if( vNext == NULL || ! VertEq( vNext, v )) break;
1328 
1329       /* Merge together all vertices at exactly the same location.
1330        * This is more efficient than processing them one at a time,
1331        * simplifies the code (see ConnectLeftDegenerate), and is also
1332        * important for correct handling of certain degenerate cases.
1333        * For example, suppose there are two identical edges A and B
1334        * that belong to different contours (so without this code they would
1335        * be processed by separate sweep events).  Suppose another edge C
1336        * crosses A and B from above.  When A is processed, we split it
1337        * at its intersection point with C.  However this also splits C,
1338        * so when we insert B we may compute a slightly different
1339        * intersection point.  This might leave two edges with a small
1340        * gap between them.  This kind of error is especially obvious
1341        * when using boundary extraction (GLU_TESS_BOUNDARY_ONLY).
1342        */
1343       vNext = (GLUvertex *)pqExtractMin( tess->pq ); /* __gl_pqSortExtractMin*/
1344       SpliceMergeVertices( tess, v->anEdge, vNext->anEdge );
1345     }
1346     SweepEvent( tess, v );
1347   }
1348 
1349   /* Set tess->event for debugging purposes */
1350   /* __GL_DICTLISTKEY */ /* __GL_DICTLISTMIN */
1351   tess->event = ((ActiveRegion *) dictKey( dictMin( tess->dict )))->eUp->Org;
1352   DebugEvent( tess );
1353   DoneEdgeDict( tess );
1354   DonePriorityQ( tess );
1355 
1356   if ( !RemoveDegenerateFaces( tess->mesh ) ) return 0;
1357   __gl_meshCheckMesh( tess->mesh );
1358 
1359   return 1;
1360 }
1361