1 #define ANSI_DECLARATORS
\r
2 /*****************************************************************************/
\r
4 /* 888888888 ,o, / 888 */
\r
5 /* 888 88o88o " o8888o 88o8888o o88888o 888 o88888o */
\r
6 /* 888 888 888 88b 888 888 888 888 888 d888 88b */
\r
7 /* 888 888 888 o88^o888 888 888 "88888" 888 8888oo888 */
\r
8 /* 888 888 888 C888 888 888 888 / 888 q888 */
\r
9 /* 888 888 888 "88o^888 888 888 Cb 888 "88oooo" */
\r
12 /* A Two-Dimensional Quality Mesh Generator and Delaunay Triangulator. */
\r
18 /* Copyright 1996 */
\r
19 /* Jonathan Richard Shewchuk */
\r
20 /* School of Computer Science */
\r
21 /* Carnegie Mellon University */
\r
22 /* 5000 Forbes Avenue */
\r
23 /* Pittsburgh, Pennsylvania 15213-3891 */
\r
24 /* jrs@cs.cmu.edu */
\r
26 /* This program may be freely redistributed under the condition that the */
\r
27 /* copyright notices (including this entire header and the copyright */
\r
28 /* notice printed when the `-h' switch is selected) are not removed, and */
\r
29 /* no compensation is received. Private, research, and institutional */
\r
30 /* use is free. You may distribute modified versions of this code UNDER */
\r
31 /* THE CONDITION THAT THIS CODE AND ANY MODIFICATIONS MADE TO IT IN THE */
\r
32 /* SAME FILE REMAIN UNDER COPYRIGHT OF THE ORIGINAL AUTHOR, BOTH SOURCE */
\r
33 /* AND OBJECT CODE ARE MADE FREELY AVAILABLE WITHOUT CHARGE, AND CLEAR */
\r
34 /* NOTICE IS GIVEN OF THE MODIFICATIONS. Distribution of this code as */
\r
35 /* part of a commercial system is permissible ONLY BY DIRECT ARRANGEMENT */
\r
36 /* WITH THE AUTHOR. (If you are not directly supplying this code to a */
\r
37 /* customer, and you are instead telling them how they can obtain it for */
\r
38 /* free, then you are not required to make any arrangement with me.) */
\r
40 /* Hypertext instructions for Triangle are available on the Web at */
\r
42 /* http://www.cs.cmu.edu/~quake/triangle.html */
\r
44 /* Some of the references listed below are marked [*]. These are available */
\r
45 /* for downloading from the Web page */
\r
47 /* http://www.cs.cmu.edu/~quake/triangle.research.html */
\r
49 /* A paper discussing some aspects of Triangle is available. See Jonathan */
\r
50 /* Richard Shewchuk, "Triangle: Engineering a 2D Quality Mesh Generator */
\r
51 /* and Delaunay Triangulator," First Workshop on Applied Computational */
\r
52 /* Geometry, ACM, May 1996. [*] */
\r
54 /* Triangle was created as part of the Archimedes project in the School of */
\r
55 /* Computer Science at Carnegie Mellon University. Archimedes is a */
\r
56 /* system for compiling parallel finite element solvers. For further */
\r
57 /* information, see Anja Feldmann, Omar Ghattas, John R. Gilbert, Gary L. */
\r
58 /* Miller, David R. O'Hallaron, Eric J. Schwabe, Jonathan R. Shewchuk, */
\r
59 /* and Shang-Hua Teng, "Automated Parallel Solution of Unstructured PDE */
\r
60 /* Problems." To appear in Communications of the ACM, we hope. */
\r
62 /* The quality mesh generation algorithm is due to Jim Ruppert, "A */
\r
63 /* Delaunay Refinement Algorithm for Quality 2-Dimensional Mesh */
\r
64 /* Generation," Journal of Algorithms 18(3):548-585, May 1995. [*] */
\r
66 /* My implementation of the divide-and-conquer and incremental Delaunay */
\r
67 /* triangulation algorithms follows closely the presentation of Guibas */
\r
68 /* and Stolfi, even though I use a triangle-based data structure instead */
\r
69 /* of their quad-edge data structure. (In fact, I originally implemented */
\r
70 /* Triangle using the quad-edge data structure, but switching to a */
\r
71 /* triangle-based data structure sped Triangle by a factor of two.) The */
\r
72 /* mesh manipulation primitives and the two aforementioned Delaunay */
\r
73 /* triangulation algorithms are described by Leonidas J. Guibas and Jorge */
\r
74 /* Stolfi, "Primitives for the Manipulation of General Subdivisions and */
\r
75 /* the Computation of Voronoi Diagrams," ACM Transactions on Graphics */
\r
76 /* 4(2):74-123, April 1985. */
\r
78 /* Their O(n log n) divide-and-conquer algorithm is adapted from Der-Tsai */
\r
79 /* Lee and Bruce J. Schachter, "Two Algorithms for Constructing the */
\r
80 /* Delaunay Triangulation," International Journal of Computer and */
\r
81 /* Information Science 9(3):219-242, 1980. The idea to improve the */
\r
82 /* divide-and-conquer algorithm by alternating between vertical and */
\r
83 /* horizontal cuts was introduced by Rex A. Dwyer, "A Faster Divide-and- */
\r
84 /* Conquer Algorithm for Constructing Delaunay Triangulations," */
\r
85 /* Algorithmica 2(2):137-151, 1987. */
\r
87 /* The incremental insertion algorithm was first proposed by C. L. Lawson, */
\r
88 /* "Software for C1 Surface Interpolation," in Mathematical Software III, */
\r
89 /* John R. Rice, editor, Academic Press, New York, pp. 161-194, 1977. */
\r
90 /* For point location, I use the algorithm of Ernst P. Mucke, Isaac */
\r
91 /* Saias, and Binhai Zhu, "Fast Randomized Point Location Without */
\r
92 /* Preprocessing in Two- and Three-dimensional Delaunay Triangulations," */
\r
93 /* Proceedings of the Twelfth Annual Symposium on Computational Geometry, */
\r
94 /* ACM, May 1996. [*] If I were to randomize the order of point */
\r
95 /* insertion (I currently don't bother), their result combined with the */
\r
96 /* result of Leonidas J. Guibas, Donald E. Knuth, and Micha Sharir, */
\r
97 /* "Randomized Incremental Construction of Delaunay and Voronoi */
\r
98 /* Diagrams," Algorithmica 7(4):381-413, 1992, would yield an expected */
\r
99 /* O(n^{4/3}) bound on running time. */
\r
101 /* The O(n log n) sweepline Delaunay triangulation algorithm is taken from */
\r
102 /* Steven Fortune, "A Sweepline Algorithm for Voronoi Diagrams", */
\r
103 /* Algorithmica 2(2):153-174, 1987. A random sample of edges on the */
\r
104 /* boundary of the triangulation are maintained in a splay tree for the */
\r
105 /* purpose of point location. Splay trees are described by Daniel */
\r
106 /* Dominic Sleator and Robert Endre Tarjan, "Self-Adjusting Binary Search */
\r
107 /* Trees," Journal of the ACM 32(3):652-686, July 1985. */
\r
109 /* The algorithms for exact computation of the signs of determinants are */
\r
110 /* described in Jonathan Richard Shewchuk, "Adaptive Precision Floating- */
\r
111 /* Point Arithmetic and Fast Robust Geometric Predicates," Technical */
\r
112 /* Report CMU-CS-96-140, School of Computer Science, Carnegie Mellon */
\r
113 /* University, Pittsburgh, Pennsylvania, May 1996. [*] (Submitted to */
\r
114 /* Discrete & Computational Geometry.) An abbreviated version appears as */
\r
115 /* Jonathan Richard Shewchuk, "Robust Adaptive Floating-Point Geometric */
\r
116 /* Predicates," Proceedings of the Twelfth Annual Symposium on Computa- */
\r
117 /* tional Geometry, ACM, May 1996. [*] Many of the ideas for my exact */
\r
118 /* arithmetic routines originate with Douglas M. Priest, "Algorithms for */
\r
119 /* Arbitrary Precision Floating Point Arithmetic," Tenth Symposium on */
\r
120 /* Computer Arithmetic, 132-143, IEEE Computer Society Press, 1991. [*] */
\r
121 /* Many of the ideas for the correct evaluation of the signs of */
\r
122 /* determinants are taken from Steven Fortune and Christopher J. Van Wyk, */
\r
123 /* "Efficient Exact Arithmetic for Computational Geometry," Proceedings */
\r
124 /* of the Ninth Annual Symposium on Computational Geometry, ACM, */
\r
125 /* pp. 163-172, May 1993, and from Steven Fortune, "Numerical Stability */
\r
126 /* of Algorithms for 2D Delaunay Triangulations," International Journal */
\r
127 /* of Computational Geometry & Applications 5(1-2):193-213, March-June */
\r
130 /* For definitions of and results involving Delaunay triangulations, */
\r
131 /* constrained and conforming versions thereof, and other aspects of */
\r
132 /* triangular mesh generation, see the excellent survey by Marshall Bern */
\r
133 /* and David Eppstein, "Mesh Generation and Optimal Triangulation," in */
\r
134 /* Computing and Euclidean Geometry, Ding-Zhu Du and Frank Hwang, */
\r
135 /* editors, World Scientific, Singapore, pp. 23-90, 1992. */
\r
137 /* The time for incrementally adding PSLG (planar straight line graph) */
\r
138 /* segments to create a constrained Delaunay triangulation is probably */
\r
139 /* O(n^2) per segment in the worst case and O(n) per edge in the common */
\r
140 /* case, where n is the number of triangles that intersect the segment */
\r
141 /* before it is inserted. This doesn't count point location, which can */
\r
142 /* be much more expensive. (This note does not apply to conforming */
\r
143 /* Delaunay triangulations, for which a different method is used to */
\r
144 /* insert segments.) */
\r
146 /* The time for adding segments to a conforming Delaunay triangulation is */
\r
147 /* not clear, but does not depend upon n alone. In some cases, very */
\r
148 /* small features (like a point lying next to a segment) can cause a */
\r
149 /* single segment to be split an arbitrary number of times. Of course, */
\r
150 /* floating-point precision is a practical barrier to how much this can */
\r
153 /* The time for deleting a point from a Delaunay triangulation is O(n^2) in */
\r
154 /* the worst case and O(n) in the common case, where n is the degree of */
\r
155 /* the point being deleted. I could improve this to expected O(n) time */
\r
156 /* by "inserting" the neighboring vertices in random order, but n is */
\r
157 /* usually quite small, so it's not worth the bother. (The O(n) time */
\r
158 /* for random insertion follows from L. Paul Chew, "Building Voronoi */
\r
159 /* Diagrams for Convex Polygons in Linear Expected Time," Technical */
\r
160 /* Report PCS-TR90-147, Department of Mathematics and Computer Science, */
\r
161 /* Dartmouth College, 1990. */
\r
163 /* Ruppert's Delaunay refinement algorithm typically generates triangles */
\r
164 /* at a linear rate (constant time per triangle) after the initial */
\r
165 /* triangulation is formed. There may be pathological cases where more */
\r
166 /* time is required, but these never arise in practice. */
\r
168 /* The segment intersection formulae are straightforward. If you want to */
\r
169 /* see them derived, see Franklin Antonio. "Faster Line Segment */
\r
170 /* Intersection." In Graphics Gems III (David Kirk, editor), pp. 199- */
\r
171 /* 202. Academic Press, Boston, 1992. */
\r
173 /* If you make any improvements to this code, please please please let me */
\r
174 /* know, so that I may obtain the improvements. Even if you don't change */
\r
175 /* the code, I'd still love to hear what it's being used for. */
\r
177 /* Disclaimer: Neither I nor Carnegie Mellon warrant this code in any way */
\r
178 /* whatsoever. This code is provided "as-is". Use at your own risk. */
\r
180 /*****************************************************************************/
\r
182 /* For single precision (which will save some memory and reduce paging), */
\r
183 /* define the symbol SINGLE by using the -DSINGLE compiler switch or by */
\r
184 /* writing "#define SINGLE" below. */
\r
186 /* For double precision (which will allow you to refine meshes to a smaller */
\r
187 /* edge length), leave SINGLE undefined. */
\r
189 /* Double precision uses more memory, but improves the resolution of the */
\r
190 /* meshes you can generate with Triangle. It also reduces the likelihood */
\r
191 /* of a floating exception due to overflow. Finally, it is much faster */
\r
192 /* than single precision on 64-bit architectures like the DEC Alpha. I */
\r
193 /* recommend double precision unless you want to generate a mesh for which */
\r
194 /* you do not have enough memory. */
\r
200 #else /* not SINGLE */
\r
201 #define REAL double
\r
202 #endif /* not SINGLE */
\r
204 /* If yours is not a Unix system, define the NO_TIMER compiler switch to */
\r
205 /* remove the Unix-specific timing code. */
\r
209 /* To insert lots of self-checks for internal errors, define the SELF_CHECK */
\r
210 /* symbol. This will slow down the program significantly. It is best to */
\r
211 /* define the symbol using the -DSELF_CHECK compiler switch, but you could */
\r
212 /* write "#define SELF_CHECK" below. If you are modifying this code, I */
\r
213 /* recommend you turn self-checks on. */
\r
215 /* #define SELF_CHECK */
\r
217 /* To compile Triangle as a callable object library (triangle.o), define the */
\r
218 /* TRILIBRARY symbol. Read the file triangle.h for details on how to call */
\r
219 /* the procedure triangulate() that results. */
\r
223 /* It is possible to generate a smaller version of Triangle using one or */
\r
224 /* both of the following symbols. Define the REDUCED symbol to eliminate */
\r
225 /* all features that are primarily of research interest; specifically, the */
\r
226 /* -i, -F, -s, and -C switches. Define the CDT_ONLY symbol to eliminate */
\r
227 /* all meshing algorithms above and beyond constrained Delaunay */
\r
228 /* triangulation; specifically, the -r, -q, -a, -S, and -s switches. */
\r
229 /* These reductions are most likely to be useful when generating an object */
\r
230 /* library (triangle.o) by defining the TRILIBRARY symbol. */
\r
235 /* On some machines, the exact arithmetic routines might be defeated by the */
\r
236 /* use of internal extended precision floating-point registers. Sometimes */
\r
237 /* this problem can be fixed by defining certain values to be volatile, */
\r
238 /* thus forcing them to be stored to memory and rounded off. This isn't */
\r
239 /* a great solution, though, as it slows Triangle down. */
\r
241 /* To try this out, write "#define INEXACT volatile" below. Normally, */
\r
242 /* however, INEXACT should be defined to be nothing. ("#define INEXACT".) */
\r
244 #define INEXACT /* Nothing */
\r
245 /* #define INEXACT volatile */
\r
247 /* Maximum number of characters in a file name (including the null). */
\r
249 #define FILENAMESIZE 512
\r
251 /* Maximum number of characters in a line read from a file (including the */
\r
254 #define INPUTLINESIZE 512
\r
256 /* For efficiency, a variety of data structures are allocated in bulk. The */
\r
257 /* following constants determine how many of each structure is allocated */
\r
260 #define TRIPERBLOCK 4092 /* Number of triangles allocated at once. */
\r
261 #define SHELLEPERBLOCK 508 /* Number of shell edges allocated at once. */
\r
262 #define POINTPERBLOCK 4092 /* Number of points allocated at once. */
\r
263 #define VIRUSPERBLOCK 1020 /* Number of virus triangles allocated at once. */
\r
264 /* Number of encroached segments allocated at once. */
\r
265 #define BADSEGMENTPERBLOCK 252
\r
266 /* Number of skinny triangles allocated at once. */
\r
267 #define BADTRIPERBLOCK 4092
\r
268 /* Number of splay tree nodes allocated at once. */
\r
269 #define SPLAYNODEPERBLOCK 508
\r
271 /* The point marker DEADPOINT is an arbitrary number chosen large enough to */
\r
272 /* (hopefully) not conflict with user boundary markers. Make sure that it */
\r
273 /* is small enough to fit into your machine's integer size. */
\r
275 #define DEADPOINT -1073741824
\r
277 /* The next line is used to outsmart some very stupid compilers. If your */
\r
278 /* compiler is smarter, feel free to replace the "int" with "void". */
\r
279 /* Not that it matters. */
\r
283 /* Two constants for algorithms based on random sampling. Both constants */
\r
284 /* have been chosen empirically to optimize their respective algorithms. */
\r
286 /* Used for the point location scheme of Mucke, Saias, and Zhu, to decide */
\r
287 /* how large a random sample of triangles to inspect. */
\r
288 #define SAMPLEFACTOR 11
\r
289 /* Used in Fortune's sweepline Delaunay algorithm to determine what fraction */
\r
290 /* of boundary edges should be maintained in the splay tree for point */
\r
291 /* location on the front. */
\r
292 #define SAMPLERATE 10
\r
294 /* A number that speaks for itself, every kissable digit. */
\r
296 #define PI 3.141592653589793238462643383279502884197169399375105820974944592308
\r
298 /* Another fave. */
\r
300 #define SQUAREROOTTWO 1.4142135623730950488016887242096980785696718753769480732
\r
302 /* And here's one for those of you who are intimidated by math. */
\r
304 #define ONETHIRD 0.333333333333333333333333333333333333333333333333333333333333
\r
307 #include <string.h>
\r
310 #include <sys/time.h>
\r
311 #endif /* NO_TIMER */
\r
313 #include "triangle.h"
\r
314 #endif /* TRILIBRARY */
\r
316 /* The following obscenity seems to be necessary to ensure that this program */
\r
317 /* will port to Dec Alphas running OSF/1, because their stdio.h file commits */
\r
318 /* the unpardonable sin of including stdlib.h. Hence, malloc(), free(), and */
\r
319 /* exit() may or may not already be defined at this point. I declare these */
\r
320 /* functions explicitly because some non-ANSI C compilers lack stdlib.h. */
\r
323 extern void *malloc();
\r
324 extern void free();
\r
325 extern void exit();
\r
326 extern double strtod();
\r
327 extern long strtol();
\r
328 #endif /* _STDLIB_H_ */
\r
330 /* A few forward declarations. */
\r
332 void poolrestart();
\r
336 #endif /* not TRILIBRARY */
\r
338 /* Labels that signify whether a record consists primarily of pointers or of */
\r
339 /* floating-point words. Used to make decisions about data alignment. */
\r
341 enum wordtype {POINTER, FLOATINGPOINT};
\r
343 /* Labels that signify the result of point location. The result of a */
\r
344 /* search indicates that the point falls in the interior of a triangle, on */
\r
345 /* an edge, on a vertex, or outside the mesh. */
\r
347 enum locateresult {INTRIANGLE, ONEDGE, ONVERTEX, OUTSIDE};
\r
349 /* Labels that signify the result of site insertion. The result indicates */
\r
350 /* that the point was inserted with complete success, was inserted but */
\r
351 /* encroaches on a segment, was not inserted because it lies on a segment, */
\r
352 /* or was not inserted because another point occupies the same location. */
\r
354 enum insertsiteresult {SUCCESSFULPOINT, ENCROACHINGPOINT, VIOLATINGPOINT,
\r
357 /* Labels that signify the result of direction finding. The result */
\r
358 /* indicates that a segment connecting the two query points falls within */
\r
359 /* the direction triangle, along the left edge of the direction triangle, */
\r
360 /* or along the right edge of the direction triangle. */
\r
362 enum finddirectionresult {WITHIN, LEFTCOLLINEAR, RIGHTCOLLINEAR};
\r
364 /* Labels that signify the result of the circumcenter computation routine. */
\r
365 /* The return value indicates which edge of the triangle is shortest. */
\r
367 enum circumcenterresult {OPPOSITEORG, OPPOSITEDEST, OPPOSITEAPEX};
\r
369 /*****************************************************************************/
\r
371 /* The basic mesh data structures */
\r
373 /* There are three: points, triangles, and shell edges (abbreviated */
\r
374 /* `shelle'). These three data structures, linked by pointers, comprise */
\r
375 /* the mesh. A point simply represents a point in space and its properties.*/
\r
376 /* A triangle is a triangle. A shell edge is a special data structure used */
\r
377 /* to represent impenetrable segments in the mesh (including the outer */
\r
378 /* boundary, boundaries of holes, and internal boundaries separating two */
\r
379 /* triangulated regions). Shell edges represent boundaries defined by the */
\r
380 /* user that triangles may not lie across. */
\r
382 /* A triangle consists of a list of three vertices, a list of three */
\r
383 /* adjoining triangles, a list of three adjoining shell edges (when shell */
\r
384 /* edges are used), an arbitrary number of optional user-defined floating- */
\r
385 /* point attributes, and an optional area constraint. The latter is an */
\r
386 /* upper bound on the permissible area of each triangle in a region, used */
\r
387 /* for mesh refinement. */
\r
389 /* For a triangle on a boundary of the mesh, some or all of the neighboring */
\r
390 /* triangles may not be present. For a triangle in the interior of the */
\r
391 /* mesh, often no neighboring shell edges are present. Such absent */
\r
392 /* triangles and shell edges are never represented by NULL pointers; they */
\r
393 /* are represented by two special records: `dummytri', the triangle that */
\r
394 /* fills "outer space", and `dummysh', the omnipresent shell edge. */
\r
395 /* `dummytri' and `dummysh' are used for several reasons; for instance, */
\r
396 /* they can be dereferenced and their contents examined without causing the */
\r
397 /* memory protection exception that would occur if NULL were dereferenced. */
\r
399 /* However, it is important to understand that a triangle includes other */
\r
400 /* information as well. The pointers to adjoining vertices, triangles, and */
\r
401 /* shell edges are ordered in a way that indicates their geometric relation */
\r
402 /* to each other. Furthermore, each of these pointers contains orientation */
\r
403 /* information. Each pointer to an adjoining triangle indicates which face */
\r
404 /* of that triangle is contacted. Similarly, each pointer to an adjoining */
\r
405 /* shell edge indicates which side of that shell edge is contacted, and how */
\r
406 /* the shell edge is oriented relative to the triangle. */
\r
408 /* Shell edges are found abutting edges of triangles; either sandwiched */
\r
409 /* between two triangles, or resting against one triangle on an exterior */
\r
410 /* boundary or hole boundary. */
\r
412 /* A shell edge consists of a list of two vertices, a list of two */
\r
413 /* adjoining shell edges, and a list of two adjoining triangles. One of */
\r
414 /* the two adjoining triangles may not be present (though there should */
\r
415 /* always be one), and neighboring shell edges might not be present. */
\r
416 /* Shell edges also store a user-defined integer "boundary marker". */
\r
417 /* Typically, this integer is used to indicate what sort of boundary */
\r
418 /* conditions are to be applied at that location in a finite element */
\r
421 /* Like triangles, shell edges maintain information about the relative */
\r
422 /* orientation of neighboring objects. */
\r
424 /* Points are relatively simple. A point is a list of floating point */
\r
425 /* numbers, starting with the x, and y coordinates, followed by an */
\r
426 /* arbitrary number of optional user-defined floating-point attributes, */
\r
427 /* followed by an integer boundary marker. During the segment insertion */
\r
428 /* phase, there is also a pointer from each point to a triangle that may */
\r
429 /* contain it. Each pointer is not always correct, but when one is, it */
\r
430 /* speeds up segment insertion. These pointers are assigned values once */
\r
431 /* at the beginning of the segment insertion phase, and are not used or */
\r
432 /* updated at any other time. Edge swapping during segment insertion will */
\r
433 /* render some of them incorrect. Hence, don't rely upon them for */
\r
434 /* anything. For the most part, points do not have any information about */
\r
435 /* what triangles or shell edges they are linked to. */
\r
437 /*****************************************************************************/
\r
439 /*****************************************************************************/
\r
443 /* The oriented triangle (`triedge') and oriented shell edge (`edge') data */
\r
444 /* structures defined below do not themselves store any part of the mesh. */
\r
445 /* The mesh itself is made of `triangle's, `shelle's, and `point's. */
\r
447 /* Oriented triangles and oriented shell edges will usually be referred to */
\r
448 /* as "handles". A handle is essentially a pointer into the mesh; it */
\r
449 /* allows you to "hold" one particular part of the mesh. Handles are used */
\r
450 /* to specify the regions in which one is traversing and modifying the mesh.*/
\r
451 /* A single `triangle' may be held by many handles, or none at all. (The */
\r
452 /* latter case is not a memory leak, because the triangle is still */
\r
453 /* connected to other triangles in the mesh.) */
\r
455 /* A `triedge' is a handle that holds a triangle. It holds a specific side */
\r
456 /* of the triangle. An `edge' is a handle that holds a shell edge. It */
\r
457 /* holds either the left or right side of the edge. */
\r
459 /* Navigation about the mesh is accomplished through a set of mesh */
\r
460 /* manipulation primitives, further below. Many of these primitives take */
\r
461 /* a handle and produce a new handle that holds the mesh near the first */
\r
462 /* handle. Other primitives take two handles and glue the corresponding */
\r
463 /* parts of the mesh together. The exact position of the handles is */
\r
464 /* important. For instance, when two triangles are glued together by the */
\r
465 /* bond() primitive, they are glued by the sides on which the handles lie. */
\r
467 /* Because points have no information about which triangles they are */
\r
468 /* attached to, I commonly represent a point by use of a handle whose */
\r
469 /* origin is the point. A single handle can simultaneously represent a */
\r
470 /* triangle, an edge, and a point. */
\r
472 /*****************************************************************************/
\r
474 /* The triangle data structure. Each triangle contains three pointers to */
\r
475 /* adjoining triangles, plus three pointers to vertex points, plus three */
\r
476 /* pointers to shell edges (defined below; these pointers are usually */
\r
477 /* `dummysh'). It may or may not also contain user-defined attributes */
\r
478 /* and/or a floating-point "area constraint". It may also contain extra */
\r
479 /* pointers for nodes, when the user asks for high-order elements. */
\r
480 /* Because the size and structure of a `triangle' is not decided until */
\r
481 /* runtime, I haven't simply defined the type `triangle' to be a struct. */
\r
483 typedef REAL **triangle; /* Really: typedef triangle *triangle */
\r
485 /* An oriented triangle: includes a pointer to a triangle and orientation. */
\r
486 /* The orientation denotes an edge of the triangle. Hence, there are */
\r
487 /* three possible orientations. By convention, each edge is always */
\r
488 /* directed to point counterclockwise about the corresponding triangle. */
\r
492 int orient; /* Ranges from 0 to 2. */
\r
495 /* The shell data structure. Each shell edge contains two pointers to */
\r
496 /* adjoining shell edges, plus two pointers to vertex points, plus two */
\r
497 /* pointers to adjoining triangles, plus one shell marker. */
\r
499 typedef REAL **shelle; /* Really: typedef shelle *shelle */
\r
501 /* An oriented shell edge: includes a pointer to a shell edge and an */
\r
502 /* orientation. The orientation denotes a side of the edge. Hence, there */
\r
503 /* are two possible orientations. By convention, the edge is always */
\r
504 /* directed so that the "side" denoted is the right side of the edge. */
\r
508 int shorient; /* Ranges from 0 to 1. */
\r
511 /* The point data structure. Each point is actually an array of REALs. */
\r
512 /* The number of REALs is unknown until runtime. An integer boundary */
\r
513 /* marker, and sometimes a pointer to a triangle, is appended after the */
\r
516 typedef REAL *point;
\r
518 /* A queue used to store encroached segments. Each segment's vertices are */
\r
519 /* stored so that one can check whether a segment is still the same. */
\r
521 struct badsegment {
\r
522 struct edge encsegment; /* An encroached segment. */
\r
523 point segorg, segdest; /* The two vertices. */
\r
524 struct badsegment *nextsegment; /* Pointer to next encroached segment. */
\r
527 /* A queue used to store bad triangles. The key is the square of the cosine */
\r
528 /* of the smallest angle of the triangle. Each triangle's vertices are */
\r
529 /* stored so that one can check whether a triangle is still the same. */
\r
532 struct triedge badfacetri; /* A bad triangle. */
\r
533 REAL key; /* cos^2 of smallest (apical) angle. */
\r
534 point faceorg, facedest, faceapex; /* The three vertices. */
\r
535 struct badface *nextface; /* Pointer to next bad triangle. */
\r
538 /* A node in a heap used to store events for the sweepline Delaunay */
\r
539 /* algorithm. Nodes do not point directly to their parents or children in */
\r
540 /* the heap. Instead, each node knows its position in the heap, and can */
\r
541 /* look up its parent and children in a separate array. The `eventptr' */
\r
542 /* points either to a `point' or to a triangle (in encoded format, so that */
\r
543 /* an orientation is included). In the latter case, the origin of the */
\r
544 /* oriented triangle is the apex of a "circle event" of the sweepline */
\r
545 /* algorithm. To distinguish site events from circle events, all circle */
\r
546 /* events are given an invalid (smaller than `xmin') x-coordinate `xkey'. */
\r
549 REAL xkey, ykey; /* Coordinates of the event. */
\r
550 VOID *eventptr; /* Can be a point or the location of a circle event. */
\r
551 int heapposition; /* Marks this event's position in the heap. */
\r
554 /* A node in the splay tree. Each node holds an oriented ghost triangle */
\r
555 /* that represents a boundary edge of the growing triangulation. When a */
\r
556 /* circle event covers two boundary edges with a triangle, so that they */
\r
557 /* are no longer boundary edges, those edges are not immediately deleted */
\r
558 /* from the tree; rather, they are lazily deleted when they are next */
\r
559 /* encountered. (Since only a random sample of boundary edges are kept */
\r
560 /* in the tree, lazy deletion is faster.) `keydest' is used to verify */
\r
561 /* that a triangle is still the same as when it entered the splay tree; if */
\r
562 /* it has been rotated (due to a circle event), it no longer represents a */
\r
563 /* boundary edge and should be deleted. */
\r
566 struct triedge keyedge; /* Lprev of an edge on the front. */
\r
567 point keydest; /* Used to verify that splay node is still live. */
\r
568 struct splaynode *lchild, *rchild; /* Children in splay tree. */
\r
571 /* A type used to allocate memory. firstblock is the first block of items. */
\r
572 /* nowblock is the block from which items are currently being allocated. */
\r
573 /* nextitem points to the next slab of free memory for an item. */
\r
574 /* deaditemstack is the head of a linked list (stack) of deallocated items */
\r
575 /* that can be recycled. unallocateditems is the number of items that */
\r
576 /* remain to be allocated from nowblock. */
\r
578 /* Traversal is the process of walking through the entire list of items, and */
\r
579 /* is separate from allocation. Note that a traversal will visit items on */
\r
580 /* the "deaditemstack" stack as well as live items. pathblock points to */
\r
581 /* the block currently being traversed. pathitem points to the next item */
\r
582 /* to be traversed. pathitemsleft is the number of items that remain to */
\r
583 /* be traversed in pathblock. */
\r
585 /* itemwordtype is set to POINTER or FLOATINGPOINT, and is used to suggest */
\r
586 /* what sort of word the record is primarily made up of. alignbytes */
\r
587 /* determines how new records should be aligned in memory. itembytes and */
\r
588 /* itemwords are the length of a record in bytes (after rounding up) and */
\r
589 /* words. itemsperblock is the number of items allocated at once in a */
\r
590 /* single block. items is the number of currently allocated items. */
\r
591 /* maxitems is the maximum number of items that have been allocated at */
\r
592 /* once; it is the current number of items plus the number of records kept */
\r
593 /* on deaditemstack. */
\r
595 struct memorypool {
\r
596 VOID **firstblock, **nowblock;
\r
598 VOID *deaditemstack;
\r
601 enum wordtype itemwordtype;
\r
603 int itembytes, itemwords;
\r
605 long items, maxitems;
\r
606 int unallocateditems;
\r
610 /* Variables used to allocate memory for triangles, shell edges, points, */
\r
611 /* viri (triangles being eaten), bad (encroached) segments, bad (skinny */
\r
612 /* or too large) triangles, and splay tree nodes. */
\r
614 static struct memorypool triangles;
\r
615 static struct memorypool shelles;
\r
616 static struct memorypool points;
\r
617 static struct memorypool viri;
\r
618 static struct memorypool badsegments;
\r
619 static struct memorypool badtriangles;
\r
620 static struct memorypool splaynodes;
\r
622 /* Variables that maintain the bad triangle queues. The tails are pointers */
\r
623 /* to the pointers that have to be filled in to enqueue an item. */
\r
625 static struct badface *queuefront[64];
\r
626 static struct badface **queuetail[64];
\r
628 static REAL xmin, xmax, ymin, ymax; /* x and y bounds. */
\r
629 static REAL xminextreme; /* Nonexistent x value used as a flag in sweepline. */
\r
630 static int inpoints; /* Number of input points. */
\r
631 static int inelements; /* Number of input triangles. */
\r
632 static int insegments; /* Number of input segments. */
\r
633 static int holes; /* Number of input holes. */
\r
634 static int regions; /* Number of input regions. */
\r
635 static long edges; /* Number of output edges. */
\r
636 static int mesh_dim; /* Dimension (ought to be 2). */
\r
637 static int nextras; /* Number of attributes per point. */
\r
638 static int eextras; /* Number of attributes per triangle. */
\r
639 static long hullsize; /* Number of edges of convex hull. */
\r
640 static int triwords; /* Total words per triangle. */
\r
641 static int shwords; /* Total words per shell edge. */
\r
642 static int pointmarkindex; /* Index to find boundary marker of a point. */
\r
643 static int point2triindex; /* Index to find a triangle adjacent to a point. */
\r
644 static int highorderindex; /* Index to find extra nodes for high-order elements. */
\r
645 static int elemattribindex; /* Index to find attributes of a triangle. */
\r
646 static int areaboundindex; /* Index to find area bound of a triangle. */
\r
647 static int checksegments; /* Are there segments in the triangulation yet? */
\r
648 static int readnodefile; /* Has a .node file been read? */
\r
649 static long samples; /* Number of random samples for point location. */
\r
650 static unsigned long randomseed; /* Current random number seed. */
\r
652 static REAL splitter; /* Used to split REAL factors for exact multiplication. */
\r
653 static REAL epsilon; /* Floating-point machine epsilon. */
\r
654 static REAL resulterrbound;
\r
655 static REAL ccwerrboundA, ccwerrboundB, ccwerrboundC;
\r
656 static REAL iccerrboundA, iccerrboundB, iccerrboundC;
\r
658 static long incirclecount; /* Number of incircle tests performed. */
\r
659 static long counterclockcount; /* Number of counterclockwise tests performed. */
\r
660 static long hyperbolacount; /* Number of right-of-hyperbola tests performed. */
\r
661 static long circumcentercount; /* Number of circumcenter calculations performed. */
\r
662 static long circletopcount; /* Number of circle top calculations performed. */
\r
664 /* Switches for the triangulator. */
\r
665 /* poly: -p switch. refine: -r switch. */
\r
666 /* quality: -q switch. */
\r
667 /* minangle: minimum angle bound, specified after -q switch. */
\r
668 /* goodangle: cosine squared of minangle. */
\r
669 /* vararea: -a switch without number. */
\r
670 /* fixedarea: -a switch with number. */
\r
671 /* maxarea: maximum area bound, specified after -a switch. */
\r
672 /* regionattrib: -A switch. convex: -c switch. */
\r
673 /* firstnumber: inverse of -z switch. All items are numbered starting */
\r
674 /* from firstnumber. */
\r
675 /* edgesout: -e switch. voronoi: -v switch. */
\r
676 /* neighbors: -n switch. geomview: -g switch. */
\r
677 /* nobound: -B switch. nopolywritten: -P switch. */
\r
678 /* nonodewritten: -N switch. noelewritten: -E switch. */
\r
679 /* noiterationnum: -I switch. noholes: -O switch. */
\r
680 /* noexact: -X switch. */
\r
681 /* order: element order, specified after -o switch. */
\r
682 /* nobisect: count of how often -Y switch is selected. */
\r
683 /* steiner: maximum number of Steiner points, specified after -S switch. */
\r
684 /* steinerleft: number of Steiner points not yet used. */
\r
685 /* incremental: -i switch. sweepline: -F switch. */
\r
686 /* dwyer: inverse of -l switch. */
\r
687 /* splitseg: -s switch. */
\r
688 /* docheck: -C switch. */
\r
689 /* quiet: -Q switch. verbose: count of how often -V switch is selected. */
\r
690 /* useshelles: -p, -r, -q, or -c switch; determines whether shell edges */
\r
691 /* are used at all. */
\r
693 /* Read the instructions to find out the meaning of these switches. */
\r
695 static int poly, refine, quality, vararea, fixedarea, regionattrib, convex;
\r
696 static int firstnumber;
\r
697 static int edgesout, voronoi, neighbors, geomview;
\r
698 static int nobound, nopolywritten, nonodewritten, noelewritten, noiterationnum;
\r
699 static int noholes, noexact;
\r
700 static int incremental, sweepline, dwyer;
\r
701 static int splitseg;
\r
702 static int docheck;
\r
703 static int quiet, verbose;
\r
704 static int useshelles;
\r
706 static int nobisect;
\r
707 static int steiner, steinerleft;
\r
708 static REAL minangle, goodangle;
\r
709 static REAL maxarea;
\r
711 /* Variables for file names. */
\r
714 char innodefilename[FILENAMESIZE];
\r
715 char inelefilename[FILENAMESIZE];
\r
716 char inpolyfilename[FILENAMESIZE];
\r
717 char areafilename[FILENAMESIZE];
\r
718 char outnodefilename[FILENAMESIZE];
\r
719 char outelefilename[FILENAMESIZE];
\r
720 char outpolyfilename[FILENAMESIZE];
\r
721 char edgefilename[FILENAMESIZE];
\r
722 char vnodefilename[FILENAMESIZE];
\r
723 char vedgefilename[FILENAMESIZE];
\r
724 char neighborfilename[FILENAMESIZE];
\r
725 char offfilename[FILENAMESIZE];
\r
726 #endif /* not TRILIBRARY */
\r
728 /* Triangular bounding box points. */
\r
730 static point infpoint1, infpoint2, infpoint3;
\r
732 /* Pointer to the `triangle' that occupies all of "outer space". */
\r
734 static triangle *dummytri;
\r
735 static triangle *dummytribase; /* Keep base address so we can free() it later. */
\r
737 /* Pointer to the omnipresent shell edge. Referenced by any triangle or */
\r
738 /* shell edge that isn't really connected to a shell edge at that */
\r
741 static shelle *dummysh;
\r
742 static shelle *dummyshbase; /* Keep base address so we can free() it later. */
\r
744 /* Pointer to a recently visited triangle. Improves point location if */
\r
745 /* proximate points are inserted sequentially. */
\r
747 static struct triedge recenttri;
\r
749 /*****************************************************************************/
\r
751 /* Mesh manipulation primitives. Each triangle contains three pointers to */
\r
752 /* other triangles, with orientations. Each pointer points not to the */
\r
753 /* first byte of a triangle, but to one of the first three bytes of a */
\r
754 /* triangle. It is necessary to extract both the triangle itself and the */
\r
755 /* orientation. To save memory, I keep both pieces of information in one */
\r
756 /* pointer. To make this possible, I assume that all triangles are aligned */
\r
757 /* to four-byte boundaries. The `decode' routine below decodes a pointer, */
\r
758 /* extracting an orientation (in the range 0 to 2) and a pointer to the */
\r
759 /* beginning of a triangle. The `encode' routine compresses a pointer to a */
\r
760 /* triangle and an orientation into a single pointer. My assumptions that */
\r
761 /* triangles are four-byte-aligned and that the `unsigned long' type is */
\r
762 /* long enough to hold a pointer are two of the few kludges in this program.*/
\r
764 /* Shell edges are manipulated similarly. A pointer to a shell edge */
\r
765 /* carries both an address and an orientation in the range 0 to 1. */
\r
767 /* The other primitives take an oriented triangle or oriented shell edge, */
\r
768 /* and return an oriented triangle or oriented shell edge or point; or they */
\r
769 /* change the connections in the data structure. */
\r
771 /*****************************************************************************/
\r
773 /********* Mesh manipulation primitives begin here *********/
\r
777 /* Fast lookup arrays to speed some of the mesh manipulation primitives. */
\r
779 int plus1mod3[3] = {1, 2, 0};
\r
780 int minus1mod3[3] = {2, 0, 1};
\r
782 /********* Primitives for triangles *********/
\r
786 /* decode() converts a pointer to an oriented triangle. The orientation is */
\r
787 /* extracted from the two least significant bits of the pointer. */
\r
789 #define decode(ptr, triedge) \
\r
790 (triedge).orient = (int) ((unsigned long) (ptr) & (unsigned long) 3l); \
\r
791 (triedge).tri = (triangle *) \
\r
792 ((unsigned long) (ptr) ^ (unsigned long) (triedge).orient)
\r
794 /* encode() compresses an oriented triangle into a single pointer. It */
\r
795 /* relies on the assumption that all triangles are aligned to four-byte */
\r
796 /* boundaries, so the two least significant bits of (triedge).tri are zero.*/
\r
798 #define encode(triedge) \
\r
799 (triangle) ((unsigned long) (triedge).tri | (unsigned long) (triedge).orient)
\r
801 /* The following edge manipulation primitives are all described by Guibas */
\r
802 /* and Stolfi. However, they use an edge-based data structure, whereas I */
\r
803 /* am using a triangle-based data structure. */
\r
805 /* sym() finds the abutting triangle, on the same edge. Note that the */
\r
806 /* edge direction is necessarily reversed, because triangle/edge handles */
\r
807 /* are always directed counterclockwise around the triangle. */
\r
809 #define sym(triedge1, triedge2) \
\r
810 ptr = (triedge1).tri[(triedge1).orient]; \
\r
811 decode(ptr, triedge2);
\r
813 #define symself(triedge) \
\r
814 ptr = (triedge).tri[(triedge).orient]; \
\r
815 decode(ptr, triedge);
\r
817 /* lnext() finds the next edge (counterclockwise) of a triangle. */
\r
819 #define lnext(triedge1, triedge2) \
\r
820 (triedge2).tri = (triedge1).tri; \
\r
821 (triedge2).orient = plus1mod3[(triedge1).orient]
\r
823 #define lnextself(triedge) \
\r
824 (triedge).orient = plus1mod3[(triedge).orient]
\r
826 /* lprev() finds the previous edge (clockwise) of a triangle. */
\r
828 #define lprev(triedge1, triedge2) \
\r
829 (triedge2).tri = (triedge1).tri; \
\r
830 (triedge2).orient = minus1mod3[(triedge1).orient]
\r
832 #define lprevself(triedge) \
\r
833 (triedge).orient = minus1mod3[(triedge).orient]
\r
835 /* onext() spins counterclockwise around a point; that is, it finds the next */
\r
836 /* edge with the same origin in the counterclockwise direction. This edge */
\r
837 /* will be part of a different triangle. */
\r
839 #define onext(triedge1, triedge2) \
\r
840 lprev(triedge1, triedge2); \
\r
843 #define onextself(triedge) \
\r
844 lprevself(triedge); \
\r
847 /* oprev() spins clockwise around a point; that is, it finds the next edge */
\r
848 /* with the same origin in the clockwise direction. This edge will be */
\r
849 /* part of a different triangle. */
\r
851 #define oprev(triedge1, triedge2) \
\r
852 sym(triedge1, triedge2); \
\r
853 lnextself(triedge2);
\r
855 #define oprevself(triedge) \
\r
856 symself(triedge); \
\r
857 lnextself(triedge);
\r
859 /* dnext() spins counterclockwise around a point; that is, it finds the next */
\r
860 /* edge with the same destination in the counterclockwise direction. This */
\r
861 /* edge will be part of a different triangle. */
\r
863 #define dnext(triedge1, triedge2) \
\r
864 sym(triedge1, triedge2); \
\r
865 lprevself(triedge2);
\r
867 #define dnextself(triedge) \
\r
868 symself(triedge); \
\r
869 lprevself(triedge);
\r
871 /* dprev() spins clockwise around a point; that is, it finds the next edge */
\r
872 /* with the same destination in the clockwise direction. This edge will */
\r
873 /* be part of a different triangle. */
\r
875 #define dprev(triedge1, triedge2) \
\r
876 lnext(triedge1, triedge2); \
\r
879 #define dprevself(triedge) \
\r
880 lnextself(triedge); \
\r
883 /* rnext() moves one edge counterclockwise about the adjacent triangle. */
\r
884 /* (It's best understood by reading Guibas and Stolfi. It involves */
\r
885 /* changing triangles twice.) */
\r
887 #define rnext(triedge1, triedge2) \
\r
888 sym(triedge1, triedge2); \
\r
889 lnextself(triedge2); \
\r
892 #define rnextself(triedge) \
\r
893 symself(triedge); \
\r
894 lnextself(triedge); \
\r
897 /* rnext() moves one edge clockwise about the adjacent triangle. */
\r
898 /* (It's best understood by reading Guibas and Stolfi. It involves */
\r
899 /* changing triangles twice.) */
\r
901 #define rprev(triedge1, triedge2) \
\r
902 sym(triedge1, triedge2); \
\r
903 lprevself(triedge2); \
\r
906 #define rprevself(triedge) \
\r
907 symself(triedge); \
\r
908 lprevself(triedge); \
\r
911 /* These primitives determine or set the origin, destination, or apex of a */
\r
914 #define org(triedge, pointptr) \
\r
915 pointptr = (point) (triedge).tri[plus1mod3[(triedge).orient] + 3]
\r
917 #define dest(triedge, pointptr) \
\r
918 pointptr = (point) (triedge).tri[minus1mod3[(triedge).orient] + 3]
\r
920 #define apex(triedge, pointptr) \
\r
921 pointptr = (point) (triedge).tri[(triedge).orient + 3]
\r
923 #define setorg(triedge, pointptr) \
\r
924 (triedge).tri[plus1mod3[(triedge).orient] + 3] = (triangle) pointptr
\r
926 #define setdest(triedge, pointptr) \
\r
927 (triedge).tri[minus1mod3[(triedge).orient] + 3] = (triangle) pointptr
\r
929 #define setapex(triedge, pointptr) \
\r
930 (triedge).tri[(triedge).orient + 3] = (triangle) pointptr
\r
932 #define setvertices2null(triedge) \
\r
933 (triedge).tri[3] = (triangle) NULL; \
\r
934 (triedge).tri[4] = (triangle) NULL; \
\r
935 (triedge).tri[5] = (triangle) NULL;
\r
937 /* Bond two triangles together. */
\r
939 #define bond(triedge1, triedge2) \
\r
940 (triedge1).tri[(triedge1).orient] = encode(triedge2); \
\r
941 (triedge2).tri[(triedge2).orient] = encode(triedge1)
\r
943 /* Dissolve a bond (from one side). Note that the other triangle will still */
\r
944 /* think it's connected to this triangle. Usually, however, the other */
\r
945 /* triangle is being deleted entirely, or bonded to another triangle, so */
\r
946 /* it doesn't matter. */
\r
948 #define dissolve(triedge) \
\r
949 (triedge).tri[(triedge).orient] = (triangle) dummytri
\r
951 /* Copy a triangle/edge handle. */
\r
953 #define triedgecopy(triedge1, triedge2) \
\r
954 (triedge2).tri = (triedge1).tri; \
\r
955 (triedge2).orient = (triedge1).orient
\r
957 /* Test for equality of triangle/edge handles. */
\r
959 #define triedgeequal(triedge1, triedge2) \
\r
960 (((triedge1).tri == (triedge2).tri) && \
\r
961 ((triedge1).orient == (triedge2).orient))
\r
963 /* Primitives to infect or cure a triangle with the virus. These rely on */
\r
964 /* the assumption that all shell edges are aligned to four-byte boundaries.*/
\r
966 #define infect(triedge) \
\r
967 (triedge).tri[6] = (triangle) \
\r
968 ((unsigned long) (triedge).tri[6] | (unsigned long) 2l)
\r
970 #define uninfect(triedge) \
\r
971 (triedge).tri[6] = (triangle) \
\r
972 ((unsigned long) (triedge).tri[6] & ~ (unsigned long) 2l)
\r
974 /* Test a triangle for viral infection. */
\r
976 #define infected(triedge) \
\r
977 (((unsigned long) (triedge).tri[6] & (unsigned long) 2l) != 0)
\r
979 /* Check or set a triangle's attributes. */
\r
981 #define elemattribute(triedge, attnum) \
\r
982 ((REAL *) (triedge).tri)[elemattribindex + (attnum)]
\r
984 #define setelemattribute(triedge, attnum, value) \
\r
985 ((REAL *) (triedge).tri)[elemattribindex + (attnum)] = (REAL)value
\r
987 /* Check or set a triangle's maximum area bound. */
\r
989 #define areabound(triedge) ((REAL *) (triedge).tri)[areaboundindex]
\r
991 #define setareabound(triedge, value) \
\r
992 ((REAL *) (triedge).tri)[areaboundindex] = (REAL)value
\r
994 /********* Primitives for shell edges *********/
\r
998 /* sdecode() converts a pointer to an oriented shell edge. The orientation */
\r
999 /* is extracted from the least significant bit of the pointer. The two */
\r
1000 /* least significant bits (one for orientation, one for viral infection) */
\r
1001 /* are masked out to produce the real pointer. */
\r
1003 #define sdecode(sptr, edge) \
\r
1004 (edge).shorient = (int) ((unsigned long) (sptr) & (unsigned long) 1l); \
\r
1005 (edge).sh = (shelle *) \
\r
1006 ((unsigned long) (sptr) & ~ (unsigned long) 3l)
\r
1008 /* sencode() compresses an oriented shell edge into a single pointer. It */
\r
1009 /* relies on the assumption that all shell edges are aligned to two-byte */
\r
1010 /* boundaries, so the least significant bit of (edge).sh is zero. */
\r
1012 #define sencode(edge) \
\r
1013 (shelle) ((unsigned long) (edge).sh | (unsigned long) (edge).shorient)
\r
1015 /* ssym() toggles the orientation of a shell edge. */
\r
1017 #define ssym(edge1, edge2) \
\r
1018 (edge2).sh = (edge1).sh; \
\r
1019 (edge2).shorient = 1 - (edge1).shorient
\r
1021 #define ssymself(edge) \
\r
1022 (edge).shorient = 1 - (edge).shorient
\r
1024 /* spivot() finds the other shell edge (from the same segment) that shares */
\r
1025 /* the same origin. */
\r
1027 #define spivot(edge1, edge2) \
\r
1028 sptr = (edge1).sh[(edge1).shorient]; \
\r
1029 sdecode(sptr, edge2)
\r
1031 #define spivotself(edge) \
\r
1032 sptr = (edge).sh[(edge).shorient]; \
\r
1033 sdecode(sptr, edge)
\r
1035 /* snext() finds the next shell edge (from the same segment) in sequence; */
\r
1036 /* one whose origin is the input shell edge's destination. */
\r
1038 #define snext(edge1, edge2) \
\r
1039 sptr = (edge1).sh[1 - (edge1).shorient]; \
\r
1040 sdecode(sptr, edge2)
\r
1042 #define snextself(edge) \
\r
1043 sptr = (edge).sh[1 - (edge).shorient]; \
\r
1044 sdecode(sptr, edge)
\r
1046 /* These primitives determine or set the origin or destination of a shell */
\r
1049 #define sorg(edge, pointptr) \
\r
1050 pointptr = (point) (edge).sh[2 + (edge).shorient]
\r
1052 #define sdest(edge, pointptr) \
\r
1053 pointptr = (point) (edge).sh[3 - (edge).shorient]
\r
1055 #define setsorg(edge, pointptr) \
\r
1056 (edge).sh[2 + (edge).shorient] = (shelle) pointptr
\r
1058 #define setsdest(edge, pointptr) \
\r
1059 (edge).sh[3 - (edge).shorient] = (shelle) pointptr
\r
1061 /* These primitives read or set a shell marker. Shell markers are used to */
\r
1062 /* hold user boundary information. */
\r
1064 #define mark(edge) (* (int *) ((edge).sh + 6))
\r
1066 #define setmark(edge, value) \
\r
1067 * (int *) ((edge).sh + 6) = value
\r
1069 /* Bond two shell edges together. */
\r
1071 #define sbond(edge1, edge2) \
\r
1072 (edge1).sh[(edge1).shorient] = sencode(edge2); \
\r
1073 (edge2).sh[(edge2).shorient] = sencode(edge1)
\r
1075 /* Dissolve a shell edge bond (from one side). Note that the other shell */
\r
1076 /* edge will still think it's connected to this shell edge. */
\r
1078 #define sdissolve(edge) \
\r
1079 (edge).sh[(edge).shorient] = (shelle) dummysh
\r
1081 /* Copy a shell edge. */
\r
1083 #define shellecopy(edge1, edge2) \
\r
1084 (edge2).sh = (edge1).sh; \
\r
1085 (edge2).shorient = (edge1).shorient
\r
1087 /* Test for equality of shell edges. */
\r
1089 #define shelleequal(edge1, edge2) \
\r
1090 (((edge1).sh == (edge2).sh) && \
\r
1091 ((edge1).shorient == (edge2).shorient))
\r
1093 /********* Primitives for interacting triangles and shell edges *********/
\r
1097 /* tspivot() finds a shell edge abutting a triangle. */
\r
1099 #define tspivot(triedge, edge) \
\r
1100 sptr = (shelle) (triedge).tri[6 + (triedge).orient]; \
\r
1101 sdecode(sptr, edge)
\r
1103 /* stpivot() finds a triangle abutting a shell edge. It requires that the */
\r
1104 /* variable `ptr' of type `triangle' be defined. */
\r
1106 #define stpivot(edge, triedge) \
\r
1107 ptr = (triangle) (edge).sh[4 + (edge).shorient]; \
\r
1108 decode(ptr, triedge)
\r
1110 /* Bond a triangle to a shell edge. */
\r
1112 #define tsbond(triedge, edge) \
\r
1113 (triedge).tri[6 + (triedge).orient] = (triangle) sencode(edge); \
\r
1114 (edge).sh[4 + (edge).shorient] = (shelle) encode(triedge)
\r
1116 /* Dissolve a bond (from the triangle side). */
\r
1118 #define tsdissolve(triedge) \
\r
1119 (triedge).tri[6 + (triedge).orient] = (triangle) dummysh
\r
1121 /* Dissolve a bond (from the shell edge side). */
\r
1123 #define stdissolve(edge) \
\r
1124 (edge).sh[4 + (edge).shorient] = (shelle) dummytri
\r
1126 /********* Primitives for points *********/
\r
1130 #define pointmark(pt) ((int *) (pt))[pointmarkindex]
\r
1132 #define setpointmark(pt, value) \
\r
1133 ((int *) (pt))[pointmarkindex] = value
\r
1135 #define point2tri(pt) ((triangle *) (pt))[point2triindex]
\r
1137 #define setpoint2tri(pt, value) \
\r
1138 ((triangle *) (pt))[point2triindex] = value
\r
1142 /********* Mesh manipulation primitives end here *********/
\r
1144 /********* User interaction routines begin here *********/
\r
1148 /*****************************************************************************/
\r
1150 /* syntax() Print list of command line switches. */
\r
1152 /*****************************************************************************/
\r
1154 #ifndef TRILIBRARY
\r
1160 printf("triangle [-pAcevngBPNEIOXzo_lQVh] input_file\n");
\r
1161 #else /* not REDUCED */
\r
1162 printf("triangle [-pAcevngBPNEIOXzo_iFlCQVh] input_file\n");
\r
1163 #endif /* not REDUCED */
\r
1164 #else /* not CDT_ONLY */
\r
1166 printf("triangle [-prq__a__AcevngBPNEIOXzo_YS__lQVh] input_file\n");
\r
1167 #else /* not REDUCED */
\r
1168 printf("triangle [-prq__a__AcevngBPNEIOXzo_YS__iFlsCQVh] input_file\n");
\r
1169 #endif /* not REDUCED */
\r
1170 #endif /* not CDT_ONLY */
\r
1172 printf(" -p Triangulates a Planar Straight Line Graph (.poly file).\n");
\r
1174 printf(" -r Refines a previously generated mesh.\n");
\r
1176 " -q Quality mesh generation. A minimum angle may be specified.\n");
\r
1177 printf(" -a Applies a maximum triangle area constraint.\n");
\r
1178 #endif /* not CDT_ONLY */
\r
1180 " -A Applies attributes to identify elements in certain regions.\n");
\r
1181 printf(" -c Encloses the convex hull with segments.\n");
\r
1182 printf(" -e Generates an edge list.\n");
\r
1183 printf(" -v Generates a Voronoi diagram.\n");
\r
1184 printf(" -n Generates a list of triangle neighbors.\n");
\r
1185 printf(" -g Generates an .off file for Geomview.\n");
\r
1186 printf(" -B Suppresses output of boundary information.\n");
\r
1187 printf(" -P Suppresses output of .poly file.\n");
\r
1188 printf(" -N Suppresses output of .node file.\n");
\r
1189 printf(" -E Suppresses output of .ele file.\n");
\r
1190 printf(" -I Suppresses mesh iteration numbers.\n");
\r
1191 printf(" -O Ignores holes in .poly file.\n");
\r
1192 printf(" -X Suppresses use of exact arithmetic.\n");
\r
1193 printf(" -z Numbers all items starting from zero (rather than one).\n");
\r
1194 printf(" -o2 Generates second-order subparametric elements.\n");
\r
1196 printf(" -Y Suppresses boundary segment splitting.\n");
\r
1197 printf(" -S Specifies maximum number of added Steiner points.\n");
\r
1198 #endif /* not CDT_ONLY */
\r
1200 printf(" -i Uses incremental method, rather than divide-and-conquer.\n");
\r
1201 printf(" -F Uses Fortune's sweepline algorithm, rather than d-and-c.\n");
\r
1202 #endif /* not REDUCED */
\r
1203 printf(" -l Uses vertical cuts only, rather than alternating cuts.\n");
\r
1207 " -s Force segments into mesh by splitting (instead of using CDT).\n");
\r
1208 #endif /* not CDT_ONLY */
\r
1209 printf(" -C Check consistency of final mesh.\n");
\r
1210 #endif /* not REDUCED */
\r
1211 printf(" -Q Quiet: No terminal output except errors.\n");
\r
1212 printf(" -V Verbose: Detailed information on what I'm doing.\n");
\r
1213 printf(" -h Help: Detailed instructions for Triangle.\n");
\r
1217 #endif /* not TRILIBRARY */
\r
1219 /*****************************************************************************/
\r
1221 /* info() Print out complete instructions. */
\r
1223 /*****************************************************************************/
\r
1225 #ifndef TRILIBRARY
\r
1229 printf("Triangle\n");
\r
1231 "A Two-Dimensional Quality Mesh Generator and Delaunay Triangulator.\n");
\r
1232 printf("Version 1.3\n\n");
\r
1234 "Copyright 1996 Jonathan Richard Shewchuk (bugs/comments to jrs@cs.cmu.edu)\n"
\r
1236 printf("School of Computer Science / Carnegie Mellon University\n");
\r
1237 printf("5000 Forbes Avenue / Pittsburgh, Pennsylvania 15213-3891\n");
\r
1239 "Created as part of the Archimedes project (tools for parallel FEM).\n");
\r
1241 "Supported in part by NSF Grant CMS-9318163 and an NSERC 1967 Scholarship.\n");
\r
1242 printf("There is no warranty whatsoever. Use at your own risk.\n");
\r
1244 printf("This executable is compiled for single precision arithmetic.\n\n\n");
\r
1245 #else /* not SINGLE */
\r
1246 printf("This executable is compiled for double precision arithmetic.\n\n\n");
\r
1247 #endif /* not SINGLE */
\r
1249 "Triangle generates exact Delaunay triangulations, constrained Delaunay\n");
\r
1251 "triangulations, and quality conforming Delaunay triangulations. The latter\n"
\r
1254 "can be generated with no small angles, and are thus suitable for finite\n");
\r
1256 "element analysis. If no command line switches are specified, your .node\n");
\r
1258 "input file will be read, and the Delaunay triangulation will be returned in\n"
\r
1260 printf(".node and .ele output files. The command syntax is:\n\n");
\r
1263 printf("triangle [-pAcevngBPNEIOXzo_lQVh] input_file\n\n");
\r
1264 #else /* not REDUCED */
\r
1265 printf("triangle [-pAcevngBPNEIOXzo_iFlCQVh] input_file\n\n");
\r
1266 #endif /* not REDUCED */
\r
1267 #else /* not CDT_ONLY */
\r
1269 printf("triangle [-prq__a__AcevngBPNEIOXzo_YS__lQVh] input_file\n\n");
\r
1270 #else /* not REDUCED */
\r
1271 printf("triangle [-prq__a__AcevngBPNEIOXzo_YS__iFlsCQVh] input_file\n\n");
\r
1272 #endif /* not REDUCED */
\r
1273 #endif /* not CDT_ONLY */
\r
1275 "Underscores indicate that numbers may optionally follow certain switches;\n");
\r
1277 "do not leave any space between a switch and its numeric parameter.\n");
\r
1279 "input_file must be a file with extension .node, or extension .poly if the\n");
\r
1281 "-p switch is used. If -r is used, you must supply .node and .ele files,\n");
\r
1283 "and possibly a .poly file and .area file as well. The formats of these\n");
\r
1284 printf("files are described below.\n\n");
\r
1285 printf("Command Line Switches:\n\n");
\r
1287 " -p Reads a Planar Straight Line Graph (.poly file), which can specify\n"
\r
1290 " points, segments, holes, and regional attributes and area\n");
\r
1292 " constraints. Will generate a constrained Delaunay triangulation\n");
\r
1294 " fitting the input; or, if -s, -q, or -a is used, a conforming\n");
\r
1296 " Delaunay triangulation. If -p is not used, Triangle reads a .node\n"
\r
1298 printf(" file by default.\n");
\r
1300 " -r Refines a previously generated mesh. The mesh is read from a .node\n"
\r
1303 " file and an .ele file. If -p is also used, a .poly file is read\n");
\r
1305 " and used to constrain edges in the mesh. Further details on\n");
\r
1306 printf(" refinement are given below.\n");
\r
1308 " -q Quality mesh generation by Jim Ruppert's Delaunay refinement\n");
\r
1310 " algorithm. Adds points to the mesh to ensure that no angles\n");
\r
1312 " smaller than 20 degrees occur. An alternative minimum angle may be\n"
\r
1315 " specified after the `q'. If the minimum angle is 20.7 degrees or\n");
\r
1317 " smaller, the triangulation algorithm is theoretically guaranteed to\n"
\r
1320 " terminate (assuming infinite precision arithmetic - Triangle may\n");
\r
1322 " fail to terminate if you run out of precision). In practice, the\n");
\r
1324 " algorithm often succeeds for minimum angles up to 33.8 degrees.\n");
\r
1326 " For highly refined meshes, however, it may be necessary to reduce\n");
\r
1328 " the minimum angle to well below 20 to avoid problems associated\n");
\r
1330 " with insufficient floating-point precision. The specified angle\n");
\r
1331 printf(" may include a decimal point.\n");
\r
1333 " -a Imposes a maximum triangle area. If a number follows the `a', no\n");
\r
1335 " triangle will be generated whose area is larger than that number.\n");
\r
1337 " If no number is specified, an .area file (if -r is used) or .poly\n");
\r
1339 " file (if -r is not used) specifies a number of maximum area\n");
\r
1341 " constraints. An .area file contains a separate area constraint for\n"
\r
1344 " each triangle, and is useful for refining a finite element mesh\n");
\r
1346 " based on a posteriori error estimates. A .poly file can optionally\n"
\r
1349 " contain an area constraint for each segment-bounded region, thereby\n"
\r
1352 " enforcing triangle densities in a first triangulation. You can\n");
\r
1354 " impose both a fixed area constraint and a varying area constraint\n");
\r
1356 " by invoking the -a switch twice, once with and once without a\n");
\r
1358 " number following. Each area specified may include a decimal point.\n"
\r
1361 " -A Assigns an additional attribute to each triangle that identifies\n");
\r
1363 " what segment-bounded region each triangle belongs to. Attributes\n");
\r
1365 " are assigned to regions by the .poly file. If a region is not\n");
\r
1367 " explicitly marked by the .poly file, triangles in that region are\n");
\r
1369 " assigned an attribute of zero. The -A switch has an effect only\n");
\r
1370 printf(" when the -p switch is used and the -r switch is not.\n");
\r
1372 " -c Creates segments on the convex hull of the triangulation. If you\n");
\r
1374 " are triangulating a point set, this switch causes a .poly file to\n");
\r
1376 " be written, containing all edges in the convex hull. (By default,\n"
\r
1379 " a .poly file is written only if a .poly file is read.) If you are\n"
\r
1382 " triangulating a PSLG, this switch specifies that the interior of\n");
\r
1384 " the convex hull of the PSLG should be triangulated. If you do not\n"
\r
1387 " use this switch when triangulating a PSLG, it is assumed that you\n");
\r
1389 " have identified the region to be triangulated by surrounding it\n");
\r
1391 " with segments of the input PSLG. Beware: if you are not careful,\n"
\r
1394 " this switch can cause the introduction of an extremely thin angle\n");
\r
1396 " between a PSLG segment and a convex hull segment, which can cause\n");
\r
1398 " overrefinement or failure if Triangle runs out of precision. If\n");
\r
1400 " you are refining a mesh, the -c switch works differently; it\n");
\r
1402 " generates the set of boundary edges of the mesh, rather than the\n");
\r
1403 printf(" convex hull.\n");
\r
1405 " -e Outputs (to an .edge file) a list of edges of the triangulation.\n");
\r
1407 " -v Outputs the Voronoi diagram associated with the triangulation.\n");
\r
1408 printf(" Does not attempt to detect degeneracies.\n");
\r
1410 " -n Outputs (to a .neigh file) a list of triangles neighboring each\n");
\r
1411 printf(" triangle.\n");
\r
1413 " -g Outputs the mesh to an Object File Format (.off) file, suitable for\n"
\r
1415 printf(" viewing with the Geometry Center's Geomview package.\n");
\r
1417 " -B No boundary markers in the output .node, .poly, and .edge output\n");
\r
1419 " files. See the detailed discussion of boundary markers below.\n");
\r
1421 " -P No output .poly file. Saves disk space, but you lose the ability\n");
\r
1423 " to impose segment constraints on later refinements of the mesh.\n");
\r
1424 printf(" -N No output .node file.\n");
\r
1425 printf(" -E No output .ele file.\n");
\r
1427 " -I No iteration numbers. Suppresses the output of .node and .poly\n");
\r
1429 " files, so your input files won't be overwritten. (If your input is\n"
\r
1432 " a .poly file only, a .node file will be written.) Cannot be used\n");
\r
1434 " with the -r switch, because that would overwrite your input .ele\n");
\r
1436 " file. Shouldn't be used with the -s, -q, or -a switch if you are\n");
\r
1438 " using a .node file for input, because no .node file will be\n");
\r
1439 printf(" written, so there will be no record of any added points.\n");
\r
1440 printf(" -O No holes. Ignores the holes in the .poly file.\n");
\r
1442 " -X No exact arithmetic. Normally, Triangle uses exact floating-point\n"
\r
1445 " arithmetic for certain tests if it thinks the inexact tests are not\n"
\r
1448 " accurate enough. Exact arithmetic ensures the robustness of the\n");
\r
1450 " triangulation algorithms, despite floating-point roundoff error.\n");
\r
1452 " Disabling exact arithmetic with the -X switch will cause a small\n");
\r
1454 " improvement in speed and create the possibility (albeit small) that\n"
\r
1457 " Triangle will fail to produce a valid mesh. Not recommended.\n");
\r
1459 " -z Numbers all items starting from zero (rather than one). Note that\n"
\r
1462 " this switch is normally overrided by the value used to number the\n");
\r
1464 " first point of the input .node or .poly file. However, this switch\n"
\r
1466 printf(" is useful when calling Triangle from another program.\n");
\r
1468 " -o2 Generates second-order subparametric elements with six nodes each.\n"
\r
1471 " -Y No new points on the boundary. This switch is useful when the mesh\n"
\r
1474 " boundary must be preserved so that it conforms to some adjacent\n");
\r
1476 " mesh. Be forewarned that you will probably sacrifice some of the\n");
\r
1478 " quality of the mesh; Triangle will try, but the resulting mesh may\n"
\r
1481 " contain triangles of poor aspect ratio. Works well if all the\n");
\r
1483 " boundary points are closely spaced. Specify this switch twice\n");
\r
1485 " (`-YY') to prevent all segment splitting, including internal\n");
\r
1486 printf(" boundaries.\n");
\r
1488 " -S Specifies the maximum number of Steiner points (points that are not\n"
\r
1491 " in the input, but are added to meet the constraints of minimum\n");
\r
1493 " angle and maximum area). The default is to allow an unlimited\n");
\r
1495 " number. If you specify this switch with no number after it,\n");
\r
1497 " the limit is set to zero. Triangle always adds points at segment\n");
\r
1499 " intersections, even if it needs to use more points than the limit\n");
\r
1501 " you set. When Triangle inserts segments by splitting (-s), it\n");
\r
1503 " always adds enough points to ensure that all the segments appear in\n"
\r
1506 " the triangulation, again ignoring the limit. Be forewarned that\n");
\r
1508 " the -S switch may result in a conforming triangulation that is not\n"
\r
1511 " truly Delaunay, because Triangle may be forced to stop adding\n");
\r
1513 " points when the mesh is in a state where a segment is non-Delaunay\n"
\r
1516 " and needs to be split. If so, Triangle will print a warning.\n");
\r
1518 " -i Uses an incremental rather than divide-and-conquer algorithm to\n");
\r
1520 " form a Delaunay triangulation. Try it if the divide-and-conquer\n");
\r
1521 printf(" algorithm fails.\n");
\r
1523 " -F Uses Steven Fortune's sweepline algorithm to form a Delaunay\n");
\r
1525 " triangulation. Warning: does not use exact arithmetic for all\n");
\r
1526 printf(" calculations. An exact result is not guaranteed.\n");
\r
1528 " -l Uses only vertical cuts in the divide-and-conquer algorithm. By\n");
\r
1530 " default, Triangle uses alternating vertical and horizontal cuts,\n");
\r
1532 " which usually improve the speed except with point sets that are\n");
\r
1534 " small or short and wide. This switch is primarily of theoretical\n");
\r
1535 printf(" interest.\n");
\r
1537 " -s Specifies that segments should be forced into the triangulation by\n"
\r
1540 " recursively splitting them at their midpoints, rather than by\n");
\r
1542 " generating a constrained Delaunay triangulation. Segment splitting\n"
\r
1545 " is true to Ruppert's original algorithm, but can create needlessly\n"
\r
1547 printf(" small triangles near external small features.\n");
\r
1549 " -C Check the consistency of the final mesh. Uses exact arithmetic for\n"
\r
1552 " checking, even if the -X switch is used. Useful if you suspect\n");
\r
1553 printf(" Triangle is buggy.\n");
\r
1555 " -Q Quiet: Suppresses all explanation of what Triangle is doing, unless\n"
\r
1557 printf(" an error occurs.\n");
\r
1559 " -V Verbose: Gives detailed information about what Triangle is doing.\n");
\r
1561 " Add more `V's for increasing amount of detail. `-V' gives\n");
\r
1563 " information on algorithmic progress and more detailed statistics.\n");
\r
1565 " `-VV' gives point-by-point details, and will print so much that\n");
\r
1567 " Triangle will run much more slowly. `-VVV' gives information only\n"
\r
1569 printf(" a debugger could love.\n");
\r
1570 printf(" -h Help: Displays these instructions.\n");
\r
1572 printf("Definitions:\n");
\r
1575 " A Delaunay triangulation of a point set is a triangulation whose vertices\n"
\r
1578 " are the point set, having the property that no point in the point set\n");
\r
1580 " falls in the interior of the circumcircle (circle that passes through all\n"
\r
1582 printf(" three vertices) of any triangle in the triangulation.\n\n");
\r
1584 " A Voronoi diagram of a point set is a subdivision of the plane into\n");
\r
1586 " polygonal regions (some of which may be infinite), where each region is\n");
\r
1588 " the set of points in the plane that are closer to some input point than\n");
\r
1590 " to any other input point. (The Voronoi diagram is the geometric dual of\n"
\r
1592 printf(" the Delaunay triangulation.)\n\n");
\r
1594 " A Planar Straight Line Graph (PSLG) is a collection of points and\n");
\r
1596 " segments. Segments are simply edges, whose endpoints are points in the\n");
\r
1598 " PSLG. The file format for PSLGs (.poly files) is described below.\n");
\r
1601 " A constrained Delaunay triangulation of a PSLG is similar to a Delaunay\n");
\r
1603 " triangulation, but each PSLG segment is present as a single edge in the\n");
\r
1605 " triangulation. (A constrained Delaunay triangulation is not truly a\n");
\r
1606 printf(" Delaunay triangulation.)\n\n");
\r
1608 " A conforming Delaunay triangulation of a PSLG is a true Delaunay\n");
\r
1610 " triangulation in which each PSLG segment may have been subdivided into\n");
\r
1612 " several edges by the insertion of additional points. These inserted\n");
\r
1614 " points are necessary to allow the segments to exist in the mesh while\n");
\r
1615 printf(" maintaining the Delaunay property.\n\n");
\r
1616 printf("File Formats:\n\n");
\r
1618 " All files may contain comments prefixed by the character '#'. Points,\n");
\r
1620 " triangles, edges, holes, and maximum area constraints must be numbered\n");
\r
1622 " consecutively, starting from either 1 or 0. Whichever you choose, all\n");
\r
1624 " input files must be consistent; if the nodes are numbered from 1, so must\n"
\r
1627 " be all other objects. Triangle automatically detects your choice while\n");
\r
1629 " reading the .node (or .poly) file. (When calling Triangle from another\n");
\r
1631 " program, use the -z switch if you wish to number objects from zero.)\n");
\r
1632 printf(" Examples of these file formats are given below.\n\n");
\r
1633 printf(" .node files:\n");
\r
1635 " First line: <# of points> <dimension (must be 2)> <# of attributes>\n");
\r
1637 " <# of boundary markers (0 or 1)>\n"
\r
1640 " Remaining lines: <point #> <x> <y> [attributes] [boundary marker]\n");
\r
1643 " The attributes, which are typically floating-point values of physical\n");
\r
1645 " quantities (such as mass or conductivity) associated with the nodes of\n"
\r
1648 " a finite element mesh, are copied unchanged to the output mesh. If -s,\n"
\r
1651 " -q, or -a is selected, each new Steiner point added to the mesh will\n");
\r
1652 printf(" have attributes assigned to it by linear interpolation.\n\n");
\r
1654 " If the fourth entry of the first line is `1', the last column of the\n");
\r
1656 " remainder of the file is assumed to contain boundary markers. Boundary\n"
\r
1659 " markers are used to identify boundary points and points resting on PSLG\n"
\r
1662 " segments; a complete description appears in a section below. The .node\n"
\r
1665 " file produced by Triangle will contain boundary markers in the last\n");
\r
1666 printf(" column unless they are suppressed by the -B switch.\n\n");
\r
1667 printf(" .ele files:\n");
\r
1669 " First line: <# of triangles> <points per triangle> <# of attributes>\n");
\r
1671 " Remaining lines: <triangle #> <point> <point> <point> ... [attributes]\n"
\r
1675 " Points are indices into the corresponding .node file. The first three\n"
\r
1678 " points are the corners, and are listed in counterclockwise order around\n"
\r
1681 " each triangle. (The remaining points, if any, depend on the type of\n");
\r
1683 " finite element used.) The attributes are just like those of .node\n");
\r
1685 " files. Because there is no simple mapping from input to output\n");
\r
1687 " triangles, an attempt is made to interpolate attributes, which may\n");
\r
1689 " result in a good deal of diffusion of attributes among nearby triangles\n"
\r
1692 " as the triangulation is refined. Diffusion does not occur across\n");
\r
1694 " segments, so attributes used to identify segment-bounded regions remain\n"
\r
1697 " intact. In output .ele files, all triangles have three points each\n");
\r
1699 " unless the -o2 switch is used, in which case they have six, and the\n");
\r
1701 " fourth, fifth, and sixth points lie on the midpoints of the edges\n");
\r
1702 printf(" opposite the first, second, and third corners.\n\n");
\r
1703 printf(" .poly files:\n");
\r
1705 " First line: <# of points> <dimension (must be 2)> <# of attributes>\n");
\r
1707 " <# of boundary markers (0 or 1)>\n"
\r
1710 " Following lines: <point #> <x> <y> [attributes] [boundary marker]\n");
\r
1711 printf(" One line: <# of segments> <# of boundary markers (0 or 1)>\n");
\r
1713 " Following lines: <segment #> <endpoint> <endpoint> [boundary marker]\n");
\r
1714 printf(" One line: <# of holes>\n");
\r
1715 printf(" Following lines: <hole #> <x> <y>\n");
\r
1717 " Optional line: <# of regional attributes and/or area constraints>\n");
\r
1719 " Optional following lines: <constraint #> <x> <y> <attrib> <max area>\n");
\r
1722 " A .poly file represents a PSLG, as well as some additional information.\n"
\r
1725 " The first section lists all the points, and is identical to the format\n"
\r
1728 " of .node files. <# of points> may be set to zero to indicate that the\n"
\r
1731 " points are listed in a separate .node file; .poly files produced by\n");
\r
1733 " Triangle always have this format. This has the advantage that a point\n"
\r
1736 " set may easily be triangulated with or without segments. (The same\n");
\r
1738 " effect can be achieved, albeit using more disk space, by making a copy\n"
\r
1741 " of the .poly file with the extension .node; all sections of the file\n");
\r
1742 printf(" but the first are ignored.)\n\n");
\r
1744 " The second section lists the segments. Segments are edges whose\n");
\r
1746 " presence in the triangulation is enforced. Each segment is specified\n");
\r
1748 " by listing the indices of its two endpoints. This means that you must\n"
\r
1751 " include its endpoints in the point list. If -s, -q, and -a are not\n");
\r
1753 " selected, Triangle will produce a constrained Delaunay triangulation,\n");
\r
1755 " in which each segment appears as a single edge in the triangulation.\n");
\r
1757 " If -q or -a is selected, Triangle will produce a conforming Delaunay\n");
\r
1759 " triangulation, in which segments may be subdivided into smaller edges.\n"
\r
1761 printf(" Each segment, like each point, may have a boundary marker.\n\n");
\r
1763 " The third section lists holes (and concavities, if -c is selected) in\n");
\r
1765 " the triangulation. Holes are specified by identifying a point inside\n");
\r
1767 " each hole. After the triangulation is formed, Triangle creates holes\n");
\r
1769 " by eating triangles, spreading out from each hole point until its\n");
\r
1771 " progress is blocked by PSLG segments; you must be careful to enclose\n");
\r
1773 " each hole in segments, or your whole triangulation may be eaten away.\n");
\r
1775 " If the two triangles abutting a segment are eaten, the segment itself\n");
\r
1777 " is also eaten. Do not place a hole directly on a segment; if you do,\n");
\r
1778 printf(" Triangle will choose one side of the segment arbitrarily.\n\n");
\r
1780 " The optional fourth section lists regional attributes (to be assigned\n");
\r
1782 " to all triangles in a region) and regional constraints on the maximum\n");
\r
1784 " triangle area. Triangle will read this section only if the -A switch\n");
\r
1786 " is used or the -a switch is used without a number following it, and the\n"
\r
1789 " -r switch is not used. Regional attributes and area constraints are\n");
\r
1791 " propagated in the same manner as holes; you specify a point for each\n");
\r
1793 " attribute and/or constraint, and the attribute and/or constraint will\n");
\r
1795 " affect the whole region (bounded by segments) containing the point. If\n"
\r
1798 " two values are written on a line after the x and y coordinate, the\n");
\r
1800 " former is assumed to be a regional attribute (but will only be applied\n"
\r
1803 " if the -A switch is selected), and the latter is assumed to be a\n");
\r
1805 " regional area constraint (but will only be applied if the -a switch is\n"
\r
1808 " selected). You may also specify just one value after the coordinates,\n"
\r
1811 " which can serve as both an attribute and an area constraint, depending\n"
\r
1814 " on the choice of switches. If you are using the -A and -a switches\n");
\r
1816 " simultaneously and wish to assign an attribute to some region without\n");
\r
1817 printf(" imposing an area constraint, use a negative maximum area.\n\n");
\r
1819 " When a triangulation is created from a .poly file, you must either\n");
\r
1821 " enclose the entire region to be triangulated in PSLG segments, or\n");
\r
1823 " use the -c switch, which encloses the convex hull of the input point\n");
\r
1825 " set. If you do not use the -c switch, Triangle will eat all triangles\n"
\r
1828 " on the outer boundary that are not protected by segments; if you are\n");
\r
1830 " not careful, your whole triangulation may be eaten away. If you do\n");
\r
1832 " use the -c switch, you can still produce concavities by appropriate\n");
\r
1833 printf(" placement of holes just inside the convex hull.\n\n");
\r
1835 " An ideal PSLG has no intersecting segments, nor any points that lie\n");
\r
1837 " upon segments (except, of course, the endpoints of each segment.) You\n"
\r
1840 " aren't required to make your .poly files ideal, but you should be aware\n"
\r
1843 " of what can go wrong. Segment intersections are relatively safe -\n");
\r
1845 " Triangle will calculate the intersection points for you and add them to\n"
\r
1848 " the triangulation - as long as your machine's floating-point precision\n"
\r
1851 " doesn't become a problem. You are tempting the fates if you have three\n"
\r
1854 " segments that cross at the same location, and expect Triangle to figure\n"
\r
1857 " out where the intersection point is. Thanks to floating-point roundoff\n"
\r
1860 " error, Triangle will probably decide that the three segments intersect\n"
\r
1863 " at three different points, and you will find a minuscule triangle in\n");
\r
1865 " your output - unless Triangle tries to refine the tiny triangle, uses\n");
\r
1867 " up the last bit of machine precision, and fails to terminate at all.\n");
\r
1869 " You're better off putting the intersection point in the input files,\n");
\r
1871 " and manually breaking up each segment into two. Similarly, if you\n");
\r
1873 " place a point at the middle of a segment, and hope that Triangle will\n");
\r
1875 " break up the segment at that point, you might get lucky. On the other\n"
\r
1878 " hand, Triangle might decide that the point doesn't lie precisely on the\n"
\r
1881 " line, and you'll have a needle-sharp triangle in your output - or a lot\n"
\r
1883 printf(" of tiny triangles if you're generating a quality mesh.\n\n");
\r
1885 " When Triangle reads a .poly file, it also writes a .poly file, which\n");
\r
1887 " includes all edges that are part of input segments. If the -c switch\n");
\r
1889 " is used, the output .poly file will also include all of the edges on\n");
\r
1891 " the convex hull. Hence, the output .poly file is useful for finding\n");
\r
1893 " edges associated with input segments and setting boundary conditions in\n"
\r
1896 " finite element simulations. More importantly, you will need it if you\n"
\r
1899 " plan to refine the output mesh, and don't want segments to be missing\n");
\r
1900 printf(" in later triangulations.\n\n");
\r
1901 printf(" .area files:\n");
\r
1902 printf(" First line: <# of triangles>\n");
\r
1903 printf(" Following lines: <triangle #> <maximum area>\n\n");
\r
1905 " An .area file associates with each triangle a maximum area that is used\n"
\r
1908 " for mesh refinement. As with other file formats, every triangle must\n");
\r
1910 " be represented, and they must be numbered consecutively. A triangle\n");
\r
1912 " may be left unconstrained by assigning it a negative maximum area.\n");
\r
1914 printf(" .edge files:\n");
\r
1915 printf(" First line: <# of edges> <# of boundary markers (0 or 1)>\n");
\r
1917 " Following lines: <edge #> <endpoint> <endpoint> [boundary marker]\n");
\r
1920 " Endpoints are indices into the corresponding .node file. Triangle can\n"
\r
1923 " produce .edge files (use the -e switch), but cannot read them. The\n");
\r
1925 " optional column of boundary markers is suppressed by the -B switch.\n");
\r
1928 " In Voronoi diagrams, one also finds a special kind of edge that is an\n");
\r
1930 " infinite ray with only one endpoint. For these edges, a different\n");
\r
1931 printf(" format is used:\n\n");
\r
1932 printf(" <edge #> <endpoint> -1 <direction x> <direction y>\n\n");
\r
1934 " The `direction' is a floating-point vector that indicates the direction\n"
\r
1936 printf(" of the infinite ray.\n\n");
\r
1937 printf(" .neigh files:\n");
\r
1939 " First line: <# of triangles> <# of neighbors per triangle (always 3)>\n"
\r
1942 " Following lines: <triangle #> <neighbor> <neighbor> <neighbor>\n");
\r
1945 " Neighbors are indices into the corresponding .ele file. An index of -1\n"
\r
1948 " indicates a mesh boundary, and therefore no neighbor. Triangle can\n");
\r
1950 " produce .neigh files (use the -n switch), but cannot read them.\n");
\r
1953 " The first neighbor of triangle i is opposite the first corner of\n");
\r
1954 printf(" triangle i, and so on.\n\n");
\r
1955 printf("Boundary Markers:\n\n");
\r
1957 " Boundary markers are tags used mainly to identify which output points and\n"
\r
1960 " edges are associated with which PSLG segment, and to identify which\n");
\r
1962 " points and edges occur on a boundary of the triangulation. A common use\n"
\r
1965 " is to determine where boundary conditions should be applied to a finite\n");
\r
1967 " element mesh. You can prevent boundary markers from being written into\n");
\r
1968 printf(" files produced by Triangle by using the -B switch.\n\n");
\r
1970 " The boundary marker associated with each segment in an output .poly file\n"
\r
1972 printf(" or edge in an output .edge file is chosen as follows:\n");
\r
1974 " - If an output edge is part or all of a PSLG segment with a nonzero\n");
\r
1976 " boundary marker, then the edge is assigned the same marker.\n");
\r
1978 " - Otherwise, if the edge occurs on a boundary of the triangulation\n");
\r
1980 " (including boundaries of holes), then the edge is assigned the marker\n"
\r
1982 printf(" one (1).\n");
\r
1983 printf(" - Otherwise, the edge is assigned the marker zero (0).\n");
\r
1985 " The boundary marker associated with each point in an output .node file is\n"
\r
1987 printf(" chosen as follows:\n");
\r
1989 " - If a point is assigned a nonzero boundary marker in the input file,\n");
\r
1991 " then it is assigned the same marker in the output .node file.\n");
\r
1993 " - Otherwise, if the point lies on a PSLG segment (including the\n");
\r
1995 " segment's endpoints) with a nonzero boundary marker, then the point\n");
\r
1997 " is assigned the same marker. If the point lies on several such\n");
\r
1998 printf(" segments, one of the markers is chosen arbitrarily.\n");
\r
2000 " - Otherwise, if the point occurs on a boundary of the triangulation,\n");
\r
2001 printf(" then the point is assigned the marker one (1).\n");
\r
2002 printf(" - Otherwise, the point is assigned the marker zero (0).\n");
\r
2005 " If you want Triangle to determine for you which points and edges are on\n");
\r
2007 " the boundary, assign them the boundary marker zero (or use no markers at\n"
\r
2010 " all) in your input files. Alternatively, you can mark some of them and\n");
\r
2011 printf(" leave others marked zero, allowing Triangle to label them.\n\n");
\r
2012 printf("Triangulation Iteration Numbers:\n\n");
\r
2014 " Because Triangle can read and refine its own triangulations, input\n");
\r
2016 " and output files have iteration numbers. For instance, Triangle might\n");
\r
2018 " read the files mesh.3.node, mesh.3.ele, and mesh.3.poly, refine the\n");
\r
2020 " triangulation, and output the files mesh.4.node, mesh.4.ele, and\n");
\r
2021 printf(" mesh.4.poly. Files with no iteration number are treated as if\n");
\r
2023 " their iteration number is zero; hence, Triangle might read the file\n");
\r
2025 " points.node, triangulate it, and produce the files points.1.node and\n");
\r
2026 printf(" points.1.ele.\n\n");
\r
2028 " Iteration numbers allow you to create a sequence of successively finer\n");
\r
2030 " meshes suitable for multigrid methods. They also allow you to produce a\n"
\r
2033 " sequence of meshes using error estimate-driven mesh refinement.\n");
\r
2036 " If you're not using refinement or quality meshing, and you don't like\n");
\r
2038 " iteration numbers, use the -I switch to disable them. This switch will\n");
\r
2040 " also disable output of .node and .poly files to prevent your input files\n"
\r
2043 " from being overwritten. (If the input is a .poly file that contains its\n"
\r
2045 printf(" own points, a .node file will be written.)\n\n");
\r
2046 printf("Examples of How to Use Triangle:\n\n");
\r
2048 " `triangle dots' will read points from dots.node, and write their Delaunay\n"
\r
2051 " triangulation to dots.1.node and dots.1.ele. (dots.1.node will be\n");
\r
2053 " identical to dots.node.) `triangle -I dots' writes the triangulation to\n"
\r
2056 " dots.ele instead. (No additional .node file is needed, so none is\n");
\r
2057 printf(" written.)\n\n");
\r
2059 " `triangle -pe object.1' will read a PSLG from object.1.poly (and possibly\n"
\r
2062 " object.1.node, if the points are omitted from object.1.poly) and write\n");
\r
2063 printf(" their constrained Delaunay triangulation to object.2.node and\n");
\r
2065 " object.2.ele. The segments will be copied to object.2.poly, and all\n");
\r
2066 printf(" edges will be written to object.2.edge.\n\n");
\r
2068 " `triangle -pq31.5a.1 object' will read a PSLG from object.poly (and\n");
\r
2070 " possibly object.node), generate a mesh whose angles are all greater than\n"
\r
2073 " 31.5 degrees and whose triangles all have area smaller than 0.1, and\n");
\r
2075 " write the mesh to object.1.node and object.1.ele. Each segment may have\n"
\r
2078 " been broken up into multiple edges; the resulting constrained edges are\n");
\r
2079 printf(" written to object.1.poly.\n\n");
\r
2081 " Here is a sample file `box.poly' describing a square with a square hole:\n"
\r
2085 " # A box with eight points in 2D, no attributes, one boundary marker.\n");
\r
2086 printf(" 8 2 0 1\n");
\r
2087 printf(" # Outer box has these vertices:\n");
\r
2088 printf(" 1 0 0 0\n");
\r
2089 printf(" 2 0 3 0\n");
\r
2090 printf(" 3 3 0 0\n");
\r
2091 printf(" 4 3 3 33 # A special marker for this point.\n");
\r
2092 printf(" # Inner square has these vertices:\n");
\r
2093 printf(" 5 1 1 0\n");
\r
2094 printf(" 6 1 2 0\n");
\r
2095 printf(" 7 2 1 0\n");
\r
2096 printf(" 8 2 2 0\n");
\r
2097 printf(" # Five segments with boundary markers.\n");
\r
2099 printf(" 1 1 2 5 # Left side of outer box.\n");
\r
2100 printf(" 2 5 7 0 # Segments 2 through 5 enclose the hole.\n");
\r
2101 printf(" 3 7 8 0\n");
\r
2102 printf(" 4 8 6 10\n");
\r
2103 printf(" 5 6 5 0\n");
\r
2104 printf(" # One hole in the middle of the inner square.\n");
\r
2106 printf(" 1 1.5 1.5\n\n");
\r
2108 " Note that some segments are missing from the outer square, so one must\n");
\r
2110 " use the `-c' switch. After `triangle -pqc box.poly', here is the output\n"
\r
2113 " file `box.1.node', with twelve points. The last four points were added\n");
\r
2115 " to meet the angle constraint. Points 1, 2, and 9 have markers from\n");
\r
2117 " segment 1. Points 6 and 8 have markers from segment 4. All the other\n");
\r
2119 " points but 4 have been marked to indicate that they lie on a boundary.\n");
\r
2121 printf(" 12 2 0 1\n");
\r
2122 printf(" 1 0 0 5\n");
\r
2123 printf(" 2 0 3 5\n");
\r
2124 printf(" 3 3 0 1\n");
\r
2125 printf(" 4 3 3 33\n");
\r
2126 printf(" 5 1 1 1\n");
\r
2127 printf(" 6 1 2 10\n");
\r
2128 printf(" 7 2 1 1\n");
\r
2129 printf(" 8 2 2 10\n");
\r
2130 printf(" 9 0 1.5 5\n");
\r
2131 printf(" 10 1.5 0 1\n");
\r
2132 printf(" 11 3 1.5 1\n");
\r
2133 printf(" 12 1.5 3 1\n");
\r
2134 printf(" # Generated by triangle -pqc box.poly\n\n");
\r
2135 printf(" Here is the output file `box.1.ele', with twelve triangles.\n\n");
\r
2136 printf(" 12 3 0\n");
\r
2137 printf(" 1 5 6 9\n");
\r
2138 printf(" 2 10 3 7\n");
\r
2139 printf(" 3 6 8 12\n");
\r
2140 printf(" 4 9 1 5\n");
\r
2141 printf(" 5 6 2 9\n");
\r
2142 printf(" 6 7 3 11\n");
\r
2143 printf(" 7 11 4 8\n");
\r
2144 printf(" 8 7 5 10\n");
\r
2145 printf(" 9 12 2 6\n");
\r
2146 printf(" 10 8 7 11\n");
\r
2147 printf(" 11 5 1 10\n");
\r
2148 printf(" 12 8 4 12\n");
\r
2149 printf(" # Generated by triangle -pqc box.poly\n\n");
\r
2151 " Here is the output file `box.1.poly'. Note that segments have been added\n"
\r
2154 " to represent the convex hull, and some segments have been split by newly\n"
\r
2157 " added points. Note also that <# of points> is set to zero to indicate\n");
\r
2158 printf(" that the points should be read from the .node file.\n\n");
\r
2159 printf(" 0 2 0 1\n");
\r
2160 printf(" 12 1\n");
\r
2161 printf(" 1 1 9 5\n");
\r
2162 printf(" 2 5 7 1\n");
\r
2163 printf(" 3 8 7 1\n");
\r
2164 printf(" 4 6 8 10\n");
\r
2165 printf(" 5 5 6 1\n");
\r
2166 printf(" 6 3 10 1\n");
\r
2167 printf(" 7 4 11 1\n");
\r
2168 printf(" 8 2 12 1\n");
\r
2169 printf(" 9 9 2 5\n");
\r
2170 printf(" 10 10 1 1\n");
\r
2171 printf(" 11 11 3 1\n");
\r
2172 printf(" 12 12 4 1\n");
\r
2174 printf(" 1 1.5 1.5\n");
\r
2175 printf(" # Generated by triangle -pqc box.poly\n\n");
\r
2176 printf("Refinement and Area Constraints:\n\n");
\r
2178 " The -r switch causes a mesh (.node and .ele files) to be read and\n");
\r
2180 " refined. If the -p switch is also used, a .poly file is read and used to\n"
\r
2183 " specify edges that are constrained and cannot be eliminated (although\n");
\r
2185 " they can be divided into smaller edges) by the refinement process.\n");
\r
2188 " When you refine a mesh, you generally want to impose tighter quality\n");
\r
2190 " constraints. One way to accomplish this is to use -q with a larger\n");
\r
2192 " angle, or -a followed by a smaller area than you used to generate the\n");
\r
2194 " mesh you are refining. Another way to do this is to create an .area\n");
\r
2196 " file, which specifies a maximum area for each triangle, and use the -a\n");
\r
2198 " switch (without a number following). Each triangle's area constraint is\n"
\r
2201 " applied to that triangle. Area constraints tend to diffuse as the mesh\n");
\r
2203 " is refined, so if there are large variations in area constraint between\n");
\r
2204 printf(" adjacent triangles, you may not get the results you want.\n\n");
\r
2206 " If you are refining a mesh composed of linear (three-node) elements, the\n"
\r
2209 " output mesh will contain all the nodes present in the input mesh, in the\n"
\r
2212 " same order, with new nodes added at the end of the .node file. However,\n"
\r
2215 " there is no guarantee that each output element is contained in a single\n");
\r
2217 " input element. Often, output elements will overlap two input elements,\n");
\r
2219 " and input edges are not present in the output mesh. Hence, a sequence of\n"
\r
2222 " refined meshes will form a hierarchy of nodes, but not a hierarchy of\n");
\r
2224 " elements. If you a refining a mesh of higher-order elements, the\n");
\r
2226 " hierarchical property applies only to the nodes at the corners of an\n");
\r
2227 printf(" element; other nodes may not be present in the refined mesh.\n\n");
\r
2229 " It is important to understand that maximum area constraints in .poly\n");
\r
2231 " files are handled differently from those in .area files. A maximum area\n"
\r
2234 " in a .poly file applies to the whole (segment-bounded) region in which a\n"
\r
2237 " point falls, whereas a maximum area in an .area file applies to only one\n"
\r
2240 " triangle. Area constraints in .poly files are used only when a mesh is\n");
\r
2242 " first generated, whereas area constraints in .area files are used only to\n"
\r
2245 " refine an existing mesh, and are typically based on a posteriori error\n");
\r
2247 " estimates resulting from a finite element simulation on that mesh.\n");
\r
2250 " `triangle -rq25 object.1' will read object.1.node and object.1.ele, then\n"
\r
2253 " refine the triangulation to enforce a 25 degree minimum angle, and then\n");
\r
2255 " write the refined triangulation to object.2.node and object.2.ele.\n");
\r
2258 " `triangle -rpaa6.2 z.3' will read z.3.node, z.3.ele, z.3.poly, and\n");
\r
2260 " z.3.area. After reconstructing the mesh and its segments, Triangle will\n"
\r
2263 " refine the mesh so that no triangle has area greater than 6.2, and\n");
\r
2265 " furthermore the triangles satisfy the maximum area constraints in\n");
\r
2267 " z.3.area. The output is written to z.4.node, z.4.ele, and z.4.poly.\n");
\r
2270 " The sequence `triangle -qa1 x', `triangle -rqa.3 x.1', `triangle -rqa.1\n");
\r
2272 " x.2' creates a sequence of successively finer meshes x.1, x.2, and x.3,\n");
\r
2273 printf(" suitable for multigrid.\n\n");
\r
2274 printf("Convex Hulls and Mesh Boundaries:\n\n");
\r
2276 " If the input is a point set (rather than a PSLG), Triangle produces its\n");
\r
2278 " convex hull as a by-product in the output .poly file if you use the -c\n");
\r
2280 " switch. There are faster algorithms for finding a two-dimensional convex\n"
\r
2283 " hull than triangulation, of course, but this one comes for free. If the\n"
\r
2286 " input is an unconstrained mesh (you are using the -r switch but not the\n");
\r
2288 " -p switch), Triangle produces a list of its boundary edges (including\n");
\r
2289 printf(" hole boundaries) as a by-product if you use the -c switch.\n\n");
\r
2290 printf("Voronoi Diagrams:\n\n");
\r
2292 " The -v switch produces a Voronoi diagram, in files suffixed .v.node and\n");
\r
2294 " .v.edge. For example, `triangle -v points' will read points.node,\n");
\r
2296 " produce its Delaunay triangulation in points.1.node and points.1.ele,\n");
\r
2298 " and produce its Voronoi diagram in points.1.v.node and points.1.v.edge.\n");
\r
2300 " The .v.node file contains a list of all Voronoi vertices, and the .v.edge\n"
\r
2303 " file contains a list of all Voronoi edges, some of which may be infinite\n"
\r
2306 " rays. (The choice of filenames makes it easy to run the set of Voronoi\n");
\r
2307 printf(" vertices through Triangle, if so desired.)\n\n");
\r
2309 " This implementation does not use exact arithmetic to compute the Voronoi\n"
\r
2312 " vertices, and does not check whether neighboring vertices are identical.\n"
\r
2315 " Be forewarned that if the Delaunay triangulation is degenerate or\n");
\r
2317 " near-degenerate, the Voronoi diagram may have duplicate points, crossing\n"
\r
2320 " edges, or infinite rays whose direction vector is zero. Also, if you\n");
\r
2322 " generate a constrained (as opposed to conforming) Delaunay triangulation,\n"
\r
2325 " or if the triangulation has holes, the corresponding Voronoi diagram is\n");
\r
2326 printf(" likely to have crossing edges and unlikely to make sense.\n\n");
\r
2327 printf("Mesh Topology:\n\n");
\r
2329 " You may wish to know which triangles are adjacent to a certain Delaunay\n");
\r
2331 " edge in an .edge file, which Voronoi regions are adjacent to a certain\n");
\r
2333 " Voronoi edge in a .v.edge file, or which Voronoi regions are adjacent to\n"
\r
2336 " each other. All of this information can be found by cross-referencing\n");
\r
2338 " output files with the recollection that the Delaunay triangulation and\n");
\r
2339 printf(" the Voronoi diagrams are planar duals.\n\n");
\r
2341 " Specifically, edge i of an .edge file is the dual of Voronoi edge i of\n");
\r
2343 " the corresponding .v.edge file, and is rotated 90 degrees counterclock-\n");
\r
2345 " wise from the Voronoi edge. Triangle j of an .ele file is the dual of\n");
\r
2347 " vertex j of the corresponding .v.node file; and Voronoi region k is the\n");
\r
2348 printf(" dual of point k of the corresponding .node file.\n\n");
\r
2350 " Hence, to find the triangles adjacent to a Delaunay edge, look at the\n");
\r
2352 " vertices of the corresponding Voronoi edge; their dual triangles are on\n");
\r
2354 " the left and right of the Delaunay edge, respectively. To find the\n");
\r
2356 " Voronoi regions adjacent to a Voronoi edge, look at the endpoints of the\n"
\r
2359 " corresponding Delaunay edge; their dual regions are on the right and left\n"
\r
2362 " of the Voronoi edge, respectively. To find which Voronoi regions are\n");
\r
2363 printf(" adjacent to each other, just read the list of Delaunay edges.\n");
\r
2365 printf("Statistics:\n");
\r
2368 " After generating a mesh, Triangle prints a count of the number of points,\n"
\r
2371 " triangles, edges, boundary edges, and segments in the output mesh. If\n");
\r
2373 " you've forgotten the statistics for an existing mesh, the -rNEP switches\n"
\r
2376 " (or -rpNEP if you've got a .poly file for the existing mesh) will\n");
\r
2377 printf(" regenerate these statistics without writing any output.\n\n");
\r
2379 " The -V switch produces extended statistics, including a rough estimate\n");
\r
2381 " of memory use and a histogram of triangle aspect ratios and angles in the\n"
\r
2383 printf(" mesh.\n\n");
\r
2384 printf("Exact Arithmetic:\n\n");
\r
2386 " Triangle uses adaptive exact arithmetic to perform what computational\n");
\r
2388 " geometers call the `orientation' and `incircle' tests. If the floating-\n"
\r
2391 " point arithmetic of your machine conforms to the IEEE 754 standard (as\n");
\r
2393 " most workstations do), and does not use extended precision internal\n");
\r
2395 " registers, then your output is guaranteed to be an absolutely true\n");
\r
2396 printf(" Delaunay or conforming Delaunay triangulation, roundoff error\n");
\r
2398 " notwithstanding. The word `adaptive' implies that these arithmetic\n");
\r
2400 " routines compute the result only to the precision necessary to guarantee\n"
\r
2403 " correctness, so they are usually nearly as fast as their approximate\n");
\r
2405 " counterparts. The exact tests can be disabled with the -X switch. On\n");
\r
2407 " most inputs, this switch will reduce the computation time by about eight\n"
\r
2410 " percent - it's not worth the risk. There are rare difficult inputs\n");
\r
2412 " (having many collinear and cocircular points), however, for which the\n");
\r
2414 " difference could be a factor of two. These are precisely the inputs most\n"
\r
2416 printf(" likely to cause errors if you use the -X switch.\n\n");
\r
2418 " Unfortunately, these routines don't solve every numerical problem. Exact\n"
\r
2421 " arithmetic is not used to compute the positions of points, because the\n");
\r
2423 " bit complexity of point coordinates would grow without bound. Hence,\n");
\r
2425 " segment intersections aren't computed exactly; in very unusual cases,\n");
\r
2427 " roundoff error in computing an intersection point might actually lead to\n"
\r
2430 " an inverted triangle and an invalid triangulation. (This is one reason\n");
\r
2432 " to compute your own intersection points in your .poly files.) Similarly,\n"
\r
2435 " exact arithmetic is not used to compute the vertices of the Voronoi\n");
\r
2436 printf(" diagram.\n\n");
\r
2438 " Underflow and overflow can also cause difficulties; the exact arithmetic\n"
\r
2441 " routines do not ameliorate out-of-bounds exponents, which can arise\n");
\r
2443 " during the orientation and incircle tests. As a rule of thumb, you\n");
\r
2445 " should ensure that your input values are within a range such that their\n");
\r
2447 " third powers can be taken without underflow or overflow. Underflow can\n");
\r
2449 " silently prevent the tests from being performed exactly, while overflow\n");
\r
2450 printf(" will typically cause a floating exception.\n\n");
\r
2451 printf("Calling Triangle from Another Program:\n\n");
\r
2452 printf(" Read the file triangle.h for details.\n\n");
\r
2453 printf("Troubleshooting:\n\n");
\r
2454 printf(" Please read this section before mailing me bugs.\n\n");
\r
2455 printf(" `My output mesh has no triangles!'\n\n");
\r
2457 " If you're using a PSLG, you've probably failed to specify a proper set\n"
\r
2460 " of bounding segments, or forgotten to use the -c switch. Or you may\n");
\r
2462 " have placed a hole badly. To test these possibilities, try again with\n"
\r
2465 " the -c and -O switches. Alternatively, all your input points may be\n");
\r
2467 " collinear, in which case you can hardly expect to triangulate them.\n");
\r
2469 printf(" `Triangle doesn't terminate, or just crashes.'\n");
\r
2472 " Bad things can happen when triangles get so small that the distance\n");
\r
2474 " between their vertices isn't much larger than the precision of your\n");
\r
2476 " machine's arithmetic. If you've compiled Triangle for single-precision\n"
\r
2479 " arithmetic, you might do better by recompiling it for double-precision.\n"
\r
2482 " Then again, you might just have to settle for more lenient constraints\n"
\r
2485 " on the minimum angle and the maximum area than you had planned.\n");
\r
2488 " You can minimize precision problems by ensuring that the origin lies\n");
\r
2490 " inside your point set, or even inside the densest part of your\n");
\r
2492 " mesh. On the other hand, if you're triangulating an object whose x\n");
\r
2494 " coordinates all fall between 6247133 and 6247134, you're not leaving\n");
\r
2495 printf(" much floating-point precision for Triangle to work with.\n\n");
\r
2497 " Precision problems can occur covertly if the input PSLG contains two\n");
\r
2499 " segments that meet (or intersect) at a very small angle, or if such an\n"
\r
2502 " angle is introduced by the -c switch, which may occur if a point lies\n");
\r
2504 " ever-so-slightly inside the convex hull, and is connected by a PSLG\n");
\r
2506 " segment to a point on the convex hull. If you don't realize that a\n");
\r
2508 " small angle is being formed, you might never discover why Triangle is\n");
\r
2510 " crashing. To check for this possibility, use the -S switch (with an\n");
\r
2512 " appropriate limit on the number of Steiner points, found by trial-and-\n"
\r
2515 " error) to stop Triangle early, and view the output .poly file with\n");
\r
2517 " Show Me (described below). Look carefully for small angles between\n");
\r
2519 " segments; zoom in closely, as such segments might look like a single\n");
\r
2520 printf(" segment from a distance.\n\n");
\r
2522 " If some of the input values are too large, Triangle may suffer a\n");
\r
2524 " floating exception due to overflow when attempting to perform an\n");
\r
2526 " orientation or incircle test. (Read the section on exact arithmetic\n");
\r
2528 " above.) Again, I recommend compiling Triangle for double (rather\n");
\r
2529 printf(" than single) precision arithmetic.\n\n");
\r
2531 " `The numbering of the output points doesn't match the input points.'\n");
\r
2534 " You may have eaten some of your input points with a hole, or by placing\n"
\r
2536 printf(" them outside the area enclosed by segments.\n\n");
\r
2538 " `Triangle executes without incident, but when I look at the resulting\n");
\r
2540 " mesh, it has overlapping triangles or other geometric inconsistencies.'\n");
\r
2543 " If you select the -X switch, Triangle's divide-and-conquer Delaunay\n");
\r
2545 " triangulation algorithm occasionally makes mistakes due to floating-\n");
\r
2547 " point roundoff error. Although these errors are rare, don't use the -X\n"
\r
2549 printf(" switch. If you still have problems, please report the bug.\n");
\r
2552 " Strange things can happen if you've taken liberties with your PSLG. Do\n");
\r
2554 " you have a point lying in the middle of a segment? Triangle sometimes\n");
\r
2556 " copes poorly with that sort of thing. Do you want to lay out a collinear\n"
\r
2559 " row of evenly spaced, segment-connected points? Have you simply defined\n"
\r
2562 " one long segment connecting the leftmost point to the rightmost point,\n");
\r
2564 " and a bunch of points lying along it? This method occasionally works,\n");
\r
2566 " especially with horizontal and vertical lines, but often it doesn't, and\n"
\r
2569 " you'll have to connect each adjacent pair of points with a separate\n");
\r
2570 printf(" segment. If you don't like it, tough.\n\n");
\r
2572 " Furthermore, if you have segments that intersect other than at their\n");
\r
2574 " endpoints, try not to let the intersections fall extremely close to PSLG\n"
\r
2576 printf(" points or each other.\n\n");
\r
2578 " If you have problems refining a triangulation not produced by Triangle:\n");
\r
2580 " Are you sure the triangulation is geometrically valid? Is it formatted\n");
\r
2582 " correctly for Triangle? Are the triangles all listed so the first three\n"
\r
2584 printf(" points are their corners in counterclockwise order?\n\n");
\r
2585 printf("Show Me:\n\n");
\r
2587 " Triangle comes with a separate program named `Show Me', whose primary\n");
\r
2589 " purpose is to draw meshes on your screen or in PostScript. Its secondary\n"
\r
2592 " purpose is to check the validity of your input files, and do so more\n");
\r
2594 " thoroughly than Triangle does. Show Me requires that you have the X\n");
\r
2596 " Windows system. If you didn't receive Show Me with Triangle, complain to\n"
\r
2598 printf(" whomever you obtained Triangle from, then send me mail.\n\n");
\r
2599 printf("Triangle on the Web:\n\n");
\r
2601 " To see an illustrated, updated version of these instructions, check out\n");
\r
2603 printf(" http://www.cs.cmu.edu/~quake/triangle.html\n");
\r
2605 printf("A Brief Plea:\n");
\r
2608 " If you use Triangle, and especially if you use it to accomplish real\n");
\r
2610 " work, I would like very much to hear from you. A short letter or email\n");
\r
2612 " (to jrs@cs.cmu.edu) describing how you use Triangle will mean a lot to\n");
\r
2614 " me. The more people I know are using this program, the more easily I can\n"
\r
2617 " justify spending time on improvements and on the three-dimensional\n");
\r
2619 " successor to Triangle, which in turn will benefit you. Also, I can put\n");
\r
2621 " you on a list to receive email whenever a new version of Triangle is\n");
\r
2622 printf(" available.\n\n");
\r
2624 " If you use a mesh generated by Triangle in a publication, please include\n"
\r
2626 printf(" an acknowledgment as well.\n\n");
\r
2627 printf("Research credit:\n\n");
\r
2629 " Of course, I can take credit for only a fraction of the ideas that made\n");
\r
2631 " this mesh generator possible. Triangle owes its existence to the efforts\n"
\r
2634 " of many fine computational geometers and other researchers, including\n");
\r
2636 " Marshall Bern, L. Paul Chew, Boris Delaunay, Rex A. Dwyer, David\n");
\r
2638 " Eppstein, Steven Fortune, Leonidas J. Guibas, Donald E. Knuth, C. L.\n");
\r
2640 " Lawson, Der-Tsai Lee, Ernst P. Mucke, Douglas M. Priest, Jim Ruppert,\n");
\r
2642 " Isaac Saias, Bruce J. Schachter, Micha Sharir, Jorge Stolfi, Christopher\n"
\r
2645 " J. Van Wyk, David F. Watson, and Binhai Zhu. See the comments at the\n");
\r
2646 printf(" beginning of the source code for references.\n\n");
\r
2650 #endif /* not TRILIBRARY */
\r
2652 /*****************************************************************************/
\r
2654 /* internalerror() Ask the user to send me the defective product. Exit. */
\r
2656 /*****************************************************************************/
\r
2658 void internalerror()
\r
2660 printf(" Please report this bug to jrs@cs.cmu.edu\n");
\r
2661 printf(" Include the message above, your input data set, and the exact\n");
\r
2662 printf(" command line you used to run Triangle.\n");
\r
2666 /*****************************************************************************/
\r
2668 /* parsecommandline() Read the command line, identify switches, and set */
\r
2669 /* up options and file names. */
\r
2671 /* The effects of this routine are felt entirely through global variables. */
\r
2673 /*****************************************************************************/
\r
2675 void parsecommandline(argc, argv)
\r
2680 #define STARTINDEX 0
\r
2681 #else /* not TRILIBRARY */
\r
2682 #define STARTINDEX 1
\r
2685 #endif /* not TRILIBRARY */
\r
2689 char workstring[FILENAMESIZE];
\r
2692 poly = refine = quality = vararea = fixedarea = regionattrib = convex = 0;
\r
2694 edgesout = voronoi = neighbors = geomview = 0;
\r
2695 nobound = nopolywritten = nonodewritten = noelewritten = noiterationnum = 0;
\r
2696 noholes = noexact = 0;
\r
2697 incremental = sweepline = 0;
\r
2706 quiet = verbose = 0;
\r
2707 #ifndef TRILIBRARY
\r
2708 innodefilename[0] = '\0';
\r
2709 #endif /* not TRILIBRARY */
\r
2711 for (i = STARTINDEX; i < argc; i++) {
\r
2712 #ifndef TRILIBRARY
\r
2713 if (argv[i][0] == '-') {
\r
2714 #endif /* not TRILIBRARY */
\r
2715 for (j = STARTINDEX; argv[i][j] != '\0'; j++) {
\r
2716 if (argv[i][j] == 'p') {
\r
2720 if (argv[i][j] == 'r') {
\r
2723 if (argv[i][j] == 'q') {
\r
2725 if (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) ||
\r
2726 (argv[i][j + 1] == '.')) {
\r
2728 while (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) ||
\r
2729 (argv[i][j + 1] == '.')) {
\r
2731 workstring[k] = argv[i][j];
\r
2734 workstring[k] = '\0';
\r
2735 minangle = (REAL) strtod(workstring, (char **) NULL);
\r
2740 if (argv[i][j] == 'a') {
\r
2742 if (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) ||
\r
2743 (argv[i][j + 1] == '.')) {
\r
2746 while (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) ||
\r
2747 (argv[i][j + 1] == '.')) {
\r
2749 workstring[k] = argv[i][j];
\r
2752 workstring[k] = '\0';
\r
2753 maxarea = (REAL) strtod(workstring, (char **) NULL);
\r
2754 if (maxarea <= 0.0) {
\r
2755 printf("Error: Maximum area must be greater than zero.\n");
\r
2762 #endif /* not CDT_ONLY */
\r
2763 if (argv[i][j] == 'A') {
\r
2766 if (argv[i][j] == 'c') {
\r
2769 if (argv[i][j] == 'z') {
\r
2772 if (argv[i][j] == 'e') {
\r
2775 if (argv[i][j] == 'v') {
\r
2778 if (argv[i][j] == 'n') {
\r
2781 if (argv[i][j] == 'g') {
\r
2784 if (argv[i][j] == 'B') {
\r
2787 if (argv[i][j] == 'P') {
\r
2788 nopolywritten = 1;
\r
2790 if (argv[i][j] == 'N') {
\r
2791 nonodewritten = 1;
\r
2793 if (argv[i][j] == 'E') {
\r
2796 #ifndef TRILIBRARY
\r
2797 if (argv[i][j] == 'I') {
\r
2798 noiterationnum = 1;
\r
2800 #endif /* not TRILIBRARY */
\r
2801 if (argv[i][j] == 'O') {
\r
2804 if (argv[i][j] == 'X') {
\r
2807 if (argv[i][j] == 'o') {
\r
2808 if (argv[i][j + 1] == '2') {
\r
2814 if (argv[i][j] == 'Y') {
\r
2817 if (argv[i][j] == 'S') {
\r
2819 while ((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) {
\r
2821 steiner = steiner * 10 + (int) (argv[i][j] - '0');
\r
2824 #endif /* not CDT_ONLY */
\r
2826 if (argv[i][j] == 'i') {
\r
2829 if (argv[i][j] == 'F') {
\r
2832 #endif /* not REDUCED */
\r
2833 if (argv[i][j] == 'l') {
\r
2838 if (argv[i][j] == 's') {
\r
2841 #endif /* not CDT_ONLY */
\r
2842 if (argv[i][j] == 'C') {
\r
2845 #endif /* not REDUCED */
\r
2846 if (argv[i][j] == 'Q') {
\r
2849 if (argv[i][j] == 'V') {
\r
2852 #ifndef TRILIBRARY
\r
2853 if ((argv[i][j] == 'h') || (argv[i][j] == 'H') ||
\r
2854 (argv[i][j] == '?')) {
\r
2857 #endif /* not TRILIBRARY */
\r
2859 #ifndef TRILIBRARY
\r
2861 strncpy(innodefilename, argv[i], FILENAMESIZE - 1);
\r
2862 innodefilename[FILENAMESIZE - 1] = '\0';
\r
2864 #endif /* not TRILIBRARY */
\r
2866 #ifndef TRILIBRARY
\r
2867 if (innodefilename[0] == '\0') {
\r
2870 if (!strcmp(&innodefilename[strlen(innodefilename) - 5], ".node")) {
\r
2871 innodefilename[strlen(innodefilename) - 5] = '\0';
\r
2873 if (!strcmp(&innodefilename[strlen(innodefilename) - 5], ".poly")) {
\r
2874 innodefilename[strlen(innodefilename) - 5] = '\0';
\r
2878 if (!strcmp(&innodefilename[strlen(innodefilename) - 4], ".ele")) {
\r
2879 innodefilename[strlen(innodefilename) - 4] = '\0';
\r
2882 if (!strcmp(&innodefilename[strlen(innodefilename) - 5], ".area")) {
\r
2883 innodefilename[strlen(innodefilename) - 5] = '\0';
\r
2888 #endif /* not CDT_ONLY */
\r
2889 #endif /* not TRILIBRARY */
\r
2890 steinerleft = steiner;
\r
2891 useshelles = poly || refine || quality || convex;
\r
2892 goodangle = (REAL)cos(minangle * PI / 180.0);
\r
2893 goodangle *= goodangle;
\r
2894 if (refine && noiterationnum) {
\r
2896 "Error: You cannot use the -I switch when refining a triangulation.\n");
\r
2899 /* Be careful not to allocate space for element area constraints that */
\r
2900 /* will never be assigned any value (other than the default -1.0). */
\r
2901 if (!refine && !poly) {
\r
2904 /* Be careful not to add an extra attribute to each element unless the */
\r
2905 /* input supports it (PSLG in, but not refining a preexisting mesh). */
\r
2906 if (refine || !poly) {
\r
2910 #ifndef TRILIBRARY
\r
2911 strcpy(inpolyfilename, innodefilename);
\r
2912 strcpy(inelefilename, innodefilename);
\r
2913 strcpy(areafilename, innodefilename);
\r
2915 strcpy(workstring, innodefilename);
\r
2917 while (workstring[j] != '\0') {
\r
2918 if ((workstring[j] == '.') && (workstring[j + 1] != '\0')) {
\r
2919 increment = j + 1;
\r
2924 if (increment > 0) {
\r
2927 if ((workstring[j] >= '0') && (workstring[j] <= '9')) {
\r
2928 meshnumber = meshnumber * 10 + (int) (workstring[j] - '0');
\r
2933 } while (workstring[j] != '\0');
\r
2935 if (noiterationnum) {
\r
2936 strcpy(outnodefilename, innodefilename);
\r
2937 strcpy(outelefilename, innodefilename);
\r
2938 strcpy(edgefilename, innodefilename);
\r
2939 strcpy(vnodefilename, innodefilename);
\r
2940 strcpy(vedgefilename, innodefilename);
\r
2941 strcpy(neighborfilename, innodefilename);
\r
2942 strcpy(offfilename, innodefilename);
\r
2943 strcat(outnodefilename, ".node");
\r
2944 strcat(outelefilename, ".ele");
\r
2945 strcat(edgefilename, ".edge");
\r
2946 strcat(vnodefilename, ".v.node");
\r
2947 strcat(vedgefilename, ".v.edge");
\r
2948 strcat(neighborfilename, ".neigh");
\r
2949 strcat(offfilename, ".off");
\r
2950 } else if (increment == 0) {
\r
2951 strcpy(outnodefilename, innodefilename);
\r
2952 strcpy(outpolyfilename, innodefilename);
\r
2953 strcpy(outelefilename, innodefilename);
\r
2954 strcpy(edgefilename, innodefilename);
\r
2955 strcpy(vnodefilename, innodefilename);
\r
2956 strcpy(vedgefilename, innodefilename);
\r
2957 strcpy(neighborfilename, innodefilename);
\r
2958 strcpy(offfilename, innodefilename);
\r
2959 strcat(outnodefilename, ".1.node");
\r
2960 strcat(outpolyfilename, ".1.poly");
\r
2961 strcat(outelefilename, ".1.ele");
\r
2962 strcat(edgefilename, ".1.edge");
\r
2963 strcat(vnodefilename, ".1.v.node");
\r
2964 strcat(vedgefilename, ".1.v.edge");
\r
2965 strcat(neighborfilename, ".1.neigh");
\r
2966 strcat(offfilename, ".1.off");
\r
2968 workstring[increment] = '%';
\r
2969 workstring[increment + 1] = 'd';
\r
2970 workstring[increment + 2] = '\0';
\r
2971 sprintf(outnodefilename, workstring, meshnumber + 1);
\r
2972 strcpy(outpolyfilename, outnodefilename);
\r
2973 strcpy(outelefilename, outnodefilename);
\r
2974 strcpy(edgefilename, outnodefilename);
\r
2975 strcpy(vnodefilename, outnodefilename);
\r
2976 strcpy(vedgefilename, outnodefilename);
\r
2977 strcpy(neighborfilename, outnodefilename);
\r
2978 strcpy(offfilename, outnodefilename);
\r
2979 strcat(outnodefilename, ".node");
\r
2980 strcat(outpolyfilename, ".poly");
\r
2981 strcat(outelefilename, ".ele");
\r
2982 strcat(edgefilename, ".edge");
\r
2983 strcat(vnodefilename, ".v.node");
\r
2984 strcat(vedgefilename, ".v.edge");
\r
2985 strcat(neighborfilename, ".neigh");
\r
2986 strcat(offfilename, ".off");
\r
2988 strcat(innodefilename, ".node");
\r
2989 strcat(inpolyfilename, ".poly");
\r
2990 strcat(inelefilename, ".ele");
\r
2991 strcat(areafilename, ".area");
\r
2992 #endif /* not TRILIBRARY */
\r
2997 /********* User interaction routines begin here *********/
\r
2999 /********* Debugging routines begin here *********/
\r
3003 /*****************************************************************************/
\r
3005 /* printtriangle() Print out the details of a triangle/edge handle. */
\r
3007 /* I originally wrote this procedure to simplify debugging; it can be */
\r
3008 /* called directly from the debugger, and presents information about a */
\r
3009 /* triangle/edge handle in digestible form. It's also used when the */
\r
3010 /* highest level of verbosity (`-VVV') is specified. */
\r
3012 /*****************************************************************************/
\r
3014 void printtriangle(t)
\r
3015 struct triedge *t;
\r
3017 struct triedge printtri;
\r
3018 struct edge printsh;
\r
3021 printf("triangle x%lx with orientation %d:\n", (unsigned long) t->tri,
\r
3023 decode(t->tri[0], printtri);
\r
3024 if (printtri.tri == dummytri) {
\r
3025 printf(" [0] = Outer space\n");
\r
3027 printf(" [0] = x%lx %d\n", (unsigned long) printtri.tri,
\r
3030 decode(t->tri[1], printtri);
\r
3031 if (printtri.tri == dummytri) {
\r
3032 printf(" [1] = Outer space\n");
\r
3034 printf(" [1] = x%lx %d\n", (unsigned long) printtri.tri,
\r
3037 decode(t->tri[2], printtri);
\r
3038 if (printtri.tri == dummytri) {
\r
3039 printf(" [2] = Outer space\n");
\r
3041 printf(" [2] = x%lx %d\n", (unsigned long) printtri.tri,
\r
3044 org(*t, printpoint);
\r
3045 if (printpoint == (point) NULL)
\r
3046 printf(" Origin[%d] = NULL\n", (t->orient + 1) % 3 + 3);
\r
3048 printf(" Origin[%d] = x%lx (%.12g, %.12g)\n",
\r
3049 (t->orient + 1) % 3 + 3, (unsigned long) printpoint,
\r
3050 printpoint[0], printpoint[1]);
\r
3051 dest(*t, printpoint);
\r
3052 if (printpoint == (point) NULL)
\r
3053 printf(" Dest [%d] = NULL\n", (t->orient + 2) % 3 + 3);
\r
3055 printf(" Dest [%d] = x%lx (%.12g, %.12g)\n",
\r
3056 (t->orient + 2) % 3 + 3, (unsigned long) printpoint,
\r
3057 printpoint[0], printpoint[1]);
\r
3058 apex(*t, printpoint);
\r
3059 if (printpoint == (point) NULL)
\r
3060 printf(" Apex [%d] = NULL\n", t->orient + 3);
\r
3062 printf(" Apex [%d] = x%lx (%.12g, %.12g)\n",
\r
3063 t->orient + 3, (unsigned long) printpoint,
\r
3064 printpoint[0], printpoint[1]);
\r
3066 sdecode(t->tri[6], printsh);
\r
3067 if (printsh.sh != dummysh) {
\r
3068 printf(" [6] = x%lx %d\n", (unsigned long) printsh.sh,
\r
3069 printsh.shorient);
\r
3071 sdecode(t->tri[7], printsh);
\r
3072 if (printsh.sh != dummysh) {
\r
3073 printf(" [7] = x%lx %d\n", (unsigned long) printsh.sh,
\r
3074 printsh.shorient);
\r
3076 sdecode(t->tri[8], printsh);
\r
3077 if (printsh.sh != dummysh) {
\r
3078 printf(" [8] = x%lx %d\n", (unsigned long) printsh.sh,
\r
3079 printsh.shorient);
\r
3083 printf(" Area constraint: %.4g\n", areabound(*t));
\r
3087 /*****************************************************************************/
\r
3089 /* printshelle() Print out the details of a shell edge handle. */
\r
3091 /* I originally wrote this procedure to simplify debugging; it can be */
\r
3092 /* called directly from the debugger, and presents information about a */
\r
3093 /* shell edge handle in digestible form. It's also used when the highest */
\r
3094 /* level of verbosity (`-VVV') is specified. */
\r
3096 /*****************************************************************************/
\r
3098 void printshelle(s)
\r
3101 struct edge printsh;
\r
3102 struct triedge printtri;
\r
3105 printf("shell edge x%lx with orientation %d and mark %d:\n",
\r
3106 (unsigned long) s->sh, s->shorient, mark(*s));
\r
3107 sdecode(s->sh[0], printsh);
\r
3108 if (printsh.sh == dummysh) {
\r
3109 printf(" [0] = No shell\n");
\r
3111 printf(" [0] = x%lx %d\n", (unsigned long) printsh.sh,
\r
3112 printsh.shorient);
\r
3114 sdecode(s->sh[1], printsh);
\r
3115 if (printsh.sh == dummysh) {
\r
3116 printf(" [1] = No shell\n");
\r
3118 printf(" [1] = x%lx %d\n", (unsigned long) printsh.sh,
\r
3119 printsh.shorient);
\r
3121 sorg(*s, printpoint);
\r
3122 if (printpoint == (point) NULL)
\r
3123 printf(" Origin[%d] = NULL\n", 2 + s->shorient);
\r
3125 printf(" Origin[%d] = x%lx (%.12g, %.12g)\n",
\r
3126 2 + s->shorient, (unsigned long) printpoint,
\r
3127 printpoint[0], printpoint[1]);
\r
3128 sdest(*s, printpoint);
\r
3129 if (printpoint == (point) NULL)
\r
3130 printf(" Dest [%d] = NULL\n", 3 - s->shorient);
\r
3132 printf(" Dest [%d] = x%lx (%.12g, %.12g)\n",
\r
3133 3 - s->shorient, (unsigned long) printpoint,
\r
3134 printpoint[0], printpoint[1]);
\r
3135 decode(s->sh[4], printtri);
\r
3136 if (printtri.tri == dummytri) {
\r
3137 printf(" [4] = Outer space\n");
\r
3139 printf(" [4] = x%lx %d\n", (unsigned long) printtri.tri,
\r
3142 decode(s->sh[5], printtri);
\r
3143 if (printtri.tri == dummytri) {
\r
3144 printf(" [5] = Outer space\n");
\r
3146 printf(" [5] = x%lx %d\n", (unsigned long) printtri.tri,
\r
3153 /********* Debugging routines end here *********/
\r
3155 /********* Memory management routines begin here *********/
\r
3159 /*****************************************************************************/
\r
3161 /* poolinit() Initialize a pool of memory for allocation of items. */
\r
3163 /* This routine initializes the machinery for allocating items. A `pool' */
\r
3164 /* is created whose records have size at least `bytecount'. Items will be */
\r
3165 /* allocated in `itemcount'-item blocks. Each item is assumed to be a */
\r
3166 /* collection of words, and either pointers or floating-point values are */
\r
3167 /* assumed to be the "primary" word type. (The "primary" word type is used */
\r
3168 /* to determine alignment of items.) If `alignment' isn't zero, all items */
\r
3169 /* will be `alignment'-byte aligned in memory. `alignment' must be either */
\r
3170 /* a multiple or a factor of the primary word size; powers of two are safe. */
\r
3171 /* `alignment' is normally used to create a few unused bits at the bottom */
\r
3172 /* of each item's pointer, in which information may be stored. */
\r
3174 /* Don't change this routine unless you understand it. */
\r
3176 /*****************************************************************************/
\r
3178 void poolinit(pool, bytecount, itemcount, wtype, alignment)
\r
3179 struct memorypool *pool;
\r
3182 enum wordtype wtype;
\r
3187 /* Initialize values in the pool. */
\r
3188 pool->itemwordtype = wtype;
\r
3189 wordsize = (pool->itemwordtype == POINTER) ? sizeof(VOID *) : sizeof(REAL);
\r
3190 /* Find the proper alignment, which must be at least as large as: */
\r
3191 /* - The parameter `alignment'. */
\r
3192 /* - The primary word type, to avoid unaligned accesses. */
\r
3193 /* - sizeof(VOID *), so the stack of dead items can be maintained */
\r
3194 /* without unaligned accesses. */
\r
3195 if (alignment > wordsize) {
\r
3196 pool->alignbytes = alignment;
\r
3198 pool->alignbytes = wordsize;
\r
3200 if (sizeof(VOID *) > pool->alignbytes) {
\r
3201 pool->alignbytes = sizeof(VOID *);
\r
3203 pool->itemwords = ((bytecount + pool->alignbytes - 1) / pool->alignbytes)
\r
3204 * (pool->alignbytes / wordsize);
\r
3205 pool->itembytes = pool->itemwords * wordsize;
\r
3206 pool->itemsperblock = itemcount;
\r
3208 /* Allocate a block of items. Space for `itemsperblock' items and one */
\r
3209 /* pointer (to point to the next block) are allocated, as well as space */
\r
3210 /* to ensure alignment of the items. */
\r
3211 pool->firstblock = (VOID **) malloc(pool->itemsperblock * pool->itembytes
\r
3212 + sizeof(VOID *) + pool->alignbytes);
\r
3213 if (pool->firstblock == (VOID **) NULL) {
\r
3214 printf("Error: Out of memory.\n");
\r
3217 /* Set the next block pointer to NULL. */
\r
3218 *(pool->firstblock) = (VOID *) NULL;
\r
3219 poolrestart(pool);
\r
3222 /*****************************************************************************/
\r
3224 /* poolrestart() Deallocate all items in a pool. */
\r
3226 /* The pool is returned to its starting state, except that no memory is */
\r
3227 /* freed to the operating system. Rather, the previously allocated blocks */
\r
3228 /* are ready to be reused. */
\r
3230 /*****************************************************************************/
\r
3232 void poolrestart(pool)
\r
3233 struct memorypool *pool;
\r
3235 unsigned long alignptr;
\r
3238 pool->maxitems = 0;
\r
3240 /* Set the currently active block. */
\r
3241 pool->nowblock = pool->firstblock;
\r
3242 /* Find the first item in the pool. Increment by the size of (VOID *). */
\r
3243 alignptr = (unsigned long) (pool->nowblock + 1);
\r
3244 /* Align the item on an `alignbytes'-byte boundary. */
\r
3245 pool->nextitem = (VOID *)
\r
3246 (alignptr + (unsigned long) pool->alignbytes
\r
3247 - (alignptr % (unsigned long) pool->alignbytes));
\r
3248 /* There are lots of unallocated items left in this block. */
\r
3249 pool->unallocateditems = pool->itemsperblock;
\r
3250 /* The stack of deallocated items is empty. */
\r
3251 pool->deaditemstack = (VOID *) NULL;
\r
3254 /*****************************************************************************/
\r
3256 /* pooldeinit() Free to the operating system all memory taken by a pool. */
\r
3258 /*****************************************************************************/
\r
3260 void pooldeinit(pool)
\r
3261 struct memorypool *pool;
\r
3263 while (pool->firstblock != (VOID **) NULL) {
\r
3264 pool->nowblock = (VOID **) *(pool->firstblock);
\r
3265 free(pool->firstblock);
\r
3266 pool->firstblock = pool->nowblock;
\r
3270 /*****************************************************************************/
\r
3272 /* poolalloc() Allocate space for an item. */
\r
3274 /*****************************************************************************/
\r
3276 VOID *poolalloc(pool)
\r
3277 struct memorypool *pool;
\r
3281 unsigned long alignptr;
\r
3283 /* First check the linked list of dead items. If the list is not */
\r
3284 /* empty, allocate an item from the list rather than a fresh one. */
\r
3285 if (pool->deaditemstack != (VOID *) NULL) {
\r
3286 newitem = pool->deaditemstack; /* Take first item in list. */
\r
3287 pool->deaditemstack = * (VOID **) pool->deaditemstack;
\r
3289 /* Check if there are any free items left in the current block. */
\r
3290 if (pool->unallocateditems == 0) {
\r
3291 /* Check if another block must be allocated. */
\r
3292 if (*(pool->nowblock) == (VOID *) NULL) {
\r
3293 /* Allocate a new block of items, pointed to by the previous block. */
\r
3294 newblock = (VOID **) malloc(pool->itemsperblock * pool->itembytes
\r
3295 + sizeof(VOID *) + pool->alignbytes);
\r
3296 if (newblock == (VOID **) NULL) {
\r
3297 printf("Error: Out of memory.\n");
\r
3300 *(pool->nowblock) = (VOID *) newblock;
\r
3301 /* The next block pointer is NULL. */
\r
3302 *newblock = (VOID *) NULL;
\r
3304 /* Move to the new block. */
\r
3305 pool->nowblock = (VOID **) *(pool->nowblock);
\r
3306 /* Find the first item in the block. */
\r
3307 /* Increment by the size of (VOID *). */
\r
3308 alignptr = (unsigned long) (pool->nowblock + 1);
\r
3309 /* Align the item on an `alignbytes'-byte boundary. */
\r
3310 pool->nextitem = (VOID *)
\r
3311 (alignptr + (unsigned long) pool->alignbytes
\r
3312 - (alignptr % (unsigned long) pool->alignbytes));
\r
3313 /* There are lots of unallocated items left in this block. */
\r
3314 pool->unallocateditems = pool->itemsperblock;
\r
3316 /* Allocate a new item. */
\r
3317 newitem = pool->nextitem;
\r
3318 /* Advance `nextitem' pointer to next free item in block. */
\r
3319 if (pool->itemwordtype == POINTER) {
\r
3320 pool->nextitem = (VOID *) ((VOID **) pool->nextitem + pool->itemwords);
\r
3322 pool->nextitem = (VOID *) ((REAL *) pool->nextitem + pool->itemwords);
\r
3324 pool->unallocateditems--;
\r
3331 /*****************************************************************************/
\r
3333 /* pooldealloc() Deallocate space for an item. */
\r
3335 /* The deallocated space is stored in a queue for later reuse. */
\r
3337 /*****************************************************************************/
\r
3339 void pooldealloc(pool, dyingitem)
\r
3340 struct memorypool *pool;
\r
3343 /* Push freshly killed item onto stack. */
\r
3344 *((VOID **) dyingitem) = pool->deaditemstack;
\r
3345 pool->deaditemstack = dyingitem;
\r
3349 /*****************************************************************************/
\r
3351 /* traversalinit() Prepare to traverse the entire list of items. */
\r
3353 /* This routine is used in conjunction with traverse(). */
\r
3355 /*****************************************************************************/
\r
3357 void traversalinit(pool)
\r
3358 struct memorypool *pool;
\r
3360 unsigned long alignptr;
\r
3362 /* Begin the traversal in the first block. */
\r
3363 pool->pathblock = pool->firstblock;
\r
3364 /* Find the first item in the block. Increment by the size of (VOID *). */
\r
3365 alignptr = (unsigned long) (pool->pathblock + 1);
\r
3366 /* Align with item on an `alignbytes'-byte boundary. */
\r
3367 pool->pathitem = (VOID *)
\r
3368 (alignptr + (unsigned long) pool->alignbytes
\r
3369 - (alignptr % (unsigned long) pool->alignbytes));
\r
3370 /* Set the number of items left in the current block. */
\r
3371 pool->pathitemsleft = pool->itemsperblock;
\r
3374 /*****************************************************************************/
\r
3376 /* traverse() Find the next item in the list. */
\r
3378 /* This routine is used in conjunction with traversalinit(). Be forewarned */
\r
3379 /* that this routine successively returns all items in the list, including */
\r
3380 /* deallocated ones on the deaditemqueue. It's up to you to figure out */
\r
3381 /* which ones are actually dead. Why? I don't want to allocate extra */
\r
3382 /* space just to demarcate dead items. It can usually be done more */
\r
3383 /* space-efficiently by a routine that knows something about the structure */
\r
3384 /* of the item. */
\r
3386 /*****************************************************************************/
\r
3388 VOID *traverse(pool)
\r
3389 struct memorypool *pool;
\r
3392 unsigned long alignptr;
\r
3394 /* Stop upon exhausting the list of items. */
\r
3395 if (pool->pathitem == pool->nextitem) {
\r
3396 return (VOID *) NULL;
\r
3398 /* Check whether any untraversed items remain in the current block. */
\r
3399 if (pool->pathitemsleft == 0) {
\r
3400 /* Find the next block. */
\r
3401 pool->pathblock = (VOID **) *(pool->pathblock);
\r
3402 /* Find the first item in the block. Increment by the size of (VOID *). */
\r
3403 alignptr = (unsigned long) (pool->pathblock + 1);
\r
3404 /* Align with item on an `alignbytes'-byte boundary. */
\r
3405 pool->pathitem = (VOID *)
\r
3406 (alignptr + (unsigned long) pool->alignbytes
\r
3407 - (alignptr % (unsigned long) pool->alignbytes));
\r
3408 /* Set the number of items left in the current block. */
\r
3409 pool->pathitemsleft = pool->itemsperblock;
\r
3411 newitem = pool->pathitem;
\r
3412 /* Find the next item in the block. */
\r
3413 if (pool->itemwordtype == POINTER) {
\r
3414 pool->pathitem = (VOID *) ((VOID **) pool->pathitem + pool->itemwords);
\r
3416 pool->pathitem = (VOID *) ((REAL *) pool->pathitem + pool->itemwords);
\r
3418 pool->pathitemsleft--;
\r
3422 /*****************************************************************************/
\r
3424 /* dummyinit() Initialize the triangle that fills "outer space" and the */
\r
3425 /* omnipresent shell edge. */
\r
3427 /* The triangle that fills "outer space", called `dummytri', is pointed to */
\r
3428 /* by every triangle and shell edge on a boundary (be it outer or inner) of */
\r
3429 /* the triangulation. Also, `dummytri' points to one of the triangles on */
\r
3430 /* the convex hull (until the holes and concavities are carved), making it */
\r
3431 /* possible to find a starting triangle for point location. */
\r
3433 /* The omnipresent shell edge, `dummysh', is pointed to by every triangle */
\r
3434 /* or shell edge that doesn't have a full complement of real shell edges */
\r
3435 /* to point to. */
\r
3437 /*****************************************************************************/
\r
3439 void dummyinit(trianglewords, shellewords)
\r
3440 int trianglewords;
\r
3443 unsigned long alignptr;
\r
3445 /* `triwords' and `shwords' are used by the mesh manipulation primitives */
\r
3446 /* to extract orientations of triangles and shell edges from pointers. */
\r
3447 triwords = trianglewords; /* Initialize `triwords' once and for all. */
\r
3448 shwords = shellewords; /* Initialize `shwords' once and for all. */
\r
3450 /* Set up `dummytri', the `triangle' that occupies "outer space". */
\r
3451 dummytribase = (triangle *) malloc(triwords * sizeof(triangle)
\r
3452 + triangles.alignbytes);
\r
3453 if (dummytribase == (triangle *) NULL) {
\r
3454 printf("Error: Out of memory.\n");
\r
3457 /* Align `dummytri' on a `triangles.alignbytes'-byte boundary. */
\r
3458 alignptr = (unsigned long) dummytribase;
\r
3459 dummytri = (triangle *)
\r
3460 (alignptr + (unsigned long) triangles.alignbytes
\r
3461 - (alignptr % (unsigned long) triangles.alignbytes));
\r
3462 /* Initialize the three adjoining triangles to be "outer space". These */
\r
3463 /* will eventually be changed by various bonding operations, but their */
\r
3464 /* values don't really matter, as long as they can legally be */
\r
3465 /* dereferenced. */
\r
3466 dummytri[0] = (triangle) dummytri;
\r
3467 dummytri[1] = (triangle) dummytri;
\r
3468 dummytri[2] = (triangle) dummytri;
\r
3469 /* Three NULL vertex points. */
\r
3470 dummytri[3] = (triangle) NULL;
\r
3471 dummytri[4] = (triangle) NULL;
\r
3472 dummytri[5] = (triangle) NULL;
\r
3475 /* Set up `dummysh', the omnipresent "shell edge" pointed to by any */
\r
3476 /* triangle side or shell edge end that isn't attached to a real shell */
\r
3478 dummyshbase = (shelle *) malloc(shwords * sizeof(shelle)
\r
3479 + shelles.alignbytes);
\r
3480 if (dummyshbase == (shelle *) NULL) {
\r
3481 printf("Error: Out of memory.\n");
\r
3484 /* Align `dummysh' on a `shelles.alignbytes'-byte boundary. */
\r
3485 alignptr = (unsigned long) dummyshbase;
\r
3486 dummysh = (shelle *)
\r
3487 (alignptr + (unsigned long) shelles.alignbytes
\r
3488 - (alignptr % (unsigned long) shelles.alignbytes));
\r
3489 /* Initialize the two adjoining shell edges to be the omnipresent shell */
\r
3490 /* edge. These will eventually be changed by various bonding */
\r
3491 /* operations, but their values don't really matter, as long as they */
\r
3492 /* can legally be dereferenced. */
\r
3493 dummysh[0] = (shelle) dummysh;
\r
3494 dummysh[1] = (shelle) dummysh;
\r
3495 /* Two NULL vertex points. */
\r
3496 dummysh[2] = (shelle) NULL;
\r
3497 dummysh[3] = (shelle) NULL;
\r
3498 /* Initialize the two adjoining triangles to be "outer space". */
\r
3499 dummysh[4] = (shelle) dummytri;
\r
3500 dummysh[5] = (shelle) dummytri;
\r
3501 /* Set the boundary marker to zero. */
\r
3502 * (int *) (dummysh + 6) = 0;
\r
3504 /* Initialize the three adjoining shell edges of `dummytri' to be */
\r
3505 /* the omnipresent shell edge. */
\r
3506 dummytri[6] = (triangle) dummysh;
\r
3507 dummytri[7] = (triangle) dummysh;
\r
3508 dummytri[8] = (triangle) dummysh;
\r
3512 /*****************************************************************************/
\r
3514 /* initializepointpool() Calculate the size of the point data structure */
\r
3515 /* and initialize its memory pool. */
\r
3517 /* This routine also computes the `pointmarkindex' and `point2triindex' */
\r
3518 /* indices used to find values within each point. */
\r
3520 /*****************************************************************************/
\r
3522 void initializepointpool()
\r
3526 /* The index within each point at which the boundary marker is found. */
\r
3527 /* Ensure the point marker is aligned to a sizeof(int)-byte address. */
\r
3528 pointmarkindex = ((mesh_dim + nextras) * sizeof(REAL) + sizeof(int) - 1)
\r
3530 pointsize = (pointmarkindex + 1) * sizeof(int);
\r
3532 /* The index within each point at which a triangle pointer is found. */
\r
3533 /* Ensure the pointer is aligned to a sizeof(triangle)-byte address. */
\r
3534 point2triindex = (pointsize + sizeof(triangle) - 1) / sizeof(triangle);
\r
3535 pointsize = (point2triindex + 1) * sizeof(triangle);
\r
3537 /* Initialize the pool of points. */
\r
3538 poolinit(&points, pointsize, POINTPERBLOCK,
\r
3539 (sizeof(REAL) >= sizeof(triangle)) ? FLOATINGPOINT : POINTER, 0);
\r
3542 /*****************************************************************************/
\r
3544 /* initializetrisegpools() Calculate the sizes of the triangle and shell */
\r
3545 /* edge data structures and initialize their */
\r
3546 /* memory pools. */
\r
3548 /* This routine also computes the `highorderindex', `elemattribindex', and */
\r
3549 /* `areaboundindex' indices used to find values within each triangle. */
\r
3551 /*****************************************************************************/
\r
3553 void initializetrisegpools()
\r
3557 /* The index within each triangle at which the extra nodes (above three) */
\r
3558 /* associated with high order elements are found. There are three */
\r
3559 /* pointers to other triangles, three pointers to corners, and possibly */
\r
3560 /* three pointers to shell edges before the extra nodes. */
\r
3561 highorderindex = 6 + (useshelles * 3);
\r
3562 /* The number of bytes occupied by a triangle. */
\r
3563 trisize = ((order + 1) * (order + 2) / 2 + (highorderindex - 3)) *
\r
3565 /* The index within each triangle at which its attributes are found, */
\r
3566 /* where the index is measured in REALs. */
\r
3567 elemattribindex = (trisize + sizeof(REAL) - 1) / sizeof(REAL);
\r
3568 /* The index within each triangle at which the maximum area constraint */
\r
3569 /* is found, where the index is measured in REALs. Note that if the */
\r
3570 /* `regionattrib' flag is set, an additional attribute will be added. */
\r
3571 areaboundindex = elemattribindex + eextras + regionattrib;
\r
3572 /* If triangle attributes or an area bound are needed, increase the number */
\r
3573 /* of bytes occupied by a triangle. */
\r
3575 trisize = (areaboundindex + 1) * sizeof(REAL);
\r
3576 } else if (eextras + regionattrib > 0) {
\r
3577 trisize = areaboundindex * sizeof(REAL);
\r
3579 /* If a Voronoi diagram or triangle neighbor graph is requested, make */
\r
3580 /* sure there's room to store an integer index in each triangle. This */
\r
3581 /* integer index can occupy the same space as the shell edges or */
\r
3582 /* attributes or area constraint or extra nodes. */
\r
3583 if ((voronoi || neighbors) &&
\r
3584 (trisize < 6 * sizeof(triangle) + sizeof(int))) {
\r
3585 trisize = 6 * sizeof(triangle) + sizeof(int);
\r
3587 /* Having determined the memory size of a triangle, initialize the pool. */
\r
3588 poolinit(&triangles, trisize, TRIPERBLOCK, POINTER, 4);
\r
3591 /* Initialize the pool of shell edges. */
\r
3592 poolinit(&shelles, 6 * sizeof(triangle) + sizeof(int), SHELLEPERBLOCK,
\r
3595 /* Initialize the "outer space" triangle and omnipresent shell edge. */
\r
3596 dummyinit(triangles.itemwords, shelles.itemwords);
\r
3598 /* Initialize the "outer space" triangle. */
\r
3599 dummyinit(triangles.itemwords, 0);
\r
3603 /*****************************************************************************/
\r
3605 /* triangledealloc() Deallocate space for a triangle, marking it dead. */
\r
3607 /*****************************************************************************/
\r
3609 void triangledealloc(dyingtriangle)
\r
3610 triangle *dyingtriangle;
\r
3612 /* Set triangle's vertices to NULL. This makes it possible to */
\r
3613 /* detect dead triangles when traversing the list of all triangles. */
\r
3614 dyingtriangle[3] = (triangle) NULL;
\r
3615 dyingtriangle[4] = (triangle) NULL;
\r
3616 dyingtriangle[5] = (triangle) NULL;
\r
3617 pooldealloc(&triangles, (VOID *) dyingtriangle);
\r
3620 /*****************************************************************************/
\r
3622 /* triangletraverse() Traverse the triangles, skipping dead ones. */
\r
3624 /*****************************************************************************/
\r
3626 triangle *triangletraverse()
\r
3628 triangle *newtriangle;
\r
3631 newtriangle = (triangle *) traverse(&triangles);
\r
3632 if (newtriangle == (triangle *) NULL) {
\r
3633 return (triangle *) NULL;
\r
3635 } while (newtriangle[3] == (triangle) NULL); /* Skip dead ones. */
\r
3636 return newtriangle;
\r
3639 /*****************************************************************************/
\r
3641 /* shelledealloc() Deallocate space for a shell edge, marking it dead. */
\r
3643 /*****************************************************************************/
\r
3645 void shelledealloc(dyingshelle)
\r
3646 shelle *dyingshelle;
\r
3648 /* Set shell edge's vertices to NULL. This makes it possible to */
\r
3649 /* detect dead shells when traversing the list of all shells. */
\r
3650 dyingshelle[2] = (shelle) NULL;
\r
3651 dyingshelle[3] = (shelle) NULL;
\r
3652 pooldealloc(&shelles, (VOID *) dyingshelle);
\r
3655 /*****************************************************************************/
\r
3657 /* shelletraverse() Traverse the shell edges, skipping dead ones. */
\r
3659 /*****************************************************************************/
\r
3661 shelle *shelletraverse()
\r
3663 shelle *newshelle;
\r
3666 newshelle = (shelle *) traverse(&shelles);
\r
3667 if (newshelle == (shelle *) NULL) {
\r
3668 return (shelle *) NULL;
\r
3670 } while (newshelle[2] == (shelle) NULL); /* Skip dead ones. */
\r
3674 /*****************************************************************************/
\r
3676 /* pointdealloc() Deallocate space for a point, marking it dead. */
\r
3678 /*****************************************************************************/
\r
3680 void pointdealloc(dyingpoint)
\r
3683 /* Mark the point as dead. This makes it possible to detect dead points */
\r
3684 /* when traversing the list of all points. */
\r
3685 setpointmark(dyingpoint, DEADPOINT);
\r
3686 pooldealloc(&points, (VOID *) dyingpoint);
\r
3689 /*****************************************************************************/
\r
3691 /* pointtraverse() Traverse the points, skipping dead ones. */
\r
3693 /*****************************************************************************/
\r
3695 point pointtraverse()
\r
3700 newpoint = (point) traverse(&points);
\r
3701 if (newpoint == (point) NULL) {
\r
3702 return (point) NULL;
\r
3704 } while (pointmark(newpoint) == DEADPOINT); /* Skip dead ones. */
\r
3708 /*****************************************************************************/
\r
3710 /* badsegmentdealloc() Deallocate space for a bad segment, marking it */
\r
3713 /*****************************************************************************/
\r
3717 void badsegmentdealloc(dyingseg)
\r
3718 struct edge *dyingseg;
\r
3720 /* Set segment's orientation to -1. This makes it possible to */
\r
3721 /* detect dead segments when traversing the list of all segments. */
\r
3722 dyingseg->shorient = -1;
\r
3723 pooldealloc(&badsegments, (VOID *) dyingseg);
\r
3726 #endif /* not CDT_ONLY */
\r
3728 /*****************************************************************************/
\r
3730 /* badsegmenttraverse() Traverse the bad segments, skipping dead ones. */
\r
3732 /*****************************************************************************/
\r
3736 struct edge *badsegmenttraverse()
\r
3738 struct edge *newseg;
\r
3741 newseg = (struct edge *) traverse(&badsegments);
\r
3742 if (newseg == (struct edge *) NULL) {
\r
3743 return (struct edge *) NULL;
\r
3745 } while (newseg->shorient == -1); /* Skip dead ones. */
\r
3749 #endif /* not CDT_ONLY */
\r
3751 /*****************************************************************************/
\r
3753 /* getpoint() Get a specific point, by number, from the list. */
\r
3755 /* The first point is number 'firstnumber'. */
\r
3757 /* Note that this takes O(n) time (with a small constant, if POINTPERBLOCK */
\r
3758 /* is large). I don't care to take the trouble to make it work in constant */
\r
3761 /*****************************************************************************/
\r
3763 point getpoint(number)
\r
3768 unsigned long alignptr;
\r
3771 getblock = points.firstblock;
\r
3772 current = firstnumber;
\r
3773 /* Find the right block. */
\r
3774 while (current + points.itemsperblock <= number) {
\r
3775 getblock = (VOID **) *getblock;
\r
3776 current += points.itemsperblock;
\r
3778 /* Now find the right point. */
\r
3779 alignptr = (unsigned long) (getblock + 1);
\r
3780 foundpoint = (point) (alignptr + (unsigned long) points.alignbytes
\r
3781 - (alignptr % (unsigned long) points.alignbytes));
\r
3782 while (current < number) {
\r
3783 foundpoint += points.itemwords;
\r
3786 return foundpoint;
\r
3789 /*****************************************************************************/
\r
3791 /* triangledeinit() Free all remaining allocated memory. */
\r
3793 /*****************************************************************************/
\r
3795 void triangledeinit()
\r
3797 pooldeinit(&triangles);
\r
3798 free(dummytribase);
\r
3800 pooldeinit(&shelles);
\r
3801 free(dummyshbase);
\r
3803 pooldeinit(&points);
\r
3806 pooldeinit(&badsegments);
\r
3807 if ((minangle > 0.0) || vararea || fixedarea) {
\r
3808 pooldeinit(&badtriangles);
\r
3811 #endif /* not CDT_ONLY */
\r
3816 /********* Memory management routines end here *********/
\r
3818 /********* Constructors begin here *********/
\r
3822 /*****************************************************************************/
\r
3824 /* maketriangle() Create a new triangle with orientation zero. */
\r
3826 /*****************************************************************************/
\r
3828 void maketriangle(newtriedge)
\r
3829 struct triedge *newtriedge;
\r
3833 newtriedge->tri = (triangle *) poolalloc(&triangles);
\r
3834 /* Initialize the three adjoining triangles to be "outer space". */
\r
3835 newtriedge->tri[0] = (triangle) dummytri;
\r
3836 newtriedge->tri[1] = (triangle) dummytri;
\r
3837 newtriedge->tri[2] = (triangle) dummytri;
\r
3838 /* Three NULL vertex points. */
\r
3839 newtriedge->tri[3] = (triangle) NULL;
\r
3840 newtriedge->tri[4] = (triangle) NULL;
\r
3841 newtriedge->tri[5] = (triangle) NULL;
\r
3842 /* Initialize the three adjoining shell edges to be the omnipresent */
\r
3845 newtriedge->tri[6] = (triangle) dummysh;
\r
3846 newtriedge->tri[7] = (triangle) dummysh;
\r
3847 newtriedge->tri[8] = (triangle) dummysh;
\r
3849 for (i = 0; i < eextras; i++) {
\r
3850 setelemattribute(*newtriedge, i, 0.0);
\r
3853 setareabound(*newtriedge, -1.0);
\r
3856 newtriedge->orient = 0;
\r
3859 /*****************************************************************************/
\r
3861 /* makeshelle() Create a new shell edge with orientation zero. */
\r
3863 /*****************************************************************************/
\r
3865 void makeshelle(newedge)
\r
3866 struct edge *newedge;
\r
3868 newedge->sh = (shelle *) poolalloc(&shelles);
\r
3869 /* Initialize the two adjoining shell edges to be the omnipresent */
\r
3871 newedge->sh[0] = (shelle) dummysh;
\r
3872 newedge->sh[1] = (shelle) dummysh;
\r
3873 /* Two NULL vertex points. */
\r
3874 newedge->sh[2] = (shelle) NULL;
\r
3875 newedge->sh[3] = (shelle) NULL;
\r
3876 /* Initialize the two adjoining triangles to be "outer space". */
\r
3877 newedge->sh[4] = (shelle) dummytri;
\r
3878 newedge->sh[5] = (shelle) dummytri;
\r
3879 /* Set the boundary marker to zero. */
\r
3880 setmark(*newedge, 0);
\r
3882 newedge->shorient = 0;
\r
3887 /********* Constructors end here *********/
\r
3889 /********* Determinant evaluation routines begin here *********/
\r
3893 /* The adaptive exact arithmetic geometric predicates implemented herein are */
\r
3894 /* described in detail in my Technical Report CMU-CS-96-140. The complete */
\r
3895 /* reference is given in the header. */
\r
3897 /* Which of the following two methods of finding the absolute values is */
\r
3898 /* fastest is compiler-dependent. A few compilers can inline and optimize */
\r
3899 /* the fabs() call; but most will incur the overhead of a function call, */
\r
3900 /* which is disastrously slow. A faster way on IEEE machines might be to */
\r
3901 /* mask the appropriate bit, but that's difficult to do in C. */
\r
3903 #define Absolute(a) ((a) >= 0.0 ? (a) : -(a))
\r
3904 /* #define Absolute(a) fabs(a) */
\r
3906 /* Many of the operations are broken up into two pieces, a main part that */
\r
3907 /* performs an approximate operation, and a "tail" that computes the */
\r
3908 /* roundoff error of that operation. */
\r
3910 /* The operations Fast_Two_Sum(), Fast_Two_Diff(), Two_Sum(), Two_Diff(), */
\r
3911 /* Split(), and Two_Product() are all implemented as described in the */
\r
3912 /* reference. Each of these macros requires certain variables to be */
\r
3913 /* defined in the calling routine. The variables `bvirt', `c', `abig', */
\r
3914 /* `_i', `_j', `_k', `_l', `_m', and `_n' are declared `INEXACT' because */
\r
3915 /* they store the result of an operation that may incur roundoff error. */
\r
3916 /* The input parameter `x' (or the highest numbered `x_' parameter) must */
\r
3917 /* also be declared `INEXACT'. */
\r
3919 #define Fast_Two_Sum_Tail(a, b, x, y) \
\r
3923 #define Fast_Two_Sum(a, b, x, y) \
\r
3924 x = (REAL) (a + b); \
\r
3925 Fast_Two_Sum_Tail(a, b, x, y)
\r
3927 #define Two_Sum_Tail(a, b, x, y) \
\r
3928 bvirt = (REAL) (x - a); \
\r
3929 avirt = x - bvirt; \
\r
3930 bround = b - bvirt; \
\r
3931 around = a - avirt; \
\r
3932 y = around + bround
\r
3934 #define Two_Sum(a, b, x, y) \
\r
3935 x = (REAL) (a + b); \
\r
3936 Two_Sum_Tail(a, b, x, y)
\r
3938 #define Two_Diff_Tail(a, b, x, y) \
\r
3939 bvirt = (REAL) (a - x); \
\r
3940 avirt = x + bvirt; \
\r
3941 bround = bvirt - b; \
\r
3942 around = a - avirt; \
\r
3943 y = around + bround
\r
3945 #define Two_Diff(a, b, x, y) \
\r
3946 x = (REAL) (a - b); \
\r
3947 Two_Diff_Tail(a, b, x, y)
\r
3949 #define Split(a, ahi, alo) \
\r
3950 c = (REAL) (splitter * a); \
\r
3951 abig = (REAL) (c - a); \
\r
3952 ahi = (REAL)(c - abig); \
\r
3953 alo = (REAL)(a - ahi)
\r
3955 #define Two_Product_Tail(a, b, x, y) \
\r
3956 Split(a, ahi, alo); \
\r
3957 Split(b, bhi, blo); \
\r
3958 err1 = x - (ahi * bhi); \
\r
3959 err2 = err1 - (alo * bhi); \
\r
3960 err3 = err2 - (ahi * blo); \
\r
3961 y = (alo * blo) - err3
\r
3963 #define Two_Product(a, b, x, y) \
\r
3964 x = (REAL) (a * b); \
\r
3965 Two_Product_Tail(a, b, x, y)
\r
3967 /* Two_Product_Presplit() is Two_Product() where one of the inputs has */
\r
3968 /* already been split. Avoids redundant splitting. */
\r
3970 #define Two_Product_Presplit(a, b, bhi, blo, x, y) \
\r
3971 x = (REAL) (a * b); \
\r
3972 Split(a, ahi, alo); \
\r
3973 err1 = x - (ahi * bhi); \
\r
3974 err2 = err1 - (alo * bhi); \
\r
3975 err3 = err2 - (ahi * blo); \
\r
3976 y = (alo * blo) - err3
\r
3978 /* Square() can be done more quickly than Two_Product(). */
\r
3980 #define Square_Tail(a, x, y) \
\r
3981 Split(a, ahi, alo); \
\r
3982 err1 = x - (ahi * ahi); \
\r
3983 err3 = err1 - ((ahi + ahi) * alo); \
\r
3984 y = (alo * alo) - err3
\r
3986 #define Square(a, x, y) \
\r
3987 x = (REAL) (a * a); \
\r
3988 Square_Tail(a, x, y)
\r
3990 /* Macros for summing expansions of various fixed lengths. These are all */
\r
3991 /* unrolled versions of Expansion_Sum(). */
\r
3993 #define Two_One_Sum(a1, a0, b, x2, x1, x0) \
\r
3994 Two_Sum(a0, b , _i, x0); \
\r
3995 Two_Sum(a1, _i, x2, x1)
\r
3997 #define Two_One_Diff(a1, a0, b, x2, x1, x0) \
\r
3998 Two_Diff(a0, b , _i, x0); \
\r
3999 Two_Sum( a1, _i, x2, x1)
\r
4001 #define Two_Two_Sum(a1, a0, b1, b0, x3, x2, x1, x0) \
\r
4002 Two_One_Sum(a1, a0, b0, _j, _0, x0); \
\r
4003 Two_One_Sum(_j, _0, b1, x3, x2, x1)
\r
4005 #define Two_Two_Diff(a1, a0, b1, b0, x3, x2, x1, x0) \
\r
4006 Two_One_Diff(a1, a0, b0, _j, _0, x0); \
\r
4007 Two_One_Diff(_j, _0, b1, x3, x2, x1)
\r
4009 /*****************************************************************************/
\r
4011 /* exactinit() Initialize the variables used for exact arithmetic. */
\r
4013 /* `epsilon' is the largest power of two such that 1.0 + epsilon = 1.0 in */
\r
4014 /* floating-point arithmetic. `epsilon' bounds the relative roundoff */
\r
4015 /* error. It is used for floating-point error analysis. */
\r
4017 /* `splitter' is used to split floating-point numbers into two half- */
\r
4018 /* length significands for exact multiplication. */
\r
4020 /* I imagine that a highly optimizing compiler might be too smart for its */
\r
4021 /* own good, and somehow cause this routine to fail, if it pretends that */
\r
4022 /* floating-point arithmetic is too much like real arithmetic. */
\r
4024 /* Don't change this routine unless you fully understand it. */
\r
4026 /*****************************************************************************/
\r
4031 REAL check, lastcheck;
\r
4039 /* Repeatedly divide `epsilon' by two until it is too small to add to */
\r
4040 /* one without causing roundoff. (Also check if the sum is equal to */
\r
4041 /* the previous sum, for machines that round up instead of using exact */
\r
4042 /* rounding. Not that these routines will work on such machines anyway. */
\r
4044 lastcheck = check;
\r
4046 if (every_other) {
\r
4049 every_other = !every_other;
\r
4050 check = (REAL)(1.0 + epsilon);
\r
4051 } while ((check != 1.0) && (check != lastcheck));
\r
4053 if (verbose > 1) {
\r
4054 printf("Floating point roundoff is of magnitude %.17g\n", epsilon);
\r
4055 printf("Floating point splitter is %.17g\n", splitter);
\r
4057 /* Error bounds for orientation and incircle tests. */
\r
4058 resulterrbound = (REAL)((3.0 + 8.0 * epsilon) * epsilon);
\r
4059 ccwerrboundA = (REAL)((3.0 + 16.0 * epsilon) * epsilon);
\r
4060 ccwerrboundB = (REAL)((2.0 + 12.0 * epsilon) * epsilon);
\r
4061 ccwerrboundC = (REAL)((9.0 + 64.0 * epsilon) * epsilon * epsilon);
\r
4062 iccerrboundA = (REAL)((10.0 + 96.0 * epsilon) * epsilon);
\r
4063 iccerrboundB = (REAL)((4.0 + 48.0 * epsilon) * epsilon);
\r
4064 iccerrboundC = (REAL)((44.0 + 576.0 * epsilon) * epsilon * epsilon);
\r
4067 /*****************************************************************************/
\r
4069 /* fast_expansion_sum_zeroelim() Sum two expansions, eliminating zero */
\r
4070 /* components from the output expansion. */
\r
4072 /* Sets h = e + f. See my Robust Predicates paper for details. */
\r
4074 /* If round-to-even is used (as with IEEE 754), maintains the strongly */
\r
4075 /* nonoverlapping property. (That is, if e is strongly nonoverlapping, h */
\r
4076 /* will be also.) Does NOT maintain the nonoverlapping or nonadjacent */
\r
4079 /*****************************************************************************/
\r
4081 int fast_expansion_sum_zeroelim(elen, e, flen, f, h) /* h cannot be e or f. */
\r
4089 INEXACT REAL Qnew;
\r
4091 INEXACT REAL bvirt;
\r
4092 REAL avirt, bround, around;
\r
4093 int eindex, findex, hindex;
\r
4098 eindex = findex = 0;
\r
4099 if ((fnow > enow) == (fnow > -enow)) {
\r
4101 enow = e[++eindex];
\r
4104 fnow = f[++findex];
\r
4107 if ((eindex < elen) && (findex < flen)) {
\r
4108 if ((fnow > enow) == (fnow > -enow)) {
\r
4109 Fast_Two_Sum(enow, Q, Qnew, hh);
\r
4110 enow = e[++eindex];
\r
4112 Fast_Two_Sum(fnow, Q, Qnew, hh);
\r
4113 fnow = f[++findex];
\r
4119 while ((eindex < elen) && (findex < flen)) {
\r
4120 if ((fnow > enow) == (fnow > -enow)) {
\r
4121 Two_Sum(Q, enow, Qnew, hh);
\r
4122 enow = e[++eindex];
\r
4124 Two_Sum(Q, fnow, Qnew, hh);
\r
4125 fnow = f[++findex];
\r
4133 while (eindex < elen) {
\r
4134 Two_Sum(Q, enow, Qnew, hh);
\r
4135 enow = e[++eindex];
\r
4141 while (findex < flen) {
\r
4142 Two_Sum(Q, fnow, Qnew, hh);
\r
4143 fnow = f[++findex];
\r
4149 if ((Q != 0.0) || (hindex == 0)) {
\r
4155 /*****************************************************************************/
\r
4157 /* scale_expansion_zeroelim() Multiply an expansion by a scalar, */
\r
4158 /* eliminating zero components from the */
\r
4159 /* output expansion. */
\r
4161 /* Sets h = be. See my Robust Predicates paper for details. */
\r
4163 /* Maintains the nonoverlapping property. If round-to-even is used (as */
\r
4164 /* with IEEE 754), maintains the strongly nonoverlapping and nonadjacent */
\r
4165 /* properties as well. (That is, if e has one of these properties, so */
\r
4168 /*****************************************************************************/
\r
4170 int scale_expansion_zeroelim(elen, e, b, h) /* e and h cannot be the same. */
\r
4176 INEXACT REAL Q, sum;
\r
4178 INEXACT REAL product1;
\r
4180 int eindex, hindex;
\r
4182 INEXACT REAL bvirt;
\r
4183 REAL avirt, bround, around;
\r
4185 INEXACT REAL abig;
\r
4186 REAL ahi, alo, bhi, blo;
\r
4187 REAL err1, err2, err3;
\r
4189 Split(b, bhi, blo);
\r
4190 Two_Product_Presplit(e[0], b, bhi, blo, Q, hh);
\r
4195 for (eindex = 1; eindex < elen; eindex++) {
\r
4197 Two_Product_Presplit(enow, b, bhi, blo, product1, product0);
\r
4198 Two_Sum(Q, product0, sum, hh);
\r
4202 Fast_Two_Sum(product1, sum, Q, hh);
\r
4207 if ((Q != 0.0) || (hindex == 0)) {
\r
4213 /*****************************************************************************/
\r
4215 /* estimate() Produce a one-word estimate of an expansion's value. */
\r
4217 /* See my Robust Predicates paper for details. */
\r
4219 /*****************************************************************************/
\r
4221 REAL estimate(elen, e)
\r
4229 for (eindex = 1; eindex < elen; eindex++) {
\r
4235 /*****************************************************************************/
\r
4237 /* counterclockwise() Return a positive value if the points pa, pb, and */
\r
4238 /* pc occur in counterclockwise order; a negative */
\r
4239 /* value if they occur in clockwise order; and zero */
\r
4240 /* if they are collinear. The result is also a rough */
\r
4241 /* approximation of twice the signed area of the */
\r
4242 /* triangle defined by the three points. */
\r
4244 /* Uses exact arithmetic if necessary to ensure a correct answer. The */
\r
4245 /* result returned is the determinant of a matrix. This determinant is */
\r
4246 /* computed adaptively, in the sense that exact arithmetic is used only to */
\r
4247 /* the degree it is needed to ensure that the returned value has the */
\r
4248 /* correct sign. Hence, this function is usually quite fast, but will run */
\r
4249 /* more slowly when the input points are collinear or nearly so. */
\r
4251 /* See my Robust Predicates paper for details. */
\r
4253 /*****************************************************************************/
\r
4255 REAL counterclockwiseadapt(pa, pb, pc, detsum)
\r
4261 INEXACT REAL acx, acy, bcx, bcy;
\r
4262 REAL acxtail, acytail, bcxtail, bcytail;
\r
4263 INEXACT REAL detleft, detright;
\r
4264 REAL detlefttail, detrighttail;
\r
4265 REAL det, errbound;
\r
4266 REAL B[4], C1[8], C2[12], D[16];
\r
4268 int C1length, C2length, Dlength;
\r
4271 INEXACT REAL s1, t1;
\r
4274 INEXACT REAL bvirt;
\r
4275 REAL avirt, bround, around;
\r
4277 INEXACT REAL abig;
\r
4278 REAL ahi, alo, bhi, blo;
\r
4279 REAL err1, err2, err3;
\r
4280 INEXACT REAL _i, _j;
\r
4283 acx = (REAL) (pa[0] - pc[0]);
\r
4284 bcx = (REAL) (pb[0] - pc[0]);
\r
4285 acy = (REAL) (pa[1] - pc[1]);
\r
4286 bcy = (REAL) (pb[1] - pc[1]);
\r
4288 Two_Product(acx, bcy, detleft, detlefttail);
\r
4289 Two_Product(acy, bcx, detright, detrighttail);
\r
4291 Two_Two_Diff(detleft, detlefttail, detright, detrighttail,
\r
4292 B3, B[2], B[1], B[0]);
\r
4295 det = estimate(4, B);
\r
4296 errbound = (REAL)(ccwerrboundB * detsum);
\r
4297 if ((det >= errbound) || (-det >= errbound)) {
\r
4301 Two_Diff_Tail(pa[0], pc[0], acx, acxtail);
\r
4302 Two_Diff_Tail(pb[0], pc[0], bcx, bcxtail);
\r
4303 Two_Diff_Tail(pa[1], pc[1], acy, acytail);
\r
4304 Two_Diff_Tail(pb[1], pc[1], bcy, bcytail);
\r
4306 if ((acxtail == 0.0) && (acytail == 0.0)
\r
4307 && (bcxtail == 0.0) && (bcytail == 0.0)) {
\r
4311 errbound = (REAL)(ccwerrboundC * detsum + resulterrbound * Absolute(det));
\r
4312 det += (acx * bcytail + bcy * acxtail)
\r
4313 - (acy * bcxtail + bcx * acytail);
\r
4314 if ((det >= errbound) || (-det >= errbound)) {
\r
4318 Two_Product(acxtail, bcy, s1, s0);
\r
4319 Two_Product(acytail, bcx, t1, t0);
\r
4320 Two_Two_Diff(s1, s0, t1, t0, u3, u[2], u[1], u[0]);
\r
4322 C1length = fast_expansion_sum_zeroelim(4, B, 4, u, C1);
\r
4324 Two_Product(acx, bcytail, s1, s0);
\r
4325 Two_Product(acy, bcxtail, t1, t0);
\r
4326 Two_Two_Diff(s1, s0, t1, t0, u3, u[2], u[1], u[0]);
\r
4328 C2length = fast_expansion_sum_zeroelim(C1length, C1, 4, u, C2);
\r
4330 Two_Product(acxtail, bcytail, s1, s0);
\r
4331 Two_Product(acytail, bcxtail, t1, t0);
\r
4332 Two_Two_Diff(s1, s0, t1, t0, u3, u[2], u[1], u[0]);
\r
4334 Dlength = fast_expansion_sum_zeroelim(C2length, C2, 4, u, D);
\r
4336 return(D[Dlength - 1]);
\r
4339 REAL counterclockwise(pa, pb, pc)
\r
4344 REAL detleft, detright, det;
\r
4345 REAL detsum, errbound;
\r
4347 counterclockcount++;
\r
4349 detleft = (pa[0] - pc[0]) * (pb[1] - pc[1]);
\r
4350 detright = (pa[1] - pc[1]) * (pb[0] - pc[0]);
\r
4351 det = detleft - detright;
\r
4357 if (detleft > 0.0) {
\r
4358 if (detright <= 0.0) {
\r
4361 detsum = detleft + detright;
\r
4363 } else if (detleft < 0.0) {
\r
4364 if (detright >= 0.0) {
\r
4367 detsum = -detleft - detright;
\r
4373 errbound = ccwerrboundA * detsum;
\r
4374 if ((det >= errbound) || (-det >= errbound)) {
\r
4378 return counterclockwiseadapt(pa, pb, pc, detsum);
\r
4381 /*****************************************************************************/
\r
4383 /* incircle() Return a positive value if the point pd lies inside the */
\r
4384 /* circle passing through pa, pb, and pc; a negative value if */
\r
4385 /* it lies outside; and zero if the four points are cocircular.*/
\r
4386 /* The points pa, pb, and pc must be in counterclockwise */
\r
4387 /* order, or the sign of the result will be reversed. */
\r
4389 /* Uses exact arithmetic if necessary to ensure a correct answer. The */
\r
4390 /* result returned is the determinant of a matrix. This determinant is */
\r
4391 /* computed adaptively, in the sense that exact arithmetic is used only to */
\r
4392 /* the degree it is needed to ensure that the returned value has the */
\r
4393 /* correct sign. Hence, this function is usually quite fast, but will run */
\r
4394 /* more slowly when the input points are cocircular or nearly so. */
\r
4396 /* See my Robust Predicates paper for details. */
\r
4398 /*****************************************************************************/
\r
4400 REAL incircleadapt(pa, pb, pc, pd, permanent)
\r
4407 INEXACT REAL adx, bdx, cdx, ady, bdy, cdy;
\r
4408 REAL det, errbound;
\r
4410 INEXACT REAL bdxcdy1, cdxbdy1, cdxady1, adxcdy1, adxbdy1, bdxady1;
\r
4411 REAL bdxcdy0, cdxbdy0, cdxady0, adxcdy0, adxbdy0, bdxady0;
\r
4412 REAL bc[4], ca[4], ab[4];
\r
4413 INEXACT REAL bc3, ca3, ab3;
\r
4414 REAL axbc[8], axxbc[16], aybc[8], ayybc[16], adet[32];
\r
4415 int axbclen, axxbclen, aybclen, ayybclen, alen;
\r
4416 REAL bxca[8], bxxca[16], byca[8], byyca[16], bdet[32];
\r
4417 int bxcalen, bxxcalen, bycalen, byycalen, blen;
\r
4418 REAL cxab[8], cxxab[16], cyab[8], cyyab[16], cdet[32];
\r
4419 int cxablen, cxxablen, cyablen, cyyablen, clen;
\r
4422 REAL fin1[1152], fin2[1152];
\r
4423 REAL *finnow, *finother, *finswap;
\r
4426 REAL adxtail, bdxtail, cdxtail, adytail, bdytail, cdytail;
\r
4427 INEXACT REAL adxadx1, adyady1, bdxbdx1, bdybdy1, cdxcdx1, cdycdy1;
\r
4428 REAL adxadx0, adyady0, bdxbdx0, bdybdy0, cdxcdx0, cdycdy0;
\r
4429 REAL aa[4], bb[4], cc[4];
\r
4430 INEXACT REAL aa3, bb3, cc3;
\r
4431 INEXACT REAL ti1, tj1;
\r
4434 INEXACT REAL u3, v3;
\r
4435 REAL temp8[8], temp16a[16], temp16b[16], temp16c[16];
\r
4436 REAL temp32a[32], temp32b[32], temp48[48], temp64[64];
\r
4437 int temp8len, temp16alen, temp16blen, temp16clen;
\r
4438 int temp32alen, temp32blen, temp48len, temp64len;
\r
4439 REAL axtbb[8], axtcc[8], aytbb[8], aytcc[8];
\r
4440 int axtbblen, axtcclen, aytbblen, aytcclen;
\r
4441 REAL bxtaa[8], bxtcc[8], bytaa[8], bytcc[8];
\r
4442 int bxtaalen, bxtcclen, bytaalen, bytcclen;
\r
4443 REAL cxtaa[8], cxtbb[8], cytaa[8], cytbb[8];
\r
4444 int cxtaalen, cxtbblen, cytaalen, cytbblen;
\r
4445 REAL axtbc[8], aytbc[8], bxtca[8], bytca[8], cxtab[8], cytab[8];
\r
4446 int axtbclen, aytbclen, bxtcalen, bytcalen, cxtablen, cytablen;
\r
4447 REAL axtbct[16], aytbct[16], bxtcat[16], bytcat[16], cxtabt[16], cytabt[16];
\r
4448 int axtbctlen, aytbctlen, bxtcatlen, bytcatlen, cxtabtlen, cytabtlen;
\r
4449 REAL axtbctt[8], aytbctt[8], bxtcatt[8];
\r
4450 REAL bytcatt[8], cxtabtt[8], cytabtt[8];
\r
4451 int axtbcttlen, aytbcttlen, bxtcattlen, bytcattlen, cxtabttlen, cytabttlen;
\r
4452 REAL abt[8], bct[8], cat[8];
\r
4453 int abtlen, bctlen, catlen;
\r
4454 REAL abtt[4], bctt[4], catt[4];
\r
4455 int abttlen, bcttlen, cattlen;
\r
4456 INEXACT REAL abtt3, bctt3, catt3;
\r
4459 INEXACT REAL bvirt;
\r
4460 REAL avirt, bround, around;
\r
4462 INEXACT REAL abig;
\r
4463 REAL ahi, alo, bhi, blo;
\r
4464 REAL err1, err2, err3;
\r
4465 INEXACT REAL _i, _j;
\r
4468 adx = (REAL) (pa[0] - pd[0]);
\r
4469 bdx = (REAL) (pb[0] - pd[0]);
\r
4470 cdx = (REAL) (pc[0] - pd[0]);
\r
4471 ady = (REAL) (pa[1] - pd[1]);
\r
4472 bdy = (REAL) (pb[1] - pd[1]);
\r
4473 cdy = (REAL) (pc[1] - pd[1]);
\r
4475 Two_Product(bdx, cdy, bdxcdy1, bdxcdy0);
\r
4476 Two_Product(cdx, bdy, cdxbdy1, cdxbdy0);
\r
4477 Two_Two_Diff(bdxcdy1, bdxcdy0, cdxbdy1, cdxbdy0, bc3, bc[2], bc[1], bc[0]);
\r
4479 axbclen = scale_expansion_zeroelim(4, bc, adx, axbc);
\r
4480 axxbclen = scale_expansion_zeroelim(axbclen, axbc, adx, axxbc);
\r
4481 aybclen = scale_expansion_zeroelim(4, bc, ady, aybc);
\r
4482 ayybclen = scale_expansion_zeroelim(aybclen, aybc, ady, ayybc);
\r
4483 alen = fast_expansion_sum_zeroelim(axxbclen, axxbc, ayybclen, ayybc, adet);
\r
4485 Two_Product(cdx, ady, cdxady1, cdxady0);
\r
4486 Two_Product(adx, cdy, adxcdy1, adxcdy0);
\r
4487 Two_Two_Diff(cdxady1, cdxady0, adxcdy1, adxcdy0, ca3, ca[2], ca[1], ca[0]);
\r
4489 bxcalen = scale_expansion_zeroelim(4, ca, bdx, bxca);
\r
4490 bxxcalen = scale_expansion_zeroelim(bxcalen, bxca, bdx, bxxca);
\r
4491 bycalen = scale_expansion_zeroelim(4, ca, bdy, byca);
\r
4492 byycalen = scale_expansion_zeroelim(bycalen, byca, bdy, byyca);
\r
4493 blen = fast_expansion_sum_zeroelim(bxxcalen, bxxca, byycalen, byyca, bdet);
\r
4495 Two_Product(adx, bdy, adxbdy1, adxbdy0);
\r
4496 Two_Product(bdx, ady, bdxady1, bdxady0);
\r
4497 Two_Two_Diff(adxbdy1, adxbdy0, bdxady1, bdxady0, ab3, ab[2], ab[1], ab[0]);
\r
4499 cxablen = scale_expansion_zeroelim(4, ab, cdx, cxab);
\r
4500 cxxablen = scale_expansion_zeroelim(cxablen, cxab, cdx, cxxab);
\r
4501 cyablen = scale_expansion_zeroelim(4, ab, cdy, cyab);
\r
4502 cyyablen = scale_expansion_zeroelim(cyablen, cyab, cdy, cyyab);
\r
4503 clen = fast_expansion_sum_zeroelim(cxxablen, cxxab, cyyablen, cyyab, cdet);
\r
4505 ablen = fast_expansion_sum_zeroelim(alen, adet, blen, bdet, abdet);
\r
4506 finlength = fast_expansion_sum_zeroelim(ablen, abdet, clen, cdet, fin1);
\r
4508 det = estimate(finlength, fin1);
\r
4509 errbound = (REAL)(iccerrboundB * permanent);
\r
4510 if ((det >= errbound) || (-det >= errbound)) {
\r
4514 Two_Diff_Tail(pa[0], pd[0], adx, adxtail);
\r
4515 Two_Diff_Tail(pa[1], pd[1], ady, adytail);
\r
4516 Two_Diff_Tail(pb[0], pd[0], bdx, bdxtail);
\r
4517 Two_Diff_Tail(pb[1], pd[1], bdy, bdytail);
\r
4518 Two_Diff_Tail(pc[0], pd[0], cdx, cdxtail);
\r
4519 Two_Diff_Tail(pc[1], pd[1], cdy, cdytail);
\r
4520 if ((adxtail == 0.0) && (bdxtail == 0.0) && (cdxtail == 0.0)
\r
4521 && (adytail == 0.0) && (bdytail == 0.0) && (cdytail == 0.0)) {
\r
4525 errbound = (REAL)(iccerrboundC * permanent + resulterrbound * Absolute(det));
\r
4526 det += (REAL)(((adx * adx + ady * ady) * ((bdx * cdytail + cdy * bdxtail)
\r
4527 - (bdy * cdxtail + cdx * bdytail))
\r
4528 + 2.0 * (adx * adxtail + ady * adytail) * (bdx * cdy - bdy * cdx))
\r
4529 + ((bdx * bdx + bdy * bdy) * ((cdx * adytail + ady * cdxtail)
\r
4530 - (cdy * adxtail + adx * cdytail))
\r
4531 + 2.0 * (bdx * bdxtail + bdy * bdytail) * (cdx * ady - cdy * adx))
\r
4532 + ((cdx * cdx + cdy * cdy) * ((adx * bdytail + bdy * adxtail)
\r
4533 - (ady * bdxtail + bdx * adytail))
\r
4534 + 2.0 * (cdx * cdxtail + cdy * cdytail) * (adx * bdy - ady * bdx)));
\r
4535 if ((det >= errbound) || (-det >= errbound)) {
\r
4542 if ((bdxtail != 0.0) || (bdytail != 0.0)
\r
4543 || (cdxtail != 0.0) || (cdytail != 0.0)) {
\r
4544 Square(adx, adxadx1, adxadx0);
\r
4545 Square(ady, adyady1, adyady0);
\r
4546 Two_Two_Sum(adxadx1, adxadx0, adyady1, adyady0, aa3, aa[2], aa[1], aa[0]);
\r
4549 if ((cdxtail != 0.0) || (cdytail != 0.0)
\r
4550 || (adxtail != 0.0) || (adytail != 0.0)) {
\r
4551 Square(bdx, bdxbdx1, bdxbdx0);
\r
4552 Square(bdy, bdybdy1, bdybdy0);
\r
4553 Two_Two_Sum(bdxbdx1, bdxbdx0, bdybdy1, bdybdy0, bb3, bb[2], bb[1], bb[0]);
\r
4556 if ((adxtail != 0.0) || (adytail != 0.0)
\r
4557 || (bdxtail != 0.0) || (bdytail != 0.0)) {
\r
4558 Square(cdx, cdxcdx1, cdxcdx0);
\r
4559 Square(cdy, cdycdy1, cdycdy0);
\r
4560 Two_Two_Sum(cdxcdx1, cdxcdx0, cdycdy1, cdycdy0, cc3, cc[2], cc[1], cc[0]);
\r
4564 if (adxtail != 0.0) {
\r
4565 axtbclen = scale_expansion_zeroelim(4, bc, adxtail, axtbc);
\r
4566 temp16alen = scale_expansion_zeroelim(axtbclen, axtbc, 2.0 * adx,
\r
4569 axtcclen = scale_expansion_zeroelim(4, cc, adxtail, axtcc);
\r
4570 temp16blen = scale_expansion_zeroelim(axtcclen, axtcc, bdy, temp16b);
\r
4572 axtbblen = scale_expansion_zeroelim(4, bb, adxtail, axtbb);
\r
4573 temp16clen = scale_expansion_zeroelim(axtbblen, axtbb, -cdy, temp16c);
\r
4575 temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
\r
4576 temp16blen, temp16b, temp32a);
\r
4577 temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
\r
4578 temp32alen, temp32a, temp48);
\r
4579 finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
\r
4580 temp48, finother);
\r
4581 finswap = finnow; finnow = finother; finother = finswap;
\r
4583 if (adytail != 0.0) {
\r
4584 aytbclen = scale_expansion_zeroelim(4, bc, adytail, aytbc);
\r
4585 temp16alen = scale_expansion_zeroelim(aytbclen, aytbc, 2.0 * ady,
\r
4588 aytbblen = scale_expansion_zeroelim(4, bb, adytail, aytbb);
\r
4589 temp16blen = scale_expansion_zeroelim(aytbblen, aytbb, cdx, temp16b);
\r
4591 aytcclen = scale_expansion_zeroelim(4, cc, adytail, aytcc);
\r
4592 temp16clen = scale_expansion_zeroelim(aytcclen, aytcc, -bdx, temp16c);
\r
4594 temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
\r
4595 temp16blen, temp16b, temp32a);
\r
4596 temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
\r
4597 temp32alen, temp32a, temp48);
\r
4598 finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
\r
4599 temp48, finother);
\r
4600 finswap = finnow; finnow = finother; finother = finswap;
\r
4602 if (bdxtail != 0.0) {
\r
4603 bxtcalen = scale_expansion_zeroelim(4, ca, bdxtail, bxtca);
\r
4604 temp16alen = scale_expansion_zeroelim(bxtcalen, bxtca, 2.0 * bdx,
\r
4607 bxtaalen = scale_expansion_zeroelim(4, aa, bdxtail, bxtaa);
\r
4608 temp16blen = scale_expansion_zeroelim(bxtaalen, bxtaa, cdy, temp16b);
\r
4610 bxtcclen = scale_expansion_zeroelim(4, cc, bdxtail, bxtcc);
\r
4611 temp16clen = scale_expansion_zeroelim(bxtcclen, bxtcc, -ady, temp16c);
\r
4613 temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
\r
4614 temp16blen, temp16b, temp32a);
\r
4615 temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
\r
4616 temp32alen, temp32a, temp48);
\r
4617 finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
\r
4618 temp48, finother);
\r
4619 finswap = finnow; finnow = finother; finother = finswap;
\r
4621 if (bdytail != 0.0) {
\r
4622 bytcalen = scale_expansion_zeroelim(4, ca, bdytail, bytca);
\r
4623 temp16alen = scale_expansion_zeroelim(bytcalen, bytca, 2.0 * bdy,
\r
4626 bytcclen = scale_expansion_zeroelim(4, cc, bdytail, bytcc);
\r
4627 temp16blen = scale_expansion_zeroelim(bytcclen, bytcc, adx, temp16b);
\r
4629 bytaalen = scale_expansion_zeroelim(4, aa, bdytail, bytaa);
\r
4630 temp16clen = scale_expansion_zeroelim(bytaalen, bytaa, -cdx, temp16c);
\r
4632 temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
\r
4633 temp16blen, temp16b, temp32a);
\r
4634 temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
\r
4635 temp32alen, temp32a, temp48);
\r
4636 finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
\r
4637 temp48, finother);
\r
4638 finswap = finnow; finnow = finother; finother = finswap;
\r
4640 if (cdxtail != 0.0) {
\r
4641 cxtablen = scale_expansion_zeroelim(4, ab, cdxtail, cxtab);
\r
4642 temp16alen = scale_expansion_zeroelim(cxtablen, cxtab, 2.0 * cdx,
\r
4645 cxtbblen = scale_expansion_zeroelim(4, bb, cdxtail, cxtbb);
\r
4646 temp16blen = scale_expansion_zeroelim(cxtbblen, cxtbb, ady, temp16b);
\r
4648 cxtaalen = scale_expansion_zeroelim(4, aa, cdxtail, cxtaa);
\r
4649 temp16clen = scale_expansion_zeroelim(cxtaalen, cxtaa, -bdy, temp16c);
\r
4651 temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
\r
4652 temp16blen, temp16b, temp32a);
\r
4653 temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
\r
4654 temp32alen, temp32a, temp48);
\r
4655 finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
\r
4656 temp48, finother);
\r
4657 finswap = finnow; finnow = finother; finother = finswap;
\r
4659 if (cdytail != 0.0) {
\r
4660 cytablen = scale_expansion_zeroelim(4, ab, cdytail, cytab);
\r
4661 temp16alen = scale_expansion_zeroelim(cytablen, cytab, 2.0 * cdy,
\r
4664 cytaalen = scale_expansion_zeroelim(4, aa, cdytail, cytaa);
\r
4665 temp16blen = scale_expansion_zeroelim(cytaalen, cytaa, bdx, temp16b);
\r
4667 cytbblen = scale_expansion_zeroelim(4, bb, cdytail, cytbb);
\r
4668 temp16clen = scale_expansion_zeroelim(cytbblen, cytbb, -adx, temp16c);
\r
4670 temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
\r
4671 temp16blen, temp16b, temp32a);
\r
4672 temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
\r
4673 temp32alen, temp32a, temp48);
\r
4674 finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
\r
4675 temp48, finother);
\r
4676 finswap = finnow; finnow = finother; finother = finswap;
\r
4679 if ((adxtail != 0.0) || (adytail != 0.0)) {
\r
4680 if ((bdxtail != 0.0) || (bdytail != 0.0)
\r
4681 || (cdxtail != 0.0) || (cdytail != 0.0)) {
\r
4682 Two_Product(bdxtail, cdy, ti1, ti0);
\r
4683 Two_Product(bdx, cdytail, tj1, tj0);
\r
4684 Two_Two_Sum(ti1, ti0, tj1, tj0, u3, u[2], u[1], u[0]);
\r
4687 Two_Product(cdxtail, negate, ti1, ti0);
\r
4688 negate = -bdytail;
\r
4689 Two_Product(cdx, negate, tj1, tj0);
\r
4690 Two_Two_Sum(ti1, ti0, tj1, tj0, v3, v[2], v[1], v[0]);
\r
4692 bctlen = fast_expansion_sum_zeroelim(4, u, 4, v, bct);
\r
4694 Two_Product(bdxtail, cdytail, ti1, ti0);
\r
4695 Two_Product(cdxtail, bdytail, tj1, tj0);
\r
4696 Two_Two_Diff(ti1, ti0, tj1, tj0, bctt3, bctt[2], bctt[1], bctt[0]);
\r
4706 if (adxtail != 0.0) {
\r
4707 temp16alen = scale_expansion_zeroelim(axtbclen, axtbc, adxtail, temp16a);
\r
4708 axtbctlen = scale_expansion_zeroelim(bctlen, bct, adxtail, axtbct);
\r
4709 temp32alen = scale_expansion_zeroelim(axtbctlen, axtbct, 2.0 * adx,
\r
4711 temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
\r
4712 temp32alen, temp32a, temp48);
\r
4713 finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
\r
4714 temp48, finother);
\r
4715 finswap = finnow; finnow = finother; finother = finswap;
\r
4716 if (bdytail != 0.0) {
\r
4717 temp8len = scale_expansion_zeroelim(4, cc, adxtail, temp8);
\r
4718 temp16alen = scale_expansion_zeroelim(temp8len, temp8, bdytail,
\r
4720 finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
\r
4721 temp16a, finother);
\r
4722 finswap = finnow; finnow = finother; finother = finswap;
\r
4724 if (cdytail != 0.0) {
\r
4725 temp8len = scale_expansion_zeroelim(4, bb, -adxtail, temp8);
\r
4726 temp16alen = scale_expansion_zeroelim(temp8len, temp8, cdytail,
\r
4728 finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
\r
4729 temp16a, finother);
\r
4730 finswap = finnow; finnow = finother; finother = finswap;
\r
4733 temp32alen = scale_expansion_zeroelim(axtbctlen, axtbct, adxtail,
\r
4735 axtbcttlen = scale_expansion_zeroelim(bcttlen, bctt, adxtail, axtbctt);
\r
4736 temp16alen = scale_expansion_zeroelim(axtbcttlen, axtbctt, 2.0 * adx,
\r
4738 temp16blen = scale_expansion_zeroelim(axtbcttlen, axtbctt, adxtail,
\r
4740 temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
\r
4741 temp16blen, temp16b, temp32b);
\r
4742 temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
\r
4743 temp32blen, temp32b, temp64);
\r
4744 finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
\r
4745 temp64, finother);
\r
4746 finswap = finnow; finnow = finother; finother = finswap;
\r
4748 if (adytail != 0.0) {
\r
4749 temp16alen = scale_expansion_zeroelim(aytbclen, aytbc, adytail, temp16a);
\r
4750 aytbctlen = scale_expansion_zeroelim(bctlen, bct, adytail, aytbct);
\r
4751 temp32alen = scale_expansion_zeroelim(aytbctlen, aytbct, 2.0 * ady,
\r
4753 temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
\r
4754 temp32alen, temp32a, temp48);
\r
4755 finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
\r
4756 temp48, finother);
\r
4757 finswap = finnow; finnow = finother; finother = finswap;
\r
4760 temp32alen = scale_expansion_zeroelim(aytbctlen, aytbct, adytail,
\r
4762 aytbcttlen = scale_expansion_zeroelim(bcttlen, bctt, adytail, aytbctt);
\r
4763 temp16alen = scale_expansion_zeroelim(aytbcttlen, aytbctt, 2.0 * ady,
\r
4765 temp16blen = scale_expansion_zeroelim(aytbcttlen, aytbctt, adytail,
\r
4767 temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
\r
4768 temp16blen, temp16b, temp32b);
\r
4769 temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
\r
4770 temp32blen, temp32b, temp64);
\r
4771 finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
\r
4772 temp64, finother);
\r
4773 finswap = finnow; finnow = finother; finother = finswap;
\r
4776 if ((bdxtail != 0.0) || (bdytail != 0.0)) {
\r
4777 if ((cdxtail != 0.0) || (cdytail != 0.0)
\r
4778 || (adxtail != 0.0) || (adytail != 0.0)) {
\r
4779 Two_Product(cdxtail, ady, ti1, ti0);
\r
4780 Two_Product(cdx, adytail, tj1, tj0);
\r
4781 Two_Two_Sum(ti1, ti0, tj1, tj0, u3, u[2], u[1], u[0]);
\r
4784 Two_Product(adxtail, negate, ti1, ti0);
\r
4785 negate = -cdytail;
\r
4786 Two_Product(adx, negate, tj1, tj0);
\r
4787 Two_Two_Sum(ti1, ti0, tj1, tj0, v3, v[2], v[1], v[0]);
\r
4789 catlen = fast_expansion_sum_zeroelim(4, u, 4, v, cat);
\r
4791 Two_Product(cdxtail, adytail, ti1, ti0);
\r
4792 Two_Product(adxtail, cdytail, tj1, tj0);
\r
4793 Two_Two_Diff(ti1, ti0, tj1, tj0, catt3, catt[2], catt[1], catt[0]);
\r
4803 if (bdxtail != 0.0) {
\r
4804 temp16alen = scale_expansion_zeroelim(bxtcalen, bxtca, bdxtail, temp16a);
\r
4805 bxtcatlen = scale_expansion_zeroelim(catlen, cat, bdxtail, bxtcat);
\r
4806 temp32alen = scale_expansion_zeroelim(bxtcatlen, bxtcat, 2.0 * bdx,
\r
4808 temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
\r
4809 temp32alen, temp32a, temp48);
\r
4810 finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
\r
4811 temp48, finother);
\r
4812 finswap = finnow; finnow = finother; finother = finswap;
\r
4813 if (cdytail != 0.0) {
\r
4814 temp8len = scale_expansion_zeroelim(4, aa, bdxtail, temp8);
\r
4815 temp16alen = scale_expansion_zeroelim(temp8len, temp8, cdytail,
\r
4817 finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
\r
4818 temp16a, finother);
\r
4819 finswap = finnow; finnow = finother; finother = finswap;
\r
4821 if (adytail != 0.0) {
\r
4822 temp8len = scale_expansion_zeroelim(4, cc, -bdxtail, temp8);
\r
4823 temp16alen = scale_expansion_zeroelim(temp8len, temp8, adytail,
\r
4825 finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
\r
4826 temp16a, finother);
\r
4827 finswap = finnow; finnow = finother; finother = finswap;
\r
4830 temp32alen = scale_expansion_zeroelim(bxtcatlen, bxtcat, bdxtail,
\r
4832 bxtcattlen = scale_expansion_zeroelim(cattlen, catt, bdxtail, bxtcatt);
\r
4833 temp16alen = scale_expansion_zeroelim(bxtcattlen, bxtcatt, 2.0 * bdx,
\r
4835 temp16blen = scale_expansion_zeroelim(bxtcattlen, bxtcatt, bdxtail,
\r
4837 temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
\r
4838 temp16blen, temp16b, temp32b);
\r
4839 temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
\r
4840 temp32blen, temp32b, temp64);
\r
4841 finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
\r
4842 temp64, finother);
\r
4843 finswap = finnow; finnow = finother; finother = finswap;
\r
4845 if (bdytail != 0.0) {
\r
4846 temp16alen = scale_expansion_zeroelim(bytcalen, bytca, bdytail, temp16a);
\r
4847 bytcatlen = scale_expansion_zeroelim(catlen, cat, bdytail, bytcat);
\r
4848 temp32alen = scale_expansion_zeroelim(bytcatlen, bytcat, 2.0 * bdy,
\r
4850 temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
\r
4851 temp32alen, temp32a, temp48);
\r
4852 finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
\r
4853 temp48, finother);
\r
4854 finswap = finnow; finnow = finother; finother = finswap;
\r
4857 temp32alen = scale_expansion_zeroelim(bytcatlen, bytcat, bdytail,
\r
4859 bytcattlen = scale_expansion_zeroelim(cattlen, catt, bdytail, bytcatt);
\r
4860 temp16alen = scale_expansion_zeroelim(bytcattlen, bytcatt, 2.0 * bdy,
\r
4862 temp16blen = scale_expansion_zeroelim(bytcattlen, bytcatt, bdytail,
\r
4864 temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
\r
4865 temp16blen, temp16b, temp32b);
\r
4866 temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
\r
4867 temp32blen, temp32b, temp64);
\r
4868 finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
\r
4869 temp64, finother);
\r
4870 finswap = finnow; finnow = finother; finother = finswap;
\r
4873 if ((cdxtail != 0.0) || (cdytail != 0.0)) {
\r
4874 if ((adxtail != 0.0) || (adytail != 0.0)
\r
4875 || (bdxtail != 0.0) || (bdytail != 0.0)) {
\r
4876 Two_Product(adxtail, bdy, ti1, ti0);
\r
4877 Two_Product(adx, bdytail, tj1, tj0);
\r
4878 Two_Two_Sum(ti1, ti0, tj1, tj0, u3, u[2], u[1], u[0]);
\r
4881 Two_Product(bdxtail, negate, ti1, ti0);
\r
4882 negate = -adytail;
\r
4883 Two_Product(bdx, negate, tj1, tj0);
\r
4884 Two_Two_Sum(ti1, ti0, tj1, tj0, v3, v[2], v[1], v[0]);
\r
4886 abtlen = fast_expansion_sum_zeroelim(4, u, 4, v, abt);
\r
4888 Two_Product(adxtail, bdytail, ti1, ti0);
\r
4889 Two_Product(bdxtail, adytail, tj1, tj0);
\r
4890 Two_Two_Diff(ti1, ti0, tj1, tj0, abtt3, abtt[2], abtt[1], abtt[0]);
\r
4900 if (cdxtail != 0.0) {
\r
4901 temp16alen = scale_expansion_zeroelim(cxtablen, cxtab, cdxtail, temp16a);
\r
4902 cxtabtlen = scale_expansion_zeroelim(abtlen, abt, cdxtail, cxtabt);
\r
4903 temp32alen = scale_expansion_zeroelim(cxtabtlen, cxtabt, 2.0 * cdx,
\r
4905 temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
\r
4906 temp32alen, temp32a, temp48);
\r
4907 finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
\r
4908 temp48, finother);
\r
4909 finswap = finnow; finnow = finother; finother = finswap;
\r
4910 if (adytail != 0.0) {
\r
4911 temp8len = scale_expansion_zeroelim(4, bb, cdxtail, temp8);
\r
4912 temp16alen = scale_expansion_zeroelim(temp8len, temp8, adytail,
\r
4914 finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
\r
4915 temp16a, finother);
\r
4916 finswap = finnow; finnow = finother; finother = finswap;
\r
4918 if (bdytail != 0.0) {
\r
4919 temp8len = scale_expansion_zeroelim(4, aa, -cdxtail, temp8);
\r
4920 temp16alen = scale_expansion_zeroelim(temp8len, temp8, bdytail,
\r
4922 finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
\r
4923 temp16a, finother);
\r
4924 finswap = finnow; finnow = finother; finother = finswap;
\r
4927 temp32alen = scale_expansion_zeroelim(cxtabtlen, cxtabt, cdxtail,
\r
4929 cxtabttlen = scale_expansion_zeroelim(abttlen, abtt, cdxtail, cxtabtt);
\r
4930 temp16alen = scale_expansion_zeroelim(cxtabttlen, cxtabtt, 2.0 * cdx,
\r
4932 temp16blen = scale_expansion_zeroelim(cxtabttlen, cxtabtt, cdxtail,
\r
4934 temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
\r
4935 temp16blen, temp16b, temp32b);
\r
4936 temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
\r
4937 temp32blen, temp32b, temp64);
\r
4938 finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
\r
4939 temp64, finother);
\r
4940 finswap = finnow; finnow = finother; finother = finswap;
\r
4942 if (cdytail != 0.0) {
\r
4943 temp16alen = scale_expansion_zeroelim(cytablen, cytab, cdytail, temp16a);
\r
4944 cytabtlen = scale_expansion_zeroelim(abtlen, abt, cdytail, cytabt);
\r
4945 temp32alen = scale_expansion_zeroelim(cytabtlen, cytabt, 2.0 * cdy,
\r
4947 temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
\r
4948 temp32alen, temp32a, temp48);
\r
4949 finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
\r
4950 temp48, finother);
\r
4951 finswap = finnow; finnow = finother; finother = finswap;
\r
4954 temp32alen = scale_expansion_zeroelim(cytabtlen, cytabt, cdytail,
\r
4956 cytabttlen = scale_expansion_zeroelim(abttlen, abtt, cdytail, cytabtt);
\r
4957 temp16alen = scale_expansion_zeroelim(cytabttlen, cytabtt, 2.0 * cdy,
\r
4959 temp16blen = scale_expansion_zeroelim(cytabttlen, cytabtt, cdytail,
\r
4961 temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
\r
4962 temp16blen, temp16b, temp32b);
\r
4963 temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
\r
4964 temp32blen, temp32b, temp64);
\r
4965 finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
\r
4966 temp64, finother);
\r
4967 finswap = finnow; finnow = finother; finother = finswap;
\r
4971 return finnow[finlength - 1];
\r
4974 REAL incircle(pa, pb, pc, pd)
\r
4980 REAL adx, bdx, cdx, ady, bdy, cdy;
\r
4981 REAL bdxcdy, cdxbdy, cdxady, adxcdy, adxbdy, bdxady;
\r
4982 REAL alift, blift, clift;
\r
4984 REAL permanent, errbound;
\r
4988 adx = pa[0] - pd[0];
\r
4989 bdx = pb[0] - pd[0];
\r
4990 cdx = pc[0] - pd[0];
\r
4991 ady = pa[1] - pd[1];
\r
4992 bdy = pb[1] - pd[1];
\r
4993 cdy = pc[1] - pd[1];
\r
4995 bdxcdy = bdx * cdy;
\r
4996 cdxbdy = cdx * bdy;
\r
4997 alift = adx * adx + ady * ady;
\r
4999 cdxady = cdx * ady;
\r
5000 adxcdy = adx * cdy;
\r
5001 blift = bdx * bdx + bdy * bdy;
\r
5003 adxbdy = adx * bdy;
\r
5004 bdxady = bdx * ady;
\r
5005 clift = cdx * cdx + cdy * cdy;
\r
5007 det = alift * (bdxcdy - cdxbdy)
\r
5008 + blift * (cdxady - adxcdy)
\r
5009 + clift * (adxbdy - bdxady);
\r
5015 permanent = (Absolute(bdxcdy) + Absolute(cdxbdy)) * alift
\r
5016 + (Absolute(cdxady) + Absolute(adxcdy)) * blift
\r
5017 + (Absolute(adxbdy) + Absolute(bdxady)) * clift;
\r
5018 errbound = iccerrboundA * permanent;
\r
5019 if ((det > errbound) || (-det > errbound)) {
\r
5023 return incircleadapt(pa, pb, pc, pd, permanent);
\r
5028 /********* Determinant evaluation routines end here *********/
\r
5030 /*****************************************************************************/
\r
5032 /* triangleinit() Initialize some variables. */
\r
5034 /*****************************************************************************/
\r
5036 void triangleinit()
\r
5038 points.maxitems = triangles.maxitems = shelles.maxitems = viri.maxitems =
\r
5039 badsegments.maxitems = badtriangles.maxitems = splaynodes.maxitems = 0l;
\r
5040 points.itembytes = triangles.itembytes = shelles.itembytes = viri.itembytes =
\r
5041 badsegments.itembytes = badtriangles.itembytes = splaynodes.itembytes = 0;
\r
5042 recenttri.tri = (triangle *) NULL; /* No triangle has been visited yet. */
\r
5043 samples = 1; /* Point location should take at least one sample. */
\r
5044 checksegments = 0; /* There are no segments in the triangulation yet. */
\r
5045 incirclecount = counterclockcount = hyperbolacount = 0;
\r
5046 circumcentercount = circletopcount = 0;
\r
5049 exactinit(); /* Initialize exact arithmetic constants. */
\r
5052 /*****************************************************************************/
\r
5054 /* randomnation() Generate a random number between 0 and `choices' - 1. */
\r
5056 /* This is a simple linear congruential random number generator. Hence, it */
\r
5057 /* is a bad random number generator, but good enough for most randomized */
\r
5058 /* geometric algorithms. */
\r
5060 /*****************************************************************************/
\r
5062 unsigned long randomnation(choices)
\r
5063 unsigned int choices;
\r
5065 randomseed = (randomseed * 1366l + 150889l) % 714025l;
\r
5066 return randomseed / (714025l / choices + 1);
\r
5069 /********* Mesh quality testing routines begin here *********/
\r
5073 /*****************************************************************************/
\r
5075 /* checkmesh() Test the mesh for topological consistency. */
\r
5077 /*****************************************************************************/
\r
5083 struct triedge triangleloop;
\r
5084 struct triedge oppotri, oppooppotri;
\r
5085 point triorg, tridest, triapex;
\r
5086 point oppoorg, oppodest;
\r
5089 triangle ptr; /* Temporary variable used by sym(). */
\r
5091 /* Temporarily turn on exact arithmetic if it's off. */
\r
5092 saveexact = noexact;
\r
5095 printf(" Checking consistency of mesh...\n");
\r
5098 /* Run through the list of triangles, checking each one. */
\r
5099 traversalinit(&triangles);
\r
5100 triangleloop.tri = triangletraverse();
\r
5101 while (triangleloop.tri != (triangle *) NULL) {
\r
5102 /* Check all three edges of the triangle. */
\r
5103 for (triangleloop.orient = 0; triangleloop.orient < 3;
\r
5104 triangleloop.orient++) {
\r
5105 org(triangleloop, triorg);
\r
5106 dest(triangleloop, tridest);
\r
5107 if (triangleloop.orient == 0) { /* Only test for inversion once. */
\r
5108 /* Test if the triangle is flat or inverted. */
\r
5109 apex(triangleloop, triapex);
\r
5110 if (counterclockwise(triorg, tridest, triapex) <= 0.0) {
\r
5111 printf(" !! !! Inverted ");
\r
5112 printtriangle(&triangleloop);
\r
5116 /* Find the neighboring triangle on this edge. */
\r
5117 sym(triangleloop, oppotri);
\r
5118 if (oppotri.tri != dummytri) {
\r
5119 /* Check that the triangle's neighbor knows it's a neighbor. */
\r
5120 sym(oppotri, oppooppotri);
\r
5121 if ((triangleloop.tri != oppooppotri.tri)
\r
5122 || (triangleloop.orient != oppooppotri.orient)) {
\r
5123 printf(" !! !! Asymmetric triangle-triangle bond:\n");
\r
5124 if (triangleloop.tri == oppooppotri.tri) {
\r
5125 printf(" (Right triangle, wrong orientation)\n");
\r
5127 printf(" First ");
\r
5128 printtriangle(&triangleloop);
\r
5129 printf(" Second (nonreciprocating) ");
\r
5130 printtriangle(&oppotri);
\r
5133 /* Check that both triangles agree on the identities */
\r
5134 /* of their shared vertices. */
\r
5135 org(oppotri, oppoorg);
\r
5136 dest(oppotri, oppodest);
\r
5137 if ((triorg != oppodest) || (tridest != oppoorg)) {
\r
5138 printf(" !! !! Mismatched edge coordinates between two triangles:\n"
\r
5140 printf(" First mismatched ");
\r
5141 printtriangle(&triangleloop);
\r
5142 printf(" Second mismatched ");
\r
5143 printtriangle(&oppotri);
\r
5148 triangleloop.tri = triangletraverse();
\r
5150 if (horrors == 0) {
\r
5152 printf(" In my studied opinion, the mesh appears to be consistent.\n");
\r
5154 } else if (horrors == 1) {
\r
5155 printf(" !! !! !! !! Precisely one festering wound discovered.\n");
\r
5157 printf(" !! !! !! !! %d abominations witnessed.\n", horrors);
\r
5159 /* Restore the status of exact arithmetic. */
\r
5160 noexact = saveexact;
\r
5163 #endif /* not REDUCED */
\r
5165 /*****************************************************************************/
\r
5167 /* checkdelaunay() Ensure that the mesh is (constrained) Delaunay. */
\r
5169 /*****************************************************************************/
\r
5173 void checkdelaunay()
\r
5175 struct triedge triangleloop;
\r
5176 struct triedge oppotri;
\r
5177 struct edge opposhelle;
\r
5178 point triorg, tridest, triapex;
\r
5180 int shouldbedelaunay;
\r
5183 triangle ptr; /* Temporary variable used by sym(). */
\r
5184 shelle sptr; /* Temporary variable used by tspivot(). */
\r
5186 /* Temporarily turn on exact arithmetic if it's off. */
\r
5187 saveexact = noexact;
\r
5190 printf(" Checking Delaunay property of mesh...\n");
\r
5193 /* Run through the list of triangles, checking each one. */
\r
5194 traversalinit(&triangles);
\r
5195 triangleloop.tri = triangletraverse();
\r
5196 while (triangleloop.tri != (triangle *) NULL) {
\r
5197 /* Check all three edges of the triangle. */
\r
5198 for (triangleloop.orient = 0; triangleloop.orient < 3;
\r
5199 triangleloop.orient++) {
\r
5200 org(triangleloop, triorg);
\r
5201 dest(triangleloop, tridest);
\r
5202 apex(triangleloop, triapex);
\r
5203 sym(triangleloop, oppotri);
\r
5204 apex(oppotri, oppoapex);
\r
5205 /* Only test that the edge is locally Delaunay if there is an */
\r
5206 /* adjoining triangle whose pointer is larger (to ensure that */
\r
5207 /* each pair isn't tested twice). */
\r
5208 shouldbedelaunay = (oppotri.tri != dummytri)
\r
5209 && (triapex != (point) NULL) && (oppoapex != (point) NULL)
\r
5210 && (triangleloop.tri < oppotri.tri);
\r
5211 if (checksegments && shouldbedelaunay) {
\r
5212 /* If a shell edge separates the triangles, then the edge is */
\r
5213 /* constrained, so no local Delaunay test should be done. */
\r
5214 tspivot(triangleloop, opposhelle);
\r
5215 if (opposhelle.sh != dummysh){
\r
5216 shouldbedelaunay = 0;
\r
5219 if (shouldbedelaunay) {
\r
5220 if (incircle(triorg, tridest, triapex, oppoapex) > 0.0) {
\r
5221 printf(" !! !! Non-Delaunay pair of triangles:\n");
\r
5222 printf(" First non-Delaunay ");
\r
5223 printtriangle(&triangleloop);
\r
5224 printf(" Second non-Delaunay ");
\r
5225 printtriangle(&oppotri);
\r
5230 triangleloop.tri = triangletraverse();
\r
5232 if (horrors == 0) {
\r
5235 " By virtue of my perceptive intelligence, I declare the mesh Delaunay.\n");
\r
5237 } else if (horrors == 1) {
\r
5239 " !! !! !! !! Precisely one terrifying transgression identified.\n");
\r
5241 printf(" !! !! !! !! %d obscenities viewed with horror.\n", horrors);
\r
5243 /* Restore the status of exact arithmetic. */
\r
5244 noexact = saveexact;
\r
5247 #endif /* not REDUCED */
\r
5249 /*****************************************************************************/
\r
5251 /* enqueuebadtri() Add a bad triangle to the end of a queue. */
\r
5253 /* The queue is actually a set of 64 queues. I use multiple queues to give */
\r
5254 /* priority to smaller angles. I originally implemented a heap, but the */
\r
5255 /* queues are (to my surprise) much faster. */
\r
5257 /*****************************************************************************/
\r
5261 void enqueuebadtri(instri, angle, insapex, insorg, insdest)
\r
5262 struct triedge *instri;
\r
5268 struct badface *newface;
\r
5271 if (verbose > 2) {
\r
5272 printf(" Queueing bad triangle:\n");
\r
5273 printf(" (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n", insorg[0],
\r
5274 insorg[1], insdest[0], insdest[1], insapex[0], insapex[1]);
\r
5276 /* Allocate space for the bad triangle. */
\r
5277 newface = (struct badface *) poolalloc(&badtriangles);
\r
5278 triedgecopy(*instri, newface->badfacetri);
\r
5279 newface->key = angle;
\r
5280 newface->faceapex = insapex;
\r
5281 newface->faceorg = insorg;
\r
5282 newface->facedest = insdest;
\r
5283 newface->nextface = (struct badface *) NULL;
\r
5284 /* Determine the appropriate queue to put the bad triangle into. */
\r
5285 if (angle > 0.6) {
\r
5286 queuenumber = (int) (160.0 * (angle - 0.6));
\r
5287 if (queuenumber > 63) {
\r
5291 /* It's not a bad angle; put the triangle in the lowest-priority queue. */
\r
5294 /* Add the triangle to the end of a queue. */
\r
5295 *queuetail[queuenumber] = newface;
\r
5296 /* Maintain a pointer to the NULL pointer at the end of the queue. */
\r
5297 queuetail[queuenumber] = &newface->nextface;
\r
5300 #endif /* not CDT_ONLY */
\r
5302 /*****************************************************************************/
\r
5304 /* dequeuebadtri() Remove a triangle from the front of the queue. */
\r
5306 /*****************************************************************************/
\r
5310 struct badface *dequeuebadtri()
\r
5312 struct badface *result;
\r
5315 /* Look for a nonempty queue. */
\r
5316 for (queuenumber = 63; queuenumber >= 0; queuenumber--) {
\r
5317 result = queuefront[queuenumber];
\r
5318 if (result != (struct badface *) NULL) {
\r
5319 /* Remove the triangle from the queue. */
\r
5320 queuefront[queuenumber] = result->nextface;
\r
5321 /* Maintain a pointer to the NULL pointer at the end of the queue. */
\r
5322 if (queuefront[queuenumber] == (struct badface *) NULL) {
\r
5323 queuetail[queuenumber] = &queuefront[queuenumber];
\r
5328 return (struct badface *) NULL;
\r
5331 #endif /* not CDT_ONLY */
\r
5333 /*****************************************************************************/
\r
5335 /* checkedge4encroach() Check a segment to see if it is encroached; add */
\r
5336 /* it to the list if it is. */
\r
5338 /* An encroached segment is an unflippable edge that has a point in its */
\r
5339 /* diametral circle (that is, it faces an angle greater than 90 degrees). */
\r
5340 /* This definition is due to Ruppert. */
\r
5342 /* Returns a nonzero value if the edge is encroached. */
\r
5344 /*****************************************************************************/
\r
5348 int checkedge4encroach(testedge)
\r
5349 struct edge *testedge;
\r
5351 struct triedge neighbortri;
\r
5352 struct edge testsym;
\r
5353 struct edge *badedge;
\r
5356 point eorg, edest, eapex;
\r
5357 triangle ptr; /* Temporary variable used by stpivot(). */
\r
5362 sorg(*testedge, eorg);
\r
5363 sdest(*testedge, edest);
\r
5364 /* Check one neighbor of the shell edge. */
\r
5365 stpivot(*testedge, neighbortri);
\r
5366 /* Does the neighbor exist, or is this a boundary edge? */
\r
5367 if (neighbortri.tri != dummytri) {
\r
5369 /* Find a vertex opposite this edge. */
\r
5370 apex(neighbortri, eapex);
\r
5371 /* Check whether the vertex is inside the diametral circle of the */
\r
5372 /* shell edge. Pythagoras' Theorem is used to check whether the */
\r
5373 /* angle at the vertex is greater than 90 degrees. */
\r
5374 if (eapex[0] * (eorg[0] + edest[0]) + eapex[1] * (eorg[1] + edest[1]) >
\r
5375 eapex[0] * eapex[0] + eorg[0] * edest[0] +
\r
5376 eapex[1] * eapex[1] + eorg[1] * edest[1]) {
\r
5380 /* Check the other neighbor of the shell edge. */
\r
5381 ssym(*testedge, testsym);
\r
5382 stpivot(testsym, neighbortri);
\r
5383 /* Does the neighbor exist, or is this a boundary edge? */
\r
5384 if (neighbortri.tri != dummytri) {
\r
5386 /* Find the other vertex opposite this edge. */
\r
5387 apex(neighbortri, eapex);
\r
5388 /* Check whether the vertex is inside the diametral circle of the */
\r
5389 /* shell edge. Pythagoras' Theorem is used to check whether the */
\r
5390 /* angle at the vertex is greater than 90 degrees. */
\r
5391 if (eapex[0] * (eorg[0] + edest[0]) +
\r
5392 eapex[1] * (eorg[1] + edest[1]) >
\r
5393 eapex[0] * eapex[0] + eorg[0] * edest[0] +
\r
5394 eapex[1] * eapex[1] + eorg[1] * edest[1]) {
\r
5399 if (addtolist && (!nobisect || ((nobisect == 1) && (sides == 2)))) {
\r
5400 if (verbose > 2) {
\r
5401 printf(" Queueing encroached segment (%.12g, %.12g) (%.12g, %.12g).\n",
\r
5402 eorg[0], eorg[1], edest[0], edest[1]);
\r
5404 /* Add the shell edge to the list of encroached segments. */
\r
5405 /* Be sure to get the orientation right. */
\r
5406 badedge = (struct edge *) poolalloc(&badsegments);
\r
5407 if (addtolist == 1) {
\r
5408 shellecopy(*testedge, *badedge);
\r
5410 shellecopy(testsym, *badedge);
\r
5416 #endif /* not CDT_ONLY */
\r
5418 /*****************************************************************************/
\r
5420 /* testtriangle() Test a face for quality measures. */
\r
5422 /* Tests a triangle to see if it satisfies the minimum angle condition and */
\r
5423 /* the maximum area condition. Triangles that aren't up to spec are added */
\r
5424 /* to the bad triangle queue. */
\r
5426 /*****************************************************************************/
\r
5430 void testtriangle(testtri)
\r
5431 struct triedge *testtri;
\r
5433 struct triedge sametesttri;
\r
5434 struct edge edge1, edge2;
\r
5435 point torg, tdest, tapex;
\r
5436 point anglevertex;
\r
5437 REAL dxod, dyod, dxda, dyda, dxao, dyao;
\r
5438 REAL dxod2, dyod2, dxda2, dyda2, dxao2, dyao2;
\r
5439 REAL apexlen, orglen, destlen;
\r
5442 shelle sptr; /* Temporary variable used by tspivot(). */
\r
5444 org(*testtri, torg);
\r
5445 dest(*testtri, tdest);
\r
5446 apex(*testtri, tapex);
\r
5447 dxod = torg[0] - tdest[0];
\r
5448 dyod = torg[1] - tdest[1];
\r
5449 dxda = tdest[0] - tapex[0];
\r
5450 dyda = tdest[1] - tapex[1];
\r
5451 dxao = tapex[0] - torg[0];
\r
5452 dyao = tapex[1] - torg[1];
\r
5453 dxod2 = dxod * dxod;
\r
5454 dyod2 = dyod * dyod;
\r
5455 dxda2 = dxda * dxda;
\r
5456 dyda2 = dyda * dyda;
\r
5457 dxao2 = dxao * dxao;
\r
5458 dyao2 = dyao * dyao;
\r
5459 /* Find the lengths of the triangle's three edges. */
\r
5460 apexlen = dxod2 + dyod2;
\r
5461 orglen = dxda2 + dyda2;
\r
5462 destlen = dxao2 + dyao2;
\r
5463 if ((apexlen < orglen) && (apexlen < destlen)) {
\r
5464 /* The edge opposite the apex is shortest. */
\r
5465 /* Find the square of the cosine of the angle at the apex. */
\r
5466 angle = dxda * dxao + dyda * dyao;
\r
5467 angle = angle * angle / (orglen * destlen);
\r
5468 anglevertex = tapex;
\r
5469 lnext(*testtri, sametesttri);
\r
5470 tspivot(sametesttri, edge1);
\r
5471 lnextself(sametesttri);
\r
5472 tspivot(sametesttri, edge2);
\r
5473 } else if (orglen < destlen) {
\r
5474 /* The edge opposite the origin is shortest. */
\r
5475 /* Find the square of the cosine of the angle at the origin. */
\r
5476 angle = dxod * dxao + dyod * dyao;
\r
5477 angle = angle * angle / (apexlen * destlen);
\r
5478 anglevertex = torg;
\r
5479 tspivot(*testtri, edge1);
\r
5480 lprev(*testtri, sametesttri);
\r
5481 tspivot(sametesttri, edge2);
\r
5483 /* The edge opposite the destination is shortest. */
\r
5484 /* Find the square of the cosine of the angle at the destination. */
\r
5485 angle = dxod * dxda + dyod * dyda;
\r
5486 angle = angle * angle / (apexlen * orglen);
\r
5487 anglevertex = tdest;
\r
5488 tspivot(*testtri, edge1);
\r
5489 lnext(*testtri, sametesttri);
\r
5490 tspivot(sametesttri, edge2);
\r
5492 /* Check if both edges that form the angle are segments. */
\r
5493 if ((edge1.sh != dummysh) && (edge2.sh != dummysh)) {
\r
5494 /* The angle is a segment intersection. */
\r
5495 if ((angle > 0.9924) && !quiet) { /* Roughly 5 degrees. */
\r
5496 if (angle > 1.0) {
\r
5497 /* Beware of a floating exception in acos(). */
\r
5500 /* Find the actual angle in degrees, for printing. */
\r
5501 angle = acos(sqrt(angle)) * (180.0 / PI);
\r
5503 "Warning: Small angle (%.4g degrees) between segments at point\n",
\r
5505 printf(" (%.12g, %.12g)\n", anglevertex[0], anglevertex[1]);
\r
5507 /* Don't add this bad triangle to the list; there's nothing that */
\r
5508 /* can be done about a small angle between two segments. */
\r
5511 /* Check whether the angle is smaller than permitted. */
\r
5512 if (angle > goodangle) {
\r
5513 /* Add this triangle to the list of bad triangles. */
\r
5514 enqueuebadtri(testtri, angle, tapex, torg, tdest);
\r
5517 if (vararea || fixedarea) {
\r
5518 /* Check whether the area is larger than permitted. */
\r
5519 area = 0.5 * (dxod * dyda - dyod * dxda);
\r
5520 if (fixedarea && (area > maxarea)) {
\r
5521 /* Add this triangle to the list of bad triangles. */
\r
5522 enqueuebadtri(testtri, angle, tapex, torg, tdest);
\r
5523 } else if (vararea) {
\r
5524 /* Nonpositive area constraints are treated as unconstrained. */
\r
5525 if ((area > areabound(*testtri)) && (areabound(*testtri) > 0.0)) {
\r
5526 /* Add this triangle to the list of bad triangles. */
\r
5527 enqueuebadtri(testtri, angle, tapex, torg, tdest);
\r
5533 #endif /* not CDT_ONLY */
\r
5537 /********* Mesh quality testing routines end here *********/
\r
5539 /********* Point location routines begin here *********/
\r
5543 /*****************************************************************************/
\r
5545 /* makepointmap() Construct a mapping from points to triangles to improve */
\r
5546 /* the speed of point location for segment insertion. */
\r
5548 /* Traverses all the triangles, and provides each corner of each triangle */
\r
5549 /* with a pointer to that triangle. Of course, pointers will be */
\r
5550 /* overwritten by other pointers because (almost) each point is a corner */
\r
5551 /* of several triangles, but in the end every point will point to some */
\r
5552 /* triangle that contains it. */
\r
5554 /*****************************************************************************/
\r
5556 void makepointmap()
\r
5558 struct triedge triangleloop;
\r
5562 printf(" Constructing mapping from points to triangles.\n");
\r
5564 traversalinit(&triangles);
\r
5565 triangleloop.tri = triangletraverse();
\r
5566 while (triangleloop.tri != (triangle *) NULL) {
\r
5567 /* Check all three points of the triangle. */
\r
5568 for (triangleloop.orient = 0; triangleloop.orient < 3;
\r
5569 triangleloop.orient++) {
\r
5570 org(triangleloop, triorg);
\r
5571 setpoint2tri(triorg, encode(triangleloop));
\r
5573 triangleloop.tri = triangletraverse();
\r
5577 /*****************************************************************************/
\r
5579 /* preciselocate() Find a triangle or edge containing a given point. */
\r
5581 /* Begins its search from `searchtri'. It is important that `searchtri' */
\r
5582 /* be a handle with the property that `searchpoint' is strictly to the left */
\r
5583 /* of the edge denoted by `searchtri', or is collinear with that edge and */
\r
5584 /* does not intersect that edge. (In particular, `searchpoint' should not */
\r
5585 /* be the origin or destination of that edge.) */
\r
5587 /* These conditions are imposed because preciselocate() is normally used in */
\r
5588 /* one of two situations: */
\r
5590 /* (1) To try to find the location to insert a new point. Normally, we */
\r
5591 /* know an edge that the point is strictly to the left of. In the */
\r
5592 /* incremental Delaunay algorithm, that edge is a bounding box edge. */
\r
5593 /* In Ruppert's Delaunay refinement algorithm for quality meshing, */
\r
5594 /* that edge is the shortest edge of the triangle whose circumcenter */
\r
5595 /* is being inserted. */
\r
5597 /* (2) To try to find an existing point. In this case, any edge on the */
\r
5598 /* convex hull is a good starting edge. The possibility that the */
\r
5599 /* vertex one seeks is an endpoint of the starting edge must be */
\r
5600 /* screened out before preciselocate() is called. */
\r
5602 /* On completion, `searchtri' is a triangle that contains `searchpoint'. */
\r
5604 /* This implementation differs from that given by Guibas and Stolfi. It */
\r
5605 /* walks from triangle to triangle, crossing an edge only if `searchpoint' */
\r
5606 /* is on the other side of the line containing that edge. After entering */
\r
5607 /* a triangle, there are two edges by which one can leave that triangle. */
\r
5608 /* If both edges are valid (`searchpoint' is on the other side of both */
\r
5609 /* edges), one of the two is chosen by drawing a line perpendicular to */
\r
5610 /* the entry edge (whose endpoints are `forg' and `fdest') passing through */
\r
5611 /* `fapex'. Depending on which side of this perpendicular `searchpoint' */
\r
5612 /* falls on, an exit edge is chosen. */
\r
5614 /* This implementation is empirically faster than the Guibas and Stolfi */
\r
5615 /* point location routine (which I originally used), which tends to spiral */
\r
5616 /* in toward its target. */
\r
5618 /* Returns ONVERTEX if the point lies on an existing vertex. `searchtri' */
\r
5619 /* is a handle whose origin is the existing vertex. */
\r
5621 /* Returns ONEDGE if the point lies on a mesh edge. `searchtri' is a */
\r
5622 /* handle whose primary edge is the edge on which the point lies. */
\r
5624 /* Returns INTRIANGLE if the point lies strictly within a triangle. */
\r
5625 /* `searchtri' is a handle on the triangle that contains the point. */
\r
5627 /* Returns OUTSIDE if the point lies outside the mesh. `searchtri' is a */
\r
5628 /* handle whose primary edge the point is to the right of. This might */
\r
5629 /* occur when the circumcenter of a triangle falls just slightly outside */
\r
5630 /* the mesh due to floating-point roundoff error. It also occurs when */
\r
5631 /* seeking a hole or region point that a foolish user has placed outside */
\r
5634 /* WARNING: This routine is designed for convex triangulations, and will */
\r
5635 /* not generally work after the holes and concavities have been carved. */
\r
5636 /* However, it can still be used to find the circumcenter of a triangle, as */
\r
5637 /* long as the search is begun from the triangle in question. */
\r
5639 /*****************************************************************************/
\r
5641 enum locateresult preciselocate(searchpoint, searchtri)
\r
5642 point searchpoint;
\r
5643 struct triedge *searchtri;
\r
5645 struct triedge backtracktri;
\r
5646 point forg, fdest, fapex;
\r
5648 REAL orgorient, destorient;
\r
5650 triangle ptr; /* Temporary variable used by sym(). */
\r
5652 if (verbose > 2) {
\r
5653 printf(" Searching for point (%.12g, %.12g).\n",
\r
5654 searchpoint[0], searchpoint[1]);
\r
5656 /* Where are we? */
\r
5657 org(*searchtri, forg);
\r
5658 dest(*searchtri, fdest);
\r
5659 apex(*searchtri, fapex);
\r
5661 if (verbose > 2) {
\r
5662 printf(" At (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
\r
5663 forg[0], forg[1], fdest[0], fdest[1], fapex[0], fapex[1]);
\r
5665 /* Check whether the apex is the point we seek. */
\r
5666 if ((fapex[0] == searchpoint[0]) && (fapex[1] == searchpoint[1])) {
\r
5667 lprevself(*searchtri);
\r
5670 /* Does the point lie on the other side of the line defined by the */
\r
5671 /* triangle edge opposite the triangle's destination? */
\r
5672 destorient = counterclockwise(forg, fapex, searchpoint);
\r
5673 /* Does the point lie on the other side of the line defined by the */
\r
5674 /* triangle edge opposite the triangle's origin? */
\r
5675 orgorient = counterclockwise(fapex, fdest, searchpoint);
\r
5676 if (destorient > 0.0) {
\r
5677 if (orgorient > 0.0) {
\r
5678 /* Move left if the inner product of (fapex - searchpoint) and */
\r
5679 /* (fdest - forg) is positive. This is equivalent to drawing */
\r
5680 /* a line perpendicular to the line (forg, fdest) passing */
\r
5681 /* through `fapex', and determining which side of this line */
\r
5682 /* `searchpoint' falls on. */
\r
5683 moveleft = (fapex[0] - searchpoint[0]) * (fdest[0] - forg[0]) +
\r
5684 (fapex[1] - searchpoint[1]) * (fdest[1] - forg[1]) > 0.0;
\r
5689 if (orgorient > 0.0) {
\r
5692 /* The point we seek must be on the boundary of or inside this */
\r
5694 if (destorient == 0.0) {
\r
5695 lprevself(*searchtri);
\r
5698 if (orgorient == 0.0) {
\r
5699 lnextself(*searchtri);
\r
5702 return INTRIANGLE;
\r
5706 /* Move to another triangle. Leave a trace `backtracktri' in case */
\r
5707 /* floating-point roundoff or some such bogey causes us to walk */
\r
5708 /* off a boundary of the triangulation. We can just bounce off */
\r
5709 /* the boundary as if it were an elastic band. */
\r
5711 lprev(*searchtri, backtracktri);
\r
5714 lnext(*searchtri, backtracktri);
\r
5717 sym(backtracktri, *searchtri);
\r
5719 /* Check for walking off the edge. */
\r
5720 if (searchtri->tri == dummytri) {
\r
5721 /* Turn around. */
\r
5722 triedgecopy(backtracktri, *searchtri);
\r
5725 fdest = swappoint;
\r
5726 apex(*searchtri, fapex);
\r
5727 /* Check if the point really is beyond the triangulation boundary. */
\r
5728 destorient = counterclockwise(forg, fapex, searchpoint);
\r
5729 orgorient = counterclockwise(fapex, fdest, searchpoint);
\r
5730 if ((orgorient < 0.0) && (destorient < 0.0)) {
\r
5734 apex(*searchtri, fapex);
\r
5739 /*****************************************************************************/
\r
5741 /* locate() Find a triangle or edge containing a given point. */
\r
5743 /* Searching begins from one of: the input `searchtri', a recently */
\r
5744 /* encountered triangle `recenttri', or from a triangle chosen from a */
\r
5745 /* random sample. The choice is made by determining which triangle's */
\r
5746 /* origin is closest to the point we are searcing for. Normally, */
\r
5747 /* `searchtri' should be a handle on the convex hull of the triangulation. */
\r
5749 /* Details on the random sampling method can be found in the Mucke, Saias, */
\r
5750 /* and Zhu paper cited in the header of this code. */
\r
5752 /* On completion, `searchtri' is a triangle that contains `searchpoint'. */
\r
5754 /* Returns ONVERTEX if the point lies on an existing vertex. `searchtri' */
\r
5755 /* is a handle whose origin is the existing vertex. */
\r
5757 /* Returns ONEDGE if the point lies on a mesh edge. `searchtri' is a */
\r
5758 /* handle whose primary edge is the edge on which the point lies. */
\r
5760 /* Returns INTRIANGLE if the point lies strictly within a triangle. */
\r
5761 /* `searchtri' is a handle on the triangle that contains the point. */
\r
5763 /* Returns OUTSIDE if the point lies outside the mesh. `searchtri' is a */
\r
5764 /* handle whose primary edge the point is to the right of. This might */
\r
5765 /* occur when the circumcenter of a triangle falls just slightly outside */
\r
5766 /* the mesh due to floating-point roundoff error. It also occurs when */
\r
5767 /* seeking a hole or region point that a foolish user has placed outside */
\r
5770 /* WARNING: This routine is designed for convex triangulations, and will */
\r
5771 /* not generally work after the holes and concavities have been carved. */
\r
5773 /*****************************************************************************/
\r
5775 enum locateresult locate(searchpoint, searchtri)
\r
5776 point searchpoint;
\r
5777 struct triedge *searchtri;
\r
5779 VOID **sampleblock;
\r
5780 triangle *firsttri;
\r
5781 struct triedge sampletri;
\r
5782 point torg, tdest;
\r
5783 unsigned long alignptr;
\r
5784 REAL searchdist, dist;
\r
5786 long sampleblocks, samplesperblock, samplenum;
\r
5789 triangle ptr; /* Temporary variable used by sym(). */
\r
5791 if (verbose > 2) {
\r
5792 printf(" Randomly sampling for a triangle near point (%.12g, %.12g).\n",
\r
5793 searchpoint[0], searchpoint[1]);
\r
5795 /* Record the distance from the suggested starting triangle to the */
\r
5796 /* point we seek. */
\r
5797 org(*searchtri, torg);
\r
5798 searchdist = (searchpoint[0] - torg[0]) * (searchpoint[0] - torg[0])
\r
5799 + (searchpoint[1] - torg[1]) * (searchpoint[1] - torg[1]);
\r
5800 if (verbose > 2) {
\r
5801 printf(" Boundary triangle has origin (%.12g, %.12g).\n",
\r
5802 torg[0], torg[1]);
\r
5805 /* If a recently encountered triangle has been recorded and has not been */
\r
5806 /* deallocated, test it as a good starting point. */
\r
5807 if (recenttri.tri != (triangle *) NULL) {
\r
5808 if (recenttri.tri[3] != (triangle) NULL) {
\r
5809 org(recenttri, torg);
\r
5810 if ((torg[0] == searchpoint[0]) && (torg[1] == searchpoint[1])) {
\r
5811 triedgecopy(recenttri, *searchtri);
\r
5814 dist = (searchpoint[0] - torg[0]) * (searchpoint[0] - torg[0])
\r
5815 + (searchpoint[1] - torg[1]) * (searchpoint[1] - torg[1]);
\r
5816 if (dist < searchdist) {
\r
5817 triedgecopy(recenttri, *searchtri);
\r
5818 searchdist = dist;
\r
5819 if (verbose > 2) {
\r
5820 printf(" Choosing recent triangle with origin (%.12g, %.12g).\n",
\r
5821 torg[0], torg[1]);
\r
5827 /* The number of random samples taken is proportional to the cube root of */
\r
5828 /* the number of triangles in the mesh. The next bit of code assumes */
\r
5829 /* that the number of triangles increases monotonically. */
\r
5830 while (SAMPLEFACTOR * samples * samples * samples < triangles.items) {
\r
5833 triblocks = (triangles.maxitems + TRIPERBLOCK - 1) / TRIPERBLOCK;
\r
5834 samplesperblock = 1 + (samples / triblocks);
\r
5835 sampleblocks = samples / samplesperblock;
\r
5836 sampleblock = triangles.firstblock;
\r
5837 sampletri.orient = 0;
\r
5838 for (i = 0; i < sampleblocks; i++) {
\r
5839 alignptr = (unsigned long) (sampleblock + 1);
\r
5840 firsttri = (triangle *) (alignptr + (unsigned long) triangles.alignbytes
\r
5841 - (alignptr % (unsigned long) triangles.alignbytes));
\r
5842 for (j = 0; j < samplesperblock; j++) {
\r
5843 if (i == triblocks - 1) {
\r
5844 samplenum = randomnation((int)
\r
5845 (triangles.maxitems - (i * TRIPERBLOCK)));
\r
5847 samplenum = randomnation(TRIPERBLOCK);
\r
5849 sampletri.tri = (triangle *)
\r
5850 (firsttri + (samplenum * triangles.itemwords));
\r
5851 if (sampletri.tri[3] != (triangle) NULL) {
\r
5852 org(sampletri, torg);
\r
5853 dist = (searchpoint[0] - torg[0]) * (searchpoint[0] - torg[0])
\r
5854 + (searchpoint[1] - torg[1]) * (searchpoint[1] - torg[1]);
\r
5855 if (dist < searchdist) {
\r
5856 triedgecopy(sampletri, *searchtri);
\r
5857 searchdist = dist;
\r
5858 if (verbose > 2) {
\r
5859 printf(" Choosing triangle with origin (%.12g, %.12g).\n",
\r
5860 torg[0], torg[1]);
\r
5865 sampleblock = (VOID **) *sampleblock;
\r
5867 /* Where are we? */
\r
5868 org(*searchtri, torg);
\r
5869 dest(*searchtri, tdest);
\r
5870 /* Check the starting triangle's vertices. */
\r
5871 if ((torg[0] == searchpoint[0]) && (torg[1] == searchpoint[1])) {
\r
5874 if ((tdest[0] == searchpoint[0]) && (tdest[1] == searchpoint[1])) {
\r
5875 lnextself(*searchtri);
\r
5878 /* Orient `searchtri' to fit the preconditions of calling preciselocate(). */
\r
5879 ahead = counterclockwise(torg, tdest, searchpoint);
\r
5880 if (ahead < 0.0) {
\r
5881 /* Turn around so that `searchpoint' is to the left of the */
\r
5882 /* edge specified by `searchtri'. */
\r
5883 symself(*searchtri);
\r
5884 } else if (ahead == 0.0) {
\r
5885 /* Check if `searchpoint' is between `torg' and `tdest'. */
\r
5886 if (((torg[0] < searchpoint[0]) == (searchpoint[0] < tdest[0]))
\r
5887 && ((torg[1] < searchpoint[1]) == (searchpoint[1] < tdest[1]))) {
\r
5891 return preciselocate(searchpoint, searchtri);
\r
5896 /********* Point location routines end here *********/
\r
5898 /********* Mesh transformation routines begin here *********/
\r
5902 /*****************************************************************************/
\r
5904 /* insertshelle() Create a new shell edge and insert it between two */
\r
5907 /* The new shell edge is inserted at the edge described by the handle */
\r
5908 /* `tri'. Its vertices are properly initialized. The marker `shellemark' */
\r
5909 /* is applied to the shell edge and, if appropriate, its vertices. */
\r
5911 /*****************************************************************************/
\r
5913 void insertshelle(tri, shellemark)
\r
5914 struct triedge *tri; /* Edge at which to insert the new shell edge. */
\r
5915 int shellemark; /* Marker for the new shell edge. */
\r
5917 struct triedge oppotri;
\r
5918 struct edge newshelle;
\r
5919 point triorg, tridest;
\r
5920 triangle ptr; /* Temporary variable used by sym(). */
\r
5921 shelle sptr; /* Temporary variable used by tspivot(). */
\r
5923 /* Mark points if possible. */
\r
5924 org(*tri, triorg);
\r
5925 dest(*tri, tridest);
\r
5926 if (pointmark(triorg) == 0) {
\r
5927 setpointmark(triorg, shellemark);
\r
5929 if (pointmark(tridest) == 0) {
\r
5930 setpointmark(tridest, shellemark);
\r
5932 /* Check if there's already a shell edge here. */
\r
5933 tspivot(*tri, newshelle);
\r
5934 if (newshelle.sh == dummysh) {
\r
5935 /* Make new shell edge and initialize its vertices. */
\r
5936 makeshelle(&newshelle);
\r
5937 setsorg(newshelle, tridest);
\r
5938 setsdest(newshelle, triorg);
\r
5939 /* Bond new shell edge to the two triangles it is sandwiched between. */
\r
5940 /* Note that the facing triangle `oppotri' might be equal to */
\r
5941 /* `dummytri' (outer space), but the new shell edge is bonded to it */
\r
5942 /* all the same. */
\r
5943 tsbond(*tri, newshelle);
\r
5944 sym(*tri, oppotri);
\r
5945 ssymself(newshelle);
\r
5946 tsbond(oppotri, newshelle);
\r
5947 setmark(newshelle, shellemark);
\r
5948 if (verbose > 2) {
\r
5949 printf(" Inserting new ");
\r
5950 printshelle(&newshelle);
\r
5953 if (mark(newshelle) == 0) {
\r
5954 setmark(newshelle, shellemark);
\r
5959 /*****************************************************************************/
\r
5963 /* A "local transformation" replaces a small set of triangles with another */
\r
5964 /* set of triangles. This may or may not involve inserting or deleting a */
\r
5967 /* The term "casing" is used to describe the set of triangles that are */
\r
5968 /* attached to the triangles being transformed, but are not transformed */
\r
5969 /* themselves. Think of the casing as a fixed hollow structure inside */
\r
5970 /* which all the action happens. A "casing" is only defined relative to */
\r
5971 /* a single transformation; each occurrence of a transformation will */
\r
5972 /* involve a different casing. */
\r
5974 /* A "shell" is similar to a "casing". The term "shell" describes the set */
\r
5975 /* of shell edges (if any) that are attached to the triangles being */
\r
5976 /* transformed. However, I sometimes use "shell" to refer to a single */
\r
5977 /* shell edge, so don't get confused. */
\r
5979 /*****************************************************************************/
\r
5981 /*****************************************************************************/
\r
5983 /* flip() Transform two triangles to two different triangles by flipping */
\r
5984 /* an edge within a quadrilateral. */
\r
5986 /* Imagine the original triangles, abc and bad, oriented so that the */
\r
5987 /* shared edge ab lies in a horizontal plane, with the point b on the left */
\r
5988 /* and the point a on the right. The point c lies below the edge, and the */
\r
5989 /* point d lies above the edge. The `flipedge' handle holds the edge ab */
\r
5990 /* of triangle abc, and is directed left, from vertex a to vertex b. */
\r
5992 /* The triangles abc and bad are deleted and replaced by the triangles cdb */
\r
5993 /* and dca. The triangles that represent abc and bad are NOT deallocated; */
\r
5994 /* they are reused for dca and cdb, respectively. Hence, any handles that */
\r
5995 /* may have held the original triangles are still valid, although not */
\r
5996 /* directed as they were before. */
\r
5998 /* Upon completion of this routine, the `flipedge' handle holds the edge */
\r
5999 /* dc of triangle dca, and is directed down, from vertex d to vertex c. */
\r
6000 /* (Hence, the two triangles have rotated counterclockwise.) */
\r
6002 /* WARNING: This transformation is geometrically valid only if the */
\r
6003 /* quadrilateral adbc is convex. Furthermore, this transformation is */
\r
6004 /* valid only if there is not a shell edge between the triangles abc and */
\r
6005 /* bad. This routine does not check either of these preconditions, and */
\r
6006 /* it is the responsibility of the calling routine to ensure that they are */
\r
6007 /* met. If they are not, the streets shall be filled with wailing and */
\r
6008 /* gnashing of teeth. */
\r
6010 /*****************************************************************************/
\r
6012 void flip(flipedge)
\r
6013 struct triedge *flipedge; /* Handle for the triangle abc. */
\r
6015 struct triedge botleft, botright;
\r
6016 struct triedge topleft, topright;
\r
6017 struct triedge top;
\r
6018 struct triedge botlcasing, botrcasing;
\r
6019 struct triedge toplcasing, toprcasing;
\r
6020 struct edge botlshelle, botrshelle;
\r
6021 struct edge toplshelle, toprshelle;
\r
6022 point leftpoint, rightpoint, botpoint;
\r
6024 triangle ptr; /* Temporary variable used by sym(). */
\r
6025 shelle sptr; /* Temporary variable used by tspivot(). */
\r
6027 /* Identify the vertices of the quadrilateral. */
\r
6028 org(*flipedge, rightpoint);
\r
6029 dest(*flipedge, leftpoint);
\r
6030 apex(*flipedge, botpoint);
\r
6031 sym(*flipedge, top);
\r
6033 if (top.tri == dummytri) {
\r
6034 printf("Internal error in flip(): Attempt to flip on boundary.\n");
\r
6035 lnextself(*flipedge);
\r
6038 if (checksegments) {
\r
6039 tspivot(*flipedge, toplshelle);
\r
6040 if (toplshelle.sh != dummysh) {
\r
6041 printf("Internal error in flip(): Attempt to flip a segment.\n");
\r
6042 lnextself(*flipedge);
\r
6046 #endif /* SELF_CHECK */
\r
6047 apex(top, farpoint);
\r
6049 /* Identify the casing of the quadrilateral. */
\r
6050 lprev(top, topleft);
\r
6051 sym(topleft, toplcasing);
\r
6052 lnext(top, topright);
\r
6053 sym(topright, toprcasing);
\r
6054 lnext(*flipedge, botleft);
\r
6055 sym(botleft, botlcasing);
\r
6056 lprev(*flipedge, botright);
\r
6057 sym(botright, botrcasing);
\r
6058 /* Rotate the quadrilateral one-quarter turn counterclockwise. */
\r
6059 bond(topleft, botlcasing);
\r
6060 bond(botleft, botrcasing);
\r
6061 bond(botright, toprcasing);
\r
6062 bond(topright, toplcasing);
\r
6064 if (checksegments) {
\r
6065 /* Check for shell edges and rebond them to the quadrilateral. */
\r
6066 tspivot(topleft, toplshelle);
\r
6067 tspivot(botleft, botlshelle);
\r
6068 tspivot(botright, botrshelle);
\r
6069 tspivot(topright, toprshelle);
\r
6070 if (toplshelle.sh == dummysh) {
\r
6071 tsdissolve(topright);
\r
6073 tsbond(topright, toplshelle);
\r
6075 if (botlshelle.sh == dummysh) {
\r
6076 tsdissolve(topleft);
\r
6078 tsbond(topleft, botlshelle);
\r
6080 if (botrshelle.sh == dummysh) {
\r
6081 tsdissolve(botleft);
\r
6083 tsbond(botleft, botrshelle);
\r
6085 if (toprshelle.sh == dummysh) {
\r
6086 tsdissolve(botright);
\r
6088 tsbond(botright, toprshelle);
\r
6092 /* New point assignments for the rotated quadrilateral. */
\r
6093 setorg(*flipedge, farpoint);
\r
6094 setdest(*flipedge, botpoint);
\r
6095 setapex(*flipedge, rightpoint);
\r
6096 setorg(top, botpoint);
\r
6097 setdest(top, farpoint);
\r
6098 setapex(top, leftpoint);
\r
6099 if (verbose > 2) {
\r
6100 printf(" Edge flip results in left ");
\r
6101 lnextself(topleft);
\r
6102 printtriangle(&topleft);
\r
6103 printf(" and right ");
\r
6104 printtriangle(flipedge);
\r
6108 /*****************************************************************************/
\r
6110 /* insertsite() Insert a vertex into a Delaunay triangulation, */
\r
6111 /* performing flips as necessary to maintain the Delaunay */
\r
6114 /* The point `insertpoint' is located. If `searchtri.tri' is not NULL, */
\r
6115 /* the search for the containing triangle begins from `searchtri'. If */
\r
6116 /* `searchtri.tri' is NULL, a full point location procedure is called. */
\r
6117 /* If `insertpoint' is found inside a triangle, the triangle is split into */
\r
6118 /* three; if `insertpoint' lies on an edge, the edge is split in two, */
\r
6119 /* thereby splitting the two adjacent triangles into four. Edge flips are */
\r
6120 /* used to restore the Delaunay property. If `insertpoint' lies on an */
\r
6121 /* existing vertex, no action is taken, and the value DUPLICATEPOINT is */
\r
6122 /* returned. On return, `searchtri' is set to a handle whose origin is the */
\r
6123 /* existing vertex. */
\r
6125 /* Normally, the parameter `splitedge' is set to NULL, implying that no */
\r
6126 /* segment should be split. In this case, if `insertpoint' is found to */
\r
6127 /* lie on a segment, no action is taken, and the value VIOLATINGPOINT is */
\r
6128 /* returned. On return, `searchtri' is set to a handle whose primary edge */
\r
6129 /* is the violated segment. */
\r
6131 /* If the calling routine wishes to split a segment by inserting a point in */
\r
6132 /* it, the parameter `splitedge' should be that segment. In this case, */
\r
6133 /* `searchtri' MUST be the triangle handle reached by pivoting from that */
\r
6134 /* segment; no point location is done. */
\r
6136 /* `segmentflaws' and `triflaws' are flags that indicate whether or not */
\r
6137 /* there should be checks for the creation of encroached segments or bad */
\r
6138 /* quality faces. If a newly inserted point encroaches upon segments, */
\r
6139 /* these segments are added to the list of segments to be split if */
\r
6140 /* `segmentflaws' is set. If bad triangles are created, these are added */
\r
6141 /* to the queue if `triflaws' is set. */
\r
6143 /* If a duplicate point or violated segment does not prevent the point */
\r
6144 /* from being inserted, the return value will be ENCROACHINGPOINT if the */
\r
6145 /* point encroaches upon a segment (and checking is enabled), or */
\r
6146 /* SUCCESSFULPOINT otherwise. In either case, `searchtri' is set to a */
\r
6147 /* handle whose origin is the newly inserted vertex. */
\r
6149 /* insertsite() does not use flip() for reasons of speed; some */
\r
6150 /* information can be reused from edge flip to edge flip, like the */
\r
6151 /* locations of shell edges. */
\r
6153 /*****************************************************************************/
\r
6155 enum insertsiteresult insertsite(insertpoint, searchtri, splitedge,
\r
6156 segmentflaws, triflaws)
\r
6157 point insertpoint;
\r
6158 struct triedge *searchtri;
\r
6159 struct edge *splitedge;
\r
6163 struct triedge horiz;
\r
6164 struct triedge top;
\r
6165 struct triedge botleft, botright;
\r
6166 struct triedge topleft, topright;
\r
6167 struct triedge newbotleft, newbotright;
\r
6168 struct triedge newtopright;
\r
6169 struct triedge botlcasing, botrcasing;
\r
6170 struct triedge toplcasing, toprcasing;
\r
6171 struct triedge testtri;
\r
6172 struct edge botlshelle, botrshelle;
\r
6173 struct edge toplshelle, toprshelle;
\r
6174 struct edge brokenshelle;
\r
6175 struct edge checkshelle;
\r
6176 struct edge rightedge;
\r
6177 struct edge newedge;
\r
6178 struct edge *encroached;
\r
6180 point leftpoint, rightpoint, botpoint, toppoint, farpoint;
\r
6183 enum insertsiteresult success;
\r
6184 enum locateresult intersect;
\r
6188 triangle ptr; /* Temporary variable used by sym(). */
\r
6189 shelle sptr; /* Temporary variable used by spivot() and tspivot(). */
\r
6191 if (verbose > 1) {
\r
6192 printf(" Inserting (%.12g, %.12g).\n", insertpoint[0], insertpoint[1]);
\r
6194 if (splitedge == (struct edge *) NULL) {
\r
6195 /* Find the location of the point to be inserted. Check if a good */
\r
6196 /* starting triangle has already been provided by the caller. */
\r
6197 if (searchtri->tri == (triangle *) NULL) {
\r
6198 /* Find a boundary triangle. */
\r
6199 horiz.tri = dummytri;
\r
6202 /* Search for a triangle containing `insertpoint'. */
\r
6203 intersect = locate(insertpoint, &horiz);
\r
6205 /* Start searching from the triangle provided by the caller. */
\r
6206 triedgecopy(*searchtri, horiz);
\r
6207 intersect = preciselocate(insertpoint, &horiz);
\r
6210 /* The calling routine provides the edge in which the point is inserted. */
\r
6211 triedgecopy(*searchtri, horiz);
\r
6212 intersect = ONEDGE;
\r
6214 if (intersect == ONVERTEX) {
\r
6215 /* There's already a vertex there. Return in `searchtri' a triangle */
\r
6216 /* whose origin is the existing vertex. */
\r
6217 triedgecopy(horiz, *searchtri);
\r
6218 triedgecopy(horiz, recenttri);
\r
6219 return DUPLICATEPOINT;
\r
6221 if ((intersect == ONEDGE) || (intersect == OUTSIDE)) {
\r
6222 /* The vertex falls on an edge or boundary. */
\r
6223 if (checksegments && (splitedge == (struct edge *) NULL)) {
\r
6224 /* Check whether the vertex falls on a shell edge. */
\r
6225 tspivot(horiz, brokenshelle);
\r
6226 if (brokenshelle.sh != dummysh) {
\r
6227 /* The vertex falls on a shell edge. */
\r
6228 if (segmentflaws) {
\r
6229 if (nobisect == 0) {
\r
6230 /* Add the shell edge to the list of encroached segments. */
\r
6231 encroached = (struct edge *) poolalloc(&badsegments);
\r
6232 shellecopy(brokenshelle, *encroached);
\r
6233 } else if ((nobisect == 1) && (intersect == ONEDGE)) {
\r
6234 /* This segment may be split only if it is an internal boundary. */
\r
6235 sym(horiz, testtri);
\r
6236 if (testtri.tri != dummytri) {
\r
6237 /* Add the shell edge to the list of encroached segments. */
\r
6238 encroached = (struct edge *) poolalloc(&badsegments);
\r
6239 shellecopy(brokenshelle, *encroached);
\r
6243 /* Return a handle whose primary edge contains the point, */
\r
6244 /* which has not been inserted. */
\r
6245 triedgecopy(horiz, *searchtri);
\r
6246 triedgecopy(horiz, recenttri);
\r
6247 return VIOLATINGPOINT;
\r
6250 /* Insert the point on an edge, dividing one triangle into two (if */
\r
6251 /* the edge lies on a boundary) or two triangles into four. */
\r
6252 lprev(horiz, botright);
\r
6253 sym(botright, botrcasing);
\r
6254 sym(horiz, topright);
\r
6255 /* Is there a second triangle? (Or does this edge lie on a boundary?) */
\r
6256 mirrorflag = topright.tri != dummytri;
\r
6258 lnextself(topright);
\r
6259 sym(topright, toprcasing);
\r
6260 maketriangle(&newtopright);
\r
6262 /* Splitting the boundary edge increases the number of boundary edges. */
\r
6265 maketriangle(&newbotright);
\r
6267 /* Set the vertices of changed and new triangles. */
\r
6268 org(horiz, rightpoint);
\r
6269 dest(horiz, leftpoint);
\r
6270 apex(horiz, botpoint);
\r
6271 setorg(newbotright, botpoint);
\r
6272 setdest(newbotright, rightpoint);
\r
6273 setapex(newbotright, insertpoint);
\r
6274 setorg(horiz, insertpoint);
\r
6275 for (i = 0; i < eextras; i++) {
\r
6276 /* Set the element attributes of a new triangle. */
\r
6277 setelemattribute(newbotright, i, elemattribute(botright, i));
\r
6280 /* Set the area constraint of a new triangle. */
\r
6281 setareabound(newbotright, areabound(botright));
\r
6284 dest(topright, toppoint);
\r
6285 setorg(newtopright, rightpoint);
\r
6286 setdest(newtopright, toppoint);
\r
6287 setapex(newtopright, insertpoint);
\r
6288 setorg(topright, insertpoint);
\r
6289 for (i = 0; i < eextras; i++) {
\r
6290 /* Set the element attributes of another new triangle. */
\r
6291 setelemattribute(newtopright, i, elemattribute(topright, i));
\r
6294 /* Set the area constraint of another new triangle. */
\r
6295 setareabound(newtopright, areabound(topright));
\r
6299 /* There may be shell edges that need to be bonded */
\r
6300 /* to the new triangle(s). */
\r
6301 if (checksegments) {
\r
6302 tspivot(botright, botrshelle);
\r
6303 if (botrshelle.sh != dummysh) {
\r
6304 tsdissolve(botright);
\r
6305 tsbond(newbotright, botrshelle);
\r
6308 tspivot(topright, toprshelle);
\r
6309 if (toprshelle.sh != dummysh) {
\r
6310 tsdissolve(topright);
\r
6311 tsbond(newtopright, toprshelle);
\r
6316 /* Bond the new triangle(s) to the surrounding triangles. */
\r
6317 bond(newbotright, botrcasing);
\r
6318 lprevself(newbotright);
\r
6319 bond(newbotright, botright);
\r
6320 lprevself(newbotright);
\r
6322 bond(newtopright, toprcasing);
\r
6323 lnextself(newtopright);
\r
6324 bond(newtopright, topright);
\r
6325 lnextself(newtopright);
\r
6326 bond(newtopright, newbotright);
\r
6329 if (splitedge != (struct edge *) NULL) {
\r
6330 /* Split the shell edge into two. */
\r
6331 setsdest(*splitedge, insertpoint);
\r
6332 ssymself(*splitedge);
\r
6333 spivot(*splitedge, rightedge);
\r
6334 insertshelle(&newbotright, mark(*splitedge));
\r
6335 tspivot(newbotright, newedge);
\r
6336 sbond(*splitedge, newedge);
\r
6337 ssymself(newedge);
\r
6338 sbond(newedge, rightedge);
\r
6339 ssymself(*splitedge);
\r
6343 if (counterclockwise(rightpoint, leftpoint, botpoint) < 0.0) {
\r
6344 printf("Internal error in insertsite():\n");
\r
6345 printf(" Clockwise triangle prior to edge point insertion (bottom).\n");
\r
6348 if (counterclockwise(leftpoint, rightpoint, toppoint) < 0.0) {
\r
6349 printf("Internal error in insertsite():\n");
\r
6350 printf(" Clockwise triangle prior to edge point insertion (top).\n");
\r
6352 if (counterclockwise(rightpoint, toppoint, insertpoint) < 0.0) {
\r
6353 printf("Internal error in insertsite():\n");
\r
6354 printf(" Clockwise triangle after edge point insertion (top right).\n"
\r
6357 if (counterclockwise(toppoint, leftpoint, insertpoint) < 0.0) {
\r
6358 printf("Internal error in insertsite():\n");
\r
6359 printf(" Clockwise triangle after edge point insertion (top left).\n"
\r
6363 if (counterclockwise(leftpoint, botpoint, insertpoint) < 0.0) {
\r
6364 printf("Internal error in insertsite():\n");
\r
6365 printf(" Clockwise triangle after edge point insertion (bottom left).\n"
\r
6368 if (counterclockwise(botpoint, rightpoint, insertpoint) < 0.0) {
\r
6369 printf("Internal error in insertsite():\n");
\r
6371 " Clockwise triangle after edge point insertion (bottom right).\n");
\r
6373 #endif /* SELF_CHECK */
\r
6374 if (verbose > 2) {
\r
6375 printf(" Updating bottom left ");
\r
6376 printtriangle(&botright);
\r
6378 printf(" Updating top left ");
\r
6379 printtriangle(&topright);
\r
6380 printf(" Creating top right ");
\r
6381 printtriangle(&newtopright);
\r
6383 printf(" Creating bottom right ");
\r
6384 printtriangle(&newbotright);
\r
6387 /* Position `horiz' on the first edge to check for */
\r
6388 /* the Delaunay property. */
\r
6391 /* Insert the point in a triangle, splitting it into three. */
\r
6392 lnext(horiz, botleft);
\r
6393 lprev(horiz, botright);
\r
6394 sym(botleft, botlcasing);
\r
6395 sym(botright, botrcasing);
\r
6396 maketriangle(&newbotleft);
\r
6397 maketriangle(&newbotright);
\r
6399 /* Set the vertices of changed and new triangles. */
\r
6400 org(horiz, rightpoint);
\r
6401 dest(horiz, leftpoint);
\r
6402 apex(horiz, botpoint);
\r
6403 setorg(newbotleft, leftpoint);
\r
6404 setdest(newbotleft, botpoint);
\r
6405 setapex(newbotleft, insertpoint);
\r
6406 setorg(newbotright, botpoint);
\r
6407 setdest(newbotright, rightpoint);
\r
6408 setapex(newbotright, insertpoint);
\r
6409 setapex(horiz, insertpoint);
\r
6410 for (i = 0; i < eextras; i++) {
\r
6411 /* Set the element attributes of the new triangles. */
\r
6412 attrib = elemattribute(horiz, i);
\r
6413 setelemattribute(newbotleft, i, attrib);
\r
6414 setelemattribute(newbotright, i, attrib);
\r
6417 /* Set the area constraint of the new triangles. */
\r
6418 area = areabound(horiz);
\r
6419 setareabound(newbotleft, area);
\r
6420 setareabound(newbotright, area);
\r
6423 /* There may be shell edges that need to be bonded */
\r
6424 /* to the new triangles. */
\r
6425 if (checksegments) {
\r
6426 tspivot(botleft, botlshelle);
\r
6427 if (botlshelle.sh != dummysh) {
\r
6428 tsdissolve(botleft);
\r
6429 tsbond(newbotleft, botlshelle);
\r
6431 tspivot(botright, botrshelle);
\r
6432 if (botrshelle.sh != dummysh) {
\r
6433 tsdissolve(botright);
\r
6434 tsbond(newbotright, botrshelle);
\r
6438 /* Bond the new triangles to the surrounding triangles. */
\r
6439 bond(newbotleft, botlcasing);
\r
6440 bond(newbotright, botrcasing);
\r
6441 lnextself(newbotleft);
\r
6442 lprevself(newbotright);
\r
6443 bond(newbotleft, newbotright);
\r
6444 lnextself(newbotleft);
\r
6445 bond(botleft, newbotleft);
\r
6446 lprevself(newbotright);
\r
6447 bond(botright, newbotright);
\r
6450 if (counterclockwise(rightpoint, leftpoint, botpoint) < 0.0) {
\r
6451 printf("Internal error in insertsite():\n");
\r
6452 printf(" Clockwise triangle prior to point insertion.\n");
\r
6454 if (counterclockwise(rightpoint, leftpoint, insertpoint) < 0.0) {
\r
6455 printf("Internal error in insertsite():\n");
\r
6456 printf(" Clockwise triangle after point insertion (top).\n");
\r
6458 if (counterclockwise(leftpoint, botpoint, insertpoint) < 0.0) {
\r
6459 printf("Internal error in insertsite():\n");
\r
6460 printf(" Clockwise triangle after point insertion (left).\n");
\r
6462 if (counterclockwise(botpoint, rightpoint, insertpoint) < 0.0) {
\r
6463 printf("Internal error in insertsite():\n");
\r
6464 printf(" Clockwise triangle after point insertion (right).\n");
\r
6466 #endif /* SELF_CHECK */
\r
6467 if (verbose > 2) {
\r
6468 printf(" Updating top ");
\r
6469 printtriangle(&horiz);
\r
6470 printf(" Creating left ");
\r
6471 printtriangle(&newbotleft);
\r
6472 printf(" Creating right ");
\r
6473 printtriangle(&newbotright);
\r
6477 /* The insertion is successful by default, unless an encroached */
\r
6478 /* edge is found. */
\r
6479 success = SUCCESSFULPOINT;
\r
6480 /* Circle around the newly inserted vertex, checking each edge opposite */
\r
6481 /* it for the Delaunay property. Non-Delaunay edges are flipped. */
\r
6482 /* `horiz' is always the edge being checked. `first' marks where to */
\r
6483 /* stop circling. */
\r
6484 org(horiz, first);
\r
6485 rightpoint = first;
\r
6486 dest(horiz, leftpoint);
\r
6487 /* Circle until finished. */
\r
6489 /* By default, the edge will be flipped. */
\r
6491 if (checksegments) {
\r
6492 /* Check for a segment, which cannot be flipped. */
\r
6493 tspivot(horiz, checkshelle);
\r
6494 if (checkshelle.sh != dummysh) {
\r
6495 /* The edge is a segment and cannot be flipped. */
\r
6498 if (segmentflaws) {
\r
6499 /* Does the new point encroach upon this segment? */
\r
6500 if (checkedge4encroach(&checkshelle)) {
\r
6501 success = ENCROACHINGPOINT;
\r
6504 #endif /* not CDT_ONLY */
\r
6508 /* Check if the edge is a boundary edge. */
\r
6510 if (top.tri == dummytri) {
\r
6511 /* The edge is a boundary edge and cannot be flipped. */
\r
6514 /* Find the point on the other side of the edge. */
\r
6515 apex(top, farpoint);
\r
6516 /* In the incremental Delaunay triangulation algorithm, any of */
\r
6517 /* `leftpoint', `rightpoint', and `farpoint' could be vertices */
\r
6518 /* of the triangular bounding box. These vertices must be */
\r
6519 /* treated as if they are infinitely distant, even though their */
\r
6520 /* "coordinates" are not. */
\r
6521 if ((leftpoint == infpoint1) || (leftpoint == infpoint2)
\r
6522 || (leftpoint == infpoint3)) {
\r
6523 /* `leftpoint' is infinitely distant. Check the convexity of */
\r
6524 /* the boundary of the triangulation. 'farpoint' might be */
\r
6525 /* infinite as well, but trust me, this same condition */
\r
6526 /* should be applied. */
\r
6527 doflip = counterclockwise(insertpoint, rightpoint, farpoint) > 0.0;
\r
6528 } else if ((rightpoint == infpoint1) || (rightpoint == infpoint2)
\r
6529 || (rightpoint == infpoint3)) {
\r
6530 /* `rightpoint' is infinitely distant. Check the convexity of */
\r
6531 /* the boundary of the triangulation. 'farpoint' might be */
\r
6532 /* infinite as well, but trust me, this same condition */
\r
6533 /* should be applied. */
\r
6534 doflip = counterclockwise(farpoint, leftpoint, insertpoint) > 0.0;
\r
6535 } else if ((farpoint == infpoint1) || (farpoint == infpoint2)
\r
6536 || (farpoint == infpoint3)) {
\r
6537 /* `farpoint' is infinitely distant and cannot be inside */
\r
6538 /* the circumcircle of the triangle `horiz'. */
\r
6541 /* Test whether the edge is locally Delaunay. */
\r
6542 doflip = incircle(leftpoint, insertpoint, rightpoint, farpoint)
\r
6546 /* We made it! Flip the edge `horiz' by rotating its containing */
\r
6547 /* quadrilateral (the two triangles adjacent to `horiz'). */
\r
6548 /* Identify the casing of the quadrilateral. */
\r
6549 lprev(top, topleft);
\r
6550 sym(topleft, toplcasing);
\r
6551 lnext(top, topright);
\r
6552 sym(topright, toprcasing);
\r
6553 lnext(horiz, botleft);
\r
6554 sym(botleft, botlcasing);
\r
6555 lprev(horiz, botright);
\r
6556 sym(botright, botrcasing);
\r
6557 /* Rotate the quadrilateral one-quarter turn counterclockwise. */
\r
6558 bond(topleft, botlcasing);
\r
6559 bond(botleft, botrcasing);
\r
6560 bond(botright, toprcasing);
\r
6561 bond(topright, toplcasing);
\r
6562 if (checksegments) {
\r
6563 /* Check for shell edges and rebond them to the quadrilateral. */
\r
6564 tspivot(topleft, toplshelle);
\r
6565 tspivot(botleft, botlshelle);
\r
6566 tspivot(botright, botrshelle);
\r
6567 tspivot(topright, toprshelle);
\r
6568 if (toplshelle.sh == dummysh) {
\r
6569 tsdissolve(topright);
\r
6571 tsbond(topright, toplshelle);
\r
6573 if (botlshelle.sh == dummysh) {
\r
6574 tsdissolve(topleft);
\r
6576 tsbond(topleft, botlshelle);
\r
6578 if (botrshelle.sh == dummysh) {
\r
6579 tsdissolve(botleft);
\r
6581 tsbond(botleft, botrshelle);
\r
6583 if (toprshelle.sh == dummysh) {
\r
6584 tsdissolve(botright);
\r
6586 tsbond(botright, toprshelle);
\r
6589 /* New point assignments for the rotated quadrilateral. */
\r
6590 setorg(horiz, farpoint);
\r
6591 setdest(horiz, insertpoint);
\r
6592 setapex(horiz, rightpoint);
\r
6593 setorg(top, insertpoint);
\r
6594 setdest(top, farpoint);
\r
6595 setapex(top, leftpoint);
\r
6596 for (i = 0; i < eextras; i++) {
\r
6597 /* Take the average of the two triangles' attributes. */
\r
6598 attrib = (REAL)(0.5 * (elemattribute(top, i) + elemattribute(horiz, i)));
\r
6599 setelemattribute(top, i, attrib);
\r
6600 setelemattribute(horiz, i, attrib);
\r
6603 if ((areabound(top) <= 0.0) || (areabound(horiz) <= 0.0)) {
\r
6606 /* Take the average of the two triangles' area constraints. */
\r
6607 /* This prevents small area constraints from migrating a */
\r
6608 /* long, long way from their original location due to flips. */
\r
6609 area = (REAL)(0.5 * (areabound(top) + areabound(horiz)));
\r
6611 setareabound(top, area);
\r
6612 setareabound(horiz, area);
\r
6615 if (insertpoint != (point) NULL) {
\r
6616 if (counterclockwise(leftpoint, insertpoint, rightpoint) < 0.0) {
\r
6617 printf("Internal error in insertsite():\n");
\r
6618 printf(" Clockwise triangle prior to edge flip (bottom).\n");
\r
6620 /* The following test has been removed because constrainededge() */
\r
6621 /* sometimes generates inverted triangles that insertsite() */
\r
6624 if (counterclockwise(rightpoint, farpoint, leftpoint) < 0.0) {
\r
6625 printf("Internal error in insertsite():\n");
\r
6626 printf(" Clockwise triangle prior to edge flip (top).\n");
\r
6629 if (counterclockwise(farpoint, leftpoint, insertpoint) < 0.0) {
\r
6630 printf("Internal error in insertsite():\n");
\r
6631 printf(" Clockwise triangle after edge flip (left).\n");
\r
6633 if (counterclockwise(insertpoint, rightpoint, farpoint) < 0.0) {
\r
6634 printf("Internal error in insertsite():\n");
\r
6635 printf(" Clockwise triangle after edge flip (right).\n");
\r
6638 #endif /* SELF_CHECK */
\r
6639 if (verbose > 2) {
\r
6640 printf(" Edge flip results in left ");
\r
6641 lnextself(topleft);
\r
6642 printtriangle(&topleft);
\r
6643 printf(" and right ");
\r
6644 printtriangle(&horiz);
\r
6646 /* On the next iterations, consider the two edges that were */
\r
6647 /* exposed (this is, are now visible to the newly inserted */
\r
6648 /* point) by the edge flip. */
\r
6650 leftpoint = farpoint;
\r
6655 /* The handle `horiz' is accepted as locally Delaunay. */
\r
6658 /* Check the triangle `horiz' for quality. */
\r
6659 testtriangle(&horiz);
\r
6661 #endif /* not CDT_ONLY */
\r
6662 /* Look for the next edge around the newly inserted point. */
\r
6664 sym(horiz, testtri);
\r
6665 /* Check for finishing a complete revolution about the new point, or */
\r
6666 /* falling off the edge of the triangulation. The latter will */
\r
6667 /* happen when a point is inserted at a boundary. */
\r
6668 if ((leftpoint == first) || (testtri.tri == dummytri)) {
\r
6669 /* We're done. Return a triangle whose origin is the new point. */
\r
6670 lnext(horiz, *searchtri);
\r
6671 lnext(horiz, recenttri);
\r
6674 /* Finish finding the next edge around the newly inserted point. */
\r
6675 lnext(testtri, horiz);
\r
6676 rightpoint = leftpoint;
\r
6677 dest(horiz, leftpoint);
\r
6682 /*****************************************************************************/
\r
6684 /* triangulatepolygon() Find the Delaunay triangulation of a polygon that */
\r
6685 /* has a certain "nice" shape. This includes the */
\r
6686 /* polygons that result from deletion of a point or */
\r
6687 /* insertion of a segment. */
\r
6689 /* This is a conceptually difficult routine. The starting assumption is */
\r
6690 /* that we have a polygon with n sides. n - 1 of these sides are currently */
\r
6691 /* represented as edges in the mesh. One side, called the "base", need not */
\r
6694 /* Inside the polygon is a structure I call a "fan", consisting of n - 1 */
\r
6695 /* triangles that share a common origin. For each of these triangles, the */
\r
6696 /* edge opposite the origin is one of the sides of the polygon. The */
\r
6697 /* primary edge of each triangle is the edge directed from the origin to */
\r
6698 /* the destination; note that this is not the same edge that is a side of */
\r
6699 /* the polygon. `firstedge' is the primary edge of the first triangle. */
\r
6700 /* From there, the triangles follow in counterclockwise order about the */
\r
6701 /* polygon, until `lastedge', the primary edge of the last triangle. */
\r
6702 /* `firstedge' and `lastedge' are probably connected to other triangles */
\r
6703 /* beyond the extremes of the fan, but their identity is not important, as */
\r
6704 /* long as the fan remains connected to them. */
\r
6706 /* Imagine the polygon oriented so that its base is at the bottom. This */
\r
6707 /* puts `firstedge' on the far right, and `lastedge' on the far left. */
\r
6708 /* The right vertex of the base is the destination of `firstedge', and the */
\r
6709 /* left vertex of the base is the apex of `lastedge'. */
\r
6711 /* The challenge now is to find the right sequence of edge flips to */
\r
6712 /* transform the fan into a Delaunay triangulation of the polygon. Each */
\r
6713 /* edge flip effectively removes one triangle from the fan, committing it */
\r
6714 /* to the polygon. The resulting polygon has one fewer edge. If `doflip' */
\r
6715 /* is set, the final flip will be performed, resulting in a fan of one */
\r
6716 /* (useless?) triangle. If `doflip' is not set, the final flip is not */
\r
6717 /* performed, resulting in a fan of two triangles, and an unfinished */
\r
6718 /* triangular polygon that is not yet filled out with a single triangle. */
\r
6719 /* On completion of the routine, `lastedge' is the last remaining triangle, */
\r
6720 /* or the leftmost of the last two. */
\r
6722 /* Although the flips are performed in the order described above, the */
\r
6723 /* decisions about what flips to perform are made in precisely the reverse */
\r
6724 /* order. The recursive triangulatepolygon() procedure makes a decision, */
\r
6725 /* uses up to two recursive calls to triangulate the "subproblems" */
\r
6726 /* (polygons with fewer edges), and then performs an edge flip. */
\r
6728 /* The "decision" it makes is which vertex of the polygon should be */
\r
6729 /* connected to the base. This decision is made by testing every possible */
\r
6730 /* vertex. Once the best vertex is found, the two edges that connect this */
\r
6731 /* vertex to the base become the bases for two smaller polygons. These */
\r
6732 /* are triangulated recursively. Unfortunately, this approach can take */
\r
6733 /* O(n^2) time not only in the worst case, but in many common cases. It's */
\r
6734 /* rarely a big deal for point deletion, where n is rarely larger than ten, */
\r
6735 /* but it could be a big deal for segment insertion, especially if there's */
\r
6736 /* a lot of long segments that each cut many triangles. I ought to code */
\r
6737 /* a faster algorithm some time. */
\r
6739 /* The `edgecount' parameter is the number of sides of the polygon, */
\r
6740 /* including its base. `triflaws' is a flag that determines whether the */
\r
6741 /* new triangles should be tested for quality, and enqueued if they are */
\r
6744 /*****************************************************************************/
\r
6746 void triangulatepolygon(firstedge, lastedge, edgecount, doflip, triflaws)
\r
6747 struct triedge *firstedge;
\r
6748 struct triedge *lastedge;
\r
6753 struct triedge testtri;
\r
6754 struct triedge besttri;
\r
6755 struct triedge tempedge;
\r
6756 point leftbasepoint, rightbasepoint;
\r
6761 triangle ptr; /* Temporary variable used by sym(), onext(), and oprev(). */
\r
6763 /* Identify the base vertices. */
\r
6764 apex(*lastedge, leftbasepoint);
\r
6765 dest(*firstedge, rightbasepoint);
\r
6766 if (verbose > 2) {
\r
6767 printf(" Triangulating interior polygon at edge\n");
\r
6768 printf(" (%.12g, %.12g) (%.12g, %.12g)\n", leftbasepoint[0],
\r
6769 leftbasepoint[1], rightbasepoint[0], rightbasepoint[1]);
\r
6771 /* Find the best vertex to connect the base to. */
\r
6772 onext(*firstedge, besttri);
\r
6773 dest(besttri, bestpoint);
\r
6774 triedgecopy(besttri, testtri);
\r
6776 for (i = 2; i <= edgecount - 2; i++) {
\r
6777 onextself(testtri);
\r
6778 dest(testtri, testpoint);
\r
6779 /* Is this a better vertex? */
\r
6780 if (incircle(leftbasepoint, rightbasepoint, bestpoint, testpoint) > 0.0) {
\r
6781 triedgecopy(testtri, besttri);
\r
6782 bestpoint = testpoint;
\r
6786 if (verbose > 2) {
\r
6787 printf(" Connecting edge to (%.12g, %.12g)\n", bestpoint[0],
\r
6790 if (bestnumber > 1) {
\r
6791 /* Recursively triangulate the smaller polygon on the right. */
\r
6792 oprev(besttri, tempedge);
\r
6793 triangulatepolygon(firstedge, &tempedge, bestnumber + 1, 1, triflaws);
\r
6795 if (bestnumber < edgecount - 2) {
\r
6796 /* Recursively triangulate the smaller polygon on the left. */
\r
6797 sym(besttri, tempedge);
\r
6798 triangulatepolygon(&besttri, lastedge, edgecount - bestnumber, 1,
\r
6800 /* Find `besttri' again; it may have been lost to edge flips. */
\r
6801 sym(tempedge, besttri);
\r
6804 /* Do one final edge flip. */
\r
6808 /* Check the quality of the newly committed triangle. */
\r
6809 sym(besttri, testtri);
\r
6810 testtriangle(&testtri);
\r
6812 #endif /* not CDT_ONLY */
\r
6814 /* Return the base triangle. */
\r
6815 triedgecopy(besttri, *lastedge);
\r
6818 /*****************************************************************************/
\r
6820 /* deletesite() Delete a vertex from a Delaunay triangulation, ensuring */
\r
6821 /* that the triangulation remains Delaunay. */
\r
6823 /* The origin of `deltri' is deleted. The union of the triangles adjacent */
\r
6824 /* to this point is a polygon, for which the Delaunay triangulation is */
\r
6825 /* found. Two triangles are removed from the mesh. */
\r
6827 /* Only interior points that do not lie on segments (shell edges) or */
\r
6828 /* boundaries may be deleted. */
\r
6830 /*****************************************************************************/
\r
6834 void deletesite(deltri)
\r
6835 struct triedge *deltri;
\r
6837 struct triedge countingtri;
\r
6838 struct triedge firstedge, lastedge;
\r
6839 struct triedge deltriright;
\r
6840 struct triedge lefttri, righttri;
\r
6841 struct triedge leftcasing, rightcasing;
\r
6842 struct edge leftshelle, rightshelle;
\r
6846 triangle ptr; /* Temporary variable used by sym(), onext(), and oprev(). */
\r
6847 shelle sptr; /* Temporary variable used by tspivot(). */
\r
6849 org(*deltri, delpoint);
\r
6850 if (verbose > 1) {
\r
6851 printf(" Deleting (%.12g, %.12g).\n", delpoint[0], delpoint[1]);
\r
6853 pointdealloc(delpoint);
\r
6855 /* Count the degree of the point being deleted. */
\r
6856 onext(*deltri, countingtri);
\r
6858 while (!triedgeequal(*deltri, countingtri)) {
\r
6860 if (countingtri.tri == dummytri) {
\r
6861 printf("Internal error in deletesite():\n");
\r
6862 printf(" Attempt to delete boundary point.\n");
\r
6865 #endif /* SELF_CHECK */
\r
6867 onextself(countingtri);
\r
6871 if (edgecount < 3) {
\r
6872 printf("Internal error in deletesite():\n Point has degree %d.\n",
\r
6876 #endif /* SELF_CHECK */
\r
6877 if (edgecount > 3) {
\r
6878 /* Triangulate the polygon defined by the union of all triangles */
\r
6879 /* adjacent to the point being deleted. Check the quality of */
\r
6880 /* the resulting triangles. */
\r
6881 onext(*deltri, firstedge);
\r
6882 oprev(*deltri, lastedge);
\r
6883 triangulatepolygon(&firstedge, &lastedge, edgecount, 0, !nobisect);
\r
6885 /* Splice out two triangles. */
\r
6886 lprev(*deltri, deltriright);
\r
6887 dnext(*deltri, lefttri);
\r
6888 sym(lefttri, leftcasing);
\r
6889 oprev(deltriright, righttri);
\r
6890 sym(righttri, rightcasing);
\r
6891 bond(*deltri, leftcasing);
\r
6892 bond(deltriright, rightcasing);
\r
6893 tspivot(lefttri, leftshelle);
\r
6894 if (leftshelle.sh != dummysh) {
\r
6895 tsbond(*deltri, leftshelle);
\r
6897 tspivot(righttri, rightshelle);
\r
6898 if (rightshelle.sh != dummysh) {
\r
6899 tsbond(deltriright, rightshelle);
\r
6902 /* Set the new origin of `deltri' and check its quality. */
\r
6903 org(lefttri, neworg);
\r
6904 setorg(*deltri, neworg);
\r
6906 testtriangle(deltri);
\r
6909 /* Delete the two spliced-out triangles. */
\r
6910 triangledealloc(lefttri.tri);
\r
6911 triangledealloc(righttri.tri);
\r
6914 #endif /* not CDT_ONLY */
\r
6918 /********* Mesh transformation routines end here *********/
\r
6920 /********* Divide-and-conquer Delaunay triangulation begins here *********/
\r
6924 /*****************************************************************************/
\r
6926 /* The divide-and-conquer bounding box */
\r
6928 /* I originally implemented the divide-and-conquer and incremental Delaunay */
\r
6929 /* triangulations using the edge-based data structure presented by Guibas */
\r
6930 /* and Stolfi. Switching to a triangle-based data structure doubled the */
\r
6931 /* speed. However, I had to think of a few extra tricks to maintain the */
\r
6932 /* elegance of the original algorithms. */
\r
6934 /* The "bounding box" used by my variant of the divide-and-conquer */
\r
6935 /* algorithm uses one triangle for each edge of the convex hull of the */
\r
6936 /* triangulation. These bounding triangles all share a common apical */
\r
6937 /* vertex, which is represented by NULL and which represents nothing. */
\r
6938 /* The bounding triangles are linked in a circular fan about this NULL */
\r
6939 /* vertex, and the edges on the convex hull of the triangulation appear */
\r
6940 /* opposite the NULL vertex. You might find it easiest to imagine that */
\r
6941 /* the NULL vertex is a point in 3D space behind the center of the */
\r
6942 /* triangulation, and that the bounding triangles form a sort of cone. */
\r
6944 /* This bounding box makes it easy to represent degenerate cases. For */
\r
6945 /* instance, the triangulation of two vertices is a single edge. This edge */
\r
6946 /* is represented by two bounding box triangles, one on each "side" of the */
\r
6947 /* edge. These triangles are also linked together in a fan about the NULL */
\r
6950 /* The bounding box also makes it easy to traverse the convex hull, as the */
\r
6951 /* divide-and-conquer algorithm needs to do. */
\r
6953 /*****************************************************************************/
\r
6955 /*****************************************************************************/
\r
6957 /* pointsort() Sort an array of points by x-coordinate, using the */
\r
6958 /* y-coordinate as a secondary key. */
\r
6960 /* Uses quicksort. Randomized O(n log n) time. No, I did not make any of */
\r
6961 /* the usual quicksort mistakes. */
\r
6963 /*****************************************************************************/
\r
6965 void pointsort(sortarray, arraysize)
\r
6971 REAL pivotx, pivoty;
\r
6974 if (arraysize == 2) {
\r
6975 /* Recursive base case. */
\r
6976 if ((sortarray[0][0] > sortarray[1][0]) ||
\r
6977 ((sortarray[0][0] == sortarray[1][0]) &&
\r
6978 (sortarray[0][1] > sortarray[1][1]))) {
\r
6979 temp = sortarray[1];
\r
6980 sortarray[1] = sortarray[0];
\r
6981 sortarray[0] = temp;
\r
6985 /* Choose a random pivot to split the array. */
\r
6986 pivot = (int) randomnation(arraysize);
\r
6987 pivotx = sortarray[pivot][0];
\r
6988 pivoty = sortarray[pivot][1];
\r
6989 /* Split the array. */
\r
6991 right = arraysize;
\r
6992 while (left < right) {
\r
6993 /* Search for a point whose x-coordinate is too large for the left. */
\r
6996 } while ((left <= right) && ((sortarray[left][0] < pivotx) ||
\r
6997 ((sortarray[left][0] == pivotx) &&
\r
6998 (sortarray[left][1] < pivoty))));
\r
6999 /* Search for a point whose x-coordinate is too small for the right. */
\r
7002 } while ((left <= right) && ((sortarray[right][0] > pivotx) ||
\r
7003 ((sortarray[right][0] == pivotx) &&
\r
7004 (sortarray[right][1] > pivoty))));
\r
7005 if (left < right) {
\r
7006 /* Swap the left and right points. */
\r
7007 temp = sortarray[left];
\r
7008 sortarray[left] = sortarray[right];
\r
7009 sortarray[right] = temp;
\r
7013 /* Recursively sort the left subset. */
\r
7014 pointsort(sortarray, left);
\r
7016 if (right < arraysize - 2) {
\r
7017 /* Recursively sort the right subset. */
\r
7018 pointsort(&sortarray[right + 1], arraysize - right - 1);
\r
7022 /*****************************************************************************/
\r
7024 /* pointmedian() An order statistic algorithm, almost. Shuffles an array */
\r
7025 /* of points so that the first `median' points occur */
\r
7026 /* lexicographically before the remaining points. */
\r
7028 /* Uses the x-coordinate as the primary key if axis == 0; the y-coordinate */
\r
7029 /* if axis == 1. Very similar to the pointsort() procedure, but runs in */
\r
7030 /* randomized linear time. */
\r
7032 /*****************************************************************************/
\r
7034 void pointmedian(sortarray, arraysize, median, axis)
\r
7042 REAL pivot1, pivot2;
\r
7045 if (arraysize == 2) {
\r
7046 /* Recursive base case. */
\r
7047 if ((sortarray[0][axis] > sortarray[1][axis]) ||
\r
7048 ((sortarray[0][axis] == sortarray[1][axis]) &&
\r
7049 (sortarray[0][1 - axis] > sortarray[1][1 - axis]))) {
\r
7050 temp = sortarray[1];
\r
7051 sortarray[1] = sortarray[0];
\r
7052 sortarray[0] = temp;
\r
7056 /* Choose a random pivot to split the array. */
\r
7057 pivot = (int) randomnation(arraysize);
\r
7058 pivot1 = sortarray[pivot][axis];
\r
7059 pivot2 = sortarray[pivot][1 - axis];
\r
7060 /* Split the array. */
\r
7062 right = arraysize;
\r
7063 while (left < right) {
\r
7064 /* Search for a point whose x-coordinate is too large for the left. */
\r
7067 } while ((left <= right) && ((sortarray[left][axis] < pivot1) ||
\r
7068 ((sortarray[left][axis] == pivot1) &&
\r
7069 (sortarray[left][1 - axis] < pivot2))));
\r
7070 /* Search for a point whose x-coordinate is too small for the right. */
\r
7073 } while ((left <= right) && ((sortarray[right][axis] > pivot1) ||
\r
7074 ((sortarray[right][axis] == pivot1) &&
\r
7075 (sortarray[right][1 - axis] > pivot2))));
\r
7076 if (left < right) {
\r
7077 /* Swap the left and right points. */
\r
7078 temp = sortarray[left];
\r
7079 sortarray[left] = sortarray[right];
\r
7080 sortarray[right] = temp;
\r
7083 /* Unlike in pointsort(), at most one of the following */
\r
7084 /* conditionals is true. */
\r
7085 if (left > median) {
\r
7086 /* Recursively shuffle the left subset. */
\r
7087 pointmedian(sortarray, left, median, axis);
\r
7089 if (right < median - 1) {
\r
7090 /* Recursively shuffle the right subset. */
\r
7091 pointmedian(&sortarray[right + 1], arraysize - right - 1,
\r
7092 median - right - 1, axis);
\r
7096 /*****************************************************************************/
\r
7098 /* alternateaxes() Sorts the points as appropriate for the divide-and- */
\r
7099 /* conquer algorithm with alternating cuts. */
\r
7101 /* Partitions by x-coordinate if axis == 0; by y-coordinate if axis == 1. */
\r
7102 /* For the base case, subsets containing only two or three points are */
\r
7103 /* always sorted by x-coordinate. */
\r
7105 /*****************************************************************************/
\r
7107 void alternateaxes(sortarray, arraysize, axis)
\r
7114 divider = arraysize >> 1;
\r
7115 if (arraysize <= 3) {
\r
7116 /* Recursive base case: subsets of two or three points will be */
\r
7117 /* handled specially, and should always be sorted by x-coordinate. */
\r
7120 /* Partition with a horizontal or vertical cut. */
\r
7121 pointmedian(sortarray, arraysize, divider, axis);
\r
7122 /* Recursively partition the subsets with a cross cut. */
\r
7123 if (arraysize - divider >= 2) {
\r
7124 if (divider >= 2) {
\r
7125 alternateaxes(sortarray, divider, 1 - axis);
\r
7127 alternateaxes(&sortarray[divider], arraysize - divider, 1 - axis);
\r
7131 /*****************************************************************************/
\r
7133 /* mergehulls() Merge two adjacent Delaunay triangulations into a */
\r
7134 /* single Delaunay triangulation. */
\r
7136 /* This is similar to the algorithm given by Guibas and Stolfi, but uses */
\r
7137 /* a triangle-based, rather than edge-based, data structure. */
\r
7139 /* The algorithm walks up the gap between the two triangulations, knitting */
\r
7140 /* them together. As they are merged, some of their bounding triangles */
\r
7141 /* are converted into real triangles of the triangulation. The procedure */
\r
7142 /* pulls each hull's bounding triangles apart, then knits them together */
\r
7143 /* like the teeth of two gears. The Delaunay property determines, at each */
\r
7144 /* step, whether the next "tooth" is a bounding triangle of the left hull */
\r
7145 /* or the right. When a bounding triangle becomes real, its apex is */
\r
7146 /* changed from NULL to a real point. */
\r
7148 /* Only two new triangles need to be allocated. These become new bounding */
\r
7149 /* triangles at the top and bottom of the seam. They are used to connect */
\r
7150 /* the remaining bounding triangles (those that have not been converted */
\r
7151 /* into real triangles) into a single fan. */
\r
7153 /* On entry, `farleft' and `innerleft' are bounding triangles of the left */
\r
7154 /* triangulation. The origin of `farleft' is the leftmost vertex, and */
\r
7155 /* the destination of `innerleft' is the rightmost vertex of the */
\r
7156 /* triangulation. Similarly, `innerright' and `farright' are bounding */
\r
7157 /* triangles of the right triangulation. The origin of `innerright' and */
\r
7158 /* destination of `farright' are the leftmost and rightmost vertices. */
\r
7160 /* On completion, the origin of `farleft' is the leftmost vertex of the */
\r
7161 /* merged triangulation, and the destination of `farright' is the rightmost */
\r
7164 /*****************************************************************************/
\r
7166 void mergehulls(farleft, innerleft, innerright, farright, axis)
\r
7167 struct triedge *farleft;
\r
7168 struct triedge *innerleft;
\r
7169 struct triedge *innerright;
\r
7170 struct triedge *farright;
\r
7173 struct triedge leftcand, rightcand;
\r
7174 struct triedge baseedge;
\r
7175 struct triedge nextedge;
\r
7176 struct triedge sidecasing, topcasing, outercasing;
\r
7177 struct triedge checkedge;
\r
7178 point innerleftdest;
\r
7179 point innerrightorg;
\r
7180 point innerleftapex, innerrightapex;
\r
7181 point farleftpt, farrightpt;
\r
7182 point farleftapex, farrightapex;
\r
7183 point lowerleft, lowerright;
\r
7184 point upperleft, upperright;
\r
7186 point checkvertex;
\r
7189 int leftfinished, rightfinished;
\r
7190 triangle ptr; /* Temporary variable used by sym(). */
\r
7192 dest(*innerleft, innerleftdest);
\r
7193 apex(*innerleft, innerleftapex);
\r
7194 org(*innerright, innerrightorg);
\r
7195 apex(*innerright, innerrightapex);
\r
7196 /* Special treatment for horizontal cuts. */
\r
7197 if (dwyer && (axis == 1)) {
\r
7198 org(*farleft, farleftpt);
\r
7199 apex(*farleft, farleftapex);
\r
7200 dest(*farright, farrightpt);
\r
7201 apex(*farright, farrightapex);
\r
7202 /* The pointers to the extremal points are shifted to point to the */
\r
7203 /* topmost and bottommost point of each hull, rather than the */
\r
7204 /* leftmost and rightmost points. */
\r
7205 while (farleftapex[1] < farleftpt[1]) {
\r
7206 lnextself(*farleft);
\r
7207 symself(*farleft);
\r
7208 farleftpt = farleftapex;
\r
7209 apex(*farleft, farleftapex);
\r
7211 sym(*innerleft, checkedge);
\r
7212 apex(checkedge, checkvertex);
\r
7213 while (checkvertex[1] > innerleftdest[1]) {
\r
7214 lnext(checkedge, *innerleft);
\r
7215 innerleftapex = innerleftdest;
\r
7216 innerleftdest = checkvertex;
\r
7217 sym(*innerleft, checkedge);
\r
7218 apex(checkedge, checkvertex);
\r
7220 while (innerrightapex[1] < innerrightorg[1]) {
\r
7221 lnextself(*innerright);
\r
7222 symself(*innerright);
\r
7223 innerrightorg = innerrightapex;
\r
7224 apex(*innerright, innerrightapex);
\r
7226 sym(*farright, checkedge);
\r
7227 apex(checkedge, checkvertex);
\r
7228 while (checkvertex[1] > farrightpt[1]) {
\r
7229 lnext(checkedge, *farright);
\r
7230 farrightapex = farrightpt;
\r
7231 farrightpt = checkvertex;
\r
7232 sym(*farright, checkedge);
\r
7233 apex(checkedge, checkvertex);
\r
7236 /* Find a line tangent to and below both hulls. */
\r
7239 /* Make innerleftdest the "bottommost" point of the left hull. */
\r
7240 if (counterclockwise(innerleftdest, innerleftapex, innerrightorg) > 0.0) {
\r
7241 lprevself(*innerleft);
\r
7242 symself(*innerleft);
\r
7243 innerleftdest = innerleftapex;
\r
7244 apex(*innerleft, innerleftapex);
\r
7247 /* Make innerrightorg the "bottommost" point of the right hull. */
\r
7248 if (counterclockwise(innerrightapex, innerrightorg, innerleftdest) > 0.0) {
\r
7249 lnextself(*innerright);
\r
7250 symself(*innerright);
\r
7251 innerrightorg = innerrightapex;
\r
7252 apex(*innerright, innerrightapex);
\r
7255 } while (changemade);
\r
7256 /* Find the two candidates to be the next "gear tooth". */
\r
7257 sym(*innerleft, leftcand);
\r
7258 sym(*innerright, rightcand);
\r
7259 /* Create the bottom new bounding triangle. */
\r
7260 maketriangle(&baseedge);
\r
7261 /* Connect it to the bounding boxes of the left and right triangulations. */
\r
7262 bond(baseedge, *innerleft);
\r
7263 lnextself(baseedge);
\r
7264 bond(baseedge, *innerright);
\r
7265 lnextself(baseedge);
\r
7266 setorg(baseedge, innerrightorg);
\r
7267 setdest(baseedge, innerleftdest);
\r
7268 /* Apex is intentionally left NULL. */
\r
7269 if (verbose > 2) {
\r
7270 printf(" Creating base bounding ");
\r
7271 printtriangle(&baseedge);
\r
7273 /* Fix the extreme triangles if necessary. */
\r
7274 org(*farleft, farleftpt);
\r
7275 if (innerleftdest == farleftpt) {
\r
7276 lnext(baseedge, *farleft);
\r
7278 dest(*farright, farrightpt);
\r
7279 if (innerrightorg == farrightpt) {
\r
7280 lprev(baseedge, *farright);
\r
7282 /* The vertices of the current knitting edge. */
\r
7283 lowerleft = innerleftdest;
\r
7284 lowerright = innerrightorg;
\r
7285 /* The candidate vertices for knitting. */
\r
7286 apex(leftcand, upperleft);
\r
7287 apex(rightcand, upperright);
\r
7288 /* Walk up the gap between the two triangulations, knitting them together. */
\r
7290 /* Have we reached the top? (This isn't quite the right question, */
\r
7291 /* because even though the left triangulation might seem finished now, */
\r
7292 /* moving up on the right triangulation might reveal a new point of */
\r
7293 /* the left triangulation. And vice-versa.) */
\r
7294 leftfinished = counterclockwise(upperleft, lowerleft, lowerright) <= 0.0;
\r
7295 rightfinished = counterclockwise(upperright, lowerleft, lowerright) <= 0.0;
\r
7296 if (leftfinished && rightfinished) {
\r
7297 /* Create the top new bounding triangle. */
\r
7298 maketriangle(&nextedge);
\r
7299 setorg(nextedge, lowerleft);
\r
7300 setdest(nextedge, lowerright);
\r
7301 /* Apex is intentionally left NULL. */
\r
7302 /* Connect it to the bounding boxes of the two triangulations. */
\r
7303 bond(nextedge, baseedge);
\r
7304 lnextself(nextedge);
\r
7305 bond(nextedge, rightcand);
\r
7306 lnextself(nextedge);
\r
7307 bond(nextedge, leftcand);
\r
7308 if (verbose > 2) {
\r
7309 printf(" Creating top bounding ");
\r
7310 printtriangle(&baseedge);
\r
7312 /* Special treatment for horizontal cuts. */
\r
7313 if (dwyer && (axis == 1)) {
\r
7314 org(*farleft, farleftpt);
\r
7315 apex(*farleft, farleftapex);
\r
7316 dest(*farright, farrightpt);
\r
7317 apex(*farright, farrightapex);
\r
7318 sym(*farleft, checkedge);
\r
7319 apex(checkedge, checkvertex);
\r
7320 /* The pointers to the extremal points are restored to the leftmost */
\r
7321 /* and rightmost points (rather than topmost and bottommost). */
\r
7322 while (checkvertex[0] < farleftpt[0]) {
\r
7323 lprev(checkedge, *farleft);
\r
7324 farleftapex = farleftpt;
\r
7325 farleftpt = checkvertex;
\r
7326 sym(*farleft, checkedge);
\r
7327 apex(checkedge, checkvertex);
\r
7329 while (farrightapex[0] > farrightpt[0]) {
\r
7330 lprevself(*farright);
\r
7331 symself(*farright);
\r
7332 farrightpt = farrightapex;
\r
7333 apex(*farright, farrightapex);
\r
7338 /* Consider eliminating edges from the left triangulation. */
\r
7339 if (!leftfinished) {
\r
7340 /* What vertex would be exposed if an edge were deleted? */
\r
7341 lprev(leftcand, nextedge);
\r
7342 symself(nextedge);
\r
7343 apex(nextedge, nextapex);
\r
7344 /* If nextapex is NULL, then no vertex would be exposed; the */
\r
7345 /* triangulation would have been eaten right through. */
\r
7346 if (nextapex != (point) NULL) {
\r
7347 /* Check whether the edge is Delaunay. */
\r
7348 badedge = incircle(lowerleft, lowerright, upperleft, nextapex) > 0.0;
\r
7350 /* Eliminate the edge with an edge flip. As a result, the */
\r
7351 /* left triangulation will have one more boundary triangle. */
\r
7352 lnextself(nextedge);
\r
7353 sym(nextedge, topcasing);
\r
7354 lnextself(nextedge);
\r
7355 sym(nextedge, sidecasing);
\r
7356 bond(nextedge, topcasing);
\r
7357 bond(leftcand, sidecasing);
\r
7358 lnextself(leftcand);
\r
7359 sym(leftcand, outercasing);
\r
7360 lprevself(nextedge);
\r
7361 bond(nextedge, outercasing);
\r
7362 /* Correct the vertices to reflect the edge flip. */
\r
7363 setorg(leftcand, lowerleft);
\r
7364 setdest(leftcand, NULL);
\r
7365 setapex(leftcand, nextapex);
\r
7366 setorg(nextedge, NULL);
\r
7367 setdest(nextedge, upperleft);
\r
7368 setapex(nextedge, nextapex);
\r
7369 /* Consider the newly exposed vertex. */
\r
7370 upperleft = nextapex;
\r
7371 /* What vertex would be exposed if another edge were deleted? */
\r
7372 triedgecopy(sidecasing, nextedge);
\r
7373 apex(nextedge, nextapex);
\r
7374 if (nextapex != (point) NULL) {
\r
7375 /* Check whether the edge is Delaunay. */
\r
7376 badedge = incircle(lowerleft, lowerright, upperleft, nextapex)
\r
7379 /* Avoid eating right through the triangulation. */
\r
7385 /* Consider eliminating edges from the right triangulation. */
\r
7386 if (!rightfinished) {
\r
7387 /* What vertex would be exposed if an edge were deleted? */
\r
7388 lnext(rightcand, nextedge);
\r
7389 symself(nextedge);
\r
7390 apex(nextedge, nextapex);
\r
7391 /* If nextapex is NULL, then no vertex would be exposed; the */
\r
7392 /* triangulation would have been eaten right through. */
\r
7393 if (nextapex != (point) NULL) {
\r
7394 /* Check whether the edge is Delaunay. */
\r
7395 badedge = incircle(lowerleft, lowerright, upperright, nextapex) > 0.0;
\r
7397 /* Eliminate the edge with an edge flip. As a result, the */
\r
7398 /* right triangulation will have one more boundary triangle. */
\r
7399 lprevself(nextedge);
\r
7400 sym(nextedge, topcasing);
\r
7401 lprevself(nextedge);
\r
7402 sym(nextedge, sidecasing);
\r
7403 bond(nextedge, topcasing);
\r
7404 bond(rightcand, sidecasing);
\r
7405 lprevself(rightcand);
\r
7406 sym(rightcand, outercasing);
\r
7407 lnextself(nextedge);
\r
7408 bond(nextedge, outercasing);
\r
7409 /* Correct the vertices to reflect the edge flip. */
\r
7410 setorg(rightcand, NULL);
\r
7411 setdest(rightcand, lowerright);
\r
7412 setapex(rightcand, nextapex);
\r
7413 setorg(nextedge, upperright);
\r
7414 setdest(nextedge, NULL);
\r
7415 setapex(nextedge, nextapex);
\r
7416 /* Consider the newly exposed vertex. */
\r
7417 upperright = nextapex;
\r
7418 /* What vertex would be exposed if another edge were deleted? */
\r
7419 triedgecopy(sidecasing, nextedge);
\r
7420 apex(nextedge, nextapex);
\r
7421 if (nextapex != (point) NULL) {
\r
7422 /* Check whether the edge is Delaunay. */
\r
7423 badedge = incircle(lowerleft, lowerright, upperright, nextapex)
\r
7426 /* Avoid eating right through the triangulation. */
\r
7432 if (leftfinished || (!rightfinished &&
\r
7433 (incircle(upperleft, lowerleft, lowerright, upperright) > 0.0))) {
\r
7434 /* Knit the triangulations, adding an edge from `lowerleft' */
\r
7435 /* to `upperright'. */
\r
7436 bond(baseedge, rightcand);
\r
7437 lprev(rightcand, baseedge);
\r
7438 setdest(baseedge, lowerleft);
\r
7439 lowerright = upperright;
\r
7440 sym(baseedge, rightcand);
\r
7441 apex(rightcand, upperright);
\r
7443 /* Knit the triangulations, adding an edge from `upperleft' */
\r
7444 /* to `lowerright'. */
\r
7445 bond(baseedge, leftcand);
\r
7446 lnext(leftcand, baseedge);
\r
7447 setorg(baseedge, lowerright);
\r
7448 lowerleft = upperleft;
\r
7449 sym(baseedge, leftcand);
\r
7450 apex(leftcand, upperleft);
\r
7452 if (verbose > 2) {
\r
7453 printf(" Connecting ");
\r
7454 printtriangle(&baseedge);
\r
7459 /*****************************************************************************/
\r
7461 /* divconqrecurse() Recursively form a Delaunay triangulation by the */
\r
7462 /* divide-and-conquer method. */
\r
7464 /* Recursively breaks down the problem into smaller pieces, which are */
\r
7465 /* knitted together by mergehulls(). The base cases (problems of two or */
\r
7466 /* three points) are handled specially here. */
\r
7468 /* On completion, `farleft' and `farright' are bounding triangles such that */
\r
7469 /* the origin of `farleft' is the leftmost vertex (breaking ties by */
\r
7470 /* choosing the highest leftmost vertex), and the destination of */
\r
7471 /* `farright' is the rightmost vertex (breaking ties by choosing the */
\r
7472 /* lowest rightmost vertex). */
\r
7474 /*****************************************************************************/
\r
7476 void divconqrecurse(sortarray, vertices, axis, farleft, farright)
\r
7480 struct triedge *farleft;
\r
7481 struct triedge *farright;
\r
7483 struct triedge midtri, tri1, tri2, tri3;
\r
7484 struct triedge innerleft, innerright;
\r
7488 if (verbose > 2) {
\r
7489 printf(" Triangulating %d points.\n", vertices);
\r
7491 if (vertices == 2) {
\r
7492 /* The triangulation of two vertices is an edge. An edge is */
\r
7493 /* represented by two bounding triangles. */
\r
7494 maketriangle(farleft);
\r
7495 setorg(*farleft, sortarray[0]);
\r
7496 setdest(*farleft, sortarray[1]);
\r
7497 /* The apex is intentionally left NULL. */
\r
7498 maketriangle(farright);
\r
7499 setorg(*farright, sortarray[1]);
\r
7500 setdest(*farright, sortarray[0]);
\r
7501 /* The apex is intentionally left NULL. */
\r
7502 bond(*farleft, *farright);
\r
7503 lprevself(*farleft);
\r
7504 lnextself(*farright);
\r
7505 bond(*farleft, *farright);
\r
7506 lprevself(*farleft);
\r
7507 lnextself(*farright);
\r
7508 bond(*farleft, *farright);
\r
7509 if (verbose > 2) {
\r
7510 printf(" Creating ");
\r
7511 printtriangle(farleft);
\r
7512 printf(" Creating ");
\r
7513 printtriangle(farright);
\r
7515 /* Ensure that the origin of `farleft' is sortarray[0]. */
\r
7516 lprev(*farright, *farleft);
\r
7518 } else if (vertices == 3) {
\r
7519 /* The triangulation of three vertices is either a triangle (with */
\r
7520 /* three bounding triangles) or two edges (with four bounding */
\r
7521 /* triangles). In either case, four triangles are created. */
\r
7522 maketriangle(&midtri);
\r
7523 maketriangle(&tri1);
\r
7524 maketriangle(&tri2);
\r
7525 maketriangle(&tri3);
\r
7526 area = counterclockwise(sortarray[0], sortarray[1], sortarray[2]);
\r
7527 if (area == 0.0) {
\r
7528 /* Three collinear points; the triangulation is two edges. */
\r
7529 setorg(midtri, sortarray[0]);
\r
7530 setdest(midtri, sortarray[1]);
\r
7531 setorg(tri1, sortarray[1]);
\r
7532 setdest(tri1, sortarray[0]);
\r
7533 setorg(tri2, sortarray[2]);
\r
7534 setdest(tri2, sortarray[1]);
\r
7535 setorg(tri3, sortarray[1]);
\r
7536 setdest(tri3, sortarray[2]);
\r
7537 /* All apices are intentionally left NULL. */
\r
7538 bond(midtri, tri1);
\r
7540 lnextself(midtri);
\r
7544 bond(midtri, tri3);
\r
7546 lnextself(midtri);
\r
7550 bond(midtri, tri1);
\r
7552 /* Ensure that the origin of `farleft' is sortarray[0]. */
\r
7553 triedgecopy(tri1, *farleft);
\r
7554 /* Ensure that the destination of `farright' is sortarray[2]. */
\r
7555 triedgecopy(tri2, *farright);
\r
7557 /* The three points are not collinear; the triangulation is one */
\r
7558 /* triangle, namely `midtri'. */
\r
7559 setorg(midtri, sortarray[0]);
\r
7560 setdest(tri1, sortarray[0]);
\r
7561 setorg(tri3, sortarray[0]);
\r
7562 /* Apices of tri1, tri2, and tri3 are left NULL. */
\r
7564 /* The vertices are in counterclockwise order. */
\r
7565 setdest(midtri, sortarray[1]);
\r
7566 setorg(tri1, sortarray[1]);
\r
7567 setdest(tri2, sortarray[1]);
\r
7568 setapex(midtri, sortarray[2]);
\r
7569 setorg(tri2, sortarray[2]);
\r
7570 setdest(tri3, sortarray[2]);
\r
7572 /* The vertices are in clockwise order. */
\r
7573 setdest(midtri, sortarray[2]);
\r
7574 setorg(tri1, sortarray[2]);
\r
7575 setdest(tri2, sortarray[2]);
\r
7576 setapex(midtri, sortarray[1]);
\r
7577 setorg(tri2, sortarray[1]);
\r
7578 setdest(tri3, sortarray[1]);
\r
7580 /* The topology does not depend on how the vertices are ordered. */
\r
7581 bond(midtri, tri1);
\r
7582 lnextself(midtri);
\r
7583 bond(midtri, tri2);
\r
7584 lnextself(midtri);
\r
7585 bond(midtri, tri3);
\r
7595 /* Ensure that the origin of `farleft' is sortarray[0]. */
\r
7596 triedgecopy(tri1, *farleft);
\r
7597 /* Ensure that the destination of `farright' is sortarray[2]. */
\r
7599 triedgecopy(tri2, *farright);
\r
7601 lnext(*farleft, *farright);
\r
7604 if (verbose > 2) {
\r
7605 printf(" Creating ");
\r
7606 printtriangle(&midtri);
\r
7607 printf(" Creating ");
\r
7608 printtriangle(&tri1);
\r
7609 printf(" Creating ");
\r
7610 printtriangle(&tri2);
\r
7611 printf(" Creating ");
\r
7612 printtriangle(&tri3);
\r
7616 /* Split the vertices in half. */
\r
7617 divider = vertices >> 1;
\r
7618 /* Recursively triangulate each half. */
\r
7619 divconqrecurse(sortarray, divider, 1 - axis, farleft, &innerleft);
\r
7620 divconqrecurse(&sortarray[divider], vertices - divider, 1 - axis,
\r
7621 &innerright, farright);
\r
7622 if (verbose > 1) {
\r
7623 printf(" Joining triangulations with %d and %d vertices.\n", divider,
\r
7624 vertices - divider);
\r
7626 /* Merge the two triangulations into one. */
\r
7627 mergehulls(farleft, &innerleft, &innerright, farright, axis);
\r
7631 long removeghosts(startghost)
\r
7632 struct triedge *startghost;
\r
7634 struct triedge searchedge;
\r
7635 struct triedge dissolveedge;
\r
7636 struct triedge deadtri;
\r
7639 triangle ptr; /* Temporary variable used by sym(). */
\r
7642 printf(" Removing ghost triangles.\n");
\r
7644 /* Find an edge on the convex hull to start point location from. */
\r
7645 lprev(*startghost, searchedge);
\r
7646 symself(searchedge);
\r
7647 dummytri[0] = encode(searchedge);
\r
7648 /* Remove the bounding box and count the convex hull edges. */
\r
7649 triedgecopy(*startghost, dissolveedge);
\r
7653 lnext(dissolveedge, deadtri);
\r
7654 lprevself(dissolveedge);
\r
7655 symself(dissolveedge);
\r
7656 /* If no PSLG is involved, set the boundary markers of all the points */
\r
7657 /* on the convex hull. If a PSLG is used, this step is done later. */
\r
7659 /* Watch out for the case where all the input points are collinear. */
\r
7660 if (dissolveedge.tri != dummytri) {
\r
7661 org(dissolveedge, markorg);
\r
7662 if (pointmark(markorg) == 0) {
\r
7663 setpointmark(markorg, 1);
\r
7667 /* Remove a bounding triangle from a convex hull triangle. */
\r
7668 dissolve(dissolveedge);
\r
7669 /* Find the next bounding triangle. */
\r
7670 sym(deadtri, dissolveedge);
\r
7671 /* Delete the bounding triangle. */
\r
7672 triangledealloc(deadtri.tri);
\r
7673 } while (!triedgeequal(dissolveedge, *startghost));
\r
7677 /*****************************************************************************/
\r
7679 /* divconqdelaunay() Form a Delaunay triangulation by the divide-and- */
\r
7680 /* conquer method. */
\r
7682 /* Sorts the points, calls a recursive procedure to triangulate them, and */
\r
7683 /* removes the bounding box, setting boundary markers as appropriate. */
\r
7685 /*****************************************************************************/
\r
7687 long divconqdelaunay()
\r
7690 struct triedge hullleft, hullright;
\r
7694 /* Allocate an array of pointers to points for sorting. */
\r
7695 sortarray = (point *) malloc(inpoints * sizeof(point));
\r
7696 if (sortarray == (point *) NULL) {
\r
7697 printf("Error: Out of memory.\n");
\r
7700 traversalinit(&points);
\r
7701 for (i = 0; i < inpoints; i++) {
\r
7702 sortarray[i] = pointtraverse();
\r
7705 printf(" Sorting points.\n");
\r
7707 /* Sort the points. */
\r
7708 pointsort(sortarray, inpoints);
\r
7709 /* Discard duplicate points, which can really mess up the algorithm. */
\r
7711 for (j = 1; j < inpoints; j++) {
\r
7712 if ((sortarray[i][0] == sortarray[j][0])
\r
7713 && (sortarray[i][1] == sortarray[j][1])) {
\r
7716 "Warning: A duplicate point at (%.12g, %.12g) appeared and was ignored.\n",
\r
7717 sortarray[j][0], sortarray[j][1]);
\r
7719 /* Commented out - would eliminate point from output .node file, but causes
\r
7720 a failure if some segment has this point as an endpoint.
\r
7721 setpointmark(sortarray[j], DEADPOINT);
\r
7725 sortarray[i] = sortarray[j];
\r
7730 /* Re-sort the array of points to accommodate alternating cuts. */
\r
7732 if (i - divider >= 2) {
\r
7733 if (divider >= 2) {
\r
7734 alternateaxes(sortarray, divider, 1);
\r
7736 alternateaxes(&sortarray[divider], i - divider, 1);
\r
7740 printf(" Forming triangulation.\n");
\r
7742 /* Form the Delaunay triangulation. */
\r
7743 divconqrecurse(sortarray, i, 0, &hullleft, &hullright);
\r
7746 return removeghosts(&hullleft);
\r
7751 /********* Divide-and-conquer Delaunay triangulation ends here *********/
\r
7753 /********* Incremental Delaunay triangulation begins here *********/
\r
7757 /*****************************************************************************/
\r
7759 /* boundingbox() Form an "infinite" bounding triangle to insert points */
\r
7762 /* The points at "infinity" are assigned finite coordinates, which are used */
\r
7763 /* by the point location routines, but (mostly) ignored by the Delaunay */
\r
7764 /* edge flip routines. */
\r
7766 /*****************************************************************************/
\r
7770 void boundingbox()
\r
7772 struct triedge inftri; /* Handle for the triangular bounding box. */
\r
7776 printf(" Creating triangular bounding box.\n");
\r
7778 /* Find the width (or height, whichever is larger) of the triangulation. */
\r
7779 width = xmax - xmin;
\r
7780 if (ymax - ymin > width) {
\r
7781 width = ymax - ymin;
\r
7783 if (width == 0.0) {
\r
7786 /* Create the vertices of the bounding box. */
\r
7787 infpoint1 = (point) malloc(points.itembytes);
\r
7788 infpoint2 = (point) malloc(points.itembytes);
\r
7789 infpoint3 = (point) malloc(points.itembytes);
\r
7790 if ((infpoint1 == (point) NULL) || (infpoint2 == (point) NULL)
\r
7791 || (infpoint3 == (point) NULL)) {
\r
7792 printf("Error: Out of memory.\n");
\r
7795 infpoint1[0] = xmin - 50.0 * width;
\r
7796 infpoint1[1] = ymin - 40.0 * width;
\r
7797 infpoint2[0] = xmax + 50.0 * width;
\r
7798 infpoint2[1] = ymin - 40.0 * width;
\r
7799 infpoint3[0] = 0.5 * (xmin + xmax);
\r
7800 infpoint3[1] = ymax + 60.0 * width;
\r
7802 /* Create the bounding box. */
\r
7803 maketriangle(&inftri);
\r
7804 setorg(inftri, infpoint1);
\r
7805 setdest(inftri, infpoint2);
\r
7806 setapex(inftri, infpoint3);
\r
7807 /* Link dummytri to the bounding box so we can always find an */
\r
7808 /* edge to begin searching (point location) from. */
\r
7809 dummytri[0] = (triangle) inftri.tri;
\r
7810 if (verbose > 2) {
\r
7811 printf(" Creating ");
\r
7812 printtriangle(&inftri);
\r
7816 #endif /* not REDUCED */
\r
7818 /*****************************************************************************/
\r
7820 /* removebox() Remove the "infinite" bounding triangle, setting boundary */
\r
7821 /* markers as appropriate. */
\r
7823 /* The triangular bounding box has three boundary triangles (one for each */
\r
7824 /* side of the bounding box), and a bunch of triangles fanning out from */
\r
7825 /* the three bounding box vertices (one triangle for each edge of the */
\r
7826 /* convex hull of the inner mesh). This routine removes these triangles. */
\r
7828 /*****************************************************************************/
\r
7834 struct triedge deadtri;
\r
7835 struct triedge searchedge;
\r
7836 struct triedge checkedge;
\r
7837 struct triedge nextedge, finaledge, dissolveedge;
\r
7840 triangle ptr; /* Temporary variable used by sym(). */
\r
7843 printf(" Removing triangular bounding box.\n");
\r
7845 /* Find a boundary triangle. */
\r
7846 nextedge.tri = dummytri;
\r
7847 nextedge.orient = 0;
\r
7848 symself(nextedge);
\r
7849 /* Mark a place to stop. */
\r
7850 lprev(nextedge, finaledge);
\r
7851 lnextself(nextedge);
\r
7852 symself(nextedge);
\r
7853 /* Find a triangle (on the boundary of the point set) that isn't */
\r
7854 /* a bounding box triangle. */
\r
7855 lprev(nextedge, searchedge);
\r
7856 symself(searchedge);
\r
7857 /* Check whether nextedge is another boundary triangle */
\r
7858 /* adjacent to the first one. */
\r
7859 lnext(nextedge, checkedge);
\r
7860 symself(checkedge);
\r
7861 if (checkedge.tri == dummytri) {
\r
7862 /* Go on to the next triangle. There are only three boundary */
\r
7863 /* triangles, and this next triangle cannot be the third one, */
\r
7864 /* so it's safe to stop here. */
\r
7865 lprevself(searchedge);
\r
7866 symself(searchedge);
\r
7868 /* Find a new boundary edge to search from, as the current search */
\r
7869 /* edge lies on a bounding box triangle and will be deleted. */
\r
7870 dummytri[0] = encode(searchedge);
\r
7872 while (!triedgeequal(nextedge, finaledge)) {
\r
7874 lprev(nextedge, dissolveedge);
\r
7875 symself(dissolveedge);
\r
7876 /* If not using a PSLG, the vertices should be marked now. */
\r
7877 /* (If using a PSLG, markhull() will do the job.) */
\r
7879 /* Be careful! One must check for the case where all the input */
\r
7880 /* points are collinear, and thus all the triangles are part of */
\r
7881 /* the bounding box. Otherwise, the setpointmark() call below */
\r
7882 /* will cause a bad pointer reference. */
\r
7883 if (dissolveedge.tri != dummytri) {
\r
7884 org(dissolveedge, markorg);
\r
7885 if (pointmark(markorg) == 0) {
\r
7886 setpointmark(markorg, 1);
\r
7890 /* Disconnect the bounding box triangle from the mesh triangle. */
\r
7891 dissolve(dissolveedge);
\r
7892 lnext(nextedge, deadtri);
\r
7893 sym(deadtri, nextedge);
\r
7894 /* Get rid of the bounding box triangle. */
\r
7895 triangledealloc(deadtri.tri);
\r
7896 /* Do we need to turn the corner? */
\r
7897 if (nextedge.tri == dummytri) {
\r
7898 /* Turn the corner. */
\r
7899 triedgecopy(dissolveedge, nextedge);
\r
7902 triangledealloc(finaledge.tri);
\r
7904 free(infpoint1); /* Deallocate the bounding box vertices. */
\r
7911 #endif /* not REDUCED */
\r
7913 /*****************************************************************************/
\r
7915 /* incrementaldelaunay() Form a Delaunay triangulation by incrementally */
\r
7916 /* adding vertices. */
\r
7918 /*****************************************************************************/
\r
7922 long incrementaldelaunay()
\r
7924 struct triedge starttri;
\r
7928 /* Create a triangular bounding box. */
\r
7931 printf(" Incrementally inserting points.\n");
\r
7933 traversalinit(&points);
\r
7934 pointloop = pointtraverse();
\r
7936 while (pointloop != (point) NULL) {
\r
7937 /* Find a boundary triangle to search from. */
\r
7938 starttri.tri = (triangle *) NULL;
\r
7939 if (insertsite(pointloop, &starttri, (struct edge *) NULL, 0, 0) ==
\r
7943 "Warning: A duplicate point at (%.12g, %.12g) appeared and was ignored.\n",
\r
7944 pointloop[0], pointloop[1]);
\r
7946 /* Commented out - would eliminate point from output .node file.
\r
7947 setpointmark(pointloop, DEADPOINT);
\r
7950 pointloop = pointtraverse();
\r
7953 /* Remove the bounding box. */
\r
7954 return removebox();
\r
7957 #endif /* not REDUCED */
\r
7961 /********* Incremental Delaunay triangulation ends here *********/
\r
7963 /********* Sweepline Delaunay triangulation begins here *********/
\r
7969 void eventheapinsert(heap, heapsize, newevent)
\r
7970 struct event **heap;
\r
7972 struct event *newevent;
\r
7974 REAL eventx, eventy;
\r
7979 eventx = newevent->xkey;
\r
7980 eventy = newevent->ykey;
\r
7981 eventnum = heapsize;
\r
7982 notdone = eventnum > 0;
\r
7984 parent = (eventnum - 1) >> 1;
\r
7985 if ((heap[parent]->ykey < eventy) ||
\r
7986 ((heap[parent]->ykey == eventy)
\r
7987 && (heap[parent]->xkey <= eventx))) {
\r
7990 heap[eventnum] = heap[parent];
\r
7991 heap[eventnum]->heapposition = eventnum;
\r
7993 eventnum = parent;
\r
7994 notdone = eventnum > 0;
\r
7997 heap[eventnum] = newevent;
\r
7998 newevent->heapposition = eventnum;
\r
8001 #endif /* not REDUCED */
\r
8005 void eventheapify(heap, heapsize, eventnum)
\r
8006 struct event **heap;
\r
8010 struct event *thisevent;
\r
8011 REAL eventx, eventy;
\r
8012 int leftchild, rightchild;
\r
8016 thisevent = heap[eventnum];
\r
8017 eventx = thisevent->xkey;
\r
8018 eventy = thisevent->ykey;
\r
8019 leftchild = 2 * eventnum + 1;
\r
8020 notdone = leftchild < heapsize;
\r
8022 if ((heap[leftchild]->ykey < eventy) ||
\r
8023 ((heap[leftchild]->ykey == eventy)
\r
8024 && (heap[leftchild]->xkey < eventx))) {
\r
8025 smallest = leftchild;
\r
8027 smallest = eventnum;
\r
8029 rightchild = leftchild + 1;
\r
8030 if (rightchild < heapsize) {
\r
8031 if ((heap[rightchild]->ykey < heap[smallest]->ykey) ||
\r
8032 ((heap[rightchild]->ykey == heap[smallest]->ykey)
\r
8033 && (heap[rightchild]->xkey < heap[smallest]->xkey))) {
\r
8034 smallest = rightchild;
\r
8037 if (smallest == eventnum) {
\r
8040 heap[eventnum] = heap[smallest];
\r
8041 heap[eventnum]->heapposition = eventnum;
\r
8042 heap[smallest] = thisevent;
\r
8043 thisevent->heapposition = smallest;
\r
8045 eventnum = smallest;
\r
8046 leftchild = 2 * eventnum + 1;
\r
8047 notdone = leftchild < heapsize;
\r
8052 #endif /* not REDUCED */
\r
8056 void eventheapdelete(heap, heapsize, eventnum)
\r
8057 struct event **heap;
\r
8061 struct event *moveevent;
\r
8062 REAL eventx, eventy;
\r
8066 moveevent = heap[heapsize - 1];
\r
8067 if (eventnum > 0) {
\r
8068 eventx = moveevent->xkey;
\r
8069 eventy = moveevent->ykey;
\r
8071 parent = (eventnum - 1) >> 1;
\r
8072 if ((heap[parent]->ykey < eventy) ||
\r
8073 ((heap[parent]->ykey == eventy)
\r
8074 && (heap[parent]->xkey <= eventx))) {
\r
8077 heap[eventnum] = heap[parent];
\r
8078 heap[eventnum]->heapposition = eventnum;
\r
8080 eventnum = parent;
\r
8081 notdone = eventnum > 0;
\r
8083 } while (notdone);
\r
8085 heap[eventnum] = moveevent;
\r
8086 moveevent->heapposition = eventnum;
\r
8087 eventheapify(heap, heapsize - 1, eventnum);
\r
8090 #endif /* not REDUCED */
\r
8094 void createeventheap(eventheap, events, freeevents)
\r
8095 struct event ***eventheap;
\r
8096 struct event **events;
\r
8097 struct event **freeevents;
\r
8103 maxevents = (3 * inpoints) / 2;
\r
8104 *eventheap = (struct event **) malloc(maxevents * sizeof(struct event *));
\r
8105 if (*eventheap == (struct event **) NULL) {
\r
8106 printf("Error: Out of memory.\n");
\r
8109 *events = (struct event *) malloc(maxevents * sizeof(struct event));
\r
8110 if (*events == (struct event *) NULL) {
\r
8111 printf("Error: Out of memory.\n");
\r
8114 traversalinit(&points);
\r
8115 for (i = 0; i < inpoints; i++) {
\r
8116 thispoint = pointtraverse();
\r
8117 (*events)[i].eventptr = (VOID *) thispoint;
\r
8118 (*events)[i].xkey = thispoint[0];
\r
8119 (*events)[i].ykey = thispoint[1];
\r
8120 eventheapinsert(*eventheap, i, *events + i);
\r
8122 *freeevents = (struct event *) NULL;
\r
8123 for (i = maxevents - 1; i >= inpoints; i--) {
\r
8124 (*events)[i].eventptr = (VOID *) *freeevents;
\r
8125 *freeevents = *events + i;
\r
8129 #endif /* not REDUCED */
\r
8133 int rightofhyperbola(fronttri, newsite)
\r
8134 struct triedge *fronttri;
\r
8137 point leftpoint, rightpoint;
\r
8138 REAL dxa, dya, dxb, dyb;
\r
8142 dest(*fronttri, leftpoint);
\r
8143 apex(*fronttri, rightpoint);
\r
8144 if ((leftpoint[1] < rightpoint[1])
\r
8145 || ((leftpoint[1] == rightpoint[1]) && (leftpoint[0] < rightpoint[0]))) {
\r
8146 if (newsite[0] >= rightpoint[0]) {
\r
8150 if (newsite[0] <= leftpoint[0]) {
\r
8154 dxa = leftpoint[0] - newsite[0];
\r
8155 dya = leftpoint[1] - newsite[1];
\r
8156 dxb = rightpoint[0] - newsite[0];
\r
8157 dyb = rightpoint[1] - newsite[1];
\r
8158 return dya * (dxb * dxb + dyb * dyb) > dyb * (dxa * dxa + dya * dya);
\r
8161 #endif /* not REDUCED */
\r
8165 REAL circletop(pa, pb, pc, ccwabc)
\r
8171 REAL xac, yac, xbc, ybc, xab, yab;
\r
8172 REAL aclen2, bclen2, ablen2;
\r
8176 xac = pa[0] - pc[0];
\r
8177 yac = pa[1] - pc[1];
\r
8178 xbc = pb[0] - pc[0];
\r
8179 ybc = pb[1] - pc[1];
\r
8180 xab = pa[0] - pb[0];
\r
8181 yab = pa[1] - pb[1];
\r
8182 aclen2 = xac * xac + yac * yac;
\r
8183 bclen2 = xbc * xbc + ybc * ybc;
\r
8184 ablen2 = xab * xab + yab * yab;
\r
8185 return pc[1] + (xac * bclen2 - xbc * aclen2 + sqrt(aclen2 * bclen2 * ablen2))
\r
8189 #endif /* not REDUCED */
\r
8193 void check4deadevent(checktri, freeevents, eventheap, heapsize)
\r
8194 struct triedge *checktri;
\r
8195 struct event **freeevents;
\r
8196 struct event **eventheap;
\r
8199 struct event *deadevent;
\r
8203 org(*checktri, eventpoint);
\r
8204 if (eventpoint != (point) NULL) {
\r
8205 deadevent = (struct event *) eventpoint;
\r
8206 eventnum = deadevent->heapposition;
\r
8207 deadevent->eventptr = (VOID *) *freeevents;
\r
8208 *freeevents = deadevent;
\r
8209 eventheapdelete(eventheap, *heapsize, eventnum);
\r
8211 setorg(*checktri, NULL);
\r
8215 #endif /* not REDUCED */
\r
8219 struct splaynode *splay(splaytree, searchpoint, searchtri)
\r
8220 struct splaynode *splaytree;
\r
8221 point searchpoint;
\r
8222 struct triedge *searchtri;
\r
8224 struct splaynode *child, *grandchild;
\r
8225 struct splaynode *lefttree, *righttree;
\r
8226 struct splaynode *leftright;
\r
8228 int rightofroot, rightofchild;
\r
8230 if (splaytree == (struct splaynode *) NULL) {
\r
8231 return (struct splaynode *) NULL;
\r
8233 dest(splaytree->keyedge, checkpoint);
\r
8234 if (checkpoint == splaytree->keydest) {
\r
8235 rightofroot = rightofhyperbola(&splaytree->keyedge, searchpoint);
\r
8236 if (rightofroot) {
\r
8237 triedgecopy(splaytree->keyedge, *searchtri);
\r
8238 child = splaytree->rchild;
\r
8240 child = splaytree->lchild;
\r
8242 if (child == (struct splaynode *) NULL) {
\r
8245 dest(child->keyedge, checkpoint);
\r
8246 if (checkpoint != child->keydest) {
\r
8247 child = splay(child, searchpoint, searchtri);
\r
8248 if (child == (struct splaynode *) NULL) {
\r
8249 if (rightofroot) {
\r
8250 splaytree->rchild = (struct splaynode *) NULL;
\r
8252 splaytree->lchild = (struct splaynode *) NULL;
\r
8257 rightofchild = rightofhyperbola(&child->keyedge, searchpoint);
\r
8258 if (rightofchild) {
\r
8259 triedgecopy(child->keyedge, *searchtri);
\r
8260 grandchild = splay(child->rchild, searchpoint, searchtri);
\r
8261 child->rchild = grandchild;
\r
8263 grandchild = splay(child->lchild, searchpoint, searchtri);
\r
8264 child->lchild = grandchild;
\r
8266 if (grandchild == (struct splaynode *) NULL) {
\r
8267 if (rightofroot) {
\r
8268 splaytree->rchild = child->lchild;
\r
8269 child->lchild = splaytree;
\r
8271 splaytree->lchild = child->rchild;
\r
8272 child->rchild = splaytree;
\r
8276 if (rightofchild) {
\r
8277 if (rightofroot) {
\r
8278 splaytree->rchild = child->lchild;
\r
8279 child->lchild = splaytree;
\r
8281 splaytree->lchild = grandchild->rchild;
\r
8282 grandchild->rchild = splaytree;
\r
8284 child->rchild = grandchild->lchild;
\r
8285 grandchild->lchild = child;
\r
8287 if (rightofroot) {
\r
8288 splaytree->rchild = grandchild->lchild;
\r
8289 grandchild->lchild = splaytree;
\r
8291 splaytree->lchild = child->rchild;
\r
8292 child->rchild = splaytree;
\r
8294 child->lchild = grandchild->rchild;
\r
8295 grandchild->rchild = child;
\r
8297 return grandchild;
\r
8299 lefttree = splay(splaytree->lchild, searchpoint, searchtri);
\r
8300 righttree = splay(splaytree->rchild, searchpoint, searchtri);
\r
8302 pooldealloc(&splaynodes, (VOID *) splaytree);
\r
8303 if (lefttree == (struct splaynode *) NULL) {
\r
8305 } else if (righttree == (struct splaynode *) NULL) {
\r
8307 } else if (lefttree->rchild == (struct splaynode *) NULL) {
\r
8308 lefttree->rchild = righttree->lchild;
\r
8309 righttree->lchild = lefttree;
\r
8311 } else if (righttree->lchild == (struct splaynode *) NULL) {
\r
8312 righttree->lchild = lefttree->rchild;
\r
8313 lefttree->rchild = righttree;
\r
8316 /* printf("Holy Toledo!!!\n"); */
\r
8317 leftright = lefttree->rchild;
\r
8318 while (leftright->rchild != (struct splaynode *) NULL) {
\r
8319 leftright = leftright->rchild;
\r
8321 leftright->rchild = righttree;
\r
8327 #endif /* not REDUCED */
\r
8331 struct splaynode *splayinsert(splayroot, newkey, searchpoint)
\r
8332 struct splaynode *splayroot;
\r
8333 struct triedge *newkey;
\r
8334 point searchpoint;
\r
8336 struct splaynode *newsplaynode;
\r
8338 newsplaynode = (struct splaynode *) poolalloc(&splaynodes);
\r
8339 triedgecopy(*newkey, newsplaynode->keyedge);
\r
8340 dest(*newkey, newsplaynode->keydest);
\r
8341 if (splayroot == (struct splaynode *) NULL) {
\r
8342 newsplaynode->lchild = (struct splaynode *) NULL;
\r
8343 newsplaynode->rchild = (struct splaynode *) NULL;
\r
8344 } else if (rightofhyperbola(&splayroot->keyedge, searchpoint)) {
\r
8345 newsplaynode->lchild = splayroot;
\r
8346 newsplaynode->rchild = splayroot->rchild;
\r
8347 splayroot->rchild = (struct splaynode *) NULL;
\r
8349 newsplaynode->lchild = splayroot->lchild;
\r
8350 newsplaynode->rchild = splayroot;
\r
8351 splayroot->lchild = (struct splaynode *) NULL;
\r
8353 return newsplaynode;
\r
8356 #endif /* not REDUCED */
\r
8360 struct splaynode *circletopinsert(splayroot, newkey, pa, pb, pc, topy)
\r
8361 struct splaynode *splayroot;
\r
8362 struct triedge *newkey;
\r
8369 REAL xac, yac, xbc, ybc;
\r
8370 REAL aclen2, bclen2;
\r
8371 REAL searchpoint[2];
\r
8372 struct triedge dummytri;
\r
8374 ccwabc = counterclockwise(pa, pb, pc);
\r
8375 xac = pa[0] - pc[0];
\r
8376 yac = pa[1] - pc[1];
\r
8377 xbc = pb[0] - pc[0];
\r
8378 ybc = pb[1] - pc[1];
\r
8379 aclen2 = xac * xac + yac * yac;
\r
8380 bclen2 = xbc * xbc + ybc * ybc;
\r
8381 searchpoint[0] = pc[0] - (yac * bclen2 - ybc * aclen2) / (2.0 * ccwabc);
\r
8382 searchpoint[1] = topy;
\r
8383 return splayinsert(splay(splayroot, (point) searchpoint, &dummytri), newkey,
\r
8384 (point) searchpoint);
\r
8387 #endif /* not REDUCED */
\r
8391 struct splaynode *frontlocate(splayroot, bottommost, searchpoint, searchtri,
\r
8393 struct splaynode *splayroot;
\r
8394 struct triedge *bottommost;
\r
8395 point searchpoint;
\r
8396 struct triedge *searchtri;
\r
8400 triangle ptr; /* Temporary variable used by onext(). */
\r
8402 triedgecopy(*bottommost, *searchtri);
\r
8403 splayroot = splay(splayroot, searchpoint, searchtri);
\r
8406 while (!farrightflag && rightofhyperbola(searchtri, searchpoint)) {
\r
8407 onextself(*searchtri);
\r
8408 farrightflag = triedgeequal(*searchtri, *bottommost);
\r
8410 *farright = farrightflag;
\r
8414 #endif /* not REDUCED */
\r
8418 long sweeplinedelaunay()
\r
8420 struct event **eventheap;
\r
8421 struct event *events;
\r
8422 struct event *freeevents;
\r
8423 struct event *nextevent;
\r
8424 struct event *newevent;
\r
8425 struct splaynode *splayroot;
\r
8426 struct triedge bottommost;
\r
8427 struct triedge searchtri;
\r
8428 struct triedge fliptri;
\r
8429 struct triedge lefttri, righttri, farlefttri, farrighttri;
\r
8430 struct triedge inserttri;
\r
8431 point firstpoint, secondpoint;
\r
8432 point nextpoint, lastpoint;
\r
8433 point connectpoint;
\r
8434 point leftpoint, midpoint, rightpoint;
\r
8435 REAL lefttest, righttest;
\r
8437 int check4events, farrightflag;
\r
8438 triangle ptr; /* Temporary variable used by sym(), onext(), and oprev(). */
\r
8440 poolinit(&splaynodes, sizeof(struct splaynode), SPLAYNODEPERBLOCK, POINTER,
\r
8442 splayroot = (struct splaynode *) NULL;
\r
8445 printf(" Placing points in event heap.\n");
\r
8447 createeventheap(&eventheap, &events, &freeevents);
\r
8448 heapsize = inpoints;
\r
8451 printf(" Forming triangulation.\n");
\r
8453 maketriangle(&lefttri);
\r
8454 maketriangle(&righttri);
\r
8455 bond(lefttri, righttri);
\r
8456 lnextself(lefttri);
\r
8457 lprevself(righttri);
\r
8458 bond(lefttri, righttri);
\r
8459 lnextself(lefttri);
\r
8460 lprevself(righttri);
\r
8461 bond(lefttri, righttri);
\r
8462 firstpoint = (point) eventheap[0]->eventptr;
\r
8463 eventheap[0]->eventptr = (VOID *) freeevents;
\r
8464 freeevents = eventheap[0];
\r
8465 eventheapdelete(eventheap, heapsize, 0);
\r
8468 if (heapsize == 0) {
\r
8469 printf("Error: Input points are all identical.\n");
\r
8472 secondpoint = (point) eventheap[0]->eventptr;
\r
8473 eventheap[0]->eventptr = (VOID *) freeevents;
\r
8474 freeevents = eventheap[0];
\r
8475 eventheapdelete(eventheap, heapsize, 0);
\r
8477 if ((firstpoint[0] == secondpoint[0])
\r
8478 && (firstpoint[1] == secondpoint[1])) {
\r
8480 "Warning: A duplicate point at (%.12g, %.12g) appeared and was ignored.\n",
\r
8481 secondpoint[0], secondpoint[1]);
\r
8482 /* Commented out - would eliminate point from output .node file.
\r
8483 setpointmark(secondpoint, DEADPOINT);
\r
8486 } while ((firstpoint[0] == secondpoint[0])
\r
8487 && (firstpoint[1] == secondpoint[1]));
\r
8488 setorg(lefttri, firstpoint);
\r
8489 setdest(lefttri, secondpoint);
\r
8490 setorg(righttri, secondpoint);
\r
8491 setdest(righttri, firstpoint);
\r
8492 lprev(lefttri, bottommost);
\r
8493 lastpoint = secondpoint;
\r
8494 while (heapsize > 0) {
\r
8495 nextevent = eventheap[0];
\r
8496 eventheapdelete(eventheap, heapsize, 0);
\r
8499 if (nextevent->xkey < xmin) {
\r
8500 decode(nextevent->eventptr, fliptri);
\r
8501 oprev(fliptri, farlefttri);
\r
8502 check4deadevent(&farlefttri, &freeevents, eventheap, &heapsize);
\r
8503 onext(fliptri, farrighttri);
\r
8504 check4deadevent(&farrighttri, &freeevents, eventheap, &heapsize);
\r
8506 if (triedgeequal(farlefttri, bottommost)) {
\r
8507 lprev(fliptri, bottommost);
\r
8510 setapex(fliptri, NULL);
\r
8511 lprev(fliptri, lefttri);
\r
8512 lnext(fliptri, righttri);
\r
8513 sym(lefttri, farlefttri);
\r
8515 if (randomnation(SAMPLERATE) == 0) {
\r
8517 dest(fliptri, leftpoint);
\r
8518 apex(fliptri, midpoint);
\r
8519 org(fliptri, rightpoint);
\r
8520 splayroot = circletopinsert(splayroot, &lefttri, leftpoint, midpoint,
\r
8521 rightpoint, nextevent->ykey);
\r
8524 nextpoint = (point) nextevent->eventptr;
\r
8525 if ((nextpoint[0] == lastpoint[0]) && (nextpoint[1] == lastpoint[1])) {
\r
8527 "Warning: A duplicate point at (%.12g, %.12g) appeared and was ignored.\n",
\r
8528 nextpoint[0], nextpoint[1]);
\r
8529 /* Commented out - would eliminate point from output .node file.
\r
8530 setpointmark(nextpoint, DEADPOINT);
\r
8534 lastpoint = nextpoint;
\r
8536 splayroot = frontlocate(splayroot, &bottommost, nextpoint, &searchtri,
\r
8539 triedgecopy(bottommost, searchtri);
\r
8541 while (!farrightflag && rightofhyperbola(&searchtri, nextpoint)) {
\r
8542 onextself(searchtri);
\r
8543 farrightflag = triedgeequal(searchtri, bottommost);
\r
8547 check4deadevent(&searchtri, &freeevents, eventheap, &heapsize);
\r
8549 triedgecopy(searchtri, farrighttri);
\r
8550 sym(searchtri, farlefttri);
\r
8551 maketriangle(&lefttri);
\r
8552 maketriangle(&righttri);
\r
8553 dest(farrighttri, connectpoint);
\r
8554 setorg(lefttri, connectpoint);
\r
8555 setdest(lefttri, nextpoint);
\r
8556 setorg(righttri, nextpoint);
\r
8557 setdest(righttri, connectpoint);
\r
8558 bond(lefttri, righttri);
\r
8559 lnextself(lefttri);
\r
8560 lprevself(righttri);
\r
8561 bond(lefttri, righttri);
\r
8562 lnextself(lefttri);
\r
8563 lprevself(righttri);
\r
8564 bond(lefttri, farlefttri);
\r
8565 bond(righttri, farrighttri);
\r
8566 if (!farrightflag && triedgeequal(farrighttri, bottommost)) {
\r
8567 triedgecopy(lefttri, bottommost);
\r
8570 if (randomnation(SAMPLERATE) == 0) {
\r
8571 splayroot = splayinsert(splayroot, &lefttri, nextpoint);
\r
8572 } else if (randomnation(SAMPLERATE) == 0) {
\r
8573 lnext(righttri, inserttri);
\r
8574 splayroot = splayinsert(splayroot, &inserttri, nextpoint);
\r
8578 nextevent->eventptr = (VOID *) freeevents;
\r
8579 freeevents = nextevent;
\r
8581 if (check4events) {
\r
8582 apex(farlefttri, leftpoint);
\r
8583 dest(lefttri, midpoint);
\r
8584 apex(lefttri, rightpoint);
\r
8585 lefttest = counterclockwise(leftpoint, midpoint, rightpoint);
\r
8586 if (lefttest > 0.0) {
\r
8587 newevent = freeevents;
\r
8588 freeevents = (struct event *) freeevents->eventptr;
\r
8589 newevent->xkey = xminextreme;
\r
8590 newevent->ykey = circletop(leftpoint, midpoint, rightpoint,
\r
8592 newevent->eventptr = (VOID *) encode(lefttri);
\r
8593 eventheapinsert(eventheap, heapsize, newevent);
\r
8595 setorg(lefttri, newevent);
\r
8597 apex(righttri, leftpoint);
\r
8598 org(righttri, midpoint);
\r
8599 apex(farrighttri, rightpoint);
\r
8600 righttest = counterclockwise(leftpoint, midpoint, rightpoint);
\r
8601 if (righttest > 0.0) {
\r
8602 newevent = freeevents;
\r
8603 freeevents = (struct event *) freeevents->eventptr;
\r
8604 newevent->xkey = xminextreme;
\r
8605 newevent->ykey = circletop(leftpoint, midpoint, rightpoint,
\r
8607 newevent->eventptr = (VOID *) encode(farrighttri);
\r
8608 eventheapinsert(eventheap, heapsize, newevent);
\r
8610 setorg(farrighttri, newevent);
\r
8615 pooldeinit(&splaynodes);
\r
8616 lprevself(bottommost);
\r
8617 return removeghosts(&bottommost);
\r
8620 #endif /* not REDUCED */
\r
8624 /********* Sweepline Delaunay triangulation ends here *********/
\r
8626 /********* General mesh construction routines begin here *********/
\r
8630 /*****************************************************************************/
\r
8632 /* delaunay() Form a Delaunay triangulation. */
\r
8634 /*****************************************************************************/
\r
8639 initializetrisegpools();
\r
8644 "Constructing Delaunay triangulation by divide-and-conquer method.\n");
\r
8646 return divconqdelaunay();
\r
8647 #else /* not REDUCED */
\r
8649 printf("Constructing Delaunay triangulation ");
\r
8650 if (incremental) {
\r
8651 printf("by incremental method.\n");
\r
8652 } else if (sweepline) {
\r
8653 printf("by sweepline method.\n");
\r
8655 printf("by divide-and-conquer method.\n");
\r
8658 if (incremental) {
\r
8659 return incrementaldelaunay();
\r
8660 } else if (sweepline) {
\r
8661 return sweeplinedelaunay();
\r
8663 return divconqdelaunay();
\r
8665 #endif /* not REDUCED */
\r
8668 /*****************************************************************************/
\r
8670 /* reconstruct() Reconstruct a triangulation from its .ele (and possibly */
\r
8671 /* .poly) file. Used when the -r switch is used. */
\r
8673 /* Reads an .ele file and reconstructs the original mesh. If the -p switch */
\r
8674 /* is used, this procedure will also read a .poly file and reconstruct the */
\r
8675 /* shell edges of the original mesh. If the -a switch is used, this */
\r
8676 /* procedure will also read an .area file and set a maximum area constraint */
\r
8677 /* on each triangle. */
\r
8679 /* Points that are not corners of triangles, such as nodes on edges of */
\r
8680 /* subparametric elements, are discarded. */
\r
8682 /* This routine finds the adjacencies between triangles (and shell edges) */
\r
8683 /* by forming one stack of triangles for each vertex. Each triangle is on */
\r
8684 /* three different stacks simultaneously. Each triangle's shell edge */
\r
8685 /* pointers are used to link the items in each stack. This memory-saving */
\r
8686 /* feature makes the code harder to read. The most important thing to keep */
\r
8687 /* in mind is that each triangle is removed from a stack precisely when */
\r
8688 /* the corresponding pointer is adjusted to refer to a shell edge rather */
\r
8689 /* than the next triangle of the stack. */
\r
8691 /*****************************************************************************/
\r
8697 int reconstruct(trianglelist, triangleattriblist, trianglearealist, elements,
\r
8698 corners, attribs, segmentlist, segmentmarkerlist,
\r
8700 int *trianglelist;
\r
8701 REAL *triangleattriblist;
\r
8702 REAL *trianglearealist;
\r
8707 int *segmentmarkerlist;
\r
8708 int numberofsegments;
\r
8710 #else /* not TRILIBRARY */
\r
8712 long reconstruct(elefilename, areafilename, polyfilename, polyfile)
\r
8713 char *elefilename;
\r
8714 char *areafilename;
\r
8715 char *polyfilename;
\r
8718 #endif /* not TRILIBRARY */
\r
8724 #else /* not TRILIBRARY */
\r
8727 char inputline[INPUTLINESIZE];
\r
8730 #endif /* not TRILIBRARY */
\r
8731 struct triedge triangleloop;
\r
8732 struct triedge triangleleft;
\r
8733 struct triedge checktri;
\r
8734 struct triedge checkleft;
\r
8735 struct triedge checkneighbor;
\r
8736 struct edge shelleloop;
\r
8737 triangle *vertexarray;
\r
8738 triangle *prevlink;
\r
8740 point tdest, tapex;
\r
8741 point checkdest, checkapex;
\r
8747 int killpointindex;
\r
8749 int segmentmarkers;
\r
8754 int elementnumber, segmentnumber;
\r
8756 triangle ptr; /* Temporary variable used by sym(). */
\r
8759 inelements = elements;
\r
8760 incorners = corners;
\r
8761 if (incorners < 3) {
\r
8762 printf("Error: Triangles must have at least 3 points.\n");
\r
8765 eextras = attribs;
\r
8766 #else /* not TRILIBRARY */
\r
8767 /* Read the triangles from an .ele file. */
\r
8769 printf("Opening %s.\n", elefilename);
\r
8771 elefile = fopen(elefilename, "r");
\r
8772 if (elefile == (FILE *) NULL) {
\r
8773 printf(" Error: Cannot access file %s.\n", elefilename);
\r
8776 /* Read number of triangles, number of points per triangle, and */
\r
8777 /* number of triangle attributes from .ele file. */
\r
8778 stringptr = readline(inputline, elefile, elefilename);
\r
8779 inelements = (int) strtol (stringptr, &stringptr, 0);
\r
8780 stringptr = findfield(stringptr);
\r
8781 if (*stringptr == '\0') {
\r
8784 incorners = (int) strtol (stringptr, &stringptr, 0);
\r
8785 if (incorners < 3) {
\r
8786 printf("Error: Triangles in %s must have at least 3 points.\n",
\r
8791 stringptr = findfield(stringptr);
\r
8792 if (*stringptr == '\0') {
\r
8795 eextras = (int) strtol (stringptr, &stringptr, 0);
\r
8797 #endif /* not TRILIBRARY */
\r
8799 initializetrisegpools();
\r
8801 /* Create the triangles. */
\r
8802 for (elementnumber = 1; elementnumber <= inelements; elementnumber++) {
\r
8803 maketriangle(&triangleloop);
\r
8804 /* Mark the triangle as living. */
\r
8805 triangleloop.tri[3] = (triangle) triangleloop.tri;
\r
8810 insegments = numberofsegments;
\r
8811 segmentmarkers = segmentmarkerlist != (int *) NULL;
\r
8812 #else /* not TRILIBRARY */
\r
8813 /* Read number of segments and number of segment */
\r
8814 /* boundary markers from .poly file. */
\r
8815 stringptr = readline(inputline, polyfile, inpolyfilename);
\r
8816 insegments = (int) strtol (stringptr, &stringptr, 0);
\r
8817 stringptr = findfield(stringptr);
\r
8818 if (*stringptr == '\0') {
\r
8819 segmentmarkers = 0;
\r
8821 segmentmarkers = (int) strtol (stringptr, &stringptr, 0);
\r
8823 #endif /* not TRILIBRARY */
\r
8825 /* Create the shell edges. */
\r
8826 for (segmentnumber = 1; segmentnumber <= insegments; segmentnumber++) {
\r
8827 makeshelle(&shelleloop);
\r
8828 /* Mark the shell edge as living. */
\r
8829 shelleloop.sh[2] = (shelle) shelleloop.sh;
\r
8836 #else /* not TRILIBRARY */
\r
8838 /* Open an .area file, check for consistency with the .ele file. */
\r
8840 printf("Opening %s.\n", areafilename);
\r
8842 areafile = fopen(areafilename, "r");
\r
8843 if (areafile == (FILE *) NULL) {
\r
8844 printf(" Error: Cannot access file %s.\n", areafilename);
\r
8847 stringptr = readline(inputline, areafile, areafilename);
\r
8848 areaelements = (int) strtol (stringptr, &stringptr, 0);
\r
8849 if (areaelements != inelements) {
\r
8850 printf("Error: %s and %s disagree on number of triangles.\n",
\r
8851 elefilename, areafilename);
\r
8855 #endif /* not TRILIBRARY */
\r
8858 printf("Reconstructing mesh.\n");
\r
8860 /* Allocate a temporary array that maps each point to some adjacent */
\r
8861 /* triangle. I took care to allocate all the permanent memory for */
\r
8862 /* triangles and shell edges first. */
\r
8863 vertexarray = (triangle *) malloc(points.items * sizeof(triangle));
\r
8864 if (vertexarray == (triangle *) NULL) {
\r
8865 printf("Error: Out of memory.\n");
\r
8868 /* Each point is initially unrepresented. */
\r
8869 for (i = 0; i < points.items; i++) {
\r
8870 vertexarray[i] = (triangle) dummytri;
\r
8874 printf(" Assembling triangles.\n");
\r
8876 /* Read the triangles from the .ele file, and link */
\r
8877 /* together those that share an edge. */
\r
8878 traversalinit(&triangles);
\r
8879 triangleloop.tri = triangletraverse();
\r
8880 elementnumber = firstnumber;
\r
8881 while (triangleloop.tri != (triangle *) NULL) {
\r
8883 /* Copy the triangle's three corners. */
\r
8884 for (j = 0; j < 3; j++) {
\r
8885 corner[j] = trianglelist[pointindex++];
\r
8886 if ((corner[j] < firstnumber) || (corner[j] >= firstnumber + inpoints)) {
\r
8887 printf("Error: Triangle %d has an invalid vertex index.\n",
\r
8892 #else /* not TRILIBRARY */
\r
8893 /* Read triangle number and the triangle's three corners. */
\r
8894 stringptr = readline(inputline, elefile, elefilename);
\r
8895 for (j = 0; j < 3; j++) {
\r
8896 stringptr = findfield(stringptr);
\r
8897 if (*stringptr == '\0') {
\r
8898 printf("Error: Triangle %d is missing point %d in %s.\n",
\r
8899 elementnumber, j + 1, elefilename);
\r
8902 corner[j] = (int) strtol (stringptr, &stringptr, 0);
\r
8903 if ((corner[j] < firstnumber) ||
\r
8904 (corner[j] >= firstnumber + inpoints)) {
\r
8905 printf("Error: Triangle %d has an invalid vertex index.\n",
\r
8911 #endif /* not TRILIBRARY */
\r
8913 /* Find out about (and throw away) extra nodes. */
\r
8914 for (j = 3; j < incorners; j++) {
\r
8916 killpointindex = trianglelist[pointindex++];
\r
8917 #else /* not TRILIBRARY */
\r
8918 stringptr = findfield(stringptr);
\r
8919 if (*stringptr != '\0') {
\r
8920 killpointindex = (int) strtol (stringptr, &stringptr, 0);
\r
8921 #endif /* not TRILIBRARY */
\r
8922 if ((killpointindex >= firstnumber) &&
\r
8923 (killpointindex < firstnumber + inpoints)) {
\r
8924 /* Delete the non-corner point if it's not already deleted. */
\r
8925 killpoint = getpoint(killpointindex);
\r
8926 if (pointmark(killpoint) != DEADPOINT) {
\r
8927 pointdealloc(killpoint);
\r
8930 #ifndef TRILIBRARY
\r
8932 #endif /* not TRILIBRARY */
\r
8935 /* Read the triangle's attributes. */
\r
8936 for (j = 0; j < eextras; j++) {
\r
8938 setelemattribute(triangleloop, j, triangleattriblist[attribindex++]);
\r
8939 #else /* not TRILIBRARY */
\r
8940 stringptr = findfield(stringptr);
\r
8941 if (*stringptr == '\0') {
\r
8942 setelemattribute(triangleloop, j, 0);
\r
8944 setelemattribute(triangleloop, j,
\r
8945 (REAL) strtod (stringptr, &stringptr));
\r
8947 #endif /* not TRILIBRARY */
\r
8952 area = trianglearealist[elementnumber - firstnumber];
\r
8953 #else /* not TRILIBRARY */
\r
8954 /* Read an area constraint from the .area file. */
\r
8955 stringptr = readline(inputline, areafile, areafilename);
\r
8956 stringptr = findfield(stringptr);
\r
8957 if (*stringptr == '\0') {
\r
8958 area = -1.0; /* No constraint on this triangle. */
\r
8960 area = (REAL) strtod(stringptr, &stringptr);
\r
8962 #endif /* not TRILIBRARY */
\r
8963 setareabound(triangleloop, area);
\r
8966 /* Set the triangle's vertices. */
\r
8967 triangleloop.orient = 0;
\r
8968 setorg(triangleloop, getpoint(corner[0]));
\r
8969 setdest(triangleloop, getpoint(corner[1]));
\r
8970 setapex(triangleloop, getpoint(corner[2]));
\r
8971 /* Try linking the triangle to others that share these vertices. */
\r
8972 for (triangleloop.orient = 0; triangleloop.orient < 3;
\r
8973 triangleloop.orient++) {
\r
8974 /* Take the number for the origin of triangleloop. */
\r
8975 aroundpoint = corner[triangleloop.orient];
\r
8976 /* Look for other triangles having this vertex. */
\r
8977 nexttri = vertexarray[aroundpoint - firstnumber];
\r
8978 /* Link the current triangle to the next one in the stack. */
\r
8979 triangleloop.tri[6 + triangleloop.orient] = nexttri;
\r
8980 /* Push the current triangle onto the stack. */
\r
8981 vertexarray[aroundpoint - firstnumber] = encode(triangleloop);
\r
8982 decode(nexttri, checktri);
\r
8983 if (checktri.tri != dummytri) {
\r
8984 dest(triangleloop, tdest);
\r
8985 apex(triangleloop, tapex);
\r
8986 /* Look for other triangles that share an edge. */
\r
8988 dest(checktri, checkdest);
\r
8989 apex(checktri, checkapex);
\r
8990 if (tapex == checkdest) {
\r
8991 /* The two triangles share an edge; bond them together. */
\r
8992 lprev(triangleloop, triangleleft);
\r
8993 bond(triangleleft, checktri);
\r
8995 if (tdest == checkapex) {
\r
8996 /* The two triangles share an edge; bond them together. */
\r
8997 lprev(checktri, checkleft);
\r
8998 bond(triangleloop, checkleft);
\r
9000 /* Find the next triangle in the stack. */
\r
9001 nexttri = checktri.tri[6 + checktri.orient];
\r
9002 decode(nexttri, checktri);
\r
9003 } while (checktri.tri != dummytri);
\r
9006 triangleloop.tri = triangletraverse();
\r
9012 #else /* not TRILIBRARY */
\r
9017 #endif /* not TRILIBRARY */
\r
9019 hullsize = 0; /* Prepare to count the boundary edges. */
\r
9022 printf(" Marking segments in triangulation.\n");
\r
9024 /* Read the segments from the .poly file, and link them */
\r
9025 /* to their neighboring triangles. */
\r
9027 traversalinit(&shelles);
\r
9028 shelleloop.sh = shelletraverse();
\r
9029 segmentnumber = firstnumber;
\r
9030 while (shelleloop.sh != (shelle *) NULL) {
\r
9032 end[0] = segmentlist[pointindex++];
\r
9033 end[1] = segmentlist[pointindex++];
\r
9034 if (segmentmarkers) {
\r
9035 boundmarker = segmentmarkerlist[segmentnumber - firstnumber];
\r
9037 #else /* not TRILIBRARY */
\r
9038 /* Read the endpoints of each segment, and possibly a boundary marker. */
\r
9039 stringptr = readline(inputline, polyfile, inpolyfilename);
\r
9040 /* Skip the first (segment number) field. */
\r
9041 stringptr = findfield(stringptr);
\r
9042 if (*stringptr == '\0') {
\r
9043 printf("Error: Segment %d has no endpoints in %s.\n", segmentnumber,
\r
9047 end[0] = (int) strtol (stringptr, &stringptr, 0);
\r
9049 stringptr = findfield(stringptr);
\r
9050 if (*stringptr == '\0') {
\r
9051 printf("Error: Segment %d is missing its second endpoint in %s.\n",
\r
9052 segmentnumber, polyfilename);
\r
9055 end[1] = (int) strtol (stringptr, &stringptr, 0);
\r
9057 if (segmentmarkers) {
\r
9058 stringptr = findfield(stringptr);
\r
9059 if (*stringptr == '\0') {
\r
9062 boundmarker = (int) strtol (stringptr, &stringptr, 0);
\r
9065 #endif /* not TRILIBRARY */
\r
9066 for (j = 0; j < 2; j++) {
\r
9067 if ((end[j] < firstnumber) || (end[j] >= firstnumber + inpoints)) {
\r
9068 printf("Error: Segment %d has an invalid vertex index.\n",
\r
9074 /* set the shell edge's vertices. */
\r
9075 shelleloop.shorient = 0;
\r
9076 setsorg(shelleloop, getpoint(end[0]));
\r
9077 setsdest(shelleloop, getpoint(end[1]));
\r
9078 setmark(shelleloop, boundmarker);
\r
9079 /* Try linking the shell edge to triangles that share these vertices. */
\r
9080 for (shelleloop.shorient = 0; shelleloop.shorient < 2;
\r
9081 shelleloop.shorient++) {
\r
9082 /* Take the number for the destination of shelleloop. */
\r
9083 aroundpoint = end[1 - shelleloop.shorient];
\r
9084 /* Look for triangles having this vertex. */
\r
9085 prevlink = &vertexarray[aroundpoint - firstnumber];
\r
9086 nexttri = vertexarray[aroundpoint - firstnumber];
\r
9087 decode(nexttri, checktri);
\r
9088 sorg(shelleloop, shorg);
\r
9090 /* Look for triangles having this edge. Note that I'm only */
\r
9091 /* comparing each triangle's destination with the shell edge; */
\r
9092 /* each triangle's apex is handled through a different vertex. */
\r
9093 /* Because each triangle appears on three vertices' lists, each */
\r
9094 /* occurrence of a triangle on a list can (and does) represent */
\r
9095 /* an edge. In this way, most edges are represented twice, and */
\r
9096 /* every triangle-segment bond is represented once. */
\r
9097 while (notfound && (checktri.tri != dummytri)) {
\r
9098 dest(checktri, checkdest);
\r
9099 if (shorg == checkdest) {
\r
9100 /* We have a match. Remove this triangle from the list. */
\r
9101 *prevlink = checktri.tri[6 + checktri.orient];
\r
9102 /* Bond the shell edge to the triangle. */
\r
9103 tsbond(checktri, shelleloop);
\r
9104 /* Check if this is a boundary edge. */
\r
9105 sym(checktri, checkneighbor);
\r
9106 if (checkneighbor.tri == dummytri) {
\r
9107 /* The next line doesn't insert a shell edge (because there's */
\r
9108 /* already one there), but it sets the boundary markers of */
\r
9109 /* the existing shell edge and its vertices. */
\r
9110 insertshelle(&checktri, 1);
\r
9115 /* Find the next triangle in the stack. */
\r
9116 prevlink = &checktri.tri[6 + checktri.orient];
\r
9117 nexttri = checktri.tri[6 + checktri.orient];
\r
9118 decode(nexttri, checktri);
\r
9121 shelleloop.sh = shelletraverse();
\r
9126 /* Mark the remaining edges as not being attached to any shell edge. */
\r
9127 /* Also, count the (yet uncounted) boundary edges. */
\r
9128 for (i = 0; i < points.items; i++) {
\r
9129 /* Search the stack of triangles adjacent to a point. */
\r
9130 nexttri = vertexarray[i];
\r
9131 decode(nexttri, checktri);
\r
9132 while (checktri.tri != dummytri) {
\r
9133 /* Find the next triangle in the stack before this */
\r
9134 /* information gets overwritten. */
\r
9135 nexttri = checktri.tri[6 + checktri.orient];
\r
9136 /* No adjacent shell edge. (This overwrites the stack info.) */
\r
9137 tsdissolve(checktri);
\r
9138 sym(checktri, checkneighbor);
\r
9139 if (checkneighbor.tri == dummytri) {
\r
9140 insertshelle(&checktri, 1);
\r
9143 decode(nexttri, checktri);
\r
9147 free(vertexarray);
\r
9151 #endif /* not CDT_ONLY */
\r
9155 /********* General mesh construction routines end here *********/
\r
9157 /********* Segment (shell edge) insertion begins here *********/
\r
9161 /*****************************************************************************/
\r
9163 /* finddirection() Find the first triangle on the path from one point */
\r
9166 /* Finds the triangle that intersects a line segment drawn from the */
\r
9167 /* origin of `searchtri' to the point `endpoint', and returns the result */
\r
9168 /* in `searchtri'. The origin of `searchtri' does not change, even though */
\r
9169 /* the triangle returned may differ from the one passed in. This routine */
\r
9170 /* is used to find the direction to move in to get from one point to */
\r
9173 /* The return value notes whether the destination or apex of the found */
\r
9174 /* triangle is collinear with the two points in question. */
\r
9176 /*****************************************************************************/
\r
9178 enum finddirectionresult finddirection(searchtri, endpoint)
\r
9179 struct triedge *searchtri;
\r
9182 struct triedge checktri;
\r
9184 point leftpoint, rightpoint;
\r
9185 REAL leftccw, rightccw;
\r
9186 int leftflag, rightflag;
\r
9187 triangle ptr; /* Temporary variable used by onext() and oprev(). */
\r
9189 org(*searchtri, startpoint);
\r
9190 dest(*searchtri, rightpoint);
\r
9191 apex(*searchtri, leftpoint);
\r
9192 /* Is `endpoint' to the left? */
\r
9193 leftccw = counterclockwise(endpoint, startpoint, leftpoint);
\r
9194 leftflag = leftccw > 0.0;
\r
9195 /* Is `endpoint' to the right? */
\r
9196 rightccw = counterclockwise(startpoint, endpoint, rightpoint);
\r
9197 rightflag = rightccw > 0.0;
\r
9198 if (leftflag && rightflag) {
\r
9199 /* `searchtri' faces directly away from `endpoint'. We could go */
\r
9200 /* left or right. Ask whether it's a triangle or a boundary */
\r
9201 /* on the left. */
\r
9202 onext(*searchtri, checktri);
\r
9203 if (checktri.tri == dummytri) {
\r
9209 while (leftflag) {
\r
9210 /* Turn left until satisfied. */
\r
9211 onextself(*searchtri);
\r
9212 if (searchtri->tri == dummytri) {
\r
9213 printf("Internal error in finddirection(): Unable to find a\n");
\r
9214 printf(" triangle leading from (%.12g, %.12g) to", startpoint[0],
\r
9216 printf(" (%.12g, %.12g).\n", endpoint[0], endpoint[1]);
\r
9219 apex(*searchtri, leftpoint);
\r
9220 rightccw = leftccw;
\r
9221 leftccw = counterclockwise(endpoint, startpoint, leftpoint);
\r
9222 leftflag = leftccw > 0.0;
\r
9224 while (rightflag) {
\r
9225 /* Turn right until satisfied. */
\r
9226 oprevself(*searchtri);
\r
9227 if (searchtri->tri == dummytri) {
\r
9228 printf("Internal error in finddirection(): Unable to find a\n");
\r
9229 printf(" triangle leading from (%.12g, %.12g) to", startpoint[0],
\r
9231 printf(" (%.12g, %.12g).\n", endpoint[0], endpoint[1]);
\r
9234 dest(*searchtri, rightpoint);
\r
9235 leftccw = rightccw;
\r
9236 rightccw = counterclockwise(startpoint, endpoint, rightpoint);
\r
9237 rightflag = rightccw > 0.0;
\r
9239 if (leftccw == 0.0) {
\r
9240 return LEFTCOLLINEAR;
\r
9241 } else if (rightccw == 0.0) {
\r
9242 return RIGHTCOLLINEAR;
\r
9248 /*****************************************************************************/
\r
9250 /* segmentintersection() Find the intersection of an existing segment */
\r
9251 /* and a segment that is being inserted. Insert */
\r
9252 /* a point at the intersection, splitting an */
\r
9253 /* existing shell edge. */
\r
9255 /* The segment being inserted connects the apex of splittri to endpoint2. */
\r
9256 /* splitshelle is the shell edge being split, and MUST be opposite */
\r
9257 /* splittri. Hence, the edge being split connects the origin and */
\r
9258 /* destination of splittri. */
\r
9260 /* On completion, splittri is a handle having the newly inserted */
\r
9261 /* intersection point as its origin, and endpoint1 as its destination. */
\r
9263 /*****************************************************************************/
\r
9265 void segmentintersection(splittri, splitshelle, endpoint2)
\r
9266 struct triedge *splittri;
\r
9267 struct edge *splitshelle;
\r
9271 point torg, tdest;
\r
9272 point leftpoint, rightpoint;
\r
9274 enum insertsiteresult success;
\r
9275 enum finddirectionresult collinear;
\r
9279 REAL split, denom;
\r
9281 triangle ptr; /* Temporary variable used by onext(). */
\r
9283 /* Find the other three segment endpoints. */
\r
9284 apex(*splittri, endpoint1);
\r
9285 org(*splittri, torg);
\r
9286 dest(*splittri, tdest);
\r
9287 /* Segment intersection formulae; see the Antonio reference. */
\r
9288 tx = tdest[0] - torg[0];
\r
9289 ty = tdest[1] - torg[1];
\r
9290 ex = endpoint2[0] - endpoint1[0];
\r
9291 ey = endpoint2[1] - endpoint1[1];
\r
9292 etx = torg[0] - endpoint2[0];
\r
9293 ety = torg[1] - endpoint2[1];
\r
9294 denom = ty * ex - tx * ey;
\r
9295 if (denom == 0.0) {
\r
9296 printf("Internal error in segmentintersection():");
\r
9297 printf(" Attempt to find intersection of parallel segments.\n");
\r
9300 split = (ey * etx - ex * ety) / denom;
\r
9301 /* Create the new point. */
\r
9302 newpoint = (point) poolalloc(&points);
\r
9303 /* Interpolate its coordinate and attributes. */
\r
9304 for (i = 0; i < 2 + nextras; i++) {
\r
9305 newpoint[i] = torg[i] + split * (tdest[i] - torg[i]);
\r
9307 setpointmark(newpoint, mark(*splitshelle));
\r
9308 if (verbose > 1) {
\r
9310 " Splitting edge (%.12g, %.12g) (%.12g, %.12g) at (%.12g, %.12g).\n",
\r
9311 torg[0], torg[1], tdest[0], tdest[1], newpoint[0], newpoint[1]);
\r
9313 /* Insert the intersection point. This should always succeed. */
\r
9314 success = insertsite(newpoint, splittri, splitshelle, 0, 0);
\r
9315 if (success != SUCCESSFULPOINT) {
\r
9316 printf("Internal error in segmentintersection():\n");
\r
9317 printf(" Failure to split a segment.\n");
\r
9320 if (steinerleft > 0) {
\r
9323 /* Inserting the point may have caused edge flips. We wish to rediscover */
\r
9324 /* the edge connecting endpoint1 to the new intersection point. */
\r
9325 collinear = finddirection(splittri, endpoint1);
\r
9326 dest(*splittri, rightpoint);
\r
9327 apex(*splittri, leftpoint);
\r
9328 if ((leftpoint[0] == endpoint1[0]) && (leftpoint[1] == endpoint1[1])) {
\r
9329 onextself(*splittri);
\r
9330 } else if ((rightpoint[0] != endpoint1[0]) ||
\r
9331 (rightpoint[1] != endpoint1[1])) {
\r
9332 printf("Internal error in segmentintersection():\n");
\r
9333 printf(" Topological inconsistency after splitting a segment.\n");
\r
9336 /* `splittri' should have destination endpoint1. */
\r
9339 /*****************************************************************************/
\r
9341 /* scoutsegment() Scout the first triangle on the path from one endpoint */
\r
9342 /* to another, and check for completion (reaching the */
\r
9343 /* second endpoint), a collinear point, and the */
\r
9344 /* intersection of two segments. */
\r
9346 /* Returns one if the entire segment is successfully inserted, and zero if */
\r
9347 /* the job must be finished by conformingedge() or constrainededge(). */
\r
9349 /* If the first triangle on the path has the second endpoint as its */
\r
9350 /* destination or apex, a shell edge is inserted and the job is done. */
\r
9352 /* If the first triangle on the path has a destination or apex that lies on */
\r
9353 /* the segment, a shell edge is inserted connecting the first endpoint to */
\r
9354 /* the collinear point, and the search is continued from the collinear */
\r
9357 /* If the first triangle on the path has a shell edge opposite its origin, */
\r
9358 /* then there is a segment that intersects the segment being inserted. */
\r
9359 /* Their intersection point is inserted, splitting the shell edge. */
\r
9361 /* Otherwise, return zero. */
\r
9363 /*****************************************************************************/
\r
9365 int scoutsegment(searchtri, endpoint2, newmark)
\r
9366 struct triedge *searchtri;
\r
9370 struct triedge crosstri;
\r
9371 struct edge crossedge;
\r
9372 point leftpoint, rightpoint;
\r
9374 enum finddirectionresult collinear;
\r
9375 shelle sptr; /* Temporary variable used by tspivot(). */
\r
9377 collinear = finddirection(searchtri, endpoint2);
\r
9378 dest(*searchtri, rightpoint);
\r
9379 apex(*searchtri, leftpoint);
\r
9380 if (((leftpoint[0] == endpoint2[0]) && (leftpoint[1] == endpoint2[1])) ||
\r
9381 ((rightpoint[0] == endpoint2[0]) && (rightpoint[1] == endpoint2[1]))) {
\r
9382 /* The segment is already an edge in the mesh. */
\r
9383 if ((leftpoint[0] == endpoint2[0]) && (leftpoint[1] == endpoint2[1])) {
\r
9384 lprevself(*searchtri);
\r
9386 /* Insert a shell edge, if there isn't already one there. */
\r
9387 insertshelle(searchtri, newmark);
\r
9389 } else if (collinear == LEFTCOLLINEAR) {
\r
9390 /* We've collided with a point between the segment's endpoints. */
\r
9391 /* Make the collinear point be the triangle's origin. */
\r
9392 lprevself(*searchtri);
\r
9393 insertshelle(searchtri, newmark);
\r
9394 /* Insert the remainder of the segment. */
\r
9395 return scoutsegment(searchtri, endpoint2, newmark);
\r
9396 } else if (collinear == RIGHTCOLLINEAR) {
\r
9397 /* We've collided with a point between the segment's endpoints. */
\r
9398 insertshelle(searchtri, newmark);
\r
9399 /* Make the collinear point be the triangle's origin. */
\r
9400 lnextself(*searchtri);
\r
9401 /* Insert the remainder of the segment. */
\r
9402 return scoutsegment(searchtri, endpoint2, newmark);
\r
9404 lnext(*searchtri, crosstri);
\r
9405 tspivot(crosstri, crossedge);
\r
9406 /* Check for a crossing segment. */
\r
9407 if (crossedge.sh == dummysh) {
\r
9410 org(*searchtri, endpoint1);
\r
9411 /* Insert a point at the intersection. */
\r
9412 segmentintersection(&crosstri, &crossedge, endpoint2);
\r
9413 triedgecopy(crosstri, *searchtri);
\r
9414 insertshelle(searchtri, newmark);
\r
9415 /* Insert the remainder of the segment. */
\r
9416 return scoutsegment(searchtri, endpoint2, newmark);
\r
9421 /*****************************************************************************/
\r
9423 /* conformingedge() Force a segment into a conforming Delaunay */
\r
9424 /* triangulation by inserting a point at its midpoint, */
\r
9425 /* and recursively forcing in the two half-segments if */
\r
9428 /* Generates a sequence of edges connecting `endpoint1' to `endpoint2'. */
\r
9429 /* `newmark' is the boundary marker of the segment, assigned to each new */
\r
9430 /* splitting point and shell edge. */
\r
9432 /* Note that conformingedge() does not always maintain the conforming */
\r
9433 /* Delaunay property. Once inserted, segments are locked into place; */
\r
9434 /* points inserted later (to force other segments in) may render these */
\r
9435 /* fixed segments non-Delaunay. The conforming Delaunay property will be */
\r
9436 /* restored by enforcequality() by splitting encroached segments. */
\r
9438 /*****************************************************************************/
\r
9443 void conformingedge(endpoint1, endpoint2, newmark)
\r
9448 struct triedge searchtri1, searchtri2;
\r
9449 struct edge brokenshelle;
\r
9451 point midpoint1, midpoint2;
\r
9452 enum insertsiteresult success;
\r
9453 int result1, result2;
\r
9455 shelle sptr; /* Temporary variable used by tspivot(). */
\r
9457 if (verbose > 2) {
\r
9458 printf("Forcing segment into triangulation by recursive splitting:\n");
\r
9459 printf(" (%.12g, %.12g) (%.12g, %.12g)\n", endpoint1[0], endpoint1[1],
\r
9460 endpoint2[0], endpoint2[1]);
\r
9462 /* Create a new point to insert in the middle of the segment. */
\r
9463 newpoint = (point) poolalloc(&points);
\r
9464 /* Interpolate coordinates and attributes. */
\r
9465 for (i = 0; i < 2 + nextras; i++) {
\r
9466 newpoint[i] = 0.5 * (endpoint1[i] + endpoint2[i]);
\r
9468 setpointmark(newpoint, newmark);
\r
9469 /* Find a boundary triangle to search from. */
\r
9470 searchtri1.tri = (triangle *) NULL;
\r
9471 /* Attempt to insert the new point. */
\r
9472 success = insertsite(newpoint, &searchtri1, (struct edge *) NULL, 0, 0);
\r
9473 if (success == DUPLICATEPOINT) {
\r
9474 if (verbose > 2) {
\r
9475 printf(" Segment intersects existing point (%.12g, %.12g).\n",
\r
9476 newpoint[0], newpoint[1]);
\r
9478 /* Use the point that's already there. */
\r
9479 pointdealloc(newpoint);
\r
9480 org(searchtri1, newpoint);
\r
9482 if (success == VIOLATINGPOINT) {
\r
9483 if (verbose > 2) {
\r
9484 printf(" Two segments intersect at (%.12g, %.12g).\n",
\r
9485 newpoint[0], newpoint[1]);
\r
9487 /* By fluke, we've landed right on another segment. Split it. */
\r
9488 tspivot(searchtri1, brokenshelle);
\r
9489 success = insertsite(newpoint, &searchtri1, &brokenshelle, 0, 0);
\r
9490 if (success != SUCCESSFULPOINT) {
\r
9491 printf("Internal error in conformingedge():\n");
\r
9492 printf(" Failure to split a segment.\n");
\r
9496 /* The point has been inserted successfully. */
\r
9497 if (steinerleft > 0) {
\r
9501 triedgecopy(searchtri1, searchtri2);
\r
9502 result1 = scoutsegment(&searchtri1, endpoint1, newmark);
\r
9503 result2 = scoutsegment(&searchtri2, endpoint2, newmark);
\r
9505 /* The origin of searchtri1 may have changed if a collision with an */
\r
9506 /* intervening vertex on the segment occurred. */
\r
9507 org(searchtri1, midpoint1);
\r
9508 conformingedge(midpoint1, endpoint1, newmark);
\r
9511 /* The origin of searchtri2 may have changed if a collision with an */
\r
9512 /* intervening vertex on the segment occurred. */
\r
9513 org(searchtri2, midpoint2);
\r
9514 conformingedge(midpoint2, endpoint2, newmark);
\r
9518 #endif /* not CDT_ONLY */
\r
9519 #endif /* not REDUCED */
\r
9521 /*****************************************************************************/
\r
9523 /* delaunayfixup() Enforce the Delaunay condition at an edge, fanning out */
\r
9524 /* recursively from an existing point. Pay special */
\r
9525 /* attention to stacking inverted triangles. */
\r
9527 /* This is a support routine for inserting segments into a constrained */
\r
9528 /* Delaunay triangulation. */
\r
9530 /* The origin of fixuptri is treated as if it has just been inserted, and */
\r
9531 /* the local Delaunay condition needs to be enforced. It is only enforced */
\r
9532 /* in one sector, however, that being the angular range defined by */
\r
9535 /* This routine also needs to make decisions regarding the "stacking" of */
\r
9536 /* triangles. (Read the description of constrainededge() below before */
\r
9537 /* reading on here, so you understand the algorithm.) If the position of */
\r
9538 /* the new point (the origin of fixuptri) indicates that the vertex before */
\r
9539 /* it on the polygon is a reflex vertex, then "stack" the triangle by */
\r
9540 /* doing nothing. (fixuptri is an inverted triangle, which is how stacked */
\r
9541 /* triangles are identified.) */
\r
9543 /* Otherwise, check whether the vertex before that was a reflex vertex. */
\r
9544 /* If so, perform an edge flip, thereby eliminating an inverted triangle */
\r
9545 /* (popping it off the stack). The edge flip may result in the creation */
\r
9546 /* of a new inverted triangle, depending on whether or not the new vertex */
\r
9547 /* is visible to the vertex three edges behind on the polygon. */
\r
9549 /* If neither of the two vertices behind the new vertex are reflex */
\r
9550 /* vertices, fixuptri and fartri, the triangle opposite it, are not */
\r
9551 /* inverted; hence, ensure that the edge between them is locally Delaunay. */
\r
9553 /* `leftside' indicates whether or not fixuptri is to the left of the */
\r
9554 /* segment being inserted. (Imagine that the segment is pointing up from */
\r
9555 /* endpoint1 to endpoint2.) */
\r
9557 /*****************************************************************************/
\r
9559 void delaunayfixup(fixuptri, leftside)
\r
9560 struct triedge *fixuptri;
\r
9563 struct triedge neartri;
\r
9564 struct triedge fartri;
\r
9565 struct edge faredge;
\r
9566 point nearpoint, leftpoint, rightpoint, farpoint;
\r
9567 triangle ptr; /* Temporary variable used by sym(). */
\r
9568 shelle sptr; /* Temporary variable used by tspivot(). */
\r
9570 lnext(*fixuptri, neartri);
\r
9571 sym(neartri, fartri);
\r
9572 /* Check if the edge opposite the origin of fixuptri can be flipped. */
\r
9573 if (fartri.tri == dummytri) {
\r
9576 tspivot(neartri, faredge);
\r
9577 if (faredge.sh != dummysh) {
\r
9580 /* Find all the relevant vertices. */
\r
9581 apex(neartri, nearpoint);
\r
9582 org(neartri, leftpoint);
\r
9583 dest(neartri, rightpoint);
\r
9584 apex(fartri, farpoint);
\r
9585 /* Check whether the previous polygon vertex is a reflex vertex. */
\r
9587 if (counterclockwise(nearpoint, leftpoint, farpoint) <= 0.0) {
\r
9588 /* leftpoint is a reflex vertex too. Nothing can */
\r
9589 /* be done until a convex section is found. */
\r
9593 if (counterclockwise(farpoint, rightpoint, nearpoint) <= 0.0) {
\r
9594 /* rightpoint is a reflex vertex too. Nothing can */
\r
9595 /* be done until a convex section is found. */
\r
9599 if (counterclockwise(rightpoint, leftpoint, farpoint) > 0.0) {
\r
9600 /* fartri is not an inverted triangle, and farpoint is not a reflex */
\r
9601 /* vertex. As there are no reflex vertices, fixuptri isn't an */
\r
9602 /* inverted triangle, either. Hence, test the edge between the */
\r
9603 /* triangles to ensure it is locally Delaunay. */
\r
9604 if (incircle(leftpoint, farpoint, rightpoint, nearpoint) <= 0.0) {
\r
9607 /* Not locally Delaunay; go on to an edge flip. */
\r
9608 } /* else fartri is inverted; remove it from the stack by flipping. */
\r
9610 lprevself(*fixuptri); /* Restore the origin of fixuptri after the flip. */
\r
9611 /* Recursively process the two triangles that result from the flip. */
\r
9612 delaunayfixup(fixuptri, leftside);
\r
9613 delaunayfixup(&fartri, leftside);
\r
9616 /*****************************************************************************/
\r
9618 /* constrainededge() Force a segment into a constrained Delaunay */
\r
9619 /* triangulation by deleting the triangles it */
\r
9620 /* intersects, and triangulating the polygons that */
\r
9621 /* form on each side of it. */
\r
9623 /* Generates a single edge connecting `endpoint1' to `endpoint2'. The */
\r
9624 /* triangle `starttri' has `endpoint1' as its origin. `newmark' is the */
\r
9625 /* boundary marker of the segment. */
\r
9627 /* To insert a segment, every triangle whose interior intersects the */
\r
9628 /* segment is deleted. The union of these deleted triangles is a polygon */
\r
9629 /* (which is not necessarily monotone, but is close enough), which is */
\r
9630 /* divided into two polygons by the new segment. This routine's task is */
\r
9631 /* to generate the Delaunay triangulation of these two polygons. */
\r
9633 /* You might think of this routine's behavior as a two-step process. The */
\r
9634 /* first step is to walk from endpoint1 to endpoint2, flipping each edge */
\r
9635 /* encountered. This step creates a fan of edges connected to endpoint1, */
\r
9636 /* including the desired edge to endpoint2. The second step enforces the */
\r
9637 /* Delaunay condition on each side of the segment in an incremental manner: */
\r
9638 /* proceeding along the polygon from endpoint1 to endpoint2 (this is done */
\r
9639 /* independently on each side of the segment), each vertex is "enforced" */
\r
9640 /* as if it had just been inserted, but affecting only the previous */
\r
9641 /* vertices. The result is the same as if the vertices had been inserted */
\r
9642 /* in the order they appear on the polygon, so the result is Delaunay. */
\r
9644 /* In truth, constrainededge() interleaves these two steps. The procedure */
\r
9645 /* walks from endpoint1 to endpoint2, and each time an edge is encountered */
\r
9646 /* and flipped, the newly exposed vertex (at the far end of the flipped */
\r
9647 /* edge) is "enforced" upon the previously flipped edges, usually affecting */
\r
9648 /* only one side of the polygon (depending upon which side of the segment */
\r
9649 /* the vertex falls on). */
\r
9651 /* The algorithm is complicated by the need to handle polygons that are not */
\r
9652 /* convex. Although the polygon is not necessarily monotone, it can be */
\r
9653 /* triangulated in a manner similar to the stack-based algorithms for */
\r
9654 /* monotone polygons. For each reflex vertex (local concavity) of the */
\r
9655 /* polygon, there will be an inverted triangle formed by one of the edge */
\r
9656 /* flips. (An inverted triangle is one with negative area - that is, its */
\r
9657 /* vertices are arranged in clockwise order - and is best thought of as a */
\r
9658 /* wrinkle in the fabric of the mesh.) Each inverted triangle can be */
\r
9659 /* thought of as a reflex vertex pushed on the stack, waiting to be fixed */
\r
9662 /* A reflex vertex is popped from the stack when a vertex is inserted that */
\r
9663 /* is visible to the reflex vertex. (However, if the vertex behind the */
\r
9664 /* reflex vertex is not visible to the reflex vertex, a new inverted */
\r
9665 /* triangle will take its place on the stack.) These details are handled */
\r
9666 /* by the delaunayfixup() routine above. */
\r
9668 /*****************************************************************************/
\r
9670 void constrainededge(starttri, endpoint2, newmark)
\r
9671 struct triedge *starttri;
\r
9675 struct triedge fixuptri, fixuptri2;
\r
9676 struct edge fixupedge;
\r
9682 triangle ptr; /* Temporary variable used by sym() and oprev(). */
\r
9683 shelle sptr; /* Temporary variable used by tspivot(). */
\r
9685 org(*starttri, endpoint1);
\r
9686 lnext(*starttri, fixuptri);
\r
9688 /* `collision' indicates whether we have found a point directly */
\r
9689 /* between endpoint1 and endpoint2. */
\r
9693 org(fixuptri, farpoint);
\r
9694 /* `farpoint' is the extreme point of the polygon we are "digging" */
\r
9695 /* to get from endpoint1 to endpoint2. */
\r
9696 if ((farpoint[0] == endpoint2[0]) && (farpoint[1] == endpoint2[1])) {
\r
9697 oprev(fixuptri, fixuptri2);
\r
9698 /* Enforce the Delaunay condition around endpoint2. */
\r
9699 delaunayfixup(&fixuptri, 0);
\r
9700 delaunayfixup(&fixuptri2, 1);
\r
9703 /* Check whether farpoint is to the left or right of the segment */
\r
9704 /* being inserted, to decide which edge of fixuptri to dig */
\r
9705 /* through next. */
\r
9706 area = counterclockwise(endpoint1, endpoint2, farpoint);
\r
9707 if (area == 0.0) {
\r
9708 /* We've collided with a point between endpoint1 and endpoint2. */
\r
9710 oprev(fixuptri, fixuptri2);
\r
9711 /* Enforce the Delaunay condition around farpoint. */
\r
9712 delaunayfixup(&fixuptri, 0);
\r
9713 delaunayfixup(&fixuptri2, 1);
\r
9716 if (area > 0.0) { /* farpoint is to the left of the segment. */
\r
9717 oprev(fixuptri, fixuptri2);
\r
9718 /* Enforce the Delaunay condition around farpoint, on the */
\r
9719 /* left side of the segment only. */
\r
9720 delaunayfixup(&fixuptri2, 1);
\r
9721 /* Flip the edge that crosses the segment. After the edge is */
\r
9722 /* flipped, one of its endpoints is the fan vertex, and the */
\r
9723 /* destination of fixuptri is the fan vertex. */
\r
9724 lprevself(fixuptri);
\r
9725 } else { /* farpoint is to the right of the segment. */
\r
9726 delaunayfixup(&fixuptri, 0);
\r
9727 /* Flip the edge that crosses the segment. After the edge is */
\r
9728 /* flipped, one of its endpoints is the fan vertex, and the */
\r
9729 /* destination of fixuptri is the fan vertex. */
\r
9730 oprevself(fixuptri);
\r
9732 /* Check for two intersecting segments. */
\r
9733 tspivot(fixuptri, fixupedge);
\r
9734 if (fixupedge.sh == dummysh) {
\r
9735 flip(&fixuptri); /* May create an inverted triangle on the left. */
\r
9737 /* We've collided with a segment between endpoint1 and endpoint2. */
\r
9739 /* Insert a point at the intersection. */
\r
9740 segmentintersection(&fixuptri, &fixupedge, endpoint2);
\r
9746 /* Insert a shell edge to make the segment permanent. */
\r
9747 insertshelle(&fixuptri, newmark);
\r
9748 /* If there was a collision with an interceding vertex, install another */
\r
9749 /* segment connecting that vertex with endpoint2. */
\r
9751 /* Insert the remainder of the segment. */
\r
9752 if (!scoutsegment(&fixuptri, endpoint2, newmark)) {
\r
9753 constrainededge(&fixuptri, endpoint2, newmark);
\r
9758 /*****************************************************************************/
\r
9760 /* insertsegment() Insert a PSLG segment into a triangulation. */
\r
9762 /*****************************************************************************/
\r
9764 void insertsegment(endpoint1, endpoint2, newmark)
\r
9769 struct triedge searchtri1, searchtri2;
\r
9770 triangle encodedtri;
\r
9772 triangle ptr; /* Temporary variable used by sym(). */
\r
9774 if (verbose > 1) {
\r
9775 printf(" Connecting (%.12g, %.12g) to (%.12g, %.12g).\n",
\r
9776 endpoint1[0], endpoint1[1], endpoint2[0], endpoint2[1]);
\r
9779 /* Find a triangle whose origin is the segment's first endpoint. */
\r
9780 checkpoint = (point) NULL;
\r
9781 encodedtri = point2tri(endpoint1);
\r
9782 if (encodedtri != (triangle) NULL) {
\r
9783 decode(encodedtri, searchtri1);
\r
9784 org(searchtri1, checkpoint);
\r
9786 if (checkpoint != endpoint1) {
\r
9787 /* Find a boundary triangle to search from. */
\r
9788 searchtri1.tri = dummytri;
\r
9789 searchtri1.orient = 0;
\r
9790 symself(searchtri1);
\r
9791 /* Search for the segment's first endpoint by point location. */
\r
9792 if (locate(endpoint1, &searchtri1) != ONVERTEX) {
\r
9794 "Internal error in insertsegment(): Unable to locate PSLG point\n");
\r
9795 printf(" (%.12g, %.12g) in triangulation.\n",
\r
9796 endpoint1[0], endpoint1[1]);
\r
9800 /* Remember this triangle to improve subsequent point location. */
\r
9801 triedgecopy(searchtri1, recenttri);
\r
9802 /* Scout the beginnings of a path from the first endpoint */
\r
9803 /* toward the second. */
\r
9804 if (scoutsegment(&searchtri1, endpoint2, newmark)) {
\r
9805 /* The segment was easily inserted. */
\r
9808 /* The first endpoint may have changed if a collision with an intervening */
\r
9809 /* vertex on the segment occurred. */
\r
9810 org(searchtri1, endpoint1);
\r
9812 /* Find a triangle whose origin is the segment's second endpoint. */
\r
9813 checkpoint = (point) NULL;
\r
9814 encodedtri = point2tri(endpoint2);
\r
9815 if (encodedtri != (triangle) NULL) {
\r
9816 decode(encodedtri, searchtri2);
\r
9817 org(searchtri2, checkpoint);
\r
9819 if (checkpoint != endpoint2) {
\r
9820 /* Find a boundary triangle to search from. */
\r
9821 searchtri2.tri = dummytri;
\r
9822 searchtri2.orient = 0;
\r
9823 symself(searchtri2);
\r
9824 /* Search for the segment's second endpoint by point location. */
\r
9825 if (locate(endpoint2, &searchtri2) != ONVERTEX) {
\r
9827 "Internal error in insertsegment(): Unable to locate PSLG point\n");
\r
9828 printf(" (%.12g, %.12g) in triangulation.\n",
\r
9829 endpoint2[0], endpoint2[1]);
\r
9833 /* Remember this triangle to improve subsequent point location. */
\r
9834 triedgecopy(searchtri2, recenttri);
\r
9835 /* Scout the beginnings of a path from the second endpoint */
\r
9836 /* toward the first. */
\r
9837 if (scoutsegment(&searchtri2, endpoint1, newmark)) {
\r
9838 /* The segment was easily inserted. */
\r
9841 /* The second endpoint may have changed if a collision with an intervening */
\r
9842 /* vertex on the segment occurred. */
\r
9843 org(searchtri2, endpoint2);
\r
9848 /* Insert vertices to force the segment into the triangulation. */
\r
9849 conformingedge(endpoint1, endpoint2, newmark);
\r
9851 #endif /* not CDT_ONLY */
\r
9852 #endif /* not REDUCED */
\r
9853 /* Insert the segment directly into the triangulation. */
\r
9854 constrainededge(&searchtri1, endpoint2, newmark);
\r
9858 #endif /* not CDT_ONLY */
\r
9859 #endif /* not REDUCED */
\r
9862 /*****************************************************************************/
\r
9864 /* markhull() Cover the convex hull of a triangulation with shell edges. */
\r
9866 /*****************************************************************************/
\r
9870 struct triedge hulltri;
\r
9871 struct triedge nexttri;
\r
9872 struct triedge starttri;
\r
9873 triangle ptr; /* Temporary variable used by sym() and oprev(). */
\r
9875 /* Find a triangle handle on the hull. */
\r
9876 hulltri.tri = dummytri;
\r
9877 hulltri.orient = 0;
\r
9879 /* Remember where we started so we know when to stop. */
\r
9880 triedgecopy(hulltri, starttri);
\r
9881 /* Go once counterclockwise around the convex hull. */
\r
9883 /* Create a shell edge if there isn't already one here. */
\r
9884 insertshelle(&hulltri, 1);
\r
9885 /* To find the next hull edge, go clockwise around the next vertex. */
\r
9886 lnextself(hulltri);
\r
9887 oprev(hulltri, nexttri);
\r
9888 while (nexttri.tri != dummytri) {
\r
9889 triedgecopy(nexttri, hulltri);
\r
9890 oprev(hulltri, nexttri);
\r
9892 } while (!triedgeequal(hulltri, starttri));
\r
9895 /*****************************************************************************/
\r
9897 /* formskeleton() Create the shell edges of a triangulation, including */
\r
9898 /* PSLG edges and edges on the convex hull. */
\r
9900 /* The PSLG edges are read from a .poly file. The return value is the */
\r
9901 /* number of segments in the file. */
\r
9903 /*****************************************************************************/
\r
9907 int formskeleton(segmentlist, segmentmarkerlist, numberofsegments)
\r
9909 int *segmentmarkerlist;
\r
9910 int numberofsegments;
\r
9912 #else /* not TRILIBRARY */
\r
9914 int formskeleton(polyfile, polyfilename)
\r
9916 char *polyfilename;
\r
9918 #endif /* not TRILIBRARY */
\r
9922 char polyfilename[6];
\r
9924 #else /* not TRILIBRARY */
\r
9925 char inputline[INPUTLINESIZE];
\r
9927 #endif /* not TRILIBRARY */
\r
9928 point endpoint1, endpoint2;
\r
9930 int segmentmarkers;
\r
9937 printf("Inserting segments into Delaunay triangulation.\n");
\r
9940 strcpy(polyfilename, "input");
\r
9941 segments = numberofsegments;
\r
9942 segmentmarkers = segmentmarkerlist != (int *) NULL;
\r
9944 #else /* not TRILIBRARY */
\r
9945 /* Read the segments from a .poly file. */
\r
9946 /* Read number of segments and number of boundary markers. */
\r
9947 stringptr = readline(inputline, polyfile, polyfilename);
\r
9948 segments = (int) strtol (stringptr, &stringptr, 0);
\r
9949 stringptr = findfield(stringptr);
\r
9950 if (*stringptr == '\0') {
\r
9951 segmentmarkers = 0;
\r
9953 segmentmarkers = (int) strtol (stringptr, &stringptr, 0);
\r
9955 #endif /* not TRILIBRARY */
\r
9956 /* If segments are to be inserted, compute a mapping */
\r
9957 /* from points to triangles. */
\r
9958 if (segments > 0) {
\r
9960 printf(" Inserting PSLG segments.\n");
\r
9966 /* Read and insert the segments. */
\r
9967 for (i = 1; i <= segments; i++) {
\r
9969 end1 = segmentlist[index++];
\r
9970 end2 = segmentlist[index++];
\r
9971 if (segmentmarkers) {
\r
9972 boundmarker = segmentmarkerlist[i - 1];
\r
9974 #else /* not TRILIBRARY */
\r
9975 stringptr = readline(inputline, polyfile, inpolyfilename);
\r
9976 stringptr = findfield(stringptr);
\r
9977 if (*stringptr == '\0') {
\r
9978 printf("Error: Segment %d has no endpoints in %s.\n", i,
\r
9982 end1 = (int) strtol (stringptr, &stringptr, 0);
\r
9984 stringptr = findfield(stringptr);
\r
9985 if (*stringptr == '\0') {
\r
9986 printf("Error: Segment %d is missing its second endpoint in %s.\n", i,
\r
9990 end2 = (int) strtol (stringptr, &stringptr, 0);
\r
9992 if (segmentmarkers) {
\r
9993 stringptr = findfield(stringptr);
\r
9994 if (*stringptr == '\0') {
\r
9997 boundmarker = (int) strtol (stringptr, &stringptr, 0);
\r
10000 #endif /* not TRILIBRARY */
\r
10001 if ((end1 < firstnumber) || (end1 >= firstnumber + inpoints)) {
\r
10003 printf("Warning: Invalid first endpoint of segment %d in %s.\n", i,
\r
10006 } else if ((end2 < firstnumber) || (end2 >= firstnumber + inpoints)) {
\r
10008 printf("Warning: Invalid second endpoint of segment %d in %s.\n", i,
\r
10012 endpoint1 = getpoint(end1);
\r
10013 endpoint2 = getpoint(end2);
\r
10014 if ((endpoint1[0] == endpoint2[0]) && (endpoint1[1] == endpoint2[1])) {
\r
10016 printf("Warning: Endpoints of segment %d are coincident in %s.\n",
\r
10017 i, polyfilename);
\r
10020 insertsegment(endpoint1, endpoint2, boundmarker);
\r
10027 if (convex || !poly) {
\r
10028 /* Enclose the convex hull with shell edges. */
\r
10030 printf(" Enclosing convex hull with segments.\n");
\r
10039 /********* Segment (shell edge) insertion ends here *********/
\r
10041 /********* Carving out holes and concavities begins here *********/
\r
10045 /*****************************************************************************/
\r
10047 /* infecthull() Virally infect all of the triangles of the convex hull */
\r
10048 /* that are not protected by shell edges. Where there are */
\r
10049 /* shell edges, set boundary markers as appropriate. */
\r
10051 /*****************************************************************************/
\r
10053 void infecthull()
\r
10055 struct triedge hulltri;
\r
10056 struct triedge nexttri;
\r
10057 struct triedge starttri;
\r
10058 struct edge hulledge;
\r
10059 triangle **deadtri;
\r
10060 point horg, hdest;
\r
10061 triangle ptr; /* Temporary variable used by sym(). */
\r
10062 shelle sptr; /* Temporary variable used by tspivot(). */
\r
10065 printf(" Marking concavities (external triangles) for elimination.\n");
\r
10067 /* Find a triangle handle on the hull. */
\r
10068 hulltri.tri = dummytri;
\r
10069 hulltri.orient = 0;
\r
10070 symself(hulltri);
\r
10071 /* Remember where we started so we know when to stop. */
\r
10072 triedgecopy(hulltri, starttri);
\r
10073 /* Go once counterclockwise around the convex hull. */
\r
10075 /* Ignore triangles that are already infected. */
\r
10076 if (!infected(hulltri)) {
\r
10077 /* Is the triangle protected by a shell edge? */
\r
10078 tspivot(hulltri, hulledge);
\r
10079 if (hulledge.sh == dummysh) {
\r
10080 /* The triangle is not protected; infect it. */
\r
10082 deadtri = (triangle **) poolalloc(&viri);
\r
10083 *deadtri = hulltri.tri;
\r
10085 /* The triangle is protected; set boundary markers if appropriate. */
\r
10086 if (mark(hulledge) == 0) {
\r
10087 setmark(hulledge, 1);
\r
10088 org(hulltri, horg);
\r
10089 dest(hulltri, hdest);
\r
10090 if (pointmark(horg) == 0) {
\r
10091 setpointmark(horg, 1);
\r
10093 if (pointmark(hdest) == 0) {
\r
10094 setpointmark(hdest, 1);
\r
10099 /* To find the next hull edge, go clockwise around the next vertex. */
\r
10100 lnextself(hulltri);
\r
10101 oprev(hulltri, nexttri);
\r
10102 while (nexttri.tri != dummytri) {
\r
10103 triedgecopy(nexttri, hulltri);
\r
10104 oprev(hulltri, nexttri);
\r
10106 } while (!triedgeequal(hulltri, starttri));
\r
10109 /*****************************************************************************/
\r
10111 /* plague() Spread the virus from all infected triangles to any neighbors */
\r
10112 /* not protected by shell edges. Delete all infected triangles. */
\r
10114 /* This is the procedure that actually creates holes and concavities. */
\r
10116 /* This procedure operates in two phases. The first phase identifies all */
\r
10117 /* the triangles that will die, and marks them as infected. They are */
\r
10118 /* marked to ensure that each triangle is added to the virus pool only */
\r
10119 /* once, so the procedure will terminate. */
\r
10121 /* The second phase actually eliminates the infected triangles. It also */
\r
10122 /* eliminates orphaned points. */
\r
10124 /*****************************************************************************/
\r
10128 struct triedge testtri;
\r
10129 struct triedge neighbor;
\r
10130 triangle **virusloop;
\r
10131 triangle **deadtri;
\r
10132 struct edge neighborshelle;
\r
10134 point norg, ndest;
\r
10135 point deadorg, deaddest, deadapex;
\r
10137 triangle ptr; /* Temporary variable used by sym() and onext(). */
\r
10138 shelle sptr; /* Temporary variable used by tspivot(). */
\r
10141 printf(" Marking neighbors of marked triangles.\n");
\r
10143 /* Loop through all the infected triangles, spreading the virus to */
\r
10144 /* their neighbors, then to their neighbors' neighbors. */
\r
10145 traversalinit(&viri);
\r
10146 virusloop = (triangle **) traverse(&viri);
\r
10147 while (virusloop != (triangle **) NULL) {
\r
10148 testtri.tri = *virusloop;
\r
10149 /* A triangle is marked as infected by messing with one of its shell */
\r
10150 /* edges, setting it to an illegal value. Hence, we have to */
\r
10151 /* temporarily uninfect this triangle so that we can examine its */
\r
10152 /* adjacent shell edges. */
\r
10153 uninfect(testtri);
\r
10154 if (verbose > 2) {
\r
10155 /* Assign the triangle an orientation for convenience in */
\r
10156 /* checking its points. */
\r
10157 testtri.orient = 0;
\r
10158 org(testtri, deadorg);
\r
10159 dest(testtri, deaddest);
\r
10160 apex(testtri, deadapex);
\r
10161 printf(" Checking (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
\r
10162 deadorg[0], deadorg[1], deaddest[0], deaddest[1],
\r
10163 deadapex[0], deadapex[1]);
\r
10165 /* Check each of the triangle's three neighbors. */
\r
10166 for (testtri.orient = 0; testtri.orient < 3; testtri.orient++) {
\r
10167 /* Find the neighbor. */
\r
10168 sym(testtri, neighbor);
\r
10169 /* Check for a shell between the triangle and its neighbor. */
\r
10170 tspivot(testtri, neighborshelle);
\r
10171 /* Check if the neighbor is nonexistent or already infected. */
\r
10172 if ((neighbor.tri == dummytri) || infected(neighbor)) {
\r
10173 if (neighborshelle.sh != dummysh) {
\r
10174 /* There is a shell edge separating the triangle from its */
\r
10175 /* neighbor, but both triangles are dying, so the shell */
\r
10176 /* edge dies too. */
\r
10177 shelledealloc(neighborshelle.sh);
\r
10178 if (neighbor.tri != dummytri) {
\r
10179 /* Make sure the shell edge doesn't get deallocated again */
\r
10180 /* later when the infected neighbor is visited. */
\r
10181 uninfect(neighbor);
\r
10182 tsdissolve(neighbor);
\r
10183 infect(neighbor);
\r
10186 } else { /* The neighbor exists and is not infected. */
\r
10187 if (neighborshelle.sh == dummysh) {
\r
10188 /* There is no shell edge protecting the neighbor, so */
\r
10189 /* the neighbor becomes infected. */
\r
10190 if (verbose > 2) {
\r
10191 org(neighbor, deadorg);
\r
10192 dest(neighbor, deaddest);
\r
10193 apex(neighbor, deadapex);
\r
10195 " Marking (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
\r
10196 deadorg[0], deadorg[1], deaddest[0], deaddest[1],
\r
10197 deadapex[0], deadapex[1]);
\r
10199 infect(neighbor);
\r
10200 /* Ensure that the neighbor's neighbors will be infected. */
\r
10201 deadtri = (triangle **) poolalloc(&viri);
\r
10202 *deadtri = neighbor.tri;
\r
10203 } else { /* The neighbor is protected by a shell edge. */
\r
10204 /* Remove this triangle from the shell edge. */
\r
10205 stdissolve(neighborshelle);
\r
10206 /* The shell edge becomes a boundary. Set markers accordingly. */
\r
10207 if (mark(neighborshelle) == 0) {
\r
10208 setmark(neighborshelle, 1);
\r
10210 org(neighbor, norg);
\r
10211 dest(neighbor, ndest);
\r
10212 if (pointmark(norg) == 0) {
\r
10213 setpointmark(norg, 1);
\r
10215 if (pointmark(ndest) == 0) {
\r
10216 setpointmark(ndest, 1);
\r
10221 /* Remark the triangle as infected, so it doesn't get added to the */
\r
10222 /* virus pool again. */
\r
10224 virusloop = (triangle **) traverse(&viri);
\r
10228 printf(" Deleting marked triangles.\n");
\r
10230 traversalinit(&viri);
\r
10231 virusloop = (triangle **) traverse(&viri);
\r
10232 while (virusloop != (triangle **) NULL) {
\r
10233 testtri.tri = *virusloop;
\r
10235 /* Check each of the three corners of the triangle for elimination. */
\r
10236 /* This is done by walking around each point, checking if it is */
\r
10237 /* still connected to at least one live triangle. */
\r
10238 for (testtri.orient = 0; testtri.orient < 3; testtri.orient++) {
\r
10239 org(testtri, testpoint);
\r
10240 /* Check if the point has already been tested. */
\r
10241 if (testpoint != (point) NULL) {
\r
10243 /* Mark the corner of the triangle as having been tested. */
\r
10244 setorg(testtri, NULL);
\r
10245 /* Walk counterclockwise about the point. */
\r
10246 onext(testtri, neighbor);
\r
10247 /* Stop upon reaching a boundary or the starting triangle. */
\r
10248 while ((neighbor.tri != dummytri)
\r
10249 && (!triedgeequal(neighbor, testtri))) {
\r
10250 if (infected(neighbor)) {
\r
10251 /* Mark the corner of this triangle as having been tested. */
\r
10252 setorg(neighbor, NULL);
\r
10254 /* A live triangle. The point survives. */
\r
10257 /* Walk counterclockwise about the point. */
\r
10258 onextself(neighbor);
\r
10260 /* If we reached a boundary, we must walk clockwise as well. */
\r
10261 if (neighbor.tri == dummytri) {
\r
10262 /* Walk clockwise about the point. */
\r
10263 oprev(testtri, neighbor);
\r
10264 /* Stop upon reaching a boundary. */
\r
10265 while (neighbor.tri != dummytri) {
\r
10266 if (infected(neighbor)) {
\r
10267 /* Mark the corner of this triangle as having been tested. */
\r
10268 setorg(neighbor, NULL);
\r
10270 /* A live triangle. The point survives. */
\r
10273 /* Walk clockwise about the point. */
\r
10274 oprevself(neighbor);
\r
10278 if (verbose > 1) {
\r
10279 printf(" Deleting point (%.12g, %.12g)\n",
\r
10280 testpoint[0], testpoint[1]);
\r
10282 pointdealloc(testpoint);
\r
10287 /* Record changes in the number of boundary edges, and disconnect */
\r
10288 /* dead triangles from their neighbors. */
\r
10289 for (testtri.orient = 0; testtri.orient < 3; testtri.orient++) {
\r
10290 sym(testtri, neighbor);
\r
10291 if (neighbor.tri == dummytri) {
\r
10292 /* There is no neighboring triangle on this edge, so this edge */
\r
10293 /* is a boundary edge. This triangle is being deleted, so this */
\r
10294 /* boundary edge is deleted. */
\r
10297 /* Disconnect the triangle from its neighbor. */
\r
10298 dissolve(neighbor);
\r
10299 /* There is a neighboring triangle on this edge, so this edge */
\r
10300 /* becomes a boundary edge when this triangle is deleted. */
\r
10304 /* Return the dead triangle to the pool of triangles. */
\r
10305 triangledealloc(testtri.tri);
\r
10306 virusloop = (triangle **) traverse(&viri);
\r
10308 /* Empty the virus pool. */
\r
10309 poolrestart(&viri);
\r
10312 /*****************************************************************************/
\r
10314 /* regionplague() Spread regional attributes and/or area constraints */
\r
10315 /* (from a .poly file) throughout the mesh. */
\r
10317 /* This procedure operates in two phases. The first phase spreads an */
\r
10318 /* attribute and/or an area constraint through a (segment-bounded) region. */
\r
10319 /* The triangles are marked to ensure that each triangle is added to the */
\r
10320 /* virus pool only once, so the procedure will terminate. */
\r
10322 /* The second phase uninfects all infected triangles, returning them to */
\r
10325 /*****************************************************************************/
\r
10327 void regionplague(attribute, area)
\r
10331 struct triedge testtri;
\r
10332 struct triedge neighbor;
\r
10333 triangle **virusloop;
\r
10334 triangle **regiontri;
\r
10335 struct edge neighborshelle;
\r
10336 point regionorg, regiondest, regionapex;
\r
10337 triangle ptr; /* Temporary variable used by sym() and onext(). */
\r
10338 shelle sptr; /* Temporary variable used by tspivot(). */
\r
10340 if (verbose > 1) {
\r
10341 printf(" Marking neighbors of marked triangles.\n");
\r
10343 /* Loop through all the infected triangles, spreading the attribute */
\r
10344 /* and/or area constraint to their neighbors, then to their neighbors' */
\r
10346 traversalinit(&viri);
\r
10347 virusloop = (triangle **) traverse(&viri);
\r
10348 while (virusloop != (triangle **) NULL) {
\r
10349 testtri.tri = *virusloop;
\r
10350 /* A triangle is marked as infected by messing with one of its shell */
\r
10351 /* edges, setting it to an illegal value. Hence, we have to */
\r
10352 /* temporarily uninfect this triangle so that we can examine its */
\r
10353 /* adjacent shell edges. */
\r
10354 uninfect(testtri);
\r
10355 if (regionattrib) {
\r
10356 /* Set an attribute. */
\r
10357 setelemattribute(testtri, eextras, attribute);
\r
10360 /* Set an area constraint. */
\r
10361 setareabound(testtri, area);
\r
10363 if (verbose > 2) {
\r
10364 /* Assign the triangle an orientation for convenience in */
\r
10365 /* checking its points. */
\r
10366 testtri.orient = 0;
\r
10367 org(testtri, regionorg);
\r
10368 dest(testtri, regiondest);
\r
10369 apex(testtri, regionapex);
\r
10370 printf(" Checking (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
\r
10371 regionorg[0], regionorg[1], regiondest[0], regiondest[1],
\r
10372 regionapex[0], regionapex[1]);
\r
10374 /* Check each of the triangle's three neighbors. */
\r
10375 for (testtri.orient = 0; testtri.orient < 3; testtri.orient++) {
\r
10376 /* Find the neighbor. */
\r
10377 sym(testtri, neighbor);
\r
10378 /* Check for a shell between the triangle and its neighbor. */
\r
10379 tspivot(testtri, neighborshelle);
\r
10380 /* Make sure the neighbor exists, is not already infected, and */
\r
10381 /* isn't protected by a shell edge. */
\r
10382 if ((neighbor.tri != dummytri) && !infected(neighbor)
\r
10383 && (neighborshelle.sh == dummysh)) {
\r
10384 if (verbose > 2) {
\r
10385 org(neighbor, regionorg);
\r
10386 dest(neighbor, regiondest);
\r
10387 apex(neighbor, regionapex);
\r
10388 printf(" Marking (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
\r
10389 regionorg[0], regionorg[1], regiondest[0], regiondest[1],
\r
10390 regionapex[0], regionapex[1]);
\r
10392 /* Infect the neighbor. */
\r
10393 infect(neighbor);
\r
10394 /* Ensure that the neighbor's neighbors will be infected. */
\r
10395 regiontri = (triangle **) poolalloc(&viri);
\r
10396 *regiontri = neighbor.tri;
\r
10399 /* Remark the triangle as infected, so it doesn't get added to the */
\r
10400 /* virus pool again. */
\r
10402 virusloop = (triangle **) traverse(&viri);
\r
10405 /* Uninfect all triangles. */
\r
10406 if (verbose > 1) {
\r
10407 printf(" Unmarking marked triangles.\n");
\r
10409 traversalinit(&viri);
\r
10410 virusloop = (triangle **) traverse(&viri);
\r
10411 while (virusloop != (triangle **) NULL) {
\r
10412 testtri.tri = *virusloop;
\r
10413 uninfect(testtri);
\r
10414 virusloop = (triangle **) traverse(&viri);
\r
10416 /* Empty the virus pool. */
\r
10417 poolrestart(&viri);
\r
10420 /*****************************************************************************/
\r
10422 /* carveholes() Find the holes and infect them. Find the area */
\r
10423 /* constraints and infect them. Infect the convex hull. */
\r
10424 /* Spread the infection and kill triangles. Spread the */
\r
10425 /* area constraints. */
\r
10427 /* This routine mainly calls other routines to carry out all these */
\r
10430 /*****************************************************************************/
\r
10432 void carveholes(holelist, holes, regionlist, regions)
\r
10435 REAL *regionlist;
\r
10438 struct triedge searchtri;
\r
10439 struct triedge triangleloop;
\r
10440 struct triedge *regiontris;
\r
10441 triangle **holetri;
\r
10442 triangle **regiontri;
\r
10443 point searchorg, searchdest;
\r
10444 enum locateresult intersect;
\r
10446 triangle ptr; /* Temporary variable used by sym(). */
\r
10448 if (!(quiet || (noholes && convex))) {
\r
10449 printf("Removing unwanted triangles.\n");
\r
10450 if (verbose && (holes > 0)) {
\r
10451 printf(" Marking holes for elimination.\n");
\r
10455 if (regions > 0) {
\r
10456 /* Allocate storage for the triangles in which region points fall. */
\r
10457 regiontris = (struct triedge *) malloc(regions * sizeof(struct triedge));
\r
10458 if (regiontris == (struct triedge *) NULL) {
\r
10459 printf("Error: Out of memory.\n");
\r
10464 if (((holes > 0) && !noholes) || !convex || (regions > 0)) {
\r
10465 /* Initialize a pool of viri to be used for holes, concavities, */
\r
10466 /* regional attributes, and/or regional area constraints. */
\r
10467 poolinit(&viri, sizeof(triangle *), VIRUSPERBLOCK, POINTER, 0);
\r
10471 /* Mark as infected any unprotected triangles on the boundary. */
\r
10472 /* This is one way by which concavities are created. */
\r
10476 if ((holes > 0) && !noholes) {
\r
10477 /* Infect each triangle in which a hole lies. */
\r
10478 for (i = 0; i < 2 * holes; i += 2) {
\r
10479 /* Ignore holes that aren't within the bounds of the mesh. */
\r
10480 if ((holelist[i] >= xmin) && (holelist[i] <= xmax)
\r
10481 && (holelist[i + 1] >= ymin) && (holelist[i + 1] <= ymax)) {
\r
10482 /* Start searching from some triangle on the outer boundary. */
\r
10483 searchtri.tri = dummytri;
\r
10484 searchtri.orient = 0;
\r
10485 symself(searchtri);
\r
10486 /* Ensure that the hole is to the left of this boundary edge; */
\r
10487 /* otherwise, locate() will falsely report that the hole */
\r
10488 /* falls within the starting triangle. */
\r
10489 org(searchtri, searchorg);
\r
10490 dest(searchtri, searchdest);
\r
10491 if (counterclockwise(searchorg, searchdest, &holelist[i]) > 0.0) {
\r
10492 /* Find a triangle that contains the hole. */
\r
10493 intersect = locate(&holelist[i], &searchtri);
\r
10494 if ((intersect != OUTSIDE) && (!infected(searchtri))) {
\r
10495 /* Infect the triangle. This is done by marking the triangle */
\r
10496 /* as infect and including the triangle in the virus pool. */
\r
10497 infect(searchtri);
\r
10498 holetri = (triangle **) poolalloc(&viri);
\r
10499 *holetri = searchtri.tri;
\r
10506 /* Now, we have to find all the regions BEFORE we carve the holes, because */
\r
10507 /* locate() won't work when the triangulation is no longer convex. */
\r
10508 /* (Incidentally, this is the reason why regional attributes and area */
\r
10509 /* constraints can't be used when refining a preexisting mesh, which */
\r
10510 /* might not be convex; they can only be used with a freshly */
\r
10511 /* triangulated PSLG.) */
\r
10512 if (regions > 0) {
\r
10513 /* Find the starting triangle for each region. */
\r
10514 for (i = 0; i < regions; i++) {
\r
10515 regiontris[i].tri = dummytri;
\r
10516 /* Ignore region points that aren't within the bounds of the mesh. */
\r
10517 if ((regionlist[4 * i] >= xmin) && (regionlist[4 * i] <= xmax) &&
\r
10518 (regionlist[4 * i + 1] >= ymin) && (regionlist[4 * i + 1] <= ymax)) {
\r
10519 /* Start searching from some triangle on the outer boundary. */
\r
10520 searchtri.tri = dummytri;
\r
10521 searchtri.orient = 0;
\r
10522 symself(searchtri);
\r
10523 /* Ensure that the region point is to the left of this boundary */
\r
10524 /* edge; otherwise, locate() will falsely report that the */
\r
10525 /* region point falls within the starting triangle. */
\r
10526 org(searchtri, searchorg);
\r
10527 dest(searchtri, searchdest);
\r
10528 if (counterclockwise(searchorg, searchdest, ®ionlist[4 * i]) >
\r
10530 /* Find a triangle that contains the region point. */
\r
10531 intersect = locate(®ionlist[4 * i], &searchtri);
\r
10532 if ((intersect != OUTSIDE) && (!infected(searchtri))) {
\r
10533 /* Record the triangle for processing after the */
\r
10534 /* holes have been carved. */
\r
10535 triedgecopy(searchtri, regiontris[i]);
\r
10542 if (viri.items > 0) {
\r
10543 /* Carve the holes and concavities. */
\r
10546 /* The virus pool should be empty now. */
\r
10548 if (regions > 0) {
\r
10550 if (regionattrib) {
\r
10552 printf("Spreading regional attributes and area constraints.\n");
\r
10554 printf("Spreading regional attributes.\n");
\r
10557 printf("Spreading regional area constraints.\n");
\r
10560 if (regionattrib && !refine) {
\r
10561 /* Assign every triangle a regional attribute of zero. */
\r
10562 traversalinit(&triangles);
\r
10563 triangleloop.orient = 0;
\r
10564 triangleloop.tri = triangletraverse();
\r
10565 while (triangleloop.tri != (triangle *) NULL) {
\r
10566 setelemattribute(triangleloop, eextras, 0.0);
\r
10567 triangleloop.tri = triangletraverse();
\r
10570 for (i = 0; i < regions; i++) {
\r
10571 if (regiontris[i].tri != dummytri) {
\r
10572 /* Make sure the triangle under consideration still exists. */
\r
10573 /* It may have been eaten by the virus. */
\r
10574 if (regiontris[i].tri[3] != (triangle) NULL) {
\r
10575 /* Put one triangle in the virus pool. */
\r
10576 infect(regiontris[i]);
\r
10577 regiontri = (triangle **) poolalloc(&viri);
\r
10578 *regiontri = regiontris[i].tri;
\r
10579 /* Apply one region's attribute and/or area constraint. */
\r
10580 regionplague(regionlist[4 * i + 2], regionlist[4 * i + 3]);
\r
10581 /* The virus pool should be empty now. */
\r
10585 if (regionattrib && !refine) {
\r
10586 /* Note the fact that each triangle has an additional attribute. */
\r
10591 /* Free up memory. */
\r
10592 if (((holes > 0) && !noholes) || !convex || (regions > 0)) {
\r
10593 pooldeinit(&viri);
\r
10595 if (regions > 0) {
\r
10596 free(regiontris);
\r
10602 /********* Carving out holes and concavities ends here *********/
\r
10604 /********* Mesh quality maintenance begins here *********/
\r
10608 /*****************************************************************************/
\r
10610 /* tallyencs() Traverse the entire list of shell edges, check each edge */
\r
10611 /* to see if it is encroached. If so, add it to the list. */
\r
10613 /*****************************************************************************/
\r
10619 struct edge edgeloop;
\r
10622 traversalinit(&shelles);
\r
10623 edgeloop.shorient = 0;
\r
10624 edgeloop.sh = shelletraverse();
\r
10625 while (edgeloop.sh != (shelle *) NULL) {
\r
10626 /* If the segment is encroached, add it to the list. */
\r
10627 dummy = checkedge4encroach(&edgeloop);
\r
10628 edgeloop.sh = shelletraverse();
\r
10632 #endif /* not CDT_ONLY */
\r
10634 /*****************************************************************************/
\r
10636 /* precisionerror() Print an error message for precision problems. */
\r
10638 /*****************************************************************************/
\r
10642 void precisionerror()
\r
10644 printf("Try increasing the area criterion and/or reducing the minimum\n");
\r
10645 printf(" allowable angle so that tiny triangles are not created.\n");
\r
10647 printf("Alternatively, try recompiling me with double precision\n");
\r
10648 printf(" arithmetic (by removing \"#define SINGLE\" from the\n");
\r
10649 printf(" source file or \"-DSINGLE\" from the makefile).\n");
\r
10650 #endif /* SINGLE */
\r
10653 #endif /* not CDT_ONLY */
\r
10655 /*****************************************************************************/
\r
10657 /* repairencs() Find and repair all the encroached segments. */
\r
10659 /* Encroached segments are repaired by splitting them by inserting a point */
\r
10660 /* at or near their centers. */
\r
10662 /* `flaws' is a flag that specifies whether one should take note of new */
\r
10663 /* encroached segments and bad triangles that result from inserting points */
\r
10664 /* to repair existing encroached segments. */
\r
10666 /* When a segment is split, the two resulting subsegments are always */
\r
10667 /* tested to see if they are encroached upon, regardless of the value */
\r
10668 /* of `flaws'. */
\r
10670 /*****************************************************************************/
\r
10674 void repairencs(flaws)
\r
10677 struct triedge enctri;
\r
10678 struct triedge testtri;
\r
10679 struct edge *encloop;
\r
10680 struct edge testsh;
\r
10681 point eorg, edest;
\r
10683 enum insertsiteresult success;
\r
10684 REAL segmentlength, nearestpoweroftwo;
\r
10686 int acuteorg, acutedest;
\r
10689 triangle ptr; /* Temporary variable used by stpivot(). */
\r
10690 shelle sptr; /* Temporary variable used by snext(). */
\r
10692 while ((badsegments.items > 0) && (steinerleft != 0)) {
\r
10693 traversalinit(&badsegments);
\r
10694 encloop = badsegmenttraverse();
\r
10695 while ((encloop != (struct edge *) NULL) && (steinerleft != 0)) {
\r
10696 /* To decide where to split a segment, we need to know if the */
\r
10697 /* segment shares an endpoint with an adjacent segment. */
\r
10698 /* The concern is that, if we simply split every encroached */
\r
10699 /* segment in its center, two adjacent segments with a small */
\r
10700 /* angle between them might lead to an infinite loop; each */
\r
10701 /* point added to split one segment will encroach upon the */
\r
10702 /* other segment, which must then be split with a point that */
\r
10703 /* will encroach upon the first segment, and so on forever. */
\r
10704 /* To avoid this, imagine a set of concentric circles, whose */
\r
10705 /* radii are powers of two, about each segment endpoint. */
\r
10706 /* These concentric circles determine where the segment is */
\r
10707 /* split. (If both endpoints are shared with adjacent */
\r
10708 /* segments, split the segment in the middle, and apply the */
\r
10709 /* concentric shells for later splittings.) */
\r
10711 /* Is the origin shared with another segment? */
\r
10712 stpivot(*encloop, enctri);
\r
10713 lnext(enctri, testtri);
\r
10714 tspivot(testtri, testsh);
\r
10715 acuteorg = testsh.sh != dummysh;
\r
10716 /* Is the destination shared with another segment? */
\r
10717 lnextself(testtri);
\r
10718 tspivot(testtri, testsh);
\r
10719 acutedest = testsh.sh != dummysh;
\r
10720 /* Now, check the other side of the segment, if there's a triangle */
\r
10722 sym(enctri, testtri);
\r
10723 if (testtri.tri != dummytri) {
\r
10724 /* Is the destination shared with another segment? */
\r
10725 lnextself(testtri);
\r
10726 tspivot(testtri, testsh);
\r
10727 acutedest = acutedest || (testsh.sh != dummysh);
\r
10728 /* Is the origin shared with another segment? */
\r
10729 lnextself(testtri);
\r
10730 tspivot(testtri, testsh);
\r
10731 acuteorg = acuteorg || (testsh.sh != dummysh);
\r
10734 sorg(*encloop, eorg);
\r
10735 sdest(*encloop, edest);
\r
10736 /* Use the concentric circles if exactly one endpoint is shared */
\r
10737 /* with another adjacent segment. */
\r
10738 if (acuteorg ^ acutedest) {
\r
10739 segmentlength = sqrt((edest[0] - eorg[0]) * (edest[0] - eorg[0])
\r
10740 + (edest[1] - eorg[1]) * (edest[1] - eorg[1]));
\r
10741 /* Find the power of two nearest the segment's length. */
\r
10742 nearestpoweroftwo = 1.0;
\r
10743 while (segmentlength > SQUAREROOTTWO * nearestpoweroftwo) {
\r
10744 nearestpoweroftwo *= 2.0;
\r
10746 while (segmentlength < (0.5 * SQUAREROOTTWO) * nearestpoweroftwo) {
\r
10747 nearestpoweroftwo *= 0.5;
\r
10749 /* Where do we split the segment? */
\r
10750 split = 0.5 * nearestpoweroftwo / segmentlength;
\r
10752 split = 1.0 - split;
\r
10755 /* If we're not worried about adjacent segments, split */
\r
10756 /* this segment in the middle. */
\r
10760 /* Create the new point. */
\r
10761 newpoint = (point) poolalloc(&points);
\r
10762 /* Interpolate its coordinate and attributes. */
\r
10763 for (i = 0; i < 2 + nextras; i++) {
\r
10764 newpoint[i] = (1.0 - split) * eorg[i] + split * edest[i];
\r
10766 setpointmark(newpoint, mark(*encloop));
\r
10767 if (verbose > 1) {
\r
10769 " Splitting edge (%.12g, %.12g) (%.12g, %.12g) at (%.12g, %.12g).\n",
\r
10770 eorg[0], eorg[1], edest[0], edest[1], newpoint[0], newpoint[1]);
\r
10772 /* Check whether the new point lies on an endpoint. */
\r
10773 if (((newpoint[0] == eorg[0]) && (newpoint[1] == eorg[1]))
\r
10774 || ((newpoint[0] == edest[0]) && (newpoint[1] == edest[1]))) {
\r
10775 printf("Error: Ran out of precision at (%.12g, %.12g).\n",
\r
10776 newpoint[0], newpoint[1]);
\r
10777 printf("I attempted to split a segment to a smaller size than can\n");
\r
10778 printf(" be accommodated by the finite precision of floating point\n"
\r
10780 printf(" arithmetic.\n");
\r
10781 precisionerror();
\r
10784 /* Insert the splitting point. This should always succeed. */
\r
10785 success = insertsite(newpoint, &enctri, encloop, flaws, flaws);
\r
10786 if ((success != SUCCESSFULPOINT) && (success != ENCROACHINGPOINT)) {
\r
10787 printf("Internal error in repairencs():\n");
\r
10788 printf(" Failure to split a segment.\n");
\r
10791 if (steinerleft > 0) {
\r
10794 /* Check the two new subsegments to see if they're encroached. */
\r
10795 dummy = checkedge4encroach(encloop);
\r
10796 snextself(*encloop);
\r
10797 dummy = checkedge4encroach(encloop);
\r
10799 badsegmentdealloc(encloop);
\r
10800 encloop = badsegmenttraverse();
\r
10805 #endif /* not CDT_ONLY */
\r
10807 /*****************************************************************************/
\r
10809 /* tallyfaces() Test every triangle in the mesh for quality measures. */
\r
10811 /*****************************************************************************/
\r
10815 void tallyfaces()
\r
10817 struct triedge triangleloop;
\r
10820 printf(" Making a list of bad triangles.\n");
\r
10822 traversalinit(&triangles);
\r
10823 triangleloop.orient = 0;
\r
10824 triangleloop.tri = triangletraverse();
\r
10825 while (triangleloop.tri != (triangle *) NULL) {
\r
10826 /* If the triangle is bad, enqueue it. */
\r
10827 testtriangle(&triangleloop);
\r
10828 triangleloop.tri = triangletraverse();
\r
10832 #endif /* not CDT_ONLY */
\r
10834 /*****************************************************************************/
\r
10836 /* findcircumcenter() Find the circumcenter of a triangle. */
\r
10838 /* The result is returned both in terms of x-y coordinates and xi-eta */
\r
10839 /* coordinates. The xi-eta coordinate system is defined in terms of the */
\r
10840 /* triangle: the origin of the triangle is the origin of the coordinate */
\r
10841 /* system; the destination of the triangle is one unit along the xi axis; */
\r
10842 /* and the apex of the triangle is one unit along the eta axis. */
\r
10844 /* The return value indicates which edge of the triangle is shortest. */
\r
10846 /*****************************************************************************/
\r
10848 enum circumcenterresult findcircumcenter(torg, tdest, tapex, circumcenter,
\r
10853 point circumcenter;
\r
10857 REAL xdo, ydo, xao, yao, xad, yad;
\r
10858 REAL dodist, aodist, addist;
\r
10859 REAL denominator;
\r
10862 circumcentercount++;
\r
10864 /* Compute the circumcenter of the triangle. */
\r
10865 xdo = tdest[0] - torg[0];
\r
10866 ydo = tdest[1] - torg[1];
\r
10867 xao = tapex[0] - torg[0];
\r
10868 yao = tapex[1] - torg[1];
\r
10869 dodist = xdo * xdo + ydo * ydo;
\r
10870 aodist = xao * xao + yao * yao;
\r
10872 denominator = (REAL)(0.5 / (xdo * yao - xao * ydo));
\r
10874 /* Use the counterclockwise() routine to ensure a positive (and */
\r
10875 /* reasonably accurate) result, avoiding any possibility of */
\r
10876 /* division by zero. */
\r
10877 denominator = (REAL)(0.5 / counterclockwise(tdest, tapex, torg));
\r
10878 /* Don't count the above as an orientation test. */
\r
10879 counterclockcount--;
\r
10881 circumcenter[0] = torg[0] - (ydo * aodist - yao * dodist) * denominator;
\r
10882 circumcenter[1] = torg[1] + (xdo * aodist - xao * dodist) * denominator;
\r
10884 /* To interpolate point attributes for the new point inserted at */
\r
10885 /* the circumcenter, define a coordinate system with a xi-axis, */
\r
10886 /* directed from the triangle's origin to its destination, and */
\r
10887 /* an eta-axis, directed from its origin to its apex. */
\r
10888 /* Calculate the xi and eta coordinates of the circumcenter. */
\r
10889 dx = circumcenter[0] - torg[0];
\r
10890 dy = circumcenter[1] - torg[1];
\r
10891 *xi = (REAL)((dx * yao - xao * dy) * (2.0 * denominator));
\r
10892 *eta = (REAL)((xdo * dy - dx * ydo) * (2.0 * denominator));
\r
10894 xad = tapex[0] - tdest[0];
\r
10895 yad = tapex[1] - tdest[1];
\r
10896 addist = xad * xad + yad * yad;
\r
10897 if ((addist < dodist) && (addist < aodist)) {
\r
10898 return OPPOSITEORG;
\r
10899 } else if (dodist < aodist) {
\r
10900 return OPPOSITEAPEX;
\r
10902 return OPPOSITEDEST;
\r
10906 /*****************************************************************************/
\r
10908 /* splittriangle() Inserts a point at the circumcenter of a triangle. */
\r
10909 /* Deletes the newly inserted point if it encroaches upon */
\r
10912 /*****************************************************************************/
\r
10916 void splittriangle(badtri)
\r
10917 struct badface *badtri;
\r
10919 point borg, bdest, bapex;
\r
10922 enum insertsiteresult success;
\r
10923 enum circumcenterresult shortedge;
\r
10927 org(badtri->badfacetri, borg);
\r
10928 dest(badtri->badfacetri, bdest);
\r
10929 apex(badtri->badfacetri, bapex);
\r
10930 /* Make sure that this triangle is still the same triangle it was */
\r
10931 /* when it was tested and determined to be of bad quality. */
\r
10932 /* Subsequent transformations may have made it a different triangle. */
\r
10933 if ((borg == badtri->faceorg) && (bdest == badtri->facedest) &&
\r
10934 (bapex == badtri->faceapex)) {
\r
10935 if (verbose > 1) {
\r
10936 printf(" Splitting this triangle at its circumcenter:\n");
\r
10937 printf(" (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n", borg[0],
\r
10938 borg[1], bdest[0], bdest[1], bapex[0], bapex[1]);
\r
10941 /* Create a new point at the triangle's circumcenter. */
\r
10942 newpoint = (point) poolalloc(&points);
\r
10943 shortedge = findcircumcenter(borg, bdest, bapex, newpoint, &xi, &eta);
\r
10944 /* Check whether the new point lies on a triangle vertex. */
\r
10945 if (((newpoint[0] == borg[0]) && (newpoint[1] == borg[1]))
\r
10946 || ((newpoint[0] == bdest[0]) && (newpoint[1] == bdest[1]))
\r
10947 || ((newpoint[0] == bapex[0]) && (newpoint[1] == bapex[1]))) {
\r
10949 printf("Warning: New point (%.12g, %.12g) falls on existing vertex.\n"
\r
10950 , newpoint[0], newpoint[1]);
\r
10953 pointdealloc(newpoint);
\r
10955 for (i = 2; i < 2 + nextras; i++) {
\r
10956 /* Interpolate the point attributes at the circumcenter. */
\r
10957 newpoint[i] = borg[i] + xi * (bdest[i] - borg[i])
\r
10958 + eta * (bapex[i] - borg[i]);
\r
10960 /* The new point must be in the interior, and have a marker of zero. */
\r
10961 setpointmark(newpoint, 0);
\r
10962 /* Ensure that the handle `badtri->badfacetri' represents the shortest */
\r
10963 /* edge of the triangle. This ensures that the circumcenter must */
\r
10964 /* fall to the left of this edge, so point location will work. */
\r
10965 if (shortedge == OPPOSITEORG) {
\r
10966 lnextself(badtri->badfacetri);
\r
10967 } else if (shortedge == OPPOSITEDEST) {
\r
10968 lprevself(badtri->badfacetri);
\r
10970 /* Insert the circumcenter, searching from the edge of the triangle, */
\r
10971 /* and maintain the Delaunay property of the triangulation. */
\r
10972 success = insertsite(newpoint, &(badtri->badfacetri),
\r
10973 (struct edge *) NULL, 1, 1);
\r
10974 if (success == SUCCESSFULPOINT) {
\r
10975 if (steinerleft > 0) {
\r
10978 } else if (success == ENCROACHINGPOINT) {
\r
10979 /* If the newly inserted point encroaches upon a segment, delete it. */
\r
10980 deletesite(&(badtri->badfacetri));
\r
10981 } else if (success == VIOLATINGPOINT) {
\r
10982 /* Failed to insert the new point, but some segment was */
\r
10983 /* marked as being encroached. */
\r
10984 pointdealloc(newpoint);
\r
10985 } else { /* success == DUPLICATEPOINT */
\r
10986 /* Failed to insert the new point because a vertex is already there. */
\r
10989 "Warning: New point (%.12g, %.12g) falls on existing vertex.\n"
\r
10990 , newpoint[0], newpoint[1]);
\r
10993 pointdealloc(newpoint);
\r
10998 printf(" The new point is at the circumcenter of triangle\n");
\r
10999 printf(" (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
\r
11000 borg[0], borg[1], bdest[0], bdest[1], bapex[0], bapex[1]);
\r
11002 printf("This probably means that I am trying to refine triangles\n");
\r
11003 printf(" to a smaller size than can be accommodated by the finite\n");
\r
11004 printf(" precision of floating point arithmetic. (You can be\n");
\r
11005 printf(" sure of this if I fail to terminate.)\n");
\r
11006 precisionerror();
\r
11009 /* Return the bad triangle to the pool. */
\r
11010 pooldealloc(&badtriangles, (VOID *) badtri);
\r
11013 #endif /* not CDT_ONLY */
\r
11015 /*****************************************************************************/
\r
11017 /* enforcequality() Remove all the encroached edges and bad triangles */
\r
11018 /* from the triangulation. */
\r
11020 /*****************************************************************************/
\r
11024 void enforcequality()
\r
11029 printf("Adding Steiner points to enforce quality.\n");
\r
11031 /* Initialize the pool of encroached segments. */
\r
11032 poolinit(&badsegments, sizeof(struct edge), BADSEGMENTPERBLOCK, POINTER, 0);
\r
11034 printf(" Looking for encroached segments.\n");
\r
11036 /* Test all segments to see if they're encroached. */
\r
11038 if (verbose && (badsegments.items > 0)) {
\r
11039 printf(" Splitting encroached segments.\n");
\r
11041 /* Note that steinerleft == -1 if an unlimited number */
\r
11042 /* of Steiner points is allowed. */
\r
11043 while ((badsegments.items > 0) && (steinerleft != 0)) {
\r
11044 /* Fix the segments without noting newly encroached segments or */
\r
11045 /* bad triangles. The reason we don't want to note newly */
\r
11046 /* encroached segments is because some encroached segments are */
\r
11047 /* likely to be noted multiple times, and would then be blindly */
\r
11048 /* split multiple times. I should fix that some time. */
\r
11050 /* Now, find all the segments that became encroached while adding */
\r
11051 /* points to split encroached segments. */
\r
11054 /* At this point, if we haven't run out of Steiner points, the */
\r
11055 /* triangulation should be (conforming) Delaunay. */
\r
11057 /* Next, we worry about enforcing triangle quality. */
\r
11058 if ((minangle > 0.0) || vararea || fixedarea) {
\r
11059 /* Initialize the pool of bad triangles. */
\r
11060 poolinit(&badtriangles, sizeof(struct badface), BADTRIPERBLOCK, POINTER,
\r
11062 /* Initialize the queues of bad triangles. */
\r
11063 for (i = 0; i < 64; i++) {
\r
11064 queuefront[i] = (struct badface *) NULL;
\r
11065 queuetail[i] = &queuefront[i];
\r
11067 /* Test all triangles to see if they're bad. */
\r
11070 printf(" Splitting bad triangles.\n");
\r
11072 while ((badtriangles.items > 0) && (steinerleft != 0)) {
\r
11073 /* Fix one bad triangle by inserting a point at its circumcenter. */
\r
11074 splittriangle(dequeuebadtri());
\r
11075 /* Fix any encroached segments that may have resulted. Record */
\r
11076 /* any new bad triangles or encroached segments that result. */
\r
11077 if (badsegments.items > 0) {
\r
11082 /* At this point, if we haven't run out of Steiner points, the */
\r
11083 /* triangulation should be (conforming) Delaunay and have no */
\r
11084 /* low-quality triangles. */
\r
11086 /* Might we have run out of Steiner points too soon? */
\r
11087 if (!quiet && (badsegments.items > 0) && (steinerleft == 0)) {
\r
11088 printf("\nWarning: I ran out of Steiner points, but the mesh has\n");
\r
11089 if (badsegments.items == 1) {
\r
11090 printf(" an encroached segment, and therefore might not be truly\n");
\r
11092 printf(" %ld encroached segments, and therefore might not be truly\n",
\r
11093 badsegments.items);
\r
11095 printf(" Delaunay. If the Delaunay property is important to you,\n");
\r
11096 printf(" try increasing the number of Steiner points (controlled by\n");
\r
11097 printf(" the -S switch) slightly and try again.\n\n");
\r
11101 #endif /* not CDT_ONLY */
\r
11105 /********* Mesh quality maintenance ends here *********/
\r
11107 /*****************************************************************************/
\r
11109 /* highorder() Create extra nodes for quadratic subparametric elements. */
\r
11111 /*****************************************************************************/
\r
11115 struct triedge triangleloop, trisym;
\r
11116 struct edge checkmark;
\r
11118 point torg, tdest;
\r
11120 triangle ptr; /* Temporary variable used by sym(). */
\r
11121 shelle sptr; /* Temporary variable used by tspivot(). */
\r
11124 printf("Adding vertices for second-order triangles.\n");
\r
11126 /* The following line ensures that dead items in the pool of nodes */
\r
11127 /* cannot be allocated for the extra nodes associated with high */
\r
11128 /* order elements. This ensures that the primary nodes (at the */
\r
11129 /* corners of elements) will occur earlier in the output files, and */
\r
11130 /* have lower indices, than the extra nodes. */
\r
11131 points.deaditemstack = (VOID *) NULL;
\r
11133 traversalinit(&triangles);
\r
11134 triangleloop.tri = triangletraverse();
\r
11135 /* To loop over the set of edges, loop over all triangles, and look at */
\r
11136 /* the three edges of each triangle. If there isn't another triangle */
\r
11137 /* adjacent to the edge, operate on the edge. If there is another */
\r
11138 /* adjacent triangle, operate on the edge only if the current triangle */
\r
11139 /* has a smaller pointer than its neighbor. This way, each edge is */
\r
11140 /* considered only once. */
\r
11141 while (triangleloop.tri != (triangle *) NULL) {
\r
11142 for (triangleloop.orient = 0; triangleloop.orient < 3;
\r
11143 triangleloop.orient++) {
\r
11144 sym(triangleloop, trisym);
\r
11145 if ((triangleloop.tri < trisym.tri) || (trisym.tri == dummytri)) {
\r
11146 org(triangleloop, torg);
\r
11147 dest(triangleloop, tdest);
\r
11148 /* Create a new node in the middle of the edge. Interpolate */
\r
11149 /* its attributes. */
\r
11150 newpoint = (point) poolalloc(&points);
\r
11151 for (i = 0; i < 2 + nextras; i++) {
\r
11152 newpoint[i] = (REAL)(0.5 * (torg[i] + tdest[i]));
\r
11154 /* Set the new node's marker to zero or one, depending on */
\r
11155 /* whether it lies on a boundary. */
\r
11156 setpointmark(newpoint, trisym.tri == dummytri);
\r
11157 if (useshelles) {
\r
11158 tspivot(triangleloop, checkmark);
\r
11159 /* If this edge is a segment, transfer the marker to the new node. */
\r
11160 if (checkmark.sh != dummysh) {
\r
11161 setpointmark(newpoint, mark(checkmark));
\r
11164 if (verbose > 1) {
\r
11165 printf(" Creating (%.12g, %.12g).\n", newpoint[0], newpoint[1]);
\r
11167 /* Record the new node in the (one or two) adjacent elements. */
\r
11168 triangleloop.tri[highorderindex + triangleloop.orient] =
\r
11169 (triangle) newpoint;
\r
11170 if (trisym.tri != dummytri) {
\r
11171 trisym.tri[highorderindex + trisym.orient] = (triangle) newpoint;
\r
11175 triangleloop.tri = triangletraverse();
\r
11179 /********* File I/O routines begin here *********/
\r
11183 /*****************************************************************************/
\r
11185 /* readline() Read a nonempty line from a file. */
\r
11187 /* A line is considered "nonempty" if it contains something that looks like */
\r
11190 /*****************************************************************************/
\r
11192 #ifndef TRILIBRARY
\r
11194 char *readline(string, infile, infilename)
\r
11197 char *infilename;
\r
11201 /* Search for something that looks like a number. */
\r
11203 result = fgets(string, INPUTLINESIZE, infile);
\r
11204 if (result == (char *) NULL) {
\r
11205 printf(" Error: Unexpected end of file in %s.\n", infilename);
\r
11208 /* Skip anything that doesn't look like a number, a comment, */
\r
11209 /* or the end of a line. */
\r
11210 while ((*result != '\0') && (*result != '#')
\r
11211 && (*result != '.') && (*result != '+') && (*result != '-')
\r
11212 && ((*result < '0') || (*result > '9'))) {
\r
11215 /* If it's a comment or end of line, read another line and try again. */
\r
11216 } while ((*result == '#') || (*result == '\0'));
\r
11220 #endif /* not TRILIBRARY */
\r
11222 /*****************************************************************************/
\r
11224 /* findfield() Find the next field of a string. */
\r
11226 /* Jumps past the current field by searching for whitespace, then jumps */
\r
11227 /* past the whitespace to find the next field. */
\r
11229 /*****************************************************************************/
\r
11231 #ifndef TRILIBRARY
\r
11233 char *findfield(string)
\r
11239 /* Skip the current field. Stop upon reaching whitespace. */
\r
11240 while ((*result != '\0') && (*result != '#')
\r
11241 && (*result != ' ') && (*result != '\t')) {
\r
11244 /* Now skip the whitespace and anything else that doesn't look like a */
\r
11245 /* number, a comment, or the end of a line. */
\r
11246 while ((*result != '\0') && (*result != '#')
\r
11247 && (*result != '.') && (*result != '+') && (*result != '-')
\r
11248 && ((*result < '0') || (*result > '9'))) {
\r
11251 /* Check for a comment (prefixed with `#'). */
\r
11252 if (*result == '#') {
\r
11258 #endif /* not TRILIBRARY */
\r
11260 /*****************************************************************************/
\r
11262 /* readnodes() Read the points from a file, which may be a .node or .poly */
\r
11265 /*****************************************************************************/
\r
11267 #ifndef TRILIBRARY
\r
11269 void readnodes(nodefilename, polyfilename, polyfile)
\r
11270 char *nodefilename;
\r
11271 char *polyfilename;
\r
11276 char inputline[INPUTLINESIZE];
\r
11278 char *infilename;
\r
11282 int currentmarker;
\r
11286 /* Read the points from a .poly file. */
\r
11288 printf("Opening %s.\n", polyfilename);
\r
11290 *polyfile = fopen(polyfilename, "r");
\r
11291 if (*polyfile == (FILE *) NULL) {
\r
11292 printf(" Error: Cannot access file %s.\n", polyfilename);
\r
11295 /* Read number of points, number of dimensions, number of point */
\r
11296 /* attributes, and number of boundary markers. */
\r
11297 stringptr = readline(inputline, *polyfile, polyfilename);
\r
11298 inpoints = (int) strtol (stringptr, &stringptr, 0);
\r
11299 stringptr = findfield(stringptr);
\r
11300 if (*stringptr == '\0') {
\r
11303 mesh_dim = (int) strtol (stringptr, &stringptr, 0);
\r
11305 stringptr = findfield(stringptr);
\r
11306 if (*stringptr == '\0') {
\r
11309 nextras = (int) strtol (stringptr, &stringptr, 0);
\r
11311 stringptr = findfield(stringptr);
\r
11312 if (*stringptr == '\0') {
\r
11315 nodemarkers = (int) strtol (stringptr, &stringptr, 0);
\r
11317 if (inpoints > 0) {
\r
11318 infile = *polyfile;
\r
11319 infilename = polyfilename;
\r
11320 readnodefile = 0;
\r
11322 /* If the .poly file claims there are zero points, that means that */
\r
11323 /* the points should be read from a separate .node file. */
\r
11324 readnodefile = 1;
\r
11325 infilename = innodefilename;
\r
11328 readnodefile = 1;
\r
11329 infilename = innodefilename;
\r
11330 *polyfile = (FILE *) NULL;
\r
11333 if (readnodefile) {
\r
11334 /* Read the points from a .node file. */
\r
11336 printf("Opening %s.\n", innodefilename);
\r
11338 infile = fopen(innodefilename, "r");
\r
11339 if (infile == (FILE *) NULL) {
\r
11340 printf(" Error: Cannot access file %s.\n", innodefilename);
\r
11343 /* Read number of points, number of dimensions, number of point */
\r
11344 /* attributes, and number of boundary markers. */
\r
11345 stringptr = readline(inputline, infile, innodefilename);
\r
11346 inpoints = (int) strtol (stringptr, &stringptr, 0);
\r
11347 stringptr = findfield(stringptr);
\r
11348 if (*stringptr == '\0') {
\r
11351 mesh_dim = (int) strtol (stringptr, &stringptr, 0);
\r
11353 stringptr = findfield(stringptr);
\r
11354 if (*stringptr == '\0') {
\r
11357 nextras = (int) strtol (stringptr, &stringptr, 0);
\r
11359 stringptr = findfield(stringptr);
\r
11360 if (*stringptr == '\0') {
\r
11363 nodemarkers = (int) strtol (stringptr, &stringptr, 0);
\r
11367 if (inpoints < 3) {
\r
11368 printf("Error: Input must have at least three input points.\n");
\r
11371 if (mesh_dim != 2) {
\r
11372 printf("Error: Triangle only works with two-dimensional meshes.\n");
\r
11376 initializepointpool();
\r
11378 /* Read the points. */
\r
11379 for (i = 0; i < inpoints; i++) {
\r
11380 pointloop = (point) poolalloc(&points);
\r
11381 stringptr = readline(inputline, infile, infilename);
\r
11383 firstnode = (int) strtol (stringptr, &stringptr, 0);
\r
11384 if ((firstnode == 0) || (firstnode == 1)) {
\r
11385 firstnumber = firstnode;
\r
11388 stringptr = findfield(stringptr);
\r
11389 if (*stringptr == '\0') {
\r
11390 printf("Error: Point %d has no x coordinate.\n", firstnumber + i);
\r
11393 x = (REAL) strtod(stringptr, &stringptr);
\r
11394 stringptr = findfield(stringptr);
\r
11395 if (*stringptr == '\0') {
\r
11396 printf("Error: Point %d has no y coordinate.\n", firstnumber + i);
\r
11399 y = (REAL) strtod(stringptr, &stringptr);
\r
11400 pointloop[0] = x;
\r
11401 pointloop[1] = y;
\r
11402 /* Read the point attributes. */
\r
11403 for (j = 2; j < 2 + nextras; j++) {
\r
11404 stringptr = findfield(stringptr);
\r
11405 if (*stringptr == '\0') {
\r
11406 pointloop[j] = 0.0;
\r
11408 pointloop[j] = (REAL) strtod(stringptr, &stringptr);
\r
11411 if (nodemarkers) {
\r
11412 /* Read a point marker. */
\r
11413 stringptr = findfield(stringptr);
\r
11414 if (*stringptr == '\0') {
\r
11415 setpointmark(pointloop, 0);
\r
11417 currentmarker = (int) strtol (stringptr, &stringptr, 0);
\r
11418 setpointmark(pointloop, currentmarker);
\r
11421 /* If no markers are specified in the file, they default to zero. */
\r
11422 setpointmark(pointloop, 0);
\r
11424 /* Determine the smallest and largest x and y coordinates. */
\r
11429 xmin = (x < xmin) ? x : xmin;
\r
11430 xmax = (x > xmax) ? x : xmax;
\r
11431 ymin = (y < ymin) ? y : ymin;
\r
11432 ymax = (y > ymax) ? y : ymax;
\r
11435 if (readnodefile) {
\r
11439 /* Nonexistent x value used as a flag to mark circle events in sweepline */
\r
11440 /* Delaunay algorithm. */
\r
11441 xminextreme = 10 * xmin - 9 * xmax;
\r
11444 #endif /* not TRILIBRARY */
\r
11446 /*****************************************************************************/
\r
11448 /* transfernodes() Read the points from memory. */
\r
11450 /*****************************************************************************/
\r
11452 #ifdef TRILIBRARY
\r
11454 void transfernodes(pointlist, pointattriblist, pointmarkerlist, numberofpoints,
\r
11455 numberofpointattribs)
\r
11457 REAL *pointattriblist;
\r
11458 int *pointmarkerlist;
\r
11459 int numberofpoints;
\r
11460 int numberofpointattribs;
\r
11468 inpoints = numberofpoints;
\r
11470 nextras = numberofpointattribs;
\r
11471 readnodefile = 0;
\r
11472 if (inpoints < 3) {
\r
11473 printf("Error: Input must have at least three input points.\n");
\r
11477 initializepointpool();
\r
11479 /* Read the points. */
\r
11482 for (i = 0; i < inpoints; i++) {
\r
11483 pointloop = (point) poolalloc(&points);
\r
11484 /* Read the point coordinates. */
\r
11485 x = pointloop[0] = pointlist[coordindex++];
\r
11486 y = pointloop[1] = pointlist[coordindex++];
\r
11487 /* Read the point attributes. */
\r
11488 for (j = 0; j < numberofpointattribs; j++) {
\r
11489 pointloop[2 + j] = pointattriblist[attribindex++];
\r
11491 if (pointmarkerlist != (int *) NULL) {
\r
11492 /* Read a point marker. */
\r
11493 setpointmark(pointloop, pointmarkerlist[i]);
\r
11495 /* If no markers are specified, they default to zero. */
\r
11496 setpointmark(pointloop, 0);
\r
11498 x = pointloop[0];
\r
11499 y = pointloop[1];
\r
11500 /* Determine the smallest and largest x and y coordinates. */
\r
11505 xmin = (x < xmin) ? x : xmin;
\r
11506 xmax = (x > xmax) ? x : xmax;
\r
11507 ymin = (y < ymin) ? y : ymin;
\r
11508 ymax = (y > ymax) ? y : ymax;
\r
11512 /* Nonexistent x value used as a flag to mark circle events in sweepline */
\r
11513 /* Delaunay algorithm. */
\r
11514 xminextreme = 10 * xmin - 9 * xmax;
\r
11517 #endif /* TRILIBRARY */
\r
11519 /*****************************************************************************/
\r
11521 /* readholes() Read the holes, and possibly regional attributes and area */
\r
11522 /* constraints, from a .poly file. */
\r
11524 /*****************************************************************************/
\r
11526 #ifndef TRILIBRARY
\r
11528 void readholes(polyfile, polyfilename, hlist, holes, rlist, regions)
\r
11530 char *polyfilename;
\r
11537 REAL *regionlist;
\r
11538 char inputline[INPUTLINESIZE];
\r
11543 /* Read the holes. */
\r
11544 stringptr = readline(inputline, polyfile, polyfilename);
\r
11545 *holes = (int) strtol (stringptr, &stringptr, 0);
\r
11546 if (*holes > 0) {
\r
11547 holelist = (REAL *) malloc(2 * *holes * sizeof(REAL));
\r
11548 *hlist = holelist;
\r
11549 if (holelist == (REAL *) NULL) {
\r
11550 printf("Error: Out of memory.\n");
\r
11553 for (i = 0; i < 2 * *holes; i += 2) {
\r
11554 stringptr = readline(inputline, polyfile, polyfilename);
\r
11555 stringptr = findfield(stringptr);
\r
11556 if (*stringptr == '\0') {
\r
11557 printf("Error: Hole %d has no x coordinate.\n",
\r
11558 firstnumber + (i >> 1));
\r
11561 holelist[i] = (REAL) strtod(stringptr, &stringptr);
\r
11563 stringptr = findfield(stringptr);
\r
11564 if (*stringptr == '\0') {
\r
11565 printf("Error: Hole %d has no y coordinate.\n",
\r
11566 firstnumber + (i >> 1));
\r
11569 holelist[i + 1] = (REAL) strtod(stringptr, &stringptr);
\r
11573 *hlist = (REAL *) NULL;
\r
11577 if ((regionattrib || vararea) && !refine) {
\r
11578 /* Read the area constraints. */
\r
11579 stringptr = readline(inputline, polyfile, polyfilename);
\r
11580 *regions = (int) strtol (stringptr, &stringptr, 0);
\r
11581 if (*regions > 0) {
\r
11582 regionlist = (REAL *) malloc(4 * *regions * sizeof(REAL));
\r
11583 *rlist = regionlist;
\r
11584 if (regionlist == (REAL *) NULL) {
\r
11585 printf("Error: Out of memory.\n");
\r
11589 for (i = 0; i < *regions; i++) {
\r
11590 stringptr = readline(inputline, polyfile, polyfilename);
\r
11591 stringptr = findfield(stringptr);
\r
11592 if (*stringptr == '\0') {
\r
11593 printf("Error: Region %d has no x coordinate.\n",
\r
11594 firstnumber + i);
\r
11597 regionlist[index++] = (REAL) strtod(stringptr, &stringptr);
\r
11599 stringptr = findfield(stringptr);
\r
11600 if (*stringptr == '\0') {
\r
11601 printf("Error: Region %d has no y coordinate.\n",
\r
11602 firstnumber + i);
\r
11605 regionlist[index++] = (REAL) strtod(stringptr, &stringptr);
\r
11607 stringptr = findfield(stringptr);
\r
11608 if (*stringptr == '\0') {
\r
11610 "Error: Region %d has no region attribute or area constraint.\n",
\r
11611 firstnumber + i);
\r
11614 regionlist[index++] = (REAL) strtod(stringptr, &stringptr);
\r
11616 stringptr = findfield(stringptr);
\r
11617 if (*stringptr == '\0') {
\r
11618 regionlist[index] = regionlist[index - 1];
\r
11620 regionlist[index] = (REAL) strtod(stringptr, &stringptr);
\r
11626 /* Set `*regions' to zero to avoid an accidental free() later. */
\r
11628 *rlist = (REAL *) NULL;
\r
11630 #endif /* not CDT_ONLY */
\r
11632 fclose(polyfile);
\r
11635 #endif /* not TRILIBRARY */
\r
11637 /*****************************************************************************/
\r
11639 /* finishfile() Write the command line to the output file so the user */
\r
11640 /* can remember how the file was generated. Close the file. */
\r
11642 /*****************************************************************************/
\r
11644 #ifndef TRILIBRARY
\r
11646 void finishfile(outfile, argc, argv)
\r
11653 fprintf(outfile, "# Generated by");
\r
11654 for (i = 0; i < argc; i++) {
\r
11655 fprintf(outfile, " ");
\r
11656 fputs(argv[i], outfile);
\r
11658 fprintf(outfile, "\n");
\r
11662 #endif /* not TRILIBRARY */
\r
11664 /*****************************************************************************/
\r
11666 /* writenodes() Number the points and write them to a .node file. */
\r
11668 /* To save memory, the point numbers are written over the shell markers */
\r
11669 /* after the points are written to a file. */
\r
11671 /*****************************************************************************/
\r
11673 #ifdef TRILIBRARY
\r
11675 void writenodes(pointlist, pointattriblist, pointmarkerlist)
\r
11676 REAL **pointlist;
\r
11677 REAL **pointattriblist;
\r
11678 int **pointmarkerlist;
\r
11680 #else /* not TRILIBRARY */
\r
11682 void writenodes(nodefilename, argc, argv)
\r
11683 char *nodefilename;
\r
11687 #endif /* not TRILIBRARY */
\r
11690 #ifdef TRILIBRARY
\r
11696 #else /* not TRILIBRARY */
\r
11698 #endif /* not TRILIBRARY */
\r
11703 #ifdef TRILIBRARY
\r
11705 printf("Writing points.\n");
\r
11707 /* Allocate memory for output points if necessary. */
\r
11708 if (*pointlist == (REAL *) NULL) {
\r
11709 *pointlist = (REAL *) malloc(points.items * 2 * sizeof(REAL));
\r
11710 if (*pointlist == (REAL *) NULL) {
\r
11711 printf("Error: Out of memory.\n");
\r
11715 /* Allocate memory for output point attributes if necessary. */
\r
11716 if ((nextras > 0) && (*pointattriblist == (REAL *) NULL)) {
\r
11717 *pointattriblist = (REAL *) malloc(points.items * nextras * sizeof(REAL));
\r
11718 if (*pointattriblist == (REAL *) NULL) {
\r
11719 printf("Error: Out of memory.\n");
\r
11723 /* Allocate memory for output point markers if necessary. */
\r
11724 if (!nobound && (*pointmarkerlist == (int *) NULL)) {
\r
11725 *pointmarkerlist = (int *) malloc(points.items * sizeof(int));
\r
11726 if (*pointmarkerlist == (int *) NULL) {
\r
11727 printf("Error: Out of memory.\n");
\r
11731 plist = *pointlist;
\r
11732 palist = *pointattriblist;
\r
11733 pmlist = *pointmarkerlist;
\r
11736 #else /* not TRILIBRARY */
\r
11738 printf("Writing %s.\n", nodefilename);
\r
11740 outfile = fopen(nodefilename, "w");
\r
11741 if (outfile == (FILE *) NULL) {
\r
11742 printf(" Error: Cannot create file %s.\n", nodefilename);
\r
11745 /* Number of points, number of dimensions, number of point attributes, */
\r
11746 /* and number of boundary markers (zero or one). */
\r
11747 fprintf(outfile, "%ld %d %d %d\n", points.items, mesh_dim, nextras,
\r
11749 #endif /* not TRILIBRARY */
\r
11751 traversalinit(&points);
\r
11752 pointloop = pointtraverse();
\r
11753 pointnumber = firstnumber;
\r
11754 while (pointloop != (point) NULL) {
\r
11755 #ifdef TRILIBRARY
\r
11756 /* X and y coordinates. */
\r
11757 plist[coordindex++] = pointloop[0];
\r
11758 plist[coordindex++] = pointloop[1];
\r
11759 /* Point attributes. */
\r
11760 for (i = 0; i < nextras; i++) {
\r
11761 palist[attribindex++] = pointloop[2 + i];
\r
11764 /* Copy the boundary marker. */
\r
11765 pmlist[pointnumber - firstnumber] = pointmark(pointloop);
\r
11767 #else /* not TRILIBRARY */
\r
11768 /* Point number, x and y coordinates. */
\r
11769 fprintf(outfile, "%4d %.17g %.17g", pointnumber, pointloop[0],
\r
11771 for (i = 0; i < nextras; i++) {
\r
11772 /* Write an attribute. */
\r
11773 fprintf(outfile, " %.17g", pointloop[i + 2]);
\r
11776 fprintf(outfile, "\n");
\r
11778 /* Write the boundary marker. */
\r
11779 fprintf(outfile, " %d\n", pointmark(pointloop));
\r
11781 #endif /* not TRILIBRARY */
\r
11783 setpointmark(pointloop, pointnumber);
\r
11784 pointloop = pointtraverse();
\r
11788 #ifndef TRILIBRARY
\r
11789 finishfile(outfile, argc, argv);
\r
11790 #endif /* not TRILIBRARY */
\r
11793 /*****************************************************************************/
\r
11795 /* numbernodes() Number the points. */
\r
11797 /* Each point is assigned a marker equal to its number. */
\r
11799 /* Used when writenodes() is not called because no .node file is written. */
\r
11801 /*****************************************************************************/
\r
11803 void numbernodes()
\r
11808 traversalinit(&points);
\r
11809 pointloop = pointtraverse();
\r
11810 pointnumber = firstnumber;
\r
11811 while (pointloop != (point) NULL) {
\r
11812 setpointmark(pointloop, pointnumber);
\r
11813 pointloop = pointtraverse();
\r
11818 /*****************************************************************************/
\r
11820 /* writeelements() Write the triangles to an .ele file. */
\r
11822 /*****************************************************************************/
\r
11824 #ifdef TRILIBRARY
\r
11826 void writeelements(trianglelist, triangleattriblist)
\r
11827 int **trianglelist;
\r
11828 REAL **triangleattriblist;
\r
11830 #else /* not TRILIBRARY */
\r
11832 void writeelements(elefilename, argc, argv)
\r
11833 char *elefilename;
\r
11837 #endif /* not TRILIBRARY */
\r
11840 #ifdef TRILIBRARY
\r
11845 #else /* not TRILIBRARY */
\r
11847 #endif /* not TRILIBRARY */
\r
11848 struct triedge triangleloop;
\r
11849 point p1, p2, p3;
\r
11850 point mid1, mid2, mid3;
\r
11851 int elementnumber;
\r
11854 #ifdef TRILIBRARY
\r
11856 printf("Writing triangles.\n");
\r
11858 /* Allocate memory for output triangles if necessary. */
\r
11859 if (*trianglelist == (int *) NULL) {
\r
11860 *trianglelist = (int *) malloc(triangles.items *
\r
11861 ((order + 1) * (order + 2) / 2) * sizeof(int));
\r
11862 if (*trianglelist == (int *) NULL) {
\r
11863 printf("Error: Out of memory.\n");
\r
11867 /* Allocate memory for output triangle attributes if necessary. */
\r
11868 if ((eextras > 0) && (*triangleattriblist == (REAL *) NULL)) {
\r
11869 *triangleattriblist = (REAL *) malloc(triangles.items * eextras *
\r
11871 if (*triangleattriblist == (REAL *) NULL) {
\r
11872 printf("Error: Out of memory.\n");
\r
11876 tlist = *trianglelist;
\r
11877 talist = *triangleattriblist;
\r
11880 #else /* not TRILIBRARY */
\r
11882 printf("Writing %s.\n", elefilename);
\r
11884 outfile = fopen(elefilename, "w");
\r
11885 if (outfile == (FILE *) NULL) {
\r
11886 printf(" Error: Cannot create file %s.\n", elefilename);
\r
11889 /* Number of triangles, points per triangle, attributes per triangle. */
\r
11890 fprintf(outfile, "%ld %d %d\n", triangles.items,
\r
11891 (order + 1) * (order + 2) / 2, eextras);
\r
11892 #endif /* not TRILIBRARY */
\r
11894 traversalinit(&triangles);
\r
11895 triangleloop.tri = triangletraverse();
\r
11896 triangleloop.orient = 0;
\r
11897 elementnumber = firstnumber;
\r
11898 while (triangleloop.tri != (triangle *) NULL) {
\r
11899 org(triangleloop, p1);
\r
11900 dest(triangleloop, p2);
\r
11901 apex(triangleloop, p3);
\r
11902 if (order == 1) {
\r
11903 #ifdef TRILIBRARY
\r
11904 tlist[pointindex++] = pointmark(p1);
\r
11905 tlist[pointindex++] = pointmark(p2);
\r
11906 tlist[pointindex++] = pointmark(p3);
\r
11907 #else /* not TRILIBRARY */
\r
11908 /* Triangle number, indices for three points. */
\r
11909 fprintf(outfile, "%4d %4d %4d %4d", elementnumber,
\r
11910 pointmark(p1), pointmark(p2), pointmark(p3));
\r
11911 #endif /* not TRILIBRARY */
\r
11913 mid1 = (point) triangleloop.tri[highorderindex + 1];
\r
11914 mid2 = (point) triangleloop.tri[highorderindex + 2];
\r
11915 mid3 = (point) triangleloop.tri[highorderindex];
\r
11916 #ifdef TRILIBRARY
\r
11917 tlist[pointindex++] = pointmark(p1);
\r
11918 tlist[pointindex++] = pointmark(p2);
\r
11919 tlist[pointindex++] = pointmark(p3);
\r
11920 tlist[pointindex++] = pointmark(mid1);
\r
11921 tlist[pointindex++] = pointmark(mid2);
\r
11922 tlist[pointindex++] = pointmark(mid3);
\r
11923 #else /* not TRILIBRARY */
\r
11924 /* Triangle number, indices for six points. */
\r
11925 fprintf(outfile, "%4d %4d %4d %4d %4d %4d %4d", elementnumber,
\r
11926 pointmark(p1), pointmark(p2), pointmark(p3), pointmark(mid1),
\r
11927 pointmark(mid2), pointmark(mid3));
\r
11928 #endif /* not TRILIBRARY */
\r
11931 #ifdef TRILIBRARY
\r
11932 for (i = 0; i < eextras; i++) {
\r
11933 talist[attribindex++] = elemattribute(triangleloop, i);
\r
11935 #else /* not TRILIBRARY */
\r
11936 for (i = 0; i < eextras; i++) {
\r
11937 fprintf(outfile, " %.17g", elemattribute(triangleloop, i));
\r
11939 fprintf(outfile, "\n");
\r
11940 #endif /* not TRILIBRARY */
\r
11942 triangleloop.tri = triangletraverse();
\r
11946 #ifndef TRILIBRARY
\r
11947 finishfile(outfile, argc, argv);
\r
11948 #endif /* not TRILIBRARY */
\r
11951 /*****************************************************************************/
\r
11953 /* writepoly() Write the segments and holes to a .poly file. */
\r
11955 /*****************************************************************************/
\r
11957 #ifdef TRILIBRARY
\r
11959 void writepoly(segmentlist, segmentmarkerlist)
\r
11960 int **segmentlist;
\r
11961 int **segmentmarkerlist;
\r
11963 #else /* not TRILIBRARY */
\r
11965 void writepoly(polyfilename, holelist, holes, regionlist, regions, argc, argv)
\r
11966 char *polyfilename;
\r
11969 REAL *regionlist;
\r
11974 #endif /* not TRILIBRARY */
\r
11977 #ifdef TRILIBRARY
\r
11981 #else /* not TRILIBRARY */
\r
11984 #endif /* not TRILIBRARY */
\r
11985 struct edge shelleloop;
\r
11986 point endpoint1, endpoint2;
\r
11987 int shellenumber;
\r
11989 #ifdef TRILIBRARY
\r
11991 printf("Writing segments.\n");
\r
11993 /* Allocate memory for output segments if necessary. */
\r
11994 if (*segmentlist == (int *) NULL) {
\r
11995 *segmentlist = (int *) malloc(shelles.items * 2 * sizeof(int));
\r
11996 if (*segmentlist == (int *) NULL) {
\r
11997 printf("Error: Out of memory.\n");
\r
12001 /* Allocate memory for output segment markers if necessary. */
\r
12002 if (!nobound && (*segmentmarkerlist == (int *) NULL)) {
\r
12003 *segmentmarkerlist = (int *) malloc(shelles.items * sizeof(int));
\r
12004 if (*segmentmarkerlist == (int *) NULL) {
\r
12005 printf("Error: Out of memory.\n");
\r
12009 slist = *segmentlist;
\r
12010 smlist = *segmentmarkerlist;
\r
12012 #else /* not TRILIBRARY */
\r
12014 printf("Writing %s.\n", polyfilename);
\r
12016 outfile = fopen(polyfilename, "w");
\r
12017 if (outfile == (FILE *) NULL) {
\r
12018 printf(" Error: Cannot create file %s.\n", polyfilename);
\r
12021 /* The zero indicates that the points are in a separate .node file. */
\r
12022 /* Followed by number of dimensions, number of point attributes, */
\r
12023 /* and number of boundary markers (zero or one). */
\r
12024 fprintf(outfile, "%d %d %d %d\n", 0, mesh_dim, nextras, 1 - nobound);
\r
12025 /* Number of segments, number of boundary markers (zero or one). */
\r
12026 fprintf(outfile, "%ld %d\n", shelles.items, 1 - nobound);
\r
12027 #endif /* not TRILIBRARY */
\r
12029 traversalinit(&shelles);
\r
12030 shelleloop.sh = shelletraverse();
\r
12031 shelleloop.shorient = 0;
\r
12032 shellenumber = firstnumber;
\r
12033 while (shelleloop.sh != (shelle *) NULL) {
\r
12034 sorg(shelleloop, endpoint1);
\r
12035 sdest(shelleloop, endpoint2);
\r
12036 #ifdef TRILIBRARY
\r
12037 /* Copy indices of the segment's two endpoints. */
\r
12038 slist[index++] = pointmark(endpoint1);
\r
12039 slist[index++] = pointmark(endpoint2);
\r
12041 /* Copy the boundary marker. */
\r
12042 smlist[shellenumber - firstnumber] = mark(shelleloop);
\r
12044 #else /* not TRILIBRARY */
\r
12045 /* Segment number, indices of its two endpoints, and possibly a marker. */
\r
12047 fprintf(outfile, "%4d %4d %4d\n", shellenumber,
\r
12048 pointmark(endpoint1), pointmark(endpoint2));
\r
12050 fprintf(outfile, "%4d %4d %4d %4d\n", shellenumber,
\r
12051 pointmark(endpoint1), pointmark(endpoint2), mark(shelleloop));
\r
12053 #endif /* not TRILIBRARY */
\r
12055 shelleloop.sh = shelletraverse();
\r
12059 #ifndef TRILIBRARY
\r
12061 fprintf(outfile, "%d\n", holes);
\r
12063 for (i = 0; i < holes; i++) {
\r
12064 /* Hole number, x and y coordinates. */
\r
12065 fprintf(outfile, "%4d %.17g %.17g\n", firstnumber + i,
\r
12066 holelist[2 * i], holelist[2 * i + 1]);
\r
12069 if (regions > 0) {
\r
12070 fprintf(outfile, "%d\n", regions);
\r
12071 for (i = 0; i < regions; i++) {
\r
12072 /* Region number, x and y coordinates, attribute, maximum area. */
\r
12073 fprintf(outfile, "%4d %.17g %.17g %.17g %.17g\n", firstnumber + i,
\r
12074 regionlist[4 * i], regionlist[4 * i + 1],
\r
12075 regionlist[4 * i + 2], regionlist[4 * i + 3]);
\r
12078 #endif /* not CDT_ONLY */
\r
12080 finishfile(outfile, argc, argv);
\r
12081 #endif /* not TRILIBRARY */
\r
12084 /*****************************************************************************/
\r
12086 /* writeedges() Write the edges to a .edge file. */
\r
12088 /*****************************************************************************/
\r
12090 #ifdef TRILIBRARY
\r
12092 void writeedges(edgelist, edgemarkerlist)
\r
12094 int **edgemarkerlist;
\r
12096 #else /* not TRILIBRARY */
\r
12098 void writeedges(edgefilename, argc, argv)
\r
12099 char *edgefilename;
\r
12103 #endif /* not TRILIBRARY */
\r
12106 #ifdef TRILIBRARY
\r
12110 #else /* not TRILIBRARY */
\r
12112 #endif /* not TRILIBRARY */
\r
12113 struct triedge triangleloop, trisym;
\r
12114 struct edge checkmark;
\r
12117 triangle ptr; /* Temporary variable used by sym(). */
\r
12118 shelle sptr; /* Temporary variable used by tspivot(). */
\r
12120 #ifdef TRILIBRARY
\r
12122 printf("Writing edges.\n");
\r
12124 /* Allocate memory for edges if necessary. */
\r
12125 if (*edgelist == (int *) NULL) {
\r
12126 *edgelist = (int *) malloc(edges * 2 * sizeof(int));
\r
12127 if (*edgelist == (int *) NULL) {
\r
12128 printf("Error: Out of memory.\n");
\r
12132 /* Allocate memory for edge markers if necessary. */
\r
12133 if (!nobound && (*edgemarkerlist == (int *) NULL)) {
\r
12134 *edgemarkerlist = (int *) malloc(edges * sizeof(int));
\r
12135 if (*edgemarkerlist == (int *) NULL) {
\r
12136 printf("Error: Out of memory.\n");
\r
12140 elist = *edgelist;
\r
12141 emlist = *edgemarkerlist;
\r
12143 #else /* not TRILIBRARY */
\r
12145 printf("Writing %s.\n", edgefilename);
\r
12147 outfile = fopen(edgefilename, "w");
\r
12148 if (outfile == (FILE *) NULL) {
\r
12149 printf(" Error: Cannot create file %s.\n", edgefilename);
\r
12152 /* Number of edges, number of boundary markers (zero or one). */
\r
12153 fprintf(outfile, "%ld %d\n", edges, 1 - nobound);
\r
12154 #endif /* not TRILIBRARY */
\r
12156 traversalinit(&triangles);
\r
12157 triangleloop.tri = triangletraverse();
\r
12158 edgenumber = firstnumber;
\r
12159 /* To loop over the set of edges, loop over all triangles, and look at */
\r
12160 /* the three edges of each triangle. If there isn't another triangle */
\r
12161 /* adjacent to the edge, operate on the edge. If there is another */
\r
12162 /* adjacent triangle, operate on the edge only if the current triangle */
\r
12163 /* has a smaller pointer than its neighbor. This way, each edge is */
\r
12164 /* considered only once. */
\r
12165 while (triangleloop.tri != (triangle *) NULL) {
\r
12166 for (triangleloop.orient = 0; triangleloop.orient < 3;
\r
12167 triangleloop.orient++) {
\r
12168 sym(triangleloop, trisym);
\r
12169 if ((triangleloop.tri < trisym.tri) || (trisym.tri == dummytri)) {
\r
12170 org(triangleloop, p1);
\r
12171 dest(triangleloop, p2);
\r
12172 #ifdef TRILIBRARY
\r
12173 elist[index++] = pointmark(p1);
\r
12174 elist[index++] = pointmark(p2);
\r
12175 #endif /* TRILIBRARY */
\r
12177 #ifndef TRILIBRARY
\r
12178 /* Edge number, indices of two endpoints. */
\r
12179 fprintf(outfile, "%4d %d %d\n", edgenumber,
\r
12180 pointmark(p1), pointmark(p2));
\r
12181 #endif /* not TRILIBRARY */
\r
12183 /* Edge number, indices of two endpoints, and a boundary marker. */
\r
12184 /* If there's no shell edge, the boundary marker is zero. */
\r
12185 if (useshelles) {
\r
12186 tspivot(triangleloop, checkmark);
\r
12187 if (checkmark.sh == dummysh) {
\r
12188 #ifdef TRILIBRARY
\r
12189 emlist[edgenumber - firstnumber] = 0;
\r
12190 #else /* not TRILIBRARY */
\r
12191 fprintf(outfile, "%4d %d %d %d\n", edgenumber,
\r
12192 pointmark(p1), pointmark(p2), 0);
\r
12193 #endif /* not TRILIBRARY */
\r
12195 #ifdef TRILIBRARY
\r
12196 emlist[edgenumber - firstnumber] = mark(checkmark);
\r
12197 #else /* not TRILIBRARY */
\r
12198 fprintf(outfile, "%4d %d %d %d\n", edgenumber,
\r
12199 pointmark(p1), pointmark(p2), mark(checkmark));
\r
12200 #endif /* not TRILIBRARY */
\r
12203 #ifdef TRILIBRARY
\r
12204 emlist[edgenumber - firstnumber] = trisym.tri == dummytri;
\r
12205 #else /* not TRILIBRARY */
\r
12206 fprintf(outfile, "%4d %d %d %d\n", edgenumber,
\r
12207 pointmark(p1), pointmark(p2), trisym.tri == dummytri);
\r
12208 #endif /* not TRILIBRARY */
\r
12214 triangleloop.tri = triangletraverse();
\r
12217 #ifndef TRILIBRARY
\r
12218 finishfile(outfile, argc, argv);
\r
12219 #endif /* not TRILIBRARY */
\r
12222 /*****************************************************************************/
\r
12224 /* writevoronoi() Write the Voronoi diagram to a .v.node and .v.edge */
\r
12227 /* The Voronoi diagram is the geometric dual of the Delaunay triangulation. */
\r
12228 /* Hence, the Voronoi vertices are listed by traversing the Delaunay */
\r
12229 /* triangles, and the Voronoi edges are listed by traversing the Delaunay */
\r
12232 /* WARNING: In order to assign numbers to the Voronoi vertices, this */
\r
12233 /* procedure messes up the shell edges or the extra nodes of every */
\r
12234 /* element. Hence, you should call this procedure last. */
\r
12236 /*****************************************************************************/
\r
12238 #ifdef TRILIBRARY
\r
12240 void writevoronoi(vpointlist, vpointattriblist, vpointmarkerlist, vedgelist,
\r
12241 vedgemarkerlist, vnormlist)
\r
12242 REAL **vpointlist;
\r
12243 REAL **vpointattriblist;
\r
12244 int **vpointmarkerlist;
\r
12246 int **vedgemarkerlist;
\r
12247 REAL **vnormlist;
\r
12249 #else /* not TRILIBRARY */
\r
12251 void writevoronoi(vnodefilename, vedgefilename, argc, argv)
\r
12252 char *vnodefilename;
\r
12253 char *vedgefilename;
\r
12257 #endif /* not TRILIBRARY */
\r
12260 #ifdef TRILIBRARY
\r
12267 #else /* not TRILIBRARY */
\r
12269 #endif /* not TRILIBRARY */
\r
12270 struct triedge triangleloop, trisym;
\r
12271 point torg, tdest, tapex;
\r
12272 REAL circumcenter[2];
\r
12274 int vnodenumber, vedgenumber;
\r
12277 triangle ptr; /* Temporary variable used by sym(). */
\r
12279 #ifdef TRILIBRARY
\r
12281 printf("Writing Voronoi vertices.\n");
\r
12283 /* Allocate memory for Voronoi vertices if necessary. */
\r
12284 if (*vpointlist == (REAL *) NULL) {
\r
12285 *vpointlist = (REAL *) malloc(triangles.items * 2 * sizeof(REAL));
\r
12286 if (*vpointlist == (REAL *) NULL) {
\r
12287 printf("Error: Out of memory.\n");
\r
12291 /* Allocate memory for Voronoi vertex attributes if necessary. */
\r
12292 if (*vpointattriblist == (REAL *) NULL) {
\r
12293 *vpointattriblist = (REAL *) malloc(triangles.items * nextras *
\r
12295 if (*vpointattriblist == (REAL *) NULL) {
\r
12296 printf("Error: Out of memory.\n");
\r
12300 *vpointmarkerlist = (int *) NULL;
\r
12301 plist = *vpointlist;
\r
12302 palist = *vpointattriblist;
\r
12305 #else /* not TRILIBRARY */
\r
12307 printf("Writing %s.\n", vnodefilename);
\r
12309 outfile = fopen(vnodefilename, "w");
\r
12310 if (outfile == (FILE *) NULL) {
\r
12311 printf(" Error: Cannot create file %s.\n", vnodefilename);
\r
12314 /* Number of triangles, two dimensions, number of point attributes, */
\r
12315 /* zero markers. */
\r
12316 fprintf(outfile, "%ld %d %d %d\n", triangles.items, 2, nextras, 0);
\r
12317 #endif /* not TRILIBRARY */
\r
12319 traversalinit(&triangles);
\r
12320 triangleloop.tri = triangletraverse();
\r
12321 triangleloop.orient = 0;
\r
12322 vnodenumber = firstnumber;
\r
12323 while (triangleloop.tri != (triangle *) NULL) {
\r
12324 org(triangleloop, torg);
\r
12325 dest(triangleloop, tdest);
\r
12326 apex(triangleloop, tapex);
\r
12327 findcircumcenter(torg, tdest, tapex, circumcenter, &xi, &eta);
\r
12328 #ifdef TRILIBRARY
\r
12329 /* X and y coordinates. */
\r
12330 plist[coordindex++] = circumcenter[0];
\r
12331 plist[coordindex++] = circumcenter[1];
\r
12332 for (i = 2; i < 2 + nextras; i++) {
\r
12333 /* Interpolate the point attributes at the circumcenter. */
\r
12334 palist[attribindex++] = torg[i] + xi * (tdest[i] - torg[i])
\r
12335 + eta * (tapex[i] - torg[i]);
\r
12337 #else /* not TRILIBRARY */
\r
12338 /* Voronoi vertex number, x and y coordinates. */
\r
12339 fprintf(outfile, "%4d %.17g %.17g", vnodenumber, circumcenter[0],
\r
12340 circumcenter[1]);
\r
12341 for (i = 2; i < 2 + nextras; i++) {
\r
12342 /* Interpolate the point attributes at the circumcenter. */
\r
12343 fprintf(outfile, " %.17g", torg[i] + xi * (tdest[i] - torg[i])
\r
12344 + eta * (tapex[i] - torg[i]));
\r
12346 fprintf(outfile, "\n");
\r
12347 #endif /* not TRILIBRARY */
\r
12349 * (int *) (triangleloop.tri + 6) = vnodenumber;
\r
12350 triangleloop.tri = triangletraverse();
\r
12354 #ifndef TRILIBRARY
\r
12355 finishfile(outfile, argc, argv);
\r
12356 #endif /* not TRILIBRARY */
\r
12358 #ifdef TRILIBRARY
\r
12360 printf("Writing Voronoi edges.\n");
\r
12362 /* Allocate memory for output Voronoi edges if necessary. */
\r
12363 if (*vedgelist == (int *) NULL) {
\r
12364 *vedgelist = (int *) malloc(edges * 2 * sizeof(int));
\r
12365 if (*vedgelist == (int *) NULL) {
\r
12366 printf("Error: Out of memory.\n");
\r
12370 *vedgemarkerlist = (int *) NULL;
\r
12371 /* Allocate memory for output Voronoi norms if necessary. */
\r
12372 if (*vnormlist == (REAL *) NULL) {
\r
12373 *vnormlist = (REAL *) malloc(edges * 2 * sizeof(REAL));
\r
12374 if (*vnormlist == (REAL *) NULL) {
\r
12375 printf("Error: Out of memory.\n");
\r
12379 elist = *vedgelist;
\r
12380 normlist = *vnormlist;
\r
12382 #else /* not TRILIBRARY */
\r
12384 printf("Writing %s.\n", vedgefilename);
\r
12386 outfile = fopen(vedgefilename, "w");
\r
12387 if (outfile == (FILE *) NULL) {
\r
12388 printf(" Error: Cannot create file %s.\n", vedgefilename);
\r
12391 /* Number of edges, zero boundary markers. */
\r
12392 fprintf(outfile, "%ld %d\n", edges, 0);
\r
12393 #endif /* not TRILIBRARY */
\r
12395 traversalinit(&triangles);
\r
12396 triangleloop.tri = triangletraverse();
\r
12397 vedgenumber = firstnumber;
\r
12398 /* To loop over the set of edges, loop over all triangles, and look at */
\r
12399 /* the three edges of each triangle. If there isn't another triangle */
\r
12400 /* adjacent to the edge, operate on the edge. If there is another */
\r
12401 /* adjacent triangle, operate on the edge only if the current triangle */
\r
12402 /* has a smaller pointer than its neighbor. This way, each edge is */
\r
12403 /* considered only once. */
\r
12404 while (triangleloop.tri != (triangle *) NULL) {
\r
12405 for (triangleloop.orient = 0; triangleloop.orient < 3;
\r
12406 triangleloop.orient++) {
\r
12407 sym(triangleloop, trisym);
\r
12408 if ((triangleloop.tri < trisym.tri) || (trisym.tri == dummytri)) {
\r
12409 /* Find the number of this triangle (and Voronoi vertex). */
\r
12410 p1 = * (int *) (triangleloop.tri + 6);
\r
12411 if (trisym.tri == dummytri) {
\r
12412 org(triangleloop, torg);
\r
12413 dest(triangleloop, tdest);
\r
12414 #ifdef TRILIBRARY
\r
12415 /* Copy an infinite ray. Index of one endpoint, and -1. */
\r
12416 elist[coordindex] = p1;
\r
12417 normlist[coordindex++] = tdest[1] - torg[1];
\r
12418 elist[coordindex] = -1;
\r
12419 normlist[coordindex++] = torg[0] - tdest[0];
\r
12420 #else /* not TRILIBRARY */
\r
12421 /* Write an infinite ray. Edge number, index of one endpoint, -1, */
\r
12422 /* and x and y coordinates of a vector representing the */
\r
12423 /* direction of the ray. */
\r
12424 fprintf(outfile, "%4d %d %d %.17g %.17g\n", vedgenumber,
\r
12425 p1, -1, tdest[1] - torg[1], torg[0] - tdest[0]);
\r
12426 #endif /* not TRILIBRARY */
\r
12428 /* Find the number of the adjacent triangle (and Voronoi vertex). */
\r
12429 p2 = * (int *) (trisym.tri + 6);
\r
12430 /* Finite edge. Write indices of two endpoints. */
\r
12431 #ifdef TRILIBRARY
\r
12432 elist[coordindex] = p1;
\r
12433 normlist[coordindex++] = 0.0;
\r
12434 elist[coordindex] = p2;
\r
12435 normlist[coordindex++] = 0.0;
\r
12436 #else /* not TRILIBRARY */
\r
12437 fprintf(outfile, "%4d %d %d\n", vedgenumber, p1, p2);
\r
12438 #endif /* not TRILIBRARY */
\r
12443 triangleloop.tri = triangletraverse();
\r
12446 #ifndef TRILIBRARY
\r
12447 finishfile(outfile, argc, argv);
\r
12448 #endif /* not TRILIBRARY */
\r
12451 #ifdef TRILIBRARY
\r
12453 void writeneighbors(neighborlist)
\r
12454 int **neighborlist;
\r
12456 #else /* not TRILIBRARY */
\r
12458 void writeneighbors(neighborfilename, argc, argv)
\r
12459 char *neighborfilename;
\r
12463 #endif /* not TRILIBRARY */
\r
12466 #ifdef TRILIBRARY
\r
12469 #else /* not TRILIBRARY */
\r
12471 #endif /* not TRILIBRARY */
\r
12472 struct triedge triangleloop, trisym;
\r
12473 int elementnumber;
\r
12474 int neighbor1, neighbor2, neighbor3;
\r
12475 triangle ptr; /* Temporary variable used by sym(). */
\r
12477 #ifdef TRILIBRARY
\r
12479 printf("Writing neighbors.\n");
\r
12481 /* Allocate memory for neighbors if necessary. */
\r
12482 if (*neighborlist == (int *) NULL) {
\r
12483 *neighborlist = (int *) malloc(triangles.items * 3 * sizeof(int));
\r
12484 if (*neighborlist == (int *) NULL) {
\r
12485 printf("Error: Out of memory.\n");
\r
12489 nlist = *neighborlist;
\r
12491 #else /* not TRILIBRARY */
\r
12493 printf("Writing %s.\n", neighborfilename);
\r
12495 outfile = fopen(neighborfilename, "w");
\r
12496 if (outfile == (FILE *) NULL) {
\r
12497 printf(" Error: Cannot create file %s.\n", neighborfilename);
\r
12500 /* Number of triangles, three edges per triangle. */
\r
12501 fprintf(outfile, "%ld %d\n", triangles.items, 3);
\r
12502 #endif /* not TRILIBRARY */
\r
12504 traversalinit(&triangles);
\r
12505 triangleloop.tri = triangletraverse();
\r
12506 triangleloop.orient = 0;
\r
12507 elementnumber = firstnumber;
\r
12508 while (triangleloop.tri != (triangle *) NULL) {
\r
12509 * (int *) (triangleloop.tri + 6) = elementnumber;
\r
12510 triangleloop.tri = triangletraverse();
\r
12513 * (int *) (dummytri + 6) = -1;
\r
12515 traversalinit(&triangles);
\r
12516 triangleloop.tri = triangletraverse();
\r
12517 elementnumber = firstnumber;
\r
12518 while (triangleloop.tri != (triangle *) NULL) {
\r
12519 triangleloop.orient = 1;
\r
12520 sym(triangleloop, trisym);
\r
12521 neighbor1 = * (int *) (trisym.tri + 6);
\r
12522 triangleloop.orient = 2;
\r
12523 sym(triangleloop, trisym);
\r
12524 neighbor2 = * (int *) (trisym.tri + 6);
\r
12525 triangleloop.orient = 0;
\r
12526 sym(triangleloop, trisym);
\r
12527 neighbor3 = * (int *) (trisym.tri + 6);
\r
12528 #ifdef TRILIBRARY
\r
12529 nlist[index++] = neighbor1;
\r
12530 nlist[index++] = neighbor2;
\r
12531 nlist[index++] = neighbor3;
\r
12532 #else /* not TRILIBRARY */
\r
12533 /* Triangle number, neighboring triangle numbers. */
\r
12534 fprintf(outfile, "%4d %d %d %d\n", elementnumber,
\r
12535 neighbor1, neighbor2, neighbor3);
\r
12536 #endif /* not TRILIBRARY */
\r
12538 triangleloop.tri = triangletraverse();
\r
12542 #ifndef TRILIBRARY
\r
12543 finishfile(outfile, argc, argv);
\r
12544 #endif /* TRILIBRARY */
\r
12547 /*****************************************************************************/
\r
12549 /* writeoff() Write the triangulation to an .off file. */
\r
12551 /* OFF stands for the Object File Format, a format used by the Geometry */
\r
12552 /* Center's Geomview package. */
\r
12554 /*****************************************************************************/
\r
12556 #ifndef TRILIBRARY
\r
12558 void writeoff(offfilename, argc, argv)
\r
12559 char *offfilename;
\r
12564 struct triedge triangleloop;
\r
12566 point p1, p2, p3;
\r
12569 printf("Writing %s.\n", offfilename);
\r
12571 outfile = fopen(offfilename, "w");
\r
12572 if (outfile == (FILE *) NULL) {
\r
12573 printf(" Error: Cannot create file %s.\n", offfilename);
\r
12576 /* Number of points, triangles, and edges. */
\r
12577 fprintf(outfile, "OFF\n%ld %ld %ld\n", points.items, triangles.items,
\r
12580 /* Write the points. */
\r
12581 traversalinit(&points);
\r
12582 pointloop = pointtraverse();
\r
12583 while (pointloop != (point) NULL) {
\r
12584 /* The "0.0" is here because the OFF format uses 3D coordinates. */
\r
12585 fprintf(outfile, " %.17g %.17g %.17g\n", pointloop[0],
\r
12586 pointloop[1], 0.0);
\r
12587 pointloop = pointtraverse();
\r
12590 /* Write the triangles. */
\r
12591 traversalinit(&triangles);
\r
12592 triangleloop.tri = triangletraverse();
\r
12593 triangleloop.orient = 0;
\r
12594 while (triangleloop.tri != (triangle *) NULL) {
\r
12595 org(triangleloop, p1);
\r
12596 dest(triangleloop, p2);
\r
12597 apex(triangleloop, p3);
\r
12598 /* The "3" means a three-vertex polygon. */
\r
12599 fprintf(outfile, " 3 %4d %4d %4d\n", pointmark(p1) - 1,
\r
12600 pointmark(p2) - 1, pointmark(p3) - 1);
\r
12601 triangleloop.tri = triangletraverse();
\r
12603 finishfile(outfile, argc, argv);
\r
12606 #endif /* not TRILIBRARY */
\r
12610 /********* File I/O routines end here *********/
\r
12612 /*****************************************************************************/
\r
12614 /* quality_statistics() Print statistics about the quality of the mesh. */
\r
12616 /*****************************************************************************/
\r
12618 void quality_statistics()
\r
12620 struct triedge triangleloop;
\r
12622 REAL cossquaretable[8];
\r
12623 REAL ratiotable[16];
\r
12624 REAL dx[3], dy[3];
\r
12625 REAL edgelength[3];
\r
12629 REAL shortest, longest;
\r
12630 REAL trilongest2;
\r
12631 REAL smallestarea, biggestarea;
\r
12632 REAL triminaltitude2;
\r
12633 REAL minaltitude;
\r
12635 REAL worstaspect;
\r
12636 REAL smallestangle, biggestangle;
\r
12637 REAL radconst, degconst;
\r
12638 int angletable[18];
\r
12639 int aspecttable[16];
\r
12642 int acutebiggest;
\r
12645 printf("Mesh quality statistics:\n\n");
\r
12646 radconst = (REAL)(PI / 18.0);
\r
12647 degconst = (REAL)(180.0 / PI);
\r
12648 for (i = 0; i < 8; i++) {
\r
12649 cossquaretable[i] = (REAL)(cos(radconst * (REAL) (i + 1)));
\r
12650 cossquaretable[i] = cossquaretable[i] * cossquaretable[i];
\r
12652 for (i = 0; i < 18; i++) {
\r
12653 angletable[i] = 0;
\r
12656 ratiotable[0] = 1.5; ratiotable[1] = 2.0;
\r
12657 ratiotable[2] = 2.5; ratiotable[3] = 3.0;
\r
12658 ratiotable[4] = 4.0; ratiotable[5] = 6.0;
\r
12659 ratiotable[6] = 10.0; ratiotable[7] = 15.0;
\r
12660 ratiotable[8] = 25.0; ratiotable[9] = 50.0;
\r
12661 ratiotable[10] = 100.0; ratiotable[11] = 300.0;
\r
12662 ratiotable[12] = 1000.0; ratiotable[13] = 10000.0;
\r
12663 ratiotable[14] = 100000.0; ratiotable[15] = 0.0;
\r
12664 for (i = 0; i < 16; i++) {
\r
12665 aspecttable[i] = 0;
\r
12668 worstaspect = 0.0;
\r
12669 minaltitude = xmax - xmin + ymax - ymin;
\r
12670 minaltitude = minaltitude * minaltitude;
\r
12671 shortest = minaltitude;
\r
12673 smallestarea = minaltitude;
\r
12674 biggestarea = 0.0;
\r
12675 worstaspect = 0.0;
\r
12676 smallestangle = 0.0;
\r
12677 biggestangle = 2.0;
\r
12678 acutebiggest = 1;
\r
12680 traversalinit(&triangles);
\r
12681 triangleloop.tri = triangletraverse();
\r
12682 triangleloop.orient = 0;
\r
12683 while (triangleloop.tri != (triangle *) NULL) {
\r
12684 org(triangleloop, p[0]);
\r
12685 dest(triangleloop, p[1]);
\r
12686 apex(triangleloop, p[2]);
\r
12687 trilongest2 = 0.0;
\r
12689 for (i = 0; i < 3; i++) {
\r
12690 j = plus1mod3[i];
\r
12691 k = minus1mod3[i];
\r
12692 dx[i] = p[j][0] - p[k][0];
\r
12693 dy[i] = p[j][1] - p[k][1];
\r
12694 edgelength[i] = dx[i] * dx[i] + dy[i] * dy[i];
\r
12695 if (edgelength[i] > trilongest2) {
\r
12696 trilongest2 = edgelength[i];
\r
12698 if (edgelength[i] > longest) {
\r
12699 longest = edgelength[i];
\r
12701 if (edgelength[i] < shortest) {
\r
12702 shortest = edgelength[i];
\r
12706 triarea = counterclockwise(p[0], p[1], p[2]);
\r
12707 if (triarea < smallestarea) {
\r
12708 smallestarea = triarea;
\r
12710 if (triarea > biggestarea) {
\r
12711 biggestarea = triarea;
\r
12713 triminaltitude2 = triarea * triarea / trilongest2;
\r
12714 if (triminaltitude2 < minaltitude) {
\r
12715 minaltitude = triminaltitude2;
\r
12717 triaspect2 = trilongest2 / triminaltitude2;
\r
12718 if (triaspect2 > worstaspect) {
\r
12719 worstaspect = triaspect2;
\r
12722 while ((triaspect2 > ratiotable[aspectindex] * ratiotable[aspectindex])
\r
12723 && (aspectindex < 15)) {
\r
12726 aspecttable[aspectindex]++;
\r
12728 for (i = 0; i < 3; i++) {
\r
12729 j = plus1mod3[i];
\r
12730 k = minus1mod3[i];
\r
12731 dotproduct = dx[j] * dx[k] + dy[j] * dy[k];
\r
12732 cossquare = dotproduct * dotproduct / (edgelength[j] * edgelength[k]);
\r
12734 for (ii = 7; ii >= 0; ii--) {
\r
12735 if (cossquare > cossquaretable[ii]) {
\r
12739 if (dotproduct <= 0.0) {
\r
12740 angletable[tendegree]++;
\r
12741 if (cossquare > smallestangle) {
\r
12742 smallestangle = cossquare;
\r
12744 if (acutebiggest && (cossquare < biggestangle)) {
\r
12745 biggestangle = cossquare;
\r
12748 angletable[17 - tendegree]++;
\r
12749 if (acutebiggest || (cossquare > biggestangle)) {
\r
12750 biggestangle = cossquare;
\r
12751 acutebiggest = 0;
\r
12755 triangleloop.tri = triangletraverse();
\r
12758 shortest = (REAL)sqrt(shortest);
\r
12759 longest = (REAL)sqrt(longest);
\r
12760 minaltitude = (REAL)sqrt(minaltitude);
\r
12761 worstaspect = (REAL)sqrt(worstaspect);
\r
12762 smallestarea *= 2.0;
\r
12763 biggestarea *= 2.0;
\r
12764 if (smallestangle >= 1.0) {
\r
12765 smallestangle = 0.0;
\r
12767 smallestangle = (REAL)(degconst * acos(sqrt(smallestangle)));
\r
12769 if (biggestangle >= 1.0) {
\r
12770 biggestangle = 180.0;
\r
12772 if (acutebiggest) {
\r
12773 biggestangle = (REAL)(degconst * acos(sqrt(biggestangle)));
\r
12775 biggestangle = (REAL)(180.0 - degconst * acos(sqrt(biggestangle)));
\r
12779 printf(" Smallest area: %16.5g | Largest area: %16.5g\n",
\r
12780 smallestarea, biggestarea);
\r
12781 printf(" Shortest edge: %16.5g | Longest edge: %16.5g\n",
\r
12782 shortest, longest);
\r
12783 printf(" Shortest altitude: %12.5g | Largest aspect ratio: %8.5g\n\n",
\r
12784 minaltitude, worstaspect);
\r
12785 printf(" Aspect ratio histogram:\n");
\r
12786 printf(" 1.1547 - %-6.6g : %8d | %6.6g - %-6.6g : %8d\n",
\r
12787 ratiotable[0], aspecttable[0], ratiotable[7], ratiotable[8],
\r
12789 for (i = 1; i < 7; i++) {
\r
12790 printf(" %6.6g - %-6.6g : %8d | %6.6g - %-6.6g : %8d\n",
\r
12791 ratiotable[i - 1], ratiotable[i], aspecttable[i],
\r
12792 ratiotable[i + 7], ratiotable[i + 8], aspecttable[i + 8]);
\r
12794 printf(" %6.6g - %-6.6g : %8d | %6.6g - : %8d\n",
\r
12795 ratiotable[6], ratiotable[7], aspecttable[7], ratiotable[14],
\r
12796 aspecttable[15]);
\r
12798 " (Triangle aspect ratio is longest edge divided by shortest altitude)\n\n");
\r
12799 printf(" Smallest angle: %15.5g | Largest angle: %15.5g\n\n",
\r
12800 smallestangle, biggestangle);
\r
12801 printf(" Angle histogram:\n");
\r
12802 for (i = 0; i < 9; i++) {
\r
12803 printf(" %3d - %3d degrees: %8d | %3d - %3d degrees: %8d\n",
\r
12804 i * 10, i * 10 + 10, angletable[i],
\r
12805 i * 10 + 90, i * 10 + 100, angletable[i + 9]);
\r
12810 /*****************************************************************************/
\r
12812 /* statistics() Print all sorts of cool facts. */
\r
12814 /*****************************************************************************/
\r
12816 void statistics()
\r
12818 printf("\nStatistics:\n\n");
\r
12819 printf(" Input points: %d\n", inpoints);
\r
12821 printf(" Input triangles: %d\n", inelements);
\r
12824 printf(" Input segments: %d\n", insegments);
\r
12826 printf(" Input holes: %d\n", holes);
\r
12830 printf("\n Mesh points: %ld\n", points.items);
\r
12831 printf(" Mesh triangles: %ld\n", triangles.items);
\r
12832 printf(" Mesh edges: %ld\n", edges);
\r
12833 if (poly || refine) {
\r
12834 printf(" Mesh boundary edges: %ld\n", hullsize);
\r
12835 printf(" Mesh segments: %ld\n\n", shelles.items);
\r
12837 printf(" Mesh convex hull edges: %ld\n\n", hullsize);
\r
12840 quality_statistics();
\r
12841 printf("Memory allocation statistics:\n\n");
\r
12842 printf(" Maximum number of points: %ld\n", points.maxitems);
\r
12843 printf(" Maximum number of triangles: %ld\n", triangles.maxitems);
\r
12844 if (shelles.maxitems > 0) {
\r
12845 printf(" Maximum number of segments: %ld\n", shelles.maxitems);
\r
12847 if (viri.maxitems > 0) {
\r
12848 printf(" Maximum number of viri: %ld\n", viri.maxitems);
\r
12850 if (badsegments.maxitems > 0) {
\r
12851 printf(" Maximum number of encroached segments: %ld\n",
\r
12852 badsegments.maxitems);
\r
12854 if (badtriangles.maxitems > 0) {
\r
12855 printf(" Maximum number of bad triangles: %ld\n",
\r
12856 badtriangles.maxitems);
\r
12858 if (splaynodes.maxitems > 0) {
\r
12859 printf(" Maximum number of splay tree nodes: %ld\n",
\r
12860 splaynodes.maxitems);
\r
12862 printf(" Approximate heap memory use (bytes): %ld\n\n",
\r
12863 points.maxitems * points.itembytes
\r
12864 + triangles.maxitems * triangles.itembytes
\r
12865 + shelles.maxitems * shelles.itembytes
\r
12866 + viri.maxitems * viri.itembytes
\r
12867 + badsegments.maxitems * badsegments.itembytes
\r
12868 + badtriangles.maxitems * badtriangles.itembytes
\r
12869 + splaynodes.maxitems * splaynodes.itembytes);
\r
12871 printf("Algorithmic statistics:\n\n");
\r
12872 printf(" Number of incircle tests: %ld\n", incirclecount);
\r
12873 printf(" Number of orientation tests: %ld\n", counterclockcount);
\r
12874 if (hyperbolacount > 0) {
\r
12875 printf(" Number of right-of-hyperbola tests: %ld\n",
\r
12878 if (circumcentercount > 0) {
\r
12879 printf(" Number of circumcenter computations: %ld\n",
\r
12880 circumcentercount);
\r
12882 if (circletopcount > 0) {
\r
12883 printf(" Number of circle top computations: %ld\n",
\r
12890 /*****************************************************************************/
\r
12892 /* main() or triangulate() Gosh, do everything. */
\r
12894 /* The sequence is roughly as follows. Many of these steps can be skipped, */
\r
12895 /* depending on the command line switches. */
\r
12897 /* - Initialize constants and parse the command line. */
\r
12898 /* - Read the points from a file and either */
\r
12899 /* - triangulate them (no -r), or */
\r
12900 /* - read an old mesh from files and reconstruct it (-r). */
\r
12901 /* - Insert the PSLG segments (-p), and possibly segments on the convex */
\r
12903 /* - Read the holes (-p), regional attributes (-pA), and regional area */
\r
12904 /* constraints (-pa). Carve the holes and concavities, and spread the */
\r
12905 /* regional attributes and area constraints. */
\r
12906 /* - Enforce the constraints on minimum angle (-q) and maximum area (-a). */
\r
12907 /* Also enforce the conforming Delaunay property (-q and -a). */
\r
12908 /* - Compute the number of edges in the resulting mesh. */
\r
12909 /* - Promote the mesh's linear triangles to higher order elements (-o). */
\r
12910 /* - Write the output files and print the statistics. */
\r
12911 /* - Check the consistency and Delaunay property of the mesh (-C). */
\r
12913 /*****************************************************************************/
\r
12915 #ifdef TRILIBRARY
\r
12917 void triangulate(triswitches, in, out, vorout)
\r
12918 char *triswitches;
\r
12919 struct triangulateio *in;
\r
12920 struct triangulateio *out;
\r
12921 struct triangulateio *vorout;
\r
12923 #else /* not TRILIBRARY */
\r
12925 int main(argc, argv)
\r
12929 #endif /* not TRILIBRARY */
\r
12932 REAL *holearray; /* Array of holes. */
\r
12933 REAL *regionarray; /* Array of regional attributes and area constraints. */
\r
12934 #ifndef TRILIBRARY
\r
12936 #endif /* not TRILIBRARY */
\r
12938 /* Variables for timing the performance of Triangle. The types are */
\r
12939 /* defined in sys/time.h. */
\r
12940 struct timeval tv0, tv1, tv2, tv3, tv4, tv5, tv6;
\r
12941 struct timezone tz;
\r
12942 #endif /* NO_TIMER */
\r
12945 gettimeofday(&tv0, &tz);
\r
12946 #endif /* NO_TIMER */
\r
12949 #ifdef TRILIBRARY
\r
12950 parsecommandline(1, &triswitches);
\r
12951 #else /* not TRILIBRARY */
\r
12952 parsecommandline(argc, argv);
\r
12953 #endif /* not TRILIBRARY */
\r
12955 #ifdef TRILIBRARY
\r
12956 transfernodes(in->pointlist, in->pointattributelist, in->pointmarkerlist,
\r
12957 in->numberofpoints, in->numberofpointattributes);
\r
12958 #else /* not TRILIBRARY */
\r
12959 readnodes(innodefilename, inpolyfilename, &polyfile);
\r
12960 #endif /* not TRILIBRARY */
\r
12964 gettimeofday(&tv1, &tz);
\r
12966 #endif /* NO_TIMER */
\r
12969 hullsize = delaunay(); /* Triangulate the points. */
\r
12970 #else /* not CDT_ONLY */
\r
12972 /* Read and reconstruct a mesh. */
\r
12973 #ifdef TRILIBRARY
\r
12974 hullsize = reconstruct(in->trianglelist, in->triangleattributelist,
\r
12975 in->trianglearealist, in->numberoftriangles,
\r
12976 in->numberofcorners, in->numberoftriangleattributes,
\r
12977 in->segmentlist, in->segmentmarkerlist,
\r
12978 in->numberofsegments);
\r
12979 #else /* not TRILIBRARY */
\r
12980 hullsize = reconstruct(inelefilename, areafilename, inpolyfilename,
\r
12982 #endif /* not TRILIBRARY */
\r
12984 hullsize = delaunay(); /* Triangulate the points. */
\r
12986 #endif /* not CDT_ONLY */
\r
12990 gettimeofday(&tv2, &tz);
\r
12992 printf("Mesh reconstruction");
\r
12994 printf("Delaunay");
\r
12996 printf(" milliseconds: %ld\n", 1000l * (tv2.tv_sec - tv1.tv_sec)
\r
12997 + (tv2.tv_usec - tv1.tv_usec) / 1000l);
\r
12999 #endif /* NO_TIMER */
\r
13001 /* Ensure that no point can be mistaken for a triangular bounding */
\r
13002 /* box point in insertsite(). */
\r
13003 infpoint1 = (point) NULL;
\r
13004 infpoint2 = (point) NULL;
\r
13005 infpoint3 = (point) NULL;
\r
13007 if (useshelles) {
\r
13008 checksegments = 1; /* Segments will be introduced next. */
\r
13010 /* Insert PSLG segments and/or convex hull segments. */
\r
13011 #ifdef TRILIBRARY
\r
13012 insegments = formskeleton(in->segmentlist, in->segmentmarkerlist,
\r
13013 in->numberofsegments);
\r
13014 #else /* not TRILIBRARY */
\r
13015 insegments = formskeleton(polyfile, inpolyfilename);
\r
13016 #endif /* not TRILIBRARY */
\r
13022 gettimeofday(&tv3, &tz);
\r
13023 if (useshelles && !refine) {
\r
13024 printf("Segment milliseconds: %ld\n",
\r
13025 1000l * (tv3.tv_sec - tv2.tv_sec)
\r
13026 + (tv3.tv_usec - tv2.tv_usec) / 1000l);
\r
13029 #endif /* NO_TIMER */
\r
13032 #ifdef TRILIBRARY
\r
13033 holearray = in->holelist;
\r
13034 holes = in->numberofholes;
\r
13035 regionarray = in->regionlist;
\r
13036 regions = in->numberofregions;
\r
13037 #else /* not TRILIBRARY */
\r
13038 readholes(polyfile, inpolyfilename, &holearray, &holes,
\r
13039 ®ionarray, ®ions);
\r
13040 #endif /* not TRILIBRARY */
\r
13042 /* Carve out holes and concavities. */
\r
13043 carveholes(holearray, holes, regionarray, regions);
\r
13046 /* Without a PSLG, there can be no holes or regional attributes */
\r
13047 /* or area constraints. The following are set to zero to avoid */
\r
13048 /* an accidental free() later. */
\r
13055 gettimeofday(&tv4, &tz);
\r
13056 if (poly && !refine) {
\r
13057 printf("Hole milliseconds: %ld\n", 1000l * (tv4.tv_sec - tv3.tv_sec)
\r
13058 + (tv4.tv_usec - tv3.tv_usec) / 1000l);
\r
13061 #endif /* NO_TIMER */
\r
13065 enforcequality(); /* Enforce angle and area constraints. */
\r
13067 #endif /* not CDT_ONLY */
\r
13071 gettimeofday(&tv5, &tz);
\r
13074 printf("Quality milliseconds: %ld\n",
\r
13075 1000l * (tv5.tv_sec - tv4.tv_sec)
\r
13076 + (tv5.tv_usec - tv4.tv_usec) / 1000l);
\r
13078 #endif /* not CDT_ONLY */
\r
13080 #endif /* NO_TIMER */
\r
13082 /* Compute the number of edges. */
\r
13083 edges = (3l * triangles.items + hullsize) / 2l;
\r
13086 highorder(); /* Promote elements to higher polynomial order. */
\r
13092 #ifdef TRILIBRARY
\r
13093 out->numberofpoints = points.items;
\r
13094 out->numberofpointattributes = nextras;
\r
13095 out->numberoftriangles = triangles.items;
\r
13096 out->numberofcorners = (order + 1) * (order + 2) / 2;
\r
13097 out->numberoftriangleattributes = eextras;
\r
13098 out->numberofedges = edges;
\r
13099 if (useshelles) {
\r
13100 out->numberofsegments = shelles.items;
\r
13102 out->numberofsegments = hullsize;
\r
13104 if (vorout != (struct triangulateio *) NULL) {
\r
13105 vorout->numberofpoints = triangles.items;
\r
13106 vorout->numberofpointattributes = nextras;
\r
13107 vorout->numberofedges = edges;
\r
13109 #endif /* TRILIBRARY */
\r
13110 /* If not using iteration numbers, don't write a .node file if one was */
\r
13111 /* read, because the original one would be overwritten! */
\r
13112 if (nonodewritten || (noiterationnum && readnodefile)) {
\r
13114 #ifdef TRILIBRARY
\r
13115 printf("NOT writing points.\n");
\r
13116 #else /* not TRILIBRARY */
\r
13117 printf("NOT writing a .node file.\n");
\r
13118 #endif /* not TRILIBRARY */
\r
13120 numbernodes(); /* We must remember to number the points. */
\r
13122 #ifdef TRILIBRARY
\r
13123 writenodes(&out->pointlist, &out->pointattributelist,
\r
13124 &out->pointmarkerlist);
\r
13125 #else /* not TRILIBRARY */
\r
13126 writenodes(outnodefilename, argc, argv); /* Numbers the points too. */
\r
13127 #endif /* TRILIBRARY */
\r
13129 if (noelewritten) {
\r
13131 #ifdef TRILIBRARY
\r
13132 printf("NOT writing triangles.\n");
\r
13133 #else /* not TRILIBRARY */
\r
13134 printf("NOT writing an .ele file.\n");
\r
13135 #endif /* not TRILIBRARY */
\r
13138 #ifdef TRILIBRARY
\r
13139 writeelements(&out->trianglelist, &out->triangleattributelist);
\r
13140 #else /* not TRILIBRARY */
\r
13141 writeelements(outelefilename, argc, argv);
\r
13142 #endif /* not TRILIBRARY */
\r
13144 /* The -c switch (convex switch) causes a PSLG to be written */
\r
13145 /* even if none was read. */
\r
13146 if (poly || convex) {
\r
13147 /* If not using iteration numbers, don't overwrite the .poly file. */
\r
13148 if (nopolywritten || noiterationnum) {
\r
13150 #ifdef TRILIBRARY
\r
13151 printf("NOT writing segments.\n");
\r
13152 #else /* not TRILIBRARY */
\r
13153 printf("NOT writing a .poly file.\n");
\r
13154 #endif /* not TRILIBRARY */
\r
13157 #ifdef TRILIBRARY
\r
13158 writepoly(&out->segmentlist, &out->segmentmarkerlist);
\r
13159 out->numberofholes = holes;
\r
13160 out->numberofregions = regions;
\r
13162 out->holelist = in->holelist;
\r
13163 out->regionlist = in->regionlist;
\r
13165 out->holelist = (REAL *) NULL;
\r
13166 out->regionlist = (REAL *) NULL;
\r
13168 #else /* not TRILIBRARY */
\r
13169 writepoly(outpolyfilename, holearray, holes, regionarray, regions,
\r
13171 #endif /* not TRILIBRARY */
\r
13174 #ifndef TRILIBRARY
\r
13176 if (regions > 0) {
\r
13177 free(regionarray);
\r
13179 #endif /* not CDT_ONLY */
\r
13184 writeoff(offfilename, argc, argv);
\r
13186 #endif /* not TRILIBRARY */
\r
13188 #ifdef TRILIBRARY
\r
13189 writeedges(&out->edgelist, &out->edgemarkerlist);
\r
13190 #else /* not TRILIBRARY */
\r
13191 writeedges(edgefilename, argc, argv);
\r
13192 #endif /* not TRILIBRARY */
\r
13195 #ifdef TRILIBRARY
\r
13196 writevoronoi(&vorout->pointlist, &vorout->pointattributelist,
\r
13197 &vorout->pointmarkerlist, &vorout->edgelist,
\r
13198 &vorout->edgemarkerlist, &vorout->normlist);
\r
13199 #else /* not TRILIBRARY */
\r
13200 writevoronoi(vnodefilename, vedgefilename, argc, argv);
\r
13201 #endif /* not TRILIBRARY */
\r
13204 #ifdef TRILIBRARY
\r
13205 writeneighbors(&out->neighborlist);
\r
13206 #else /* not TRILIBRARY */
\r
13207 writeneighbors(neighborfilename, argc, argv);
\r
13208 #endif /* not TRILIBRARY */
\r
13213 gettimeofday(&tv6, &tz);
\r
13214 printf("\nOutput milliseconds: %ld\n",
\r
13215 1000l * (tv6.tv_sec - tv5.tv_sec)
\r
13216 + (tv6.tv_usec - tv5.tv_usec) / 1000l);
\r
13217 printf("Total running milliseconds: %ld\n",
\r
13218 1000l * (tv6.tv_sec - tv0.tv_sec)
\r
13219 + (tv6.tv_usec - tv0.tv_usec) / 1000l);
\r
13220 #endif /* NO_TIMER */
\r
13230 #endif /* not REDUCED */
\r
13232 triangledeinit();
\r
13233 #ifndef TRILIBRARY
\r
13235 #endif /* not TRILIBRARY */
\r