1 /*****************************************************************************/
2 /*                                                                           */
3 /*      888888888        ,o,                          / 888                  */
4 /*         888    88o88o  "    o8888o  88o8888o o88888o 888  o88888o         */
5 /*         888    888    888       88b 888  888 888 888 888 d888  88b        */
6 /*         888    888    888  o88^o888 888  888 "88888" 888 8888oo888        */
7 /*         888    888    888 C888  888 888  888  /      888 q888             */
8 /*         888    888    888  "88o^888 888  888 Cb      888  "88oooo"        */
9 /*                                              "8oo8D                       */
10 /*                                                                           */
11 /*  A Two-Dimensional Quality Mesh Generator and Delaunay Triangulator.      */
12 /*  (triangle.c)                                                             */
13 /*                                                                           */
14 /*  Version 1.6                                                              */
15 /*  July 28, 2005                                                            */
16 /*                                                                           */
17 /*  Copyright 1993, 1995, 1997, 1998, 2002, 2005                             */
18 /*  Jonathan Richard Shewchuk                                                */
19 /*  2360 Woolsey #H                                                          */
20 /*  Berkeley, California  94705-1927                                         */
21 /*  jrs@cs.berkeley.edu                                                      */
22 /*                                                                           */
23 /*  This program may be freely redistributed under the condition that the    */
24 /*    copyright notices (including this entire header and the copyright      */
25 /*    notice printed when the `-h' switch is selected) are not removed, and  */
26 /*    no compensation is received.  Private, research, and institutional     */
27 /*    use is free.  You may distribute modified versions of this code UNDER  */
28 /*    THE CONDITION THAT THIS CODE AND ANY MODIFICATIONS MADE TO IT IN THE   */
29 /*    SAME FILE REMAIN UNDER COPYRIGHT OF THE ORIGINAL AUTHOR, BOTH SOURCE   */
30 /*    AND OBJECT CODE ARE MADE FREELY AVAILABLE WITHOUT CHARGE, AND CLEAR    */
31 /*    NOTICE IS GIVEN OF THE MODIFICATIONS.  Distribution of this code as    */
32 /*    part of a commercial system is permissible ONLY BY DIRECT ARRANGEMENT  */
33 /*    WITH THE AUTHOR.  (If you are not directly supplying this code to a    */
34 /*    customer, and you are instead telling them how they can obtain it for  */
35 /*    free, then you are not required to make any arrangement with me.)      */
36 /*                                                                           */
37 /*  Hypertext instructions for Triangle are available on the Web at          */
38 /*                                                                           */
39 /*      http://www.cs.cmu.edu/~quake/triangle.html                           */
40 /*                                                                           */
41 /*  Disclaimer:  Neither I nor Carnegie Mellon warrant this code in any way  */
42 /*    whatsoever.  This code is provided "as-is".  Use at your own risk.     */
43 /*                                                                           */
44 /*  Some of the references listed below are marked with an asterisk.  [*]    */
45 /*    These references are available for downloading from the Web page       */
46 /*                                                                           */
47 /*      http://www.cs.cmu.edu/~quake/triangle.research.html                  */
48 /*                                                                           */
49 /*  Three papers discussing aspects of Triangle are available.  A short      */
50 /*    overview appears in "Triangle:  Engineering a 2D Quality Mesh          */
51 /*    Generator and Delaunay Triangulator," in Applied Computational         */
52 /*    Geometry:  Towards Geometric Engineering, Ming C. Lin and Dinesh       */
53 /*    Manocha, editors, Lecture Notes in Computer Science volume 1148,       */
54 /*    pages 203-222, Springer-Verlag, Berlin, May 1996 (from the First ACM   */
55 /*    Workshop on Applied Computational Geometry).  [*]                      */
56 /*                                                                           */
57 /*    The algorithms are discussed in the greatest detail in "Delaunay       */
58 /*    Refinement Algorithms for Triangular Mesh Generation," Computational   */
59 /*    Geometry:  Theory and Applications 22(1-3):21-74, May 2002.  [*]       */
60 /*                                                                           */
61 /*    More detail about the data structures may be found in my dissertation: */
62 /*    "Delaunay Refinement Mesh Generation," Ph.D. thesis, Technical Report  */
63 /*    CMU-CS-97-137, School of Computer Science, Carnegie Mellon University, */
64 /*    Pittsburgh, Pennsylvania, 18 May 1997.  [*]                            */
65 /*                                                                           */
66 /*  Triangle was created as part of the Quake Project in the School of       */
67 /*    Computer Science at Carnegie Mellon University.  For further           */
68 /*    information, see Hesheng Bao, Jacobo Bielak, Omar Ghattas, Loukas F.   */
69 /*    Kallivokas, David R. O'Hallaron, Jonathan R. Shewchuk, and Jifeng Xu,  */
70 /*    "Large-scale Simulation of Elastic Wave Propagation in Heterogeneous   */
71 /*    Media on Parallel Computers," Computer Methods in Applied Mechanics    */
72 /*    and Engineering 152(1-2):85-102, 22 January 1998.                      */
73 /*                                                                           */
74 /*  Triangle's Delaunay refinement algorithm for quality mesh generation is  */
75 /*    a hybrid of one due to Jim Ruppert, "A Delaunay Refinement Algorithm   */
76 /*    for Quality 2-Dimensional Mesh Generation," Journal of Algorithms      */
77 /*    18(3):548-585, May 1995 [*], and one due to L. Paul Chew, "Guaranteed- */
78 /*    Quality Mesh Generation for Curved Surfaces," Proceedings of the Ninth */
79 /*    Annual Symposium on Computational Geometry (San Diego, California),    */
80 /*    pages 274-280, Association for Computing Machinery, May 1993,          */
81 /*    http://portal.acm.org/citation.cfm?id=161150 .                         */
82 /*                                                                           */
83 /*  The Delaunay refinement algorithm has been modified so that it meshes    */
84 /*    domains with small input angles well, as described in Gary L. Miller,  */
85 /*    Steven E. Pav, and Noel J. Walkington, "When and Why Ruppert's         */
86 /*    Algorithm Works," Twelfth International Meshing Roundtable, pages      */
87 /*    91-102, Sandia National Laboratories, September 2003.  [*]             */
88 /*                                                                           */
89 /*  My implementation of the divide-and-conquer and incremental Delaunay     */
90 /*    triangulation algorithms follows closely the presentation of Guibas    */
91 /*    and Stolfi, even though I use a triangle-based data structure instead  */
92 /*    of their quad-edge data structure.  (In fact, I originally implemented */
93 /*    Triangle using the quad-edge data structure, but the switch to a       */
94 /*    triangle-based data structure sped Triangle by a factor of two.)  The  */
95 /*    mesh manipulation primitives and the two aforementioned Delaunay       */
96 /*    triangulation algorithms are described by Leonidas J. Guibas and Jorge */
97 /*    Stolfi, "Primitives for the Manipulation of General Subdivisions and   */
98 /*    the Computation of Voronoi Diagrams," ACM Transactions on Graphics     */
99 /*    4(2):74-123, April 1985, http://portal.acm.org/citation.cfm?id=282923 .*/
100 /*                                                                           */
101 /*  Their O(n log n) divide-and-conquer algorithm is adapted from Der-Tsai   */
102 /*    Lee and Bruce J. Schachter, "Two Algorithms for Constructing the       */
103 /*    Delaunay Triangulation," International Journal of Computer and         */
104 /*    Information Science 9(3):219-242, 1980.  Triangle's improvement of the */
105 /*    divide-and-conquer algorithm by alternating between vertical and       */
106 /*    horizontal cuts was introduced by Rex A. Dwyer, "A Faster Divide-and-  */
107 /*    Conquer Algorithm for Constructing Delaunay Triangulations,"           */
108 /*    Algorithmica 2(2):137-151, 1987.                                       */
109 /*                                                                           */
110 /*  The incremental insertion algorithm was first proposed by C. L. Lawson,  */
111 /*    "Software for C1 Surface Interpolation," in Mathematical Software III, */
112 /*    John R. Rice, editor, Academic Press, New York, pp. 161-194, 1977.     */
113 /*    For point location, I use the algorithm of Ernst P. Mucke, Isaac       */
114 /*    Saias, and Binhai Zhu, "Fast Randomized Point Location Without         */
115 /*    Preprocessing in Two- and Three-Dimensional Delaunay Triangulations,"  */
116 /*    Proceedings of the Twelfth Annual Symposium on Computational Geometry, */
117 /*    ACM, May 1996.  [*]  If I were to randomize the order of vertex        */
118 /*    insertion (I currently don't bother), their result combined with the   */
119 /*    result of Kenneth L. Clarkson and Peter W. Shor, "Applications of      */
120 /*    Random Sampling in Computational Geometry II," Discrete &              */
121 /*    Computational Geometry 4(1):387-421, 1989, would yield an expected     */
122 /*    O(n^{4/3}) bound on running time.                                      */
123 /*                                                                           */
124 /*  The O(n log n) sweepline Delaunay triangulation algorithm is taken from  */
125 /*    Steven Fortune, "A Sweepline Algorithm for Voronoi Diagrams",          */
126 /*    Algorithmica 2(2):153-174, 1987.  A random sample of edges on the      */
127 /*    boundary of the triangulation are maintained in a splay tree for the   */
128 /*    purpose of point location.  Splay trees are described by Daniel        */
129 /*    Dominic Sleator and Robert Endre Tarjan, "Self-Adjusting Binary Search */
130 /*    Trees," Journal of the ACM 32(3):652-686, July 1985,                   */
131 /*    http://portal.acm.org/citation.cfm?id=3835 .                           */
132 /*                                                                           */
133 /*  The algorithms for exact computation of the signs of determinants are    */
134 /*    described in Jonathan Richard Shewchuk, "Adaptive Precision Floating-  */
135 /*    Point Arithmetic and Fast Robust Geometric Predicates," Discrete &     */
136 /*    Computational Geometry 18(3):305-363, October 1997.  (Also available   */
137 /*    as Technical Report CMU-CS-96-140, School of Computer Science,         */
138 /*    Carnegie Mellon University, Pittsburgh, Pennsylvania, May 1996.)  [*]  */
139 /*    An abbreviated version appears as Jonathan Richard Shewchuk, "Robust   */
140 /*    Adaptive Floating-Point Geometric Predicates," Proceedings of the      */
141 /*    Twelfth Annual Symposium on Computational Geometry, ACM, May 1996. [*] */
142 /*    Many of the ideas for my exact arithmetic routines originate with      */
143 /*    Douglas M. Priest, "Algorithms for Arbitrary Precision Floating Point  */
144 /*    Arithmetic," Tenth Symposium on Computer Arithmetic, pp. 132-143, IEEE */
145 /*    Computer Society Press, 1991.  [*]  Many of the ideas for the correct  */
146 /*    evaluation of the signs of determinants are taken from Steven Fortune  */
147 /*    and Christopher J. Van Wyk, "Efficient Exact Arithmetic for Computa-   */
148 /*    tional Geometry," Proceedings of the Ninth Annual Symposium on         */
149 /*    Computational Geometry, ACM, pp. 163-172, May 1993, and from Steven    */
150 /*    Fortune, "Numerical Stability of Algorithms for 2D Delaunay Triangu-   */
151 /*    lations," International Journal of Computational Geometry & Applica-   */
152 /*    tions 5(1-2):193-213, March-June 1995.                                 */
153 /*                                                                           */
154 /*  The method of inserting new vertices off-center (not precisely at the    */
155 /*    circumcenter of every poor-quality triangle) is from Alper Ungor,      */
156 /*    "Off-centers:  A New Type of Steiner Points for Computing Size-Optimal */
157 /*    Quality-Guaranteed Delaunay Triangulations," Proceedings of LATIN      */
158 /*    2004 (Buenos Aires, Argentina), April 2004.                            */
159 /*                                                                           */
160 /*  For definitions of and results involving Delaunay triangulations,        */
161 /*    constrained and conforming versions thereof, and other aspects of      */
162 /*    triangular mesh generation, see the excellent survey by Marshall Bern  */
163 /*    and David Eppstein, "Mesh Generation and Optimal Triangulation," in    */
164 /*    Computing and Euclidean Geometry, Ding-Zhu Du and Frank Hwang,         */
165 /*    editors, World Scientific, Singapore, pp. 23-90, 1992.  [*]            */
166 /*                                                                           */
167 /*  The time for incrementally adding PSLG (planar straight line graph)      */
168 /*    segments to create a constrained Delaunay triangulation is probably    */
169 /*    O(t^2) per segment in the worst case and O(t) per segment in the       */
170 /*    common case, where t is the number of triangles that intersect the     */
171 /*    segment before it is inserted.  This doesn't count point location,     */
172 /*    which can be much more expensive.  I could improve this to O(d log d)  */
173 /*    time, but d is usually quite small, so it's not worth the bother.      */
174 /*    (This note does not apply when the -s switch is used, invoking a       */
175 /*    different method is used to insert segments.)                          */
176 /*                                                                           */
177 /*  The time for deleting a vertex from a Delaunay triangulation is O(d^2)   */
178 /*    in the worst case and O(d) in the common case, where d is the degree   */
179 /*    of the vertex being deleted.  I could improve this to O(d log d) time, */
180 /*    but d is usually quite small, so it's not worth the bother.            */
181 /*                                                                           */
182 /*  Ruppert's Delaunay refinement algorithm typically generates triangles    */
183 /*    at a linear rate (constant time per triangle) after the initial        */
184 /*    triangulation is formed.  There may be pathological cases where        */
185 /*    quadratic time is required, but these never arise in practice.         */
186 /*                                                                           */
187 /*  The geometric predicates (circumcenter calculations, segment             */
188 /*    intersection formulae, etc.) appear in my "Lecture Notes on Geometric  */
189 /*    Robustness" at http://www.cs.berkeley.edu/~jrs/mesh .                  */
190 /*                                                                           */
191 /*  If you make any improvements to this code, please please please let me   */
192 /*    know, so that I may obtain the improvements.  Even if you don't change */
193 /*    the code, I'd still love to hear what it's being used for.             */
194 /*                                                                           */
195 /*****************************************************************************/
196 
197 /* For single precision (which will save some memory and reduce paging),     */
198 /*   define the symbol SINGLE by using the -DSINGLE compiler switch or by    */
199 /*   writing "#define SINGLE" below.                                         */
200 /*                                                                           */
201 /* For double precision (which will allow you to refine meshes to a smaller  */
202 /*   edge length), leave SINGLE undefined.                                   */
203 /*                                                                           */
204 /* Double precision uses more memory, but improves the resolution of the     */
205 /*   meshes you can generate with Triangle.  It also reduces the likelihood  */
206 /*   of a floating exception due to overflow.  Finally, it is much faster    */
207 /*   than single precision on 64-bit architectures like the DEC Alpha.  I    */
208 /*   recommend double precision unless you want to generate a mesh for which */
209 /*   you do not have enough memory.                                          */
210 
211 /* #define SINGLE */
212 
213 #ifdef SINGLE
214 #define REAL float
215 #else /* not SINGLE */
216 #define REAL double
217 #endif /* not SINGLE */
218 
219 /* If yours is not a Unix system, define the NO_TIMER compiler switch to     */
220 /*   remove the Unix-specific timing code.                                   */
221 
222 /* #define NO_TIMER */
223 
224 /* To insert lots of self-checks for internal errors, define the SELF_CHECK  */
225 /*   symbol.  This will slow down the program significantly.  It is best to  */
226 /*   define the symbol using the -DSELF_CHECK compiler switch, but you could */
227 /*   write "#define SELF_CHECK" below.  If you are modifying this code, I    */
228 /*   recommend you turn self-checks on until your work is debugged.          */
229 
230 /* #define SELF_CHECK */
231 
232 /* To compile Triangle as a callable object library (triangle.o), define the */
233 /*   TRILIBRARY symbol.  Read the file triangle.h for details on how to call */
234 /*   the procedure triangulate() that results.                               */
235 
236 /* #define TRILIBRARY */
237 
238 /* It is possible to generate a smaller version of Triangle using one or     */
239 /*   both of the following symbols.  Define the REDUCED symbol to eliminate  */
240 /*   all features that are primarily of research interest; specifically, the */
241 /*   -i, -F, -s, and -C switches.  Define the CDT_ONLY symbol to eliminate   */
242 /*   all meshing algorithms above and beyond constrained Delaunay            */
243 /*   triangulation; specifically, the -r, -q, -a, -u, -D, -S, and -s         */
244 /*   switches.  These reductions are most likely to be useful when           */
245 /*   generating an object library (triangle.o) by defining the TRILIBRARY    */
246 /*   symbol.                                                                 */
247 
248 /* #define REDUCED */
249 /* #define CDT_ONLY */
250 
251 /* On some machines, my exact arithmetic routines might be defeated by the   */
252 /*   use of internal extended precision floating-point registers.  The best  */
253 /*   way to solve this problem is to set the floating-point registers to use */
254 /*   single or double precision internally.  On 80x86 processors, this may   */
255 /*   be accomplished by setting the CPU86 symbol for the Microsoft C         */
256 /*   compiler, or the LINUX symbol for the gcc compiler running on Linux.    */
257 /*                                                                           */
258 /* An inferior solution is to declare certain values as `volatile', thus     */
259 /*   forcing them to be stored to memory and rounded off.  Unfortunately,    */
260 /*   this solution might slow Triangle down quite a bit.  To use volatile    */
261 /*   values, write "#define INEXACT volatile" below.  Normally, however,     */
262 /*   INEXACT should be defined to be nothing.  ("#define INEXACT".)          */
263 /*                                                                           */
264 /* For more discussion, see http://www.cs.cmu.edu/~quake/robust.pc.html .    */
265 /*   For yet more discussion, see Section 5 of my paper, "Adaptive Precision */
266 /*   Floating-Point Arithmetic and Fast Robust Geometric Predicates" (also   */
267 /*   available as Section 6.6 of my dissertation).                           */
268 
269 /* #define CPU86 */
270 /* #define LINUX */
271 
272 #define INEXACT /* Nothing */
273 /* #define INEXACT volatile */
274 
275 /* Maximum number of characters in a file name (including the null).         */
276 
277 #define FILENAMESIZE 2048
278 
279 /* Maximum number of characters in a line read from a file (including the    */
280 /*   null).                                                                  */
281 
282 #define INPUTLINESIZE 1024
283 
284 /* For efficiency, a variety of data structures are allocated in bulk.  The  */
285 /*   following constants determine how many of each structure is allocated   */
286 /*   at once.                                                                */
287 
288 #define TRIPERBLOCK 4092           /* Number of triangles allocated at once. */
289 #define SUBSEGPERBLOCK 508       /* Number of subsegments allocated at once. */
290 #define VERTEXPERBLOCK 4092         /* Number of vertices allocated at once. */
291 #define VIRUSPERBLOCK 1020   /* Number of virus triangles allocated at once. */
292 /* Number of encroached subsegments allocated at once. */
293 #define BADSUBSEGPERBLOCK 252
294 /* Number of skinny triangles allocated at once. */
295 #define BADTRIPERBLOCK 4092
296 /* Number of flipped triangles allocated at once. */
297 #define FLIPSTACKERPERBLOCK 252
298 /* Number of splay tree nodes allocated at once. */
299 #define SPLAYNODEPERBLOCK 508
300 
301 /* The vertex types.   A DEADVERTEX has been deleted entirely.  An           */
302 /*   UNDEADVERTEX is not part of the mesh, but is written to the output      */
303 /*   .node file and affects the node indexing in the other output files.     */
304 
305 #define INPUTVERTEX 0
306 #define SEGMENTVERTEX 1
307 #define FREEVERTEX 2
308 #define DEADVERTEX -32768
309 #define UNDEADVERTEX -32767
310 
311 /* The next line is used to outsmart some very stupid compilers.  If your    */
312 /*   compiler is smarter, feel free to replace the "int" with "void".        */
313 /*   Not that it matters.                                                    */
314 
315 #define VOID int
316 
317 /* Two constants for algorithms based on random sampling.  Both constants    */
318 /*   have been chosen empirically to optimize their respective algorithms.   */
319 
320 /* Used for the point location scheme of Mucke, Saias, and Zhu, to decide    */
321 /*   how large a random sample of triangles to inspect.                      */
322 
323 #define SAMPLEFACTOR 11
324 
325 /* Used in Fortune's sweepline Delaunay algorithm to determine what fraction */
326 /*   of boundary edges should be maintained in the splay tree for point      */
327 /*   location on the front.                                                  */
328 
329 #define SAMPLERATE 10
330 
331 /* A number that speaks for itself, every kissable digit.                    */
332 
333 #define PI 3.141592653589793238462643383279502884197169399375105820974944592308
334 
335 /* Another fave.                                                             */
336 
337 #define SQUAREROOTTWO 1.4142135623730950488016887242096980785696718753769480732
338 
339 /* And here's one for those of you who are intimidated by math.              */
340 
341 #define ONETHIRD 0.333333333333333333333333333333333333333333333333333333333333
342 
343 #include <stdio.h>
344 #include <stdlib.h>
345 #include <string.h>
346 #include <math.h>
347 #ifndef NO_TIMER
348 #include <sys/time.h>
349 #endif /* not NO_TIMER */
350 #ifdef CPU86
351 #include <float.h>
352 #endif /* CPU86 */
353 #ifdef LINUX
354 #include <fpu_control.h>
355 #endif /* LINUX */
356 #ifdef TRILIBRARY
357 #include "triangle.h"
358 #endif /* TRILIBRARY */
359 
360 /* A few forward declarations.                                               */
361 
362 #ifndef TRILIBRARY
363 char *readline();
364 char *findfield();
365 #endif /* not TRILIBRARY */
366 
367 /* Labels that signify the result of point location.  The result of a        */
368 /*   search indicates that the point falls in the interior of a triangle, on */
369 /*   an edge, on a vertex, or outside the mesh.                              */
370 
371 enum locateresult {INTRIANGLE, ONEDGE, ONVERTEX, OUTSIDE};
372 
373 /* Labels that signify the result of vertex insertion.  The result indicates */
374 /*   that the vertex was inserted with complete success, was inserted but    */
375 /*   encroaches upon a subsegment, was not inserted because it lies on a     */
376 /*   segment, or was not inserted because another vertex occupies the same   */
377 /*   location.                                                               */
378 
379 enum insertvertexresult {SUCCESSFULVERTEX, ENCROACHINGVERTEX, VIOLATINGVERTEX,
380                          DUPLICATEVERTEX};
381 
382 /* Labels that signify the result of direction finding.  The result          */
383 /*   indicates that a segment connecting the two query points falls within   */
384 /*   the direction triangle, along the left edge of the direction triangle,  */
385 /*   or along the right edge of the direction triangle.                      */
386 
387 enum finddirectionresult {WITHIN, LEFTCOLLINEAR, RIGHTCOLLINEAR};
388 
389 /*****************************************************************************/
390 /*                                                                           */
391 /*  The basic mesh data structures                                           */
392 /*                                                                           */
393 /*  There are three:  vertices, triangles, and subsegments (abbreviated      */
394 /*  `subseg').  These three data structures, linked by pointers, comprise    */
395 /*  the mesh.  A vertex simply represents a mesh vertex and its properties.  */
396 /*  A triangle is a triangle.  A subsegment is a special data structure used */
397 /*  to represent an impenetrable edge of the mesh (perhaps on the outer      */
398 /*  boundary, on the boundary of a hole, or part of an internal boundary     */
399 /*  separating two triangulated regions).  Subsegments represent boundaries, */
400 /*  defined by the user, that triangles may not lie across.                  */
401 /*                                                                           */
402 /*  A triangle consists of a list of three vertices, a list of three         */
403 /*  adjoining triangles, a list of three adjoining subsegments (when         */
404 /*  segments exist), an arbitrary number of optional user-defined            */
405 /*  floating-point attributes, and an optional area constraint.  The latter  */
406 /*  is an upper bound on the permissible area of each triangle in a region,  */
407 /*  used for mesh refinement.                                                */
408 /*                                                                           */
409 /*  For a triangle on a boundary of the mesh, some or all of the neighboring */
410 /*  triangles may not be present.  For a triangle in the interior of the     */
411 /*  mesh, often no neighboring subsegments are present.  Such absent         */
412 /*  triangles and subsegments are never represented by NULL pointers; they   */
413 /*  are represented by two special records:  `dummytri', the triangle that   */
414 /*  fills "outer space", and `dummysub', the omnipresent subsegment.         */
415 /*  `dummytri' and `dummysub' are used for several reasons; for instance,    */
416 /*  they can be dereferenced and their contents examined without violating   */
417 /*  protected memory.                                                        */
418 /*                                                                           */
419 /*  However, it is important to understand that a triangle includes other    */
420 /*  information as well.  The pointers to adjoining vertices, triangles, and */
421 /*  subsegments are ordered in a way that indicates their geometric relation */
422 /*  to each other.  Furthermore, each of these pointers contains orientation */
423 /*  information.  Each pointer to an adjoining triangle indicates which face */
424 /*  of that triangle is contacted.  Similarly, each pointer to an adjoining  */
425 /*  subsegment indicates which side of that subsegment is contacted, and how */
426 /*  the subsegment is oriented relative to the triangle.                     */
427 /*                                                                           */
428 /*  The data structure representing a subsegment may be thought to be        */
429 /*  abutting the edge of one or two triangle data structures:  either        */
430 /*  sandwiched between two triangles, or resting against one triangle on an  */
431 /*  exterior boundary or hole boundary.                                      */
432 /*                                                                           */
433 /*  A subsegment consists of a list of four vertices--the vertices of the    */
434 /*  subsegment, and the vertices of the segment it is a part of--a list of   */
435 /*  two adjoining subsegments, and a list of two adjoining triangles.  One   */
436 /*  of the two adjoining triangles may not be present (though there should   */
437 /*  always be one), and neighboring subsegments might not be present.        */
438 /*  Subsegments also store a user-defined integer "boundary marker".         */
439 /*  Typically, this integer is used to indicate what boundary conditions are */
440 /*  to be applied at that location in a finite element simulation.           */
441 /*                                                                           */
442 /*  Like triangles, subsegments maintain information about the relative      */
443 /*  orientation of neighboring objects.                                      */
444 /*                                                                           */
445 /*  Vertices are relatively simple.  A vertex is a list of floating-point    */
446 /*  numbers, starting with the x, and y coordinates, followed by an          */
447 /*  arbitrary number of optional user-defined floating-point attributes,     */
448 /*  followed by an integer boundary marker.  During the segment insertion    */
449 /*  phase, there is also a pointer from each vertex to a triangle that may   */
450 /*  contain it.  Each pointer is not always correct, but when one is, it     */
451 /*  speeds up segment insertion.  These pointers are assigned values once    */
452 /*  at the beginning of the segment insertion phase, and are not used or     */
453 /*  updated except during this phase.  Edge flipping during segment          */
454 /*  insertion will render some of them incorrect.  Hence, don't rely upon    */
455 /*  them for anything.                                                       */
456 /*                                                                           */
457 /*  Other than the exception mentioned above, vertices have no information   */
458 /*  about what triangles, subfacets, or subsegments they are linked to.      */
459 /*                                                                           */
460 /*****************************************************************************/
461 
462 /*****************************************************************************/
463 /*                                                                           */
464 /*  Handles                                                                  */
465 /*                                                                           */
466 /*  The oriented triangle (`otri') and oriented subsegment (`osub') data     */
467 /*  structures defined below do not themselves store any part of the mesh.   */
468 /*  The mesh itself is made of `triangle's, `subseg's, and `vertex's.        */
469 /*                                                                           */
470 /*  Oriented triangles and oriented subsegments will usually be referred to  */
471 /*  as "handles."  A handle is essentially a pointer into the mesh; it       */
472 /*  allows you to "hold" one particular part of the mesh.  Handles are used  */
473 /*  to specify the regions in which one is traversing and modifying the mesh.*/
474 /*  A single `triangle' may be held by many handles, or none at all.  (The   */
475 /*  latter case is not a memory leak, because the triangle is still          */
476 /*  connected to other triangles in the mesh.)                               */
477 /*                                                                           */
478 /*  An `otri' is a handle that holds a triangle.  It holds a specific edge   */
479 /*  of the triangle.  An `osub' is a handle that holds a subsegment.  It     */
480 /*  holds either the left or right side of the subsegment.                   */
481 /*                                                                           */
482 /*  Navigation about the mesh is accomplished through a set of mesh          */
483 /*  manipulation primitives, further below.  Many of these primitives take   */
484 /*  a handle and produce a new handle that holds the mesh near the first     */
485 /*  handle.  Other primitives take two handles and glue the corresponding    */
486 /*  parts of the mesh together.  The orientation of the handles is           */
487 /*  important.  For instance, when two triangles are glued together by the   */
488 /*  bond() primitive, they are glued at the edges on which the handles lie.  */
489 /*                                                                           */
490 /*  Because vertices have no information about which triangles they are      */
491 /*  attached to, I commonly represent a vertex by use of a handle whose      */
492 /*  origin is the vertex.  A single handle can simultaneously represent a    */
493 /*  triangle, an edge, and a vertex.                                         */
494 /*                                                                           */
495 /*****************************************************************************/
496 
497 /* The triangle data structure.  Each triangle contains three pointers to    */
498 /*   adjoining triangles, plus three pointers to vertices, plus three        */
499 /*   pointers to subsegments (declared below; these pointers are usually     */
500 /*   `dummysub').  It may or may not also contain user-defined attributes    */
501 /*   and/or a floating-point "area constraint."  It may also contain extra   */
502 /*   pointers for nodes, when the user asks for high-order elements.         */
503 /*   Because the size and structure of a `triangle' is not decided until     */
504 /*   runtime, I haven't simply declared the type `triangle' as a struct.     */
505 
506 typedef REAL **triangle;            /* Really:  typedef triangle *triangle   */
507 
508 /* An oriented triangle:  includes a pointer to a triangle and orientation.  */
509 /*   The orientation denotes an edge of the triangle.  Hence, there are      */
510 /*   three possible orientations.  By convention, each edge always points    */
511 /*   counterclockwise about the corresponding triangle.                      */
512 
513 struct otri {
514   triangle *tri;
515   int orient;                                         /* Ranges from 0 to 2. */
516 };
517 
518 /* The subsegment data structure.  Each subsegment contains two pointers to  */
519 /*   adjoining subsegments, plus four pointers to vertices, plus two         */
520 /*   pointers to adjoining triangles, plus one boundary marker, plus one     */
521 /*   segment number.                                                         */
522 
523 typedef REAL **subseg;                  /* Really:  typedef subseg *subseg   */
524 
525 /* An oriented subsegment:  includes a pointer to a subsegment and an        */
526 /*   orientation.  The orientation denotes a side of the edge.  Hence, there */
527 /*   are two possible orientations.  By convention, the edge is always       */
528 /*   directed so that the "side" denoted is the right side of the edge.      */
529 
530 struct osub {
531   subseg *ss;
532   int ssorient;                                       /* Ranges from 0 to 1. */
533 };
534 
535 /* The vertex data structure.  Each vertex is actually an array of REALs.    */
536 /*   The number of REALs is unknown until runtime.  An integer boundary      */
537 /*   marker, and sometimes a pointer to a triangle, is appended after the    */
538 /*   REALs.                                                                  */
539 
540 typedef REAL *vertex;
541 
542 /* A queue used to store encroached subsegments.  Each subsegment's vertices */
543 /*   are stored so that we can check whether a subsegment is still the same. */
544 
545 struct badsubseg {
546   subseg encsubseg;                             /* An encroached subsegment. */
547   vertex subsegorg, subsegdest;                         /* Its two vertices. */
548 };
549 
550 /* A queue used to store bad triangles.  The key is the square of the cosine */
551 /*   of the smallest angle of the triangle.  Each triangle's vertices are    */
552 /*   stored so that one can check whether a triangle is still the same.      */
553 
554 struct badtriang {
555   triangle poortri;                       /* A skinny or too-large triangle. */
556   REAL key;                             /* cos^2 of smallest (apical) angle. */
557   vertex triangorg, triangdest, triangapex;           /* Its three vertices. */
558   struct badtriang *nexttriang;             /* Pointer to next bad triangle. */
559 };
560 
561 /* A stack of triangles flipped during the most recent vertex insertion.     */
562 /*   The stack is used to undo the vertex insertion if the vertex encroaches */
563 /*   upon a subsegment.                                                      */
564 
565 struct flipstacker {
566   triangle flippedtri;                       /* A recently flipped triangle. */
567   struct flipstacker *prevflip;               /* Previous flip in the stack. */
568 };
569 
570 /* A node in a heap used to store events for the sweepline Delaunay          */
571 /*   algorithm.  Nodes do not point directly to their parents or children in */
572 /*   the heap.  Instead, each node knows its position in the heap, and can   */
573 /*   look up its parent and children in a separate array.  The `eventptr'    */
574 /*   points either to a `vertex' or to a triangle (in encoded format, so     */
575 /*   that an orientation is included).  In the latter case, the origin of    */
576 /*   the oriented triangle is the apex of a "circle event" of the sweepline  */
577 /*   algorithm.  To distinguish site events from circle events, all circle   */
578 /*   events are given an invalid (smaller than `xmin') x-coordinate `xkey'.  */
579 
580 struct event {
581   REAL xkey, ykey;                              /* Coordinates of the event. */
582   VOID *eventptr;      /* Can be a vertex or the location of a circle event. */
583   int heapposition;              /* Marks this event's position in the heap. */
584 };
585 
586 /* A node in the splay tree.  Each node holds an oriented ghost triangle     */
587 /*   that represents a boundary edge of the growing triangulation.  When a   */
588 /*   circle event covers two boundary edges with a triangle, so that they    */
589 /*   are no longer boundary edges, those edges are not immediately deleted   */
590 /*   from the tree; rather, they are lazily deleted when they are next       */
591 /*   encountered.  (Since only a random sample of boundary edges are kept    */
592 /*   in the tree, lazy deletion is faster.)  `keydest' is used to verify     */
593 /*   that a triangle is still the same as when it entered the splay tree; if */
594 /*   it has been rotated (due to a circle event), it no longer represents a  */
595 /*   boundary edge and should be deleted.                                    */
596 
597 struct splaynode {
598   struct otri keyedge;                     /* Lprev of an edge on the front. */
599   vertex keydest;           /* Used to verify that splay node is still live. */
600   struct splaynode *lchild, *rchild;              /* Children in splay tree. */
601 };
602 
603 /* A type used to allocate memory.  firstblock is the first block of items.  */
604 /*   nowblock is the block from which items are currently being allocated.   */
605 /*   nextitem points to the next slab of free memory for an item.            */
606 /*   deaditemstack is the head of a linked list (stack) of deallocated items */
607 /*   that can be recycled.  unallocateditems is the number of items that     */
608 /*   remain to be allocated from nowblock.                                   */
609 /*                                                                           */
610 /* Traversal is the process of walking through the entire list of items, and */
611 /*   is separate from allocation.  Note that a traversal will visit items on */
612 /*   the "deaditemstack" stack as well as live items.  pathblock points to   */
613 /*   the block currently being traversed.  pathitem points to the next item  */
614 /*   to be traversed.  pathitemsleft is the number of items that remain to   */
615 /*   be traversed in pathblock.                                              */
616 /*                                                                           */
617 /* alignbytes determines how new records should be aligned in memory.        */
618 /*   itembytes is the length of a record in bytes (after rounding up).       */
619 /*   itemsperblock is the number of items allocated at once in a single      */
620 /*   block.  itemsfirstblock is the number of items in the first block,      */
621 /*   which can vary from the others.  items is the number of currently       */
622 /*   allocated items.  maxitems is the maximum number of items that have     */
623 /*   been allocated at once; it is the current number of items plus the      */
624 /*   number of records kept on deaditemstack.                                */
625 
626 struct memorypool {
627   VOID **firstblock, **nowblock;
628   VOID *nextitem;
629   VOID *deaditemstack;
630   VOID **pathblock;
631   VOID *pathitem;
632   int alignbytes;
633   int itembytes;
634   int itemsperblock;
635   int itemsfirstblock;
636   long items, maxitems;
637   int unallocateditems;
638   int pathitemsleft;
639 };
640 
641 
642 /* Global constants.                                                         */
643 
644 REAL splitter;       /* Used to split REAL factors for exact multiplication. */
645 REAL epsilon;                             /* Floating-point machine epsilon. */
646 REAL resulterrbound;
647 REAL ccwerrboundA, ccwerrboundB, ccwerrboundC;
648 REAL iccerrboundA, iccerrboundB, iccerrboundC;
649 REAL o3derrboundA, o3derrboundB, o3derrboundC;
650 
651 /* Random number seed is not constant, but I've made it global anyway.       */
652 
653 unsigned long randomseed;                     /* Current random number seed. */
654 
655 
656 /* Mesh data structure.  Triangle operates on only one mesh, but the mesh    */
657 /*   structure is used (instead of global variables) to allow reentrancy.    */
658 
659 struct mesh {
660 
661 /* Variables used to allocate memory for triangles, subsegments, vertices,   */
662 /*   viri (triangles being eaten), encroached segments, bad (skinny or too   */
663 /*   large) triangles, and splay tree nodes.                                 */
664 
665   struct memorypool triangles;
666   struct memorypool subsegs;
667   struct memorypool vertices;
668   struct memorypool viri;
669   struct memorypool badsubsegs;
670   struct memorypool badtriangles;
671   struct memorypool flipstackers;
672   struct memorypool splaynodes;
673 
674 /* Variables that maintain the bad triangle queues.  The queues are          */
675 /*   ordered from 4095 (highest priority) to 0 (lowest priority).            */
676 
677   struct badtriang *queuefront[4096];
678   struct badtriang *queuetail[4096];
679   int nextnonemptyq[4096];
680   int firstnonemptyq;
681 
682 /* Variable that maintains the stack of recently flipped triangles.          */
683 
684   struct flipstacker *lastflip;
685 
686 /* Other variables. */
687 
688   REAL xmin, xmax, ymin, ymax;                            /* x and y bounds. */
689   REAL xminextreme;      /* Nonexistent x value used as a flag in sweepline. */
690   int invertices;                               /* Number of input vertices. */
691   int inelements;                              /* Number of input triangles. */
692   int insegments;                               /* Number of input segments. */
693   int holes;                                       /* Number of input holes. */
694   int regions;                                   /* Number of input regions. */
695   int undeads;    /* Number of input vertices that don't appear in the mesh. */
696   long edges;                                     /* Number of output edges. */
697   int mesh_dim;                                /* Dimension (ought to be 2). */
698   int nextras;                           /* Number of attributes per vertex. */
699   int eextras;                         /* Number of attributes per triangle. */
700   long hullsize;                          /* Number of edges in convex hull. */
701   int steinerleft;                 /* Number of Steiner points not yet used. */
702   int vertexmarkindex;         /* Index to find boundary marker of a vertex. */
703   int vertex2triindex;     /* Index to find a triangle adjacent to a vertex. */
704   int highorderindex;  /* Index to find extra nodes for high-order elements. */
705   int elemattribindex;            /* Index to find attributes of a triangle. */
706   int areaboundindex;             /* Index to find area bound of a triangle. */
707   int checksegments;         /* Are there segments in the triangulation yet? */
708   int checkquality;                  /* Has quality triangulation begun yet? */
709   int readnodefile;                           /* Has a .node file been read? */
710   long samples;              /* Number of random samples for point location. */
711 
712   long incirclecount;                 /* Number of incircle tests performed. */
713   long counterclockcount;     /* Number of counterclockwise tests performed. */
714   long orient3dcount;           /* Number of 3D orientation tests performed. */
715   long hyperbolacount;      /* Number of right-of-hyperbola tests performed. */
716   long circumcentercount;  /* Number of circumcenter calculations performed. */
717   long circletopcount;       /* Number of circle top calculations performed. */
718 
719 /* Triangular bounding box vertices.                                         */
720 
721   vertex infvertex1, infvertex2, infvertex3;
722 
723 /* Pointer to the `triangle' that occupies all of "outer space."             */
724 
725   triangle *dummytri;
726   triangle *dummytribase;    /* Keep base address so we can free() it later. */
727 
728 /* Pointer to the omnipresent subsegment.  Referenced by any triangle or     */
729 /*   subsegment that isn't really connected to a subsegment at that          */
730 /*   location.                                                               */
731 
732   subseg *dummysub;
733   subseg *dummysubbase;      /* Keep base address so we can free() it later. */
734 
735 /* Pointer to a recently visited triangle.  Improves point location if       */
736 /*   proximate vertices are inserted sequentially.                           */
737 
738   struct otri recenttri;
739 
740 };                                                  /* End of `struct mesh'. */
741 
742 
743 /* Data structure for command line switches and file names.  This structure  */
744 /*   is used (instead of global variables) to allow reentrancy.              */
745 
746 struct behavior {
747 
748 /* Switches for the triangulator.                                            */
749 /*   poly: -p switch.  refine: -r switch.                                    */
750 /*   quality: -q switch.                                                     */
751 /*     minangle: minimum angle bound, specified after -q switch.             */
752 /*     goodangle: cosine squared of minangle.                                */
753 /*     offconstant: constant used to place off-center Steiner points.        */
754 /*   vararea: -a switch without number.                                      */
755 /*   fixedarea: -a switch with number.                                       */
756 /*     maxarea: maximum area bound, specified after -a switch.               */
757 /*   usertest: -u switch.                                                    */
758 /*   regionattrib: -A switch.  convex: -c switch.                            */
759 /*   weighted: 1 for -w switch, 2 for -W switch.  jettison: -j switch        */
760 /*   firstnumber: inverse of -z switch.  All items are numbered starting     */
761 /*     from `firstnumber'.                                                   */
762 /*   edgesout: -e switch.  voronoi: -v switch.                               */
763 /*   neighbors: -n switch.  geomview: -g switch.                             */
764 /*   nobound: -B switch.  nopolywritten: -P switch.                          */
765 /*   nonodewritten: -N switch.  noelewritten: -E switch.                     */
766 /*   noiterationnum: -I switch.  noholes: -O switch.                         */
767 /*   noexact: -X switch.                                                     */
768 /*   order: element order, specified after -o switch.                        */
769 /*   nobisect: count of how often -Y switch is selected.                     */
770 /*   steiner: maximum number of Steiner points, specified after -S switch.   */
771 /*   incremental: -i switch.  sweepline: -F switch.                          */
772 /*   dwyer: inverse of -l switch.                                            */
773 /*   splitseg: -s switch.                                                    */
774 /*   conformdel: -D switch.  docheck: -C switch.                             */
775 /*   quiet: -Q switch.  verbose: count of how often -V switch is selected.   */
776 /*   usesegments: -p, -r, -q, or -c switch; determines whether segments are  */
777 /*     used at all.                                                          */
778 /*                                                                           */
779 /* Read the instructions to find out the meaning of these switches.          */
780 
781   int poly, refine, quality, vararea, fixedarea, usertest;
782   int regionattrib, convex, weighted, jettison;
783   int firstnumber;
784   int edgesout, voronoi, neighbors, geomview;
785   int nobound, nopolywritten, nonodewritten, noelewritten, noiterationnum;
786   int noholes, noexact, conformdel;
787   int incremental, sweepline, dwyer;
788   int splitseg;
789   int docheck;
790   int quiet, verbose;
791   int usesegments;
792   int order;
793   int nobisect;
794   int steiner;
795   REAL minangle, goodangle, offconstant;
796   REAL maxarea;
797 
798 /* Variables for file names.                                                 */
799 
800 #ifndef TRILIBRARY
801   char innodefilename[FILENAMESIZE];
802   char inelefilename[FILENAMESIZE];
803   char inpolyfilename[FILENAMESIZE];
804   char areafilename[FILENAMESIZE];
805   char outnodefilename[FILENAMESIZE];
806   char outelefilename[FILENAMESIZE];
807   char outpolyfilename[FILENAMESIZE];
808   char edgefilename[FILENAMESIZE];
809   char vnodefilename[FILENAMESIZE];
810   char vedgefilename[FILENAMESIZE];
811   char neighborfilename[FILENAMESIZE];
812   char offfilename[FILENAMESIZE];
813 #endif /* not TRILIBRARY */
814 
815 };                                              /* End of `struct behavior'. */
816 
817 
818 /*****************************************************************************/
819 /*                                                                           */
820 /*  Mesh manipulation primitives.  Each triangle contains three pointers to  */
821 /*  other triangles, with orientations.  Each pointer points not to the      */
822 /*  first byte of a triangle, but to one of the first three bytes of a       */
823 /*  triangle.  It is necessary to extract both the triangle itself and the   */
824 /*  orientation.  To save memory, I keep both pieces of information in one   */
825 /*  pointer.  To make this possible, I assume that all triangles are aligned */
826 /*  to four-byte boundaries.  The decode() routine below decodes a pointer,  */
827 /*  extracting an orientation (in the range 0 to 2) and a pointer to the     */
828 /*  beginning of a triangle.  The encode() routine compresses a pointer to a */
829 /*  triangle and an orientation into a single pointer.  My assumptions that  */
830 /*  triangles are four-byte-aligned and that the `unsigned long' type is     */
831 /*  long enough to hold a pointer are two of the few kludges in this program.*/
832 /*                                                                           */
833 /*  Subsegments are manipulated similarly.  A pointer to a subsegment        */
834 /*  carries both an address and an orientation in the range 0 to 1.          */
835 /*                                                                           */
836 /*  The other primitives take an oriented triangle or oriented subsegment,   */
837 /*  and return an oriented triangle or oriented subsegment or vertex; or     */
838 /*  they change the connections in the data structure.                       */
839 /*                                                                           */
840 /*  Below, triangles and subsegments are denoted by their vertices.  The     */
841 /*  triangle abc has origin (org) a, destination (dest) b, and apex (apex)   */
842 /*  c.  These vertices occur in counterclockwise order about the triangle.   */
843 /*  The handle abc may simultaneously denote vertex a, edge ab, and triangle */
844 /*  abc.                                                                     */
845 /*                                                                           */
846 /*  Similarly, the subsegment ab has origin (sorg) a and destination (sdest) */
847 /*  b.  If ab is thought to be directed upward (with b directly above a),    */
848 /*  then the handle ab is thought to grasp the right side of ab, and may     */
849 /*  simultaneously denote vertex a and edge ab.                              */
850 /*                                                                           */
851 /*  An asterisk (*) denotes a vertex whose identity is unknown.              */
852 /*                                                                           */
853 /*  Given this notation, a partial list of mesh manipulation primitives      */
854 /*  follows.                                                                 */
855 /*                                                                           */
856 /*                                                                           */
857 /*  For triangles:                                                           */
858 /*                                                                           */
859 /*  sym:  Find the abutting triangle; same edge.                             */
860 /*  sym(abc) -> ba*                                                          */
861 /*                                                                           */
862 /*  lnext:  Find the next edge (counterclockwise) of a triangle.             */
863 /*  lnext(abc) -> bca                                                        */
864 /*                                                                           */
865 /*  lprev:  Find the previous edge (clockwise) of a triangle.                */
866 /*  lprev(abc) -> cab                                                        */
867 /*                                                                           */
868 /*  onext:  Find the next edge counterclockwise with the same origin.        */
869 /*  onext(abc) -> ac*                                                        */
870 /*                                                                           */
871 /*  oprev:  Find the next edge clockwise with the same origin.               */
872 /*  oprev(abc) -> a*b                                                        */
873 /*                                                                           */
874 /*  dnext:  Find the next edge counterclockwise with the same destination.   */
875 /*  dnext(abc) -> *ba                                                        */
876 /*                                                                           */
877 /*  dprev:  Find the next edge clockwise with the same destination.          */
878 /*  dprev(abc) -> cb*                                                        */
879 /*                                                                           */
880 /*  rnext:  Find the next edge (counterclockwise) of the adjacent triangle.  */
881 /*  rnext(abc) -> *a*                                                        */
882 /*                                                                           */
883 /*  rprev:  Find the previous edge (clockwise) of the adjacent triangle.     */
884 /*  rprev(abc) -> b**                                                        */
885 /*                                                                           */
886 /*  org:  Origin          dest:  Destination          apex:  Apex            */
887 /*  org(abc) -> a         dest(abc) -> b              apex(abc) -> c         */
888 /*                                                                           */
889 /*  bond:  Bond two triangles together at the resepective handles.           */
890 /*  bond(abc, bad)                                                           */
891 /*                                                                           */
892 /*                                                                           */
893 /*  For subsegments:                                                         */
894 /*                                                                           */
895 /*  ssym:  Reverse the orientation of a subsegment.                          */
896 /*  ssym(ab) -> ba                                                           */
897 /*                                                                           */
898 /*  spivot:  Find adjoining subsegment with the same origin.                 */
899 /*  spivot(ab) -> a*                                                         */
900 /*                                                                           */
901 /*  snext:  Find next subsegment in sequence.                                */
902 /*  snext(ab) -> b*                                                          */
903 /*                                                                           */
904 /*  sorg:  Origin                      sdest:  Destination                   */
905 /*  sorg(ab) -> a                      sdest(ab) -> b                        */
906 /*                                                                           */
907 /*  sbond:  Bond two subsegments together at the respective origins.         */
908 /*  sbond(ab, ac)                                                            */
909 /*                                                                           */
910 /*                                                                           */
911 /*  For interacting tetrahedra and subfacets:                                */
912 /*                                                                           */
913 /*  tspivot:  Find a subsegment abutting a triangle.                         */
914 /*  tspivot(abc) -> ba                                                       */
915 /*                                                                           */
916 /*  stpivot:  Find a triangle abutting a subsegment.                         */
917 /*  stpivot(ab) -> ba*                                                       */
918 /*                                                                           */
919 /*  tsbond:  Bond a triangle to a subsegment.                                */
920 /*  tsbond(abc, ba)                                                          */
921 /*                                                                           */
922 /*****************************************************************************/
923 
924 /********* Mesh manipulation primitives begin here                   *********/
925 /**                                                                         **/
926 /**                                                                         **/
927 
928 /* Fast lookup arrays to speed some of the mesh manipulation primitives.     */
929 
930 int plus1mod3[3] = {1, 2, 0};
931 int minus1mod3[3] = {2, 0, 1};
932 
933 /********* Primitives for triangles                                  *********/
934 /*                                                                           */
935 /*                                                                           */
936 
937 /* decode() converts a pointer to an oriented triangle.  The orientation is  */
938 /*   extracted from the two least significant bits of the pointer.           */
939 
940 #define decode(ptr, otri)                                                     \
941   (otri).orient = (int) ((unsigned long) (ptr) & (unsigned long) 3l);         \
942   (otri).tri = (triangle *)                                                   \
943                   ((unsigned long) (ptr) ^ (unsigned long) (otri).orient)
944 
945 /* encode() compresses an oriented triangle into a single pointer.  It       */
946 /*   relies on the assumption that all triangles are aligned to four-byte    */
947 /*   boundaries, so the two least significant bits of (otri).tri are zero.   */
948 
949 #define encode(otri)                                                          \
950   (triangle) ((unsigned long) (otri).tri | (unsigned long) (otri).orient)
951 
952 /* The following handle manipulation primitives are all described by Guibas  */
953 /*   and Stolfi.  However, Guibas and Stolfi use an edge-based data          */
954 /*   structure, whereas I use a triangle-based data structure.               */
955 
956 /* sym() finds the abutting triangle, on the same edge.  Note that the edge  */
957 /*   direction is necessarily reversed, because the handle specified by an   */
958 /*   oriented triangle is directed counterclockwise around the triangle.     */
959 
960 #define sym(otri1, otri2)                                                     \
961   ptr = (otri1).tri[(otri1).orient];                                          \
962   decode(ptr, otri2);
963 
964 #define symself(otri)                                                         \
965   ptr = (otri).tri[(otri).orient];                                            \
966   decode(ptr, otri);
967 
968 /* lnext() finds the next edge (counterclockwise) of a triangle.             */
969 
970 #define lnext(otri1, otri2)                                                   \
971   (otri2).tri = (otri1).tri;                                                  \
972   (otri2).orient = plus1mod3[(otri1).orient]
973 
974 #define lnextself(otri)                                                       \
975   (otri).orient = plus1mod3[(otri).orient]
976 
977 /* lprev() finds the previous edge (clockwise) of a triangle.                */
978 
979 #define lprev(otri1, otri2)                                                   \
980   (otri2).tri = (otri1).tri;                                                  \
981   (otri2).orient = minus1mod3[(otri1).orient]
982 
983 #define lprevself(otri)                                                       \
984   (otri).orient = minus1mod3[(otri).orient]
985 
986 /* onext() spins counterclockwise around a vertex; that is, it finds the     */
987 /*   next edge with the same origin in the counterclockwise direction.  This */
988 /*   edge is part of a different triangle.                                   */
989 
990 #define onext(otri1, otri2)                                                   \
991   lprev(otri1, otri2);                                                        \
992   symself(otri2);
993 
994 #define onextself(otri)                                                       \
995   lprevself(otri);                                                            \
996   symself(otri);
997 
998 /* oprev() spins clockwise around a vertex; that is, it finds the next edge  */
999 /*   with the same origin in the clockwise direction.  This edge is part of  */
1000 /*   a different triangle.                                                   */
1001 
1002 #define oprev(otri1, otri2)                                                   \
1003   sym(otri1, otri2);                                                          \
1004   lnextself(otri2);
1005 
1006 #define oprevself(otri)                                                       \
1007   symself(otri);                                                              \
1008   lnextself(otri);
1009 
1010 /* dnext() spins counterclockwise around a vertex; that is, it finds the     */
1011 /*   next edge with the same destination in the counterclockwise direction.  */
1012 /*   This edge is part of a different triangle.                              */
1013 
1014 #define dnext(otri1, otri2)                                                   \
1015   sym(otri1, otri2);                                                          \
1016   lprevself(otri2);
1017 
1018 #define dnextself(otri)                                                       \
1019   symself(otri);                                                              \
1020   lprevself(otri);
1021 
1022 /* dprev() spins clockwise around a vertex; that is, it finds the next edge  */
1023 /*   with the same destination in the clockwise direction.  This edge is     */
1024 /*   part of a different triangle.                                           */
1025 
1026 #define dprev(otri1, otri2)                                                   \
1027   lnext(otri1, otri2);                                                        \
1028   symself(otri2);
1029 
1030 #define dprevself(otri)                                                       \
1031   lnextself(otri);                                                            \
1032   symself(otri);
1033 
1034 /* rnext() moves one edge counterclockwise about the adjacent triangle.      */
1035 /*   (It's best understood by reading Guibas and Stolfi.  It involves        */
1036 /*   changing triangles twice.)                                              */
1037 
1038 #define rnext(otri1, otri2)                                                   \
1039   sym(otri1, otri2);                                                          \
1040   lnextself(otri2);                                                           \
1041   symself(otri2);
1042 
1043 #define rnextself(otri)                                                       \
1044   symself(otri);                                                              \
1045   lnextself(otri);                                                            \
1046   symself(otri);
1047 
1048 /* rprev() moves one edge clockwise about the adjacent triangle.             */
1049 /*   (It's best understood by reading Guibas and Stolfi.  It involves        */
1050 /*   changing triangles twice.)                                              */
1051 
1052 #define rprev(otri1, otri2)                                                   \
1053   sym(otri1, otri2);                                                          \
1054   lprevself(otri2);                                                           \
1055   symself(otri2);
1056 
1057 #define rprevself(otri)                                                       \
1058   symself(otri);                                                              \
1059   lprevself(otri);                                                            \
1060   symself(otri);
1061 
1062 /* These primitives determine or set the origin, destination, or apex of a   */
1063 /* triangle.                                                                 */
1064 
1065 #define org(otri, vertexptr)                                                  \
1066   vertexptr = (vertex) (otri).tri[plus1mod3[(otri).orient] + 3]
1067 
1068 #define dest(otri, vertexptr)                                                 \
1069   vertexptr = (vertex) (otri).tri[minus1mod3[(otri).orient] + 3]
1070 
1071 #define apex(otri, vertexptr)                                                 \
1072   vertexptr = (vertex) (otri).tri[(otri).orient + 3]
1073 
1074 #define setorg(otri, vertexptr)                                               \
1075   (otri).tri[plus1mod3[(otri).orient] + 3] = (triangle) vertexptr
1076 
1077 #define setdest(otri, vertexptr)                                              \
1078   (otri).tri[minus1mod3[(otri).orient] + 3] = (triangle) vertexptr
1079 
1080 #define setapex(otri, vertexptr)                                              \
1081   (otri).tri[(otri).orient + 3] = (triangle) vertexptr
1082 
1083 /* Bond two triangles together.                                              */
1084 
1085 #define bond(otri1, otri2)                                                    \
1086   (otri1).tri[(otri1).orient] = encode(otri2);                                \
1087   (otri2).tri[(otri2).orient] = encode(otri1)
1088 
1089 /* Dissolve a bond (from one side).  Note that the other triangle will still */
1090 /*   think it's connected to this triangle.  Usually, however, the other     */
1091 /*   triangle is being deleted entirely, or bonded to another triangle, so   */
1092 /*   it doesn't matter.                                                      */
1093 
1094 #define dissolve(otri)                                                        \
1095   (otri).tri[(otri).orient] = (triangle) m->dummytri
1096 
1097 /* Copy an oriented triangle.                                                */
1098 
1099 #define otricopy(otri1, otri2)                                                \
1100   (otri2).tri = (otri1).tri;                                                  \
1101   (otri2).orient = (otri1).orient
1102 
1103 /* Test for equality of oriented triangles.                                  */
1104 
1105 #define otriequal(otri1, otri2)                                               \
1106   (((otri1).tri == (otri2).tri) &&                                            \
1107    ((otri1).orient == (otri2).orient))
1108 
1109 /* Primitives to infect or cure a triangle with the virus.  These rely on    */
1110 /*   the assumption that all subsegments are aligned to four-byte boundaries.*/
1111 
1112 #define infect(otri)                                                          \
1113   (otri).tri[6] = (triangle)                                                  \
1114                     ((unsigned long) (otri).tri[6] | (unsigned long) 2l)
1115 
1116 #define uninfect(otri)                                                        \
1117   (otri).tri[6] = (triangle)                                                  \
1118                     ((unsigned long) (otri).tri[6] & ~ (unsigned long) 2l)
1119 
1120 /* Test a triangle for viral infection.                                      */
1121 
1122 #define infected(otri)                                                        \
1123   (((unsigned long) (otri).tri[6] & (unsigned long) 2l) != 0l)
1124 
1125 /* Check or set a triangle's attributes.                                     */
1126 
1127 #define elemattribute(otri, attnum)                                           \
1128   ((REAL *) (otri).tri)[m->elemattribindex + (attnum)]
1129 
1130 #define setelemattribute(otri, attnum, value)                                 \
1131   ((REAL *) (otri).tri)[m->elemattribindex + (attnum)] = value
1132 
1133 /* Check or set a triangle's maximum area bound.                             */
1134 
1135 #define areabound(otri)  ((REAL *) (otri).tri)[m->areaboundindex]
1136 
1137 #define setareabound(otri, value)                                             \
1138   ((REAL *) (otri).tri)[m->areaboundindex] = value
1139 
1140 /* Check or set a triangle's deallocation.  Its second pointer is set to     */
1141 /*   NULL to indicate that it is not allocated.  (Its first pointer is used  */
1142 /*   for the stack of dead items.)  Its fourth pointer (its first vertex)    */
1143 /*   is set to NULL in case a `badtriang' structure points to it.            */
1144 
1145 #define deadtri(tria)  ((tria)[1] == (triangle) NULL)
1146 
1147 #define killtri(tria)                                                         \
1148   (tria)[1] = (triangle) NULL;                                                \
1149   (tria)[3] = (triangle) NULL
1150 
1151 /********* Primitives for subsegments                                *********/
1152 /*                                                                           */
1153 /*                                                                           */
1154 
1155 /* sdecode() converts a pointer to an oriented subsegment.  The orientation  */
1156 /*   is extracted from the least significant bit of the pointer.  The two    */
1157 /*   least significant bits (one for orientation, one for viral infection)   */
1158 /*   are masked out to produce the real pointer.                             */
1159 
1160 #define sdecode(sptr, osub)                                                   \
1161   (osub).ssorient = (int) ((unsigned long) (sptr) & (unsigned long) 1l);      \
1162   (osub).ss = (subseg *)                                                      \
1163               ((unsigned long) (sptr) & ~ (unsigned long) 3l)
1164 
1165 /* sencode() compresses an oriented subsegment into a single pointer.  It    */
1166 /*   relies on the assumption that all subsegments are aligned to two-byte   */
1167 /*   boundaries, so the least significant bit of (osub).ss is zero.          */
1168 
1169 #define sencode(osub)                                                         \
1170   (subseg) ((unsigned long) (osub).ss | (unsigned long) (osub).ssorient)
1171 
1172 /* ssym() toggles the orientation of a subsegment.                           */
1173 
1174 #define ssym(osub1, osub2)                                                    \
1175   (osub2).ss = (osub1).ss;                                                    \
1176   (osub2).ssorient = 1 - (osub1).ssorient
1177 
1178 #define ssymself(osub)                                                        \
1179   (osub).ssorient = 1 - (osub).ssorient
1180 
1181 /* spivot() finds the other subsegment (from the same segment) that shares   */
1182 /*   the same origin.                                                        */
1183 
1184 #define spivot(osub1, osub2)                                                  \
1185   sptr = (osub1).ss[(osub1).ssorient];                                        \
1186   sdecode(sptr, osub2)
1187 
1188 #define spivotself(osub)                                                      \
1189   sptr = (osub).ss[(osub).ssorient];                                          \
1190   sdecode(sptr, osub)
1191 
1192 /* snext() finds the next subsegment (from the same segment) in sequence;    */
1193 /*   one whose origin is the input subsegment's destination.                 */
1194 
1195 #define snext(osub1, osub2)                                                   \
1196   sptr = (osub1).ss[1 - (osub1).ssorient];                                    \
1197   sdecode(sptr, osub2)
1198 
1199 #define snextself(osub)                                                       \
1200   sptr = (osub).ss[1 - (osub).ssorient];                                      \
1201   sdecode(sptr, osub)
1202 
1203 /* These primitives determine or set the origin or destination of a          */
1204 /*   subsegment or the segment that includes it.                             */
1205 
1206 #define sorg(osub, vertexptr)                                                 \
1207   vertexptr = (vertex) (osub).ss[2 + (osub).ssorient]
1208 
1209 #define sdest(osub, vertexptr)                                                \
1210   vertexptr = (vertex) (osub).ss[3 - (osub).ssorient]
1211 
1212 #define setsorg(osub, vertexptr)                                              \
1213   (osub).ss[2 + (osub).ssorient] = (subseg) vertexptr
1214 
1215 #define setsdest(osub, vertexptr)                                             \
1216   (osub).ss[3 - (osub).ssorient] = (subseg) vertexptr
1217 
1218 #define segorg(osub, vertexptr)                                               \
1219   vertexptr = (vertex) (osub).ss[4 + (osub).ssorient]
1220 
1221 #define segdest(osub, vertexptr)                                              \
1222   vertexptr = (vertex) (osub).ss[5 - (osub).ssorient]
1223 
1224 #define setsegorg(osub, vertexptr)                                            \
1225   (osub).ss[4 + (osub).ssorient] = (subseg) vertexptr
1226 
1227 #define setsegdest(osub, vertexptr)                                           \
1228   (osub).ss[5 - (osub).ssorient] = (subseg) vertexptr
1229 
1230 /* These primitives read or set a boundary marker.  Boundary markers are     */
1231 /*   used to hold user-defined tags for setting boundary conditions in       */
1232 /*   finite element solvers.                                                 */
1233 
1234 #define mark(osub)  (* (int *) ((osub).ss + 8))
1235 
1236 #define setmark(osub, value)                                                  \
1237   * (int *) ((osub).ss + 8) = value
1238 
1239 /* Bond two subsegments together.                                            */
1240 
1241 #define sbond(osub1, osub2)                                                   \
1242   (osub1).ss[(osub1).ssorient] = sencode(osub2);                              \
1243   (osub2).ss[(osub2).ssorient] = sencode(osub1)
1244 
1245 /* Dissolve a subsegment bond (from one side).  Note that the other          */
1246 /*   subsegment will still think it's connected to this subsegment.          */
1247 
1248 #define sdissolve(osub)                                                       \
1249   (osub).ss[(osub).ssorient] = (subseg) m->dummysub
1250 
1251 /* Copy a subsegment.                                                        */
1252 
1253 #define subsegcopy(osub1, osub2)                                              \
1254   (osub2).ss = (osub1).ss;                                                    \
1255   (osub2).ssorient = (osub1).ssorient
1256 
1257 /* Test for equality of subsegments.                                         */
1258 
1259 #define subsegequal(osub1, osub2)                                             \
1260   (((osub1).ss == (osub2).ss) &&                                              \
1261    ((osub1).ssorient == (osub2).ssorient))
1262 
1263 /* Check or set a subsegment's deallocation.  Its second pointer is set to   */
1264 /*   NULL to indicate that it is not allocated.  (Its first pointer is used  */
1265 /*   for the stack of dead items.)  Its third pointer (its first vertex)     */
1266 /*   is set to NULL in case a `badsubseg' structure points to it.            */
1267 
1268 #define deadsubseg(sub)  ((sub)[1] == (subseg) NULL)
1269 
1270 #define killsubseg(sub)                                                       \
1271   (sub)[1] = (subseg) NULL;                                                   \
1272   (sub)[2] = (subseg) NULL
1273 
1274 /********* Primitives for interacting triangles and subsegments      *********/
1275 /*                                                                           */
1276 /*                                                                           */
1277 
1278 /* tspivot() finds a subsegment abutting a triangle.                         */
1279 
1280 #define tspivot(otri, osub)                                                   \
1281   sptr = (subseg) (otri).tri[6 + (otri).orient];                              \
1282   sdecode(sptr, osub)
1283 
1284 /* stpivot() finds a triangle abutting a subsegment.  It requires that the   */
1285 /*   variable `ptr' of type `triangle' be defined.                           */
1286 
1287 #define stpivot(osub, otri)                                                   \
1288   ptr = (triangle) (osub).ss[6 + (osub).ssorient];                            \
1289   decode(ptr, otri)
1290 
1291 /* Bond a triangle to a subsegment.                                          */
1292 
1293 #define tsbond(otri, osub)                                                    \
1294   (otri).tri[6 + (otri).orient] = (triangle) sencode(osub);                   \
1295   (osub).ss[6 + (osub).ssorient] = (subseg) encode(otri)
1296 
1297 /* Dissolve a bond (from the triangle side).                                 */
1298 
1299 #define tsdissolve(otri)                                                      \
1300   (otri).tri[6 + (otri).orient] = (triangle) m->dummysub
1301 
1302 /* Dissolve a bond (from the subsegment side).                               */
1303 
1304 #define stdissolve(osub)                                                      \
1305   (osub).ss[6 + (osub).ssorient] = (subseg) m->dummytri
1306 
1307 /********* Primitives for vertices                                   *********/
1308 /*                                                                           */
1309 /*                                                                           */
1310 
1311 #define vertexmark(vx)  ((int *) (vx))[m->vertexmarkindex]
1312 
1313 #define setvertexmark(vx, value)                                              \
1314   ((int *) (vx))[m->vertexmarkindex] = value
1315 
1316 #define vertextype(vx)  ((int *) (vx))[m->vertexmarkindex + 1]
1317 
1318 #define setvertextype(vx, value)                                              \
1319   ((int *) (vx))[m->vertexmarkindex + 1] = value
1320 
1321 #define vertex2tri(vx)  ((triangle *) (vx))[m->vertex2triindex]
1322 
1323 #define setvertex2tri(vx, value)                                              \
1324   ((triangle *) (vx))[m->vertex2triindex] = value
1325 
1326 /**                                                                         **/
1327 /**                                                                         **/
1328 /********* Mesh manipulation primitives end here                     *********/
1329 
1330 /********* User-defined triangle evaluation routine begins here      *********/
1331 /**                                                                         **/
1332 /**                                                                         **/
1333 
1334 /*****************************************************************************/
1335 /*                                                                           */
1336 /*  triunsuitable()   Determine if a triangle is unsuitable, and thus must   */
1337 /*                    be further refined.                                    */
1338 /*                                                                           */
1339 /*  You may write your own procedure that decides whether or not a selected  */
1340 /*  triangle is too big (and needs to be refined).  There are two ways to do */
1341 /*  this.                                                                    */
1342 /*                                                                           */
1343 /*  (1)  Modify the procedure `triunsuitable' below, then recompile          */
1344 /*  Triangle.                                                                */
1345 /*                                                                           */
1346 /*  (2)  Define the symbol EXTERNAL_TEST (either by adding the definition    */
1347 /*  to this file, or by using the appropriate compiler switch).  This way,   */
1348 /*  you can compile triangle.c separately from your test.  Write your own    */
1349 /*  `triunsuitable' procedure in a separate C file (using the same prototype */
1350 /*  as below).  Compile it and link the object code with triangle.o.         */
1351 /*                                                                           */
1352 /*  This procedure returns 1 if the triangle is too large and should be      */
1353 /*  refined; 0 otherwise.                                                    */
1354 /*                                                                           */
1355 /*****************************************************************************/
1356 
1357 #ifdef EXTERNAL_TEST
1358 
1359 int triunsuitable();
1360 
1361 #else /* not EXTERNAL_TEST */
1362 
1363 #ifdef ANSI_DECLARATORS
1364 int triunsuitable(vertex triorg, vertex tridest, vertex triapex, REAL area)
1365 #else /* not ANSI_DECLARATORS */
1366 int triunsuitable(triorg, tridest, triapex, area)
1367 vertex triorg;                              /* The triangle's origin vertex. */
1368 vertex tridest;                        /* The triangle's destination vertex. */
1369 vertex triapex;                               /* The triangle's apex vertex. */
1370 REAL area;                                      /* The area of the triangle. */
1371 #endif /* not ANSI_DECLARATORS */
1372 
1373 {
1374   REAL dxoa, dxda, dxod;
1375   REAL dyoa, dyda, dyod;
1376   REAL oalen, dalen, odlen;
1377   REAL maxlen;
1378 
1379   dxoa = triorg[0] - triapex[0];
1380   dyoa = triorg[1] - triapex[1];
1381   dxda = tridest[0] - triapex[0];
1382   dyda = tridest[1] - triapex[1];
1383   dxod = triorg[0] - tridest[0];
1384   dyod = triorg[1] - tridest[1];
1385   /* Find the squares of the lengths of the triangle's three edges. */
1386   oalen = dxoa * dxoa + dyoa * dyoa;
1387   dalen = dxda * dxda + dyda * dyda;
1388   odlen = dxod * dxod + dyod * dyod;
1389   /* Find the square of the length of the longest edge. */
1390   maxlen = (dalen > oalen) ? dalen : oalen;
1391   maxlen = (odlen > maxlen) ? odlen : maxlen;
1392 
1393   if (maxlen > 0.05 * (triorg[0] * triorg[0] + triorg[1] * triorg[1]) + 0.02) {
1394     return 1;
1395   } else {
1396     return 0;
1397   }
1398 }
1399 
1400 #endif /* not EXTERNAL_TEST */
1401 
1402 /**                                                                         **/
1403 /**                                                                         **/
1404 /********* User-defined triangle evaluation routine ends here        *********/
1405 
1406 /********* Memory allocation and program exit wrappers begin here    *********/
1407 /**                                                                         **/
1408 /**                                                                         **/
1409 
1410 #ifdef ANSI_DECLARATORS
1411 void triexit(int status)
1412 #else /* not ANSI_DECLARATORS */
1413 void triexit(status)
1414 int status;
1415 #endif /* not ANSI_DECLARATORS */
1416 
1417 {
1418   exit(status);
1419 }
1420 
1421 #ifdef ANSI_DECLARATORS
1422 VOID *trimalloc(int size)
1423 #else /* not ANSI_DECLARATORS */
1424 VOID *trimalloc(size)
1425 int size;
1426 #endif /* not ANSI_DECLARATORS */
1427 
1428 {
1429   VOID *memptr;
1430 
1431   memptr = (VOID *) malloc((unsigned int) size);
1432   if (memptr == (VOID *) NULL) {
1433     printf("Error:  Out of memory.\n");
1434     triexit(1);
1435   }
1436   return(memptr);
1437 }
1438 
1439 #ifdef ANSI_DECLARATORS
1440 void trifree(VOID *memptr)
1441 #else /* not ANSI_DECLARATORS */
1442 void trifree(memptr)
1443 VOID *memptr;
1444 #endif /* not ANSI_DECLARATORS */
1445 
1446 {
1447   free(memptr);
1448 }
1449 
1450 /**                                                                         **/
1451 /**                                                                         **/
1452 /********* Memory allocation and program exit wrappers end here      *********/
1453 
1454 /********* User interaction routines begin here                      *********/
1455 /**                                                                         **/
1456 /**                                                                         **/
1457 
1458 /*****************************************************************************/
1459 /*                                                                           */
1460 /*  syntax()   Print list of command line switches.                          */
1461 /*                                                                           */
1462 /*****************************************************************************/
1463 
1464 #ifndef TRILIBRARY
1465 
syntax()1466 void syntax()
1467 {
1468 #ifdef CDT_ONLY
1469 #ifdef REDUCED
1470   printf("triangle [-pAcjevngBPNEIOXzo_lQVh] input_file\n");
1471 #else /* not REDUCED */
1472   printf("triangle [-pAcjevngBPNEIOXzo_iFlCQVh] input_file\n");
1473 #endif /* not REDUCED */
1474 #else /* not CDT_ONLY */
1475 #ifdef REDUCED
1476   printf("triangle [-prq__a__uAcDjevngBPNEIOXzo_YS__lQVh] input_file\n");
1477 #else /* not REDUCED */
1478   printf("triangle [-prq__a__uAcDjevngBPNEIOXzo_YS__iFlsCQVh] input_file\n");
1479 #endif /* not REDUCED */
1480 #endif /* not CDT_ONLY */
1481 
1482   printf("    -p  Triangulates a Planar Straight Line Graph (.poly file).\n");
1483 #ifndef CDT_ONLY
1484   printf("    -r  Refines a previously generated mesh.\n");
1485   printf(
1486     "    -q  Quality mesh generation.  A minimum angle may be specified.\n");
1487   printf("    -a  Applies a maximum triangle area constraint.\n");
1488   printf("    -u  Applies a user-defined triangle constraint.\n");
1489 #endif /* not CDT_ONLY */
1490   printf(
1491     "    -A  Applies attributes to identify triangles in certain regions.\n");
1492   printf("    -c  Encloses the convex hull with segments.\n");
1493 #ifndef CDT_ONLY
1494   printf("    -D  Conforming Delaunay:  all triangles are truly Delaunay.\n");
1495 #endif /* not CDT_ONLY */
1496 /*
1497   printf("    -w  Weighted Delaunay triangulation.\n");
1498   printf("    -W  Regular triangulation (lower hull of a height field).\n");
1499 */
1500   printf("    -j  Jettison unused vertices from output .node file.\n");
1501   printf("    -e  Generates an edge list.\n");
1502   printf("    -v  Generates a Voronoi diagram.\n");
1503   printf("    -n  Generates a list of triangle neighbors.\n");
1504   printf("    -g  Generates an .off file for Geomview.\n");
1505   printf("    -B  Suppresses output of boundary information.\n");
1506   printf("    -P  Suppresses output of .poly file.\n");
1507   printf("    -N  Suppresses output of .node file.\n");
1508   printf("    -E  Suppresses output of .ele file.\n");
1509   printf("    -I  Suppresses mesh iteration numbers.\n");
1510   printf("    -O  Ignores holes in .poly file.\n");
1511   printf("    -X  Suppresses use of exact arithmetic.\n");
1512   printf("    -z  Numbers all items starting from zero (rather than one).\n");
1513   printf("    -o2 Generates second-order subparametric elements.\n");
1514 #ifndef CDT_ONLY
1515   printf("    -Y  Suppresses boundary segment splitting.\n");
1516   printf("    -S  Specifies maximum number of added Steiner points.\n");
1517 #endif /* not CDT_ONLY */
1518 #ifndef REDUCED
1519   printf("    -i  Uses incremental method, rather than divide-and-conquer.\n");
1520   printf("    -F  Uses Fortune's sweepline algorithm, rather than d-and-c.\n");
1521 #endif /* not REDUCED */
1522   printf("    -l  Uses vertical cuts only, rather than alternating cuts.\n");
1523 #ifndef REDUCED
1524 #ifndef CDT_ONLY
1525   printf(
1526     "    -s  Force segments into mesh by splitting (instead of using CDT).\n");
1527 #endif /* not CDT_ONLY */
1528   printf("    -C  Check consistency of final mesh.\n");
1529 #endif /* not REDUCED */
1530   printf("    -Q  Quiet:  No terminal output except errors.\n");
1531   printf("    -V  Verbose:  Detailed information on what I'm doing.\n");
1532   printf("    -h  Help:  Detailed instructions for Triangle.\n");
1533   triexit(0);
1534 }
1535 
1536 #endif /* not TRILIBRARY */
1537 
1538 /*****************************************************************************/
1539 /*                                                                           */
1540 /*  info()   Print out complete instructions.                                */
1541 /*                                                                           */
1542 /*****************************************************************************/
1543 
1544 #ifndef TRILIBRARY
1545 
info()1546 void info()
1547 {
1548   printf("Triangle\n");
1549   printf(
1550 "A Two-Dimensional Quality Mesh Generator and Delaunay Triangulator.\n");
1551   printf("Version 1.6\n\n");
1552   printf(
1553 "Copyright 1993, 1995, 1997, 1998, 2002, 2005 Jonathan Richard Shewchuk\n");
1554   printf("2360 Woolsey #H / Berkeley, California 94705-1927\n");
1555   printf("Bugs/comments to jrs@cs.berkeley.edu\n");
1556   printf(
1557 "Created as part of the Quake project (tools for earthquake simulation).\n");
1558   printf(
1559 "Supported in part by NSF Grant CMS-9318163 and an NSERC 1967 Scholarship.\n");
1560   printf("There is no warranty whatsoever.  Use at your own risk.\n");
1561 #ifdef SINGLE
1562   printf("This executable is compiled for single precision arithmetic.\n\n\n");
1563 #else /* not SINGLE */
1564   printf("This executable is compiled for double precision arithmetic.\n\n\n");
1565 #endif /* not SINGLE */
1566   printf(
1567 "Triangle generates exact Delaunay triangulations, constrained Delaunay\n");
1568   printf(
1569 "triangulations, conforming Delaunay triangulations, Voronoi diagrams, and\n");
1570   printf(
1571 "high-quality triangular meshes.  The latter can be generated with no small\n"
1572 );
1573   printf(
1574 "or large angles, and are thus suitable for finite element analysis.  If no\n"
1575 );
1576   printf(
1577 "command line switch is specified, your .node input file is read, and the\n");
1578   printf(
1579 "Delaunay triangulation is returned in .node and .ele output files.  The\n");
1580   printf("command syntax is:\n\n");
1581   printf("triangle [-prq__a__uAcDjevngBPNEIOXzo_YS__iFlsCQVh] input_file\n\n");
1582   printf(
1583 "Underscores indicate that numbers may optionally follow certain switches.\n");
1584   printf(
1585 "Do not leave any space between a switch and its numeric parameter.\n");
1586   printf(
1587 "input_file must be a file with extension .node, or extension .poly if the\n");
1588   printf(
1589 "-p switch is used.  If -r is used, you must supply .node and .ele files,\n");
1590   printf(
1591 "and possibly a .poly file and an .area file as well.  The formats of these\n"
1592 );
1593   printf("files are described below.\n\n");
1594   printf("Command Line Switches:\n\n");
1595   printf(
1596 "    -p  Reads a Planar Straight Line Graph (.poly file), which can specify\n"
1597 );
1598   printf(
1599 "        vertices, segments, holes, regional attributes, and regional area\n");
1600   printf(
1601 "        constraints.  Generates a constrained Delaunay triangulation (CDT)\n"
1602 );
1603   printf(
1604 "        fitting the input; or, if -s, -q, -a, or -u is used, a conforming\n");
1605   printf(
1606 "        constrained Delaunay triangulation (CCDT).  If you want a truly\n");
1607   printf(
1608 "        Delaunay (not just constrained Delaunay) triangulation, use -D as\n");
1609   printf(
1610 "        well.  When -p is not used, Triangle reads a .node file by default.\n"
1611 );
1612   printf(
1613 "    -r  Refines a previously generated mesh.  The mesh is read from a .node\n"
1614 );
1615   printf(
1616 "        file and an .ele file.  If -p is also used, a .poly file is read\n");
1617   printf(
1618 "        and used to constrain segments in the mesh.  If -a is also used\n");
1619   printf(
1620 "        (with no number following), an .area file is read and used to\n");
1621   printf(
1622 "        impose area constraints on the mesh.  Further details on refinement\n"
1623 );
1624   printf("        appear below.\n");
1625   printf(
1626 "    -q  Quality mesh generation by Delaunay refinement (a hybrid of Paul\n");
1627   printf(
1628 "        Chew's and Jim Ruppert's algorithms).  Adds vertices to the mesh to\n"
1629 );
1630   printf(
1631 "        ensure that all angles are between 20 and 140 degrees.  An\n");
1632   printf(
1633 "        alternative bound on the minimum angle, replacing 20 degrees, may\n");
1634   printf(
1635 "        be specified after the `q'.  The specified angle may include a\n");
1636   printf(
1637 "        decimal point, but not exponential notation.  Note that a bound of\n"
1638 );
1639   printf(
1640 "        theta degrees on the smallest angle also implies a bound of\n");
1641   printf(
1642 "        (180 - 2 theta) on the largest angle.  If the minimum angle is 28.6\n"
1643 );
1644   printf(
1645 "        degrees or smaller, Triangle is mathematically guaranteed to\n");
1646   printf(
1647 "        terminate (assuming infinite precision arithmetic--Triangle may\n");
1648   printf(
1649 "        fail to terminate if you run out of precision).  In practice,\n");
1650   printf(
1651 "        Triangle often succeeds for minimum angles up to 34 degrees.  For\n");
1652   printf(
1653 "        some meshes, however, you might need to reduce the minimum angle to\n"
1654 );
1655   printf(
1656 "        avoid problems associated with insufficient floating-point\n");
1657   printf("        precision.\n");
1658   printf(
1659 "    -a  Imposes a maximum triangle area.  If a number follows the `a', no\n");
1660   printf(
1661 "        triangle is generated whose area is larger than that number.  If no\n"
1662 );
1663   printf(
1664 "        number is specified, an .area file (if -r is used) or .poly file\n");
1665   printf(
1666 "        (if -r is not used) specifies a set of maximum area constraints.\n");
1667   printf(
1668 "        An .area file contains a separate area constraint for each\n");
1669   printf(
1670 "        triangle, and is useful for refining a finite element mesh based on\n"
1671 );
1672   printf(
1673 "        a posteriori error estimates.  A .poly file can optionally contain\n"
1674 );
1675   printf(
1676 "        an area constraint for each segment-bounded region, thereby\n");
1677   printf(
1678 "        controlling triangle densities in a first triangulation of a PSLG.\n"
1679 );
1680   printf(
1681 "        You can impose both a fixed area constraint and a varying area\n");
1682   printf(
1683 "        constraint by invoking the -a switch twice, once with and once\n");
1684   printf(
1685 "        without a number following.  Each area specified may include a\n");
1686   printf("        decimal point.\n");
1687   printf(
1688 "    -u  Imposes a user-defined constraint on triangle size.  There are two\n"
1689 );
1690   printf(
1691 "        ways to use this feature.  One is to edit the triunsuitable()\n");
1692   printf(
1693 "        procedure in triangle.c to encode any constraint you like, then\n");
1694   printf(
1695 "        recompile Triangle.  The other is to compile triangle.c with the\n");
1696   printf(
1697 "        EXTERNAL_TEST symbol set (compiler switch -DEXTERNAL_TEST), then\n");
1698   printf(
1699 "        link Triangle with a separate object file that implements\n");
1700   printf(
1701 "        triunsuitable().  In either case, the -u switch causes the user-\n");
1702   printf("        defined test to be applied to every triangle.\n");
1703   printf(
1704 "    -A  Assigns an additional floating-point attribute to each triangle\n");
1705   printf(
1706 "        that identifies what segment-bounded region each triangle belongs\n");
1707   printf(
1708 "        to.  Attributes are assigned to regions by the .poly file.  If a\n");
1709   printf(
1710 "        region is not explicitly marked by the .poly file, triangles in\n");
1711   printf(
1712 "        that region are assigned an attribute of zero.  The -A switch has\n");
1713   printf(
1714 "        an effect only when the -p switch is used and the -r switch is not.\n"
1715 );
1716   printf(
1717 "    -c  Creates segments on the convex hull of the triangulation.  If you\n");
1718   printf(
1719 "        are triangulating a vertex set, this switch causes a .poly file to\n"
1720 );
1721   printf(
1722 "        be written, containing all edges of the convex hull.  If you are\n");
1723   printf(
1724 "        triangulating a PSLG, this switch specifies that the whole convex\n");
1725   printf(
1726 "        hull of the PSLG should be triangulated, regardless of what\n");
1727   printf(
1728 "        segments the PSLG has.  If you do not use this switch when\n");
1729   printf(
1730 "        triangulating a PSLG, Triangle assumes that you have identified the\n"
1731 );
1732   printf(
1733 "        region to be triangulated by surrounding it with segments of the\n");
1734   printf(
1735 "        input PSLG.  Beware:  if you are not careful, this switch can cause\n"
1736 );
1737   printf(
1738 "        the introduction of an extremely thin angle between a PSLG segment\n"
1739 );
1740   printf(
1741 "        and a convex hull segment, which can cause overrefinement (and\n");
1742   printf(
1743 "        possibly failure if Triangle runs out of precision).  If you are\n");
1744   printf(
1745 "        refining a mesh, the -c switch works differently:  it causes a\n");
1746   printf(
1747 "        .poly file to be written containing the boundary edges of the mesh\n"
1748 );
1749   printf("        (useful if no .poly file was read).\n");
1750   printf(
1751 "    -D  Conforming Delaunay triangulation:  use this switch if you want to\n"
1752 );
1753   printf(
1754 "        ensure that all the triangles in the mesh are Delaunay, and not\n");
1755   printf(
1756 "        merely constrained Delaunay; or if you want to ensure that all the\n"
1757 );
1758   printf(
1759 "        Voronoi vertices lie within the triangulation.  (Some finite volume\n"
1760 );
1761   printf(
1762 "        methods have this requirement.)  This switch invokes Ruppert's\n");
1763   printf(
1764 "        original algorithm, which splits every subsegment whose diametral\n");
1765   printf(
1766 "        circle is encroached.  It usually increases the number of vertices\n"
1767 );
1768   printf("        and triangles.\n");
1769   printf(
1770 "    -j  Jettisons vertices that are not part of the final triangulation\n");
1771   printf(
1772 "        from the output .node file.  By default, Triangle copies all\n");
1773   printf(
1774 "        vertices in the input .node file to the output .node file, in the\n");
1775   printf(
1776 "        same order, so their indices do not change.  The -j switch prevents\n"
1777 );
1778   printf(
1779 "        duplicated input vertices, or vertices `eaten' by holes, from\n");
1780   printf(
1781 "        appearing in the output .node file.  Thus, if two input vertices\n");
1782   printf(
1783 "        have exactly the same coordinates, only the first appears in the\n");
1784   printf(
1785 "        output.  If any vertices are jettisoned, the vertex numbering in\n");
1786   printf(
1787 "        the output .node file differs from that of the input .node file.\n");
1788   printf(
1789 "    -e  Outputs (to an .edge file) a list of edges of the triangulation.\n");
1790   printf(
1791 "    -v  Outputs the Voronoi diagram associated with the triangulation.\n");
1792   printf(
1793 "        Does not attempt to detect degeneracies, so some Voronoi vertices\n");
1794   printf(
1795 "        may be duplicated.  See the discussion of Voronoi diagrams below.\n");
1796   printf(
1797 "    -n  Outputs (to a .neigh file) a list of triangles neighboring each\n");
1798   printf("        triangle.\n");
1799   printf(
1800 "    -g  Outputs the mesh to an Object File Format (.off) file, suitable for\n"
1801 );
1802   printf("        viewing with the Geometry Center's Geomview package.\n");
1803   printf(
1804 "    -B  No boundary markers in the output .node, .poly, and .edge output\n");
1805   printf(
1806 "        files.  See the detailed discussion of boundary markers below.\n");
1807   printf(
1808 "    -P  No output .poly file.  Saves disk space, but you lose the ability\n");
1809   printf(
1810 "        to maintain constraining segments on later refinements of the mesh.\n"
1811 );
1812   printf("    -N  No output .node file.\n");
1813   printf("    -E  No output .ele file.\n");
1814   printf(
1815 "    -I  No iteration numbers.  Suppresses the output of .node and .poly\n");
1816   printf(
1817 "        files, so your input files won't be overwritten.  (If your input is\n"
1818 );
1819   printf(
1820 "        a .poly file only, a .node file is written.)  Cannot be used with\n");
1821   printf(
1822 "        the -r switch, because that would overwrite your input .ele file.\n");
1823   printf(
1824 "        Shouldn't be used with the -q, -a, -u, or -s switch if you are\n");
1825   printf(
1826 "        using a .node file for input, because no .node file is written, so\n"
1827 );
1828   printf("        there is no record of any added Steiner points.\n");
1829   printf("    -O  No holes.  Ignores the holes in the .poly file.\n");
1830   printf(
1831 "    -X  No exact arithmetic.  Normally, Triangle uses exact floating-point\n"
1832 );
1833   printf(
1834 "        arithmetic for certain tests if it thinks the inexact tests are not\n"
1835 );
1836   printf(
1837 "        accurate enough.  Exact arithmetic ensures the robustness of the\n");
1838   printf(
1839 "        triangulation algorithms, despite floating-point roundoff error.\n");
1840   printf(
1841 "        Disabling exact arithmetic with the -X switch causes a small\n");
1842   printf(
1843 "        improvement in speed and creates the possibility that Triangle will\n"
1844 );
1845   printf("        fail to produce a valid mesh.  Not recommended.\n");
1846   printf(
1847 "    -z  Numbers all items starting from zero (rather than one).  Note that\n"
1848 );
1849   printf(
1850 "        this switch is normally overridden by the value used to number the\n"
1851 );
1852   printf(
1853 "        first vertex of the input .node or .poly file.  However, this\n");
1854   printf(
1855 "        switch is useful when calling Triangle from another program.\n");
1856   printf(
1857 "    -o2 Generates second-order subparametric elements with six nodes each.\n"
1858 );
1859   printf(
1860 "    -Y  No new vertices on the boundary.  This switch is useful when the\n");
1861   printf(
1862 "        mesh boundary must be preserved so that it conforms to some\n");
1863   printf(
1864 "        adjacent mesh.  Be forewarned that you will probably sacrifice much\n"
1865 );
1866   printf(
1867 "        of the quality of the mesh; Triangle will try, but the resulting\n");
1868   printf(
1869 "        mesh may contain poorly shaped triangles.  Works well if all the\n");
1870   printf(
1871 "        boundary vertices are closely spaced.  Specify this switch twice\n");
1872   printf(
1873 "        (`-YY') to prevent all segment splitting, including internal\n");
1874   printf("        boundaries.\n");
1875   printf(
1876 "    -S  Specifies the maximum number of Steiner points (vertices that are\n");
1877   printf(
1878 "        not in the input, but are added to meet the constraints on minimum\n"
1879 );
1880   printf(
1881 "        angle and maximum area).  The default is to allow an unlimited\n");
1882   printf(
1883 "        number.  If you specify this switch with no number after it,\n");
1884   printf(
1885 "        the limit is set to zero.  Triangle always adds vertices at segment\n"
1886 );
1887   printf(
1888 "        intersections, even if it needs to use more vertices than the limit\n"
1889 );
1890   printf(
1891 "        you set.  When Triangle inserts segments by splitting (-s), it\n");
1892   printf(
1893 "        always adds enough vertices to ensure that all the segments of the\n"
1894 );
1895   printf("        PLSG are recovered, ignoring the limit if necessary.\n");
1896   printf(
1897 "    -i  Uses an incremental rather than a divide-and-conquer algorithm to\n");
1898   printf(
1899 "        construct a Delaunay triangulation.  Try it if the divide-and-\n");
1900   printf("        conquer algorithm fails.\n");
1901   printf(
1902 "    -F  Uses Steven Fortune's sweepline algorithm to construct a Delaunay\n");
1903   printf(
1904 "        triangulation.  Warning:  does not use exact arithmetic for all\n");
1905   printf("        calculations.  An exact result is not guaranteed.\n");
1906   printf(
1907 "    -l  Uses only vertical cuts in the divide-and-conquer algorithm.  By\n");
1908   printf(
1909 "        default, Triangle alternates between vertical and horizontal cuts,\n"
1910 );
1911   printf(
1912 "        which usually improve the speed except with vertex sets that are\n");
1913   printf(
1914 "        small or short and wide.  This switch is primarily of theoretical\n");
1915   printf("        interest.\n");
1916   printf(
1917 "    -s  Specifies that segments should be forced into the triangulation by\n"
1918 );
1919   printf(
1920 "        recursively splitting them at their midpoints, rather than by\n");
1921   printf(
1922 "        generating a constrained Delaunay triangulation.  Segment splitting\n"
1923 );
1924   printf(
1925 "        is true to Ruppert's original algorithm, but can create needlessly\n"
1926 );
1927   printf(
1928 "        small triangles.  This switch is primarily of theoretical interest.\n"
1929 );
1930   printf(
1931 "    -C  Check the consistency of the final mesh.  Uses exact arithmetic for\n"
1932 );
1933   printf(
1934 "        checking, even if the -X switch is used.  Useful if you suspect\n");
1935   printf("        Triangle is buggy.\n");
1936   printf(
1937 "    -Q  Quiet:  Suppresses all explanation of what Triangle is doing,\n");
1938   printf("        unless an error occurs.\n");
1939   printf(
1940 "    -V  Verbose:  Gives detailed information about what Triangle is doing.\n"
1941 );
1942   printf(
1943 "        Add more `V's for increasing amount of detail.  `-V' is most\n");
1944   printf(
1945 "        useful; itgives information on algorithmic progress and much more\n");
1946   printf(
1947 "        detailed statistics.  `-VV' gives vertex-by-vertex details, and\n");
1948   printf(
1949 "        prints so much that Triangle runs much more slowly.  `-VVVV' gives\n"
1950 );
1951   printf("        information only a debugger could love.\n");
1952   printf("    -h  Help:  Displays these instructions.\n");
1953   printf("\n");
1954   printf("Definitions:\n");
1955   printf("\n");
1956   printf(
1957 "  A Delaunay triangulation of a vertex set is a triangulation whose\n");
1958   printf(
1959 "  vertices are the vertex set, that covers the convex hull of the vertex\n");
1960   printf(
1961 "  set.  A Delaunay triangulation has the property that no vertex lies\n");
1962   printf(
1963 "  inside the circumscribing circle (circle that passes through all three\n");
1964   printf("  vertices) of any triangle in the triangulation.\n\n");
1965   printf(
1966 "  A Voronoi diagram of a vertex set is a subdivision of the plane into\n");
1967   printf(
1968 "  polygonal cells (some of which may be unbounded, meaning infinitely\n");
1969   printf(
1970 "  large), where each cell is the set of points in the plane that are closer\n"
1971 );
1972   printf(
1973 "  to some input vertex than to any other input vertex.  The Voronoi diagram\n"
1974 );
1975   printf("  is a geometric dual of the Delaunay triangulation.\n\n");
1976   printf(
1977 "  A Planar Straight Line Graph (PSLG) is a set of vertices and segments.\n");
1978   printf(
1979 "  Segments are simply edges, whose endpoints are all vertices in the PSLG.\n"
1980 );
1981   printf(
1982 "  Segments may intersect each other only at their endpoints.  The file\n");
1983   printf("  format for PSLGs (.poly files) is described below.\n\n");
1984   printf(
1985 "  A constrained Delaunay triangulation (CDT) of a PSLG is similar to a\n");
1986   printf(
1987 "  Delaunay triangulation, but each PSLG segment is present as a single edge\n"
1988 );
1989   printf(
1990 "  of the CDT.  (A constrained Delaunay triangulation is not truly a\n");
1991   printf(
1992 "  Delaunay triangulation, because some of its triangles might not be\n");
1993   printf(
1994 "  Delaunay.)  By definition, a CDT does not have any vertices other than\n");
1995   printf(
1996 "  those specified in the input PSLG.  Depending on context, a CDT might\n");
1997   printf(
1998 "  cover the convex hull of the PSLG, or it might cover only a segment-\n");
1999   printf("  bounded region (e.g. a polygon).\n\n");
2000   printf(
2001 "  A conforming Delaunay triangulation of a PSLG is a triangulation in which\n"
2002 );
2003   printf(
2004 "  each triangle is truly Delaunay, and each PSLG segment is represented by\n"
2005 );
2006   printf(
2007 "  a linear contiguous sequence of edges of the triangulation.  New vertices\n"
2008 );
2009   printf(
2010 "  (not part of the PSLG) may appear, and each input segment may have been\n");
2011   printf(
2012 "  subdivided into shorter edges (subsegments) by these additional vertices.\n"
2013 );
2014   printf(
2015 "  The new vertices are frequently necessary to maintain the Delaunay\n");
2016   printf("  property while ensuring that every segment is represented.\n\n");
2017   printf(
2018 "  A conforming constrained Delaunay triangulation (CCDT) of a PSLG is a\n");
2019   printf(
2020 "  triangulation of a PSLG whose triangles are constrained Delaunay.  New\n");
2021   printf("  vertices may appear, and input segments may be subdivided into\n");
2022   printf(
2023 "  subsegments, but not to guarantee that segments are respected; rather, to\n"
2024 );
2025   printf(
2026 "  improve the quality of the triangles.  The high-quality meshes produced\n");
2027   printf(
2028 "  by the -q switch are usually CCDTs, but can be made conforming Delaunay\n");
2029   printf("  with the -D switch.\n\n");
2030   printf("File Formats:\n\n");
2031   printf(
2032 "  All files may contain comments prefixed by the character '#'.  Vertices,\n"
2033 );
2034   printf(
2035 "  triangles, edges, holes, and maximum area constraints must be numbered\n");
2036   printf(
2037 "  consecutively, starting from either 1 or 0.  Whichever you choose, all\n");
2038   printf(
2039 "  input files must be consistent; if the vertices are numbered from 1, so\n");
2040   printf(
2041 "  must be all other objects.  Triangle automatically detects your choice\n");
2042   printf(
2043 "  while reading the .node (or .poly) file.  (When calling Triangle from\n");
2044   printf(
2045 "  another program, use the -z switch if you wish to number objects from\n");
2046   printf("  zero.)  Examples of these file formats are given below.\n\n");
2047   printf("  .node files:\n");
2048   printf(
2049 "    First line:  <# of vertices> <dimension (must be 2)> <# of attributes>\n"
2050 );
2051   printf(
2052 "                                           <# of boundary markers (0 or 1)>\n"
2053 );
2054   printf(
2055 "    Remaining lines:  <vertex #> <x> <y> [attributes] [boundary marker]\n");
2056   printf("\n");
2057   printf(
2058 "    The attributes, which are typically floating-point values of physical\n");
2059   printf(
2060 "    quantities (such as mass or conductivity) associated with the nodes of\n"
2061 );
2062   printf(
2063 "    a finite element mesh, are copied unchanged to the output mesh.  If -q,\n"
2064 );
2065   printf(
2066 "    -a, -u, -D, or -s is selected, each new Steiner point added to the mesh\n"
2067 );
2068   printf("    has attributes assigned to it by linear interpolation.\n\n");
2069   printf(
2070 "    If the fourth entry of the first line is `1', the last column of the\n");
2071   printf(
2072 "    remainder of the file is assumed to contain boundary markers.  Boundary\n"
2073 );
2074   printf(
2075 "    markers are used to identify boundary vertices and vertices resting on\n"
2076 );
2077   printf(
2078 "    PSLG segments; a complete description appears in a section below.  The\n"
2079 );
2080   printf(
2081 "    .node file produced by Triangle contains boundary markers in the last\n");
2082   printf("    column unless they are suppressed by the -B switch.\n\n");
2083   printf("  .ele files:\n");
2084   printf(
2085 "    First line:  <# of triangles> <nodes per triangle> <# of attributes>\n");
2086   printf(
2087 "    Remaining lines:  <triangle #> <node> <node> <node> ... [attributes]\n");
2088   printf("\n");
2089   printf(
2090 "    Nodes are indices into the corresponding .node file.  The first three\n");
2091   printf(
2092 "    nodes are the corner vertices, and are listed in counterclockwise order\n"
2093 );
2094   printf(
2095 "    around each triangle.  (The remaining nodes, if any, depend on the type\n"
2096 );
2097   printf("    of finite element used.)\n\n");
2098   printf(
2099 "    The attributes are just like those of .node files.  Because there is no\n"
2100 );
2101   printf(
2102 "    simple mapping from input to output triangles, Triangle attempts to\n");
2103   printf(
2104 "    interpolate attributes, and may cause a lot of diffusion of attributes\n"
2105 );
2106   printf(
2107 "    among nearby triangles as the triangulation is refined.  Attributes do\n"
2108 );
2109   printf("    not diffuse across segments, so attributes used to identify\n");
2110   printf("    segment-bounded regions remain intact.\n\n");
2111   printf(
2112 "    In .ele files produced by Triangle, each triangular element has three\n");
2113   printf(
2114 "    nodes (vertices) unless the -o2 switch is used, in which case\n");
2115   printf(
2116 "    subparametric quadratic elements with six nodes each are generated.\n");
2117   printf(
2118 "    The first three nodes are the corners in counterclockwise order, and\n");
2119   printf(
2120 "    the fourth, fifth, and sixth nodes lie on the midpoints of the edges\n");
2121   printf(
2122 "    opposite the first, second, and third vertices, respectively.\n");
2123   printf("\n");
2124   printf("  .poly files:\n");
2125   printf(
2126 "    First line:  <# of vertices> <dimension (must be 2)> <# of attributes>\n"
2127 );
2128   printf(
2129 "                                           <# of boundary markers (0 or 1)>\n"
2130 );
2131   printf(
2132 "    Following lines:  <vertex #> <x> <y> [attributes] [boundary marker]\n");
2133   printf("    One line:  <# of segments> <# of boundary markers (0 or 1)>\n");
2134   printf(
2135 "    Following lines:  <segment #> <endpoint> <endpoint> [boundary marker]\n");
2136   printf("    One line:  <# of holes>\n");
2137   printf("    Following lines:  <hole #> <x> <y>\n");
2138   printf(
2139 "    Optional line:  <# of regional attributes and/or area constraints>\n");
2140   printf(
2141 "    Optional following lines:  <region #> <x> <y> <attribute> <max area>\n");
2142   printf("\n");
2143   printf(
2144 "    A .poly file represents a PSLG, as well as some additional information.\n"
2145 );
2146   printf(
2147 "    The first section lists all the vertices, and is identical to the\n");
2148   printf(
2149 "    format of .node files.  <# of vertices> may be set to zero to indicate\n"
2150 );
2151   printf(
2152 "    that the vertices are listed in a separate .node file; .poly files\n");
2153   printf(
2154 "    produced by Triangle always have this format.  A vertex set represented\n"
2155 );
2156   printf(
2157 "    this way has the advantage that it may easily be triangulated with or\n");
2158   printf(
2159 "    without segments (depending on whether the -p switch is invoked).\n");
2160   printf("\n");
2161   printf(
2162 "    The second section lists the segments.  Segments are edges whose\n");
2163   printf(
2164 "    presence in the triangulation is enforced.  (Depending on the choice of\n"
2165 );
2166   printf(
2167 "    switches, segment might be subdivided into smaller edges).  Each\n");
2168   printf(
2169 "    segment is specified by listing the indices of its two endpoints.  This\n"
2170 );
2171   printf(
2172 "    means that you must include its endpoints in the vertex list.  Each\n");
2173   printf("    segment, like each point, may have a boundary marker.\n\n");
2174   printf(
2175 "    If -q, -a, -u, and -s are not selected, Triangle produces a constrained\n"
2176 );
2177   printf(
2178 "    Delaunay triangulation (CDT), in which each segment appears as a single\n"
2179 );
2180   printf(
2181 "    edge in the triangulation.  If -q, -a, -u, or -s is selected, Triangle\n"
2182 );
2183   printf(
2184 "    produces a conforming constrained Delaunay triangulation (CCDT), in\n");
2185   printf(
2186 "    which segments may be subdivided into smaller edges.  If -D is\n");
2187   printf(
2188 "    selected, Triangle produces a conforming Delaunay triangulation, so\n");
2189   printf(
2190 "    that every triangle is Delaunay, and not just constrained Delaunay.\n");
2191   printf("\n");
2192   printf(
2193 "    The third section lists holes (and concavities, if -c is selected) in\n");
2194   printf(
2195 "    the triangulation.  Holes are specified by identifying a point inside\n");
2196   printf(
2197 "    each hole.  After the triangulation is formed, Triangle creates holes\n");
2198   printf(
2199 "    by eating triangles, spreading out from each hole point until its\n");
2200   printf(
2201 "    progress is blocked by segments in the PSLG.  You must be careful to\n");
2202   printf(
2203 "    enclose each hole in segments, or your whole triangulation might be\n");
2204   printf(
2205 "    eaten away.  If the two triangles abutting a segment are eaten, the\n");
2206   printf(
2207 "    segment itself is also eaten.  Do not place a hole directly on a\n");
2208   printf("    segment; if you do, Triangle chooses one side of the segment\n");
2209   printf("    arbitrarily.\n\n");
2210   printf(
2211 "    The optional fourth section lists regional attributes (to be assigned\n");
2212   printf(
2213 "    to all triangles in a region) and regional constraints on the maximum\n");
2214   printf(
2215 "    triangle area.  Triangle reads this section only if the -A switch is\n");
2216   printf(
2217 "    used or the -a switch is used without a number following it, and the -r\n"
2218 );
2219   printf(
2220 "    switch is not used.  Regional attributes and area constraints are\n");
2221   printf(
2222 "    propagated in the same manner as holes:  you specify a point for each\n");
2223   printf(
2224 "    attribute and/or constraint, and the attribute and/or constraint\n");
2225   printf(
2226 "    affects the whole region (bounded by segments) containing the point.\n");
2227   printf(
2228 "    If two values are written on a line after the x and y coordinate, the\n");
2229   printf(
2230 "    first such value is assumed to be a regional attribute (but is only\n");
2231   printf(
2232 "    applied if the -A switch is selected), and the second value is assumed\n"
2233 );
2234   printf(
2235 "    to be a regional area constraint (but is only applied if the -a switch\n"
2236 );
2237   printf(
2238 "    is selected).  You may specify just one value after the coordinates,\n");
2239   printf(
2240 "    which can serve as both an attribute and an area constraint, depending\n"
2241 );
2242   printf(
2243 "    on the choice of switches.  If you are using the -A and -a switches\n");
2244   printf(
2245 "    simultaneously and wish to assign an attribute to some region without\n");
2246   printf("    imposing an area constraint, use a negative maximum area.\n\n");
2247   printf(
2248 "    When a triangulation is created from a .poly file, you must either\n");
2249   printf(
2250 "    enclose the entire region to be triangulated in PSLG segments, or\n");
2251   printf(
2252 "    use the -c switch, which automatically creates extra segments that\n");
2253   printf(
2254 "    enclose the convex hull of the PSLG.  If you do not use the -c switch,\n"
2255 );
2256   printf(
2257 "    Triangle eats all triangles that are not enclosed by segments; if you\n");
2258   printf(
2259 "    are not careful, your whole triangulation may be eaten away.  If you do\n"
2260 );
2261   printf(
2262 "    use the -c switch, you can still produce concavities by the appropriate\n"
2263 );
2264   printf(
2265 "    placement of holes just inside the boundary of the convex hull.\n");
2266   printf("\n");
2267   printf(
2268 "    An ideal PSLG has no intersecting segments, nor any vertices that lie\n");
2269   printf(
2270 "    upon segments (except, of course, the endpoints of each segment).  You\n"
2271 );
2272   printf(
2273 "    aren't required to make your .poly files ideal, but you should be aware\n"
2274 );
2275   printf(
2276 "    of what can go wrong.  Segment intersections are relatively safe--\n");
2277   printf(
2278 "    Triangle calculates the intersection points for you and adds them to\n");
2279   printf(
2280 "    the triangulation--as long as your machine's floating-point precision\n");
2281   printf(
2282 "    doesn't become a problem.  You are tempting the fates if you have three\n"
2283 );
2284   printf(
2285 "    segments that cross at the same location, and expect Triangle to figure\n"
2286 );
2287   printf(
2288 "    out where the intersection point is.  Thanks to floating-point roundoff\n"
2289 );
2290   printf(
2291 "    error, Triangle will probably decide that the three segments intersect\n"
2292 );
2293   printf(
2294 "    at three different points, and you will find a minuscule triangle in\n");
2295   printf(
2296 "    your output--unless Triangle tries to refine the tiny triangle, uses\n");
2297   printf(
2298 "    up the last bit of machine precision, and fails to terminate at all.\n");
2299   printf(
2300 "    You're better off putting the intersection point in the input files,\n");
2301   printf(
2302 "    and manually breaking up each segment into two.  Similarly, if you\n");
2303   printf(
2304 "    place a vertex at the middle of a segment, and hope that Triangle will\n"
2305 );
2306   printf(
2307 "    break up the segment at that vertex, you might get lucky.  On the other\n"
2308 );
2309   printf(
2310 "    hand, Triangle might decide that the vertex doesn't lie precisely on\n");
2311   printf(
2312 "    the segment, and you'll have a needle-sharp triangle in your output--or\n"
2313 );
2314   printf("    a lot of tiny triangles if you're generating a quality mesh.\n");
2315   printf("\n");
2316   printf(
2317 "    When Triangle reads a .poly file, it also writes a .poly file, which\n");
2318   printf(
2319 "    includes all the subsegments--the edges that are parts of input\n");
2320   printf(
2321 "    segments.  If the -c switch is used, the output .poly file also\n");
2322   printf(
2323 "    includes all of the edges on the convex hull.  Hence, the output .poly\n"
2324 );
2325   printf(
2326 "    file is useful for finding edges associated with input segments and for\n"
2327 );
2328   printf(
2329 "    setting boundary conditions in finite element simulations.  Moreover,\n");
2330   printf(
2331 "    you will need the output .poly file if you plan to refine the output\n");
2332   printf(
2333 "    mesh, and don't want segments to be missing in later triangulations.\n");
2334   printf("\n");
2335   printf("  .area files:\n");
2336   printf("    First line:  <# of triangles>\n");
2337   printf("    Following lines:  <triangle #> <maximum area>\n");
2338   printf("\n");
2339   printf(
2340 "    An .area file associates with each triangle a maximum area that is used\n"
2341 );
2342   printf(
2343 "    for mesh refinement.  As with other file formats, every triangle must\n");
2344   printf(
2345 "    be represented, and the triangles must be numbered consecutively.  A\n");
2346   printf(
2347 "    triangle may be left unconstrained by assigning it a negative maximum\n");
2348   printf("    area.\n\n");
2349   printf("  .edge files:\n");
2350   printf("    First line:  <# of edges> <# of boundary markers (0 or 1)>\n");
2351   printf(
2352 "    Following lines:  <edge #> <endpoint> <endpoint> [boundary marker]\n");
2353   printf("\n");
2354   printf(
2355 "    Endpoints are indices into the corresponding .node file.  Triangle can\n"
2356 );
2357   printf(
2358 "    produce .edge files (use the -e switch), but cannot read them.  The\n");
2359   printf(
2360 "    optional column of boundary markers is suppressed by the -B switch.\n");
2361   printf("\n");
2362   printf(
2363 "    In Voronoi diagrams, one also finds a special kind of edge that is an\n");
2364   printf(
2365 "    infinite ray with only one endpoint.  For these edges, a different\n");
2366   printf("    format is used:\n\n");
2367   printf("        <edge #> <endpoint> -1 <direction x> <direction y>\n\n");
2368   printf(
2369 "    The `direction' is a floating-point vector that indicates the direction\n"
2370 );
2371   printf("    of the infinite ray.\n\n");
2372   printf("  .neigh files:\n");
2373   printf(
2374 "    First line:  <# of triangles> <# of neighbors per triangle (always 3)>\n"
2375 );
2376   printf(
2377 "    Following lines:  <triangle #> <neighbor> <neighbor> <neighbor>\n");
2378   printf("\n");
2379   printf(
2380 "    Neighbors are indices into the corresponding .ele file.  An index of -1\n"
2381 );
2382   printf(
2383 "    indicates no neighbor (because the triangle is on an exterior\n");
2384   printf(
2385 "    boundary).  The first neighbor of triangle i is opposite the first\n");
2386   printf("    corner of triangle i, and so on.\n\n");
2387   printf(
2388 "    Triangle can produce .neigh files (use the -n switch), but cannot read\n"
2389 );
2390   printf("    them.\n\n");
2391   printf("Boundary Markers:\n\n");
2392   printf(
2393 "  Boundary markers are tags used mainly to identify which output vertices\n");
2394   printf(
2395 "  and edges are associated with which PSLG segment, and to identify which\n");
2396   printf(
2397 "  vertices and edges occur on a boundary of the triangulation.  A common\n");
2398   printf(
2399 "  use is to determine where boundary conditions should be applied to a\n");
2400   printf(
2401 "  finite element mesh.  You can prevent boundary markers from being written\n"
2402 );
2403   printf("  into files produced by Triangle by using the -B switch.\n\n");
2404   printf(
2405 "  The boundary marker associated with each segment in an output .poly file\n"
2406 );
2407   printf("  and each edge in an output .edge file is chosen as follows:\n");
2408   printf(
2409 "    - If an output edge is part or all of a PSLG segment with a nonzero\n");
2410   printf(
2411 "      boundary marker, then the edge is assigned the same marker.\n");
2412   printf(
2413 "    - Otherwise, if the edge lies on a boundary of the triangulation\n");
2414   printf(
2415 "      (even the boundary of a hole), then the edge is assigned the marker\n");
2416   printf("      one (1).\n");
2417   printf("    - Otherwise, the edge is assigned the marker zero (0).\n");
2418   printf(
2419 "  The boundary marker associated with each vertex in an output .node file\n");
2420   printf("  is chosen as follows:\n");
2421   printf(
2422 "    - If a vertex is assigned a nonzero boundary marker in the input file,\n"
2423 );
2424   printf(
2425 "      then it is assigned the same marker in the output .node file.\n");
2426   printf(
2427 "    - Otherwise, if the vertex lies on a PSLG segment (even if it is an\n");
2428   printf(
2429 "      endpoint of the segment) with a nonzero boundary marker, then the\n");
2430   printf(
2431 "      vertex is assigned the same marker.  If the vertex lies on several\n");
2432   printf("      such segments, one of the markers is chosen arbitrarily.\n");
2433   printf(
2434 "    - Otherwise, if the vertex occurs on a boundary of the triangulation,\n");
2435   printf("      then the vertex is assigned the marker one (1).\n");
2436   printf("    - Otherwise, the vertex is assigned the marker zero (0).\n");
2437   printf("\n");
2438   printf(
2439 "  If you want Triangle to determine for you which vertices and edges are on\n"
2440 );
2441   printf(
2442 "  the boundary, assign them the boundary marker zero (or use no markers at\n"
2443 );
2444   printf(
2445 "  all) in your input files.  In the output files, all boundary vertices,\n");
2446   printf("  edges, and segments will be assigned the value one.\n\n");
2447   printf("Triangulation Iteration Numbers:\n\n");
2448   printf(
2449 "  Because Triangle can read and refine its own triangulations, input\n");
2450   printf(
2451 "  and output files have iteration numbers.  For instance, Triangle might\n");
2452   printf(
2453 "  read the files mesh.3.node, mesh.3.ele, and mesh.3.poly, refine the\n");
2454   printf(
2455 "  triangulation, and output the files mesh.4.node, mesh.4.ele, and\n");
2456   printf("  mesh.4.poly.  Files with no iteration number are treated as if\n");
2457   printf(
2458 "  their iteration number is zero; hence, Triangle might read the file\n");
2459   printf(
2460 "  points.node, triangulate it, and produce the files points.1.node and\n");
2461   printf("  points.1.ele.\n\n");
2462   printf(
2463 "  Iteration numbers allow you to create a sequence of successively finer\n");
2464   printf(
2465 "  meshes suitable for multigrid methods.  They also allow you to produce a\n"
2466 );
2467   printf(
2468 "  sequence of meshes using error estimate-driven mesh refinement.\n");
2469   printf("\n");
2470   printf(
2471 "  If you're not using refinement or quality meshing, and you don't like\n");
2472   printf(
2473 "  iteration numbers, use the -I switch to disable them.  This switch also\n");
2474   printf(
2475 "  disables output of .node and .poly files to prevent your input files from\n"
2476 );
2477   printf(
2478 "  being overwritten.  (If the input is a .poly file that contains its own\n");
2479   printf(
2480 "  points, a .node file is written.  This can be quite convenient for\n");
2481   printf("  computing CDTs or quality meshes.)\n\n");
2482   printf("Examples of How to Use Triangle:\n\n");
2483   printf(
2484 "  `triangle dots' reads vertices from dots.node, and writes their Delaunay\n"
2485 );
2486   printf(
2487 "  triangulation to dots.1.node and dots.1.ele.  (dots.1.node is identical\n");
2488   printf(
2489 "  to dots.node.)  `triangle -I dots' writes the triangulation to dots.ele\n");
2490   printf(
2491 "  instead.  (No additional .node file is needed, so none is written.)\n");
2492   printf("\n");
2493   printf(
2494 "  `triangle -pe object.1' reads a PSLG from object.1.poly (and possibly\n");
2495   printf(
2496 "  object.1.node, if the vertices are omitted from object.1.poly) and writes\n"
2497 );
2498   printf(
2499 "  its constrained Delaunay triangulation to object.2.node and object.2.ele.\n"
2500 );
2501   printf(
2502 "  The segments are copied to object.2.poly, and all edges are written to\n");
2503   printf("  object.2.edge.\n\n");
2504   printf(
2505 "  `triangle -pq31.5a.1 object' reads a PSLG from object.poly (and possibly\n"
2506 );
2507   printf(
2508 "  object.node), generates a mesh whose angles are all between 31.5 and 117\n"
2509 );
2510   printf(
2511 "  degrees and whose triangles all have areas of 0.1 or less, and writes the\n"
2512 );
2513   printf(
2514 "  mesh to object.1.node and object.1.ele.  Each segment may be broken up\n");
2515   printf("  into multiple subsegments; these are written to object.1.poly.\n");
2516   printf("\n");
2517   printf(
2518 "  Here is a sample file `box.poly' describing a square with a square hole:\n"
2519 );
2520   printf("\n");
2521   printf(
2522 "    # A box with eight vertices in 2D, no attributes, one boundary marker.\n"
2523 );
2524   printf("    8 2 0 1\n");
2525   printf("     # Outer box has these vertices:\n");
2526   printf("     1   0 0   0\n");
2527   printf("     2   0 3   0\n");
2528   printf("     3   3 0   0\n");
2529   printf("     4   3 3   33     # A special marker for this vertex.\n");
2530   printf("     # Inner square has these vertices:\n");
2531   printf("     5   1 1   0\n");
2532   printf("     6   1 2   0\n");
2533   printf("     7   2 1   0\n");
2534   printf("     8   2 2   0\n");
2535   printf("    # Five segments with boundary markers.\n");
2536   printf("    5 1\n");
2537   printf("     1   1 2   5      # Left side of outer box.\n");
2538   printf("     # Square hole has these segments:\n");
2539   printf("     2   5 7   0\n");
2540   printf("     3   7 8   0\n");
2541   printf("     4   8 6   10\n");
2542   printf("     5   6 5   0\n");
2543   printf("    # One hole in the middle of the inner square.\n");
2544   printf("    1\n");
2545   printf("     1   1.5 1.5\n");
2546   printf("\n");
2547   printf(
2548 "  Note that some segments are missing from the outer square, so you must\n");
2549   printf(
2550 "  use the `-c' switch.  After `triangle -pqc box.poly', here is the output\n"
2551 );
2552   printf(
2553 "  file `box.1.node', with twelve vertices.  The last four vertices were\n");
2554   printf(
2555 "  added to meet the angle constraint.  Vertices 1, 2, and 9 have markers\n");
2556   printf(
2557 "  from segment 1.  Vertices 6 and 8 have markers from segment 4.  All the\n");
2558   printf(
2559 "  other vertices but 4 have been marked to indicate that they lie on a\n");
2560   printf("  boundary.\n\n");
2561   printf("    12  2  0  1\n");
2562   printf("       1    0   0      5\n");
2563   printf("       2    0   3      5\n");
2564   printf("       3    3   0      1\n");
2565   printf("       4    3   3     33\n");
2566   printf("       5    1   1      1\n");
2567   printf("       6    1   2     10\n");
2568   printf("       7    2   1      1\n");
2569   printf("       8    2   2     10\n");
2570   printf("       9    0   1.5    5\n");
2571   printf("      10    1.5   0    1\n");
2572   printf("      11    3   1.5    1\n");
2573   printf("      12    1.5   3    1\n");
2574   printf("    # Generated by triangle -pqc box.poly\n");
2575   printf("\n");
2576   printf("  Here is the output file `box.1.ele', with twelve triangles.\n");
2577   printf("\n");
2578   printf("    12  3  0\n");
2579   printf("       1     5   6   9\n");
2580   printf("       2    10   3   7\n");
2581   printf("       3     6   8  12\n");
2582   printf("       4     9   1   5\n");
2583   printf("       5     6   2   9\n");
2584   printf("       6     7   3  11\n");
2585   printf("       7    11   4   8\n");
2586   printf("       8     7   5  10\n");
2587   printf("       9    12   2   6\n");
2588   printf("      10     8   7  11\n");
2589   printf("      11     5   1  10\n");
2590   printf("      12     8   4  12\n");
2591   printf("    # Generated by triangle -pqc box.poly\n\n");
2592   printf(
2593 "  Here is the output file `box.1.poly'.  Note that segments have been added\n"
2594 );
2595   printf(
2596 "  to represent the convex hull, and some segments have been subdivided by\n");
2597   printf(
2598 "  newly added vertices.  Note also that <# of vertices> is set to zero to\n");
2599   printf("  indicate that the vertices should be read from the .node file.\n");
2600   printf("\n");
2601   printf("    0  2  0  1\n");
2602   printf("    12  1\n");
2603   printf("       1     1   9     5\n");
2604   printf("       2     5   7     1\n");
2605   printf("       3     8   7     1\n");
2606   printf("       4     6   8    10\n");
2607   printf("       5     5   6     1\n");
2608   printf("       6     3  10     1\n");
2609   printf("       7     4  11     1\n");
2610   printf("       8     2  12     1\n");
2611   printf("       9     9   2     5\n");
2612   printf("      10    10   1     1\n");
2613   printf("      11    11   3     1\n");
2614   printf("      12    12   4     1\n");
2615   printf("    1\n");
2616   printf("       1   1.5 1.5\n");
2617   printf("    # Generated by triangle -pqc box.poly\n");
2618   printf("\n");
2619   printf("Refinement and Area Constraints:\n");
2620   printf("\n");
2621   printf(
2622 "  The -r switch causes a mesh (.node and .ele files) to be read and\n");
2623   printf(
2624 "  refined.  If the -p switch is also used, a .poly file is read and used to\n"
2625 );
2626   printf(
2627 "  specify edges that are constrained and cannot be eliminated (although\n");
2628   printf(
2629 "  they can be subdivided into smaller edges) by the refinement process.\n");
2630   printf("\n");
2631   printf(
2632 "  When you refine a mesh, you generally want to impose tighter constraints.\n"
2633 );
2634   printf(
2635 "  One way to accomplish this is to use -q with a larger angle, or -a\n");
2636   printf(
2637 "  followed by a smaller area than you used to generate the mesh you are\n");
2638   printf(
2639 "  refining.  Another way to do this is to create an .area file, which\n");
2640   printf(
2641 "  specifies a maximum area for each triangle, and use the -a switch\n");
2642   printf(
2643 "  (without a number following).  Each triangle's area constraint is applied\n"
2644 );
2645   printf(
2646 "  to that triangle.  Area constraints tend to diffuse as the mesh is\n");
2647   printf(
2648 "  refined, so if there are large variations in area constraint between\n");
2649   printf(
2650 "  adjacent triangles, you may not get the results you want.  In that case,\n"
2651 );
2652   printf(
2653 "  consider instead using the -u switch and writing a C procedure that\n");
2654   printf("  determines which triangles are too large.\n\n");
2655   printf(
2656 "  If you are refining a mesh composed of linear (three-node) elements, the\n"
2657 );
2658   printf(
2659 "  output mesh contains all the nodes present in the input mesh, in the same\n"
2660 );
2661   printf(
2662 "  order, with new nodes added at the end of the .node file.  However, the\n");
2663   printf(
2664 "  refinement is not hierarchical: there is no guarantee that each output\n");
2665   printf(
2666 "  element is contained in a single input element.  Often, an output element\n"
2667 );
2668   printf(
2669 "  can overlap two or three input elements, and some input edges are not\n");
2670   printf(
2671 "  present in the output mesh.  Hence, a sequence of refined meshes forms a\n"
2672 );
2673   printf(
2674 "  hierarchy of nodes, but not a hierarchy of elements.  If you refine a\n");
2675   printf(
2676 "  mesh of higher-order elements, the hierarchical property applies only to\n"
2677 );
2678   printf(
2679 "  the nodes at the corners of an element; the midpoint nodes on each edge\n");
2680   printf("  are discarded before the mesh is refined.\n\n");
2681   printf(
2682 "  Maximum area constraints in .poly files operate differently from those in\n"
2683 );
2684   printf(
2685 "  .area files.  A maximum area in a .poly file applies to the whole\n");
2686   printf(
2687 "  (segment-bounded) region in which a point falls, whereas a maximum area\n");
2688   printf(
2689 "  in an .area file applies to only one triangle.  Area constraints in .poly\n"
2690 );
2691   printf(
2692 "  files are used only when a mesh is first generated, whereas area\n");
2693   printf(
2694 "  constraints in .area files are used only to refine an existing mesh, and\n"
2695 );
2696   printf(
2697 "  are typically based on a posteriori error estimates resulting from a\n");
2698   printf("  finite element simulation on that mesh.\n\n");
2699   printf(
2700 "  `triangle -rq25 object.1' reads object.1.node and object.1.ele, then\n");
2701   printf(
2702 "  refines the triangulation to enforce a 25 degree minimum angle, and then\n"
2703 );
2704   printf(
2705 "  writes the refined triangulation to object.2.node and object.2.ele.\n");
2706   printf("\n");
2707   printf(
2708 "  `triangle -rpaa6.2 z.3' reads z.3.node, z.3.ele, z.3.poly, and z.3.area.\n"
2709 );
2710   printf(
2711 "  After reconstructing the mesh and its subsegments, Triangle refines the\n");
2712   printf(
2713 "  mesh so that no triangle has area greater than 6.2, and furthermore the\n");
2714   printf(
2715 "  triangles satisfy the maximum area constraints in z.3.area.  No angle\n");
2716   printf(
2717 "  bound is imposed at all.  The output is written to z.4.node, z.4.ele, and\n"
2718 );
2719   printf("  z.4.poly.\n\n");
2720   printf(
2721 "  The sequence `triangle -qa1 x', `triangle -rqa.3 x.1', `triangle -rqa.1\n");
2722   printf(
2723 "  x.2' creates a sequence of successively finer meshes x.1, x.2, and x.3,\n");
2724   printf("  suitable for multigrid.\n\n");
2725   printf("Convex Hulls and Mesh Boundaries:\n\n");
2726   printf(
2727 "  If the input is a vertex set (not a PSLG), Triangle produces its convex\n");
2728   printf(
2729 "  hull as a by-product in the output .poly file if you use the -c switch.\n");
2730   printf(
2731 "  There are faster algorithms for finding a two-dimensional convex hull\n");
2732   printf("  than triangulation, of course, but this one comes for free.\n\n");
2733   printf(
2734 "  If the input is an unconstrained mesh (you are using the -r switch but\n");
2735   printf(
2736 "  not the -p switch), Triangle produces a list of its boundary edges\n");
2737   printf(
2738 "  (including hole boundaries) as a by-product when you use the -c switch.\n");
2739   printf(
2740 "  If you also use the -p switch, the output .poly file contains all the\n");
2741   printf("  segments from the input .poly file as well.\n\n");
2742   printf("Voronoi Diagrams:\n\n");
2743   printf(
2744 "  The -v switch produces a Voronoi diagram, in files suffixed .v.node and\n");
2745   printf(
2746 "  .v.edge.  For example, `triangle -v points' reads points.node, produces\n");
2747   printf(
2748 "  its Delaunay triangulation in points.1.node and points.1.ele, and\n");
2749   printf(
2750 "  produces its Voronoi diagram in points.1.v.node and points.1.v.edge.  The\n"
2751 );
2752   printf(
2753 "  .v.node file contains a list of all Voronoi vertices, and the .v.edge\n");
2754   printf(
2755 "  file contains a list of all Voronoi edges, some of which may be infinite\n"
2756 );
2757   printf(
2758 "  rays.  (The choice of filenames makes it easy to run the set of Voronoi\n");
2759   printf("  vertices through Triangle, if so desired.)\n\n");
2760   printf(
2761 "  This implementation does not use exact arithmetic to compute the Voronoi\n"
2762 );
2763   printf(
2764 "  vertices, and does not check whether neighboring vertices are identical.\n"
2765 );
2766   printf(
2767 "  Be forewarned that if the Delaunay triangulation is degenerate or\n");
2768   printf(
2769 "  near-degenerate, the Voronoi diagram may have duplicate vertices or\n");
2770   printf("  crossing edges.\n\n");
2771   printf(
2772 "  The result is a valid Voronoi diagram only if Triangle's output is a true\n"
2773 );
2774   printf(
2775 "  Delaunay triangulation.  The Voronoi output is usually meaningless (and\n");
2776   printf(
2777 "  may contain crossing edges and other pathology) if the output is a CDT or\n"
2778 );
2779   printf(
2780 "  CCDT, or if it has holes or concavities.  If the triangulated domain is\n");
2781   printf(
2782 "  convex and has no holes, you can use -D switch to force Triangle to\n");
2783   printf(
2784 "  construct a conforming Delaunay triangulation instead of a CCDT, so the\n");
2785   printf("  Voronoi diagram will be valid.\n\n");
2786   printf("Mesh Topology:\n\n");
2787   printf(
2788 "  You may wish to know which triangles are adjacent to a certain Delaunay\n");
2789   printf(
2790 "  edge in an .edge file, which Voronoi cells are adjacent to a certain\n");
2791   printf(
2792 "  Voronoi edge in a .v.edge file, or which Voronoi cells are adjacent to\n");
2793   printf(
2794 "  each other.  All of this information can be found by cross-referencing\n");
2795   printf(
2796 "  output files with the recollection that the Delaunay triangulation and\n");
2797   printf("  the Voronoi diagram are planar duals.\n\n");
2798   printf(
2799 "  Specifically, edge i of an .edge file is the dual of Voronoi edge i of\n");
2800   printf(
2801 "  the corresponding .v.edge file, and is rotated 90 degrees counterclock-\n");
2802   printf(
2803 "  wise from the Voronoi edge.  Triangle j of an .ele file is the dual of\n");
2804   printf(
2805 "  vertex j of the corresponding .v.node file.  Voronoi cell k is the dual\n");
2806   printf("  of vertex k of the corresponding .node file.\n\n");
2807   printf(
2808 "  Hence, to find the triangles adjacent to a Delaunay edge, look at the\n");
2809   printf(
2810 "  vertices of the corresponding Voronoi edge.  If the endpoints of a\n");
2811   printf(
2812 "  Voronoi edge are Voronoi vertices 2 and 6 respectively, then triangles 2\n"
2813 );
2814   printf(
2815 "  and 6 adjoin the left and right sides of the corresponding Delaunay edge,\n"
2816 );
2817   printf(
2818 "  respectively.  To find the Voronoi cells adjacent to a Voronoi edge, look\n"
2819 );
2820   printf(
2821 "  at the endpoints of the corresponding Delaunay edge.  If the endpoints of\n"
2822 );
2823   printf(
2824 "  a Delaunay edge are input vertices 7 and 12, then Voronoi cells 7 and 12\n"
2825 );
2826   printf(
2827 "  adjoin the right and left sides of the corresponding Voronoi edge,\n");
2828   printf(
2829 "  respectively.  To find which Voronoi cells are adjacent to each other,\n");
2830   printf("  just read the list of Delaunay edges.\n\n");
2831   printf(
2832 "  Triangle does not write a list of the edges adjoining each Voronoi cell,\n"
2833 );
2834   printf(
2835 "  but you can reconstructed it straightforwardly.  For instance, to find\n");
2836   printf(
2837 "  all the edges of Voronoi cell 1, search the output .edge file for every\n");
2838   printf(
2839 "  edge that has input vertex 1 as an endpoint.  The corresponding dual\n");
2840   printf(
2841 "  edges in the output .v.edge file form the boundary of Voronoi cell 1.\n");
2842   printf("\n");
2843   printf(
2844 "  For each Voronoi vertex, the .neigh file gives a list of the three\n");
2845   printf(
2846 "  Voronoi vertices attached to it.  You might find this more convenient\n");
2847   printf("  than the .v.edge file.\n\n");
2848   printf("Quadratic Elements:\n\n");
2849   printf(
2850 "  Triangle generates meshes with subparametric quadratic elements if the\n");
2851   printf(
2852 "  -o2 switch is specified.  Quadratic elements have six nodes per element,\n"
2853 );
2854   printf(
2855 "  rather than three.  `Subparametric' means that the edges of the triangles\n"
2856 );
2857   printf(
2858 "  are always straight, so that subparametric quadratic elements are\n");
2859   printf(
2860 "  geometrically identical to linear elements, even though they can be used\n"
2861 );
2862   printf(
2863 "  with quadratic interpolating functions.  The three extra nodes of an\n");
2864   printf(
2865 "  element fall at the midpoints of the three edges, with the fourth, fifth,\n"
2866 );
2867   printf(
2868 "  and sixth nodes appearing opposite the first, second, and third corners\n");
2869   printf("  respectively.\n\n");
2870   printf("Domains with Small Angles:\n\n");
2871   printf(
2872 "  If two input segments adjoin each other at a small angle, clearly the -q\n"
2873 );
2874   printf(
2875 "  switch cannot remove the small angle.  Moreover, Triangle may have no\n");
2876   printf(
2877 "  choice but to generate additional triangles whose smallest angles are\n");
2878   printf(
2879 "  smaller than the specified bound.  However, these triangles only appear\n");
2880   printf(
2881 "  between input segments separated by small angles.  Moreover, if you\n");
2882   printf(
2883 "  request a minimum angle of theta degrees, Triangle will generally produce\n"
2884 );
2885   printf(
2886 "  no angle larger than 180 - 2 theta, even if it is forced to compromise on\n"
2887 );
2888   printf("  the minimum angle.\n\n");
2889   printf("Statistics:\n\n");
2890   printf(
2891 "  After generating a mesh, Triangle prints a count of entities in the\n");
2892   printf(
2893 "  output mesh, including the number of vertices, triangles, edges, exterior\n"
2894 );
2895   printf(
2896 "  boundary edges (i.e. subsegments on the boundary of the triangulation,\n");
2897   printf(
2898 "  including hole boundaries), interior boundary edges (i.e. subsegments of\n"
2899 );
2900   printf(
2901 "  input segments not on the boundary), and total subsegments.  If you've\n");
2902   printf(
2903 "  forgotten the statistics for an existing mesh, run Triangle on that mesh\n"
2904 );
2905   printf(
2906 "  with the -rNEP switches to read the mesh and print the statistics without\n"
2907 );
2908   printf(
2909 "  writing any files.  Use -rpNEP if you've got a .poly file for the mesh.\n");
2910   printf("\n");
2911   printf(
2912 "  The -V switch produces extended statistics, including a rough estimate\n");
2913   printf(
2914 "  of memory use, the number of calls to geometric predicates, and\n");
2915   printf(
2916 "  histograms of the angles and the aspect ratios of the triangles in the\n");
2917   printf("  mesh.\n\n");
2918   printf("Exact Arithmetic:\n\n");
2919   printf(
2920 "  Triangle uses adaptive exact arithmetic to perform what computational\n");
2921   printf(
2922 "  geometers call the `orientation' and `incircle' tests.  If the floating-\n"
2923 );
2924   printf(
2925 "  point arithmetic of your machine conforms to the IEEE 754 standard (as\n");
2926   printf(
2927 "  most workstations do), and does not use extended precision internal\n");
2928   printf(
2929 "  floating-point registers, then your output is guaranteed to be an\n");
2930   printf(
2931 "  absolutely true Delaunay or constrained Delaunay triangulation, roundoff\n"
2932 );
2933   printf(
2934 "  error notwithstanding.  The word `adaptive' implies that these arithmetic\n"
2935 );
2936   printf(
2937 "  routines compute the result only to the precision necessary to guarantee\n"
2938 );
2939   printf(
2940 "  correctness, so they are usually nearly as fast as their approximate\n");
2941   printf("  counterparts.\n\n");
2942   printf(
2943 "  May CPUs, including Intel x86 processors, have extended precision\n");
2944   printf(
2945 "  floating-point registers.  These must be reconfigured so their precision\n"
2946 );
2947   printf(
2948 "  is reduced to memory precision.  Triangle does this if it is compiled\n");
2949   printf("  correctly.  See the makefile for details.\n\n");
2950   printf(
2951 "  The exact tests can be disabled with the -X switch.  On most inputs, this\n"
2952 );
2953   printf(
2954 "  switch reduces the computation time by about eight percent--it's not\n");
2955   printf(
2956 "  worth the risk.  There are rare difficult inputs (having many collinear\n");
2957   printf(
2958 "  and cocircular vertices), however, for which the difference in speed\n");
2959   printf(
2960 "  could be a factor of two.  Be forewarned that these are precisely the\n");
2961   printf(
2962 "  inputs most likely to cause errors if you use the -X switch.  Hence, the\n"
2963 );
2964   printf("  -X switch is not recommended.\n\n");
2965   printf(
2966 "  Unfortunately, the exact tests don't solve every numerical problem.\n");
2967   printf(
2968 "  Exact arithmetic is not used to compute the positions of new vertices,\n");
2969   printf(
2970 "  because the bit complexity of vertex coordinates would grow without\n");
2971   printf(
2972 "  bound.  Hence, segment intersections aren't computed exactly; in very\n");
2973   printf(
2974 "  unusual cases, roundoff error in computing an intersection point might\n");
2975   printf(
2976 "  actually lead to an inverted triangle and an invalid triangulation.\n");
2977   printf(
2978 "  (This is one reason to specify your own intersection points in your .poly\n"
2979 );
2980   printf(
2981 "  files.)  Similarly, exact arithmetic is not used to compute the vertices\n"
2982 );
2983   printf("  of the Voronoi diagram.\n\n");
2984   printf(
2985 "  Another pair of problems not solved by the exact arithmetic routines is\n");
2986   printf(
2987 "  underflow and overflow.  If Triangle is compiled for double precision\n");
2988   printf(
2989 "  arithmetic, I believe that Triangle's geometric predicates work correctly\n"
2990 );
2991   printf(
2992 "  if the exponent of every input coordinate falls in the range [-148, 201].\n"
2993 );
2994   printf(
2995 "  Underflow can silently prevent the orientation and incircle tests from\n");
2996   printf(
2997 "  being performed exactly, while overflow typically causes a floating\n");
2998   printf("  exception.\n\n");
2999   printf("Calling Triangle from Another Program:\n\n");
3000   printf("  Read the file triangle.h for details.\n\n");
3001   printf("Troubleshooting:\n\n");
3002   printf("  Please read this section before mailing me bugs.\n\n");
3003   printf("  `My output mesh has no triangles!'\n\n");
3004   printf(
3005 "    If you're using a PSLG, you've probably failed to specify a proper set\n"
3006 );
3007   printf(
3008 "    of bounding segments, or forgotten to use the -c switch.  Or you may\n");
3009   printf(
3010 "    have placed a hole badly, thereby eating all your triangles.  To test\n");
3011   printf("    these possibilities, try again with the -c and -O switches.\n");
3012   printf(
3013 "    Alternatively, all your input vertices may be collinear, in which case\n"
3014 );
3015   printf("    you can hardly expect to triangulate them.\n\n");
3016   printf("  `Triangle doesn't terminate, or just crashes.'\n\n");
3017   printf(
3018 "    Bad things can happen when triangles get so small that the distance\n");
3019   printf(
3020 "    between their vertices isn't much larger than the precision of your\n");
3021   printf(
3022 "    machine's arithmetic.  If you've compiled Triangle for single-precision\n"
3023 );
3024   printf(
3025 "    arithmetic, you might do better by recompiling it for double-precision.\n"
3026 );
3027   printf(
3028 "    Then again, you might just have to settle for more lenient constraints\n"
3029 );
3030   printf(
3031 "    on the minimum angle and the maximum area than you had planned.\n");
3032   printf("\n");
3033   printf(
3034 "    You can minimize precision problems by ensuring that the origin lies\n");
3035   printf(
3036 "    inside your vertex set, or even inside the densest part of your\n");
3037   printf(
3038 "    mesh.  If you're triangulating an object whose x-coordinates all fall\n");
3039   printf(
3040 "    between 6247133 and 6247134, you're not leaving much floating-point\n");
3041   printf("    precision for Triangle to work with.\n\n");
3042   printf(
3043 "    Precision problems can occur covertly if the input PSLG contains two\n");
3044   printf(
3045 "    segments that meet (or intersect) at an extremely small angle, or if\n");
3046   printf(
3047 "    such an angle is introduced by the -c switch.  If you don't realize\n");
3048   printf(
3049 "    that a tiny angle is being formed, you might never discover why\n");
3050   printf(
3051 "    Triangle is crashing.  To check for this possibility, use the -S switch\n"
3052 );
3053   printf(
3054 "    (with an appropriate limit on the number of Steiner points, found by\n");
3055   printf(
3056 "    trial-and-error) to stop Triangle early, and view the output .poly file\n"
3057 );
3058   printf(
3059 "    with Show Me (described below).  Look carefully for regions where dense\n"
3060 );
3061   printf(
3062 "    clusters of vertices are forming and for small angles between segments.\n"
3063 );
3064   printf(
3065 "    Zoom in closely, as such segments might look like a single segment from\n"
3066 );
3067   printf("    a distance.\n\n");
3068   printf(
3069 "    If some of the input values are too large, Triangle may suffer a\n");
3070   printf(
3071 "    floating exception due to overflow when attempting to perform an\n");
3072   printf(
3073 "    orientation or incircle test.  (Read the section on exact arithmetic\n");
3074   printf(
3075 "    above.)  Again, I recommend compiling Triangle for double (rather\n");
3076   printf("    than single) precision arithmetic.\n\n");
3077   printf(
3078 "    Unexpected problems can arise if you use quality meshing (-q, -a, or\n");
3079   printf(
3080 "    -u) with an input that is not segment-bounded--that is, if your input\n");
3081   printf(
3082 "    is a vertex set, or you're using the -c switch.  If the convex hull of\n"
3083 );
3084   printf(
3085 "    your input vertices has collinear vertices on its boundary, an input\n");
3086   printf(
3087 "    vertex that you think lies on the convex hull might actually lie just\n");
3088   printf(
3089 "    inside the convex hull.  If so, the vertex and the nearby convex hull\n");
3090   printf(
3091 "    edge form an extremely thin triangle.  When Triangle tries to refine\n");
3092   printf(
3093 "    the mesh to enforce angle and area constraints, Triangle might generate\n"
3094 );
3095   printf(
3096 "    extremely tiny triangles, or it might fail because of insufficient\n");
3097   printf("    floating-point precision.\n\n");
3098   printf(
3099 "  `The numbering of the output vertices doesn't match the input vertices.'\n"
3100 );
3101   printf("\n");
3102   printf(
3103 "    You may have had duplicate input vertices, or you may have eaten some\n");
3104   printf(
3105 "    of your input vertices with a hole, or by placing them outside the area\n"
3106 );
3107   printf(
3108 "    enclosed by segments.  In any case, you can solve the problem by not\n");
3109   printf("    using the -j switch.\n\n");
3110   printf(
3111 "  `Triangle executes without incident, but when I look at the resulting\n");
3112   printf(
3113 "  mesh, it has overlapping triangles or other geometric inconsistencies.'\n");
3114   printf("\n");
3115   printf(
3116 "    If you select the -X switch, Triangle occasionally makes mistakes due\n");
3117   printf(
3118 "    to floating-point roundoff error.  Although these errors are rare,\n");
3119   printf(
3120 "    don't use the -X switch.  If you still have problems, please report the\n"
3121 );
3122   printf("    bug.\n\n");
3123   printf(
3124 "  `Triangle executes without incident, but when I look at the resulting\n");
3125   printf("  Voronoi diagram, it has overlapping edges or other geometric\n");
3126   printf("  inconsistencies.'\n");
3127   printf("\n");
3128   printf(
3129 "    If your input is a PSLG (-p), you can only expect a meaningful Voronoi\n"
3130 );
3131   printf(
3132 "    diagram if the domain you are triangulating is convex and free of\n");
3133   printf(
3134 "    holes, and you use the -D switch to construct a conforming Delaunay\n");
3135   printf("    triangulation (instead of a CDT or CCDT).\n\n");
3136   printf(
3137 "  Strange things can happen if you've taken liberties with your PSLG.  Do\n");
3138   printf(
3139 "  you have a vertex lying in the middle of a segment?  Triangle sometimes\n");
3140   printf(
3141 "  copes poorly with that sort of thing.  Do you want to lay out a collinear\n"
3142 );
3143   printf(
3144 "  row of evenly spaced, segment-connected vertices?  Have you simply\n");
3145   printf(
3146 "  defined one long segment connecting the leftmost vertex to the rightmost\n"
3147 );
3148   printf(
3149 "  vertex, and a bunch of vertices lying along it?  This method occasionally\n"
3150 );
3151   printf(
3152 "  works, especially with horizontal and vertical lines, but often it\n");
3153   printf(
3154 "  doesn't, and you'll have to connect each adjacent pair of vertices with a\n"
3155 );
3156   printf("  separate segment.  If you don't like it, tough.\n\n");
3157   printf(
3158 "  Furthermore, if you have segments that intersect other than at their\n");
3159   printf(
3160 "  endpoints, try not to let the intersections fall extremely close to PSLG\n"
3161 );
3162   printf("  vertices or each other.\n\n");
3163   printf(
3164 "  If you have problems refining a triangulation not produced by Triangle:\n");
3165   printf(
3166 "  Are you sure the triangulation is geometrically valid?  Is it formatted\n");
3167   printf(
3168 "  correctly for Triangle?  Are the triangles all listed so the first three\n"
3169 );
3170   printf(
3171 "  vertices are their corners in counterclockwise order?  Are all of the\n");
3172   printf(
3173 "  triangles constrained Delaunay?  Triangle's Delaunay refinement algorithm\n"
3174 );
3175   printf("  assumes that it starts with a CDT.\n\n");
3176   printf("Show Me:\n\n");
3177   printf(
3178 "  Triangle comes with a separate program named `Show Me', whose primary\n");
3179   printf(
3180 "  purpose is to draw meshes on your screen or in PostScript.  Its secondary\n"
3181 );
3182   printf(
3183 "  purpose is to check the validity of your input files, and do so more\n");
3184   printf(
3185 "  thoroughly than Triangle does.  Unlike Triangle, Show Me requires that\n");
3186   printf(
3187 "  you have the X Windows system.  Sorry, Microsoft Windows users.\n");
3188   printf("\n");
3189   printf("Triangle on the Web:\n");
3190   printf("\n");
3191   printf("  To see an illustrated version of these instructions, check out\n");
3192   printf("\n");
3193   printf("    http://www.cs.cmu.edu/~quake/triangle.html\n");
3194   printf("\n");
3195   printf("A Brief Plea:\n");
3196   printf("\n");
3197   printf(
3198 "  If you use Triangle, and especially if you use it to accomplish real\n");
3199   printf(
3200 "  work, I would like very much to hear from you.  A short letter or email\n");
3201   printf(
3202 "  (to jrs@cs.berkeley.edu) describing how you use Triangle will mean a lot\n"
3203 );
3204   printf(
3205 "  to me.  The more people I know are using this program, the more easily I\n"
3206 );
3207   printf(
3208 "  can justify spending time on improvements, which in turn will benefit\n");
3209   printf(
3210 "  you.  Also, I can put you on a list to receive email whenever a new\n");
3211   printf("  version of Triangle is available.\n\n");
3212   printf(
3213 "  If you use a mesh generated by Triangle in a publication, please include\n"
3214 );
3215   printf(
3216 "  an acknowledgment as well.  And please spell Triangle with a capital `T'!\n"
3217 );
3218   printf(
3219 "  If you want to include a citation, use `Jonathan Richard Shewchuk,\n");
3220   printf(
3221 "  ``Triangle: Engineering a 2D Quality Mesh Generator and Delaunay\n");
3222   printf(
3223 "  Triangulator,'' in Applied Computational Geometry:  Towards Geometric\n");
3224   printf(
3225 "  Engineering (Ming C. Lin and Dinesh Manocha, editors), volume 1148 of\n");
3226   printf(
3227 "  Lecture Notes in Computer Science, pages 203-222, Springer-Verlag,\n");
3228   printf(
3229 "  Berlin, May 1996.  (From the First ACM Workshop on Applied Computational\n"
3230 );
3231   printf("  Geometry.)'\n\n");
3232   printf("Research credit:\n\n");
3233   printf(
3234 "  Of course, I can take credit for only a fraction of the ideas that made\n");
3235   printf(
3236 "  this mesh generator possible.  Triangle owes its existence to the efforts\n"
3237 );
3238   printf(
3239 "  of many fine computational geometers and other researchers, including\n");
3240   printf(
3241 "  Marshall Bern, L. Paul Chew, Kenneth L. Clarkson, Boris Delaunay, Rex A.\n"
3242 );
3243   printf(
3244 "  Dwyer, David Eppstein, Steven Fortune, Leonidas J. Guibas, Donald E.\n");
3245   printf(
3246 "  Knuth, Charles L. Lawson, Der-Tsai Lee, Gary L. Miller, Ernst P. Mucke,\n");
3247   printf(
3248 "  Steven E. Pav, Douglas M. Priest, Jim Ruppert, Isaac Saias, Bruce J.\n");
3249   printf(
3250 "  Schachter, Micha Sharir, Peter W. Shor, Daniel D. Sleator, Jorge Stolfi,\n"
3251 );
3252   printf("  Robert E. Tarjan, Alper Ungor, Christopher J. Van Wyk, Noel J.\n");
3253   printf(
3254 "  Walkington, and Binhai Zhu.  See the comments at the beginning of the\n");
3255   printf("  source code for references.\n\n");
3256   triexit(0);
3257 }
3258 
3259 #endif /* not TRILIBRARY */
3260 
3261 /*****************************************************************************/
3262 /*                                                                           */
3263 /*  internalerror()   Ask the user to send me the defective product.  Exit.  */
3264 /*                                                                           */
3265 /*****************************************************************************/
3266 
internalerror()3267 void internalerror()
3268 {
3269   printf("  Please report this bug to jrs@cs.berkeley.edu\n");
3270   printf("  Include the message above, your input data set, and the exact\n");
3271   printf("    command line you used to run Triangle.\n");
3272   triexit(1);
3273 }
3274 
3275 /*****************************************************************************/
3276 /*                                                                           */
3277 /*  parsecommandline()   Read the command line, identify switches, and set   */
3278 /*                       up options and file names.                          */
3279 /*                                                                           */
3280 /*****************************************************************************/
3281 
3282 #ifdef ANSI_DECLARATORS
3283 void parsecommandline(int argc, char **argv, struct behavior *b)
3284 #else /* not ANSI_DECLARATORS */
3285 void parsecommandline(argc, argv, b)
3286 int argc;
3287 char **argv;
3288 struct behavior *b;
3289 #endif /* not ANSI_DECLARATORS */
3290 
3291 {
3292 #ifdef TRILIBRARY
3293 #define STARTINDEX 0
3294 #else /* not TRILIBRARY */
3295 #define STARTINDEX 1
3296   int increment;
3297   int meshnumber;
3298 #endif /* not TRILIBRARY */
3299   int i, j, k;
3300   char workstring[FILENAMESIZE];
3301 
3302   b->poly = b->refine = b->quality = 0;
3303   b->vararea = b->fixedarea = b->usertest = 0;
3304   b->regionattrib = b->convex = b->weighted = b->jettison = 0;
3305   b->firstnumber = 1;
3306   b->edgesout = b->voronoi = b->neighbors = b->geomview = 0;
3307   b->nobound = b->nopolywritten = b->nonodewritten = b->noelewritten = 0;
3308   b->noiterationnum = 0;
3309   b->noholes = b->noexact = 0;
3310   b->incremental = b->sweepline = 0;
3311   b->dwyer = 1;
3312   b->splitseg = 0;
3313   b->docheck = 0;
3314   b->nobisect = 0;
3315   b->conformdel = 0;
3316   b->steiner = -1;
3317   b->order = 1;
3318   b->minangle = 0.0;
3319   b->maxarea = -1.0;
3320   b->quiet = b->verbose = 0;
3321 #ifndef TRILIBRARY
3322   b->innodefilename[0] = '\0';
3323 #endif /* not TRILIBRARY */
3324 
3325   for (i = STARTINDEX; i < argc; i++) {
3326 #ifndef TRILIBRARY
3327     if (argv[i][0] == '-') {
3328 #endif /* not TRILIBRARY */
3329       for (j = STARTINDEX; argv[i][j] != '\0'; j++) {
3330         if (argv[i][j] == 'p') {
3331           b->poly = 1;
3332 	}
3333 #ifndef CDT_ONLY
3334         if (argv[i][j] == 'r') {
3335           b->refine = 1;
3336 	}
3337         if (argv[i][j] == 'q') {
3338           b->quality = 1;
3339           if (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) ||
3340               (argv[i][j + 1] == '.')) {
3341             k = 0;
3342             while (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) ||
3343                    (argv[i][j + 1] == '.')) {
3344               j++;
3345               workstring[k] = argv[i][j];
3346               k++;
3347             }
3348             workstring[k] = '\0';
3349             b->minangle = (REAL) strtod(workstring, (char **) NULL);
3350 	  } else {
3351             b->minangle = 20.0;
3352 	  }
3353 	}
3354         if (argv[i][j] == 'a') {
3355           b->quality = 1;
3356           if (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) ||
3357               (argv[i][j + 1] == '.')) {
3358             b->fixedarea = 1;
3359             k = 0;
3360             while (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) ||
3361                    (argv[i][j + 1] == '.')) {
3362               j++;
3363               workstring[k] = argv[i][j];
3364               k++;
3365             }
3366             workstring[k] = '\0';
3367             b->maxarea = (REAL) strtod(workstring, (char **) NULL);
3368             if (b->maxarea <= 0.0) {
3369               printf("Error:  Maximum area must be greater than zero.\n");
3370               triexit(1);
3371 	    }
3372 	  } else {
3373             b->vararea = 1;
3374 	  }
3375 	}
3376         if (argv[i][j] == 'u') {
3377           b->quality = 1;
3378           b->usertest = 1;
3379         }
3380 #endif /* not CDT_ONLY */
3381         if (argv[i][j] == 'A') {
3382           b->regionattrib = 1;
3383         }
3384         if (argv[i][j] == 'c') {
3385           b->convex = 1;
3386         }
3387         if (argv[i][j] == 'w') {
3388           b->weighted = 1;
3389         }
3390         if (argv[i][j] == 'W') {
3391           b->weighted = 2;
3392         }
3393         if (argv[i][j] == 'j') {
3394           b->jettison = 1;
3395         }
3396         if (argv[i][j] == 'z') {
3397           b->firstnumber = 0;
3398         }
3399         if (argv[i][j] == 'e') {
3400           b->edgesout = 1;
3401 	}
3402         if (argv[i][j] == 'v') {
3403           b->voronoi = 1;
3404 	}
3405         if (argv[i][j] == 'n') {
3406           b->neighbors = 1;
3407 	}
3408         if (argv[i][j] == 'g') {
3409           b->geomview = 1;
3410 	}
3411         if (argv[i][j] == 'B') {
3412           b->nobound = 1;
3413 	}
3414         if (argv[i][j] == 'P') {
3415           b->nopolywritten = 1;
3416 	}
3417         if (argv[i][j] == 'N') {
3418           b->nonodewritten = 1;
3419 	}
3420         if (argv[i][j] == 'E') {
3421           b->noelewritten = 1;
3422 	}
3423 #ifndef TRILIBRARY
3424         if (argv[i][j] == 'I') {
3425           b->noiterationnum = 1;
3426 	}
3427 #endif /* not TRILIBRARY */
3428         if (argv[i][j] == 'O') {
3429           b->noholes = 1;
3430 	}
3431         if (argv[i][j] == 'X') {
3432           b->noexact = 1;
3433 	}
3434         if (argv[i][j] == 'o') {
3435           if (argv[i][j + 1] == '2') {
3436             j++;
3437             b->order = 2;
3438           }
3439 	}
3440 #ifndef CDT_ONLY
3441         if (argv[i][j] == 'Y') {
3442           b->nobisect++;
3443 	}
3444         if (argv[i][j] == 'S') {
3445           b->steiner = 0;
3446           while ((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) {
3447             j++;
3448             b->steiner = b->steiner * 10 + (int) (argv[i][j] - '0');
3449           }
3450         }
3451 #endif /* not CDT_ONLY */
3452 #ifndef REDUCED
3453         if (argv[i][j] == 'i') {
3454           b->incremental = 1;
3455         }
3456         if (argv[i][j] == 'F') {
3457           b->sweepline = 1;
3458         }
3459 #endif /* not REDUCED */
3460         if (argv[i][j] == 'l') {
3461           b->dwyer = 0;
3462         }
3463 #ifndef REDUCED
3464 #ifndef CDT_ONLY
3465         if (argv[i][j] == 's') {
3466           b->splitseg = 1;
3467         }
3468         if ((argv[i][j] == 'D') || (argv[i][j] == 'L')) {
3469           b->quality = 1;
3470           b->conformdel = 1;
3471         }
3472 #endif /* not CDT_ONLY */
3473         if (argv[i][j] == 'C') {
3474           b->docheck = 1;
3475         }
3476 #endif /* not REDUCED */
3477         if (argv[i][j] == 'Q') {
3478           b->quiet = 1;
3479         }
3480         if (argv[i][j] == 'V') {
3481           b->verbose++;
3482         }
3483 #ifndef TRILIBRARY
3484         if ((argv[i][j] == 'h') || (argv[i][j] == 'H') ||
3485             (argv[i][j] == '?')) {
3486           info();
3487 	}
3488 #endif /* not TRILIBRARY */
3489       }
3490 #ifndef TRILIBRARY
3491     } else {
3492       strncpy(b->innodefilename, argv[i], FILENAMESIZE - 1);
3493       b->innodefilename[FILENAMESIZE - 1] = '\0';
3494     }
3495 #endif /* not TRILIBRARY */
3496   }
3497 #ifndef TRILIBRARY
3498   if (b->innodefilename[0] == '\0') {
3499     syntax();
3500   }
3501   if (!strcmp(&b->innodefilename[strlen(b->innodefilename) - 5], ".node")) {
3502     b->innodefilename[strlen(b->innodefilename) - 5] = '\0';
3503   }
3504   if (!strcmp(&b->innodefilename[strlen(b->innodefilename) - 5], ".poly")) {
3505     b->innodefilename[strlen(b->innodefilename) - 5] = '\0';
3506     b->poly = 1;
3507   }
3508 #ifndef CDT_ONLY
3509   if (!strcmp(&b->innodefilename[strlen(b->innodefilename) - 4], ".ele")) {
3510     b->innodefilename[strlen(b->innodefilename) - 4] = '\0';
3511     b->refine = 1;
3512   }
3513   if (!strcmp(&b->innodefilename[strlen(b->innodefilename) - 5], ".area")) {
3514     b->innodefilename[strlen(b->innodefilename) - 5] = '\0';
3515     b->refine = 1;
3516     b->quality = 1;
3517     b->vararea = 1;
3518   }
3519 #endif /* not CDT_ONLY */
3520 #endif /* not TRILIBRARY */
3521   b->usesegments = b->poly || b->refine || b->quality || b->convex;
3522   b->goodangle = cos(b->minangle * PI / 180.0);
3523   if (b->goodangle == 1.0) {
3524     b->offconstant = 0.0;
3525   } else {
3526     b->offconstant = 0.475 * sqrt((1.0 + b->goodangle) / (1.0 - b->goodangle));
3527   }
3528   b->goodangle *= b->goodangle;
3529   if (b->refine && b->noiterationnum) {
3530     printf(
3531       "Error:  You cannot use the -I switch when refining a triangulation.\n");
3532     triexit(1);
3533   }
3534   /* Be careful not to allocate space for element area constraints that */
3535   /*   will never be assigned any value (other than the default -1.0).  */
3536   if (!b->refine && !b->poly) {
3537     b->vararea = 0;
3538   }
3539   /* Be careful not to add an extra attribute to each element unless the */
3540   /*   input supports it (PSLG in, but not refining a preexisting mesh). */
3541   if (b->refine || !b->poly) {
3542     b->regionattrib = 0;
3543   }
3544   /* Regular/weighted triangulations are incompatible with PSLGs */
3545   /*   and meshing.                                              */
3546   if (b->weighted && (b->poly || b->quality)) {
3547     b->weighted = 0;
3548     if (!b->quiet) {
3549       printf("Warning:  weighted triangulations (-w, -W) are incompatible\n");
3550       printf("  with PSLGs (-p) and meshing (-q, -a, -u).  Weights ignored.\n"
3551              );
3552     }
3553   }
3554   if (b->jettison && b->nonodewritten && !b->quiet) {
3555     printf("Warning:  -j and -N switches are somewhat incompatible.\n");
3556     printf("  If any vertices are jettisoned, you will need the output\n");
3557     printf("  .node file to reconstruct the new node indices.");
3558   }
3559 
3560 #ifndef TRILIBRARY
3561   strcpy(b->inpolyfilename, b->innodefilename);
3562   strcpy(b->inelefilename, b->innodefilename);
3563   strcpy(b->areafilename, b->innodefilename);
3564   increment = 0;
3565   strcpy(workstring, b->innodefilename);
3566   j = 1;
3567   while (workstring[j] != '\0') {
3568     if ((workstring[j] == '.') && (workstring[j + 1] != '\0')) {
3569       increment = j + 1;
3570     }
3571     j++;
3572   }
3573   meshnumber = 0;
3574   if (increment > 0) {
3575     j = increment;
3576     do {
3577       if ((workstring[j] >= '0') && (workstring[j] <= '9')) {
3578         meshnumber = meshnumber * 10 + (int) (workstring[j] - '0');
3579       } else {
3580         increment = 0;
3581       }
3582       j++;
3583     } while (workstring[j] != '\0');
3584   }
3585   if (b->noiterationnum) {
3586     strcpy(b->outnodefilename, b->innodefilename);
3587     strcpy(b->outelefilename, b->innodefilename);
3588     strcpy(b->edgefilename, b->innodefilename);
3589     strcpy(b->vnodefilename, b->innodefilename);
3590     strcpy(b->vedgefilename, b->innodefilename);
3591     strcpy(b->neighborfilename, b->innodefilename);
3592     strcpy(b->offfilename, b->innodefilename);
3593     strcat(b->outnodefilename, ".node");
3594     strcat(b->outelefilename, ".ele");
3595     strcat(b->edgefilename, ".edge");
3596     strcat(b->vnodefilename, ".v.node");
3597     strcat(b->vedgefilename, ".v.edge");
3598     strcat(b->neighborfilename, ".neigh");
3599     strcat(b->offfilename, ".off");
3600   } else if (increment == 0) {
3601     strcpy(b->outnodefilename, b->innodefilename);
3602     strcpy(b->outpolyfilename, b->innodefilename);
3603     strcpy(b->outelefilename, b->innodefilename);
3604     strcpy(b->edgefilename, b->innodefilename);
3605     strcpy(b->vnodefilename, b->innodefilename);
3606     strcpy(b->vedgefilename, b->innodefilename);
3607     strcpy(b->neighborfilename, b->innodefilename);
3608     strcpy(b->offfilename, b->innodefilename);
3609     strcat(b->outnodefilename, ".1.node");
3610     strcat(b->outpolyfilename, ".1.poly");
3611     strcat(b->outelefilename, ".1.ele");
3612     strcat(b->edgefilename, ".1.edge");
3613     strcat(b->vnodefilename, ".1.v.node");
3614     strcat(b->vedgefilename, ".1.v.edge");
3615     strcat(b->neighborfilename, ".1.neigh");
3616     strcat(b->offfilename, ".1.off");
3617   } else {
3618     workstring[increment] = '%';
3619     workstring[increment + 1] = 'd';
3620     workstring[increment + 2] = '\0';
3621     sprintf(b->outnodefilename, workstring, meshnumber + 1);
3622     strcpy(b->outpolyfilename, b->outnodefilename);
3623     strcpy(b->outelefilename, b->outnodefilename);
3624     strcpy(b->edgefilename, b->outnodefilename);
3625     strcpy(b->vnodefilename, b->outnodefilename);
3626     strcpy(b->vedgefilename, b->outnodefilename);
3627     strcpy(b->neighborfilename, b->outnodefilename);
3628     strcpy(b->offfilename, b->outnodefilename);
3629     strcat(b->outnodefilename, ".node");
3630     strcat(b->outpolyfilename, ".poly");
3631     strcat(b->outelefilename, ".ele");
3632     strcat(b->edgefilename, ".edge");
3633     strcat(b->vnodefilename, ".v.node");
3634     strcat(b->vedgefilename, ".v.edge");
3635     strcat(b->neighborfilename, ".neigh");
3636     strcat(b->offfilename, ".off");
3637   }
3638   strcat(b->innodefilename, ".node");
3639   strcat(b->inpolyfilename, ".poly");
3640   strcat(b->inelefilename, ".ele");
3641   strcat(b->areafilename, ".area");
3642 #endif /* not TRILIBRARY */
3643 }
3644 
3645 /**                                                                         **/
3646 /**                                                                         **/
3647 /********* User interaction routines begin here                      *********/
3648 
3649 /********* Debugging routines begin here                             *********/
3650 /**                                                                         **/
3651 /**                                                                         **/
3652 
3653 /*****************************************************************************/
3654 /*                                                                           */
3655 /*  printtriangle()   Print out the details of an oriented triangle.         */
3656 /*                                                                           */
3657 /*  I originally wrote this procedure to simplify debugging; it can be       */
3658 /*  called directly from the debugger, and presents information about an     */
3659 /*  oriented triangle in digestible form.  It's also used when the           */
3660 /*  highest level of verbosity (`-VVV') is specified.                        */
3661 /*                                                                           */
3662 /*****************************************************************************/
3663 
3664 #ifdef ANSI_DECLARATORS
3665 void printtriangle(struct mesh *m, struct behavior *b, struct otri *t)
3666 #else /* not ANSI_DECLARATORS */
3667 void printtriangle(m, b, t)
3668 struct mesh *m;
3669 struct behavior *b;
3670 struct otri *t;
3671 #endif /* not ANSI_DECLARATORS */
3672 
3673 {
3674   struct otri printtri;
3675   struct osub printsh;
3676   vertex printvertex;
3677 
3678   printf("triangle x%lx with orientation %d:\n", (unsigned long) t->tri,
3679          t->orient);
3680   decode(t->tri[0], printtri);
3681   if (printtri.tri == m->dummytri) {
3682     printf("    [0] = Outer space\n");
3683   } else {
3684     printf("    [0] = x%lx  %d\n", (unsigned long) printtri.tri,
3685            printtri.orient);
3686   }
3687   decode(t->tri[1], printtri);
3688   if (printtri.tri == m->dummytri) {
3689     printf("    [1] = Outer space\n");
3690   } else {
3691     printf("    [1] = x%lx  %d\n", (unsigned long) printtri.tri,
3692            printtri.orient);
3693   }
3694   decode(t->tri[2], printtri);
3695   if (printtri.tri == m->dummytri) {
3696     printf("    [2] = Outer space\n");
3697   } else {
3698     printf("    [2] = x%lx  %d\n", (unsigned long) printtri.tri,
3699            printtri.orient);
3700   }
3701 
3702   org(*t, printvertex);
3703   if (printvertex == (vertex) NULL)
3704     printf("    Origin[%d] = NULL\n", (t->orient + 1) % 3 + 3);
3705   else
3706     printf("    Origin[%d] = x%lx  (%.12g, %.12g)\n",
3707            (t->orient + 1) % 3 + 3, (unsigned long) printvertex,
3708            printvertex[0], printvertex[1]);
3709   dest(*t, printvertex);
3710   if (printvertex == (vertex) NULL)
3711     printf("    Dest  [%d] = NULL\n", (t->orient + 2) % 3 + 3);
3712   else
3713     printf("    Dest  [%d] = x%lx  (%.12g, %.12g)\n",
3714            (t->orient + 2) % 3 + 3, (unsigned long) printvertex,
3715            printvertex[0], printvertex[1]);
3716   apex(*t, printvertex);
3717   if (printvertex == (vertex) NULL)
3718     printf("    Apex  [%d] = NULL\n", t->orient + 3);
3719   else
3720     printf("    Apex  [%d] = x%lx  (%.12g, %.12g)\n",
3721            t->orient + 3, (unsigned long) printvertex,
3722            printvertex[0], printvertex[1]);
3723 
3724   if (b->usesegments) {
3725     sdecode(t->tri[6], printsh);
3726     if (printsh.ss != m->dummysub) {
3727       printf("    [6] = x%lx  %d\n", (unsigned long) printsh.ss,
3728              printsh.ssorient);
3729     }
3730     sdecode(t->tri[7], printsh);
3731     if (printsh.ss != m->dummysub) {
3732       printf("    [7] = x%lx  %d\n", (unsigned long) printsh.ss,
3733              printsh.ssorient);
3734     }
3735     sdecode(t->tri[8], printsh);
3736     if (printsh.ss != m->dummysub) {
3737       printf("    [8] = x%lx  %d\n", (unsigned long) printsh.ss,
3738              printsh.ssorient);
3739     }
3740   }
3741 
3742   if (b->vararea) {
3743     printf("    Area constraint:  %.4g\n", areabound(*t));
3744   }
3745 }
3746 
3747 /*****************************************************************************/
3748 /*                                                                           */
3749 /*  printsubseg()   Print out the details of an oriented subsegment.         */
3750 /*                                                                           */
3751 /*  I originally wrote this procedure to simplify debugging; it can be       */
3752 /*  called directly from the debugger, and presents information about an     */
3753 /*  oriented subsegment in digestible form.  It's also used when the highest */
3754 /*  level of verbosity (`-VVV') is specified.                                */
3755 /*                                                                           */
3756 /*****************************************************************************/
3757 
3758 #ifdef ANSI_DECLARATORS
3759 void printsubseg(struct mesh *m, struct behavior *b, struct osub *s)
3760 #else /* not ANSI_DECLARATORS */
3761 void printsubseg(m, b, s)
3762 struct mesh *m;
3763 struct behavior *b;
3764 struct osub *s;
3765 #endif /* not ANSI_DECLARATORS */
3766 
3767 {
3768   struct osub printsh;
3769   struct otri printtri;
3770   vertex printvertex;
3771 
3772   printf("subsegment x%lx with orientation %d and mark %d:\n",
3773          (unsigned long) s->ss, s->ssorient, mark(*s));
3774   sdecode(s->ss[0], printsh);
3775   if (printsh.ss == m->dummysub) {
3776     printf("    [0] = No subsegment\n");
3777   } else {
3778     printf("    [0] = x%lx  %d\n", (unsigned long) printsh.ss,
3779            printsh.ssorient);
3780   }
3781   sdecode(s->ss[1], printsh);
3782   if (printsh.ss == m->dummysub) {
3783     printf("    [1] = No subsegment\n");
3784   } else {
3785     printf("    [1] = x%lx  %d\n", (unsigned long) printsh.ss,
3786            printsh.ssorient);
3787   }
3788 
3789   sorg(*s, printvertex);
3790   if (printvertex == (vertex) NULL)
3791     printf("    Origin[%d] = NULL\n", 2 + s->ssorient);
3792   else
3793     printf("    Origin[%d] = x%lx  (%.12g, %.12g)\n",
3794            2 + s->ssorient, (unsigned long) printvertex,
3795            printvertex[0], printvertex[1]);
3796   sdest(*s, printvertex);
3797   if (printvertex == (vertex) NULL)
3798     printf("    Dest  [%d] = NULL\n", 3 - s->ssorient);
3799   else
3800     printf("    Dest  [%d] = x%lx  (%.12g, %.12g)\n",
3801            3 - s->ssorient, (unsigned long) printvertex,
3802            printvertex[0], printvertex[1]);
3803 
3804   decode(s->ss[6], printtri);
3805   if (printtri.tri == m->dummytri) {
3806     printf("    [6] = Outer space\n");
3807   } else {
3808     printf("    [6] = x%lx  %d\n", (unsigned long) printtri.tri,
3809            printtri.orient);
3810   }
3811   decode(s->ss[7], printtri);
3812   if (printtri.tri == m->dummytri) {
3813     printf("    [7] = Outer space\n");
3814   } else {
3815     printf("    [7] = x%lx  %d\n", (unsigned long) printtri.tri,
3816            printtri.orient);
3817   }
3818 
3819   segorg(*s, printvertex);
3820   if (printvertex == (vertex) NULL)
3821     printf("    Segment origin[%d] = NULL\n", 4 + s->ssorient);
3822   else
3823     printf("    Segment origin[%d] = x%lx  (%.12g, %.12g)\n",
3824            4 + s->ssorient, (unsigned long) printvertex,
3825            printvertex[0], printvertex[1]);
3826   segdest(*s, printvertex);
3827   if (printvertex == (vertex) NULL)
3828     printf("    Segment dest  [%d] = NULL\n", 5 - s->ssorient);
3829   else
3830     printf("    Segment dest  [%d] = x%lx  (%.12g, %.12g)\n",
3831            5 - s->ssorient, (unsigned long) printvertex,
3832            printvertex[0], printvertex[1]);
3833 }
3834 
3835 /**                                                                         **/
3836 /**                                                                         **/
3837 /********* Debugging routines end here                               *********/
3838 
3839 /********* Memory management routines begin here                     *********/
3840 /**                                                                         **/
3841 /**                                                                         **/
3842 
3843 /*****************************************************************************/
3844 /*                                                                           */
3845 /*  poolzero()   Set all of a pool's fields to zero.                         */
3846 /*                                                                           */
3847 /*  This procedure should never be called on a pool that has any memory      */
3848 /*  allocated to it, as that memory would leak.                              */
3849 /*                                                                           */
3850 /*****************************************************************************/
3851 
3852 #ifdef ANSI_DECLARATORS
3853 void poolzero(struct memorypool *pool)
3854 #else /* not ANSI_DECLARATORS */
3855 void poolzero(pool)
3856 struct memorypool *pool;
3857 #endif /* not ANSI_DECLARATORS */
3858 
3859 {
3860   pool->firstblock = (VOID **) NULL;
3861   pool->nowblock = (VOID **) NULL;
3862   pool->nextitem = (VOID *) NULL;
3863   pool->deaditemstack = (VOID *) NULL;
3864   pool->pathblock = (VOID **) NULL;
3865   pool->pathitem = (VOID *) NULL;
3866   pool->alignbytes = 0;
3867   pool->itembytes = 0;
3868   pool->itemsperblock = 0;
3869   pool->itemsfirstblock = 0;
3870   pool->items = 0;
3871   pool->maxitems = 0;
3872   pool->unallocateditems = 0;
3873   pool->pathitemsleft = 0;
3874 }
3875 
3876 /*****************************************************************************/
3877 /*                                                                           */
3878 /*  poolrestart()   Deallocate all items in a pool.                          */
3879 /*                                                                           */
3880 /*  The pool is returned to its starting state, except that no memory is     */
3881 /*  freed to the operating system.  Rather, the previously allocated blocks  */
3882 /*  are ready to be reused.                                                  */
3883 /*                                                                           */
3884 /*****************************************************************************/
3885 
3886 #ifdef ANSI_DECLARATORS
3887 void poolrestart(struct memorypool *pool)
3888 #else /* not ANSI_DECLARATORS */
3889 void poolrestart(pool)
3890 struct memorypool *pool;
3891 #endif /* not ANSI_DECLARATORS */
3892 
3893 {
3894   unsigned long alignptr;
3895 
3896   pool->items = 0;
3897   pool->maxitems = 0;
3898 
3899   /* Set the currently active block. */
3900   pool->nowblock = pool->firstblock;
3901   /* Find the first item in the pool.  Increment by the size of (VOID *). */
3902   alignptr = (unsigned long) (pool->nowblock + 1);
3903   /* Align the item on an `alignbytes'-byte boundary. */
3904   pool->nextitem = (VOID *)
3905     (alignptr + (unsigned long) pool->alignbytes -
3906      (alignptr % (unsigned long) pool->alignbytes));
3907   /* There are lots of unallocated items left in this block. */
3908   pool->unallocateditems = pool->itemsfirstblock;
3909   /* The stack of deallocated items is empty. */
3910   pool->deaditemstack = (VOID *) NULL;
3911 }
3912 
3913 /*****************************************************************************/
3914 /*                                                                           */
3915 /*  poolinit()   Initialize a pool of memory for allocation of items.        */
3916 /*                                                                           */
3917 /*  This routine initializes the machinery for allocating items.  A `pool'   */
3918 /*  is created whose records have size at least `bytecount'.  Items will be  */
3919 /*  allocated in `itemcount'-item blocks.  Each item is assumed to be a      */
3920 /*  collection of words, and either pointers or floating-point values are    */
3921 /*  assumed to be the "primary" word type.  (The "primary" word type is used */
3922 /*  to determine alignment of items.)  If `alignment' isn't zero, all items  */
3923 /*  will be `alignment'-byte aligned in memory.  `alignment' must be either  */
3924 /*  a multiple or a factor of the primary word size; powers of two are safe. */
3925 /*  `alignment' is normally used to create a few unused bits at the bottom   */
3926 /*  of each item's pointer, in which information may be stored.              */
3927 /*                                                                           */
3928 /*  Don't change this routine unless you understand it.                      */
3929 /*                                                                           */
3930 /*****************************************************************************/
3931 
3932 #ifdef ANSI_DECLARATORS
3933 void poolinit(struct memorypool *pool, int bytecount, int itemcount,
3934               int firstitemcount, int alignment)
3935 #else /* not ANSI_DECLARATORS */
3936 void poolinit(pool, bytecount, itemcount, firstitemcount, alignment)
3937 struct memorypool *pool;
3938 int bytecount;
3939 int itemcount;
3940 int firstitemcount;
3941 int alignment;
3942 #endif /* not ANSI_DECLARATORS */
3943 
3944 {
3945   /* Find the proper alignment, which must be at least as large as:   */
3946   /*   - The parameter `alignment'.                                   */
3947   /*   - sizeof(VOID *), so the stack of dead items can be maintained */
3948   /*       without unaligned accesses.                                */
3949   if (alignment > sizeof(VOID *)) {
3950     pool->alignbytes = alignment;
3951   } else {
3952     pool->alignbytes = sizeof(VOID *);
3953   }
3954   pool->itembytes = ((bytecount - 1) / pool->alignbytes + 1) *
3955                     pool->alignbytes;
3956   pool->itemsperblock = itemcount;
3957   if (firstitemcount == 0) {
3958     pool->itemsfirstblock = itemcount;
3959   } else {
3960     pool->itemsfirstblock = firstitemcount;
3961   }
3962 
3963   /* Allocate a block of items.  Space for `itemsfirstblock' items and one  */
3964   /*   pointer (to point to the next block) are allocated, as well as space */
3965   /*   to ensure alignment of the items.                                    */
3966   pool->firstblock = (VOID **)
3967     trimalloc(pool->itemsfirstblock * pool->itembytes + (int) sizeof(VOID *) +
3968               pool->alignbytes);
3969   /* Set the next block pointer to NULL. */
3970   *(pool->firstblock) = (VOID *) NULL;
3971   poolrestart(pool);
3972 }
3973 
3974 /*****************************************************************************/
3975 /*                                                                           */
3976 /*  pooldeinit()   Free to the operating system all memory taken by a pool.  */
3977 /*                                                                           */
3978 /*****************************************************************************/
3979 
3980 #ifdef ANSI_DECLARATORS
3981 void pooldeinit(struct memorypool *pool)
3982 #else /* not ANSI_DECLARATORS */
3983 void pooldeinit(pool)
3984 struct memorypool *pool;
3985 #endif /* not ANSI_DECLARATORS */
3986 
3987 {
3988   while (pool->firstblock != (VOID **) NULL) {
3989     pool->nowblock = (VOID **) *(pool->firstblock);
3990     trifree((VOID *) pool->firstblock);
3991     pool->firstblock = pool->nowblock;
3992   }
3993 }
3994 
3995 /*****************************************************************************/
3996 /*                                                                           */
3997 /*  poolalloc()   Allocate space for an item.                                */
3998 /*                                                                           */
3999 /*****************************************************************************/
4000 
4001 #ifdef ANSI_DECLARATORS
4002 VOID *poolalloc(struct memorypool *pool)
4003 #else /* not ANSI_DECLARATORS */
4004 VOID *poolalloc(pool)
4005 struct memorypool *pool;
4006 #endif /* not ANSI_DECLARATORS */
4007 
4008 {
4009   VOID *newitem;
4010   VOID **newblock;
4011   unsigned long alignptr;
4012 
4013   /* First check the linked list of dead items.  If the list is not   */
4014   /*   empty, allocate an item from the list rather than a fresh one. */
4015   if (pool->deaditemstack != (VOID *) NULL) {
4016     newitem = pool->deaditemstack;               /* Take first item in list. */
4017     pool->deaditemstack = * (VOID **) pool->deaditemstack;
4018   } else {
4019     /* Check if there are any free items left in the current block. */
4020     if (pool->unallocateditems == 0) {
4021       /* Check if another block must be allocated. */
4022       if (*(pool->nowblock) == (VOID *) NULL) {
4023         /* Allocate a new block of items, pointed to by the previous block. */
4024         newblock = (VOID **) trimalloc(pool->itemsperblock * pool->itembytes +
4025                                        (int) sizeof(VOID *) +
4026                                        pool->alignbytes);
4027         *(pool->nowblock) = (VOID *) newblock;
4028         /* The next block pointer is NULL. */
4029         *newblock = (VOID *) NULL;
4030       }
4031 
4032       /* Move to the new block. */
4033       pool->nowblock = (VOID **) *(pool->nowblock);
4034       /* Find the first item in the block.    */
4035       /*   Increment by the size of (VOID *). */
4036       alignptr = (unsigned long) (pool->nowblock + 1);
4037       /* Align the item on an `alignbytes'-byte boundary. */
4038       pool->nextitem = (VOID *)
4039         (alignptr + (unsigned long) pool->alignbytes -
4040          (alignptr % (unsigned long) pool->alignbytes));
4041       /* There are lots of unallocated items left in this block. */
4042       pool->unallocateditems = pool->itemsperblock;
4043     }
4044 
4045     /* Allocate a new item. */
4046     newitem = pool->nextitem;
4047     /* Advance `nextitem' pointer to next free item in block. */
4048     pool->nextitem = (VOID *) ((char *) pool->nextitem + pool->itembytes);
4049     pool->unallocateditems--;
4050     pool->maxitems++;
4051   }
4052   pool->items++;
4053   return newitem;
4054 }
4055 
4056 /*****************************************************************************/
4057 /*                                                                           */
4058 /*  pooldealloc()   Deallocate space for an item.                            */
4059 /*                                                                           */
4060 /*  The deallocated space is stored in a queue for later reuse.              */
4061 /*                                                                           */
4062 /*****************************************************************************/
4063 
4064 #ifdef ANSI_DECLARATORS
4065 void pooldealloc(struct memorypool *pool, VOID *dyingitem)
4066 #else /* not ANSI_DECLARATORS */
4067 void pooldealloc(pool, dyingitem)
4068 struct memorypool *pool;
4069 VOID *dyingitem;
4070 #endif /* not ANSI_DECLARATORS */
4071 
4072 {
4073   /* Push freshly killed item onto stack. */
4074   *((VOID **) dyingitem) = pool->deaditemstack;
4075   pool->deaditemstack = dyingitem;
4076   pool->items--;
4077 }
4078 
4079 /*****************************************************************************/
4080 /*                                                                           */
4081 /*  traversalinit()   Prepare to traverse the entire list of items.          */
4082 /*                                                                           */
4083 /*  This routine is used in conjunction with traverse().                     */
4084 /*                                                                           */
4085 /*****************************************************************************/
4086 
4087 #ifdef ANSI_DECLARATORS
4088 void traversalinit(struct memorypool *pool)
4089 #else /* not ANSI_DECLARATORS */
4090 void traversalinit(pool)
4091 struct memorypool *pool;
4092 #endif /* not ANSI_DECLARATORS */
4093 
4094 {
4095   unsigned long alignptr;
4096 
4097   /* Begin the traversal in the first block. */
4098   pool->pathblock = pool->firstblock;
4099   /* Find the first item in the block.  Increment by the size of (VOID *). */
4100   alignptr = (unsigned long) (pool->pathblock + 1);
4101   /* Align with item on an `alignbytes'-byte boundary. */
4102   pool->pathitem = (VOID *)
4103     (alignptr + (unsigned long) pool->alignbytes -
4104      (alignptr % (unsigned long) pool->alignbytes));
4105   /* Set the number of items left in the current block. */
4106   pool->pathitemsleft = pool->itemsfirstblock;
4107 }
4108 
4109 /*****************************************************************************/
4110 /*                                                                           */
4111 /*  traverse()   Find the next item in the list.                             */
4112 /*                                                                           */
4113 /*  This routine is used in conjunction with traversalinit().  Be forewarned */
4114 /*  that this routine successively returns all items in the list, including  */
4115 /*  deallocated ones on the deaditemqueue.  It's up to you to figure out     */
4116 /*  which ones are actually dead.  Why?  I don't want to allocate extra      */
4117 /*  space just to demarcate dead items.  It can usually be done more         */
4118 /*  space-efficiently by a routine that knows something about the structure  */
4119 /*  of the item.                                                             */
4120 /*                                                                           */
4121 /*****************************************************************************/
4122 
4123 #ifdef ANSI_DECLARATORS
4124 VOID *traverse(struct memorypool *pool)
4125 #else /* not ANSI_DECLARATORS */
4126 VOID *traverse(pool)
4127 struct memorypool *pool;
4128 #endif /* not ANSI_DECLARATORS */
4129 
4130 {
4131   VOID *newitem;
4132   unsigned long alignptr;
4133 
4134   /* Stop upon exhausting the list of items. */
4135   if (pool->pathitem == pool->nextitem) {
4136     return (VOID *) NULL;
4137   }
4138 
4139   /* Check whether any untraversed items remain in the current block. */
4140   if (pool->pathitemsleft == 0) {
4141     /* Find the next block. */
4142     pool->pathblock = (VOID **) *(pool->pathblock);
4143     /* Find the first item in the block.  Increment by the size of (VOID *). */
4144     alignptr = (unsigned long) (pool->pathblock + 1);
4145     /* Align with item on an `alignbytes'-byte boundary. */
4146     pool->pathitem = (VOID *)
4147       (alignptr + (unsigned long) pool->alignbytes -
4148        (alignptr % (unsigned long) pool->alignbytes));
4149     /* Set the number of items left in the current block. */
4150     pool->pathitemsleft = pool->itemsperblock;
4151   }
4152 
4153   newitem = pool->pathitem;
4154   /* Find the next item in the block. */
4155   pool->pathitem = (VOID *) ((char *) pool->pathitem + pool->itembytes);
4156   pool->pathitemsleft--;
4157   return newitem;
4158 }
4159 
4160 /*****************************************************************************/
4161 /*                                                                           */
4162 /*  dummyinit()   Initialize the triangle that fills "outer space" and the   */
4163 /*                omnipresent subsegment.                                    */
4164 /*                                                                           */
4165 /*  The triangle that fills "outer space," called `dummytri', is pointed to  */
4166 /*  by every triangle and subsegment on a boundary (be it outer or inner) of */
4167 /*  the triangulation.  Also, `dummytri' points to one of the triangles on   */
4168 /*  the convex hull (until the holes and concavities are carved), making it  */
4169 /*  possible to find a starting triangle for point location.                 */
4170 /*                                                                           */
4171 /*  The omnipresent subsegment, `dummysub', is pointed to by every triangle  */
4172 /*  or subsegment that doesn't have a full complement of real subsegments    */
4173 /*  to point to.                                                             */
4174 /*                                                                           */
4175 /*  `dummytri' and `dummysub' are generally required to fulfill only a few   */
4176 /*  invariants:  their vertices must remain NULL and `dummytri' must always  */
4177 /*  be bonded (at offset zero) to some triangle on the convex hull of the    */
4178 /*  mesh, via a boundary edge.  Otherwise, the connections of `dummytri' and */
4179 /*  `dummysub' may change willy-nilly.  This makes it possible to avoid      */
4180 /*  writing a good deal of special-case code (in the edge flip, for example) */
4181 /*  for dealing with the boundary of the mesh, places where no subsegment is */
4182 /*  present, and so forth.  Other entities are frequently bonded to          */
4183 /*  `dummytri' and `dummysub' as if they were real mesh entities, with no    */
4184 /*  harm done.                                                               */
4185 /*                                                                           */
4186 /*****************************************************************************/
4187 
4188 #ifdef ANSI_DECLARATORS
4189 void dummyinit(struct mesh *m, struct behavior *b, int trianglebytes,
4190                int subsegbytes)
4191 #else /* not ANSI_DECLARATORS */
4192 void dummyinit(m, b, trianglebytes, subsegbytes)
4193 struct mesh *m;
4194 struct behavior *b;
4195 int trianglebytes;
4196 int subsegbytes;
4197 #endif /* not ANSI_DECLARATORS */
4198 
4199 {
4200   unsigned long alignptr;
4201 
4202   /* Set up `dummytri', the `triangle' that occupies "outer space." */
4203   m->dummytribase = (triangle *) trimalloc(trianglebytes +
4204                                            m->triangles.alignbytes);
4205   /* Align `dummytri' on a `triangles.alignbytes'-byte boundary. */
4206   alignptr = (unsigned long) m->dummytribase;
4207   m->dummytri = (triangle *)
4208     (alignptr + (unsigned long) m->triangles.alignbytes -
4209      (alignptr % (unsigned long) m->triangles.alignbytes));
4210   /* Initialize the three adjoining triangles to be "outer space."  These  */
4211   /*   will eventually be changed by various bonding operations, but their */
4212   /*   values don't really matter, as long as they can legally be          */
4213   /*   dereferenced.                                                       */
4214   m->dummytri[0] = (triangle) m->dummytri;
4215   m->dummytri[1] = (triangle) m->dummytri;
4216   m->dummytri[2] = (triangle) m->dummytri;
4217   /* Three NULL vertices. */
4218   m->dummytri[3] = (triangle) NULL;
4219   m->dummytri[4] = (triangle) NULL;
4220   m->dummytri[5] = (triangle) NULL;
4221 
4222   if (b->usesegments) {
4223     /* Set up `dummysub', the omnipresent subsegment pointed to by any */
4224     /*   triangle side or subsegment end that isn't attached to a real */
4225     /*   subsegment.                                                   */
4226     m->dummysubbase = (subseg *) trimalloc(subsegbytes +
4227                                            m->subsegs.alignbytes);
4228     /* Align `dummysub' on a `subsegs.alignbytes'-byte boundary. */
4229     alignptr = (unsigned long) m->dummysubbase;
4230     m->dummysub = (subseg *)
4231       (alignptr + (unsigned long) m->subsegs.alignbytes -
4232        (alignptr % (unsigned long) m->subsegs.alignbytes));
4233     /* Initialize the two adjoining subsegments to be the omnipresent      */
4234     /*   subsegment.  These will eventually be changed by various bonding  */
4235     /*   operations, but their values don't really matter, as long as they */
4236     /*   can legally be dereferenced.                                      */
4237     m->dummysub[0] = (subseg) m->dummysub;
4238     m->dummysub[1] = (subseg) m->dummysub;
4239     /* Four NULL vertices. */
4240     m->dummysub[2] = (subseg) NULL;
4241     m->dummysub[3] = (subseg) NULL;
4242     m->dummysub[4] = (subseg) NULL;
4243     m->dummysub[5] = (subseg) NULL;
4244     /* Initialize the two adjoining triangles to be "outer space." */
4245     m->dummysub[6] = (subseg) m->dummytri;
4246     m->dummysub[7] = (subseg) m->dummytri;
4247     /* Set the boundary marker to zero. */
4248     * (int *) (m->dummysub + 8) = 0;
4249 
4250     /* Initialize the three adjoining subsegments of `dummytri' to be */
4251     /*   the omnipresent subsegment.                                  */
4252     m->dummytri[6] = (triangle) m->dummysub;
4253     m->dummytri[7] = (triangle) m->dummysub;
4254     m->dummytri[8] = (triangle) m->dummysub;
4255   }
4256 }
4257 
4258 /*****************************************************************************/
4259 /*                                                                           */
4260 /*  initializevertexpool()   Calculate the size of the vertex data structure */
4261 /*                           and initialize its memory pool.                 */
4262 /*                                                                           */
4263 /*  This routine also computes the `vertexmarkindex' and `vertex2triindex'   */
4264 /*  indices used to find values within each vertex.                          */
4265 /*                                                                           */
4266 /*****************************************************************************/
4267 
4268 #ifdef ANSI_DECLARATORS
4269 void initializevertexpool(struct mesh *m, struct behavior *b)
4270 #else /* not ANSI_DECLARATORS */
4271 void initializevertexpool(m, b)
4272 struct mesh *m;
4273 struct behavior *b;
4274 #endif /* not ANSI_DECLARATORS */
4275 
4276 {
4277   int vertexsize;
4278 
4279   /* The index within each vertex at which the boundary marker is found,    */
4280   /*   followed by the vertex type.  Ensure the vertex marker is aligned to */
4281   /*   a sizeof(int)-byte address.                                          */
4282   m->vertexmarkindex = ((m->mesh_dim + m->nextras) * sizeof(REAL) +
4283                         sizeof(int) - 1) /
4284                        sizeof(int);
4285   vertexsize = (m->vertexmarkindex + 2) * sizeof(int);
4286   if (b->poly) {
4287     /* The index within each vertex at which a triangle pointer is found.  */
4288     /*   Ensure the pointer is aligned to a sizeof(triangle)-byte address. */
4289     m->vertex2triindex = (vertexsize + sizeof(triangle) - 1) /
4290                          sizeof(triangle);
4291     vertexsize = (m->vertex2triindex + 1) * sizeof(triangle);
4292   }
4293 
4294   /* Initialize the pool of vertices. */
4295   poolinit(&m->vertices, vertexsize, VERTEXPERBLOCK,
4296            m->invertices > VERTEXPERBLOCK ? m->invertices : VERTEXPERBLOCK,
4297            sizeof(REAL));
4298 }
4299 
4300 /*****************************************************************************/
4301 /*                                                                           */
4302 /*  initializetrisubpools()   Calculate the sizes of the triangle and        */
4303 /*                            subsegment data structures and initialize      */
4304 /*                            their memory pools.                            */
4305 /*                                                                           */
4306 /*  This routine also computes the `highorderindex', `elemattribindex', and  */
4307 /*  `areaboundindex' indices used to find values within each triangle.       */
4308 /*                                                                           */
4309 /*****************************************************************************/
4310 
4311 #ifdef ANSI_DECLARATORS
4312 void initializetrisubpools(struct mesh *m, struct behavior *b)
4313 #else /* not ANSI_DECLARATORS */
4314 void initializetrisubpools(m, b)
4315 struct mesh *m;
4316 struct behavior *b;
4317 #endif /* not ANSI_DECLARATORS */
4318 
4319 {
4320   int trisize;
4321 
4322   /* The index within each triangle at which the extra nodes (above three)  */
4323   /*   associated with high order elements are found.  There are three      */
4324   /*   pointers to other triangles, three pointers to corners, and possibly */
4325   /*   three pointers to subsegments before the extra nodes.                */
4326   m->highorderindex = 6 + (b->usesegments * 3);
4327   /* The number of bytes occupied by a triangle. */
4328   trisize = ((b->order + 1) * (b->order + 2) / 2 + (m->highorderindex - 3)) *
4329             sizeof(triangle);
4330   /* The index within each triangle at which its attributes are found, */
4331   /*   where the index is measured in REALs.                           */
4332   m->elemattribindex = (trisize + sizeof(REAL) - 1) / sizeof(REAL);
4333   /* The index within each triangle at which the maximum area constraint  */
4334   /*   is found, where the index is measured in REALs.  Note that if the  */
4335   /*   `regionattrib' flag is set, an additional attribute will be added. */
4336   m->areaboundindex = m->elemattribindex + m->eextras + b->regionattrib;
4337   /* If triangle attributes or an area bound are needed, increase the number */
4338   /*   of bytes occupied by a triangle.                                      */
4339   if (b->vararea) {
4340     trisize = (m->areaboundindex + 1) * sizeof(REAL);
4341   } else if (m->eextras + b->regionattrib > 0) {
4342     trisize = m->areaboundindex * sizeof(REAL);
4343   }
4344   /* If a Voronoi diagram or triangle neighbor graph is requested, make    */
4345   /*   sure there's room to store an integer index in each triangle.  This */
4346   /*   integer index can occupy the same space as the subsegment pointers  */
4347   /*   or attributes or area constraint or extra nodes.                    */
4348   if ((b->voronoi || b->neighbors) &&
4349       (trisize < 6 * sizeof(triangle) + sizeof(int))) {
4350     trisize = 6 * sizeof(triangle) + sizeof(int);
4351   }
4352 
4353   /* Having determined the memory size of a triangle, initialize the pool. */
4354   poolinit(&m->triangles, trisize, TRIPERBLOCK,
4355            (2 * m->invertices - 2) > TRIPERBLOCK ? (2 * m->invertices - 2) :
4356            TRIPERBLOCK, 4);
4357 
4358   if (b->usesegments) {
4359     /* Initialize the pool of subsegments.  Take into account all eight */
4360     /*   pointers and one boundary marker.                              */
4361     poolinit(&m->subsegs, 8 * sizeof(triangle) + sizeof(int),
4362              SUBSEGPERBLOCK, SUBSEGPERBLOCK, 4);
4363 
4364     /* Initialize the "outer space" triangle and omnipresent subsegment. */
4365     dummyinit(m, b, m->triangles.itembytes, m->subsegs.itembytes);
4366   } else {
4367     /* Initialize the "outer space" triangle. */
4368     dummyinit(m, b, m->triangles.itembytes, 0);
4369   }
4370 }
4371 
4372 /*****************************************************************************/
4373 /*                                                                           */
4374 /*  triangledealloc()   Deallocate space for a triangle, marking it dead.    */
4375 /*                                                                           */
4376 /*****************************************************************************/
4377 
4378 #ifdef ANSI_DECLARATORS
4379 void triangledealloc(struct mesh *m, triangle *dyingtriangle)
4380 #else /* not ANSI_DECLARATORS */
4381 void triangledealloc(m, dyingtriangle)
4382 struct mesh *m;
4383 triangle *dyingtriangle;
4384 #endif /* not ANSI_DECLARATORS */
4385 
4386 {
4387   /* Mark the triangle as dead.  This makes it possible to detect dead */
4388   /*   triangles when traversing the list of all triangles.            */
4389   killtri(dyingtriangle);
4390   pooldealloc(&m->triangles, (VOID *) dyingtriangle);
4391 }
4392 
4393 /*****************************************************************************/
4394 /*                                                                           */
4395 /*  triangletraverse()   Traverse the triangles, skipping dead ones.         */
4396 /*                                                                           */
4397 /*****************************************************************************/
4398 
4399 #ifdef ANSI_DECLARATORS
4400 triangle *triangletraverse(struct mesh *m)
4401 #else /* not ANSI_DECLARATORS */
4402 triangle *triangletraverse(m)
4403 struct mesh *m;
4404 #endif /* not ANSI_DECLARATORS */
4405 
4406 {
4407   triangle *newtriangle;
4408 
4409   do {
4410     newtriangle = (triangle *) traverse(&m->triangles);
4411     if (newtriangle == (triangle *) NULL) {
4412       return (triangle *) NULL;
4413     }
4414   } while (deadtri(newtriangle));                         /* Skip dead ones. */
4415   return newtriangle;
4416 }
4417 
4418 /*****************************************************************************/
4419 /*                                                                           */
4420 /*  subsegdealloc()   Deallocate space for a subsegment, marking it dead.    */
4421 /*                                                                           */
4422 /*****************************************************************************/
4423 
4424 #ifdef ANSI_DECLARATORS
4425 void subsegdealloc(struct mesh *m, subseg *dyingsubseg)
4426 #else /* not ANSI_DECLARATORS */
4427 void subsegdealloc(m, dyingsubseg)
4428 struct mesh *m;
4429 subseg *dyingsubseg;
4430 #endif /* not ANSI_DECLARATORS */
4431 
4432 {
4433   /* Mark the subsegment as dead.  This makes it possible to detect dead */
4434   /*   subsegments when traversing the list of all subsegments.          */
4435   killsubseg(dyingsubseg);
4436   pooldealloc(&m->subsegs, (VOID *) dyingsubseg);
4437 }
4438 
4439 /*****************************************************************************/
4440 /*                                                                           */
4441 /*  subsegtraverse()   Traverse the subsegments, skipping dead ones.         */
4442 /*                                                                           */
4443 /*****************************************************************************/
4444 
4445 #ifdef ANSI_DECLARATORS
4446 subseg *subsegtraverse(struct mesh *m)
4447 #else /* not ANSI_DECLARATORS */
4448 subseg *subsegtraverse(m)
4449 struct mesh *m;
4450 #endif /* not ANSI_DECLARATORS */
4451 
4452 {
4453   subseg *newsubseg;
4454 
4455   do {
4456     newsubseg = (subseg *) traverse(&m->subsegs);
4457     if (newsubseg == (subseg *) NULL) {
4458       return (subseg *) NULL;
4459     }
4460   } while (deadsubseg(newsubseg));                        /* Skip dead ones. */
4461   return newsubseg;
4462 }
4463 
4464 /*****************************************************************************/
4465 /*                                                                           */
4466 /*  vertexdealloc()   Deallocate space for a vertex, marking it dead.        */
4467 /*                                                                           */
4468 /*****************************************************************************/
4469 
4470 #ifdef ANSI_DECLARATORS
4471 void vertexdealloc(struct mesh *m, vertex dyingvertex)
4472 #else /* not ANSI_DECLARATORS */
4473 void vertexdealloc(m, dyingvertex)
4474 struct mesh *m;
4475 vertex dyingvertex;
4476 #endif /* not ANSI_DECLARATORS */
4477 
4478 {
4479   /* Mark the vertex as dead.  This makes it possible to detect dead */
4480   /*   vertices when traversing the list of all vertices.            */
4481   setvertextype(dyingvertex, DEADVERTEX);
4482   pooldealloc(&m->vertices, (VOID *) dyingvertex);
4483 }
4484 
4485 /*****************************************************************************/
4486 /*                                                                           */
4487 /*  vertextraverse()   Traverse the vertices, skipping dead ones.            */
4488 /*                                                                           */
4489 /*****************************************************************************/
4490 
4491 #ifdef ANSI_DECLARATORS
4492 vertex vertextraverse(struct mesh *m)
4493 #else /* not ANSI_DECLARATORS */
4494 vertex vertextraverse(m)
4495 struct mesh *m;
4496 #endif /* not ANSI_DECLARATORS */
4497 
4498 {
4499   vertex newvertex;
4500 
4501   do {
4502     newvertex = (vertex) traverse(&m->vertices);
4503     if (newvertex == (vertex) NULL) {
4504       return (vertex) NULL;
4505     }
4506   } while (vertextype(newvertex) == DEADVERTEX);          /* Skip dead ones. */
4507   return newvertex;
4508 }
4509 
4510 /*****************************************************************************/
4511 /*                                                                           */
4512 /*  badsubsegdealloc()   Deallocate space for a bad subsegment, marking it   */
4513 /*                       dead.                                               */
4514 /*                                                                           */
4515 /*****************************************************************************/
4516 
4517 #ifndef CDT_ONLY
4518 
4519 #ifdef ANSI_DECLARATORS
4520 void badsubsegdealloc(struct mesh *m, struct badsubseg *dyingseg)
4521 #else /* not ANSI_DECLARATORS */
4522 void badsubsegdealloc(m, dyingseg)
4523 struct mesh *m;
4524 struct badsubseg *dyingseg;
4525 #endif /* not ANSI_DECLARATORS */
4526 
4527 {
4528   /* Set subsegment's origin to NULL.  This makes it possible to detect dead */
4529   /*   badsubsegs when traversing the list of all badsubsegs             .   */
4530   dyingseg->subsegorg = (vertex) NULL;
4531   pooldealloc(&m->badsubsegs, (VOID *) dyingseg);
4532 }
4533 
4534 #endif /* not CDT_ONLY */
4535 
4536 /*****************************************************************************/
4537 /*                                                                           */
4538 /*  badsubsegtraverse()   Traverse the bad subsegments, skipping dead ones.  */
4539 /*                                                                           */
4540 /*****************************************************************************/
4541 
4542 #ifndef CDT_ONLY
4543 
4544 #ifdef ANSI_DECLARATORS
4545 struct badsubseg *badsubsegtraverse(struct mesh *m)
4546 #else /* not ANSI_DECLARATORS */
4547 struct badsubseg *badsubsegtraverse(m)
4548 struct mesh *m;
4549 #endif /* not ANSI_DECLARATORS */
4550 
4551 {
4552   struct badsubseg *newseg;
4553 
4554   do {
4555     newseg = (struct badsubseg *) traverse(&m->badsubsegs);
4556     if (newseg == (struct badsubseg *) NULL) {
4557       return (struct badsubseg *) NULL;
4558     }
4559   } while (newseg->subsegorg == (vertex) NULL);           /* Skip dead ones. */
4560   return newseg;
4561 }
4562 
4563 #endif /* not CDT_ONLY */
4564 
4565 /*****************************************************************************/
4566 /*                                                                           */
4567 /*  getvertex()   Get a specific vertex, by number, from the list.           */
4568 /*                                                                           */
4569 /*  The first vertex is number 'firstnumber'.                                */
4570 /*                                                                           */
4571 /*  Note that this takes O(n) time (with a small constant, if VERTEXPERBLOCK */
4572 /*  is large).  I don't care to take the trouble to make it work in constant */
4573 /*  time.                                                                    */
4574 /*                                                                           */
4575 /*****************************************************************************/
4576 
4577 #ifdef ANSI_DECLARATORS
4578 vertex getvertex(struct mesh *m, struct behavior *b, int number)
4579 #else /* not ANSI_DECLARATORS */
4580 vertex getvertex(m, b, number)
4581 struct mesh *m;
4582 struct behavior *b;
4583 int number;
4584 #endif /* not ANSI_DECLARATORS */
4585 
4586 {
4587   VOID **getblock;
4588   char *foundvertex;
4589   unsigned long alignptr;
4590   int current;
4591 
4592   getblock = m->vertices.firstblock;
4593   current = b->firstnumber;
4594 
4595   /* Find the right block. */
4596   if (current + m->vertices.itemsfirstblock <= number) {
4597     getblock = (VOID **) *getblock;
4598     current += m->vertices.itemsfirstblock;
4599     while (current + m->vertices.itemsperblock <= number) {
4600       getblock = (VOID **) *getblock;
4601       current += m->vertices.itemsperblock;
4602     }
4603   }
4604 
4605   /* Now find the right vertex. */
4606   alignptr = (unsigned long) (getblock + 1);
4607   foundvertex = (char *) (alignptr + (unsigned long) m->vertices.alignbytes -
4608                           (alignptr % (unsigned long) m->vertices.alignbytes));
4609   return (vertex) (foundvertex + m->vertices.itembytes * (number - current));
4610 }
4611 
4612 /*****************************************************************************/
4613 /*                                                                           */
4614 /*  triangledeinit()   Free all remaining allocated memory.                  */
4615 /*                                                                           */
4616 /*****************************************************************************/
4617 
4618 #ifdef ANSI_DECLARATORS
4619 void triangledeinit(struct mesh *m, struct behavior *b)
4620 #else /* not ANSI_DECLARATORS */
4621 void triangledeinit(m, b)
4622 struct mesh *m;
4623 struct behavior *b;
4624 #endif /* not ANSI_DECLARATORS */
4625 
4626 {
4627   pooldeinit(&m->triangles);
4628   trifree((VOID *) m->dummytribase);
4629   if (b->usesegments) {
4630     pooldeinit(&m->subsegs);
4631     trifree((VOID *) m->dummysubbase);
4632   }
4633   pooldeinit(&m->vertices);
4634 #ifndef CDT_ONLY
4635   if (b->quality) {
4636     pooldeinit(&m->badsubsegs);
4637     if ((b->minangle > 0.0) || b->vararea || b->fixedarea || b->usertest) {
4638       pooldeinit(&m->badtriangles);
4639       pooldeinit(&m->flipstackers);
4640     }
4641   }
4642 #endif /* not CDT_ONLY */
4643 }
4644 
4645 /**                                                                         **/
4646 /**                                                                         **/
4647 /********* Memory management routines end here                       *********/
4648 
4649 /********* Constructors begin here                                   *********/
4650 /**                                                                         **/
4651 /**                                                                         **/
4652 
4653 /*****************************************************************************/
4654 /*                                                                           */
4655 /*  maketriangle()   Create a new triangle with orientation zero.            */
4656 /*                                                                           */
4657 /*****************************************************************************/
4658 
4659 #ifdef ANSI_DECLARATORS
4660 void maketriangle(struct mesh *m, struct behavior *b, struct otri *newotri)
4661 #else /* not ANSI_DECLARATORS */
4662 void maketriangle(m, b, newotri)
4663 struct mesh *m;
4664 struct behavior *b;
4665 struct otri *newotri;
4666 #endif /* not ANSI_DECLARATORS */
4667 
4668 {
4669   int i;
4670 
4671   newotri->tri = (triangle *) poolalloc(&m->triangles);
4672   /* Initialize the three adjoining triangles to be "outer space". */
4673   newotri->tri[0] = (triangle) m->dummytri;
4674   newotri->tri[1] = (triangle) m->dummytri;
4675   newotri->tri[2] = (triangle) m->dummytri;
4676   /* Three NULL vertices. */
4677   newotri->tri[3] = (triangle) NULL;
4678   newotri->tri[4] = (triangle) NULL;
4679   newotri->tri[5] = (triangle) NULL;
4680   if (b->usesegments) {
4681     /* Initialize the three adjoining subsegments to be the omnipresent */
4682     /*   subsegment.                                                    */
4683     newotri->tri[6] = (triangle) m->dummysub;
4684     newotri->tri[7] = (triangle) m->dummysub;
4685     newotri->tri[8] = (triangle) m->dummysub;
4686   }
4687   for (i = 0; i < m->eextras; i++) {
4688     setelemattribute(*newotri, i, 0.0);
4689   }
4690   if (b->vararea) {
4691     setareabound(*newotri, -1.0);
4692   }
4693 
4694   newotri->orient = 0;
4695 }
4696 
4697 /*****************************************************************************/
4698 /*                                                                           */
4699 /*  makesubseg()   Create a new subsegment with orientation zero.            */
4700 /*                                                                           */
4701 /*****************************************************************************/
4702 
4703 #ifdef ANSI_DECLARATORS
4704 void makesubseg(struct mesh *m, struct osub *newsubseg)
4705 #else /* not ANSI_DECLARATORS */
4706 void makesubseg(m, newsubseg)
4707 struct mesh *m;
4708 struct osub *newsubseg;
4709 #endif /* not ANSI_DECLARATORS */
4710 
4711 {
4712   newsubseg->ss = (subseg *) poolalloc(&m->subsegs);
4713   /* Initialize the two adjoining subsegments to be the omnipresent */
4714   /*   subsegment.                                                  */
4715   newsubseg->ss[0] = (subseg) m->dummysub;
4716   newsubseg->ss[1] = (subseg) m->dummysub;
4717   /* Four NULL vertices. */
4718   newsubseg->ss[2] = (subseg) NULL;
4719   newsubseg->ss[3] = (subseg) NULL;
4720   newsubseg->ss[4] = (subseg) NULL;
4721   newsubseg->ss[5] = (subseg) NULL;
4722   /* Initialize the two adjoining triangles to be "outer space." */
4723   newsubseg->ss[6] = (subseg) m->dummytri;
4724   newsubseg->ss[7] = (subseg) m->dummytri;
4725   /* Set the boundary marker to zero. */
4726   setmark(*newsubseg, 0);
4727 
4728   newsubseg->ssorient = 0;
4729 }
4730 
4731 /**                                                                         **/
4732 /**                                                                         **/
4733 /********* Constructors end here                                     *********/
4734 
4735 /********* Geometric primitives begin here                           *********/
4736 /**                                                                         **/
4737 /**                                                                         **/
4738 
4739 /* The adaptive exact arithmetic geometric predicates implemented herein are */
4740 /*   described in detail in my paper, "Adaptive Precision Floating-Point     */
4741 /*   Arithmetic and Fast Robust Geometric Predicates."  See the header for a */
4742 /*   full citation.                                                          */
4743 
4744 /* Which of the following two methods of finding the absolute values is      */
4745 /*   fastest is compiler-dependent.  A few compilers can inline and optimize */
4746 /*   the fabs() call; but most will incur the overhead of a function call,   */
4747 /*   which is disastrously slow.  A faster way on IEEE machines might be to  */
4748 /*   mask the appropriate bit, but that's difficult to do in C without       */
4749 /*   forcing the value to be stored to memory (rather than be kept in the    */
4750 /*   register to which the optimizer assigned it).                           */
4751 
4752 #define Absolute(a)  ((a) >= 0.0 ? (a) : -(a))
4753 /* #define Absolute(a)  fabs(a) */
4754 
4755 /* Many of the operations are broken up into two pieces, a main part that    */
4756 /*   performs an approximate operation, and a "tail" that computes the       */
4757 /*   roundoff error of that operation.                                       */
4758 /*                                                                           */
4759 /* The operations Fast_Two_Sum(), Fast_Two_Diff(), Two_Sum(), Two_Diff(),    */
4760 /*   Split(), and Two_Product() are all implemented as described in the      */
4761 /*   reference.  Each of these macros requires certain variables to be       */
4762 /*   defined in the calling routine.  The variables `bvirt', `c', `abig',    */
4763 /*   `_i', `_j', `_k', `_l', `_m', and `_n' are declared `INEXACT' because   */
4764 /*   they store the result of an operation that may incur roundoff error.    */
4765 /*   The input parameter `x' (or the highest numbered `x_' parameter) must   */
4766 /*   also be declared `INEXACT'.                                             */
4767 
4768 #define Fast_Two_Sum_Tail(a, b, x, y) \
4769   bvirt = x - a; \
4770   y = b - bvirt
4771 
4772 #define Fast_Two_Sum(a, b, x, y) \
4773   x = (REAL) (a + b); \
4774   Fast_Two_Sum_Tail(a, b, x, y)
4775 
4776 #define Two_Sum_Tail(a, b, x, y) \
4777   bvirt = (REAL) (x - a); \
4778   avirt = x - bvirt; \
4779   bround = b - bvirt; \
4780   around = a - avirt; \
4781   y = around + bround
4782 
4783 #define Two_Sum(a, b, x, y) \
4784   x = (REAL) (a + b); \
4785   Two_Sum_Tail(a, b, x, y)
4786 
4787 #define Two_Diff_Tail(a, b, x, y) \
4788   bvirt = (REAL) (a - x); \
4789   avirt = x + bvirt; \
4790   bround = bvirt - b; \
4791   around = a - avirt; \
4792   y = around + bround
4793 
4794 #define Two_Diff(a, b, x, y) \
4795   x = (REAL) (a - b); \
4796   Two_Diff_Tail(a, b, x, y)
4797 
4798 #define Split(a, ahi, alo) \
4799   c = (REAL) (splitter * a); \
4800   abig = (REAL) (c - a); \
4801   ahi = c - abig; \
4802   alo = a - ahi
4803 
4804 #define Two_Product_Tail(a, b, x, y) \
4805   Split(a, ahi, alo); \
4806   Split(b, bhi, blo); \
4807   err1 = x - (ahi * bhi); \
4808   err2 = err1 - (alo * bhi); \
4809   err3 = err2 - (ahi * blo); \
4810   y = (alo * blo) - err3
4811 
4812 #define Two_Product(a, b, x, y) \
4813   x = (REAL) (a * b); \
4814   Two_Product_Tail(a, b, x, y)
4815 
4816 /* Two_Product_Presplit() is Two_Product() where one of the inputs has       */
4817 /*   already been split.  Avoids redundant splitting.                        */
4818 
4819 #define Two_Product_Presplit(a, b, bhi, blo, x, y) \
4820   x = (REAL) (a * b); \
4821   Split(a, ahi, alo); \
4822   err1 = x - (ahi * bhi); \
4823   err2 = err1 - (alo * bhi); \
4824   err3 = err2 - (ahi * blo); \
4825   y = (alo * blo) - err3
4826 
4827 /* Square() can be done more quickly than Two_Product().                     */
4828 
4829 #define Square_Tail(a, x, y) \
4830   Split(a, ahi, alo); \
4831   err1 = x - (ahi * ahi); \
4832   err3 = err1 - ((ahi + ahi) * alo); \
4833   y = (alo * alo) - err3
4834 
4835 #define Square(a, x, y) \
4836   x = (REAL) (a * a); \
4837   Square_Tail(a, x, y)
4838 
4839 /* Macros for summing expansions of various fixed lengths.  These are all    */
4840 /*   unrolled versions of Expansion_Sum().                                   */
4841 
4842 #define Two_One_Sum(a1, a0, b, x2, x1, x0) \
4843   Two_Sum(a0, b , _i, x0); \
4844   Two_Sum(a1, _i, x2, x1)
4845 
4846 #define Two_One_Diff(a1, a0, b, x2, x1, x0) \
4847   Two_Diff(a0, b , _i, x0); \
4848   Two_Sum( a1, _i, x2, x1)
4849 
4850 #define Two_Two_Sum(a1, a0, b1, b0, x3, x2, x1, x0) \
4851   Two_One_Sum(a1, a0, b0, _j, _0, x0); \
4852   Two_One_Sum(_j, _0, b1, x3, x2, x1)
4853 
4854 #define Two_Two_Diff(a1, a0, b1, b0, x3, x2, x1, x0) \
4855   Two_One_Diff(a1, a0, b0, _j, _0, x0); \
4856   Two_One_Diff(_j, _0, b1, x3, x2, x1)
4857 
4858 /* Macro for multiplying a two-component expansion by a single component.    */
4859 
4860 #define Two_One_Product(a1, a0, b, x3, x2, x1, x0) \
4861   Split(b, bhi, blo); \
4862   Two_Product_Presplit(a0, b, bhi, blo, _i, x0); \
4863   Two_Product_Presplit(a1, b, bhi, blo, _j, _0); \
4864   Two_Sum(_i, _0, _k, x1); \
4865   Fast_Two_Sum(_j, _k, x3, x2)
4866 
4867 /*****************************************************************************/
4868 /*                                                                           */
4869 /*  exactinit()   Initialize the variables used for exact arithmetic.        */
4870 /*                                                                           */
4871 /*  `epsilon' is the largest power of two such that 1.0 + epsilon = 1.0 in   */
4872 /*  floating-point arithmetic.  `epsilon' bounds the relative roundoff       */
4873 /*  error.  It is used for floating-point error analysis.                    */
4874 /*                                                                           */
4875 /*  `splitter' is used to split floating-point numbers into two half-        */
4876 /*  length significands for exact multiplication.                            */
4877 /*                                                                           */
4878 /*  I imagine that a highly optimizing compiler might be too smart for its   */
4879 /*  own good, and somehow cause this routine to fail, if it pretends that    */
4880 /*  floating-point arithmetic is too much like real arithmetic.              */
4881 /*                                                                           */
4882 /*  Don't change this routine unless you fully understand it.                */
4883 /*                                                                           */
4884 /*****************************************************************************/
4885 
exactinit()4886 void exactinit()
4887 {
4888   REAL half;
4889   REAL check, lastcheck;
4890   int every_other;
4891 #ifdef LINUX
4892   int cword;
4893 #endif /* LINUX */
4894 
4895 #ifdef CPU86
4896 #ifdef SINGLE
4897   _control87(_PC_24, _MCW_PC); /* Set FPU control word for single precision. */
4898 #else /* not SINGLE */
4899   _control87(_PC_53, _MCW_PC); /* Set FPU control word for double precision. */
4900 #endif /* not SINGLE */
4901 #endif /* CPU86 */
4902 #ifdef LINUX
4903 #ifdef SINGLE
4904   /*  cword = 4223; */
4905   cword = 4210;                 /* set FPU control word for single precision */
4906 #else /* not SINGLE */
4907   /*  cword = 4735; */
4908   cword = 4722;                 /* set FPU control word for double precision */
4909 #endif /* not SINGLE */
4910   _FPU_SETCW(cword);
4911 #endif /* LINUX */
4912 
4913   every_other = 1;
4914   half = 0.5;
4915   epsilon = 1.0;
4916   splitter = 1.0;
4917   check = 1.0;
4918   /* Repeatedly divide `epsilon' by two until it is too small to add to      */
4919   /*   one without causing roundoff.  (Also check if the sum is equal to     */
4920   /*   the previous sum, for machines that round up instead of using exact   */
4921   /*   rounding.  Not that these routines will work on such machines.)       */
4922   do {
4923     lastcheck = check;
4924     epsilon *= half;
4925     if (every_other) {
4926       splitter *= 2.0;
4927     }
4928     every_other = !every_other;
4929     check = 1.0 + epsilon;
4930   } while ((check != 1.0) && (check != lastcheck));
4931   splitter += 1.0;
4932   /* Error bounds for orientation and incircle tests. */
4933   resulterrbound = (3.0 + 8.0 * epsilon) * epsilon;
4934   ccwerrboundA = (3.0 + 16.0 * epsilon) * epsilon;
4935   ccwerrboundB = (2.0 + 12.0 * epsilon) * epsilon;
4936   ccwerrboundC = (9.0 + 64.0 * epsilon) * epsilon * epsilon;
4937   iccerrboundA = (10.0 + 96.0 * epsilon) * epsilon;
4938   iccerrboundB = (4.0 + 48.0 * epsilon) * epsilon;
4939   iccerrboundC = (44.0 + 576.0 * epsilon) * epsilon * epsilon;
4940   o3derrboundA = (7.0 + 56.0 * epsilon) * epsilon;
4941   o3derrboundB = (3.0 + 28.0 * epsilon) * epsilon;
4942   o3derrboundC = (26.0 + 288.0 * epsilon) * epsilon * epsilon;
4943 }
4944 
4945 /*****************************************************************************/
4946 /*                                                                           */
4947 /*  fast_expansion_sum_zeroelim()   Sum two expansions, eliminating zero     */
4948 /*                                  components from the output expansion.    */
4949 /*                                                                           */
4950 /*  Sets h = e + f.  See my Robust Predicates paper for details.             */
4951 /*                                                                           */
4952 /*  If round-to-even is used (as with IEEE 754), maintains the strongly      */
4953 /*  nonoverlapping property.  (That is, if e is strongly nonoverlapping, h   */
4954 /*  will be also.)  Does NOT maintain the nonoverlapping or nonadjacent      */
4955 /*  properties.                                                              */
4956 /*                                                                           */
4957 /*****************************************************************************/
4958 
4959 #ifdef ANSI_DECLARATORS
4960 int fast_expansion_sum_zeroelim(int elen, REAL *e, int flen, REAL *f, REAL *h)
4961 #else /* not ANSI_DECLARATORS */
4962 int fast_expansion_sum_zeroelim(elen, e, flen, f, h)  /* h cannot be e or f. */
4963 int elen;
4964 REAL *e;
4965 int flen;
4966 REAL *f;
4967 REAL *h;
4968 #endif /* not ANSI_DECLARATORS */
4969 
4970 {
4971   REAL Q;
4972   INEXACT REAL Qnew;
4973   INEXACT REAL hh;
4974   INEXACT REAL bvirt;
4975   REAL avirt, bround, around;
4976   int eindex, findex, hindex;
4977   REAL enow, fnow;
4978 
4979   enow = e[0];
4980   fnow = f[0];
4981   eindex = findex = 0;
4982   if ((fnow > enow) == (fnow > -enow)) {
4983     Q = enow;
4984     enow = e[++eindex];
4985   } else {
4986     Q = fnow;
4987     fnow = f[++findex];
4988   }
4989   hindex = 0;
4990   if ((eindex < elen) && (findex < flen)) {
4991     if ((fnow > enow) == (fnow > -enow)) {
4992       Fast_Two_Sum(enow, Q, Qnew, hh);
4993       enow = e[++eindex];
4994     } else {
4995       Fast_Two_Sum(fnow, Q, Qnew, hh);
4996       fnow = f[++findex];
4997     }
4998     Q = Qnew;
4999     if (hh != 0.0) {
5000       h[hindex++] = hh;
5001     }
5002     while ((eindex < elen) && (findex < flen)) {
5003       if ((fnow > enow) == (fnow > -enow)) {
5004         Two_Sum(Q, enow, Qnew, hh);
5005         enow = e[++eindex];
5006       } else {
5007         Two_Sum(Q, fnow, Qnew, hh);
5008         fnow = f[++findex];
5009       }
5010       Q = Qnew;
5011       if (hh != 0.0) {
5012         h[hindex++] = hh;
5013       }
5014     }
5015   }
5016   while (eindex < elen) {
5017     Two_Sum(Q, enow, Qnew, hh);
5018     enow = e[++eindex];
5019     Q = Qnew;
5020     if (hh != 0.0) {
5021       h[hindex++] = hh;
5022     }
5023   }
5024   while (findex < flen) {
5025     Two_Sum(Q, fnow, Qnew, hh);
5026     fnow = f[++findex];
5027     Q = Qnew;
5028     if (hh != 0.0) {
5029       h[hindex++] = hh;
5030     }
5031   }
5032   if ((Q != 0.0) || (hindex == 0)) {
5033     h[hindex++] = Q;
5034   }
5035   return hindex;
5036 }
5037 
5038 /*****************************************************************************/
5039 /*                                                                           */
5040 /*  scale_expansion_zeroelim()   Multiply an expansion by a scalar,          */
5041 /*                               eliminating zero components from the        */
5042 /*                               output expansion.                           */
5043 /*                                                                           */
5044 /*  Sets h = be.  See my Robust Predicates paper for details.                */
5045 /*                                                                           */
5046 /*  Maintains the nonoverlapping property.  If round-to-even is used (as     */
5047 /*  with IEEE 754), maintains the strongly nonoverlapping and nonadjacent    */
5048 /*  properties as well.  (That is, if e has one of these properties, so      */
5049 /*  will h.)                                                                 */
5050 /*                                                                           */
5051 /*****************************************************************************/
5052 
5053 #ifdef ANSI_DECLARATORS
5054 int scale_expansion_zeroelim(int elen, REAL *e, REAL b, REAL *h)
5055 #else /* not ANSI_DECLARATORS */
5056 int scale_expansion_zeroelim(elen, e, b, h)   /* e and h cannot be the same. */
5057 int elen;
5058 REAL *e;
5059 REAL b;
5060 REAL *h;
5061 #endif /* not ANSI_DECLARATORS */
5062 
5063 {
5064   INEXACT REAL Q, sum;
5065   REAL hh;
5066   INEXACT REAL product1;
5067   REAL product0;
5068   int eindex, hindex;
5069   REAL enow;
5070   INEXACT REAL bvirt;
5071   REAL avirt, bround, around;
5072   INEXACT REAL c;
5073   INEXACT REAL abig;
5074   REAL ahi, alo, bhi, blo;
5075   REAL err1, err2, err3;
5076 
5077   Split(b, bhi, blo);
5078   Two_Product_Presplit(e[0], b, bhi, blo, Q, hh);
5079   hindex = 0;
5080   if (hh != 0) {
5081     h[hindex++] = hh;
5082   }
5083   for (eindex = 1; eindex < elen; eindex++) {
5084     enow = e[eindex];
5085     Two_Product_Presplit(enow, b, bhi, blo, product1, product0);
5086     Two_Sum(Q, product0, sum, hh);
5087     if (hh != 0) {
5088       h[hindex++] = hh;
5089     }
5090     Fast_Two_Sum(product1, sum, Q, hh);
5091     if (hh != 0) {
5092       h[hindex++] = hh;
5093     }
5094   }
5095   if ((Q != 0.0) || (hindex == 0)) {
5096     h[hindex++] = Q;
5097   }
5098   return hindex;
5099 }
5100 
5101 /*****************************************************************************/
5102 /*                                                                           */
5103 /*  estimate()   Produce a one-word estimate of an expansion's value.        */
5104 /*                                                                           */
5105 /*  See my Robust Predicates paper for details.                              */
5106 /*                                                                           */
5107 /*****************************************************************************/
5108 
5109 #ifdef ANSI_DECLARATORS
5110 REAL estimate(int elen, REAL *e)
5111 #else /* not ANSI_DECLARATORS */
5112 REAL estimate(elen, e)
5113 int elen;
5114 REAL *e;
5115 #endif /* not ANSI_DECLARATORS */
5116 
5117 {
5118   REAL Q;
5119   int eindex;
5120 
5121   Q = e[0];
5122   for (eindex = 1; eindex < elen; eindex++) {
5123     Q += e[eindex];
5124   }
5125   return Q;
5126 }
5127 
5128 /*****************************************************************************/
5129 /*                                                                           */
5130 /*  counterclockwise()   Return a positive value if the points pa, pb, and   */
5131 /*                       pc occur in counterclockwise order; a negative      */
5132 /*                       value if they occur in clockwise order; and zero    */
5133 /*                       if they are collinear.  The result is also a rough  */
5134 /*                       approximation of twice the signed area of the       */
5135 /*                       triangle defined by the three points.               */
5136 /*                                                                           */
5137 /*  Uses exact arithmetic if necessary to ensure a correct answer.  The      */
5138 /*  result returned is the determinant of a matrix.  This determinant is     */
5139 /*  computed adaptively, in the sense that exact arithmetic is used only to  */
5140 /*  the degree it is needed to ensure that the returned value has the        */
5141 /*  correct sign.  Hence, this function is usually quite fast, but will run  */
5142 /*  more slowly when the input points are collinear or nearly so.            */
5143 /*                                                                           */
5144 /*  See my Robust Predicates paper for details.                              */
5145 /*                                                                           */
5146 /*****************************************************************************/
5147 
5148 #ifdef ANSI_DECLARATORS
5149 REAL counterclockwiseadapt(vertex pa, vertex pb, vertex pc, REAL detsum)
5150 #else /* not ANSI_DECLARATORS */
5151 REAL counterclockwiseadapt(pa, pb, pc, detsum)
5152 vertex pa;
5153 vertex pb;
5154 vertex pc;
5155 REAL detsum;
5156 #endif /* not ANSI_DECLARATORS */
5157 
5158 {
5159   INEXACT REAL acx, acy, bcx, bcy;
5160   REAL acxtail, acytail, bcxtail, bcytail;
5161   INEXACT REAL detleft, detright;
5162   REAL detlefttail, detrighttail;
5163   REAL det, errbound;
5164   REAL B[4], C1[8], C2[12], D[16];
5165   INEXACT REAL B3;
5166   int C1length, C2length, Dlength;
5167   REAL u[4];
5168   INEXACT REAL u3;
5169   INEXACT REAL s1, t1;
5170   REAL s0, t0;
5171 
5172   INEXACT REAL bvirt;
5173   REAL avirt, bround, around;
5174   INEXACT REAL c;
5175   INEXACT REAL abig;
5176   REAL ahi, alo, bhi, blo;
5177   REAL err1, err2, err3;
5178   INEXACT REAL _i, _j;
5179   REAL _0;
5180 
5181   acx = (REAL) (pa[0] - pc[0]);
5182   bcx = (REAL) (pb[0] - pc[0]);
5183   acy = (REAL) (pa[1] - pc[1]);
5184   bcy = (REAL) (pb[1] - pc[1]);
5185 
5186   Two_Product(acx, bcy, detleft, detlefttail);
5187   Two_Product(acy, bcx, detright, detrighttail);
5188 
5189   Two_Two_Diff(detleft, detlefttail, detright, detrighttail,
5190                B3, B[2], B[1], B[0]);
5191   B[3] = B3;
5192 
5193   det = estimate(4, B);
5194   errbound = ccwerrboundB * detsum;
5195   if ((det >= errbound) || (-det >= errbound)) {
5196     return det;
5197   }
5198 
5199   Two_Diff_Tail(pa[0], pc[0], acx, acxtail);
5200   Two_Diff_Tail(pb[0], pc[0], bcx, bcxtail);
5201   Two_Diff_Tail(pa[1], pc[1], acy, acytail);
5202   Two_Diff_Tail(pb[1], pc[1], bcy, bcytail);
5203 
5204   if ((acxtail == 0.0) && (acytail == 0.0)
5205       && (bcxtail == 0.0) && (bcytail == 0.0)) {
5206     return det;
5207   }
5208 
5209   errbound = ccwerrboundC * detsum + resulterrbound * Absolute(det);
5210   det += (acx * bcytail + bcy * acxtail)
5211        - (acy * bcxtail + bcx * acytail);
5212   if ((det >= errbound) || (-det >= errbound)) {
5213     return det;
5214   }
5215 
5216   Two_Product(acxtail, bcy, s1, s0);
5217   Two_Product(acytail, bcx, t1, t0);
5218   Two_Two_Diff(s1, s0, t1, t0, u3, u[2], u[1], u[0]);
5219   u[3] = u3;
5220   C1length = fast_expansion_sum_zeroelim(4, B, 4, u, C1);
5221 
5222   Two_Product(acx, bcytail, s1, s0);
5223   Two_Product(acy, bcxtail, t1, t0);
5224   Two_Two_Diff(s1, s0, t1, t0, u3, u[2], u[1], u[0]);
5225   u[3] = u3;
5226   C2length = fast_expansion_sum_zeroelim(C1length, C1, 4, u, C2);
5227 
5228   Two_Product(acxtail, bcytail, s1, s0);
5229   Two_Product(acytail, bcxtail, t1, t0);
5230   Two_Two_Diff(s1, s0, t1, t0, u3, u[2], u[1], u[0]);
5231   u[3] = u3;
5232   Dlength = fast_expansion_sum_zeroelim(C2length, C2, 4, u, D);
5233 
5234   return(D[Dlength - 1]);
5235 }
5236 
5237 #ifdef ANSI_DECLARATORS
5238 REAL counterclockwise(struct mesh *m, struct behavior *b,
5239                       vertex pa, vertex pb, vertex pc)
5240 #else /* not ANSI_DECLARATORS */
5241 REAL counterclockwise(m, b, pa, pb, pc)
5242 struct mesh *m;
5243 struct behavior *b;
5244 vertex pa;
5245 vertex pb;
5246 vertex pc;
5247 #endif /* not ANSI_DECLARATORS */
5248 
5249 {
5250   REAL detleft, detright, det;
5251   REAL detsum, errbound;
5252 
5253   m->counterclockcount++;
5254 
5255   detleft = (pa[0] - pc[0]) * (pb[1] - pc[1]);
5256   detright = (pa[1] - pc[1]) * (pb[0] - pc[0]);
5257   det = detleft - detright;
5258 
5259   if (b->noexact) {
5260     return det;
5261   }
5262 
5263   if (detleft > 0.0) {
5264     if (detright <= 0.0) {
5265       return det;
5266     } else {
5267       detsum = detleft + detright;
5268     }
5269   } else if (detleft < 0.0) {
5270     if (detright >= 0.0) {
5271       return det;
5272     } else {
5273       detsum = -detleft - detright;
5274     }
5275   } else {
5276     return det;
5277   }
5278 
5279   errbound = ccwerrboundA * detsum;
5280   if ((det >= errbound) || (-det >= errbound)) {
5281     return det;
5282   }
5283 
5284   return counterclockwiseadapt(pa, pb, pc, detsum);
5285 }
5286 
5287 /*****************************************************************************/
5288 /*                                                                           */
5289 /*  incircle()   Return a positive value if the point pd lies inside the     */
5290 /*               circle passing through pa, pb, and pc; a negative value if  */
5291 /*               it lies outside; and zero if the four points are cocircular.*/
5292 /*               The points pa, pb, and pc must be in counterclockwise       */
5293 /*               order, or the sign of the result will be reversed.          */
5294 /*                                                                           */
5295 /*  Uses exact arithmetic if necessary to ensure a correct answer.  The      */
5296 /*  result returned is the determinant of a matrix.  This determinant is     */
5297 /*  computed adaptively, in the sense that exact arithmetic is used only to  */
5298 /*  the degree it is needed to ensure that the returned value has the        */
5299 /*  correct sign.  Hence, this function is usually quite fast, but will run  */
5300 /*  more slowly when the input points are cocircular or nearly so.           */
5301 /*                                                                           */
5302 /*  See my Robust Predicates paper for details.                              */
5303 /*                                                                           */
5304 /*****************************************************************************/
5305 
5306 #ifdef ANSI_DECLARATORS
5307 REAL incircleadapt(vertex pa, vertex pb, vertex pc, vertex pd, REAL permanent)
5308 #else /* not ANSI_DECLARATORS */
5309 REAL incircleadapt(pa, pb, pc, pd, permanent)
5310 vertex pa;
5311 vertex pb;
5312 vertex pc;
5313 vertex pd;
5314 REAL permanent;
5315 #endif /* not ANSI_DECLARATORS */
5316 
5317 {
5318   INEXACT REAL adx, bdx, cdx, ady, bdy, cdy;
5319   REAL det, errbound;
5320 
5321   INEXACT REAL bdxcdy1, cdxbdy1, cdxady1, adxcdy1, adxbdy1, bdxady1;
5322   REAL bdxcdy0, cdxbdy0, cdxady0, adxcdy0, adxbdy0, bdxady0;
5323   REAL bc[4], ca[4], ab[4];
5324   INEXACT REAL bc3, ca3, ab3;
5325   REAL axbc[8], axxbc[16], aybc[8], ayybc[16], adet[32];
5326   int axbclen, axxbclen, aybclen, ayybclen, alen;
5327   REAL bxca[8], bxxca[16], byca[8], byyca[16], bdet[32];
5328   int bxcalen, bxxcalen, bycalen, byycalen, blen;
5329   REAL cxab[8], cxxab[16], cyab[8], cyyab[16], cdet[32];
5330   int cxablen, cxxablen, cyablen, cyyablen, clen;
5331   REAL abdet[64];
5332   int ablen;
5333   REAL fin1[1152], fin2[1152];
5334   REAL *finnow, *finother, *finswap;
5335   int finlength;
5336 
5337   REAL adxtail, bdxtail, cdxtail, adytail, bdytail, cdytail;
5338   INEXACT REAL adxadx1, adyady1, bdxbdx1, bdybdy1, cdxcdx1, cdycdy1;
5339   REAL adxadx0, adyady0, bdxbdx0, bdybdy0, cdxcdx0, cdycdy0;
5340   REAL aa[4], bb[4], cc[4];
5341   INEXACT REAL aa3, bb3, cc3;
5342   INEXACT REAL ti1, tj1;
5343   REAL ti0, tj0;
5344   REAL u[4], v[4];
5345   INEXACT REAL u3, v3;
5346   REAL temp8[8], temp16a[16], temp16b[16], temp16c[16];
5347   REAL temp32a[32], temp32b[32], temp48[48], temp64[64];
5348   int temp8len, temp16alen, temp16blen, temp16clen;
5349   int temp32alen, temp32blen, temp48len, temp64len;
5350   REAL axtbb[8], axtcc[8], aytbb[8], aytcc[8];
5351   int axtbblen, axtcclen, aytbblen, aytcclen;
5352   REAL bxtaa[8], bxtcc[8], bytaa[8], bytcc[8];
5353   int bxtaalen, bxtcclen, bytaalen, bytcclen;
5354   REAL cxtaa[8], cxtbb[8], cytaa[8], cytbb[8];
5355   int cxtaalen, cxtbblen, cytaalen, cytbblen;
5356   REAL axtbc[8], aytbc[8], bxtca[8], bytca[8], cxtab[8], cytab[8];
5357   int axtbclen, aytbclen, bxtcalen, bytcalen, cxtablen, cytablen;
5358   REAL axtbct[16], aytbct[16], bxtcat[16], bytcat[16], cxtabt[16], cytabt[16];
5359   int axtbctlen, aytbctlen, bxtcatlen, bytcatlen, cxtabtlen, cytabtlen;
5360   REAL axtbctt[8], aytbctt[8], bxtcatt[8];
5361   REAL bytcatt[8], cxtabtt[8], cytabtt[8];
5362   int axtbcttlen, aytbcttlen, bxtcattlen, bytcattlen, cxtabttlen, cytabttlen;
5363   REAL abt[8], bct[8], cat[8];
5364   int abtlen, bctlen, catlen;
5365   REAL abtt[4], bctt[4], catt[4];
5366   int abttlen, bcttlen, cattlen;
5367   INEXACT REAL abtt3, bctt3, catt3;
5368   REAL negate;
5369 
5370   INEXACT REAL bvirt;
5371   REAL avirt, bround, around;
5372   INEXACT REAL c;
5373   INEXACT REAL abig;
5374   REAL ahi, alo, bhi, blo;
5375   REAL err1, err2, err3;
5376   INEXACT REAL _i, _j;
5377   REAL _0;
5378 
5379   adx = (REAL) (pa[0] - pd[0]);
5380   bdx = (REAL) (pb[0] - pd[0]);
5381   cdx = (REAL) (pc[0] - pd[0]);
5382   ady = (REAL) (pa[1] - pd[1]);
5383   bdy = (REAL) (pb[1] - pd[1]);
5384   cdy = (REAL) (pc[1] - pd[1]);
5385 
5386   Two_Product(bdx, cdy, bdxcdy1, bdxcdy0);
5387   Two_Product(cdx, bdy, cdxbdy1, cdxbdy0);
5388   Two_Two_Diff(bdxcdy1, bdxcdy0, cdxbdy1, cdxbdy0, bc3, bc[2], bc[1], bc[0]);
5389   bc[3] = bc3;
5390   axbclen = scale_expansion_zeroelim(4, bc, adx, axbc);
5391   axxbclen = scale_expansion_zeroelim(axbclen, axbc, adx, axxbc);
5392   aybclen = scale_expansion_zeroelim(4, bc, ady, aybc);
5393   ayybclen = scale_expansion_zeroelim(aybclen, aybc, ady, ayybc);
5394   alen = fast_expansion_sum_zeroelim(axxbclen, axxbc, ayybclen, ayybc, adet);
5395 
5396   Two_Product(cdx, ady, cdxady1, cdxady0);
5397   Two_Product(adx, cdy, adxcdy1, adxcdy0);
5398   Two_Two_Diff(cdxady1, cdxady0, adxcdy1, adxcdy0, ca3, ca[2], ca[1], ca[0]);
5399   ca[3] = ca3;
5400   bxcalen = scale_expansion_zeroelim(4, ca, bdx, bxca);
5401   bxxcalen = scale_expansion_zeroelim(bxcalen, bxca, bdx, bxxca);
5402   bycalen = scale_expansion_zeroelim(4, ca, bdy, byca);
5403   byycalen = scale_expansion_zeroelim(bycalen, byca, bdy, byyca);
5404   blen = fast_expansion_sum_zeroelim(bxxcalen, bxxca, byycalen, byyca, bdet);
5405 
5406   Two_Product(adx, bdy, adxbdy1, adxbdy0);
5407   Two_Product(bdx, ady, bdxady1, bdxady0);
5408   Two_Two_Diff(adxbdy1, adxbdy0, bdxady1, bdxady0, ab3, ab[2], ab[1], ab[0]);
5409   ab[3] = ab3;
5410   cxablen = scale_expansion_zeroelim(4, ab, cdx, cxab);
5411   cxxablen = scale_expansion_zeroelim(cxablen, cxab, cdx, cxxab);
5412   cyablen = scale_expansion_zeroelim(4, ab, cdy, cyab);
5413   cyyablen = scale_expansion_zeroelim(cyablen, cyab, cdy, cyyab);
5414   clen = fast_expansion_sum_zeroelim(cxxablen, cxxab, cyyablen, cyyab, cdet);
5415 
5416   ablen = fast_expansion_sum_zeroelim(alen, adet, blen, bdet, abdet);
5417   finlength = fast_expansion_sum_zeroelim(ablen, abdet, clen, cdet, fin1);
5418 
5419   det = estimate(finlength, fin1);
5420   errbound = iccerrboundB * permanent;
5421   if ((det >= errbound) || (-det >= errbound)) {
5422     return det;
5423   }
5424 
5425   Two_Diff_Tail(pa[0], pd[0], adx, adxtail);
5426   Two_Diff_Tail(pa[1], pd[1], ady, adytail);
5427   Two_Diff_Tail(pb[0], pd[0], bdx, bdxtail);
5428   Two_Diff_Tail(pb[1], pd[1], bdy, bdytail);
5429   Two_Diff_Tail(pc[0], pd[0], cdx, cdxtail);
5430   Two_Diff_Tail(pc[1], pd[1], cdy, cdytail);
5431   if ((adxtail == 0.0) && (bdxtail == 0.0) && (cdxtail == 0.0)
5432       && (adytail == 0.0) && (bdytail == 0.0) && (cdytail == 0.0)) {
5433     return det;
5434   }
5435 
5436   errbound = iccerrboundC * permanent + resulterrbound * Absolute(det);
5437   det += ((adx * adx + ady * ady) * ((bdx * cdytail + cdy * bdxtail)
5438                                      - (bdy * cdxtail + cdx * bdytail))
5439           + 2.0 * (adx * adxtail + ady * adytail) * (bdx * cdy - bdy * cdx))
5440        + ((bdx * bdx + bdy * bdy) * ((cdx * adytail + ady * cdxtail)
5441                                      - (cdy * adxtail + adx * cdytail))
5442           + 2.0 * (bdx * bdxtail + bdy * bdytail) * (cdx * ady - cdy * adx))
5443        + ((cdx * cdx + cdy * cdy) * ((adx * bdytail + bdy * adxtail)
5444                                      - (ady * bdxtail + bdx * adytail))
5445           + 2.0 * (cdx * cdxtail + cdy * cdytail) * (adx * bdy - ady * bdx));
5446   if ((det >= errbound) || (-det >= errbound)) {
5447     return det;
5448   }
5449 
5450   finnow = fin1;
5451   finother = fin2;
5452 
5453   if ((bdxtail != 0.0) || (bdytail != 0.0)
5454       || (cdxtail != 0.0) || (cdytail != 0.0)) {
5455     Square(adx, adxadx1, adxadx0);
5456     Square(ady, adyady1, adyady0);
5457     Two_Two_Sum(adxadx1, adxadx0, adyady1, adyady0, aa3, aa[2], aa[1], aa[0]);
5458     aa[3] = aa3;
5459   }
5460   if ((cdxtail != 0.0) || (cdytail != 0.0)
5461       || (adxtail != 0.0) || (adytail != 0.0)) {
5462     Square(bdx, bdxbdx1, bdxbdx0);
5463     Square(bdy, bdybdy1, bdybdy0);
5464     Two_Two_Sum(bdxbdx1, bdxbdx0, bdybdy1, bdybdy0, bb3, bb[2], bb[1], bb[0]);
5465     bb[3] = bb3;
5466   }
5467   if ((adxtail != 0.0) || (adytail != 0.0)
5468       || (bdxtail != 0.0) || (bdytail != 0.0)) {
5469     Square(cdx, cdxcdx1, cdxcdx0);
5470     Square(cdy, cdycdy1, cdycdy0);
5471     Two_Two_Sum(cdxcdx1, cdxcdx0, cdycdy1, cdycdy0, cc3, cc[2], cc[1], cc[0]);
5472     cc[3] = cc3;
5473   }
5474 
5475   if (adxtail != 0.0) {
5476     axtbclen = scale_expansion_zeroelim(4, bc, adxtail, axtbc);
5477     temp16alen = scale_expansion_zeroelim(axtbclen, axtbc, 2.0 * adx,
5478                                           temp16a);
5479 
5480     axtcclen = scale_expansion_zeroelim(4, cc, adxtail, axtcc);
5481     temp16blen = scale_expansion_zeroelim(axtcclen, axtcc, bdy, temp16b);
5482 
5483     axtbblen = scale_expansion_zeroelim(4, bb, adxtail, axtbb);
5484     temp16clen = scale_expansion_zeroelim(axtbblen, axtbb, -cdy, temp16c);
5485 
5486     temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5487                                             temp16blen, temp16b, temp32a);
5488     temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
5489                                             temp32alen, temp32a, temp48);
5490     finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
5491                                             temp48, finother);
5492     finswap = finnow; finnow = finother; finother = finswap;
5493   }
5494   if (adytail != 0.0) {
5495     aytbclen = scale_expansion_zeroelim(4, bc, adytail, aytbc);
5496     temp16alen = scale_expansion_zeroelim(aytbclen, aytbc, 2.0 * ady,
5497                                           temp16a);
5498 
5499     aytbblen = scale_expansion_zeroelim(4, bb, adytail, aytbb);
5500     temp16blen = scale_expansion_zeroelim(aytbblen, aytbb, cdx, temp16b);
5501 
5502     aytcclen = scale_expansion_zeroelim(4, cc, adytail, aytcc);
5503     temp16clen = scale_expansion_zeroelim(aytcclen, aytcc, -bdx, temp16c);
5504 
5505     temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5506                                             temp16blen, temp16b, temp32a);
5507     temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
5508                                             temp32alen, temp32a, temp48);
5509     finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
5510                                             temp48, finother);
5511     finswap = finnow; finnow = finother; finother = finswap;
5512   }
5513   if (bdxtail != 0.0) {
5514     bxtcalen = scale_expansion_zeroelim(4, ca, bdxtail, bxtca);
5515     temp16alen = scale_expansion_zeroelim(bxtcalen, bxtca, 2.0 * bdx,
5516                                           temp16a);
5517 
5518     bxtaalen = scale_expansion_zeroelim(4, aa, bdxtail, bxtaa);
5519     temp16blen = scale_expansion_zeroelim(bxtaalen, bxtaa, cdy, temp16b);
5520 
5521     bxtcclen = scale_expansion_zeroelim(4, cc, bdxtail, bxtcc);
5522     temp16clen = scale_expansion_zeroelim(bxtcclen, bxtcc, -ady, temp16c);
5523 
5524     temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5525                                             temp16blen, temp16b, temp32a);
5526     temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
5527                                             temp32alen, temp32a, temp48);
5528     finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
5529                                             temp48, finother);
5530     finswap = finnow; finnow = finother; finother = finswap;
5531   }
5532   if (bdytail != 0.0) {
5533     bytcalen = scale_expansion_zeroelim(4, ca, bdytail, bytca);
5534     temp16alen = scale_expansion_zeroelim(bytcalen, bytca, 2.0 * bdy,
5535                                           temp16a);
5536 
5537     bytcclen = scale_expansion_zeroelim(4, cc, bdytail, bytcc);
5538     temp16blen = scale_expansion_zeroelim(bytcclen, bytcc, adx, temp16b);
5539 
5540     bytaalen = scale_expansion_zeroelim(4, aa, bdytail, bytaa);
5541     temp16clen = scale_expansion_zeroelim(bytaalen, bytaa, -cdx, temp16c);
5542 
5543     temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5544                                             temp16blen, temp16b, temp32a);
5545     temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
5546                                             temp32alen, temp32a, temp48);
5547     finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
5548                                             temp48, finother);
5549     finswap = finnow; finnow = finother; finother = finswap;
5550   }
5551   if (cdxtail != 0.0) {
5552     cxtablen = scale_expansion_zeroelim(4, ab, cdxtail, cxtab);
5553     temp16alen = scale_expansion_zeroelim(cxtablen, cxtab, 2.0 * cdx,
5554                                           temp16a);
5555 
5556     cxtbblen = scale_expansion_zeroelim(4, bb, cdxtail, cxtbb);
5557     temp16blen = scale_expansion_zeroelim(cxtbblen, cxtbb, ady, temp16b);
5558 
5559     cxtaalen = scale_expansion_zeroelim(4, aa, cdxtail, cxtaa);
5560     temp16clen = scale_expansion_zeroelim(cxtaalen, cxtaa, -bdy, temp16c);
5561 
5562     temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5563                                             temp16blen, temp16b, temp32a);
5564     temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
5565                                             temp32alen, temp32a, temp48);
5566     finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
5567                                             temp48, finother);
5568     finswap = finnow; finnow = finother; finother = finswap;
5569   }
5570   if (cdytail != 0.0) {
5571     cytablen = scale_expansion_zeroelim(4, ab, cdytail, cytab);
5572     temp16alen = scale_expansion_zeroelim(cytablen, cytab, 2.0 * cdy,
5573                                           temp16a);
5574 
5575     cytaalen = scale_expansion_zeroelim(4, aa, cdytail, cytaa);
5576     temp16blen = scale_expansion_zeroelim(cytaalen, cytaa, bdx, temp16b);
5577 
5578     cytbblen = scale_expansion_zeroelim(4, bb, cdytail, cytbb);
5579     temp16clen = scale_expansion_zeroelim(cytbblen, cytbb, -adx, temp16c);
5580 
5581     temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5582                                             temp16blen, temp16b, temp32a);
5583     temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
5584                                             temp32alen, temp32a, temp48);
5585     finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
5586                                             temp48, finother);
5587     finswap = finnow; finnow = finother; finother = finswap;
5588   }
5589 
5590   if ((adxtail != 0.0) || (adytail != 0.0)) {
5591     if ((bdxtail != 0.0) || (bdytail != 0.0)
5592         || (cdxtail != 0.0) || (cdytail != 0.0)) {
5593       Two_Product(bdxtail, cdy, ti1, ti0);
5594       Two_Product(bdx, cdytail, tj1, tj0);
5595       Two_Two_Sum(ti1, ti0, tj1, tj0, u3, u[2], u[1], u[0]);
5596       u[3] = u3;
5597       negate = -bdy;
5598       Two_Product(cdxtail, negate, ti1, ti0);
5599       negate = -bdytail;
5600       Two_Product(cdx, negate, tj1, tj0);
5601       Two_Two_Sum(ti1, ti0, tj1, tj0, v3, v[2], v[1], v[0]);
5602       v[3] = v3;
5603       bctlen = fast_expansion_sum_zeroelim(4, u, 4, v, bct);
5604 
5605       Two_Product(bdxtail, cdytail, ti1, ti0);
5606       Two_Product(cdxtail, bdytail, tj1, tj0);
5607       Two_Two_Diff(ti1, ti0, tj1, tj0, bctt3, bctt[2], bctt[1], bctt[0]);
5608       bctt[3] = bctt3;
5609       bcttlen = 4;
5610     } else {
5611       bct[0] = 0.0;
5612       bctlen = 1;
5613       bctt[0] = 0.0;
5614       bcttlen = 1;
5615     }
5616 
5617     if (adxtail != 0.0) {
5618       temp16alen = scale_expansion_zeroelim(axtbclen, axtbc, adxtail, temp16a);
5619       axtbctlen = scale_expansion_zeroelim(bctlen, bct, adxtail, axtbct);
5620       temp32alen = scale_expansion_zeroelim(axtbctlen, axtbct, 2.0 * adx,
5621                                             temp32a);
5622       temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5623                                               temp32alen, temp32a, temp48);
5624       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
5625                                               temp48, finother);
5626       finswap = finnow; finnow = finother; finother = finswap;
5627       if (bdytail != 0.0) {
5628         temp8len = scale_expansion_zeroelim(4, cc, adxtail, temp8);
5629         temp16alen = scale_expansion_zeroelim(temp8len, temp8, bdytail,
5630                                               temp16a);
5631         finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
5632                                                 temp16a, finother);
5633         finswap = finnow; finnow = finother; finother = finswap;
5634       }
5635       if (cdytail != 0.0) {
5636         temp8len = scale_expansion_zeroelim(4, bb, -adxtail, temp8);
5637         temp16alen = scale_expansion_zeroelim(temp8len, temp8, cdytail,
5638                                               temp16a);
5639         finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
5640                                                 temp16a, finother);
5641         finswap = finnow; finnow = finother; finother = finswap;
5642       }
5643 
5644       temp32alen = scale_expansion_zeroelim(axtbctlen, axtbct, adxtail,
5645                                             temp32a);
5646       axtbcttlen = scale_expansion_zeroelim(bcttlen, bctt, adxtail, axtbctt);
5647       temp16alen = scale_expansion_zeroelim(axtbcttlen, axtbctt, 2.0 * adx,
5648                                             temp16a);
5649       temp16blen = scale_expansion_zeroelim(axtbcttlen, axtbctt, adxtail,
5650                                             temp16b);
5651       temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5652                                               temp16blen, temp16b, temp32b);
5653       temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
5654                                               temp32blen, temp32b, temp64);
5655       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
5656                                               temp64, finother);
5657       finswap = finnow; finnow = finother; finother = finswap;
5658     }
5659     if (adytail != 0.0) {
5660       temp16alen = scale_expansion_zeroelim(aytbclen, aytbc, adytail, temp16a);
5661       aytbctlen = scale_expansion_zeroelim(bctlen, bct, adytail, aytbct);
5662       temp32alen = scale_expansion_zeroelim(aytbctlen, aytbct, 2.0 * ady,
5663                                             temp32a);
5664       temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5665                                               temp32alen, temp32a, temp48);
5666       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
5667                                               temp48, finother);
5668       finswap = finnow; finnow = finother; finother = finswap;
5669 
5670 
5671       temp32alen = scale_expansion_zeroelim(aytbctlen, aytbct, adytail,
5672                                             temp32a);
5673       aytbcttlen = scale_expansion_zeroelim(bcttlen, bctt, adytail, aytbctt);
5674       temp16alen = scale_expansion_zeroelim(aytbcttlen, aytbctt, 2.0 * ady,
5675                                             temp16a);
5676       temp16blen = scale_expansion_zeroelim(aytbcttlen, aytbctt, adytail,
5677                                             temp16b);
5678       temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5679                                               temp16blen, temp16b, temp32b);
5680       temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
5681                                               temp32blen, temp32b, temp64);
5682       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
5683                                               temp64, finother);
5684       finswap = finnow; finnow = finother; finother = finswap;
5685     }
5686   }
5687   if ((bdxtail != 0.0) || (bdytail != 0.0)) {
5688     if ((cdxtail != 0.0) || (cdytail != 0.0)
5689         || (adxtail != 0.0) || (adytail != 0.0)) {
5690       Two_Product(cdxtail, ady, ti1, ti0);
5691       Two_Product(cdx, adytail, tj1, tj0);
5692       Two_Two_Sum(ti1, ti0, tj1, tj0, u3, u[2], u[1], u[0]);
5693       u[3] = u3;
5694       negate = -cdy;
5695       Two_Product(adxtail, negate, ti1, ti0);
5696       negate = -cdytail;
5697       Two_Product(adx, negate, tj1, tj0);
5698       Two_Two_Sum(ti1, ti0, tj1, tj0, v3, v[2], v[1], v[0]);
5699       v[3] = v3;
5700       catlen = fast_expansion_sum_zeroelim(4, u, 4, v, cat);
5701 
5702       Two_Product(cdxtail, adytail, ti1, ti0);
5703       Two_Product(adxtail, cdytail, tj1, tj0);
5704       Two_Two_Diff(ti1, ti0, tj1, tj0, catt3, catt[2], catt[1], catt[0]);
5705       catt[3] = catt3;
5706       cattlen = 4;
5707     } else {
5708       cat[0] = 0.0;
5709       catlen = 1;
5710       catt[0] = 0.0;
5711       cattlen = 1;
5712     }
5713 
5714     if (bdxtail != 0.0) {
5715       temp16alen = scale_expansion_zeroelim(bxtcalen, bxtca, bdxtail, temp16a);
5716       bxtcatlen = scale_expansion_zeroelim(catlen, cat, bdxtail, bxtcat);
5717       temp32alen = scale_expansion_zeroelim(bxtcatlen, bxtcat, 2.0 * bdx,
5718                                             temp32a);
5719       temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5720                                               temp32alen, temp32a, temp48);
5721       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
5722                                               temp48, finother);
5723       finswap = finnow; finnow = finother; finother = finswap;
5724       if (cdytail != 0.0) {
5725         temp8len = scale_expansion_zeroelim(4, aa, bdxtail, temp8);
5726         temp16alen = scale_expansion_zeroelim(temp8len, temp8, cdytail,
5727                                               temp16a);
5728         finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
5729                                                 temp16a, finother);
5730         finswap = finnow; finnow = finother; finother = finswap;
5731       }
5732       if (adytail != 0.0) {
5733         temp8len = scale_expansion_zeroelim(4, cc, -bdxtail, temp8);
5734         temp16alen = scale_expansion_zeroelim(temp8len, temp8, adytail,
5735                                               temp16a);
5736         finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
5737                                                 temp16a, finother);
5738         finswap = finnow; finnow = finother; finother = finswap;
5739       }
5740 
5741       temp32alen = scale_expansion_zeroelim(bxtcatlen, bxtcat, bdxtail,
5742                                             temp32a);
5743       bxtcattlen = scale_expansion_zeroelim(cattlen, catt, bdxtail, bxtcatt);
5744       temp16alen = scale_expansion_zeroelim(bxtcattlen, bxtcatt, 2.0 * bdx,
5745                                             temp16a);
5746       temp16blen = scale_expansion_zeroelim(bxtcattlen, bxtcatt, bdxtail,
5747                                             temp16b);
5748       temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5749                                               temp16blen, temp16b, temp32b);
5750       temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
5751                                               temp32blen, temp32b, temp64);
5752       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
5753                                               temp64, finother);
5754       finswap = finnow; finnow = finother; finother = finswap;
5755     }
5756     if (bdytail != 0.0) {
5757       temp16alen = scale_expansion_zeroelim(bytcalen, bytca, bdytail, temp16a);
5758       bytcatlen = scale_expansion_zeroelim(catlen, cat, bdytail, bytcat);
5759       temp32alen = scale_expansion_zeroelim(bytcatlen, bytcat, 2.0 * bdy,
5760                                             temp32a);
5761       temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5762                                               temp32alen, temp32a, temp48);
5763       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
5764                                               temp48, finother);
5765       finswap = finnow; finnow = finother; finother = finswap;
5766 
5767 
5768       temp32alen = scale_expansion_zeroelim(bytcatlen, bytcat, bdytail,
5769                                             temp32a);
5770       bytcattlen = scale_expansion_zeroelim(cattlen, catt, bdytail, bytcatt);
5771       temp16alen = scale_expansion_zeroelim(bytcattlen, bytcatt, 2.0 * bdy,
5772                                             temp16a);
5773       temp16blen = scale_expansion_zeroelim(bytcattlen, bytcatt, bdytail,
5774                                             temp16b);
5775       temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5776                                               temp16blen, temp16b, temp32b);
5777       temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
5778                                               temp32blen, temp32b, temp64);
5779       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
5780                                               temp64, finother);
5781       finswap = finnow; finnow = finother; finother = finswap;
5782     }
5783   }
5784   if ((cdxtail != 0.0) || (cdytail != 0.0)) {
5785     if ((adxtail != 0.0) || (adytail != 0.0)
5786         || (bdxtail != 0.0) || (bdytail != 0.0)) {
5787       Two_Product(adxtail, bdy, ti1, ti0);
5788       Two_Product(adx, bdytail, tj1, tj0);
5789       Two_Two_Sum(ti1, ti0, tj1, tj0, u3, u[2], u[1], u[0]);
5790       u[3] = u3;
5791       negate = -ady;
5792       Two_Product(bdxtail, negate, ti1, ti0);
5793       negate = -adytail;
5794       Two_Product(bdx, negate, tj1, tj0);
5795       Two_Two_Sum(ti1, ti0, tj1, tj0, v3, v[2], v[1], v[0]);
5796       v[3] = v3;
5797       abtlen = fast_expansion_sum_zeroelim(4, u, 4, v, abt);
5798 
5799       Two_Product(adxtail, bdytail, ti1, ti0);
5800       Two_Product(bdxtail, adytail, tj1, tj0);
5801       Two_Two_Diff(ti1, ti0, tj1, tj0, abtt3, abtt[2], abtt[1], abtt[0]);
5802       abtt[3] = abtt3;
5803       abttlen = 4;
5804     } else {
5805       abt[0] = 0.0;
5806       abtlen = 1;
5807       abtt[0] = 0.0;
5808       abttlen = 1;
5809     }
5810 
5811     if (cdxtail != 0.0) {
5812       temp16alen = scale_expansion_zeroelim(cxtablen, cxtab, cdxtail, temp16a);
5813       cxtabtlen = scale_expansion_zeroelim(abtlen, abt, cdxtail, cxtabt);
5814       temp32alen = scale_expansion_zeroelim(cxtabtlen, cxtabt, 2.0 * cdx,
5815                                             temp32a);
5816       temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5817                                               temp32alen, temp32a, temp48);
5818       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
5819                                               temp48, finother);
5820       finswap = finnow; finnow = finother; finother = finswap;
5821       if (adytail != 0.0) {
5822         temp8len = scale_expansion_zeroelim(4, bb, cdxtail, temp8);
5823         temp16alen = scale_expansion_zeroelim(temp8len, temp8, adytail,
5824                                               temp16a);
5825         finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
5826                                                 temp16a, finother);
5827         finswap = finnow; finnow = finother; finother = finswap;
5828       }
5829       if (bdytail != 0.0) {
5830         temp8len = scale_expansion_zeroelim(4, aa, -cdxtail, temp8);
5831         temp16alen = scale_expansion_zeroelim(temp8len, temp8, bdytail,
5832                                               temp16a);
5833         finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
5834                                                 temp16a, finother);
5835         finswap = finnow; finnow = finother; finother = finswap;
5836       }
5837 
5838       temp32alen = scale_expansion_zeroelim(cxtabtlen, cxtabt, cdxtail,
5839                                             temp32a);
5840       cxtabttlen = scale_expansion_zeroelim(abttlen, abtt, cdxtail, cxtabtt);
5841       temp16alen = scale_expansion_zeroelim(cxtabttlen, cxtabtt, 2.0 * cdx,
5842                                             temp16a);
5843       temp16blen = scale_expansion_zeroelim(cxtabttlen, cxtabtt, cdxtail,
5844                                             temp16b);
5845       temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5846                                               temp16blen, temp16b, temp32b);
5847       temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
5848                                               temp32blen, temp32b, temp64);
5849       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
5850                                               temp64, finother);
5851       finswap = finnow; finnow = finother; finother = finswap;
5852     }
5853     if (cdytail != 0.0) {
5854       temp16alen = scale_expansion_zeroelim(cytablen, cytab, cdytail, temp16a);
5855       cytabtlen = scale_expansion_zeroelim(abtlen, abt, cdytail, cytabt);
5856       temp32alen = scale_expansion_zeroelim(cytabtlen, cytabt, 2.0 * cdy,
5857                                             temp32a);
5858       temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5859                                               temp32alen, temp32a, temp48);
5860       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
5861                                               temp48, finother);
5862       finswap = finnow; finnow = finother; finother = finswap;
5863 
5864 
5865       temp32alen = scale_expansion_zeroelim(cytabtlen, cytabt, cdytail,
5866                                             temp32a);
5867       cytabttlen = scale_expansion_zeroelim(abttlen, abtt, cdytail, cytabtt);
5868       temp16alen = scale_expansion_zeroelim(cytabttlen, cytabtt, 2.0 * cdy,
5869                                             temp16a);
5870       temp16blen = scale_expansion_zeroelim(cytabttlen, cytabtt, cdytail,
5871                                             temp16b);
5872       temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5873                                               temp16blen, temp16b, temp32b);
5874       temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
5875                                               temp32blen, temp32b, temp64);
5876       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
5877                                               temp64, finother);
5878       finswap = finnow; finnow = finother; finother = finswap;
5879     }
5880   }
5881 
5882   return finnow[finlength - 1];
5883 }
5884 
5885 #ifdef ANSI_DECLARATORS
5886 REAL incircle(struct mesh *m, struct behavior *b,
5887               vertex pa, vertex pb, vertex pc, vertex pd)
5888 #else /* not ANSI_DECLARATORS */
5889 REAL incircle(m, b, pa, pb, pc, pd)
5890 struct mesh *m;
5891 struct behavior *b;
5892 vertex pa;
5893 vertex pb;
5894 vertex pc;
5895 vertex pd;
5896 #endif /* not ANSI_DECLARATORS */
5897 
5898 {
5899   REAL adx, bdx, cdx, ady, bdy, cdy;
5900   REAL bdxcdy, cdxbdy, cdxady, adxcdy, adxbdy, bdxady;
5901   REAL alift, blift, clift;
5902   REAL det;
5903   REAL permanent, errbound;
5904 
5905   m->incirclecount++;
5906 
5907   adx = pa[0] - pd[0];
5908   bdx = pb[0] - pd[0];
5909   cdx = pc[0] - pd[0];
5910   ady = pa[1] - pd[1];
5911   bdy = pb[1] - pd[1];
5912   cdy = pc[1] - pd[1];
5913 
5914   bdxcdy = bdx * cdy;
5915   cdxbdy = cdx * bdy;
5916   alift = adx * adx + ady * ady;
5917 
5918   cdxady = cdx * ady;
5919   adxcdy = adx * cdy;
5920   blift = bdx * bdx + bdy * bdy;
5921 
5922   adxbdy = adx * bdy;
5923   bdxady = bdx * ady;
5924   clift = cdx * cdx + cdy * cdy;
5925 
5926   det = alift * (bdxcdy - cdxbdy)
5927       + blift * (cdxady - adxcdy)
5928       + clift * (adxbdy - bdxady);
5929 
5930   if (b->noexact) {
5931     return det;
5932   }
5933 
5934   permanent = (Absolute(bdxcdy) + Absolute(cdxbdy)) * alift
5935             + (Absolute(cdxady) + Absolute(adxcdy)) * blift
5936             + (Absolute(adxbdy) + Absolute(bdxady)) * clift;
5937   errbound = iccerrboundA * permanent;
5938   if ((det > errbound) || (-det > errbound)) {
5939     return det;
5940   }
5941 
5942   return incircleadapt(pa, pb, pc, pd, permanent);
5943 }
5944 
5945 /*****************************************************************************/
5946 /*                                                                           */
5947 /*  orient3d()   Return a positive value if the point pd lies below the      */
5948 /*               plane passing through pa, pb, and pc; "below" is defined so */
5949 /*               that pa, pb, and pc appear in counterclockwise order when   */
5950 /*               viewed from above the plane.  Returns a negative value if   */
5951 /*               pd lies above the plane.  Returns zero if the points are    */
5952 /*               coplanar.  The result is also a rough approximation of six  */
5953 /*               times the signed volume of the tetrahedron defined by the   */
5954 /*               four points.                                                */
5955 /*                                                                           */
5956 /*  Uses exact arithmetic if necessary to ensure a correct answer.  The      */
5957 /*  result returned is the determinant of a matrix.  This determinant is     */
5958 /*  computed adaptively, in the sense that exact arithmetic is used only to  */
5959 /*  the degree it is needed to ensure that the returned value has the        */
5960 /*  correct sign.  Hence, this function is usually quite fast, but will run  */
5961 /*  more slowly when the input points are coplanar or nearly so.             */
5962 /*                                                                           */
5963 /*  See my Robust Predicates paper for details.                              */
5964 /*                                                                           */
5965 /*****************************************************************************/
5966 
5967 #ifdef ANSI_DECLARATORS
5968 REAL orient3dadapt(vertex pa, vertex pb, vertex pc, vertex pd,
5969                    REAL aheight, REAL bheight, REAL cheight, REAL dheight,
5970                    REAL permanent)
5971 #else /* not ANSI_DECLARATORS */
5972 REAL orient3dadapt(pa, pb, pc, pd,
5973                    aheight, bheight, cheight, dheight, permanent)
5974 vertex pa;
5975 vertex pb;
5976 vertex pc;
5977 vertex pd;
5978 REAL aheight;
5979 REAL bheight;
5980 REAL cheight;
5981 REAL dheight;
5982 REAL permanent;
5983 #endif /* not ANSI_DECLARATORS */
5984 
5985 {
5986   INEXACT REAL adx, bdx, cdx, ady, bdy, cdy, adheight, bdheight, cdheight;
5987   REAL det, errbound;
5988 
5989   INEXACT REAL bdxcdy1, cdxbdy1, cdxady1, adxcdy1, adxbdy1, bdxady1;
5990   REAL bdxcdy0, cdxbdy0, cdxady0, adxcdy0, adxbdy0, bdxady0;
5991   REAL bc[4], ca[4], ab[4];
5992   INEXACT REAL bc3, ca3, ab3;
5993   REAL adet[8], bdet[8], cdet[8];
5994   int alen, blen, clen;
5995   REAL abdet[16];
5996   int ablen;
5997   REAL *finnow, *finother, *finswap;
5998   REAL fin1[192], fin2[192];
5999   int finlength;
6000 
6001   REAL adxtail, bdxtail, cdxtail;
6002   REAL adytail, bdytail, cdytail;
6003   REAL adheighttail, bdheighttail, cdheighttail;
6004   INEXACT REAL at_blarge, at_clarge;
6005   INEXACT REAL bt_clarge, bt_alarge;
6006   INEXACT REAL ct_alarge, ct_blarge;
6007   REAL at_b[4], at_c[4], bt_c[4], bt_a[4], ct_a[4], ct_b[4];
6008   int at_blen, at_clen, bt_clen, bt_alen, ct_alen, ct_blen;
6009   INEXACT REAL bdxt_cdy1, cdxt_bdy1, cdxt_ady1;
6010   INEXACT REAL adxt_cdy1, adxt_bdy1, bdxt_ady1;
6011   REAL bdxt_cdy0, cdxt_bdy0, cdxt_ady0;
6012   REAL adxt_cdy0, adxt_bdy0, bdxt_ady0;
6013   INEXACT REAL bdyt_cdx1, cdyt_bdx1, cdyt_adx1;
6014   INEXACT REAL adyt_cdx1, adyt_bdx1, bdyt_adx1;
6015   REAL bdyt_cdx0, cdyt_bdx0, cdyt_adx0;
6016   REAL adyt_cdx0, adyt_bdx0, bdyt_adx0;
6017   REAL bct[8], cat[8], abt[8];
6018   int bctlen, catlen, abtlen;
6019   INEXACT REAL bdxt_cdyt1, cdxt_bdyt1, cdxt_adyt1;
6020   INEXACT REAL adxt_cdyt1, adxt_bdyt1, bdxt_adyt1;
6021   REAL bdxt_cdyt0, cdxt_bdyt0, cdxt_adyt0;
6022   REAL adxt_cdyt0, adxt_bdyt0, bdxt_adyt0;
6023   REAL u[4], v[12], w[16];
6024   INEXACT REAL u3;
6025   int vlength, wlength;
6026   REAL negate;
6027 
6028   INEXACT REAL bvirt;
6029   REAL avirt, bround, around;
6030   INEXACT REAL c;
6031   INEXACT REAL abig;
6032   REAL ahi, alo, bhi, blo;
6033   REAL err1, err2, err3;
6034   INEXACT REAL _i, _j, _k;
6035   REAL _0;
6036 
6037   adx = (REAL) (pa[0] - pd[0]);
6038   bdx = (REAL) (pb[0] - pd[0]);
6039   cdx = (REAL) (pc[0] - pd[0]);
6040   ady = (REAL) (pa[1] - pd[1]);
6041   bdy = (REAL) (pb[1] - pd[1]);
6042   cdy = (REAL) (pc[1] - pd[1]);
6043   adheight = (REAL) (aheight - dheight);
6044   bdheight = (REAL) (bheight - dheight);
6045   cdheight = (REAL) (cheight - dheight);
6046 
6047   Two_Product(bdx, cdy, bdxcdy1, bdxcdy0);
6048   Two_Product(cdx, bdy, cdxbdy1, cdxbdy0);
6049   Two_Two_Diff(bdxcdy1, bdxcdy0, cdxbdy1, cdxbdy0, bc3, bc[2], bc[1], bc[0]);
6050   bc[3] = bc3;
6051   alen = scale_expansion_zeroelim(4, bc, adheight, adet);
6052 
6053   Two_Product(cdx, ady, cdxady1, cdxady0);
6054   Two_Product(adx, cdy, adxcdy1, adxcdy0);
6055   Two_Two_Diff(cdxady1, cdxady0, adxcdy1, adxcdy0, ca3, ca[2], ca[1], ca[0]);
6056   ca[3] = ca3;
6057   blen = scale_expansion_zeroelim(4, ca, bdheight, bdet);
6058 
6059   Two_Product(adx, bdy, adxbdy1, adxbdy0);
6060   Two_Product(bdx, ady, bdxady1, bdxady0);
6061   Two_Two_Diff(adxbdy1, adxbdy0, bdxady1, bdxady0, ab3, ab[2], ab[1], ab[0]);
6062   ab[3] = ab3;
6063   clen = scale_expansion_zeroelim(4, ab, cdheight, cdet);
6064 
6065   ablen = fast_expansion_sum_zeroelim(alen, adet, blen, bdet, abdet);
6066   finlength = fast_expansion_sum_zeroelim(ablen, abdet, clen, cdet, fin1);
6067 
6068   det = estimate(finlength, fin1);
6069   errbound = o3derrboundB * permanent;
6070   if ((det >= errbound) || (-det >= errbound)) {
6071     return det;
6072   }
6073 
6074   Two_Diff_Tail(pa[0], pd[0], adx, adxtail);
6075   Two_Diff_Tail(pb[0], pd[0], bdx, bdxtail);
6076   Two_Diff_Tail(pc[0], pd[0], cdx, cdxtail);
6077   Two_Diff_Tail(pa[1], pd[1], ady, adytail);
6078   Two_Diff_Tail(pb[1], pd[1], bdy, bdytail);
6079   Two_Diff_Tail(pc[1], pd[1], cdy, cdytail);
6080   Two_Diff_Tail(aheight, dheight, adheight, adheighttail);
6081   Two_Diff_Tail(bheight, dheight, bdheight, bdheighttail);
6082   Two_Diff_Tail(cheight, dheight, cdheight, cdheighttail);
6083 
6084   if ((adxtail == 0.0) && (bdxtail == 0.0) && (cdxtail == 0.0) &&
6085       (adytail == 0.0) && (bdytail == 0.0) && (cdytail == 0.0) &&
6086       (adheighttail == 0.0) &&
6087       (bdheighttail == 0.0) &&
6088       (cdheighttail == 0.0)) {
6089     return det;
6090   }
6091 
6092   errbound = o3derrboundC * permanent + resulterrbound * Absolute(det);
6093   det += (adheight * ((bdx * cdytail + cdy * bdxtail) -
6094                       (bdy * cdxtail + cdx * bdytail)) +
6095           adheighttail * (bdx * cdy - bdy * cdx)) +
6096          (bdheight * ((cdx * adytail + ady * cdxtail) -
6097                       (cdy * adxtail + adx * cdytail)) +
6098           bdheighttail * (cdx * ady - cdy * adx)) +
6099          (cdheight * ((adx * bdytail + bdy * adxtail) -
6100                       (ady * bdxtail + bdx * adytail)) +
6101           cdheighttail * (adx * bdy - ady * bdx));
6102   if ((det >= errbound) || (-det >= errbound)) {
6103     return det;
6104   }
6105 
6106   finnow = fin1;
6107   finother = fin2;
6108 
6109   if (adxtail == 0.0) {
6110     if (adytail == 0.0) {
6111       at_b[0] = 0.0;
6112       at_blen = 1;
6113       at_c[0] = 0.0;
6114       at_clen = 1;
6115     } else {
6116       negate = -adytail;
6117       Two_Product(negate, bdx, at_blarge, at_b[0]);
6118       at_b[1] = at_blarge;
6119       at_blen = 2;
6120       Two_Product(adytail, cdx, at_clarge, at_c[0]);
6121       at_c[1] = at_clarge;
6122       at_clen = 2;
6123     }
6124   } else {
6125     if (adytail == 0.0) {
6126       Two_Product(adxtail, bdy, at_blarge, at_b[0]);
6127       at_b[1] = at_blarge;
6128       at_blen = 2;
6129       negate = -adxtail;
6130       Two_Product(negate, cdy, at_clarge, at_c[0]);
6131       at_c[1] = at_clarge;
6132       at_clen = 2;
6133     } else {
6134       Two_Product(adxtail, bdy, adxt_bdy1, adxt_bdy0);
6135       Two_Product(adytail, bdx, adyt_bdx1, adyt_bdx0);
6136       Two_Two_Diff(adxt_bdy1, adxt_bdy0, adyt_bdx1, adyt_bdx0,
6137                    at_blarge, at_b[2], at_b[1], at_b[0]);
6138       at_b[3] = at_blarge;
6139       at_blen = 4;
6140       Two_Product(adytail, cdx, adyt_cdx1, adyt_cdx0);
6141       Two_Product(adxtail, cdy, adxt_cdy1, adxt_cdy0);
6142       Two_Two_Diff(adyt_cdx1, adyt_cdx0, adxt_cdy1, adxt_cdy0,
6143                    at_clarge, at_c[2], at_c[1], at_c[0]);
6144       at_c[3] = at_clarge;
6145       at_clen = 4;
6146     }
6147   }
6148   if (bdxtail == 0.0) {
6149     if (bdytail == 0.0) {
6150       bt_c[0] = 0.0;
6151       bt_clen = 1;
6152       bt_a[0] = 0.0;
6153       bt_alen = 1;
6154     } else {
6155       negate = -bdytail;
6156       Two_Product(negate, cdx, bt_clarge, bt_c[0]);
6157       bt_c[1] = bt_clarge;
6158       bt_clen = 2;
6159       Two_Product(bdytail, adx, bt_alarge, bt_a[0]);
6160       bt_a[1] = bt_alarge;
6161       bt_alen = 2;
6162     }
6163   } else {
6164     if (bdytail == 0.0) {
6165       Two_Product(bdxtail, cdy, bt_clarge, bt_c[0]);
6166       bt_c[1] = bt_clarge;
6167       bt_clen = 2;
6168       negate = -bdxtail;
6169       Two_Product(negate, ady, bt_alarge, bt_a[0]);
6170       bt_a[1] = bt_alarge;
6171       bt_alen = 2;
6172     } else {
6173       Two_Product(bdxtail, cdy, bdxt_cdy1, bdxt_cdy0);
6174       Two_Product(bdytail, cdx, bdyt_cdx1, bdyt_cdx0);
6175       Two_Two_Diff(bdxt_cdy1, bdxt_cdy0, bdyt_cdx1, bdyt_cdx0,
6176                    bt_clarge, bt_c[2], bt_c[1], bt_c[0]);
6177       bt_c[3] = bt_clarge;
6178       bt_clen = 4;
6179       Two_Product(bdytail, adx, bdyt_adx1, bdyt_adx0);
6180       Two_Product(bdxtail, ady, bdxt_ady1, bdxt_ady0);
6181       Two_Two_Diff(bdyt_adx1, bdyt_adx0, bdxt_ady1, bdxt_ady0,
6182                   bt_alarge, bt_a[2], bt_a[1], bt_a[0]);
6183       bt_a[3] = bt_alarge;
6184       bt_alen = 4;
6185     }
6186   }
6187   if (cdxtail == 0.0) {
6188     if (cdytail == 0.0) {
6189       ct_a[0] = 0.0;
6190       ct_alen = 1;
6191       ct_b[0] = 0.0;
6192       ct_blen = 1;
6193     } else {
6194       negate = -cdytail;
6195       Two_Product(negate, adx, ct_alarge, ct_a[0]);
6196       ct_a[1] = ct_alarge;
6197       ct_alen = 2;
6198       Two_Product(cdytail, bdx, ct_blarge, ct_b[0]);
6199       ct_b[1] = ct_blarge;
6200       ct_blen = 2;
6201     }
6202   } else {
6203     if (cdytail == 0.0) {
6204       Two_Product(cdxtail, ady, ct_alarge, ct_a[0]);
6205       ct_a[1] = ct_alarge;
6206       ct_alen = 2;
6207       negate = -cdxtail;
6208       Two_Product(negate, bdy, ct_blarge, ct_b[0]);
6209       ct_b[1] = ct_blarge;
6210       ct_blen = 2;
6211     } else {
6212       Two_Product(cdxtail, ady, cdxt_ady1, cdxt_ady0);
6213       Two_Product(cdytail, adx, cdyt_adx1, cdyt_adx0);
6214       Two_Two_Diff(cdxt_ady1, cdxt_ady0, cdyt_adx1, cdyt_adx0,
6215                    ct_alarge, ct_a[2], ct_a[1], ct_a[0]);
6216       ct_a[3] = ct_alarge;
6217       ct_alen = 4;
6218       Two_Product(cdytail, bdx, cdyt_bdx1, cdyt_bdx0);
6219       Two_Product(cdxtail, bdy, cdxt_bdy1, cdxt_bdy0);
6220       Two_Two_Diff(cdyt_bdx1, cdyt_bdx0, cdxt_bdy1, cdxt_bdy0,
6221                    ct_blarge, ct_b[2], ct_b[1], ct_b[0]);
6222       ct_b[3] = ct_blarge;
6223       ct_blen = 4;
6224     }
6225   }
6226 
6227   bctlen = fast_expansion_sum_zeroelim(bt_clen, bt_c, ct_blen, ct_b, bct);
6228   wlength = scale_expansion_zeroelim(bctlen, bct, adheight, w);
6229   finlength = fast_expansion_sum_zeroelim(finlength, finnow, wlength, w,
6230                                           finother);
6231   finswap = finnow; finnow = finother; finother = finswap;
6232 
6233   catlen = fast_expansion_sum_zeroelim(ct_alen, ct_a, at_clen, at_c, cat);
6234   wlength = scale_expansion_zeroelim(catlen, cat, bdheight, w);
6235   finlength = fast_expansion_sum_zeroelim(finlength, finnow, wlength, w,
6236                                           finother);
6237   finswap = finnow; finnow = finother; finother = finswap;
6238 
6239   abtlen = fast_expansion_sum_zeroelim(at_blen, at_b, bt_alen, bt_a, abt);
6240   wlength = scale_expansion_zeroelim(abtlen, abt, cdheight, w);
6241   finlength = fast_expansion_sum_zeroelim(finlength, finnow, wlength, w,
6242                                           finother);
6243   finswap = finnow; finnow = finother; finother = finswap;
6244 
6245   if (adheighttail != 0.0) {
6246     vlength = scale_expansion_zeroelim(4, bc, adheighttail, v);
6247     finlength = fast_expansion_sum_zeroelim(finlength, finnow, vlength, v,
6248                                             finother);
6249     finswap = finnow; finnow = finother; finother = finswap;
6250   }
6251   if (bdheighttail != 0.0) {
6252     vlength = scale_expansion_zeroelim(4, ca, bdheighttail, v);
6253     finlength = fast_expansion_sum_zeroelim(finlength, finnow, vlength, v,
6254                                             finother);
6255     finswap = finnow; finnow = finother; finother = finswap;
6256   }
6257   if (cdheighttail != 0.0) {
6258     vlength = scale_expansion_zeroelim(4, ab, cdheighttail, v);
6259     finlength = fast_expansion_sum_zeroelim(finlength, finnow, vlength, v,
6260                                             finother);
6261     finswap = finnow; finnow = finother; finother = finswap;
6262   }
6263 
6264   if (adxtail != 0.0) {
6265     if (bdytail != 0.0) {
6266       Two_Product(adxtail, bdytail, adxt_bdyt1, adxt_bdyt0);
6267       Two_One_Product(adxt_bdyt1, adxt_bdyt0, cdheight, u3, u[2], u[1], u[0]);
6268       u[3] = u3;
6269       finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
6270                                               finother);
6271       finswap = finnow; finnow = finother; finother = finswap;
6272       if (cdheighttail != 0.0) {
6273         Two_One_Product(adxt_bdyt1, adxt_bdyt0, cdheighttail,
6274                         u3, u[2], u[1], u[0]);
6275         u[3] = u3;
6276         finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
6277                                                 finother);
6278         finswap = finnow; finnow = finother; finother = finswap;
6279       }
6280     }
6281     if (cdytail != 0.0) {
6282       negate = -adxtail;
6283       Two_Product(negate, cdytail, adxt_cdyt1, adxt_cdyt0);
6284       Two_One_Product(adxt_cdyt1, adxt_cdyt0, bdheight, u3, u[2], u[1], u[0]);
6285       u[3] = u3;
6286       finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
6287                                               finother);
6288       finswap = finnow; finnow = finother; finother = finswap;
6289       if (bdheighttail != 0.0) {
6290         Two_One_Product(adxt_cdyt1, adxt_cdyt0, bdheighttail,
6291                         u3, u[2], u[1], u[0]);
6292         u[3] = u3;
6293         finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
6294                                                 finother);
6295         finswap = finnow; finnow = finother; finother = finswap;
6296       }
6297     }
6298   }
6299   if (bdxtail != 0.0) {
6300     if (cdytail != 0.0) {
6301       Two_Product(bdxtail, cdytail, bdxt_cdyt1, bdxt_cdyt0);
6302       Two_One_Product(bdxt_cdyt1, bdxt_cdyt0, adheight, u3, u[2], u[1], u[0]);
6303       u[3] = u3;
6304       finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
6305                                               finother);
6306       finswap = finnow; finnow = finother; finother = finswap;
6307       if (adheighttail != 0.0) {
6308         Two_One_Product(bdxt_cdyt1, bdxt_cdyt0, adheighttail,
6309                         u3, u[2], u[1], u[0]);
6310         u[3] = u3;
6311         finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
6312                                                 finother);
6313         finswap = finnow; finnow = finother; finother = finswap;
6314       }
6315     }
6316     if (adytail != 0.0) {
6317       negate = -bdxtail;
6318       Two_Product(negate, adytail, bdxt_adyt1, bdxt_adyt0);
6319       Two_One_Product(bdxt_adyt1, bdxt_adyt0, cdheight, u3, u[2], u[1], u[0]);
6320       u[3] = u3;
6321       finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
6322                                               finother);
6323       finswap = finnow; finnow = finother; finother = finswap;
6324       if (cdheighttail != 0.0) {
6325         Two_One_Product(bdxt_adyt1, bdxt_adyt0, cdheighttail,
6326                         u3, u[2], u[1], u[0]);
6327         u[3] = u3;
6328         finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
6329                                                 finother);
6330         finswap = finnow; finnow = finother; finother = finswap;
6331       }
6332     }
6333   }
6334   if (cdxtail != 0.0) {
6335     if (adytail != 0.0) {
6336       Two_Product(cdxtail, adytail, cdxt_adyt1, cdxt_adyt0);
6337       Two_One_Product(cdxt_adyt1, cdxt_adyt0, bdheight, u3, u[2], u[1], u[0]);
6338       u[3] = u3;
6339       finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
6340                                               finother);
6341       finswap = finnow; finnow = finother; finother = finswap;
6342       if (bdheighttail != 0.0) {
6343         Two_One_Product(cdxt_adyt1, cdxt_adyt0, bdheighttail,
6344                         u3, u[2], u[1], u[0]);
6345         u[3] = u3;
6346         finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
6347                                                 finother);
6348         finswap = finnow; finnow = finother; finother = finswap;
6349       }
6350     }
6351     if (bdytail != 0.0) {
6352       negate = -cdxtail;
6353       Two_Product(negate, bdytail, cdxt_bdyt1, cdxt_bdyt0);
6354       Two_One_Product(cdxt_bdyt1, cdxt_bdyt0, adheight, u3, u[2], u[1], u[0]);
6355       u[3] = u3;
6356       finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
6357                                               finother);
6358       finswap = finnow; finnow = finother; finother = finswap;
6359       if (adheighttail != 0.0) {
6360         Two_One_Product(cdxt_bdyt1, cdxt_bdyt0, adheighttail,
6361                         u3, u[2], u[1], u[0]);
6362         u[3] = u3;
6363         finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
6364                                                 finother);
6365         finswap = finnow; finnow = finother; finother = finswap;
6366       }
6367     }
6368   }
6369 
6370   if (adheighttail != 0.0) {
6371     wlength = scale_expansion_zeroelim(bctlen, bct, adheighttail, w);
6372     finlength = fast_expansion_sum_zeroelim(finlength, finnow, wlength, w,
6373                                             finother);
6374     finswap = finnow; finnow = finother; finother = finswap;
6375   }
6376   if (bdheighttail != 0.0) {
6377     wlength = scale_expansion_zeroelim(catlen, cat, bdheighttail, w);
6378     finlength = fast_expansion_sum_zeroelim(finlength, finnow, wlength, w,
6379                                             finother);
6380     finswap = finnow; finnow = finother; finother = finswap;
6381   }
6382   if (cdheighttail != 0.0) {
6383     wlength = scale_expansion_zeroelim(abtlen, abt, cdheighttail, w);
6384     finlength = fast_expansion_sum_zeroelim(finlength, finnow, wlength, w,
6385                                             finother);
6386     finswap = finnow; finnow = finother; finother = finswap;
6387   }
6388 
6389   return finnow[finlength - 1];
6390 }
6391 
6392 #ifdef ANSI_DECLARATORS
6393 REAL orient3d(struct mesh *m, struct behavior *b,
6394               vertex pa, vertex pb, vertex pc, vertex pd,
6395               REAL aheight, REAL bheight, REAL cheight, REAL dheight)
6396 #else /* not ANSI_DECLARATORS */
6397 REAL orient3d(m, b, pa, pb, pc, pd, aheight, bheight, cheight, dheight)
6398 struct mesh *m;
6399 struct behavior *b;
6400 vertex pa;
6401 vertex pb;
6402 vertex pc;
6403 vertex pd;
6404 REAL aheight;
6405 REAL bheight;
6406 REAL cheight;
6407 REAL dheight;
6408 #endif /* not ANSI_DECLARATORS */
6409 
6410 {
6411   REAL adx, bdx, cdx, ady, bdy, cdy, adheight, bdheight, cdheight;
6412   REAL bdxcdy, cdxbdy, cdxady, adxcdy, adxbdy, bdxady;
6413   REAL det;
6414   REAL permanent, errbound;
6415 
6416   m->orient3dcount++;
6417 
6418   adx = pa[0] - pd[0];
6419   bdx = pb[0] - pd[0];
6420   cdx = pc[0] - pd[0];
6421   ady = pa[1] - pd[1];
6422   bdy = pb[1] - pd[1];
6423   cdy = pc[1] - pd[1];
6424   adheight = aheight - dheight;
6425   bdheight = bheight - dheight;
6426   cdheight = cheight - dheight;
6427 
6428   bdxcdy = bdx * cdy;
6429   cdxbdy = cdx * bdy;
6430 
6431   cdxady = cdx * ady;
6432   adxcdy = adx * cdy;
6433 
6434   adxbdy = adx * bdy;
6435   bdxady = bdx * ady;
6436 
6437   det = adheight * (bdxcdy - cdxbdy)
6438       + bdheight * (cdxady - adxcdy)
6439       + cdheight * (adxbdy - bdxady);
6440 
6441   if (b->noexact) {
6442     return det;
6443   }
6444 
6445   permanent = (Absolute(bdxcdy) + Absolute(cdxbdy)) * Absolute(adheight)
6446             + (Absolute(cdxady) + Absolute(adxcdy)) * Absolute(bdheight)
6447             + (Absolute(adxbdy) + Absolute(bdxady)) * Absolute(cdheight);
6448   errbound = o3derrboundA * permanent;
6449   if ((det > errbound) || (-det > errbound)) {
6450     return det;
6451   }
6452 
6453   return orient3dadapt(pa, pb, pc, pd, aheight, bheight, cheight, dheight,
6454                        permanent);
6455 }
6456 
6457 /*****************************************************************************/
6458 /*                                                                           */
6459 /*  nonregular()   Return a positive value if the point pd is incompatible   */
6460 /*                 with the circle or plane passing through pa, pb, and pc   */
6461 /*                 (meaning that pd is inside the circle or below the        */
6462 /*                 plane); a negative value if it is compatible; and zero if */
6463 /*                 the four points are cocircular/coplanar.  The points pa,  */
6464 /*                 pb, and pc must be in counterclockwise order, or the sign */
6465 /*                 of the result will be reversed.                           */
6466 /*                                                                           */
6467 /*  If the -w switch is used, the points are lifted onto the parabolic       */
6468 /*  lifting map, then they are dropped according to their weights, then the  */
6469 /*  3D orientation test is applied.  If the -W switch is used, the points'   */
6470 /*  heights are already provided, so the 3D orientation test is applied      */
6471 /*  directly.  If neither switch is used, the incircle test is applied.      */
6472 /*                                                                           */
6473 /*****************************************************************************/
6474 
6475 #ifdef ANSI_DECLARATORS
6476 REAL nonregular(struct mesh *m, struct behavior *b,
6477                 vertex pa, vertex pb, vertex pc, vertex pd)
6478 #else /* not ANSI_DECLARATORS */
6479 REAL nonregular(m, b, pa, pb, pc, pd)
6480 struct mesh *m;
6481 struct behavior *b;
6482 vertex pa;
6483 vertex pb;
6484 vertex pc;
6485 vertex pd;
6486 #endif /* not ANSI_DECLARATORS */
6487 
6488 {
6489   if (b->weighted == 0) {
6490     return incircle(m, b, pa, pb, pc, pd);
6491   } else if (b->weighted == 1) {
6492     return orient3d(m, b, pa, pb, pc, pd,
6493                     pa[0] * pa[0] + pa[1] * pa[1] - pa[2],
6494                     pb[0] * pb[0] + pb[1] * pb[1] - pb[2],
6495                     pc[0] * pc[0] + pc[1] * pc[1] - pc[2],
6496                     pd[0] * pd[0] + pd[1] * pd[1] - pd[2]);
6497   } else {
6498     return orient3d(m, b, pa, pb, pc, pd, pa[2], pb[2], pc[2], pd[2]);
6499   }
6500 }
6501 
6502 /*****************************************************************************/
6503 /*                                                                           */
6504 /*  findcircumcenter()   Find the circumcenter of a triangle.                */
6505 /*                                                                           */
6506 /*  The result is returned both in terms of x-y coordinates and xi-eta       */
6507 /*  (barycentric) coordinates.  The xi-eta coordinate system is defined in   */
6508 /*  terms of the triangle:  the origin of the triangle is the origin of the  */
6509 /*  coordinate system; the destination of the triangle is one unit along the */
6510 /*  xi axis; and the apex of the triangle is one unit along the eta axis.    */
6511 /*  This procedure also returns the square of the length of the triangle's   */
6512 /*  shortest edge.                                                           */
6513 /*                                                                           */
6514 /*****************************************************************************/
6515 
6516 #ifdef ANSI_DECLARATORS
6517 void findcircumcenter(struct mesh *m, struct behavior *b,
6518                       vertex torg, vertex tdest, vertex tapex,
6519                       vertex circumcenter, REAL *xi, REAL *eta, int offcenter)
6520 #else /* not ANSI_DECLARATORS */
6521 void findcircumcenter(m, b, torg, tdest, tapex, circumcenter, xi, eta,
6522                       offcenter)
6523 struct mesh *m;
6524 struct behavior *b;
6525 vertex torg;
6526 vertex tdest;
6527 vertex tapex;
6528 vertex circumcenter;
6529 REAL *xi;
6530 REAL *eta;
6531 int offcenter;
6532 #endif /* not ANSI_DECLARATORS */
6533 
6534 {
6535   REAL xdo, ydo, xao, yao;
6536   REAL dodist, aodist, dadist;
6537   REAL denominator;
6538   REAL dx, dy, dxoff, dyoff;
6539 
6540   m->circumcentercount++;
6541 
6542   /* Compute the circumcenter of the triangle. */
6543   xdo = tdest[0] - torg[0];
6544   ydo = tdest[1] - torg[1];
6545   xao = tapex[0] - torg[0];
6546   yao = tapex[1] - torg[1];
6547   dodist = xdo * xdo + ydo * ydo;
6548   aodist = xao * xao + yao * yao;
6549   dadist = (tdest[0] - tapex[0]) * (tdest[0] - tapex[0]) +
6550            (tdest[1] - tapex[1]) * (tdest[1] - tapex[1]);
6551   if (b->noexact) {
6552     denominator = 0.5 / (xdo * yao - xao * ydo);
6553   } else {
6554     /* Use the counterclockwise() routine to ensure a positive (and */
6555     /*   reasonably accurate) result, avoiding any possibility of   */
6556     /*   division by zero.                                          */
6557     denominator = 0.5 / counterclockwise(m, b, tdest, tapex, torg);
6558     /* Don't count the above as an orientation test. */
6559     m->counterclockcount--;
6560   }
6561   dx = (yao * dodist - ydo * aodist) * denominator;
6562   dy = (xdo * aodist - xao * dodist) * denominator;
6563 
6564   /* Find the (squared) length of the triangle's shortest edge.  This   */
6565   /*   serves as a conservative estimate of the insertion radius of the */
6566   /*   circumcenter's parent.  The estimate is used to ensure that      */
6567   /*   the algorithm terminates even if very small angles appear in     */
6568   /*   the input PSLG.                                                  */
6569   if ((dodist < aodist) && (dodist < dadist)) {
6570     if (offcenter && (b->offconstant > 0.0)) {
6571       /* Find the position of the off-center, as described by Alper Ungor. */
6572       dxoff = 0.5 * xdo - b->offconstant * ydo;
6573       dyoff = 0.5 * ydo + b->offconstant * xdo;
6574       /* If the off-center is closer to the origin than the */
6575       /*   circumcenter, use the off-center instead.        */
6576       if (dxoff * dxoff + dyoff * dyoff < dx * dx + dy * dy) {
6577         dx = dxoff;
6578         dy = dyoff;
6579       }
6580     }
6581   } else if (aodist < dadist) {
6582     if (offcenter && (b->offconstant > 0.0)) {
6583       dxoff = 0.5 * xao + b->offconstant * yao;
6584       dyoff = 0.5 * yao - b->offconstant * xao;
6585       /* If the off-center is closer to the origin than the */
6586       /*   circumcenter, use the off-center instead.        */
6587       if (dxoff * dxoff + dyoff * dyoff < dx * dx + dy * dy) {
6588         dx = dxoff;
6589         dy = dyoff;
6590       }
6591     }
6592   } else {
6593     if (offcenter && (b->offconstant > 0.0)) {
6594       dxoff = 0.5 * (tapex[0] - tdest[0]) -
6595               b->offconstant * (tapex[1] - tdest[1]);
6596       dyoff = 0.5 * (tapex[1] - tdest[1]) +
6597               b->offconstant * (tapex[0] - tdest[0]);
6598       /* If the off-center is closer to the destination than the */
6599       /*   circumcenter, use the off-center instead.             */
6600       if (dxoff * dxoff + dyoff * dyoff <
6601           (dx - xdo) * (dx - xdo) + (dy - ydo) * (dy - ydo)) {
6602         dx = xdo + dxoff;
6603         dy = ydo + dyoff;
6604       }
6605     }
6606   }
6607 
6608   circumcenter[0] = torg[0] + dx;
6609   circumcenter[1] = torg[1] + dy;
6610 
6611   /* To interpolate vertex attributes for the new vertex inserted at */
6612   /*   the circumcenter, define a coordinate system with a xi-axis,  */
6613   /*   directed from the triangle's origin to its destination, and   */
6614   /*   an eta-axis, directed from its origin to its apex.            */
6615   /*   Calculate the xi and eta coordinates of the circumcenter.     */
6616   *xi = (yao * dx - xao * dy) * (2.0 * denominator);
6617   *eta = (xdo * dy - ydo * dx) * (2.0 * denominator);
6618 }
6619 
6620 /**                                                                         **/
6621 /**                                                                         **/
6622 /********* Geometric primitives end here                             *********/
6623 
6624 /*****************************************************************************/
6625 /*                                                                           */
6626 /*  triangleinit()   Initialize some variables.                              */
6627 /*                                                                           */
6628 /*****************************************************************************/
6629 
6630 #ifdef ANSI_DECLARATORS
6631 void triangleinit(struct mesh *m)
6632 #else /* not ANSI_DECLARATORS */
6633 void triangleinit(m)
6634 struct mesh *m;
6635 #endif /* not ANSI_DECLARATORS */
6636 
6637 {
6638   poolzero(&m->vertices);
6639   poolzero(&m->triangles);
6640   poolzero(&m->subsegs);
6641   poolzero(&m->viri);
6642   poolzero(&m->badsubsegs);
6643   poolzero(&m->badtriangles);
6644   poolzero(&m->flipstackers);
6645   poolzero(&m->splaynodes);
6646 
6647   m->recenttri.tri = (triangle *) NULL; /* No triangle has been visited yet. */
6648   m->undeads = 0;                       /* No eliminated input vertices yet. */
6649   m->samples = 1;         /* Point location should take at least one sample. */
6650   m->checksegments = 0;   /* There are no segments in the triangulation yet. */
6651   m->checkquality = 0;     /* The quality triangulation stage has not begun. */
6652   m->incirclecount = m->counterclockcount = m->orient3dcount = 0;
6653   m->hyperbolacount = m->circletopcount = m->circumcentercount = 0;
6654   randomseed = 1;
6655 
6656   exactinit();                     /* Initialize exact arithmetic constants. */
6657 }
6658 
6659 /*****************************************************************************/
6660 /*                                                                           */
6661 /*  randomnation()   Generate a random number between 0 and `choices' - 1.   */
6662 /*                                                                           */
6663 /*  This is a simple linear congruential random number generator.  Hence, it */
6664 /*  is a bad random number generator, but good enough for most randomized    */
6665 /*  geometric algorithms.                                                    */
6666 /*                                                                           */
6667 /*****************************************************************************/
6668 
6669 #ifdef ANSI_DECLARATORS
6670 unsigned long randomnation(unsigned int choices)
6671 #else /* not ANSI_DECLARATORS */
6672 unsigned long randomnation(choices)
6673 unsigned int choices;
6674 #endif /* not ANSI_DECLARATORS */
6675 
6676 {
6677   randomseed = (randomseed * 1366l + 150889l) % 714025l;
6678   return randomseed / (714025l / choices + 1);
6679 }
6680 
6681 /********* Mesh quality testing routines begin here                  *********/
6682 /**                                                                         **/
6683 /**                                                                         **/
6684 
6685 /*****************************************************************************/
6686 /*                                                                           */
6687 /*  checkmesh()   Test the mesh for topological consistency.                 */
6688 /*                                                                           */
6689 /*****************************************************************************/
6690 
6691 #ifndef REDUCED
6692 
6693 #ifdef ANSI_DECLARATORS
6694 void checkmesh(struct mesh *m, struct behavior *b)
6695 #else /* not ANSI_DECLARATORS */
6696 void checkmesh(m, b)
6697 struct mesh *m;
6698 struct behavior *b;
6699 #endif /* not ANSI_DECLARATORS */
6700 
6701 {
6702   struct otri triangleloop;
6703   struct otri oppotri, oppooppotri;
6704   vertex triorg, tridest, triapex;
6705   vertex oppoorg, oppodest;
6706   int horrors;
6707   int saveexact;
6708   triangle ptr;                         /* Temporary variable used by sym(). */
6709 
6710   /* Temporarily turn on exact arithmetic if it's off. */
6711   saveexact = b->noexact;
6712   b->noexact = 0;
6713   if (!b->quiet) {
6714     printf("  Checking consistency of mesh...\n");
6715   }
6716   horrors = 0;
6717   /* Run through the list of triangles, checking each one. */
6718   traversalinit(&m->triangles);
6719   triangleloop.tri = triangletraverse(m);
6720   while (triangleloop.tri != (triangle *) NULL) {
6721     /* Check all three edges of the triangle. */
6722     for (triangleloop.orient = 0; triangleloop.orient < 3;
6723          triangleloop.orient++) {
6724       org(triangleloop, triorg);
6725       dest(triangleloop, tridest);
6726       if (triangleloop.orient == 0) {       /* Only test for inversion once. */
6727         /* Test if the triangle is flat or inverted. */
6728         apex(triangleloop, triapex);
6729         if (counterclockwise(m, b, triorg, tridest, triapex) <= 0.0) {
6730           printf("  !! !! Inverted ");
6731           printtriangle(m, b, &triangleloop);
6732           horrors++;
6733         }
6734       }
6735       /* Find the neighboring triangle on this edge. */
6736       sym(triangleloop, oppotri);
6737       if (oppotri.tri != m->dummytri) {
6738         /* Check that the triangle's neighbor knows it's a neighbor. */
6739         sym(oppotri, oppooppotri);
6740         if ((triangleloop.tri != oppooppotri.tri)
6741             || (triangleloop.orient != oppooppotri.orient)) {
6742           printf("  !! !! Asymmetric triangle-triangle bond:\n");
6743           if (triangleloop.tri == oppooppotri.tri) {
6744             printf("   (Right triangle, wrong orientation)\n");
6745           }
6746           printf("    First ");
6747           printtriangle(m, b, &triangleloop);
6748           printf("    Second (nonreciprocating) ");
6749           printtriangle(m, b, &oppotri);
6750           horrors++;
6751         }
6752         /* Check that both triangles agree on the identities */
6753         /*   of their shared vertices.                       */
6754         org(oppotri, oppoorg);
6755         dest(oppotri, oppodest);
6756         if ((triorg != oppodest) || (tridest != oppoorg)) {
6757           printf("  !! !! Mismatched edge coordinates between two triangles:\n"
6758                  );
6759           printf("    First mismatched ");
6760           printtriangle(m, b, &triangleloop);
6761           printf("    Second mismatched ");
6762           printtriangle(m, b, &oppotri);
6763           horrors++;
6764         }
6765       }
6766     }
6767     triangleloop.tri = triangletraverse(m);
6768   }
6769   if (horrors == 0) {
6770     if (!b->quiet) {
6771       printf("  In my studied opinion, the mesh appears to be consistent.\n");
6772     }
6773   } else if (horrors == 1) {
6774     printf("  !! !! !! !! Precisely one festering wound discovered.\n");
6775   } else {
6776     printf("  !! !! !! !! %d abominations witnessed.\n", horrors);
6777   }
6778   /* Restore the status of exact arithmetic. */
6779   b->noexact = saveexact;
6780 }
6781 
6782 #endif /* not REDUCED */
6783 
6784 /*****************************************************************************/
6785 /*                                                                           */
6786 /*  checkdelaunay()   Ensure that the mesh is (constrained) Delaunay.        */
6787 /*                                                                           */
6788 /*****************************************************************************/
6789 
6790 #ifndef REDUCED
6791 
6792 #ifdef ANSI_DECLARATORS
6793 void checkdelaunay(struct mesh *m, struct behavior *b)
6794 #else /* not ANSI_DECLARATORS */
6795 void checkdelaunay(m, b)
6796 struct mesh *m;
6797 struct behavior *b;
6798 #endif /* not ANSI_DECLARATORS */
6799 
6800 {
6801   struct otri triangleloop;
6802   struct otri oppotri;
6803   struct osub opposubseg;
6804   vertex triorg, tridest, triapex;
6805   vertex oppoapex;
6806   int shouldbedelaunay;
6807   int horrors;
6808   int saveexact;
6809   triangle ptr;                         /* Temporary variable used by sym(). */
6810   subseg sptr;                      /* Temporary variable used by tspivot(). */
6811 
6812   /* Temporarily turn on exact arithmetic if it's off. */
6813   saveexact = b->noexact;
6814   b->noexact = 0;
6815   if (!b->quiet) {
6816     printf("  Checking Delaunay property of mesh...\n");
6817   }
6818   horrors = 0;
6819   /* Run through the list of triangles, checking each one. */
6820   traversalinit(&m->triangles);
6821   triangleloop.tri = triangletraverse(m);
6822   while (triangleloop.tri != (triangle *) NULL) {
6823     /* Check all three edges of the triangle. */
6824     for (triangleloop.orient = 0; triangleloop.orient < 3;
6825          triangleloop.orient++) {
6826       org(triangleloop, triorg);
6827       dest(triangleloop, tridest);
6828       apex(triangleloop, triapex);
6829       sym(triangleloop, oppotri);
6830       apex(oppotri, oppoapex);
6831       /* Only test that the edge is locally Delaunay if there is an   */
6832       /*   adjoining triangle whose pointer is larger (to ensure that */
6833       /*   each pair isn't tested twice).                             */
6834       shouldbedelaunay = (oppotri.tri != m->dummytri) &&
6835             !deadtri(oppotri.tri) && (triangleloop.tri < oppotri.tri) &&
6836             (triorg != m->infvertex1) && (triorg != m->infvertex2) &&
6837             (triorg != m->infvertex3) &&
6838             (tridest != m->infvertex1) && (tridest != m->infvertex2) &&
6839             (tridest != m->infvertex3) &&
6840             (triapex != m->infvertex1) && (triapex != m->infvertex2) &&
6841             (triapex != m->infvertex3) &&
6842             (oppoapex != m->infvertex1) && (oppoapex != m->infvertex2) &&
6843             (oppoapex != m->infvertex3);
6844       if (m->checksegments && shouldbedelaunay) {
6845         /* If a subsegment separates the triangles, then the edge is */
6846         /*   constrained, so no local Delaunay test should be done.  */
6847         tspivot(triangleloop, opposubseg);
6848         if (opposubseg.ss != m->dummysub){
6849           shouldbedelaunay = 0;
6850         }
6851       }
6852       if (shouldbedelaunay) {
6853         if (nonregular(m, b, triorg, tridest, triapex, oppoapex) > 0.0) {
6854           if (!b->weighted) {
6855             printf("  !! !! Non-Delaunay pair of triangles:\n");
6856             printf("    First non-Delaunay ");
6857             printtriangle(m, b, &triangleloop);
6858             printf("    Second non-Delaunay ");
6859           } else {
6860             printf("  !! !! Non-regular pair of triangles:\n");
6861             printf("    First non-regular ");
6862             printtriangle(m, b, &triangleloop);
6863             printf("    Second non-regular ");
6864           }
6865           printtriangle(m, b, &oppotri);
6866           horrors++;
6867         }
6868       }
6869     }
6870     triangleloop.tri = triangletraverse(m);
6871   }
6872   if (horrors == 0) {
6873     if (!b->quiet) {
6874       printf(
6875   "  By virtue of my perceptive intelligence, I declare the mesh Delaunay.\n");
6876     }
6877   } else if (horrors == 1) {
6878     printf(
6879          "  !! !! !! !! Precisely one terrifying transgression identified.\n");
6880   } else {
6881     printf("  !! !! !! !! %d obscenities viewed with horror.\n", horrors);
6882   }
6883   /* Restore the status of exact arithmetic. */
6884   b->noexact = saveexact;
6885 }
6886 
6887 #endif /* not REDUCED */
6888 
6889 /*****************************************************************************/
6890 /*                                                                           */
6891 /*  enqueuebadtriang()   Add a bad triangle data structure to the end of a   */
6892 /*                       queue.                                              */
6893 /*                                                                           */
6894 /*  The queue is actually a set of 4096 queues.  I use multiple queues to    */
6895 /*  give priority to smaller angles.  I originally implemented a heap, but   */
6896 /*  the queues are faster by a larger margin than I'd suspected.             */
6897 /*                                                                           */
6898 /*****************************************************************************/
6899 
6900 #ifndef CDT_ONLY
6901 
6902 #ifdef ANSI_DECLARATORS
6903 void enqueuebadtriang(struct mesh *m, struct behavior *b,
6904                       struct badtriang *badtri)
6905 #else /* not ANSI_DECLARATORS */
6906 void enqueuebadtriang(m, b, badtri)
6907 struct mesh *m;
6908 struct behavior *b;
6909 struct badtriang *badtri;
6910 #endif /* not ANSI_DECLARATORS */
6911 
6912 {
6913   REAL length, multiplier;
6914   int exponent, expincrement;
6915   int queuenumber;
6916   int posexponent;
6917   int i;
6918 
6919   if (b->verbose > 2) {
6920     printf("  Queueing bad triangle:\n");
6921     printf("    (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
6922            badtri->triangorg[0], badtri->triangorg[1],
6923            badtri->triangdest[0], badtri->triangdest[1],
6924            badtri->triangapex[0], badtri->triangapex[1]);
6925   }
6926 
6927   /* Determine the appropriate queue to put the bad triangle into.    */
6928   /*   Recall that the key is the square of its shortest edge length. */
6929   if (badtri->key >= 1.0) {
6930     length = badtri->key;
6931     posexponent = 1;
6932   } else {
6933     /* `badtri->key' is 2.0 to a negative exponent, so we'll record that */
6934     /*   fact and use the reciprocal of `badtri->key', which is > 1.0.   */
6935     length = 1.0 / badtri->key;
6936     posexponent = 0;
6937   }
6938   /* `length' is approximately 2.0 to what exponent?  The following code */
6939   /*   determines the answer in time logarithmic in the exponent.        */
6940   exponent = 0;
6941   while (length > 2.0) {
6942     /* Find an approximation by repeated squaring of two. */
6943     expincrement = 1;
6944     multiplier = 0.5;
6945     while (length * multiplier * multiplier > 1.0) {
6946       expincrement *= 2;
6947       multiplier *= multiplier;
6948     }
6949     /* Reduce the value of `length', then iterate if necessary. */
6950     exponent += expincrement;
6951     length *= multiplier;
6952   }
6953   /* `length' is approximately squareroot(2.0) to what exponent? */
6954   exponent = 2.0 * exponent + (length > SQUAREROOTTWO);
6955   /* `exponent' is now in the range 0...2047 for IEEE double precision.   */
6956   /*   Choose a queue in the range 0...4095.  The shortest edges have the */
6957   /*   highest priority (queue 4095).                                     */
6958   if (posexponent) {
6959     queuenumber = 2047 - exponent;
6960   } else {
6961     queuenumber = 2048 + exponent;
6962   }
6963 
6964   /* Are we inserting into an empty queue? */
6965   if (m->queuefront[queuenumber] == (struct badtriang *) NULL) {
6966     /* Yes, we are inserting into an empty queue.     */
6967     /*   Will this become the highest-priority queue? */
6968     if (queuenumber > m->firstnonemptyq) {
6969       /* Yes, this is the highest-priority queue. */
6970       m->nextnonemptyq[queuenumber] = m->firstnonemptyq;
6971       m->firstnonemptyq = queuenumber;
6972     } else {
6973       /* No, this is not the highest-priority queue. */
6974       /*   Find the queue with next higher priority. */
6975       i = queuenumber + 1;
6976       while (m->queuefront[i] == (struct badtriang *) NULL) {
6977         i++;
6978       }
6979       /* Mark the newly nonempty queue as following a higher-priority queue. */
6980       m->nextnonemptyq[queuenumber] = m->nextnonemptyq[i];
6981       m->nextnonemptyq[i] = queuenumber;
6982     }
6983     /* Put the bad triangle at the beginning of the (empty) queue. */
6984     m->queuefront[queuenumber] = badtri;
6985   } else {
6986     /* Add the bad triangle to the end of an already nonempty queue. */
6987     m->queuetail[queuenumber]->nexttriang = badtri;
6988   }
6989   /* Maintain a pointer to the last triangle of the queue. */
6990   m->queuetail[queuenumber] = badtri;
6991   /* Newly enqueued bad triangle has no successor in the queue. */
6992   badtri->nexttriang = (struct badtriang *) NULL;
6993 }
6994 
6995 #endif /* not CDT_ONLY */
6996 
6997 /*****************************************************************************/
6998 /*                                                                           */
6999 /*  enqueuebadtri()   Add a bad triangle to the end of a queue.              */
7000 /*                                                                           */
7001 /*  Allocates a badtriang data structure for the triangle, then passes it to */
7002 /*  enqueuebadtriang().                                                      */
7003 /*                                                                           */
7004 /*****************************************************************************/
7005 
7006 #ifndef CDT_ONLY
7007 
7008 #ifdef ANSI_DECLARATORS
7009 void enqueuebadtri(struct mesh *m, struct behavior *b, struct otri *enqtri,
7010                    REAL minedge, vertex enqapex, vertex enqorg, vertex enqdest)
7011 #else /* not ANSI_DECLARATORS */
7012 void enqueuebadtri(m, b, enqtri, minedge, enqapex, enqorg, enqdest)
7013 struct mesh *m;
7014 struct behavior *b;
7015 struct otri *enqtri;
7016 REAL minedge;
7017 vertex enqapex;
7018 vertex enqorg;
7019 vertex enqdest;
7020 #endif /* not ANSI_DECLARATORS */
7021 
7022 {
7023   struct badtriang *newbad;
7024 
7025   /* Allocate space for the bad triangle. */
7026   newbad = (struct badtriang *) poolalloc(&m->badtriangles);
7027   newbad->poortri = encode(*enqtri);
7028   newbad->key = minedge;
7029   newbad->triangapex = enqapex;
7030   newbad->triangorg = enqorg;
7031   newbad->triangdest = enqdest;
7032   enqueuebadtriang(m, b, newbad);
7033 }
7034 
7035 #endif /* not CDT_ONLY */
7036 
7037 /*****************************************************************************/
7038 /*                                                                           */
7039 /*  dequeuebadtriang()   Remove a triangle from the front of the queue.      */
7040 /*                                                                           */
7041 /*****************************************************************************/
7042 
7043 #ifndef CDT_ONLY
7044 
7045 #ifdef ANSI_DECLARATORS
7046 struct badtriang *dequeuebadtriang(struct mesh *m)
7047 #else /* not ANSI_DECLARATORS */
7048 struct badtriang *dequeuebadtriang(m)
7049 struct mesh *m;
7050 #endif /* not ANSI_DECLARATORS */
7051 
7052 {
7053   struct badtriang *result;
7054 
7055   /* If no queues are nonempty, return NULL. */
7056   if (m->firstnonemptyq < 0) {
7057     return (struct badtriang *) NULL;
7058   }
7059   /* Find the first triangle of the highest-priority queue. */
7060   result = m->queuefront[m->firstnonemptyq];
7061   /* Remove the triangle from the queue. */
7062   m->queuefront[m->firstnonemptyq] = result->nexttriang;
7063   /* If this queue is now empty, note the new highest-priority */
7064   /*   nonempty queue.                                         */
7065   if (result == m->queuetail[m->firstnonemptyq]) {
7066     m->firstnonemptyq = m->nextnonemptyq[m->firstnonemptyq];
7067   }
7068   return result;
7069 }
7070 
7071 #endif /* not CDT_ONLY */
7072 
7073 /*****************************************************************************/
7074 /*                                                                           */
7075 /*  checkseg4encroach()   Check a subsegment to see if it is encroached; add */
7076 /*                        it to the list if it is.                           */
7077 /*                                                                           */
7078 /*  A subsegment is encroached if there is a vertex in its diametral lens.   */
7079 /*  For Ruppert's algorithm (-D switch), the "diametral lens" is the         */
7080 /*  diametral circle.  For Chew's algorithm (default), the diametral lens is */
7081 /*  just big enough to enclose two isosceles triangles whose bases are the   */
7082 /*  subsegment.  Each of the two isosceles triangles has two angles equal    */
7083 /*  to `b->minangle'.                                                        */
7084 /*                                                                           */
7085 /*  Chew's algorithm does not require diametral lenses at all--but they save */
7086 /*  time.  Any vertex inside a subsegment's diametral lens implies that the  */
7087 /*  triangle adjoining the subsegment will be too skinny, so it's only a     */
7088 /*  matter of time before the encroaching vertex is deleted by Chew's        */
7089 /*  algorithm.  It's faster to simply not insert the doomed vertex in the    */
7090 /*  first place, which is why I use diametral lenses with Chew's algorithm.  */
7091 /*                                                                           */
7092 /*  Returns a nonzero value if the subsegment is encroached.                 */
7093 /*                                                                           */
7094 /*****************************************************************************/
7095 
7096 #ifndef CDT_ONLY
7097 
7098 #ifdef ANSI_DECLARATORS
7099 int checkseg4encroach(struct mesh *m, struct behavior *b,
7100                       struct osub *testsubseg)
7101 #else /* not ANSI_DECLARATORS */
7102 int checkseg4encroach(m, b, testsubseg)
7103 struct mesh *m;
7104 struct behavior *b;
7105 struct osub *testsubseg;
7106 #endif /* not ANSI_DECLARATORS */
7107 
7108 {
7109   struct otri neighbortri;
7110   struct osub testsym;
7111   struct badsubseg *encroachedseg;
7112   REAL dotproduct;
7113   int encroached;
7114   int sides;
7115   vertex eorg, edest, eapex;
7116   triangle ptr;                     /* Temporary variable used by stpivot(). */
7117 
7118   encroached = 0;
7119   sides = 0;
7120 
7121   sorg(*testsubseg, eorg);
7122   sdest(*testsubseg, edest);
7123   /* Check one neighbor of the subsegment. */
7124   stpivot(*testsubseg, neighbortri);
7125   /* Does the neighbor exist, or is this a boundary edge? */
7126   if (neighbortri.tri != m->dummytri) {
7127     sides++;
7128     /* Find a vertex opposite this subsegment. */
7129     apex(neighbortri, eapex);
7130     /* Check whether the apex is in the diametral lens of the subsegment */
7131     /*   (the diametral circle if `conformdel' is set).  A dot product   */
7132     /*   of two sides of the triangle is used to check whether the angle */
7133     /*   at the apex is greater than (180 - 2 `minangle') degrees (for   */
7134     /*   lenses; 90 degrees for diametral circles).                      */
7135     dotproduct = (eorg[0] - eapex[0]) * (edest[0] - eapex[0]) +
7136                  (eorg[1] - eapex[1]) * (edest[1] - eapex[1]);
7137     if (dotproduct < 0.0) {
7138       if (b->conformdel ||
7139           (dotproduct * dotproduct >=
7140            (2.0 * b->goodangle - 1.0) * (2.0 * b->goodangle - 1.0) *
7141            ((eorg[0] - eapex[0]) * (eorg[0] - eapex[0]) +
7142             (eorg[1] - eapex[1]) * (eorg[1] - eapex[1])) *
7143            ((edest[0] - eapex[0]) * (edest[0] - eapex[0]) +
7144             (edest[1] - eapex[1]) * (edest[1] - eapex[1])))) {
7145         encroached = 1;
7146       }
7147     }
7148   }
7149   /* Check the other neighbor of the subsegment. */
7150   ssym(*testsubseg, testsym);
7151   stpivot(testsym, neighbortri);
7152   /* Does the neighbor exist, or is this a boundary edge? */
7153   if (neighbortri.tri != m->dummytri) {
7154     sides++;
7155     /* Find the other vertex opposite this subsegment. */
7156     apex(neighbortri, eapex);
7157     /* Check whether the apex is in the diametral lens of the subsegment */
7158     /*   (or the diametral circle, if `conformdel' is set).              */
7159     dotproduct = (eorg[0] - eapex[0]) * (edest[0] - eapex[0]) +
7160                  (eorg[1] - eapex[1]) * (edest[1] - eapex[1]);
7161     if (dotproduct < 0.0) {
7162       if (b->conformdel ||
7163           (dotproduct * dotproduct >=
7164            (2.0 * b->goodangle - 1.0) * (2.0 * b->goodangle - 1.0) *
7165            ((eorg[0] - eapex[0]) * (eorg[0] - eapex[0]) +
7166             (eorg[1] - eapex[1]) * (eorg[1] - eapex[1])) *
7167            ((edest[0] - eapex[0]) * (edest[0] - eapex[0]) +
7168             (edest[1] - eapex[1]) * (edest[1] - eapex[1])))) {
7169         encroached += 2;
7170       }
7171     }
7172   }
7173 
7174   if (encroached && (!b->nobisect || ((b->nobisect == 1) && (sides == 2)))) {
7175     if (b->verbose > 2) {
7176       printf(
7177         "  Queueing encroached subsegment (%.12g, %.12g) (%.12g, %.12g).\n",
7178         eorg[0], eorg[1], edest[0], edest[1]);
7179     }
7180     /* Add the subsegment to the list of encroached subsegments. */
7181     /*   Be sure to get the orientation right.                   */
7182     encroachedseg = (struct badsubseg *) poolalloc(&m->badsubsegs);
7183     if (encroached == 1) {
7184       encroachedseg->encsubseg = sencode(*testsubseg);
7185       encroachedseg->subsegorg = eorg;
7186       encroachedseg->subsegdest = edest;
7187     } else {
7188       encroachedseg->encsubseg = sencode(testsym);
7189       encroachedseg->subsegorg = edest;
7190       encroachedseg->subsegdest = eorg;
7191     }
7192   }
7193 
7194   return encroached;
7195 }
7196 
7197 #endif /* not CDT_ONLY */
7198 
7199 /*****************************************************************************/
7200 /*                                                                           */
7201 /*  testtriangle()   Test a triangle for quality and size.                   */
7202 /*                                                                           */
7203 /*  Tests a triangle to see if it satisfies the minimum angle condition and  */
7204 /*  the maximum area condition.  Triangles that aren't up to spec are added  */
7205 /*  to the bad triangle queue.                                               */
7206 /*                                                                           */
7207 /*****************************************************************************/
7208 
7209 #ifndef CDT_ONLY
7210 
7211 #ifdef ANSI_DECLARATORS
7212 void testtriangle(struct mesh *m, struct behavior *b, struct otri *testtri)
7213 #else /* not ANSI_DECLARATORS */
7214 void testtriangle(m, b, testtri)
7215 struct mesh *m;
7216 struct behavior *b;
7217 struct otri *testtri;
7218 #endif /* not ANSI_DECLARATORS */
7219 
7220 {
7221   struct otri tri1, tri2;
7222   struct osub testsub;
7223   vertex torg, tdest, tapex;
7224   vertex base1, base2;
7225   vertex org1, dest1, org2, dest2;
7226   vertex joinvertex;
7227   REAL dxod, dyod, dxda, dyda, dxao, dyao;
7228   REAL dxod2, dyod2, dxda2, dyda2, dxao2, dyao2;
7229   REAL apexlen, orglen, destlen, minedge;
7230   REAL angle;
7231   REAL area;
7232   REAL dist1, dist2;
7233   subseg sptr;                      /* Temporary variable used by tspivot(). */
7234   triangle ptr;           /* Temporary variable used by oprev() and dnext(). */
7235 
7236   org(*testtri, torg);
7237   dest(*testtri, tdest);
7238   apex(*testtri, tapex);
7239   dxod = torg[0] - tdest[0];
7240   dyod = torg[1] - tdest[1];
7241   dxda = tdest[0] - tapex[0];
7242   dyda = tdest[1] - tapex[1];
7243   dxao = tapex[0] - torg[0];
7244   dyao = tapex[1] - torg[1];
7245   dxod2 = dxod * dxod;
7246   dyod2 = dyod * dyod;
7247   dxda2 = dxda * dxda;
7248   dyda2 = dyda * dyda;
7249   dxao2 = dxao * dxao;
7250   dyao2 = dyao * dyao;
7251   /* Find the lengths of the triangle's three edges. */
7252   apexlen = dxod2 + dyod2;
7253   orglen = dxda2 + dyda2;
7254   destlen = dxao2 + dyao2;
7255 
7256   if ((apexlen < orglen) && (apexlen < destlen)) {
7257     /* The edge opposite the apex is shortest. */
7258     minedge = apexlen;
7259     /* Find the square of the cosine of the angle at the apex. */
7260     angle = dxda * dxao + dyda * dyao;
7261     angle = angle * angle / (orglen * destlen);
7262     base1 = torg;
7263     base2 = tdest;
7264     otricopy(*testtri, tri1);
7265   } else if (orglen < destlen) {
7266     /* The edge opposite the origin is shortest. */
7267     minedge = orglen;
7268     /* Find the square of the cosine of the angle at the origin. */
7269     angle = dxod * dxao + dyod * dyao;
7270     angle = angle * angle / (apexlen * destlen);
7271     base1 = tdest;
7272     base2 = tapex;
7273     lnext(*testtri, tri1);
7274   } else {
7275     /* The edge opposite the destination is shortest. */
7276     minedge = destlen;
7277     /* Find the square of the cosine of the angle at the destination. */
7278     angle = dxod * dxda + dyod * dyda;
7279     angle = angle * angle / (apexlen * orglen);
7280     base1 = tapex;
7281     base2 = torg;
7282     lprev(*testtri, tri1);
7283   }
7284 
7285   if (b->vararea || b->fixedarea || b->usertest) {
7286     /* Check whether the area is larger than permitted. */
7287     area = 0.5 * (dxod * dyda - dyod * dxda);
7288     if (b->fixedarea && (area > b->maxarea)) {
7289       /* Add this triangle to the list of bad triangles. */
7290       enqueuebadtri(m, b, testtri, minedge, tapex, torg, tdest);
7291       return;
7292     }
7293 
7294     /* Nonpositive area constraints are treated as unconstrained. */
7295     if ((b->vararea) && (area > areabound(*testtri)) &&
7296         (areabound(*testtri) > 0.0)) {
7297       /* Add this triangle to the list of bad triangles. */
7298       enqueuebadtri(m, b, testtri, minedge, tapex, torg, tdest);
7299       return;
7300     }
7301 
7302     if (b->usertest) {
7303       /* Check whether the user thinks this triangle is too large. */
7304       if (triunsuitable(torg, tdest, tapex, area)) {
7305         enqueuebadtri(m, b, testtri, minedge, tapex, torg, tdest);
7306         return;
7307       }
7308     }
7309   }
7310 
7311   /* Check whether the angle is smaller than permitted. */
7312   if (angle > b->goodangle) {
7313     /* Use the rules of Miller, Pav, and Walkington to decide that certain */
7314     /*   triangles should not be split, even if they have bad angles.      */
7315     /*   A skinny triangle is not split if its shortest edge subtends a    */
7316     /*   small input angle, and both endpoints of the edge lie on a        */
7317     /*   concentric circular shell.  For convenience, I make a small       */
7318     /*   adjustment to that rule:  I check if the endpoints of the edge    */
7319     /*   both lie in segment interiors, equidistant from the apex where    */
7320     /*   the two segments meet.                                            */
7321     /* First, check if both points lie in segment interiors.               */
7322     if ((vertextype(base1) == SEGMENTVERTEX) &&
7323         (vertextype(base2) == SEGMENTVERTEX)) {
7324       /* Check if both points lie in a common segment.  If they do, the */
7325       /*   skinny triangle is enqueued to be split as usual.            */
7326       tspivot(tri1, testsub);
7327       if (testsub.ss == m->dummysub) {
7328         /* No common segment.  Find a subsegment that contains `torg'. */
7329         otricopy(tri1, tri2);
7330         do {
7331           oprevself(tri1);
7332           tspivot(tri1, testsub);
7333         } while (testsub.ss == m->dummysub);
7334         /* Find the endpoints of the containing segment. */
7335         segorg(testsub, org1);
7336         segdest(testsub, dest1);
7337         /* Find a subsegment that contains `tdest'. */
7338         do {
7339           dnextself(tri2);
7340           tspivot(tri2, testsub);
7341         } while (testsub.ss == m->dummysub);
7342         /* Find the endpoints of the containing segment. */
7343         segorg(testsub, org2);
7344         segdest(testsub, dest2);
7345         /* Check if the two containing segments have an endpoint in common. */
7346         joinvertex = (vertex) NULL;
7347         if ((dest1[0] == org2[0]) && (dest1[1] == org2[1])) {
7348           joinvertex = dest1;
7349         } else if ((org1[0] == dest2[0]) && (org1[1] == dest2[1])) {
7350           joinvertex = org1;
7351         }
7352         if (joinvertex != (vertex) NULL) {
7353           /* Compute the distance from the common endpoint (of the two  */
7354           /*   segments) to each of the endpoints of the shortest edge. */
7355           dist1 = ((base1[0] - joinvertex[0]) * (base1[0] - joinvertex[0]) +
7356                    (base1[1] - joinvertex[1]) * (base1[1] - joinvertex[1]));
7357           dist2 = ((base2[0] - joinvertex[0]) * (base2[0] - joinvertex[0]) +
7358                    (base2[1] - joinvertex[1]) * (base2[1] - joinvertex[1]));
7359           /* If the two distances are equal, don't split the triangle. */
7360           if ((dist1 < 1.001 * dist2) && (dist1 > 0.999 * dist2)) {
7361             /* Return now to avoid enqueueing the bad triangle. */
7362             return;
7363           }
7364         }
7365       }
7366     }
7367 
7368     /* Add this triangle to the list of bad triangles. */
7369     enqueuebadtri(m, b, testtri, minedge, tapex, torg, tdest);
7370   }
7371 }
7372 
7373 #endif /* not CDT_ONLY */
7374 
7375 /**                                                                         **/
7376 /**                                                                         **/
7377 /********* Mesh quality testing routines end here                    *********/
7378 
7379 /********* Point location routines begin here                        *********/
7380 /**                                                                         **/
7381 /**                                                                         **/
7382 
7383 /*****************************************************************************/
7384 /*                                                                           */
7385 /*  makevertexmap()   Construct a mapping from vertices to triangles to      */
7386 /*                    improve the speed of point location for segment        */
7387 /*                    insertion.                                             */
7388 /*                                                                           */
7389 /*  Traverses all the triangles, and provides each corner of each triangle   */
7390 /*  with a pointer to that triangle.  Of course, pointers will be            */
7391 /*  overwritten by other pointers because (almost) each vertex is a corner   */
7392 /*  of several triangles, but in the end every vertex will point to some     */
7393 /*  triangle that contains it.                                               */
7394 /*                                                                           */
7395 /*****************************************************************************/
7396 
7397 #ifdef ANSI_DECLARATORS
7398 void makevertexmap(struct mesh *m, struct behavior *b)
7399 #else /* not ANSI_DECLARATORS */
7400 void makevertexmap(m, b)
7401 struct mesh *m;
7402 struct behavior *b;
7403 #endif /* not ANSI_DECLARATORS */
7404 
7405 {
7406   struct otri triangleloop;
7407   vertex triorg;
7408 
7409   if (b->verbose) {
7410     printf("    Constructing mapping from vertices to triangles.\n");
7411   }
7412   traversalinit(&m->triangles);
7413   triangleloop.tri = triangletraverse(m);
7414   while (triangleloop.tri != (triangle *) NULL) {
7415     /* Check all three vertices of the triangle. */
7416     for (triangleloop.orient = 0; triangleloop.orient < 3;
7417          triangleloop.orient++) {
7418       org(triangleloop, triorg);
7419       setvertex2tri(triorg, encode(triangleloop));
7420     }
7421     triangleloop.tri = triangletraverse(m);
7422   }
7423 }
7424 
7425 /*****************************************************************************/
7426 /*                                                                           */
7427 /*  preciselocate()   Find a triangle or edge containing a given point.      */
7428 /*                                                                           */
7429 /*  Begins its search from `searchtri'.  It is important that `searchtri'    */
7430 /*  be a handle with the property that `searchpoint' is strictly to the left */
7431 /*  of the edge denoted by `searchtri', or is collinear with that edge and   */
7432 /*  does not intersect that edge.  (In particular, `searchpoint' should not  */
7433 /*  be the origin or destination of that edge.)                              */
7434 /*                                                                           */
7435 /*  These conditions are imposed because preciselocate() is normally used in */
7436 /*  one of two situations:                                                   */
7437 /*                                                                           */
7438 /*  (1)  To try to find the location to insert a new point.  Normally, we    */
7439 /*       know an edge that the point is strictly to the left of.  In the     */
7440 /*       incremental Delaunay algorithm, that edge is a bounding box edge.   */
7441 /*       In Ruppert's Delaunay refinement algorithm for quality meshing,     */
7442 /*       that edge is the shortest edge of the triangle whose circumcenter   */
7443 /*       is being inserted.                                                  */
7444 /*                                                                           */
7445 /*  (2)  To try to find an existing point.  In this case, any edge on the    */
7446 /*       convex hull is a good starting edge.  You must screen out the       */
7447 /*       possibility that the vertex sought is an endpoint of the starting   */
7448 /*       edge before you call preciselocate().                               */
7449 /*                                                                           */
7450 /*  On completion, `searchtri' is a triangle that contains `searchpoint'.    */
7451 /*                                                                           */
7452 /*  This implementation differs from that given by Guibas and Stolfi.  It    */
7453 /*  walks from triangle to triangle, crossing an edge only if `searchpoint'  */
7454 /*  is on the other side of the line containing that edge.  After entering   */
7455 /*  a triangle, there are two edges by which one can leave that triangle.    */
7456 /*  If both edges are valid (`searchpoint' is on the other side of both      */
7457 /*  edges), one of the two is chosen by drawing a line perpendicular to      */
7458 /*  the entry edge (whose endpoints are `forg' and `fdest') passing through  */
7459 /*  `fapex'.  Depending on which side of this perpendicular `searchpoint'    */
7460 /*  falls on, an exit edge is chosen.                                        */
7461 /*                                                                           */
7462 /*  This implementation is empirically faster than the Guibas and Stolfi     */
7463 /*  point location routine (which I originally used), which tends to spiral  */
7464 /*  in toward its target.                                                    */
7465 /*                                                                           */
7466 /*  Returns ONVERTEX if the point lies on an existing vertex.  `searchtri'   */
7467 /*  is a handle whose origin is the existing vertex.                         */
7468 /*                                                                           */
7469 /*  Returns ONEDGE if the point lies on a mesh edge.  `searchtri' is a       */
7470 /*  handle whose primary edge is the edge on which the point lies.           */
7471 /*                                                                           */
7472 /*  Returns INTRIANGLE if the point lies strictly within a triangle.         */
7473 /*  `searchtri' is a handle on the triangle that contains the point.         */
7474 /*                                                                           */
7475 /*  Returns OUTSIDE if the point lies outside the mesh.  `searchtri' is a    */
7476 /*  handle whose primary edge the point is to the right of.  This might      */
7477 /*  occur when the circumcenter of a triangle falls just slightly outside    */
7478 /*  the mesh due to floating-point roundoff error.  It also occurs when      */
7479 /*  seeking a hole or region point that a foolish user has placed outside    */
7480 /*  the mesh.                                                                */
7481 /*                                                                           */
7482 /*  If `stopatsubsegment' is nonzero, the search will stop if it tries to    */
7483 /*  walk through a subsegment, and will return OUTSIDE.                      */
7484 /*                                                                           */
7485 /*  WARNING:  This routine is designed for convex triangulations, and will   */
7486 /*  not generally work after the holes and concavities have been carved.     */
7487 /*  However, it can still be used to find the circumcenter of a triangle, as */
7488 /*  long as the search is begun from the triangle in question.               */
7489 /*                                                                           */
7490 /*****************************************************************************/
7491 
7492 #ifdef ANSI_DECLARATORS
7493 enum locateresult preciselocate(struct mesh *m, struct behavior *b,
7494                                 vertex searchpoint, struct otri *searchtri,
7495                                 int stopatsubsegment)
7496 #else /* not ANSI_DECLARATORS */
7497 enum locateresult preciselocate(m, b, searchpoint, searchtri, stopatsubsegment)
7498 struct mesh *m;
7499 struct behavior *b;
7500 vertex searchpoint;
7501 struct otri *searchtri;
7502 int stopatsubsegment;
7503 #endif /* not ANSI_DECLARATORS */
7504 
7505 {
7506   struct otri backtracktri;
7507   struct osub checkedge;
7508   vertex forg, fdest, fapex;
7509   REAL orgorient, destorient;
7510   int moveleft;
7511   triangle ptr;                         /* Temporary variable used by sym(). */
7512   subseg sptr;                      /* Temporary variable used by tspivot(). */
7513 
7514   if (b->verbose > 2) {
7515     printf("  Searching for point (%.12g, %.12g).\n",
7516            searchpoint[0], searchpoint[1]);
7517   }
7518   /* Where are we? */
7519   org(*searchtri, forg);
7520   dest(*searchtri, fdest);
7521   apex(*searchtri, fapex);
7522   while (1) {
7523     if (b->verbose > 2) {
7524       printf("    At (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
7525              forg[0], forg[1], fdest[0], fdest[1], fapex[0], fapex[1]);
7526     }
7527     /* Check whether the apex is the point we seek. */
7528     if ((fapex[0] == searchpoint[0]) && (fapex[1] == searchpoint[1])) {
7529       lprevself(*searchtri);
7530       return ONVERTEX;
7531     }
7532     /* Does the point lie on the other side of the line defined by the */
7533     /*   triangle edge opposite the triangle's destination?            */
7534     destorient = counterclockwise(m, b, forg, fapex, searchpoint);
7535     /* Does the point lie on the other side of the line defined by the */
7536     /*   triangle edge opposite the triangle's origin?                 */
7537     orgorient = counterclockwise(m, b, fapex, fdest, searchpoint);
7538     if (destorient > 0.0) {
7539       if (orgorient > 0.0) {
7540         /* Move left if the inner product of (fapex - searchpoint) and  */
7541         /*   (fdest - forg) is positive.  This is equivalent to drawing */
7542         /*   a line perpendicular to the line (forg, fdest) and passing */
7543         /*   through `fapex', and determining which side of this line   */
7544         /*   `searchpoint' falls on.                                    */
7545         moveleft = (fapex[0] - searchpoint[0]) * (fdest[0] - forg[0]) +
7546                    (fapex[1] - searchpoint[1]) * (fdest[1] - forg[1]) > 0.0;
7547       } else {
7548         moveleft = 1;
7549       }
7550     } else {
7551       if (orgorient > 0.0) {
7552         moveleft = 0;
7553       } else {
7554         /* The point we seek must be on the boundary of or inside this */
7555         /*   triangle.                                                 */
7556         if (destorient == 0.0) {
7557           lprevself(*searchtri);
7558           return ONEDGE;
7559         }
7560         if (orgorient == 0.0) {
7561           lnextself(*searchtri);
7562           return ONEDGE;
7563         }
7564         return INTRIANGLE;
7565       }
7566     }
7567 
7568     /* Move to another triangle.  Leave a trace `backtracktri' in case */
7569     /*   floating-point roundoff or some such bogey causes us to walk  */
7570     /*   off a boundary of the triangulation.                          */
7571     if (moveleft) {
7572       lprev(*searchtri, backtracktri);
7573       fdest = fapex;
7574     } else {
7575       lnext(*searchtri, backtracktri);
7576       forg = fapex;
7577     }
7578     sym(backtracktri, *searchtri);
7579 
7580     if (m->checksegments && stopatsubsegment) {
7581       /* Check for walking through a subsegment. */
7582       tspivot(backtracktri, checkedge);
7583       if (checkedge.ss != m->dummysub) {
7584         /* Go back to the last triangle. */
7585         otricopy(backtracktri, *searchtri);
7586         return OUTSIDE;
7587       }
7588     }
7589     /* Check for walking right out of the triangulation. */
7590     if (searchtri->tri == m->dummytri) {
7591       /* Go back to the last triangle. */
7592       otricopy(backtracktri, *searchtri);
7593       return OUTSIDE;
7594     }
7595 
7596     apex(*searchtri, fapex);
7597   }
7598 }
7599 
7600 /*****************************************************************************/
7601 /*                                                                           */
7602 /*  locate()   Find a triangle or edge containing a given point.             */
7603 /*                                                                           */
7604 /*  Searching begins from one of:  the input `searchtri', a recently         */
7605 /*  encountered triangle `recenttri', or from a triangle chosen from a       */
7606 /*  random sample.  The choice is made by determining which triangle's       */
7607 /*  origin is closest to the point we are searching for.  Normally,          */
7608 /*  `searchtri' should be a handle on the convex hull of the triangulation.  */
7609 /*                                                                           */
7610 /*  Details on the random sampling method can be found in the Mucke, Saias,  */
7611 /*  and Zhu paper cited in the header of this code.                          */
7612 /*                                                                           */
7613 /*  On completion, `searchtri' is a triangle that contains `searchpoint'.    */
7614 /*                                                                           */
7615 /*  Returns ONVERTEX if the point lies on an existing vertex.  `searchtri'   */
7616 /*  is a handle whose origin is the existing vertex.                         */
7617 /*                                                                           */
7618 /*  Returns ONEDGE if the point lies on a mesh edge.  `searchtri' is a       */
7619 /*  handle whose primary edge is the edge on which the point lies.           */
7620 /*                                                                           */
7621 /*  Returns INTRIANGLE if the point lies strictly within a triangle.         */
7622 /*  `searchtri' is a handle on the triangle that contains the point.         */
7623 /*                                                                           */
7624 /*  Returns OUTSIDE if the point lies outside the mesh.  `searchtri' is a    */
7625 /*  handle whose primary edge the point is to the right of.  This might      */
7626 /*  occur when the circumcenter of a triangle falls just slightly outside    */
7627 /*  the mesh due to floating-point roundoff error.  It also occurs when      */
7628 /*  seeking a hole or region point that a foolish user has placed outside    */
7629 /*  the mesh.                                                                */
7630 /*                                                                           */
7631 /*  WARNING:  This routine is designed for convex triangulations, and will   */
7632 /*  not generally work after the holes and concavities have been carved.     */
7633 /*                                                                           */
7634 /*****************************************************************************/
7635 
7636 #ifdef ANSI_DECLARATORS
7637 enum locateresult locate(struct mesh *m, struct behavior *b,
7638                          vertex searchpoint, struct otri *searchtri)
7639 #else /* not ANSI_DECLARATORS */
7640 enum locateresult locate(m, b, searchpoint, searchtri)
7641 struct mesh *m;
7642 struct behavior *b;
7643 vertex searchpoint;
7644 struct otri *searchtri;
7645 #endif /* not ANSI_DECLARATORS */
7646 
7647 {
7648   VOID **sampleblock;
7649   char *firsttri;
7650   struct otri sampletri;
7651   vertex torg, tdest;
7652   unsigned long alignptr;
7653   REAL searchdist, dist;
7654   REAL ahead;
7655   long samplesperblock, totalsamplesleft, samplesleft;
7656   long population, totalpopulation;
7657   triangle ptr;                         /* Temporary variable used by sym(). */
7658 
7659   if (b->verbose > 2) {
7660     printf("  Randomly sampling for a triangle near point (%.12g, %.12g).\n",
7661            searchpoint[0], searchpoint[1]);
7662   }
7663   /* Record the distance from the suggested starting triangle to the */
7664   /*   point we seek.                                                */
7665   org(*searchtri, torg);
7666   searchdist = (searchpoint[0] - torg[0]) * (searchpoint[0] - torg[0]) +
7667                (searchpoint[1] - torg[1]) * (searchpoint[1] - torg[1]);
7668   if (b->verbose > 2) {
7669     printf("    Boundary triangle has origin (%.12g, %.12g).\n",
7670            torg[0], torg[1]);
7671   }
7672 
7673   /* If a recently encountered triangle has been recorded and has not been */
7674   /*   deallocated, test it as a good starting point.                      */
7675   if (m->recenttri.tri != (triangle *) NULL) {
7676     if (!deadtri(m->recenttri.tri)) {
7677       org(m->recenttri, torg);
7678       if ((torg[0] == searchpoint[0]) && (torg[1] == searchpoint[1])) {
7679         otricopy(m->recenttri, *searchtri);
7680         return ONVERTEX;
7681       }
7682       dist = (searchpoint[0] - torg[0]) * (searchpoint[0] - torg[0]) +
7683              (searchpoint[1] - torg[1]) * (searchpoint[1] - torg[1]);
7684       if (dist < searchdist) {
7685         otricopy(m->recenttri, *searchtri);
7686         searchdist = dist;
7687         if (b->verbose > 2) {
7688           printf("    Choosing recent triangle with origin (%.12g, %.12g).\n",
7689                  torg[0], torg[1]);
7690         }
7691       }
7692     }
7693   }
7694 
7695   /* The number of random samples taken is proportional to the cube root of */
7696   /*   the number of triangles in the mesh.  The next bit of code assumes   */
7697   /*   that the number of triangles increases monotonically (or at least    */
7698   /*   doesn't decrease enough to matter).                                  */
7699   while (SAMPLEFACTOR * m->samples * m->samples * m->samples <
7700          m->triangles.items) {
7701     m->samples++;
7702   }
7703 
7704   /* We'll draw ceiling(samples * TRIPERBLOCK / maxitems) random samples  */
7705   /*   from each block of triangles (except the first)--until we meet the */
7706   /*   sample quota.  The ceiling means that blocks at the end might be   */
7707   /*   neglected, but I don't care.                                       */
7708   samplesperblock = (m->samples * TRIPERBLOCK - 1) / m->triangles.maxitems + 1;
7709   /* We'll draw ceiling(samples * itemsfirstblock / maxitems) random samples */
7710   /*   from the first block of triangles.                                    */
7711   samplesleft = (m->samples * m->triangles.itemsfirstblock - 1) /
7712                 m->triangles.maxitems + 1;
7713   totalsamplesleft = m->samples;
7714   population = m->triangles.itemsfirstblock;
7715   totalpopulation = m->triangles.maxitems;
7716   sampleblock = m->triangles.firstblock;
7717   sampletri.orient = 0;
7718   while (totalsamplesleft > 0) {
7719     /* If we're in the last block, `population' needs to be corrected. */
7720     if (population > totalpopulation) {
7721       population = totalpopulation;
7722     }
7723     /* Find a pointer to the first triangle in the block. */
7724     alignptr = (unsigned long) (sampleblock + 1);
7725     firsttri = (char *) (alignptr +
7726                          (unsigned long) m->triangles.alignbytes -
7727                          (alignptr %
7728                           (unsigned long) m->triangles.alignbytes));
7729 
7730     /* Choose `samplesleft' randomly sampled triangles in this block. */
7731     do {
7732       sampletri.tri = (triangle *) (firsttri +
7733                                     (randomnation((unsigned int) population) *
7734                                      m->triangles.itembytes));
7735       if (!deadtri(sampletri.tri)) {
7736         org(sampletri, torg);
7737         dist = (searchpoint[0] - torg[0]) * (searchpoint[0] - torg[0]) +
7738                (searchpoint[1] - torg[1]) * (searchpoint[1] - torg[1]);
7739         if (dist < searchdist) {
7740           otricopy(sampletri, *searchtri);
7741           searchdist = dist;
7742           if (b->verbose > 2) {
7743             printf("    Choosing triangle with origin (%.12g, %.12g).\n",
7744                    torg[0], torg[1]);
7745           }
7746         }
7747       }
7748 
7749       samplesleft--;
7750       totalsamplesleft--;
7751     } while ((samplesleft > 0) && (totalsamplesleft > 0));
7752 
7753     if (totalsamplesleft > 0) {
7754       sampleblock = (VOID **) *sampleblock;
7755       samplesleft = samplesperblock;
7756       totalpopulation -= population;
7757       population = TRIPERBLOCK;
7758     }
7759   }
7760 
7761   /* Where are we? */
7762   org(*searchtri, torg);
7763   dest(*searchtri, tdest);
7764   /* Check the starting triangle's vertices. */
7765   if ((torg[0] == searchpoint[0]) && (torg[1] == searchpoint[1])) {
7766     return ONVERTEX;
7767   }
7768   if ((tdest[0] == searchpoint[0]) && (tdest[1] == searchpoint[1])) {
7769     lnextself(*searchtri);
7770     return ONVERTEX;
7771   }
7772   /* Orient `searchtri' to fit the preconditions of calling preciselocate(). */
7773   ahead = counterclockwise(m, b, torg, tdest, searchpoint);
7774   if (ahead < 0.0) {
7775     /* Turn around so that `searchpoint' is to the left of the */
7776     /*   edge specified by `searchtri'.                        */
7777     symself(*searchtri);
7778   } else if (ahead == 0.0) {
7779     /* Check if `searchpoint' is between `torg' and `tdest'. */
7780     if (((torg[0] < searchpoint[0]) == (searchpoint[0] < tdest[0])) &&
7781         ((torg[1] < searchpoint[1]) == (searchpoint[1] < tdest[1]))) {
7782       return ONEDGE;
7783     }
7784   }
7785   return preciselocate(m, b, searchpoint, searchtri, 0);
7786 }
7787 
7788 /**                                                                         **/
7789 /**                                                                         **/
7790 /********* Point location routines end here                          *********/
7791 
7792 /********* Mesh transformation routines begin here                   *********/
7793 /**                                                                         **/
7794 /**                                                                         **/
7795 
7796 /*****************************************************************************/
7797 /*                                                                           */
7798 /*  insertsubseg()   Create a new subsegment and insert it between two       */
7799 /*                   triangles.                                              */
7800 /*                                                                           */
7801 /*  The new subsegment is inserted at the edge described by the handle       */
7802 /*  `tri'.  Its vertices are properly initialized.  The marker `subsegmark'  */
7803 /*  is applied to the subsegment and, if appropriate, its vertices.          */
7804 /*                                                                           */
7805 /*****************************************************************************/
7806 
7807 #ifdef ANSI_DECLARATORS
7808 void insertsubseg(struct mesh *m, struct behavior *b, struct otri *tri,
7809                   int subsegmark)
7810 #else /* not ANSI_DECLARATORS */
7811 void insertsubseg(m, b, tri, subsegmark)
7812 struct mesh *m;
7813 struct behavior *b;
7814 struct otri *tri;             /* Edge at which to insert the new subsegment. */
7815 int subsegmark;                            /* Marker for the new subsegment. */
7816 #endif /* not ANSI_DECLARATORS */
7817 
7818 {
7819   struct otri oppotri;
7820   struct osub newsubseg;
7821   vertex triorg, tridest;
7822   triangle ptr;                         /* Temporary variable used by sym(). */
7823   subseg sptr;                      /* Temporary variable used by tspivot(). */
7824 
7825   org(*tri, triorg);
7826   dest(*tri, tridest);
7827   /* Mark vertices if possible. */
7828   if (vertexmark(triorg) == 0) {
7829     setvertexmark(triorg, subsegmark);
7830   }
7831   if (vertexmark(tridest) == 0) {
7832     setvertexmark(tridest, subsegmark);
7833   }
7834   /* Check if there's already a subsegment here. */
7835   tspivot(*tri, newsubseg);
7836   if (newsubseg.ss == m->dummysub) {
7837     /* Make new subsegment and initialize its vertices. */
7838     makesubseg(m, &newsubseg);
7839     setsorg(newsubseg, tridest);
7840     setsdest(newsubseg, triorg);
7841     setsegorg(newsubseg, tridest);
7842     setsegdest(newsubseg, triorg);
7843     /* Bond new subsegment to the two triangles it is sandwiched between. */
7844     /*   Note that the facing triangle `oppotri' might be equal to        */
7845     /*   `dummytri' (outer space), but the new subsegment is bonded to it */
7846     /*   all the same.                                                    */
7847     tsbond(*tri, newsubseg);
7848     sym(*tri, oppotri);
7849     ssymself(newsubseg);
7850     tsbond(oppotri, newsubseg);
7851     setmark(newsubseg, subsegmark);
7852     if (b->verbose > 2) {
7853       printf("  Inserting new ");
7854       printsubseg(m, b, &newsubseg);
7855     }
7856   } else {
7857     if (mark(newsubseg) == 0) {
7858       setmark(newsubseg, subsegmark);
7859     }
7860   }
7861 }
7862 
7863 /*****************************************************************************/
7864 /*                                                                           */
7865 /*  Terminology                                                              */
7866 /*                                                                           */
7867 /*  A "local transformation" replaces a small set of triangles with another  */
7868 /*  set of triangles.  This may or may not involve inserting or deleting a   */
7869 /*  vertex.                                                                  */
7870 /*                                                                           */
7871 /*  The term "casing" is used to describe the set of triangles that are      */
7872 /*  attached to the triangles being transformed, but are not transformed     */
7873 /*  themselves.  Think of the casing as a fixed hollow structure inside      */
7874 /*  which all the action happens.  A "casing" is only defined relative to    */
7875 /*  a single transformation; each occurrence of a transformation will        */
7876 /*  involve a different casing.                                              */
7877 /*                                                                           */
7878 /*****************************************************************************/
7879 
7880 /*****************************************************************************/
7881 /*                                                                           */
7882 /*  flip()   Transform two triangles to two different triangles by flipping  */
7883 /*           an edge counterclockwise within a quadrilateral.                */
7884 /*                                                                           */
7885 /*  Imagine the original triangles, abc and bad, oriented so that the        */
7886 /*  shared edge ab lies in a horizontal plane, with the vertex b on the left */
7887 /*  and the vertex a on the right.  The vertex c lies below the edge, and    */
7888 /*  the vertex d lies above the edge.  The `flipedge' handle holds the edge  */
7889 /*  ab of triangle abc, and is directed left, from vertex a to vertex b.     */
7890 /*                                                                           */
7891 /*  The triangles abc and bad are deleted and replaced by the triangles cdb  */
7892 /*  and dca.  The triangles that represent abc and bad are NOT deallocated;  */
7893 /*  they are reused for dca and cdb, respectively.  Hence, any handles that  */
7894 /*  may have held the original triangles are still valid, although not       */
7895 /*  directed as they were before.                                            */
7896 /*                                                                           */
7897 /*  Upon completion of this routine, the `flipedge' handle holds the edge    */
7898 /*  dc of triangle dca, and is directed down, from vertex d to vertex c.     */
7899 /*  (Hence, the two triangles have rotated counterclockwise.)                */
7900 /*                                                                           */
7901 /*  WARNING:  This transformation is geometrically valid only if the         */
7902 /*  quadrilateral adbc is convex.  Furthermore, this transformation is       */
7903 /*  valid only if there is not a subsegment between the triangles abc and    */
7904 /*  bad.  This routine does not check either of these preconditions, and     */
7905 /*  it is the responsibility of the calling routine to ensure that they are  */
7906 /*  met.  If they are not, the streets shall be filled with wailing and      */
7907 /*  gnashing of teeth.                                                       */
7908 /*                                                                           */
7909 /*****************************************************************************/
7910 
7911 #ifdef ANSI_DECLARATORS
7912 void flip(struct mesh *m, struct behavior *b, struct otri *flipedge)
7913 #else /* not ANSI_DECLARATORS */
7914 void flip(m, b, flipedge)
7915 struct mesh *m;
7916 struct behavior *b;
7917 struct otri *flipedge;                    /* Handle for the triangle abc. */
7918 #endif /* not ANSI_DECLARATORS */
7919 
7920 {
7921   struct otri botleft, botright;
7922   struct otri topleft, topright;
7923   struct otri top;
7924   struct otri botlcasing, botrcasing;
7925   struct otri toplcasing, toprcasing;
7926   struct osub botlsubseg, botrsubseg;
7927   struct osub toplsubseg, toprsubseg;
7928   vertex leftvertex, rightvertex, botvertex;
7929   vertex farvertex;
7930   triangle ptr;                         /* Temporary variable used by sym(). */
7931   subseg sptr;                      /* Temporary variable used by tspivot(). */
7932 
7933   /* Identify the vertices of the quadrilateral. */
7934   org(*flipedge, rightvertex);
7935   dest(*flipedge, leftvertex);
7936   apex(*flipedge, botvertex);
7937   sym(*flipedge, top);
7938 #ifdef SELF_CHECK
7939   if (top.tri == m->dummytri) {
7940     printf("Internal error in flip():  Attempt to flip on boundary.\n");
7941     lnextself(*flipedge);
7942     return;
7943   }
7944   if (m->checksegments) {
7945     tspivot(*flipedge, toplsubseg);
7946     if (toplsubseg.ss != m->dummysub) {
7947       printf("Internal error in flip():  Attempt to flip a segment.\n");
7948       lnextself(*flipedge);
7949       return;
7950     }
7951   }
7952 #endif /* SELF_CHECK */
7953   apex(top, farvertex);
7954 
7955   /* Identify the casing of the quadrilateral. */
7956   lprev(top, topleft);
7957   sym(topleft, toplcasing);
7958   lnext(top, topright);
7959   sym(topright, toprcasing);
7960   lnext(*flipedge, botleft);
7961   sym(botleft, botlcasing);
7962   lprev(*flipedge, botright);
7963   sym(botright, botrcasing);
7964   /* Rotate the quadrilateral one-quarter turn counterclockwise. */
7965   bond(topleft, botlcasing);
7966   bond(botleft, botrcasing);
7967   bond(botright, toprcasing);
7968   bond(topright, toplcasing);
7969 
7970   if (m->checksegments) {
7971     /* Check for subsegments and rebond them to the quadrilateral. */
7972     tspivot(topleft, toplsubseg);
7973     tspivot(botleft, botlsubseg);
7974     tspivot(botright, botrsubseg);
7975     tspivot(topright, toprsubseg);
7976     if (toplsubseg.ss == m->dummysub) {
7977       tsdissolve(topright);
7978     } else {
7979       tsbond(topright, toplsubseg);
7980     }
7981     if (botlsubseg.ss == m->dummysub) {
7982       tsdissolve(topleft);
7983     } else {
7984       tsbond(topleft, botlsubseg);
7985     }
7986     if (botrsubseg.ss == m->dummysub) {
7987       tsdissolve(botleft);
7988     } else {
7989       tsbond(botleft, botrsubseg);
7990     }
7991     if (toprsubseg.ss == m->dummysub) {
7992       tsdissolve(botright);
7993     } else {
7994       tsbond(botright, toprsubseg);
7995     }
7996   }
7997 
7998   /* New vertex assignments for the rotated quadrilateral. */
7999   setorg(*flipedge, farvertex);
8000   setdest(*flipedge, botvertex);
8001   setapex(*flipedge, rightvertex);
8002   setorg(top, botvertex);
8003   setdest(top, farvertex);
8004   setapex(top, leftvertex);
8005   if (b->verbose > 2) {
8006     printf("  Edge flip results in left ");
8007     printtriangle(m, b, &top);
8008     printf("  and right ");
8009     printtriangle(m, b, flipedge);
8010   }
8011 }
8012 
8013 /*****************************************************************************/
8014 /*                                                                           */
8015 /*  unflip()   Transform two triangles to two different triangles by         */
8016 /*             flipping an edge clockwise within a quadrilateral.  Reverses  */
8017 /*             the flip() operation so that the data structures representing */
8018 /*             the triangles are back where they were before the flip().     */
8019 /*                                                                           */
8020 /*  Imagine the original triangles, abc and bad, oriented so that the        */
8021 /*  shared edge ab lies in a horizontal plane, with the vertex b on the left */
8022 /*  and the vertex a on the right.  The vertex c lies below the edge, and    */
8023 /*  the vertex d lies above the edge.  The `flipedge' handle holds the edge  */
8024 /*  ab of triangle abc, and is directed left, from vertex a to vertex b.     */
8025 /*                                                                           */
8026 /*  The triangles abc and bad are deleted and replaced by the triangles cdb  */
8027 /*  and dca.  The triangles that represent abc and bad are NOT deallocated;  */
8028 /*  they are reused for cdb and dca, respectively.  Hence, any handles that  */
8029 /*  may have held the original triangles are still valid, although not       */
8030 /*  directed as they were before.                                            */
8031 /*                                                                           */
8032 /*  Upon completion of this routine, the `flipedge' handle holds the edge    */
8033 /*  cd of triangle cdb, and is directed up, from vertex c to vertex d.       */
8034 /*  (Hence, the two triangles have rotated clockwise.)                       */
8035 /*                                                                           */
8036 /*  WARNING:  This transformation is geometrically valid only if the         */
8037 /*  quadrilateral adbc is convex.  Furthermore, this transformation is       */
8038 /*  valid only if there is not a subsegment between the triangles abc and    */
8039 /*  bad.  This routine does not check either of these preconditions, and     */
8040 /*  it is the responsibility of the calling routine to ensure that they are  */
8041 /*  met.  If they are not, the streets shall be filled with wailing and      */
8042 /*  gnashing of teeth.                                                       */
8043 /*                                                                           */
8044 /*****************************************************************************/
8045 
8046 #ifdef ANSI_DECLARATORS
8047 void unflip(struct mesh *m, struct behavior *b, struct otri *flipedge)
8048 #else /* not ANSI_DECLARATORS */
8049 void unflip(m, b, flipedge)
8050 struct mesh *m;
8051 struct behavior *b;
8052 struct otri *flipedge;                    /* Handle for the triangle abc. */
8053 #endif /* not ANSI_DECLARATORS */
8054 
8055 {
8056   struct otri botleft, botright;
8057   struct otri topleft, topright;
8058   struct otri top;
8059   struct otri botlcasing, botrcasing;
8060   struct otri toplcasing, toprcasing;
8061   struct osub botlsubseg, botrsubseg;
8062   struct osub toplsubseg, toprsubseg;
8063   vertex leftvertex, rightvertex, botvertex;
8064   vertex farvertex;
8065   triangle ptr;                         /* Temporary variable used by sym(). */
8066   subseg sptr;                      /* Temporary variable used by tspivot(). */
8067 
8068   /* Identify the vertices of the quadrilateral. */
8069   org(*flipedge, rightvertex);
8070   dest(*flipedge, leftvertex);
8071   apex(*flipedge, botvertex);
8072   sym(*flipedge, top);
8073 #ifdef SELF_CHECK
8074   if (top.tri == m->dummytri) {
8075     printf("Internal error in unflip():  Attempt to flip on boundary.\n");
8076     lnextself(*flipedge);
8077     return;
8078   }
8079   if (m->checksegments) {
8080     tspivot(*flipedge, toplsubseg);
8081     if (toplsubseg.ss != m->dummysub) {
8082       printf("Internal error in unflip():  Attempt to flip a subsegment.\n");
8083       lnextself(*flipedge);
8084       return;
8085     }
8086   }
8087 #endif /* SELF_CHECK */
8088   apex(top, farvertex);
8089 
8090   /* Identify the casing of the quadrilateral. */
8091   lprev(top, topleft);
8092   sym(topleft, toplcasing);
8093   lnext(top, topright);
8094   sym(topright, toprcasing);
8095   lnext(*flipedge, botleft);
8096   sym(botleft, botlcasing);
8097   lprev(*flipedge, botright);
8098   sym(botright, botrcasing);
8099   /* Rotate the quadrilateral one-quarter turn clockwise. */
8100   bond(topleft, toprcasing);
8101   bond(botleft, toplcasing);
8102   bond(botright, botlcasing);
8103   bond(topright, botrcasing);
8104 
8105   if (m->checksegments) {
8106     /* Check for subsegments and rebond them to the quadrilateral. */
8107     tspivot(topleft, toplsubseg);
8108     tspivot(botleft, botlsubseg);
8109     tspivot(botright, botrsubseg);
8110     tspivot(topright, toprsubseg);
8111     if (toplsubseg.ss == m->dummysub) {
8112       tsdissolve(botleft);
8113     } else {
8114       tsbond(botleft, toplsubseg);
8115     }
8116     if (botlsubseg.ss == m->dummysub) {
8117       tsdissolve(botright);
8118     } else {
8119       tsbond(botright, botlsubseg);
8120     }
8121     if (botrsubseg.ss == m->dummysub) {
8122       tsdissolve(topright);
8123     } else {
8124       tsbond(topright, botrsubseg);
8125     }
8126     if (toprsubseg.ss == m->dummysub) {
8127       tsdissolve(topleft);
8128     } else {
8129       tsbond(topleft, toprsubseg);
8130     }
8131   }
8132 
8133   /* New vertex assignments for the rotated quadrilateral. */
8134   setorg(*flipedge, botvertex);
8135   setdest(*flipedge, farvertex);
8136   setapex(*flipedge, leftvertex);
8137   setorg(top, farvertex);
8138   setdest(top, botvertex);
8139   setapex(top, rightvertex);
8140   if (b->verbose > 2) {
8141     printf("  Edge unflip results in left ");
8142     printtriangle(m, b, flipedge);
8143     printf("  and right ");
8144     printtriangle(m, b, &top);
8145   }
8146 }
8147 
8148 /*****************************************************************************/
8149 /*                                                                           */
8150 /*  insertvertex()   Insert a vertex into a Delaunay triangulation,          */
8151 /*                   performing flips as necessary to maintain the Delaunay  */
8152 /*                   property.                                               */
8153 /*                                                                           */
8154 /*  The point `insertvertex' is located.  If `searchtri.tri' is not NULL,    */
8155 /*  the search for the containing triangle begins from `searchtri'.  If      */
8156 /*  `searchtri.tri' is NULL, a full point location procedure is called.      */
8157 /*  If `insertvertex' is found inside a triangle, the triangle is split into */
8158 /*  three; if `insertvertex' lies on an edge, the edge is split in two,      */
8159 /*  thereby splitting the two adjacent triangles into four.  Edge flips are  */
8160 /*  used to restore the Delaunay property.  If `insertvertex' lies on an     */
8161 /*  existing vertex, no action is taken, and the value DUPLICATEVERTEX is    */
8162 /*  returned.  On return, `searchtri' is set to a handle whose origin is the */
8163 /*  existing vertex.                                                         */
8164 /*                                                                           */
8165 /*  Normally, the parameter `splitseg' is set to NULL, implying that no      */
8166 /*  subsegment should be split.  In this case, if `insertvertex' is found to */
8167 /*  lie on a segment, no action is taken, and the value VIOLATINGVERTEX is   */
8168 /*  returned.  On return, `searchtri' is set to a handle whose primary edge  */
8169 /*  is the violated subsegment.                                              */
8170 /*                                                                           */
8171 /*  If the calling routine wishes to split a subsegment by inserting a       */
8172 /*  vertex in it, the parameter `splitseg' should be that subsegment.  In    */
8173 /*  this case, `searchtri' MUST be the triangle handle reached by pivoting   */
8174 /*  from that subsegment; no point location is done.                         */
8175 /*                                                                           */
8176 /*  `segmentflaws' and `triflaws' are flags that indicate whether or not     */
8177 /*  there should be checks for the creation of encroached subsegments or bad */
8178 /*  quality triangles.  If a newly inserted vertex encroaches upon           */
8179 /*  subsegments, these subsegments are added to the list of subsegments to   */
8180 /*  be split if `segmentflaws' is set.  If bad triangles are created, these  */
8181 /*  are added to the queue if `triflaws' is set.                             */
8182 /*                                                                           */
8183 /*  If a duplicate vertex or violated segment does not prevent the vertex    */
8184 /*  from being inserted, the return value will be ENCROACHINGVERTEX if the   */
8185 /*  vertex encroaches upon a subsegment (and checking is enabled), or        */
8186 /*  SUCCESSFULVERTEX otherwise.  In either case, `searchtri' is set to a     */
8187 /*  handle whose origin is the newly inserted vertex.                        */
8188 /*                                                                           */
8189 /*  insertvertex() does not use flip() for reasons of speed; some            */
8190 /*  information can be reused from edge flip to edge flip, like the          */
8191 /*  locations of subsegments.                                                */
8192 /*                                                                           */
8193 /*****************************************************************************/
8194 
8195 #ifdef ANSI_DECLARATORS
8196 enum insertvertexresult insertvertex(struct mesh *m, struct behavior *b,
8197                                      vertex newvertex, struct otri *searchtri,
8198                                      struct osub *splitseg,
8199                                      int segmentflaws, int triflaws)
8200 #else /* not ANSI_DECLARATORS */
8201 enum insertvertexresult insertvertex(m, b, newvertex, searchtri, splitseg,
8202                                      segmentflaws, triflaws)
8203 struct mesh *m;
8204 struct behavior *b;
8205 vertex newvertex;
8206 struct otri *searchtri;
8207 struct osub *splitseg;
8208 int segmentflaws;
8209 int triflaws;
8210 #endif /* not ANSI_DECLARATORS */
8211 
8212 {
8213   struct otri horiz;
8214   struct otri top;
8215   struct otri botleft, botright;
8216   struct otri topleft, topright;
8217   struct otri newbotleft, newbotright;
8218   struct otri newtopright;
8219   struct otri botlcasing, botrcasing;
8220   struct otri toplcasing, toprcasing;
8221   struct otri testtri;
8222   struct osub botlsubseg, botrsubseg;
8223   struct osub toplsubseg, toprsubseg;
8224   struct osub brokensubseg;
8225   struct osub checksubseg;
8226   struct osub rightsubseg;
8227   struct osub newsubseg;
8228   struct badsubseg *encroached;
8229   struct flipstacker *newflip;
8230   vertex first;
8231   vertex leftvertex, rightvertex, botvertex, topvertex, farvertex;
8232   vertex segmentorg, segmentdest;
8233   REAL attrib;
8234   REAL area;
8235   enum insertvertexresult success;
8236   enum locateresult intersect;
8237   int doflip;
8238   int mirrorflag;
8239   int enq;
8240   int i;
8241   triangle ptr;                         /* Temporary variable used by sym(). */
8242   subseg sptr;         /* Temporary variable used by spivot() and tspivot(). */
8243 
8244   if (b->verbose > 1) {
8245     printf("  Inserting (%.12g, %.12g).\n", newvertex[0], newvertex[1]);
8246   }
8247 
8248   if (splitseg == (struct osub *) NULL) {
8249     /* Find the location of the vertex to be inserted.  Check if a good */
8250     /*   starting triangle has already been provided by the caller.     */
8251     if (searchtri->tri == m->dummytri) {
8252       /* Find a boundary triangle. */
8253       horiz.tri = m->dummytri;
8254       horiz.orient = 0;
8255       symself(horiz);
8256       /* Search for a triangle containing `newvertex'. */
8257       intersect = locate(m, b, newvertex, &horiz);
8258     } else {
8259       /* Start searching from the triangle provided by the caller. */
8260       otricopy(*searchtri, horiz);
8261       intersect = preciselocate(m, b, newvertex, &horiz, 1);
8262     }
8263   } else {
8264     /* The calling routine provides the subsegment in which */
8265     /*   the vertex is inserted.                             */
8266     otricopy(*searchtri, horiz);
8267     intersect = ONEDGE;
8268   }
8269 
8270   if (intersect == ONVERTEX) {
8271     /* There's already a vertex there.  Return in `searchtri' a triangle */
8272     /*   whose origin is the existing vertex.                            */
8273     otricopy(horiz, *searchtri);
8274     otricopy(horiz, m->recenttri);
8275     return DUPLICATEVERTEX;
8276   }
8277   if ((intersect == ONEDGE) || (intersect == OUTSIDE)) {
8278     /* The vertex falls on an edge or boundary. */
8279     if (m->checksegments && (splitseg == (struct osub *) NULL)) {
8280       /* Check whether the vertex falls on a subsegment. */
8281       tspivot(horiz, brokensubseg);
8282       if (brokensubseg.ss != m->dummysub) {
8283         /* The vertex falls on a subsegment, and hence will not be inserted. */
8284         if (segmentflaws) {
8285           enq = b->nobisect != 2;
8286           if (enq && (b->nobisect == 1)) {
8287             /* This subsegment may be split only if it is an */
8288             /*   internal boundary.                          */
8289             sym(horiz, testtri);
8290             enq = testtri.tri != m->dummytri;
8291           }
8292           if (enq) {
8293             /* Add the subsegment to the list of encroached subsegments. */
8294             encroached = (struct badsubseg *) poolalloc(&m->badsubsegs);
8295             encroached->encsubseg = sencode(brokensubseg);
8296             sorg(brokensubseg, encroached->subsegorg);
8297             sdest(brokensubseg, encroached->subsegdest);
8298             if (b->verbose > 2) {
8299               printf(
8300           "  Queueing encroached subsegment (%.12g, %.12g) (%.12g, %.12g).\n",
8301                      encroached->subsegorg[0], encroached->subsegorg[1],
8302                      encroached->subsegdest[0], encroached->subsegdest[1]);
8303             }
8304           }
8305         }
8306         /* Return a handle whose primary edge contains the vertex, */
8307         /*   which has not been inserted.                          */
8308         otricopy(horiz, *searchtri);
8309         otricopy(horiz, m->recenttri);
8310         return VIOLATINGVERTEX;
8311       }
8312     }
8313 
8314     /* Insert the vertex on an edge, dividing one triangle into two (if */
8315     /*   the edge lies on a boundary) or two triangles into four.       */
8316     lprev(horiz, botright);
8317     sym(botright, botrcasing);
8318     sym(horiz, topright);
8319     /* Is there a second triangle?  (Or does this edge lie on a boundary?) */
8320     mirrorflag = topright.tri != m->dummytri;
8321     if (mirrorflag) {
8322       lnextself(topright);
8323       sym(topright, toprcasing);
8324       maketriangle(m, b, &newtopright);
8325     } else {
8326       /* Splitting a boundary edge increases the number of boundary edges. */
8327       m->hullsize++;
8328     }
8329     maketriangle(m, b, &newbotright);
8330 
8331     /* Set the vertices of changed and new triangles. */
8332     org(horiz, rightvertex);
8333     dest(horiz, leftvertex);
8334     apex(horiz, botvertex);
8335     setorg(newbotright, botvertex);
8336     setdest(newbotright, rightvertex);
8337     setapex(newbotright, newvertex);
8338     setorg(horiz, newvertex);
8339     for (i = 0; i < m->eextras; i++) {
8340       /* Set the element attributes of a new triangle. */
8341       setelemattribute(newbotright, i, elemattribute(botright, i));
8342     }
8343     if (b->vararea) {
8344       /* Set the area constraint of a new triangle. */
8345       setareabound(newbotright, areabound(botright));
8346     }
8347     if (mirrorflag) {
8348       dest(topright, topvertex);
8349       setorg(newtopright, rightvertex);
8350       setdest(newtopright, topvertex);
8351       setapex(newtopright, newvertex);
8352       setorg(topright, newvertex);
8353       for (i = 0; i < m->eextras; i++) {
8354         /* Set the element attributes of another new triangle. */
8355         setelemattribute(newtopright, i, elemattribute(topright, i));
8356       }
8357       if (b->vararea) {
8358         /* Set the area constraint of another new triangle. */
8359         setareabound(newtopright, areabound(topright));
8360       }
8361     }
8362 
8363     /* There may be subsegments that need to be bonded */
8364     /*   to the new triangle(s).                       */
8365     if (m->checksegments) {
8366       tspivot(botright, botrsubseg);
8367       if (botrsubseg.ss != m->dummysub) {
8368         tsdissolve(botright);
8369         tsbond(newbotright, botrsubseg);
8370       }
8371       if (mirrorflag) {
8372         tspivot(topright, toprsubseg);
8373         if (toprsubseg.ss != m->dummysub) {
8374           tsdissolve(topright);
8375           tsbond(newtopright, toprsubseg);
8376         }
8377       }
8378     }
8379 
8380     /* Bond the new triangle(s) to the surrounding triangles. */
8381     bond(newbotright, botrcasing);
8382     lprevself(newbotright);
8383     bond(newbotright, botright);
8384     lprevself(newbotright);
8385     if (mirrorflag) {
8386       bond(newtopright, toprcasing);
8387       lnextself(newtopright);
8388       bond(newtopright, topright);
8389       lnextself(newtopright);
8390       bond(newtopright, newbotright);
8391     }
8392 
8393     if (splitseg != (struct osub *) NULL) {
8394       /* Split the subsegment into two. */
8395       setsdest(*splitseg, newvertex);
8396       segorg(*splitseg, segmentorg);
8397       segdest(*splitseg, segmentdest);
8398       ssymself(*splitseg);
8399       spivot(*splitseg, rightsubseg);
8400       insertsubseg(m, b, &newbotright, mark(*splitseg));
8401       tspivot(newbotright, newsubseg);
8402       setsegorg(newsubseg, segmentorg);
8403       setsegdest(newsubseg, segmentdest);
8404       sbond(*splitseg, newsubseg);
8405       ssymself(newsubseg);
8406       sbond(newsubseg, rightsubseg);
8407       ssymself(*splitseg);
8408       /* Transfer the subsegment's boundary marker to the vertex */
8409       /*   if required.                                          */
8410       if (vertexmark(newvertex) == 0) {
8411         setvertexmark(newvertex, mark(*splitseg));
8412       }
8413     }
8414 
8415     if (m->checkquality) {
8416       poolrestart(&m->flipstackers);
8417       m->lastflip = (struct flipstacker *) poolalloc(&m->flipstackers);
8418       m->lastflip->flippedtri = encode(horiz);
8419       m->lastflip->prevflip = (struct flipstacker *) &insertvertex;
8420     }
8421 
8422 #ifdef SELF_CHECK
8423     if (counterclockwise(m, b, rightvertex, leftvertex, botvertex) < 0.0) {
8424       printf("Internal error in insertvertex():\n");
8425       printf(
8426             "  Clockwise triangle prior to edge vertex insertion (bottom).\n");
8427     }
8428     if (mirrorflag) {
8429       if (counterclockwise(m, b, leftvertex, rightvertex, topvertex) < 0.0) {
8430         printf("Internal error in insertvertex():\n");
8431         printf("  Clockwise triangle prior to edge vertex insertion (top).\n");
8432       }
8433       if (counterclockwise(m, b, rightvertex, topvertex, newvertex) < 0.0) {
8434         printf("Internal error in insertvertex():\n");
8435         printf(
8436             "  Clockwise triangle after edge vertex insertion (top right).\n");
8437       }
8438       if (counterclockwise(m, b, topvertex, leftvertex, newvertex) < 0.0) {
8439         printf("Internal error in insertvertex():\n");
8440         printf(
8441             "  Clockwise triangle after edge vertex insertion (top left).\n");
8442       }
8443     }
8444     if (counterclockwise(m, b, leftvertex, botvertex, newvertex) < 0.0) {
8445       printf("Internal error in insertvertex():\n");
8446       printf(
8447           "  Clockwise triangle after edge vertex insertion (bottom left).\n");
8448     }
8449     if (counterclockwise(m, b, botvertex, rightvertex, newvertex) < 0.0) {
8450       printf("Internal error in insertvertex():\n");
8451       printf(
8452         "  Clockwise triangle after edge vertex insertion (bottom right).\n");
8453     }
8454 #endif /* SELF_CHECK */
8455     if (b->verbose > 2) {
8456       printf("  Updating bottom left ");
8457       printtriangle(m, b, &botright);
8458       if (mirrorflag) {
8459         printf("  Updating top left ");
8460         printtriangle(m, b, &topright);
8461         printf("  Creating top right ");
8462         printtriangle(m, b, &newtopright);
8463       }
8464       printf("  Creating bottom right ");
8465       printtriangle(m, b, &newbotright);
8466     }
8467 
8468     /* Position `horiz' on the first edge to check for */
8469     /*   the Delaunay property.                        */
8470     lnextself(horiz);
8471   } else {
8472     /* Insert the vertex in a triangle, splitting it into three. */
8473     lnext(horiz, botleft);
8474     lprev(horiz, botright);
8475     sym(botleft, botlcasing);
8476     sym(botright, botrcasing);
8477     maketriangle(m, b, &newbotleft);
8478     maketriangle(m, b, &newbotright);
8479 
8480     /* Set the vertices of changed and new triangles. */
8481     org(horiz, rightvertex);
8482     dest(horiz, leftvertex);
8483     apex(horiz, botvertex);
8484     setorg(newbotleft, leftvertex);
8485     setdest(newbotleft, botvertex);
8486     setapex(newbotleft, newvertex);
8487     setorg(newbotright, botvertex);
8488     setdest(newbotright, rightvertex);
8489     setapex(newbotright, newvertex);
8490     setapex(horiz, newvertex);
8491     for (i = 0; i < m->eextras; i++) {
8492       /* Set the element attributes of the new triangles. */
8493       attrib = elemattribute(horiz, i);
8494       setelemattribute(newbotleft, i, attrib);
8495       setelemattribute(newbotright, i, attrib);
8496     }
8497     if (b->vararea) {
8498       /* Set the area constraint of the new triangles. */
8499       area = areabound(horiz);
8500       setareabound(newbotleft, area);
8501       setareabound(newbotright, area);
8502     }
8503 
8504     /* There may be subsegments that need to be bonded */
8505     /*   to the new triangles.                         */
8506     if (m->checksegments) {
8507       tspivot(botleft, botlsubseg);
8508       if (botlsubseg.ss != m->dummysub) {
8509         tsdissolve(botleft);
8510         tsbond(newbotleft, botlsubseg);
8511       }
8512       tspivot(botright, botrsubseg);
8513       if (botrsubseg.ss != m->dummysub) {
8514         tsdissolve(botright);
8515         tsbond(newbotright, botrsubseg);
8516       }
8517     }
8518 
8519     /* Bond the new triangles to the surrounding triangles. */
8520     bond(newbotleft, botlcasing);
8521     bond(newbotright, botrcasing);
8522     lnextself(newbotleft);
8523     lprevself(newbotright);
8524     bond(newbotleft, newbotright);
8525     lnextself(newbotleft);
8526     bond(botleft, newbotleft);
8527     lprevself(newbotright);
8528     bond(botright, newbotright);
8529 
8530     if (m->checkquality) {
8531       poolrestart(&m->flipstackers);
8532       m->lastflip = (struct flipstacker *) poolalloc(&m->flipstackers);
8533       m->lastflip->flippedtri = encode(horiz);
8534       m->lastflip->prevflip = (struct flipstacker *) NULL;
8535     }
8536 
8537 #ifdef SELF_CHECK
8538     if (counterclockwise(m, b, rightvertex, leftvertex, botvertex) < 0.0) {
8539       printf("Internal error in insertvertex():\n");
8540       printf("  Clockwise triangle prior to vertex insertion.\n");
8541     }
8542     if (counterclockwise(m, b, rightvertex, leftvertex, newvertex) < 0.0) {
8543       printf("Internal error in insertvertex():\n");
8544       printf("  Clockwise triangle after vertex insertion (top).\n");
8545     }
8546     if (counterclockwise(m, b, leftvertex, botvertex, newvertex) < 0.0) {
8547       printf("Internal error in insertvertex():\n");
8548       printf("  Clockwise triangle after vertex insertion (left).\n");
8549     }
8550     if (counterclockwise(m, b, botvertex, rightvertex, newvertex) < 0.0) {
8551       printf("Internal error in insertvertex():\n");
8552       printf("  Clockwise triangle after vertex insertion (right).\n");
8553     }
8554 #endif /* SELF_CHECK */
8555     if (b->verbose > 2) {
8556       printf("  Updating top ");
8557       printtriangle(m, b, &horiz);
8558       printf("  Creating left ");
8559       printtriangle(m, b, &newbotleft);
8560       printf("  Creating right ");
8561       printtriangle(m, b, &newbotright);
8562     }
8563   }
8564 
8565   /* The insertion is successful by default, unless an encroached */
8566   /*   subsegment is found.                                       */
8567   success = SUCCESSFULVERTEX;
8568   /* Circle around the newly inserted vertex, checking each edge opposite */
8569   /*   it for the Delaunay property.  Non-Delaunay edges are flipped.     */
8570   /*   `horiz' is always the edge being checked.  `first' marks where to  */
8571   /*   stop circling.                                                     */
8572   org(horiz, first);
8573   rightvertex = first;
8574   dest(horiz, leftvertex);
8575   /* Circle until finished. */
8576   while (1) {
8577     /* By default, the edge will be flipped. */
8578     doflip = 1;
8579 
8580     if (m->checksegments) {
8581       /* Check for a subsegment, which cannot be flipped. */
8582       tspivot(horiz, checksubseg);
8583       if (checksubseg.ss != m->dummysub) {
8584         /* The edge is a subsegment and cannot be flipped. */
8585         doflip = 0;
8586 #ifndef CDT_ONLY
8587         if (segmentflaws) {
8588           /* Does the new vertex encroach upon this subsegment? */
8589           if (checkseg4encroach(m, b, &checksubseg)) {
8590             success = ENCROACHINGVERTEX;
8591           }
8592         }
8593 #endif /* not CDT_ONLY */
8594       }
8595     }
8596 
8597     if (doflip) {
8598       /* Check if the edge is a boundary edge. */
8599       sym(horiz, top);
8600       if (top.tri == m->dummytri) {
8601         /* The edge is a boundary edge and cannot be flipped. */
8602         doflip = 0;
8603       } else {
8604         /* Find the vertex on the other side of the edge. */
8605         apex(top, farvertex);
8606         /* In the incremental Delaunay triangulation algorithm, any of      */
8607         /*   `leftvertex', `rightvertex', and `farvertex' could be vertices */
8608         /*   of the triangular bounding box.  These vertices must be        */
8609         /*   treated as if they are infinitely distant, even though their   */
8610         /*   "coordinates" are not.                                         */
8611         if ((leftvertex == m->infvertex1) || (leftvertex == m->infvertex2) ||
8612             (leftvertex == m->infvertex3)) {
8613           /* `leftvertex' is infinitely distant.  Check the convexity of  */
8614           /*   the boundary of the triangulation.  'farvertex' might be   */
8615           /*   infinite as well, but trust me, this same condition should */
8616           /*   be applied.                                                */
8617           doflip = counterclockwise(m, b, newvertex, rightvertex, farvertex)
8618                    > 0.0;
8619         } else if ((rightvertex == m->infvertex1) ||
8620                    (rightvertex == m->infvertex2) ||
8621                    (rightvertex == m->infvertex3)) {
8622           /* `rightvertex' is infinitely distant.  Check the convexity of */
8623           /*   the boundary of the triangulation.  'farvertex' might be   */
8624           /*   infinite as well, but trust me, this same condition should */
8625           /*   be applied.                                                */
8626           doflip = counterclockwise(m, b, farvertex, leftvertex, newvertex)
8627                    > 0.0;
8628         } else if ((farvertex == m->infvertex1) ||
8629                    (farvertex == m->infvertex2) ||
8630                    (farvertex == m->infvertex3)) {
8631           /* `farvertex' is infinitely distant and cannot be inside */
8632           /*   the circumcircle of the triangle `horiz'.            */
8633           doflip = 0;
8634         } else {
8635           /* Test whether the edge is locally Delaunay. */
8636           doflip = incircle(m, b, leftvertex, newvertex, rightvertex,
8637                             farvertex) > 0.0;
8638         }
8639         if (doflip) {
8640           /* We made it!  Flip the edge `horiz' by rotating its containing */
8641           /*   quadrilateral (the two triangles adjacent to `horiz').      */
8642           /* Identify the casing of the quadrilateral. */
8643           lprev(top, topleft);
8644           sym(topleft, toplcasing);
8645           lnext(top, topright);
8646           sym(topright, toprcasing);
8647           lnext(horiz, botleft);
8648           sym(botleft, botlcasing);
8649           lprev(horiz, botright);
8650           sym(botright, botrcasing);
8651           /* Rotate the quadrilateral one-quarter turn counterclockwise. */
8652           bond(topleft, botlcasing);
8653           bond(botleft, botrcasing);
8654           bond(botright, toprcasing);
8655           bond(topright, toplcasing);
8656           if (m->checksegments) {
8657             /* Check for subsegments and rebond them to the quadrilateral. */
8658             tspivot(topleft, toplsubseg);
8659             tspivot(botleft, botlsubseg);
8660             tspivot(botright, botrsubseg);
8661             tspivot(topright, toprsubseg);
8662             if (toplsubseg.ss == m->dummysub) {
8663               tsdissolve(topright);
8664             } else {
8665               tsbond(topright, toplsubseg);
8666             }
8667             if (botlsubseg.ss == m->dummysub) {
8668               tsdissolve(topleft);
8669             } else {
8670               tsbond(topleft, botlsubseg);
8671             }
8672             if (botrsubseg.ss == m->dummysub) {
8673               tsdissolve(botleft);
8674             } else {
8675               tsbond(botleft, botrsubseg);
8676             }
8677             if (toprsubseg.ss == m->dummysub) {
8678               tsdissolve(botright);
8679             } else {
8680               tsbond(botright, toprsubseg);
8681             }
8682           }
8683           /* New vertex assignments for the rotated quadrilateral. */
8684           setorg(horiz, farvertex);
8685           setdest(horiz, newvertex);
8686           setapex(horiz, rightvertex);
8687           setorg(top, newvertex);
8688           setdest(top, farvertex);
8689           setapex(top, leftvertex);
8690           for (i = 0; i < m->eextras; i++) {
8691             /* Take the average of the two triangles' attributes. */
8692             attrib = 0.5 * (elemattribute(top, i) + elemattribute(horiz, i));
8693             setelemattribute(top, i, attrib);
8694             setelemattribute(horiz, i, attrib);
8695           }
8696           if (b->vararea) {
8697             if ((areabound(top) <= 0.0) || (areabound(horiz) <= 0.0)) {
8698               area = -1.0;
8699             } else {
8700               /* Take the average of the two triangles' area constraints.    */
8701               /*   This prevents small area constraints from migrating a     */
8702               /*   long, long way from their original location due to flips. */
8703               area = 0.5 * (areabound(top) + areabound(horiz));
8704             }
8705             setareabound(top, area);
8706             setareabound(horiz, area);
8707           }
8708 
8709           if (m->checkquality) {
8710             newflip = (struct flipstacker *) poolalloc(&m->flipstackers);
8711             newflip->flippedtri = encode(horiz);
8712             newflip->prevflip = m->lastflip;
8713             m->lastflip = newflip;
8714           }
8715 
8716 #ifdef SELF_CHECK
8717           if (newvertex != (vertex) NULL) {
8718             if (counterclockwise(m, b, leftvertex, newvertex, rightvertex) <
8719                 0.0) {
8720               printf("Internal error in insertvertex():\n");
8721               printf("  Clockwise triangle prior to edge flip (bottom).\n");
8722             }
8723             /* The following test has been removed because constrainededge() */
8724             /*   sometimes generates inverted triangles that insertvertex()  */
8725             /*   removes.                                                    */
8726 /*
8727             if (counterclockwise(m, b, rightvertex, farvertex, leftvertex) <
8728                 0.0) {
8729               printf("Internal error in insertvertex():\n");
8730               printf("  Clockwise triangle prior to edge flip (top).\n");
8731             }
8732 */
8733             if (counterclockwise(m, b, farvertex, leftvertex, newvertex) <
8734                 0.0) {
8735               printf("Internal error in insertvertex():\n");
8736               printf("  Clockwise triangle after edge flip (left).\n");
8737             }
8738             if (counterclockwise(m, b, newvertex, rightvertex, farvertex) <
8739                 0.0) {
8740               printf("Internal error in insertvertex():\n");
8741               printf("  Clockwise triangle after edge flip (right).\n");
8742             }
8743           }
8744 #endif /* SELF_CHECK */
8745           if (b->verbose > 2) {
8746             printf("  Edge flip results in left ");
8747             lnextself(topleft);
8748             printtriangle(m, b, &topleft);
8749             printf("  and right ");
8750             printtriangle(m, b, &horiz);
8751           }
8752           /* On the next iterations, consider the two edges that were  */
8753           /*   exposed (this is, are now visible to the newly inserted */
8754           /*   vertex) by the edge flip.                               */
8755           lprevself(horiz);
8756           leftvertex = farvertex;
8757         }
8758       }
8759     }
8760     if (!doflip) {
8761       /* The handle `horiz' is accepted as locally Delaunay. */
8762 #ifndef CDT_ONLY
8763       if (triflaws) {
8764         /* Check the triangle `horiz' for quality. */
8765         testtriangle(m, b, &horiz);
8766       }
8767 #endif /* not CDT_ONLY */
8768       /* Look for the next edge around the newly inserted vertex. */
8769       lnextself(horiz);
8770       sym(horiz, testtri);
8771       /* Check for finishing a complete revolution about the new vertex, or */
8772       /*   falling outside  of the triangulation.  The latter will happen   */
8773       /*   when a vertex is inserted at a boundary.                         */
8774       if ((leftvertex == first) || (testtri.tri == m->dummytri)) {
8775         /* We're done.  Return a triangle whose origin is the new vertex. */
8776         lnext(horiz, *searchtri);
8777         lnext(horiz, m->recenttri);
8778         return success;
8779       }
8780       /* Finish finding the next edge around the newly inserted vertex. */
8781       lnext(testtri, horiz);
8782       rightvertex = leftvertex;
8783       dest(horiz, leftvertex);
8784     }
8785   }
8786 }
8787 
8788 /*****************************************************************************/
8789 /*                                                                           */
8790 /*  triangulatepolygon()   Find the Delaunay triangulation of a polygon that */
8791 /*                         has a certain "nice" shape.  This includes the    */
8792 /*                         polygons that result from deletion of a vertex or */
8793 /*                         insertion of a segment.                           */
8794 /*                                                                           */
8795 /*  This is a conceptually difficult routine.  The starting assumption is    */
8796 /*  that we have a polygon with n sides.  n - 1 of these sides are currently */
8797 /*  represented as edges in the mesh.  One side, called the "base", need not */
8798 /*  be.                                                                      */
8799 /*                                                                           */
8800 /*  Inside the polygon is a structure I call a "fan", consisting of n - 1    */
8801 /*  triangles that share a common origin.  For each of these triangles, the  */
8802 /*  edge opposite the origin is one of the sides of the polygon.  The        */
8803 /*  primary edge of each triangle is the edge directed from the origin to    */
8804 /*  the destination; note that this is not the same edge that is a side of   */
8805 /*  the polygon.  `firstedge' is the primary edge of the first triangle.     */
8806 /*  From there, the triangles follow in counterclockwise order about the     */
8807 /*  polygon, until `lastedge', the primary edge of the last triangle.        */
8808 /*  `firstedge' and `lastedge' are probably connected to other triangles     */
8809 /*  beyond the extremes of the fan, but their identity is not important, as  */
8810 /*  long as the fan remains connected to them.                               */
8811 /*                                                                           */
8812 /*  Imagine the polygon oriented so that its base is at the bottom.  This    */
8813 /*  puts `firstedge' on the far right, and `lastedge' on the far left.       */
8814 /*  The right vertex of the base is the destination of `firstedge', and the  */
8815 /*  left vertex of the base is the apex of `lastedge'.                       */
8816 /*                                                                           */
8817 /*  The challenge now is to find the right sequence of edge flips to         */
8818 /*  transform the fan into a Delaunay triangulation of the polygon.  Each    */
8819 /*  edge flip effectively removes one triangle from the fan, committing it   */
8820 /*  to the polygon.  The resulting polygon has one fewer edge.  If `doflip'  */
8821 /*  is set, the final flip will be performed, resulting in a fan of one      */
8822 /*  (useless?) triangle.  If `doflip' is not set, the final flip is not      */
8823 /*  performed, resulting in a fan of two triangles, and an unfinished        */
8824 /*  triangular polygon that is not yet filled out with a single triangle.    */
8825 /*  On completion of the routine, `lastedge' is the last remaining triangle, */
8826 /*  or the leftmost of the last two.                                         */
8827 /*                                                                           */
8828 /*  Although the flips are performed in the order described above, the       */
8829 /*  decisions about what flips to perform are made in precisely the reverse  */
8830 /*  order.  The recursive triangulatepolygon() procedure makes a decision,   */
8831 /*  uses up to two recursive calls to triangulate the "subproblems"          */
8832 /*  (polygons with fewer edges), and then performs an edge flip.             */
8833 /*                                                                           */
8834 /*  The "decision" it makes is which vertex of the polygon should be         */
8835 /*  connected to the base.  This decision is made by testing every possible  */
8836 /*  vertex.  Once the best vertex is found, the two edges that connect this  */
8837 /*  vertex to the base become the bases for two smaller polygons.  These     */
8838 /*  are triangulated recursively.  Unfortunately, this approach can take     */
8839 /*  O(n^2) time not only in the worst case, but in many common cases.  It's  */
8840 /*  rarely a big deal for vertex deletion, where n is rarely larger than     */
8841 /*  ten, but it could be a big deal for segment insertion, especially if     */
8842 /*  there's a lot of long segments that each cut many triangles.  I ought to */
8843 /*  code a faster algorithm some day.                                        */
8844 /*                                                                           */
8845 /*  The `edgecount' parameter is the number of sides of the polygon,         */
8846 /*  including its base.  `triflaws' is a flag that determines whether the    */
8847 /*  new triangles should be tested for quality, and enqueued if they are     */
8848 /*  bad.                                                                     */
8849 /*                                                                           */
8850 /*****************************************************************************/
8851 
8852 #ifdef ANSI_DECLARATORS
8853 void triangulatepolygon(struct mesh *m, struct behavior *b,
8854                         struct otri *firstedge, struct otri *lastedge,
8855                         int edgecount, int doflip, int triflaws)
8856 #else /* not ANSI_DECLARATORS */
8857 void triangulatepolygon(m, b, firstedge, lastedge, edgecount, doflip, triflaws)
8858 struct mesh *m;
8859 struct behavior *b;
8860 struct otri *firstedge;
8861 struct otri *lastedge;
8862 int edgecount;
8863 int doflip;
8864 int triflaws;
8865 #endif /* not ANSI_DECLARATORS */
8866 
8867 {
8868   struct otri testtri;
8869   struct otri besttri;
8870   struct otri tempedge;
8871   vertex leftbasevertex, rightbasevertex;
8872   vertex testvertex;
8873   vertex bestvertex;
8874   int bestnumber;
8875   int i;
8876   triangle ptr;   /* Temporary variable used by sym(), onext(), and oprev(). */
8877 
8878   /* Identify the base vertices. */
8879   apex(*lastedge, leftbasevertex);
8880   dest(*firstedge, rightbasevertex);
8881   if (b->verbose > 2) {
8882     printf("  Triangulating interior polygon at edge\n");
8883     printf("    (%.12g, %.12g) (%.12g, %.12g)\n", leftbasevertex[0],
8884            leftbasevertex[1], rightbasevertex[0], rightbasevertex[1]);
8885   }
8886   /* Find the best vertex to connect the base to. */
8887   onext(*firstedge, besttri);
8888   dest(besttri, bestvertex);
8889   otricopy(besttri, testtri);
8890   bestnumber = 1;
8891   for (i = 2; i <= edgecount - 2; i++) {
8892     onextself(testtri);
8893     dest(testtri, testvertex);
8894     /* Is this a better vertex? */
8895     if (incircle(m, b, leftbasevertex, rightbasevertex, bestvertex,
8896                  testvertex) > 0.0) {
8897       otricopy(testtri, besttri);
8898       bestvertex = testvertex;
8899       bestnumber = i;
8900     }
8901   }
8902   if (b->verbose > 2) {
8903     printf("    Connecting edge to (%.12g, %.12g)\n", bestvertex[0],
8904            bestvertex[1]);
8905   }
8906   if (bestnumber > 1) {
8907     /* Recursively triangulate the smaller polygon on the right. */
8908     oprev(besttri, tempedge);
8909     triangulatepolygon(m, b, firstedge, &tempedge, bestnumber + 1, 1,
8910                        triflaws);
8911   }
8912   if (bestnumber < edgecount - 2) {
8913     /* Recursively triangulate the smaller polygon on the left. */
8914     sym(besttri, tempedge);
8915     triangulatepolygon(m, b, &besttri, lastedge, edgecount - bestnumber, 1,
8916                        triflaws);
8917     /* Find `besttri' again; it may have been lost to edge flips. */
8918     sym(tempedge, besttri);
8919   }
8920   if (doflip) {
8921     /* Do one final edge flip. */
8922     flip(m, b, &besttri);
8923 #ifndef CDT_ONLY
8924     if (triflaws) {
8925       /* Check the quality of the newly committed triangle. */
8926       sym(besttri, testtri);
8927       testtriangle(m, b, &testtri);
8928     }
8929 #endif /* not CDT_ONLY */
8930   }
8931   /* Return the base triangle. */
8932   otricopy(besttri, *lastedge);
8933 }
8934 
8935 /*****************************************************************************/
8936 /*                                                                           */
8937 /*  deletevertex()   Delete a vertex from a Delaunay triangulation, ensuring */
8938 /*                   that the triangulation remains Delaunay.                */
8939 /*                                                                           */
8940 /*  The origin of `deltri' is deleted.  The union of the triangles adjacent  */
8941 /*  to this vertex is a polygon, for which the Delaunay triangulation is     */
8942 /*  found.  Two triangles are removed from the mesh.                         */
8943 /*                                                                           */
8944 /*  Only interior vertices that do not lie on segments or boundaries may be  */
8945 /*  deleted.                                                                 */
8946 /*                                                                           */
8947 /*****************************************************************************/
8948 
8949 #ifndef CDT_ONLY
8950 
8951 #ifdef ANSI_DECLARATORS
8952 void deletevertex(struct mesh *m, struct behavior *b, struct otri *deltri)
8953 #else /* not ANSI_DECLARATORS */
8954 void deletevertex(m, b, deltri)
8955 struct mesh *m;
8956 struct behavior *b;
8957 struct otri *deltri;
8958 #endif /* not ANSI_DECLARATORS */
8959 
8960 {
8961   struct otri countingtri;
8962   struct otri firstedge, lastedge;
8963   struct otri deltriright;
8964   struct otri lefttri, righttri;
8965   struct otri leftcasing, rightcasing;
8966   struct osub leftsubseg, rightsubseg;
8967   vertex delvertex;
8968   vertex neworg;
8969   int edgecount;
8970   triangle ptr;   /* Temporary variable used by sym(), onext(), and oprev(). */
8971   subseg sptr;                      /* Temporary variable used by tspivot(). */
8972 
8973   org(*deltri, delvertex);
8974   if (b->verbose > 1) {
8975     printf("  Deleting (%.12g, %.12g).\n", delvertex[0], delvertex[1]);
8976   }
8977   vertexdealloc(m, delvertex);
8978 
8979   /* Count the degree of the vertex being deleted. */
8980   onext(*deltri, countingtri);
8981   edgecount = 1;
8982   while (!otriequal(*deltri, countingtri)) {
8983 #ifdef SELF_CHECK
8984     if (countingtri.tri == m->dummytri) {
8985       printf("Internal error in deletevertex():\n");
8986       printf("  Attempt to delete boundary vertex.\n");
8987       internalerror();
8988     }
8989 #endif /* SELF_CHECK */
8990     edgecount++;
8991     onextself(countingtri);
8992   }
8993 
8994 #ifdef SELF_CHECK
8995   if (edgecount < 3) {
8996     printf("Internal error in deletevertex():\n  Vertex has degree %d.\n",
8997            edgecount);
8998     internalerror();
8999   }
9000 #endif /* SELF_CHECK */
9001   if (edgecount > 3) {
9002     /* Triangulate the polygon defined by the union of all triangles */
9003     /*   adjacent to the vertex being deleted.  Check the quality of */
9004     /*   the resulting triangles.                                    */
9005     onext(*deltri, firstedge);
9006     oprev(*deltri, lastedge);
9007     triangulatepolygon(m, b, &firstedge, &lastedge, edgecount, 0,
9008                        !b->nobisect);
9009   }
9010   /* Splice out two triangles. */
9011   lprev(*deltri, deltriright);
9012   dnext(*deltri, lefttri);
9013   sym(lefttri, leftcasing);
9014   oprev(deltriright, righttri);
9015   sym(righttri, rightcasing);
9016   bond(*deltri, leftcasing);
9017   bond(deltriright, rightcasing);
9018   tspivot(lefttri, leftsubseg);
9019   if (leftsubseg.ss != m->dummysub) {
9020     tsbond(*deltri, leftsubseg);
9021   }
9022   tspivot(righttri, rightsubseg);
9023   if (rightsubseg.ss != m->dummysub) {
9024     tsbond(deltriright, rightsubseg);
9025   }
9026 
9027   /* Set the new origin of `deltri' and check its quality. */
9028   org(lefttri, neworg);
9029   setorg(*deltri, neworg);
9030   if (!b->nobisect) {
9031     testtriangle(m, b, deltri);
9032   }
9033 
9034   /* Delete the two spliced-out triangles. */
9035   triangledealloc(m, lefttri.tri);
9036   triangledealloc(m, righttri.tri);
9037 }
9038 
9039 #endif /* not CDT_ONLY */
9040 
9041 /*****************************************************************************/
9042 /*                                                                           */
9043 /*  undovertex()   Undo the most recent vertex insertion.                    */
9044 /*                                                                           */
9045 /*  Walks through the list of transformations (flips and a vertex insertion) */
9046 /*  in the reverse of the order in which they were done, and undoes them.    */
9047 /*  The inserted vertex is removed from the triangulation and deallocated.   */
9048 /*  Two triangles (possibly just one) are also deallocated.                  */
9049 /*                                                                           */
9050 /*****************************************************************************/
9051 
9052 #ifndef CDT_ONLY
9053 
9054 #ifdef ANSI_DECLARATORS
9055 void undovertex(struct mesh *m, struct behavior *b)
9056 #else /* not ANSI_DECLARATORS */
9057 void undovertex(m, b)
9058 struct mesh *m;
9059 struct behavior *b;
9060 #endif /* not ANSI_DECLARATORS */
9061 
9062 {
9063   struct otri fliptri;
9064   struct otri botleft, botright, topright;
9065   struct otri botlcasing, botrcasing, toprcasing;
9066   struct otri gluetri;
9067   struct osub botlsubseg, botrsubseg, toprsubseg;
9068   vertex botvertex, rightvertex;
9069   triangle ptr;                         /* Temporary variable used by sym(). */
9070   subseg sptr;                      /* Temporary variable used by tspivot(). */
9071 
9072   /* Walk through the list of transformations (flips and a vertex insertion) */
9073   /*   in the reverse of the order in which they were done, and undo them.   */
9074   while (m->lastflip != (struct flipstacker *) NULL) {
9075     /* Find a triangle involved in the last unreversed transformation. */
9076     decode(m->lastflip->flippedtri, fliptri);
9077 
9078     /* We are reversing one of three transformations:  a trisection of one */
9079     /*   triangle into three (by inserting a vertex in the triangle), a    */
9080     /*   bisection of two triangles into four (by inserting a vertex in an */
9081     /*   edge), or an edge flip.                                           */
9082     if (m->lastflip->prevflip == (struct flipstacker *) NULL) {
9083       /* Restore a triangle that was split into three triangles, */
9084       /*   so it is again one triangle.                          */
9085       dprev(fliptri, botleft);
9086       lnextself(botleft);
9087       onext(fliptri, botright);
9088       lprevself(botright);
9089       sym(botleft, botlcasing);
9090       sym(botright, botrcasing);
9091       dest(botleft, botvertex);
9092 
9093       setapex(fliptri, botvertex);
9094       lnextself(fliptri);
9095       bond(fliptri, botlcasing);
9096       tspivot(botleft, botlsubseg);
9097       tsbond(fliptri, botlsubseg);
9098       lnextself(fliptri);
9099       bond(fliptri, botrcasing);
9100       tspivot(botright, botrsubseg);
9101       tsbond(fliptri, botrsubseg);
9102 
9103       /* Delete the two spliced-out triangles. */
9104       triangledealloc(m, botleft.tri);
9105       triangledealloc(m, botright.tri);
9106     } else if (m->lastflip->prevflip == (struct flipstacker *) &insertvertex) {
9107       /* Restore two triangles that were split into four triangles, */
9108       /*   so they are again two triangles.                         */
9109       lprev(fliptri, gluetri);
9110       sym(gluetri, botright);
9111       lnextself(botright);
9112       sym(botright, botrcasing);
9113       dest(botright, rightvertex);
9114 
9115       setorg(fliptri, rightvertex);
9116       bond(gluetri, botrcasing);
9117       tspivot(botright, botrsubseg);
9118       tsbond(gluetri, botrsubseg);
9119 
9120       /* Delete the spliced-out triangle. */
9121       triangledealloc(m, botright.tri);
9122 
9123       sym(fliptri, gluetri);
9124       if (gluetri.tri != m->dummytri) {
9125         lnextself(gluetri);
9126         dnext(gluetri, topright);
9127         sym(topright, toprcasing);
9128 
9129         setorg(gluetri, rightvertex);
9130         bond(gluetri, toprcasing);
9131         tspivot(topright, toprsubseg);
9132         tsbond(gluetri, toprsubseg);
9133 
9134         /* Delete the spliced-out triangle. */
9135         triangledealloc(m, topright.tri);
9136       }
9137 
9138       /* This is the end of the list, sneakily encoded. */
9139       m->lastflip->prevflip = (struct flipstacker *) NULL;
9140     } else {
9141       /* Undo an edge flip. */
9142       unflip(m, b, &fliptri);
9143     }
9144 
9145     /* Go on and process the next transformation. */
9146     m->lastflip = m->lastflip->prevflip;
9147   }
9148 }
9149 
9150 #endif /* not CDT_ONLY */
9151 
9152 /**                                                                         **/
9153 /**                                                                         **/
9154 /********* Mesh transformation routines end here                     *********/
9155 
9156 /********* Divide-and-conquer Delaunay triangulation begins here     *********/
9157 /**                                                                         **/
9158 /**                                                                         **/
9159 
9160 /*****************************************************************************/
9161 /*                                                                           */
9162 /*  The divide-and-conquer bounding box                                      */
9163 /*                                                                           */
9164 /*  I originally implemented the divide-and-conquer and incremental Delaunay */
9165 /*  triangulations using the edge-based data structure presented by Guibas   */
9166 /*  and Stolfi.  Switching to a triangle-based data structure doubled the    */
9167 /*  speed.  However, I had to think of a few extra tricks to maintain the    */
9168 /*  elegance of the original algorithms.                                     */
9169 /*                                                                           */
9170 /*  The "bounding box" used by my variant of the divide-and-conquer          */
9171 /*  algorithm uses one triangle for each edge of the convex hull of the      */
9172 /*  triangulation.  These bounding triangles all share a common apical       */
9173 /*  vertex, which is represented by NULL and which represents nothing.       */
9174 /*  The bounding triangles are linked in a circular fan about this NULL      */
9175 /*  vertex, and the edges on the convex hull of the triangulation appear     */
9176 /*  opposite the NULL vertex.  You might find it easiest to imagine that     */
9177 /*  the NULL vertex is a point in 3D space behind the center of the          */
9178 /*  triangulation, and that the bounding triangles form a sort of cone.      */
9179 /*                                                                           */
9180 /*  This bounding box makes it easy to represent degenerate cases.  For      */
9181 /*  instance, the triangulation of two vertices is a single edge.  This edge */
9182 /*  is represented by two bounding box triangles, one on each "side" of the  */
9183 /*  edge.  These triangles are also linked together in a fan about the NULL  */
9184 /*  vertex.                                                                  */
9185 /*                                                                           */
9186 /*  The bounding box also makes it easy to traverse the convex hull, as the  */
9187 /*  divide-and-conquer algorithm needs to do.                                */
9188 /*                                                                           */
9189 /*****************************************************************************/
9190 
9191 /*****************************************************************************/
9192 /*                                                                           */
9193 /*  vertexsort()   Sort an array of vertices by x-coordinate, using the      */
9194 /*                 y-coordinate as a secondary key.                          */
9195 /*                                                                           */
9196 /*  Uses quicksort.  Randomized O(n log n) time.  No, I did not make any of  */
9197 /*  the usual quicksort mistakes.                                            */
9198 /*                                                                           */
9199 /*****************************************************************************/
9200 
9201 #ifdef ANSI_DECLARATORS
9202 void vertexsort(vertex *sortarray, int arraysize)
9203 #else /* not ANSI_DECLARATORS */
9204 void vertexsort(sortarray, arraysize)
9205 vertex *sortarray;
9206 int arraysize;
9207 #endif /* not ANSI_DECLARATORS */
9208 
9209 {
9210   int left, right;
9211   int pivot;
9212   REAL pivotx, pivoty;
9213   vertex temp;
9214 
9215   if (arraysize == 2) {
9216     /* Recursive base case. */
9217     if ((sortarray[0][0] > sortarray[1][0]) ||
9218         ((sortarray[0][0] == sortarray[1][0]) &&
9219          (sortarray[0][1] > sortarray[1][1]))) {
9220       temp = sortarray[1];
9221       sortarray[1] = sortarray[0];
9222       sortarray[0] = temp;
9223     }
9224     return;
9225   }
9226   /* Choose a random pivot to split the array. */
9227   pivot = (int) randomnation((unsigned int) arraysize);
9228   pivotx = sortarray[pivot][0];
9229   pivoty = sortarray[pivot][1];
9230   /* Split the array. */
9231   left = -1;
9232   right = arraysize;
9233   while (left < right) {
9234     /* Search for a vertex whose x-coordinate is too large for the left. */
9235     do {
9236       left++;
9237     } while ((left <= right) && ((sortarray[left][0] < pivotx) ||
9238                                  ((sortarray[left][0] == pivotx) &&
9239                                   (sortarray[left][1] < pivoty))));
9240     /* Search for a vertex whose x-coordinate is too small for the right. */
9241     do {
9242       right--;
9243     } while ((left <= right) && ((sortarray[right][0] > pivotx) ||
9244                                  ((sortarray[right][0] == pivotx) &&
9245                                   (sortarray[right][1] > pivoty))));
9246     if (left < right) {
9247       /* Swap the left and right vertices. */
9248       temp = sortarray[left];
9249       sortarray[left] = sortarray[right];
9250       sortarray[right] = temp;
9251     }
9252   }
9253   if (left > 1) {
9254     /* Recursively sort the left subset. */
9255     vertexsort(sortarray, left);
9256   }
9257   if (right < arraysize - 2) {
9258     /* Recursively sort the right subset. */
9259     vertexsort(&sortarray[right + 1], arraysize - right - 1);
9260   }
9261 }
9262 
9263 /*****************************************************************************/
9264 /*                                                                           */
9265 /*  vertexmedian()   An order statistic algorithm, almost.  Shuffles an      */
9266 /*                   array of vertices so that the first `median' vertices   */
9267 /*                   occur lexicographically before the remaining vertices.  */
9268 /*                                                                           */
9269 /*  Uses the x-coordinate as the primary key if axis == 0; the y-coordinate  */
9270 /*  if axis == 1.  Very similar to the vertexsort() procedure, but runs in   */
9271 /*  randomized linear time.                                                  */
9272 /*                                                                           */
9273 /*****************************************************************************/
9274 
9275 #ifdef ANSI_DECLARATORS
9276 void vertexmedian(vertex *sortarray, int arraysize, int median, int axis)
9277 #else /* not ANSI_DECLARATORS */
9278 void vertexmedian(sortarray, arraysize, median, axis)
9279 vertex *sortarray;
9280 int arraysize;
9281 int median;
9282 int axis;
9283 #endif /* not ANSI_DECLARATORS */
9284 
9285 {
9286   int left, right;
9287   int pivot;
9288   REAL pivot1, pivot2;
9289   vertex temp;
9290 
9291   if (arraysize == 2) {
9292     /* Recursive base case. */
9293     if ((sortarray[0][axis] > sortarray[1][axis]) ||
9294         ((sortarray[0][axis] == sortarray[1][axis]) &&
9295          (sortarray[0][1 - axis] > sortarray[1][1 - axis]))) {
9296       temp = sortarray[1];
9297       sortarray[1] = sortarray[0];
9298       sortarray[0] = temp;
9299     }
9300     return;
9301   }
9302   /* Choose a random pivot to split the array. */
9303   pivot = (int) randomnation((unsigned int) arraysize);
9304   pivot1 = sortarray[pivot][axis];
9305   pivot2 = sortarray[pivot][1 - axis];
9306   /* Split the array. */
9307   left = -1;
9308   right = arraysize;
9309   while (left < right) {
9310     /* Search for a vertex whose x-coordinate is too large for the left. */
9311     do {
9312       left++;
9313     } while ((left <= right) && ((sortarray[left][axis] < pivot1) ||
9314                                  ((sortarray[left][axis] == pivot1) &&
9315                                   (sortarray[left][1 - axis] < pivot2))));
9316     /* Search for a vertex whose x-coordinate is too small for the right. */
9317     do {
9318       right--;
9319     } while ((left <= right) && ((sortarray[right][axis] > pivot1) ||
9320                                  ((sortarray[right][axis] == pivot1) &&
9321                                   (sortarray[right][1 - axis] > pivot2))));
9322     if (left < right) {
9323       /* Swap the left and right vertices. */
9324       temp = sortarray[left];
9325       sortarray[left] = sortarray[right];
9326       sortarray[right] = temp;
9327     }
9328   }
9329   /* Unlike in vertexsort(), at most one of the following */
9330   /*   conditionals is true.                             */
9331   if (left > median) {
9332     /* Recursively shuffle the left subset. */
9333     vertexmedian(sortarray, left, median, axis);
9334   }
9335   if (right < median - 1) {
9336     /* Recursively shuffle the right subset. */
9337     vertexmedian(&sortarray[right + 1], arraysize - right - 1,
9338                  median - right - 1, axis);
9339   }
9340 }
9341 
9342 /*****************************************************************************/
9343 /*                                                                           */
9344 /*  alternateaxes()   Sorts the vertices as appropriate for the divide-and-  */
9345 /*                    conquer algorithm with alternating cuts.               */
9346 /*                                                                           */
9347 /*  Partitions by x-coordinate if axis == 0; by y-coordinate if axis == 1.   */
9348 /*  For the base case, subsets containing only two or three vertices are     */
9349 /*  always sorted by x-coordinate.                                           */
9350 /*                                                                           */
9351 /*****************************************************************************/
9352 
9353 #ifdef ANSI_DECLARATORS
9354 void alternateaxes(vertex *sortarray, int arraysize, int axis)
9355 #else /* not ANSI_DECLARATORS */
9356 void alternateaxes(sortarray, arraysize, axis)
9357 vertex *sortarray;
9358 int arraysize;
9359 int axis;
9360 #endif /* not ANSI_DECLARATORS */
9361 
9362 {
9363   int divider;
9364 
9365   divider = arraysize >> 1;
9366   if (arraysize <= 3) {
9367     /* Recursive base case:  subsets of two or three vertices will be    */
9368     /*   handled specially, and should always be sorted by x-coordinate. */
9369     axis = 0;
9370   }
9371   /* Partition with a horizontal or vertical cut. */
9372   vertexmedian(sortarray, arraysize, divider, axis);
9373   /* Recursively partition the subsets with a cross cut. */
9374   if (arraysize - divider >= 2) {
9375     if (divider >= 2) {
9376       alternateaxes(sortarray, divider, 1 - axis);
9377     }
9378     alternateaxes(&sortarray[divider], arraysize - divider, 1 - axis);
9379   }
9380 }
9381 
9382 /*****************************************************************************/
9383 /*                                                                           */
9384 /*  mergehulls()   Merge two adjacent Delaunay triangulations into a         */
9385 /*                 single Delaunay triangulation.                            */
9386 /*                                                                           */
9387 /*  This is similar to the algorithm given by Guibas and Stolfi, but uses    */
9388 /*  a triangle-based, rather than edge-based, data structure.                */
9389 /*                                                                           */
9390 /*  The algorithm walks up the gap between the two triangulations, knitting  */
9391 /*  them together.  As they are merged, some of their bounding triangles     */
9392 /*  are converted into real triangles of the triangulation.  The procedure   */
9393 /*  pulls each hull's bounding triangles apart, then knits them together     */
9394 /*  like the teeth of two gears.  The Delaunay property determines, at each  */
9395 /*  step, whether the next "tooth" is a bounding triangle of the left hull   */
9396 /*  or the right.  When a bounding triangle becomes real, its apex is        */
9397 /*  changed from NULL to a real vertex.                                      */
9398 /*                                                                           */
9399 /*  Only two new triangles need to be allocated.  These become new bounding  */
9400 /*  triangles at the top and bottom of the seam.  They are used to connect   */
9401 /*  the remaining bounding triangles (those that have not been converted     */
9402 /*  into real triangles) into a single fan.                                  */
9403 /*                                                                           */
9404 /*  On entry, `farleft' and `innerleft' are bounding triangles of the left   */
9405 /*  triangulation.  The origin of `farleft' is the leftmost vertex, and      */
9406 /*  the destination of `innerleft' is the rightmost vertex of the            */
9407 /*  triangulation.  Similarly, `innerright' and `farright' are bounding      */
9408 /*  triangles of the right triangulation.  The origin of `innerright' and    */
9409 /*  destination of `farright' are the leftmost and rightmost vertices.       */
9410 /*                                                                           */
9411 /*  On completion, the origin of `farleft' is the leftmost vertex of the     */
9412 /*  merged triangulation, and the destination of `farright' is the rightmost */
9413 /*  vertex.                                                                  */
9414 /*                                                                           */
9415 /*****************************************************************************/
9416 
9417 #ifdef ANSI_DECLARATORS
9418 void mergehulls(struct mesh *m, struct behavior *b, struct otri *farleft,
9419                 struct otri *innerleft, struct otri *innerright,
9420                 struct otri *farright, int axis)
9421 #else /* not ANSI_DECLARATORS */
9422 void mergehulls(m, b, farleft, innerleft, innerright, farright, axis)
9423 struct mesh *m;
9424 struct behavior *b;
9425 struct otri *farleft;
9426 struct otri *innerleft;
9427 struct otri *innerright;
9428 struct otri *farright;
9429 int axis;
9430 #endif /* not ANSI_DECLARATORS */
9431 
9432 {
9433   struct otri leftcand, rightcand;
9434   struct otri baseedge;
9435   struct otri nextedge;
9436   struct otri sidecasing, topcasing, outercasing;
9437   struct otri checkedge;
9438   vertex innerleftdest;
9439   vertex innerrightorg;
9440   vertex innerleftapex, innerrightapex;
9441   vertex farleftpt, farrightpt;
9442   vertex farleftapex, farrightapex;
9443   vertex lowerleft, lowerright;
9444   vertex upperleft, upperright;
9445   vertex nextapex;
9446   vertex checkvertex;
9447   int changemade;
9448   int badedge;
9449   int leftfinished, rightfinished;
9450   triangle ptr;                         /* Temporary variable used by sym(). */
9451 
9452   dest(*innerleft, innerleftdest);
9453   apex(*innerleft, innerleftapex);
9454   org(*innerright, innerrightorg);
9455   apex(*innerright, innerrightapex);
9456   /* Special treatment for horizontal cuts. */
9457   if (b->dwyer && (axis == 1)) {
9458     org(*farleft, farleftpt);
9459     apex(*farleft, farleftapex);
9460     dest(*farright, farrightpt);
9461     apex(*farright, farrightapex);
9462     /* The pointers to the extremal vertices are shifted to point to the */
9463     /*   topmost and bottommost vertex of each hull, rather than the     */
9464     /*   leftmost and rightmost vertices.                                */
9465     while (farleftapex[1] < farleftpt[1]) {
9466       lnextself(*farleft);
9467       symself(*farleft);
9468       farleftpt = farleftapex;
9469       apex(*farleft, farleftapex);
9470     }
9471     sym(*innerleft, checkedge);
9472     apex(checkedge, checkvertex);
9473     while (checkvertex[1] > innerleftdest[1]) {
9474       lnext(checkedge, *innerleft);
9475       innerleftapex = innerleftdest;
9476       innerleftdest = checkvertex;
9477       sym(*innerleft, checkedge);
9478       apex(checkedge, checkvertex);
9479     }
9480     while (innerrightapex[1] < innerrightorg[1]) {
9481       lnextself(*innerright);
9482       symself(*innerright);
9483       innerrightorg = innerrightapex;
9484       apex(*innerright, innerrightapex);
9485     }
9486     sym(*farright, checkedge);
9487     apex(checkedge, checkvertex);
9488     while (checkvertex[1] > farrightpt[1]) {
9489       lnext(checkedge, *farright);
9490       farrightapex = farrightpt;
9491       farrightpt = checkvertex;
9492       sym(*farright, checkedge);
9493       apex(checkedge, checkvertex);
9494     }
9495   }
9496   /* Find a line tangent to and below both hulls. */
9497   do {
9498     changemade = 0;
9499     /* Make innerleftdest the "bottommost" vertex of the left hull. */
9500     if (counterclockwise(m, b, innerleftdest, innerleftapex, innerrightorg) >
9501         0.0) {
9502       lprevself(*innerleft);
9503       symself(*innerleft);
9504       innerleftdest = innerleftapex;
9505       apex(*innerleft, innerleftapex);
9506       changemade = 1;
9507     }
9508     /* Make innerrightorg the "bottommost" vertex of the right hull. */
9509     if (counterclockwise(m, b, innerrightapex, innerrightorg, innerleftdest) >
9510         0.0) {
9511       lnextself(*innerright);
9512       symself(*innerright);
9513       innerrightorg = innerrightapex;
9514       apex(*innerright, innerrightapex);
9515       changemade = 1;
9516     }
9517   } while (changemade);
9518   /* Find the two candidates to be the next "gear tooth." */
9519   sym(*innerleft, leftcand);
9520   sym(*innerright, rightcand);
9521   /* Create the bottom new bounding triangle. */
9522   maketriangle(m, b, &baseedge);
9523   /* Connect it to the bounding boxes of the left and right triangulations. */
9524   bond(baseedge, *innerleft);
9525   lnextself(baseedge);
9526   bond(baseedge, *innerright);
9527   lnextself(baseedge);
9528   setorg(baseedge, innerrightorg);
9529   setdest(baseedge, innerleftdest);
9530   /* Apex is intentionally left NULL. */
9531   if (b->verbose > 2) {
9532     printf("  Creating base bounding ");
9533     printtriangle(m, b, &baseedge);
9534   }
9535   /* Fix the extreme triangles if necessary. */
9536   org(*farleft, farleftpt);
9537   if (innerleftdest == farleftpt) {
9538     lnext(baseedge, *farleft);
9539   }
9540   dest(*farright, farrightpt);
9541   if (innerrightorg == farrightpt) {
9542     lprev(baseedge, *farright);
9543   }
9544   /* The vertices of the current knitting edge. */
9545   lowerleft = innerleftdest;
9546   lowerright = innerrightorg;
9547   /* The candidate vertices for knitting. */
9548   apex(leftcand, upperleft);
9549   apex(rightcand, upperright);
9550   /* Walk up the gap between the two triangulations, knitting them together. */
9551   while (1) {
9552     /* Have we reached the top?  (This isn't quite the right question,       */
9553     /*   because even though the left triangulation might seem finished now, */
9554     /*   moving up on the right triangulation might reveal a new vertex of   */
9555     /*   the left triangulation.  And vice-versa.)                           */
9556     leftfinished = counterclockwise(m, b, upperleft, lowerleft, lowerright) <=
9557                    0.0;
9558     rightfinished = counterclockwise(m, b, upperright, lowerleft, lowerright)
9559                  <= 0.0;
9560     if (leftfinished && rightfinished) {
9561       /* Create the top new bounding triangle. */
9562       maketriangle(m, b, &nextedge);
9563       setorg(nextedge, lowerleft);
9564       setdest(nextedge, lowerright);
9565       /* Apex is intentionally left NULL. */
9566       /* Connect it to the bounding boxes of the two triangulations. */
9567       bond(nextedge, baseedge);
9568       lnextself(nextedge);
9569       bond(nextedge, rightcand);
9570       lnextself(nextedge);
9571       bond(nextedge, leftcand);
9572       if (b->verbose > 2) {
9573         printf("  Creating top bounding ");
9574         printtriangle(m, b, &nextedge);
9575       }
9576       /* Special treatment for horizontal cuts. */
9577       if (b->dwyer && (axis == 1)) {
9578         org(*farleft, farleftpt);
9579         apex(*farleft, farleftapex);
9580         dest(*farright, farrightpt);
9581         apex(*farright, farrightapex);
9582         sym(*farleft, checkedge);
9583         apex(checkedge, checkvertex);
9584         /* The pointers to the extremal vertices are restored to the  */
9585         /*   leftmost and rightmost vertices (rather than topmost and */
9586         /*   bottommost).                                             */
9587         while (checkvertex[0] < farleftpt[0]) {
9588           lprev(checkedge, *farleft);
9589           farleftapex = farleftpt;
9590           farleftpt = checkvertex;
9591           sym(*farleft, checkedge);
9592           apex(checkedge, checkvertex);
9593         }
9594         while (farrightapex[0] > farrightpt[0]) {
9595           lprevself(*farright);
9596           symself(*farright);
9597           farrightpt = farrightapex;
9598           apex(*farright, farrightapex);
9599         }
9600       }
9601       return;
9602     }
9603     /* Consider eliminating edges from the left triangulation. */
9604     if (!leftfinished) {
9605       /* What vertex would be exposed if an edge were deleted? */
9606       lprev(leftcand, nextedge);
9607       symself(nextedge);
9608       apex(nextedge, nextapex);
9609       /* If nextapex is NULL, then no vertex would be exposed; the */
9610       /*   triangulation would have been eaten right through.      */
9611       if (nextapex != (vertex) NULL) {
9612         /* Check whether the edge is Delaunay. */
9613         badedge = incircle(m, b, lowerleft, lowerright, upperleft, nextapex) >
9614                   0.0;
9615         while (badedge) {
9616           /* Eliminate the edge with an edge flip.  As a result, the    */
9617           /*   left triangulation will have one more boundary triangle. */
9618           lnextself(nextedge);
9619           sym(nextedge, topcasing);
9620           lnextself(nextedge);
9621           sym(nextedge, sidecasing);
9622           bond(nextedge, topcasing);
9623           bond(leftcand, sidecasing);
9624           lnextself(leftcand);
9625           sym(leftcand, outercasing);
9626           lprevself(nextedge);
9627           bond(nextedge, outercasing);
9628           /* Correct the vertices to reflect the edge flip. */
9629           setorg(leftcand, lowerleft);
9630           setdest(leftcand, NULL);
9631           setapex(leftcand, nextapex);
9632           setorg(nextedge, NULL);
9633           setdest(nextedge, upperleft);
9634           setapex(nextedge, nextapex);
9635           /* Consider the newly exposed vertex. */
9636           upperleft = nextapex;
9637           /* What vertex would be exposed if another edge were deleted? */
9638           otricopy(sidecasing, nextedge);
9639           apex(nextedge, nextapex);
9640           if (nextapex != (vertex) NULL) {
9641             /* Check whether the edge is Delaunay. */
9642             badedge = incircle(m, b, lowerleft, lowerright, upperleft,
9643                                nextapex) > 0.0;
9644           } else {
9645             /* Avoid eating right through the triangulation. */
9646             badedge = 0;
9647           }
9648         }
9649       }
9650     }
9651     /* Consider eliminating edges from the right triangulation. */
9652     if (!rightfinished) {
9653       /* What vertex would be exposed if an edge were deleted? */
9654       lnext(rightcand, nextedge);
9655       symself(nextedge);
9656       apex(nextedge, nextapex);
9657       /* If nextapex is NULL, then no vertex would be exposed; the */
9658       /*   triangulation would have been eaten right through.      */
9659       if (nextapex != (vertex) NULL) {
9660         /* Check whether the edge is Delaunay. */
9661         badedge = incircle(m, b, lowerleft, lowerright, upperright, nextapex) >
9662                   0.0;
9663         while (badedge) {
9664           /* Eliminate the edge with an edge flip.  As a result, the     */
9665           /*   right triangulation will have one more boundary triangle. */
9666           lprevself(nextedge);
9667           sym(nextedge, topcasing);
9668           lprevself(nextedge);
9669           sym(nextedge, sidecasing);
9670           bond(nextedge, topcasing);
9671           bond(rightcand, sidecasing);
9672           lprevself(rightcand);
9673           sym(rightcand, outercasing);
9674           lnextself(nextedge);
9675           bond(nextedge, outercasing);
9676           /* Correct the vertices to reflect the edge flip. */
9677           setorg(rightcand, NULL);
9678           setdest(rightcand, lowerright);
9679           setapex(rightcand, nextapex);
9680           setorg(nextedge, upperright);
9681           setdest(nextedge, NULL);
9682           setapex(nextedge, nextapex);
9683           /* Consider the newly exposed vertex. */
9684           upperright = nextapex;
9685           /* What vertex would be exposed if another edge were deleted? */
9686           otricopy(sidecasing, nextedge);
9687           apex(nextedge, nextapex);
9688           if (nextapex != (vertex) NULL) {
9689             /* Check whether the edge is Delaunay. */
9690             badedge = incircle(m, b, lowerleft, lowerright, upperright,
9691                                nextapex) > 0.0;
9692           } else {
9693             /* Avoid eating right through the triangulation. */
9694             badedge = 0;
9695           }
9696         }
9697       }
9698     }
9699     if (leftfinished || (!rightfinished &&
9700            (incircle(m, b, upperleft, lowerleft, lowerright, upperright) >
9701             0.0))) {
9702       /* Knit the triangulations, adding an edge from `lowerleft' */
9703       /*   to `upperright'.                                       */
9704       bond(baseedge, rightcand);
9705       lprev(rightcand, baseedge);
9706       setdest(baseedge, lowerleft);
9707       lowerright = upperright;
9708       sym(baseedge, rightcand);
9709       apex(rightcand, upperright);
9710     } else {
9711       /* Knit the triangulations, adding an edge from `upperleft' */
9712       /*   to `lowerright'.                                       */
9713       bond(baseedge, leftcand);
9714       lnext(leftcand, baseedge);
9715       setorg(baseedge, lowerright);
9716       lowerleft = upperleft;
9717       sym(baseedge, leftcand);
9718       apex(leftcand, upperleft);
9719     }
9720     if (b->verbose > 2) {
9721       printf("  Connecting ");
9722       printtriangle(m, b, &baseedge);
9723     }
9724   }
9725 }
9726 
9727 /*****************************************************************************/
9728 /*                                                                           */
9729 /*  divconqrecurse()   Recursively form a Delaunay triangulation by the      */
9730 /*                     divide-and-conquer method.                            */
9731 /*                                                                           */
9732 /*  Recursively breaks down the problem into smaller pieces, which are       */
9733 /*  knitted together by mergehulls().  The base cases (problems of two or    */
9734 /*  three vertices) are handled specially here.                              */
9735 /*                                                                           */
9736 /*  On completion, `farleft' and `farright' are bounding triangles such that */
9737 /*  the origin of `farleft' is the leftmost vertex (breaking ties by         */
9738 /*  choosing the highest leftmost vertex), and the destination of            */
9739 /*  `farright' is the rightmost vertex (breaking ties by choosing the        */
9740 /*  lowest rightmost vertex).                                                */
9741 /*                                                                           */
9742 /*****************************************************************************/
9743 
9744 #ifdef ANSI_DECLARATORS
9745 void divconqrecurse(struct mesh *m, struct behavior *b, vertex *sortarray,
9746                     int vertices, int axis,
9747                     struct otri *farleft, struct otri *farright)
9748 #else /* not ANSI_DECLARATORS */
9749 void divconqrecurse(m, b, sortarray, vertices, axis, farleft, farright)
9750 struct mesh *m;
9751 struct behavior *b;
9752 vertex *sortarray;
9753 int vertices;
9754 int axis;
9755 struct otri *farleft;
9756 struct otri *farright;
9757 #endif /* not ANSI_DECLARATORS */
9758 
9759 {
9760   struct otri midtri, tri1, tri2, tri3;
9761   struct otri innerleft, innerright;
9762   REAL area;
9763   int divider;
9764 
9765   if (b->verbose > 2) {
9766     printf("  Triangulating %d vertices.\n", vertices);
9767   }
9768   if (vertices == 2) {
9769     /* The triangulation of two vertices is an edge.  An edge is */
9770     /*   represented by two bounding triangles.                  */
9771     maketriangle(m, b, farleft);
9772     setorg(*farleft, sortarray[0]);
9773     setdest(*farleft, sortarray[1]);
9774     /* The apex is intentionally left NULL. */
9775     maketriangle(m, b, farright);
9776     setorg(*farright, sortarray[1]);
9777     setdest(*farright, sortarray[0]);
9778     /* The apex is intentionally left NULL. */
9779     bond(*farleft, *farright);
9780     lprevself(*farleft);
9781     lnextself(*farright);
9782     bond(*farleft, *farright);
9783     lprevself(*farleft);
9784     lnextself(*farright);
9785     bond(*farleft, *farright);
9786     if (b->verbose > 2) {
9787       printf("  Creating ");
9788       printtriangle(m, b, farleft);
9789       printf("  Creating ");
9790       printtriangle(m, b, farright);
9791     }
9792     /* Ensure that the origin of `farleft' is sortarray[0]. */
9793     lprev(*farright, *farleft);
9794     return;
9795   } else if (vertices == 3) {
9796     /* The triangulation of three vertices is either a triangle (with */
9797     /*   three bounding triangles) or two edges (with four bounding   */
9798     /*   triangles).  In either case, four triangles are created.     */
9799     maketriangle(m, b, &midtri);
9800     maketriangle(m, b, &tri1);
9801     maketriangle(m, b, &tri2);
9802     maketriangle(m, b, &tri3);
9803     area = counterclockwise(m, b, sortarray[0], sortarray[1], sortarray[2]);
9804     if (area == 0.0) {
9805       /* Three collinear vertices; the triangulation is two edges. */
9806       setorg(midtri, sortarray[0]);
9807       setdest(midtri, sortarray[1]);
9808       setorg(tri1, sortarray[1]);
9809       setdest(tri1, sortarray[0]);
9810       setorg(tri2, sortarray[2]);
9811       setdest(tri2, sortarray[1]);
9812       setorg(tri3, sortarray[1]);
9813       setdest(tri3, sortarray[2]);
9814       /* All apices are intentionally left NULL. */
9815       bond(midtri, tri1);
9816       bond(tri2, tri3);
9817       lnextself(midtri);
9818       lprevself(tri1);
9819       lnextself(tri2);
9820       lprevself(tri3);
9821       bond(midtri, tri3);
9822       bond(tri1, tri2);
9823       lnextself(midtri);
9824       lprevself(tri1);
9825       lnextself(tri2);
9826       lprevself(tri3);
9827       bond(midtri, tri1);
9828       bond(tri2, tri3);
9829       /* Ensure that the origin of `farleft' is sortarray[0]. */
9830       otricopy(tri1, *farleft);
9831       /* Ensure that the destination of `farright' is sortarray[2]. */
9832       otricopy(tri2, *farright);
9833     } else {
9834       /* The three vertices are not collinear; the triangulation is one */
9835       /*   triangle, namely `midtri'.                                   */
9836       setorg(midtri, sortarray[0]);
9837       setdest(tri1, sortarray[0]);
9838       setorg(tri3, sortarray[0]);
9839       /* Apices of tri1, tri2, and tri3 are left NULL. */
9840       if (area > 0.0) {
9841         /* The vertices are in counterclockwise order. */
9842         setdest(midtri, sortarray[1]);
9843         setorg(tri1, sortarray[1]);
9844         setdest(tri2, sortarray[1]);
9845         setapex(midtri, sortarray[2]);
9846         setorg(tri2, sortarray[2]);
9847         setdest(tri3, sortarray[2]);
9848       } else {
9849         /* The vertices are in clockwise order. */
9850         setdest(midtri, sortarray[2]);
9851         setorg(tri1, sortarray[2]);
9852         setdest(tri2, sortarray[2]);
9853         setapex(midtri, sortarray[1]);
9854         setorg(tri2, sortarray[1]);
9855         setdest(tri3, sortarray[1]);
9856       }
9857       /* The topology does not depend on how the vertices are ordered. */
9858       bond(midtri, tri1);
9859       lnextself(midtri);
9860       bond(midtri, tri2);
9861       lnextself(midtri);
9862       bond(midtri, tri3);
9863       lprevself(tri1);
9864       lnextself(tri2);
9865       bond(tri1, tri2);
9866       lprevself(tri1);
9867       lprevself(tri3);
9868       bond(tri1, tri3);
9869       lnextself(tri2);
9870       lprevself(tri3);
9871       bond(tri2, tri3);
9872       /* Ensure that the origin of `farleft' is sortarray[0]. */
9873       otricopy(tri1, *farleft);
9874       /* Ensure that the destination of `farright' is sortarray[2]. */
9875       if (area > 0.0) {
9876         otricopy(tri2, *farright);
9877       } else {
9878         lnext(*farleft, *farright);
9879       }
9880     }
9881     if (b->verbose > 2) {
9882       printf("  Creating ");
9883       printtriangle(m, b, &midtri);
9884       printf("  Creating ");
9885       printtriangle(m, b, &tri1);
9886       printf("  Creating ");
9887       printtriangle(m, b, &tri2);
9888       printf("  Creating ");
9889       printtriangle(m, b, &tri3);
9890     }
9891     return;
9892   } else {
9893     /* Split the vertices in half. */
9894     divider = vertices >> 1;
9895     /* Recursively triangulate each half. */
9896     divconqrecurse(m, b, sortarray, divider, 1 - axis, farleft, &innerleft);
9897     divconqrecurse(m, b, &sortarray[divider], vertices - divider, 1 - axis,
9898                    &innerright, farright);
9899     if (b->verbose > 1) {
9900       printf("  Joining triangulations with %d and %d vertices.\n", divider,
9901              vertices - divider);
9902     }
9903     /* Merge the two triangulations into one. */
9904     mergehulls(m, b, farleft, &innerleft, &innerright, farright, axis);
9905   }
9906 }
9907 
9908 #ifdef ANSI_DECLARATORS
9909 long removeghosts(struct mesh *m, struct behavior *b, struct otri *startghost)
9910 #else /* not ANSI_DECLARATORS */
9911 long removeghosts(m, b, startghost)
9912 struct mesh *m;
9913 struct behavior *b;
9914 struct otri *startghost;
9915 #endif /* not ANSI_DECLARATORS */
9916 
9917 {
9918   struct otri searchedge;
9919   struct otri dissolveedge;
9920   struct otri deadtriangle;
9921   vertex markorg;
9922   long hullsize;
9923   triangle ptr;                         /* Temporary variable used by sym(). */
9924 
9925   if (b->verbose) {
9926     printf("  Removing ghost triangles.\n");
9927   }
9928   /* Find an edge on the convex hull to start point location from. */
9929   lprev(*startghost, searchedge);
9930   symself(searchedge);
9931   m->dummytri[0] = encode(searchedge);
9932   /* Remove the bounding box and count the convex hull edges. */
9933   otricopy(*startghost, dissolveedge);
9934   hullsize = 0;
9935   do {
9936     hullsize++;
9937     lnext(dissolveedge, deadtriangle);
9938     lprevself(dissolveedge);
9939     symself(dissolveedge);
9940     /* If no PSLG is involved, set the boundary markers of all the vertices */
9941     /*   on the convex hull.  If a PSLG is used, this step is done later.   */
9942     if (!b->poly) {
9943       /* Watch out for the case where all the input vertices are collinear. */
9944       if (dissolveedge.tri != m->dummytri) {
9945         org(dissolveedge, markorg);
9946         if (vertexmark(markorg) == 0) {
9947           setvertexmark(markorg, 1);
9948         }
9949       }
9950     }
9951     /* Remove a bounding triangle from a convex hull triangle. */
9952     dissolve(dissolveedge);
9953     /* Find the next bounding triangle. */
9954     sym(deadtriangle, dissolveedge);
9955     /* Delete the bounding triangle. */
9956     triangledealloc(m, deadtriangle.tri);
9957   } while (!otriequal(dissolveedge, *startghost));
9958   return hullsize;
9959 }
9960 
9961 /*****************************************************************************/
9962 /*                                                                           */
9963 /*  divconqdelaunay()   Form a Delaunay triangulation by the divide-and-     */
9964 /*                      conquer method.                                      */
9965 /*                                                                           */
9966 /*  Sorts the vertices, calls a recursive procedure to triangulate them, and */
9967 /*  removes the bounding box, setting boundary markers as appropriate.       */
9968 /*                                                                           */
9969 /*****************************************************************************/
9970 
9971 #ifdef ANSI_DECLARATORS
9972 long divconqdelaunay(struct mesh *m, struct behavior *b)
9973 #else /* not ANSI_DECLARATORS */
9974 long divconqdelaunay(m, b)
9975 struct mesh *m;
9976 struct behavior *b;
9977 #endif /* not ANSI_DECLARATORS */
9978 
9979 {
9980   vertex *sortarray;
9981   struct otri hullleft, hullright;
9982   int divider;
9983   int i, j;
9984 
9985   if (b->verbose) {
9986     printf("  Sorting vertices.\n");
9987   }
9988 
9989   /* Allocate an array of pointers to vertices for sorting. */
9990   sortarray = (vertex *) trimalloc(m->invertices * (int) sizeof(vertex));
9991   traversalinit(&m->vertices);
9992   for (i = 0; i < m->invertices; i++) {
9993     sortarray[i] = vertextraverse(m);
9994   }
9995   /* Sort the vertices. */
9996   vertexsort(sortarray, m->invertices);
9997   /* Discard duplicate vertices, which can really mess up the algorithm. */
9998   i = 0;
9999   for (j = 1; j < m->invertices; j++) {
10000     if ((sortarray[i][0] == sortarray[j][0])
10001         && (sortarray[i][1] == sortarray[j][1])) {
10002       if (!b->quiet) {
10003         printf(
10004 "Warning:  A duplicate vertex at (%.12g, %.12g) appeared and was ignored.\n",
10005                sortarray[j][0], sortarray[j][1]);
10006       }
10007       setvertextype(sortarray[j], UNDEADVERTEX);
10008       m->undeads++;
10009     } else {
10010       i++;
10011       sortarray[i] = sortarray[j];
10012     }
10013   }
10014   i++;
10015   if (b->dwyer) {
10016     /* Re-sort the array of vertices to accommodate alternating cuts. */
10017     divider = i >> 1;
10018     if (i - divider >= 2) {
10019       if (divider >= 2) {
10020         alternateaxes(sortarray, divider, 1);
10021       }
10022       alternateaxes(&sortarray[divider], i - divider, 1);
10023     }
10024   }
10025 
10026   if (b->verbose) {
10027     printf("  Forming triangulation.\n");
10028   }
10029 
10030   /* Form the Delaunay triangulation. */
10031   divconqrecurse(m, b, sortarray, i, 0, &hullleft, &hullright);
10032   trifree((VOID *) sortarray);
10033 
10034   return removeghosts(m, b, &hullleft);
10035 }
10036 
10037 /**                                                                         **/
10038 /**                                                                         **/
10039 /********* Divide-and-conquer Delaunay triangulation ends here       *********/
10040 
10041 /********* Incremental Delaunay triangulation begins here            *********/
10042 /**                                                                         **/
10043 /**                                                                         **/
10044 
10045 /*****************************************************************************/
10046 /*                                                                           */
10047 /*  boundingbox()   Form an "infinite" bounding triangle to insert vertices  */
10048 /*                  into.                                                    */
10049 /*                                                                           */
10050 /*  The vertices at "infinity" are assigned finite coordinates, which are    */
10051 /*  used by the point location routines, but (mostly) ignored by the         */
10052 /*  Delaunay edge flip routines.                                             */
10053 /*                                                                           */
10054 /*****************************************************************************/
10055 
10056 #ifndef REDUCED
10057 
10058 #ifdef ANSI_DECLARATORS
10059 void boundingbox(struct mesh *m, struct behavior *b)
10060 #else /* not ANSI_DECLARATORS */
10061 void boundingbox(m, b)
10062 struct mesh *m;
10063 struct behavior *b;
10064 #endif /* not ANSI_DECLARATORS */
10065 
10066 {
10067   struct otri inftri;          /* Handle for the triangular bounding box. */
10068   REAL width;
10069 
10070   if (b->verbose) {
10071     printf("  Creating triangular bounding box.\n");
10072   }
10073   /* Find the width (or height, whichever is larger) of the triangulation. */
10074   width = m->xmax - m->xmin;
10075   if (m->ymax - m->ymin > width) {
10076     width = m->ymax - m->ymin;
10077   }
10078   if (width == 0.0) {
10079     width = 1.0;
10080   }
10081   /* Create the vertices of the bounding box. */
10082   m->infvertex1 = (vertex) trimalloc(m->vertices.itembytes);
10083   m->infvertex2 = (vertex) trimalloc(m->vertices.itembytes);
10084   m->infvertex3 = (vertex) trimalloc(m->vertices.itembytes);
10085   m->infvertex1[0] = m->xmin - 50.0 * width;
10086   m->infvertex1[1] = m->ymin - 40.0 * width;
10087   m->infvertex2[0] = m->xmax + 50.0 * width;
10088   m->infvertex2[1] = m->ymin - 40.0 * width;
10089   m->infvertex3[0] = 0.5 * (m->xmin + m->xmax);
10090   m->infvertex3[1] = m->ymax + 60.0 * width;
10091 
10092   /* Create the bounding box. */
10093   maketriangle(m, b, &inftri);
10094   setorg(inftri, m->infvertex1);
10095   setdest(inftri, m->infvertex2);
10096   setapex(inftri, m->infvertex3);
10097   /* Link dummytri to the bounding box so we can always find an */
10098   /*   edge to begin searching (point location) from.           */
10099   m->dummytri[0] = (triangle) inftri.tri;
10100   if (b->verbose > 2) {
10101     printf("  Creating ");
10102     printtriangle(m, b, &inftri);
10103   }
10104 }
10105 
10106 #endif /* not REDUCED */
10107 
10108 /*****************************************************************************/
10109 /*                                                                           */
10110 /*  removebox()   Remove the "infinite" bounding triangle, setting boundary  */
10111 /*                markers as appropriate.                                    */
10112 /*                                                                           */
10113 /*  The triangular bounding box has three boundary triangles (one for each   */
10114 /*  side of the bounding box), and a bunch of triangles fanning out from     */
10115 /*  the three bounding box vertices (one triangle for each edge of the       */
10116 /*  convex hull of the inner mesh).  This routine removes these triangles.   */
10117 /*                                                                           */
10118 /*  Returns the number of edges on the convex hull of the triangulation.     */
10119 /*                                                                           */
10120 /*****************************************************************************/
10121 
10122 #ifndef REDUCED
10123 
10124 #ifdef ANSI_DECLARATORS
10125 long removebox(struct mesh *m, struct behavior *b)
10126 #else /* not ANSI_DECLARATORS */
10127 long removebox(m, b)
10128 struct mesh *m;
10129 struct behavior *b;
10130 #endif /* not ANSI_DECLARATORS */
10131 
10132 {
10133   struct otri deadtriangle;
10134   struct otri searchedge;
10135   struct otri checkedge;
10136   struct otri nextedge, finaledge, dissolveedge;
10137   vertex markorg;
10138   long hullsize;
10139   triangle ptr;                         /* Temporary variable used by sym(). */
10140 
10141   if (b->verbose) {
10142     printf("  Removing triangular bounding box.\n");
10143   }
10144   /* Find a boundary triangle. */
10145   nextedge.tri = m->dummytri;
10146   nextedge.orient = 0;
10147   symself(nextedge);
10148   /* Mark a place to stop. */
10149   lprev(nextedge, finaledge);
10150   lnextself(nextedge);
10151   symself(nextedge);
10152   /* Find a triangle (on the boundary of the vertex set) that isn't */
10153   /*   a bounding box triangle.                                     */
10154   lprev(nextedge, searchedge);
10155   symself(searchedge);
10156   /* Check whether nextedge is another boundary triangle */
10157   /*   adjacent to the first one.                        */
10158   lnext(nextedge, checkedge);
10159   symself(checkedge);
10160   if (checkedge.tri == m->dummytri) {
10161     /* Go on to the next triangle.  There are only three boundary   */
10162     /*   triangles, and this next triangle cannot be the third one, */
10163     /*   so it's safe to stop here.                                 */
10164     lprevself(searchedge);
10165     symself(searchedge);
10166   }
10167   /* Find a new boundary edge to search from, as the current search */
10168   /*   edge lies on a bounding box triangle and will be deleted.    */
10169   m->dummytri[0] = encode(searchedge);
10170   hullsize = -2l;
10171   while (!otriequal(nextedge, finaledge)) {
10172     hullsize++;
10173     lprev(nextedge, dissolveedge);
10174     symself(dissolveedge);
10175     /* If not using a PSLG, the vertices should be marked now. */
10176     /*   (If using a PSLG, markhull() will do the job.)        */
10177     if (!b->poly) {
10178       /* Be careful!  One must check for the case where all the input     */
10179       /*   vertices are collinear, and thus all the triangles are part of */
10180       /*   the bounding box.  Otherwise, the setvertexmark() call below   */
10181       /*   will cause a bad pointer reference.                            */
10182       if (dissolveedge.tri != m->dummytri) {
10183         org(dissolveedge, markorg);
10184         if (vertexmark(markorg) == 0) {
10185           setvertexmark(markorg, 1);
10186         }
10187       }
10188     }
10189     /* Disconnect the bounding box triangle from the mesh triangle. */
10190     dissolve(dissolveedge);
10191     lnext(nextedge, deadtriangle);
10192     sym(deadtriangle, nextedge);
10193     /* Get rid of the bounding box triangle. */
10194     triangledealloc(m, deadtriangle.tri);
10195     /* Do we need to turn the corner? */
10196     if (nextedge.tri == m->dummytri) {
10197       /* Turn the corner. */
10198       otricopy(dissolveedge, nextedge);
10199     }
10200   }
10201   triangledealloc(m, finaledge.tri);
10202 
10203   trifree((VOID *) m->infvertex1);  /* Deallocate the bounding box vertices. */
10204   trifree((VOID *) m->infvertex2);
10205   trifree((VOID *) m->infvertex3);
10206 
10207   return hullsize;
10208 }
10209 
10210 #endif /* not REDUCED */
10211 
10212 /*****************************************************************************/
10213 /*                                                                           */
10214 /*  incrementaldelaunay()   Form a Delaunay triangulation by incrementally   */
10215 /*                          inserting vertices.                              */
10216 /*                                                                           */
10217 /*  Returns the number of edges on the convex hull of the triangulation.     */
10218 /*                                                                           */
10219 /*****************************************************************************/
10220 
10221 #ifndef REDUCED
10222 
10223 #ifdef ANSI_DECLARATORS
10224 long incrementaldelaunay(struct mesh *m, struct behavior *b)
10225 #else /* not ANSI_DECLARATORS */
10226 long incrementaldelaunay(m, b)
10227 struct mesh *m;
10228 struct behavior *b;
10229 #endif /* not ANSI_DECLARATORS */
10230 
10231 {
10232   struct otri starttri;
10233   vertex vertexloop;
10234 
10235   /* Create a triangular bounding box. */
10236   boundingbox(m, b);
10237   if (b->verbose) {
10238     printf("  Incrementally inserting vertices.\n");
10239   }
10240   traversalinit(&m->vertices);
10241   vertexloop = vertextraverse(m);
10242   while (vertexloop != (vertex) NULL) {
10243     starttri.tri = m->dummytri;
10244     if (insertvertex(m, b, vertexloop, &starttri, (struct osub *) NULL, 0, 0)
10245         == DUPLICATEVERTEX) {
10246       if (!b->quiet) {
10247         printf(
10248 "Warning:  A duplicate vertex at (%.12g, %.12g) appeared and was ignored.\n",
10249                vertexloop[0], vertexloop[1]);
10250       }
10251       setvertextype(vertexloop, UNDEADVERTEX);
10252       m->undeads++;
10253     }
10254     vertexloop = vertextraverse(m);
10255   }
10256   /* Remove the bounding box. */
10257   return removebox(m, b);
10258 }
10259 
10260 #endif /* not REDUCED */
10261 
10262 /**                                                                         **/
10263 /**                                                                         **/
10264 /********* Incremental Delaunay triangulation ends here              *********/
10265 
10266 /********* Sweepline Delaunay triangulation begins here              *********/
10267 /**                                                                         **/
10268 /**                                                                         **/
10269 
10270 #ifndef REDUCED
10271 
10272 #ifdef ANSI_DECLARATORS
10273 void eventheapinsert(struct event **heap, int heapsize, struct event *newevent)
10274 #else /* not ANSI_DECLARATORS */
10275 void eventheapinsert(heap, heapsize, newevent)
10276 struct event **heap;
10277 int heapsize;
10278 struct event *newevent;
10279 #endif /* not ANSI_DECLARATORS */
10280 
10281 {
10282   REAL eventx, eventy;
10283   int eventnum;
10284   int parent;
10285   int notdone;
10286 
10287   eventx = newevent->xkey;
10288   eventy = newevent->ykey;
10289   eventnum = heapsize;
10290   notdone = eventnum > 0;
10291   while (notdone) {
10292     parent = (eventnum - 1) >> 1;
10293     if ((heap[parent]->ykey < eventy) ||
10294         ((heap[parent]->ykey == eventy)
10295          && (heap[parent]->xkey <= eventx))) {
10296       notdone = 0;
10297     } else {
10298       heap[eventnum] = heap[parent];
10299       heap[eventnum]->heapposition = eventnum;
10300 
10301       eventnum = parent;
10302       notdone = eventnum > 0;
10303     }
10304   }
10305   heap[eventnum] = newevent;
10306   newevent->heapposition = eventnum;
10307 }
10308 
10309 #endif /* not REDUCED */
10310 
10311 #ifndef REDUCED
10312 
10313 #ifdef ANSI_DECLARATORS
10314 void eventheapify(struct event **heap, int heapsize, int eventnum)
10315 #else /* not ANSI_DECLARATORS */
10316 void eventheapify(heap, heapsize, eventnum)
10317 struct event **heap;
10318 int heapsize;
10319 int eventnum;
10320 #endif /* not ANSI_DECLARATORS */
10321 
10322 {
10323   struct event *thisevent;
10324   REAL eventx, eventy;
10325   int leftchild, rightchild;
10326   int smallest;
10327   int notdone;
10328 
10329   thisevent = heap[eventnum];
10330   eventx = thisevent->xkey;
10331   eventy = thisevent->ykey;
10332   leftchild = 2 * eventnum + 1;
10333   notdone = leftchild < heapsize;
10334   while (notdone) {
10335     if ((heap[leftchild]->ykey < eventy) ||
10336         ((heap[leftchild]->ykey == eventy)
10337          && (heap[leftchild]->xkey < eventx))) {
10338       smallest = leftchild;
10339     } else {
10340       smallest = eventnum;
10341     }
10342     rightchild = leftchild + 1;
10343     if (rightchild < heapsize) {
10344       if ((heap[rightchild]->ykey < heap[smallest]->ykey) ||
10345           ((heap[rightchild]->ykey == heap[smallest]->ykey)
10346            && (heap[rightchild]->xkey < heap[smallest]->xkey))) {
10347         smallest = rightchild;
10348       }
10349     }
10350     if (smallest == eventnum) {
10351       notdone = 0;
10352     } else {
10353       heap[eventnum] = heap[smallest];
10354       heap[eventnum]->heapposition = eventnum;
10355       heap[smallest] = thisevent;
10356       thisevent->heapposition = smallest;
10357 
10358       eventnum = smallest;
10359       leftchild = 2 * eventnum + 1;
10360       notdone = leftchild < heapsize;
10361     }
10362   }
10363 }
10364 
10365 #endif /* not REDUCED */
10366 
10367 #ifndef REDUCED
10368 
10369 #ifdef ANSI_DECLARATORS
10370 void eventheapdelete(struct event **heap, int heapsize, int eventnum)
10371 #else /* not ANSI_DECLARATORS */
10372 void eventheapdelete(heap, heapsize, eventnum)
10373 struct event **heap;
10374 int heapsize;
10375 int eventnum;
10376 #endif /* not ANSI_DECLARATORS */
10377 
10378 {
10379   struct event *moveevent;
10380   REAL eventx, eventy;
10381   int parent;
10382   int notdone;
10383 
10384   moveevent = heap[heapsize - 1];
10385   if (eventnum > 0) {
10386     eventx = moveevent->xkey;
10387     eventy = moveevent->ykey;
10388     do {
10389       parent = (eventnum - 1) >> 1;
10390       if ((heap[parent]->ykey < eventy) ||
10391           ((heap[parent]->ykey == eventy)
10392            && (heap[parent]->xkey <= eventx))) {
10393         notdone = 0;
10394       } else {
10395         heap[eventnum] = heap[parent];
10396         heap[eventnum]->heapposition = eventnum;
10397 
10398         eventnum = parent;
10399         notdone = eventnum > 0;
10400       }
10401     } while (notdone);
10402   }
10403   heap[eventnum] = moveevent;
10404   moveevent->heapposition = eventnum;
10405   eventheapify(heap, heapsize - 1, eventnum);
10406 }
10407 
10408 #endif /* not REDUCED */
10409 
10410 #ifndef REDUCED
10411 
10412 #ifdef ANSI_DECLARATORS
10413 void createeventheap(struct mesh *m, struct event ***eventheap,
10414                      struct event **events, struct event **freeevents)
10415 #else /* not ANSI_DECLARATORS */
10416 void createeventheap(m, eventheap, events, freeevents)
10417 struct mesh *m;
10418 struct event ***eventheap;
10419 struct event **events;
10420 struct event **freeevents;
10421 #endif /* not ANSI_DECLARATORS */
10422 
10423 {
10424   vertex thisvertex;
10425   int maxevents;
10426   int i;
10427 
10428   maxevents = (3 * m->invertices) / 2;
10429   *eventheap = (struct event **) trimalloc(maxevents *
10430                                            (int) sizeof(struct event *));
10431   *events = (struct event *) trimalloc(maxevents * (int) sizeof(struct event));
10432   traversalinit(&m->vertices);
10433   for (i = 0; i < m->invertices; i++) {
10434     thisvertex = vertextraverse(m);
10435     (*events)[i].eventptr = (VOID *) thisvertex;
10436     (*events)[i].xkey = thisvertex[0];
10437     (*events)[i].ykey = thisvertex[1];
10438     eventheapinsert(*eventheap, i, *events + i);
10439   }
10440   *freeevents = (struct event *) NULL;
10441   for (i = maxevents - 1; i >= m->invertices; i--) {
10442     (*events)[i].eventptr = (VOID *) *freeevents;
10443     *freeevents = *events + i;
10444   }
10445 }
10446 
10447 #endif /* not REDUCED */
10448 
10449 #ifndef REDUCED
10450 
10451 #ifdef ANSI_DECLARATORS
10452 int rightofhyperbola(struct mesh *m, struct otri *fronttri, vertex newsite)
10453 #else /* not ANSI_DECLARATORS */
10454 int rightofhyperbola(m, fronttri, newsite)
10455 struct mesh *m;
10456 struct otri *fronttri;
10457 vertex newsite;
10458 #endif /* not ANSI_DECLARATORS */
10459 
10460 {
10461   vertex leftvertex, rightvertex;
10462   REAL dxa, dya, dxb, dyb;
10463 
10464   m->hyperbolacount++;
10465 
10466   dest(*fronttri, leftvertex);
10467   apex(*fronttri, rightvertex);
10468   if ((leftvertex[1] < rightvertex[1]) ||
10469       ((leftvertex[1] == rightvertex[1]) &&
10470        (leftvertex[0] < rightvertex[0]))) {
10471     if (newsite[0] >= rightvertex[0]) {
10472       return 1;
10473     }
10474   } else {
10475     if (newsite[0] <= leftvertex[0]) {
10476       return 0;
10477     }
10478   }
10479   dxa = leftvertex[0] - newsite[0];
10480   dya = leftvertex[1] - newsite[1];
10481   dxb = rightvertex[0] - newsite[0];
10482   dyb = rightvertex[1] - newsite[1];
10483   return dya * (dxb * dxb + dyb * dyb) > dyb * (dxa * dxa + dya * dya);
10484 }
10485 
10486 #endif /* not REDUCED */
10487 
10488 #ifndef REDUCED
10489 
10490 #ifdef ANSI_DECLARATORS
10491 REAL circletop(struct mesh *m, vertex pa, vertex pb, vertex pc, REAL ccwabc)
10492 #else /* not ANSI_DECLARATORS */
10493 REAL circletop(m, pa, pb, pc, ccwabc)
10494 struct mesh *m;
10495 vertex pa;
10496 vertex pb;
10497 vertex pc;
10498 REAL ccwabc;
10499 #endif /* not ANSI_DECLARATORS */
10500 
10501 {
10502   REAL xac, yac, xbc, ybc, xab, yab;
10503   REAL aclen2, bclen2, ablen2;
10504 
10505   m->circletopcount++;
10506 
10507   xac = pa[0] - pc[0];
10508   yac = pa[1] - pc[1];
10509   xbc = pb[0] - pc[0];
10510   ybc = pb[1] - pc[1];
10511   xab = pa[0] - pb[0];
10512   yab = pa[1] - pb[1];
10513   aclen2 = xac * xac + yac * yac;
10514   bclen2 = xbc * xbc + ybc * ybc;
10515   ablen2 = xab * xab + yab * yab;
10516   return pc[1] + (xac * bclen2 - xbc * aclen2 + sqrt(aclen2 * bclen2 * ablen2))
10517                / (2.0 * ccwabc);
10518 }
10519 
10520 #endif /* not REDUCED */
10521 
10522 #ifndef REDUCED
10523 
10524 #ifdef ANSI_DECLARATORS
10525 void check4deadevent(struct otri *checktri, struct event **freeevents,
10526                      struct event **eventheap, int *heapsize)
10527 #else /* not ANSI_DECLARATORS */
10528 void check4deadevent(checktri, freeevents, eventheap, heapsize)
10529 struct otri *checktri;
10530 struct event **freeevents;
10531 struct event **eventheap;
10532 int *heapsize;
10533 #endif /* not ANSI_DECLARATORS */
10534 
10535 {
10536   struct event *deadevent;
10537   vertex eventvertex;
10538   int eventnum;
10539 
10540   org(*checktri, eventvertex);
10541   if (eventvertex != (vertex) NULL) {
10542     deadevent = (struct event *) eventvertex;
10543     eventnum = deadevent->heapposition;
10544     deadevent->eventptr = (VOID *) *freeevents;
10545     *freeevents = deadevent;
10546     eventheapdelete(eventheap, *heapsize, eventnum);
10547     (*heapsize)--;
10548     setorg(*checktri, NULL);
10549   }
10550 }
10551 
10552 #endif /* not REDUCED */
10553 
10554 #ifndef REDUCED
10555 
10556 #ifdef ANSI_DECLARATORS
10557 struct splaynode *splay(struct mesh *m, struct splaynode *splaytree,
10558                         vertex searchpoint, struct otri *searchtri)
10559 #else /* not ANSI_DECLARATORS */
10560 struct splaynode *splay(m, splaytree, searchpoint, searchtri)
10561 struct mesh *m;
10562 struct splaynode *splaytree;
10563 vertex searchpoint;
10564 struct otri *searchtri;
10565 #endif /* not ANSI_DECLARATORS */
10566 
10567 {
10568   struct splaynode *child, *grandchild;
10569   struct splaynode *lefttree, *righttree;
10570   struct splaynode *leftright;
10571   vertex checkvertex;
10572   int rightofroot, rightofchild;
10573 
10574   if (splaytree == (struct splaynode *) NULL) {
10575     return (struct splaynode *) NULL;
10576   }
10577   dest(splaytree->keyedge, checkvertex);
10578   if (checkvertex == splaytree->keydest) {
10579     rightofroot = rightofhyperbola(m, &splaytree->keyedge, searchpoint);
10580     if (rightofroot) {
10581       otricopy(splaytree->keyedge, *searchtri);
10582       child = splaytree->rchild;
10583     } else {
10584       child = splaytree->lchild;
10585     }
10586     if (child == (struct splaynode *) NULL) {
10587       return splaytree;
10588     }
10589     dest(child->keyedge, checkvertex);
10590     if (checkvertex != child->keydest) {
10591       child = splay(m, child, searchpoint, searchtri);
10592       if (child == (struct splaynode *) NULL) {
10593         if (rightofroot) {
10594           splaytree->rchild = (struct splaynode *) NULL;
10595         } else {
10596           splaytree->lchild = (struct splaynode *) NULL;
10597         }
10598         return splaytree;
10599       }
10600     }
10601     rightofchild = rightofhyperbola(m, &child->keyedge, searchpoint);
10602     if (rightofchild) {
10603       otricopy(child->keyedge, *searchtri);
10604       grandchild = splay(m, child->rchild, searchpoint, searchtri);
10605       child->rchild = grandchild;
10606     } else {
10607       grandchild = splay(m, child->lchild, searchpoint, searchtri);
10608       child->lchild = grandchild;
10609     }
10610     if (grandchild == (struct splaynode *) NULL) {
10611       if (rightofroot) {
10612         splaytree->rchild = child->lchild;
10613         child->lchild = splaytree;
10614       } else {
10615         splaytree->lchild = child->rchild;
10616         child->rchild = splaytree;
10617       }
10618       return child;
10619     }
10620     if (rightofchild) {
10621       if (rightofroot) {
10622         splaytree->rchild = child->lchild;
10623         child->lchild = splaytree;
10624       } else {
10625         splaytree->lchild = grandchild->rchild;
10626         grandchild->rchild = splaytree;
10627       }
10628       child->rchild = grandchild->lchild;
10629       grandchild->lchild = child;
10630     } else {
10631       if (rightofroot) {
10632         splaytree->rchild = grandchild->lchild;
10633         grandchild->lchild = splaytree;
10634       } else {
10635         splaytree->lchild = child->rchild;
10636         child->rchild = splaytree;
10637       }
10638       child->lchild = grandchild->rchild;
10639       grandchild->rchild = child;
10640     }
10641     return grandchild;
10642   } else {
10643     lefttree = splay(m, splaytree->lchild, searchpoint, searchtri);
10644     righttree = splay(m, splaytree->rchild, searchpoint, searchtri);
10645 
10646     pooldealloc(&m->splaynodes, (VOID *) splaytree);
10647     if (lefttree == (struct splaynode *) NULL) {
10648       return righttree;
10649     } else if (righttree == (struct splaynode *) NULL) {
10650       return lefttree;
10651     } else if (lefttree->rchild == (struct splaynode *) NULL) {
10652       lefttree->rchild = righttree->lchild;
10653       righttree->lchild = lefttree;
10654       return righttree;
10655     } else if (righttree->lchild == (struct splaynode *) NULL) {
10656       righttree->lchild = lefttree->rchild;
10657       lefttree->rchild = righttree;
10658       return lefttree;
10659     } else {
10660 /*      printf("Holy Toledo!!!\n"); */
10661       leftright = lefttree->rchild;
10662       while (leftright->rchild != (struct splaynode *) NULL) {
10663         leftright = leftright->rchild;
10664       }
10665       leftright->rchild = righttree;
10666       return lefttree;
10667     }
10668   }
10669 }
10670 
10671 #endif /* not REDUCED */
10672 
10673 #ifndef REDUCED
10674 
10675 #ifdef ANSI_DECLARATORS
10676 struct splaynode *splayinsert(struct mesh *m, struct splaynode *splayroot,
10677                               struct otri *newkey, vertex searchpoint)
10678 #else /* not ANSI_DECLARATORS */
10679 struct splaynode *splayinsert(m, splayroot, newkey, searchpoint)
10680 struct mesh *m;
10681 struct splaynode *splayroot;
10682 struct otri *newkey;
10683 vertex searchpoint;
10684 #endif /* not ANSI_DECLARATORS */
10685 
10686 {
10687   struct splaynode *newsplaynode;
10688 
10689   newsplaynode = (struct splaynode *) poolalloc(&m->splaynodes);
10690   otricopy(*newkey, newsplaynode->keyedge);
10691   dest(*newkey, newsplaynode->keydest);
10692   if (splayroot == (struct splaynode *) NULL) {
10693     newsplaynode->lchild = (struct splaynode *) NULL;
10694     newsplaynode->rchild = (struct splaynode *) NULL;
10695   } else if (rightofhyperbola(m, &splayroot->keyedge, searchpoint)) {
10696     newsplaynode->lchild = splayroot;
10697     newsplaynode->rchild = splayroot->rchild;
10698     splayroot->rchild = (struct splaynode *) NULL;
10699   } else {
10700     newsplaynode->lchild = splayroot->lchild;
10701     newsplaynode->rchild = splayroot;
10702     splayroot->lchild = (struct splaynode *) NULL;
10703   }
10704   return newsplaynode;
10705 }
10706 
10707 #endif /* not REDUCED */
10708 
10709 #ifndef REDUCED
10710 
10711 #ifdef ANSI_DECLARATORS
10712 struct splaynode *circletopinsert(struct mesh *m, struct behavior *b,
10713                                   struct splaynode *splayroot,
10714                                   struct otri *newkey,
10715                                   vertex pa, vertex pb, vertex pc, REAL topy)
10716 #else /* not ANSI_DECLARATORS */
10717 struct splaynode *circletopinsert(m, b, splayroot, newkey, pa, pb, pc, topy)
10718 struct mesh *m;
10719 struct behavior *b;
10720 struct splaynode *splayroot;
10721 struct otri *newkey;
10722 vertex pa;
10723 vertex pb;
10724 vertex pc;
10725 REAL topy;
10726 #endif /* not ANSI_DECLARATORS */
10727 
10728 {
10729   REAL ccwabc;
10730   REAL xac, yac, xbc, ybc;
10731   REAL aclen2, bclen2;
10732   REAL searchpoint[2];
10733   struct otri dummytri;
10734 
10735   ccwabc = counterclockwise(m, b, pa, pb, pc);
10736   xac = pa[0] - pc[0];
10737   yac = pa[1] - pc[1];
10738   xbc = pb[0] - pc[0];
10739   ybc = pb[1] - pc[1];
10740   aclen2 = xac * xac + yac * yac;
10741   bclen2 = xbc * xbc + ybc * ybc;
10742   searchpoint[0] = pc[0] - (yac * bclen2 - ybc * aclen2) / (2.0 * ccwabc);
10743   searchpoint[1] = topy;
10744   return splayinsert(m, splay(m, splayroot, (vertex) searchpoint, &dummytri),
10745                      newkey, (vertex) searchpoint);
10746 }
10747 
10748 #endif /* not REDUCED */
10749 
10750 #ifndef REDUCED
10751 
10752 #ifdef ANSI_DECLARATORS
10753 struct splaynode *frontlocate(struct mesh *m, struct splaynode *splayroot,
10754                               struct otri *bottommost, vertex searchvertex,
10755                               struct otri *searchtri, int *farright)
10756 #else /* not ANSI_DECLARATORS */
10757 struct splaynode *frontlocate(m, splayroot, bottommost, searchvertex,
10758                               searchtri, farright)
10759 struct mesh *m;
10760 struct splaynode *splayroot;
10761 struct otri *bottommost;
10762 vertex searchvertex;
10763 struct otri *searchtri;
10764 int *farright;
10765 #endif /* not ANSI_DECLARATORS */
10766 
10767 {
10768   int farrightflag;
10769   triangle ptr;                       /* Temporary variable used by onext(). */
10770 
10771   otricopy(*bottommost, *searchtri);
10772   splayroot = splay(m, splayroot, searchvertex, searchtri);
10773 
10774   farrightflag = 0;
10775   while (!farrightflag && rightofhyperbola(m, searchtri, searchvertex)) {
10776     onextself(*searchtri);
10777     farrightflag = otriequal(*searchtri, *bottommost);
10778   }
10779   *farright = farrightflag;
10780   return splayroot;
10781 }
10782 
10783 #endif /* not REDUCED */
10784 
10785 #ifndef REDUCED
10786 
10787 #ifdef ANSI_DECLARATORS
10788 long sweeplinedelaunay(struct mesh *m, struct behavior *b)
10789 #else /* not ANSI_DECLARATORS */
10790 long sweeplinedelaunay(m, b)
10791 struct mesh *m;
10792 struct behavior *b;
10793 #endif /* not ANSI_DECLARATORS */
10794 
10795 {
10796   struct event **eventheap;
10797   struct event *events;
10798   struct event *freeevents;
10799   struct event *nextevent;
10800   struct event *newevent;
10801   struct splaynode *splayroot;
10802   struct otri bottommost;
10803   struct otri searchtri;
10804   struct otri fliptri;
10805   struct otri lefttri, righttri, farlefttri, farrighttri;
10806   struct otri inserttri;
10807   vertex firstvertex, secondvertex;
10808   vertex nextvertex, lastvertex;
10809   vertex connectvertex;
10810   vertex leftvertex, midvertex, rightvertex;
10811   REAL lefttest, righttest;
10812   int heapsize;
10813   int check4events, farrightflag;
10814   triangle ptr;   /* Temporary variable used by sym(), onext(), and oprev(). */
10815 
10816   poolinit(&m->splaynodes, sizeof(struct splaynode), SPLAYNODEPERBLOCK,
10817            SPLAYNODEPERBLOCK, 0);
10818   splayroot = (struct splaynode *) NULL;
10819 
10820   if (b->verbose) {
10821     printf("  Placing vertices in event heap.\n");
10822   }
10823   createeventheap(m, &eventheap, &events, &freeevents);
10824   heapsize = m->invertices;
10825 
10826   if (b->verbose) {
10827     printf("  Forming triangulation.\n");
10828   }
10829   maketriangle(m, b, &lefttri);
10830   maketriangle(m, b, &righttri);
10831   bond(lefttri, righttri);
10832   lnextself(lefttri);
10833   lprevself(righttri);
10834   bond(lefttri, righttri);
10835   lnextself(lefttri);
10836   lprevself(righttri);
10837   bond(lefttri, righttri);
10838   firstvertex = (vertex) eventheap[0]->eventptr;
10839   eventheap[0]->eventptr = (VOID *) freeevents;
10840   freeevents = eventheap[0];
10841   eventheapdelete(eventheap, heapsize, 0);
10842   heapsize--;
10843   do {
10844     if (heapsize == 0) {
10845       printf("Error:  Input vertices are all identical.\n");
10846       triexit(1);
10847     }
10848     secondvertex = (vertex) eventheap[0]->eventptr;
10849     eventheap[0]->eventptr = (VOID *) freeevents;
10850     freeevents = eventheap[0];
10851     eventheapdelete(eventheap, heapsize, 0);
10852     heapsize--;
10853     if ((firstvertex[0] == secondvertex[0]) &&
10854         (firstvertex[1] == secondvertex[1])) {
10855       if (!b->quiet) {
10856         printf(
10857 "Warning:  A duplicate vertex at (%.12g, %.12g) appeared and was ignored.\n",
10858                secondvertex[0], secondvertex[1]);
10859       }
10860       setvertextype(secondvertex, UNDEADVERTEX);
10861       m->undeads++;
10862     }
10863   } while ((firstvertex[0] == secondvertex[0]) &&
10864            (firstvertex[1] == secondvertex[1]));
10865   setorg(lefttri, firstvertex);
10866   setdest(lefttri, secondvertex);
10867   setorg(righttri, secondvertex);
10868   setdest(righttri, firstvertex);
10869   lprev(lefttri, bottommost);
10870   lastvertex = secondvertex;
10871   while (heapsize > 0) {
10872     nextevent = eventheap[0];
10873     eventheapdelete(eventheap, heapsize, 0);
10874     heapsize--;
10875     check4events = 1;
10876     if (nextevent->xkey < m->xmin) {
10877       decode(nextevent->eventptr, fliptri);
10878       oprev(fliptri, farlefttri);
10879       check4deadevent(&farlefttri, &freeevents, eventheap, &heapsize);
10880       onext(fliptri, farrighttri);
10881       check4deadevent(&farrighttri, &freeevents, eventheap, &heapsize);
10882 
10883       if (otriequal(farlefttri, bottommost)) {
10884         lprev(fliptri, bottommost);
10885       }
10886       flip(m, b, &fliptri);
10887       setapex(fliptri, NULL);
10888       lprev(fliptri, lefttri);
10889       lnext(fliptri, righttri);
10890       sym(lefttri, farlefttri);
10891 
10892       if (randomnation(SAMPLERATE) == 0) {
10893         symself(fliptri);
10894         dest(fliptri, leftvertex);
10895         apex(fliptri, midvertex);
10896         org(fliptri, rightvertex);
10897         splayroot = circletopinsert(m, b, splayroot, &lefttri, leftvertex,
10898                                     midvertex, rightvertex, nextevent->ykey);
10899       }
10900     } else {
10901       nextvertex = (vertex) nextevent->eventptr;
10902       if ((nextvertex[0] == lastvertex[0]) &&
10903           (nextvertex[1] == lastvertex[1])) {
10904         if (!b->quiet) {
10905           printf(
10906 "Warning:  A duplicate vertex at (%.12g, %.12g) appeared and was ignored.\n",
10907                  nextvertex[0], nextvertex[1]);
10908         }
10909         setvertextype(nextvertex, UNDEADVERTEX);
10910         m->undeads++;
10911         check4events = 0;
10912       } else {
10913         lastvertex = nextvertex;
10914 
10915         splayroot = frontlocate(m, splayroot, &bottommost, nextvertex,
10916                                 &searchtri, &farrightflag);
10917 /*
10918         otricopy(bottommost, searchtri);
10919         farrightflag = 0;
10920         while (!farrightflag && rightofhyperbola(m, &searchtri, nextvertex)) {
10921           onextself(searchtri);
10922           farrightflag = otriequal(searchtri, bottommost);
10923         }
10924 */
10925 
10926         check4deadevent(&searchtri, &freeevents, eventheap, &heapsize);
10927 
10928         otricopy(searchtri, farrighttri);
10929         sym(searchtri, farlefttri);
10930         maketriangle(m, b, &lefttri);
10931         maketriangle(m, b, &righttri);
10932         dest(farrighttri, connectvertex);
10933         setorg(lefttri, connectvertex);
10934         setdest(lefttri, nextvertex);
10935         setorg(righttri, nextvertex);
10936         setdest(righttri, connectvertex);
10937         bond(lefttri, righttri);
10938         lnextself(lefttri);
10939         lprevself(righttri);
10940         bond(lefttri, righttri);
10941         lnextself(lefttri);
10942         lprevself(righttri);
10943         bond(lefttri, farlefttri);
10944         bond(righttri, farrighttri);
10945         if (!farrightflag && otriequal(farrighttri, bottommost)) {
10946           otricopy(lefttri, bottommost);
10947         }
10948 
10949         if (randomnation(SAMPLERATE) == 0) {
10950           splayroot = splayinsert(m, splayroot, &lefttri, nextvertex);
10951         } else if (randomnation(SAMPLERATE) == 0) {
10952           lnext(righttri, inserttri);
10953           splayroot = splayinsert(m, splayroot, &inserttri, nextvertex);
10954         }
10955       }
10956     }
10957     nextevent->eventptr = (VOID *) freeevents;
10958     freeevents = nextevent;
10959 
10960     if (check4events) {
10961       apex(farlefttri, leftvertex);
10962       dest(lefttri, midvertex);
10963       apex(lefttri, rightvertex);
10964       lefttest = counterclockwise(m, b, leftvertex, midvertex, rightvertex);
10965       if (lefttest > 0.0) {
10966         newevent = freeevents;
10967         freeevents = (struct event *) freeevents->eventptr;
10968         newevent->xkey = m->xminextreme;
10969         newevent->ykey = circletop(m, leftvertex, midvertex, rightvertex,
10970                                    lefttest);
10971         newevent->eventptr = (VOID *) encode(lefttri);
10972         eventheapinsert(eventheap, heapsize, newevent);
10973         heapsize++;
10974         setorg(lefttri, newevent);
10975       }
10976       apex(righttri, leftvertex);
10977       org(righttri, midvertex);
10978       apex(farrighttri, rightvertex);
10979       righttest = counterclockwise(m, b, leftvertex, midvertex, rightvertex);
10980       if (righttest > 0.0) {
10981         newevent = freeevents;
10982         freeevents = (struct event *) freeevents->eventptr;
10983         newevent->xkey = m->xminextreme;
10984         newevent->ykey = circletop(m, leftvertex, midvertex, rightvertex,
10985                                    righttest);
10986         newevent->eventptr = (VOID *) encode(farrighttri);
10987         eventheapinsert(eventheap, heapsize, newevent);
10988         heapsize++;
10989         setorg(farrighttri, newevent);
10990       }
10991     }
10992   }
10993 
10994   pooldeinit(&m->splaynodes);
10995   lprevself(bottommost);
10996   return removeghosts(m, b, &bottommost);
10997 }
10998 
10999 #endif /* not REDUCED */
11000 
11001 /**                                                                         **/
11002 /**                                                                         **/
11003 /********* Sweepline Delaunay triangulation ends here                *********/
11004 
11005 /********* General mesh construction routines begin here             *********/
11006 /**                                                                         **/
11007 /**                                                                         **/
11008 
11009 /*****************************************************************************/
11010 /*                                                                           */
11011 /*  delaunay()   Form a Delaunay triangulation.                              */
11012 /*                                                                           */
11013 /*****************************************************************************/
11014 
11015 #ifdef ANSI_DECLARATORS
11016 long delaunay(struct mesh *m, struct behavior *b)
11017 #else /* not ANSI_DECLARATORS */
11018 long delaunay(m, b)
11019 struct mesh *m;
11020 struct behavior *b;
11021 #endif /* not ANSI_DECLARATORS */
11022 
11023 {
11024   long hulledges;
11025 
11026   m->eextras = 0;
11027   initializetrisubpools(m, b);
11028 
11029 #ifdef REDUCED
11030   if (!b->quiet) {
11031     printf(
11032       "Constructing Delaunay triangulation by divide-and-conquer method.\n");
11033   }
11034   hulledges = divconqdelaunay(m, b);
11035 #else /* not REDUCED */
11036   if (!b->quiet) {
11037     printf("Constructing Delaunay triangulation ");
11038     if (b->incremental) {
11039       printf("by incremental method.\n");
11040     } else if (b->sweepline) {
11041       printf("by sweepline method.\n");
11042     } else {
11043       printf("by divide-and-conquer method.\n");
11044     }
11045   }
11046   if (b->incremental) {
11047     hulledges = incrementaldelaunay(m, b);
11048   } else if (b->sweepline) {
11049     hulledges = sweeplinedelaunay(m, b);
11050   } else {
11051     hulledges = divconqdelaunay(m, b);
11052   }
11053 #endif /* not REDUCED */
11054 
11055   if (m->triangles.items == 0) {
11056     /* The input vertices were all collinear, so there are no triangles. */
11057     return 0l;
11058   } else {
11059     return hulledges;
11060   }
11061 }
11062 
11063 /*****************************************************************************/
11064 /*                                                                           */
11065 /*  reconstruct()   Reconstruct a triangulation from its .ele (and possibly  */
11066 /*                  .poly) file.  Used when the -r switch is used.           */
11067 /*                                                                           */
11068 /*  Reads an .ele file and reconstructs the original mesh.  If the -p switch */
11069 /*  is used, this procedure will also read a .poly file and reconstruct the  */
11070 /*  subsegments of the original mesh.  If the -a switch is used, this        */
11071 /*  procedure will also read an .area file and set a maximum area constraint */
11072 /*  on each triangle.                                                        */
11073 /*                                                                           */
11074 /*  Vertices that are not corners of triangles, such as nodes on edges of    */
11075 /*  subparametric elements, are discarded.                                   */
11076 /*                                                                           */
11077 /*  This routine finds the adjacencies between triangles (and subsegments)   */
11078 /*  by forming one stack of triangles for each vertex.  Each triangle is on  */
11079 /*  three different stacks simultaneously.  Each triangle's subsegment       */
11080 /*  pointers are used to link the items in each stack.  This memory-saving   */
11081 /*  feature makes the code harder to read.  The most important thing to keep */
11082 /*  in mind is that each triangle is removed from a stack precisely when     */
11083 /*  the corresponding pointer is adjusted to refer to a subsegment rather    */
11084 /*  than the next triangle of the stack.                                     */
11085 /*                                                                           */
11086 /*****************************************************************************/
11087 
11088 #ifndef CDT_ONLY
11089 
11090 #ifdef TRILIBRARY
11091 
11092 #ifdef ANSI_DECLARATORS
11093 int reconstruct(struct mesh *m, struct behavior *b, int *trianglelist,
11094                 REAL *triangleattriblist, REAL *trianglearealist,
11095                 int elements, int corners, int attribs,
11096                 int *segmentlist,int *segmentmarkerlist, int numberofsegments)
11097 #else /* not ANSI_DECLARATORS */
11098 int reconstruct(m, b, trianglelist, triangleattriblist, trianglearealist,
11099                 elements, corners, attribs, segmentlist, segmentmarkerlist,
11100                 numberofsegments)
11101 struct mesh *m;
11102 struct behavior *b;
11103 int *trianglelist;
11104 REAL *triangleattriblist;
11105 REAL *trianglearealist;
11106 int elements;
11107 int corners;
11108 int attribs;
11109 int *segmentlist;
11110 int *segmentmarkerlist;
11111 int numberofsegments;
11112 #endif /* not ANSI_DECLARATORS */
11113 
11114 #else /* not TRILIBRARY */
11115 
11116 #ifdef ANSI_DECLARATORS
11117 long reconstruct(struct mesh *m, struct behavior *b, char *elefilename,
11118                  char *areafilename, char *polyfilename, FILE *polyfile)
11119 #else /* not ANSI_DECLARATORS */
11120 long reconstruct(m, b, elefilename, areafilename, polyfilename, polyfile)
11121 struct mesh *m;
11122 struct behavior *b;
11123 char *elefilename;
11124 char *areafilename;
11125 char *polyfilename;
11126 FILE *polyfile;
11127 #endif /* not ANSI_DECLARATORS */
11128 
11129 #endif /* not TRILIBRARY */
11130 
11131 {
11132 #ifdef TRILIBRARY
11133   int vertexindex;
11134   int attribindex;
11135 #else /* not TRILIBRARY */
11136   FILE *elefile;
11137   FILE *areafile;
11138   char inputline[INPUTLINESIZE];
11139   char *stringptr;
11140   int areaelements;
11141 #endif /* not TRILIBRARY */
11142   struct otri triangleloop;
11143   struct otri triangleleft;
11144   struct otri checktri;
11145   struct otri checkleft;
11146   struct otri checkneighbor;
11147   struct osub subsegloop;
11148   triangle *vertexarray;
11149   triangle *prevlink;
11150   triangle nexttri;
11151   vertex tdest, tapex;
11152   vertex checkdest, checkapex;
11153   vertex shorg;
11154   vertex killvertex;
11155   vertex segmentorg, segmentdest;
11156   REAL area;
11157   int corner[3];
11158   int end[2];
11159   int killvertexindex;
11160   int incorners;
11161   int segmentmarkers;
11162   int boundmarker;
11163   int aroundvertex;
11164   long hullsize;
11165   int notfound;
11166   long elementnumber, segmentnumber;
11167   int i, j;
11168   triangle ptr;                         /* Temporary variable used by sym(). */
11169 
11170 #ifdef TRILIBRARY
11171   m->inelements = elements;
11172   incorners = corners;
11173   if (incorners < 3) {
11174     printf("Error:  Triangles must have at least 3 vertices.\n");
11175     triexit(1);
11176   }
11177   m->eextras = attribs;
11178 #else /* not TRILIBRARY */
11179   /* Read the triangles from an .ele file. */
11180   if (!b->quiet) {
11181     printf("Opening %s.\n", elefilename);
11182   }
11183   elefile = fopen(elefilename, "r");
11184   if (elefile == (FILE *) NULL) {
11185     printf("  Error:  Cannot access file %s.\n", elefilename);
11186     triexit(1);
11187   }
11188   /* Read number of triangles, number of vertices per triangle, and */
11189   /*   number of triangle attributes from .ele file.                */
11190   stringptr = readline(inputline, elefile, elefilename);
11191   m->inelements = (int) strtol(stringptr, &stringptr, 0);
11192   stringptr = findfield(stringptr);
11193   if (*stringptr == '\0') {
11194     incorners = 3;
11195   } else {
11196     incorners = (int) strtol(stringptr, &stringptr, 0);
11197     if (incorners < 3) {
11198       printf("Error:  Triangles in %s must have at least 3 vertices.\n",
11199              elefilename);
11200       triexit(1);
11201     }
11202   }
11203   stringptr = findfield(stringptr);
11204   if (*stringptr == '\0') {
11205     m->eextras = 0;
11206   } else {
11207     m->eextras = (int) strtol(stringptr, &stringptr, 0);
11208   }
11209 #endif /* not TRILIBRARY */
11210 
11211   initializetrisubpools(m, b);
11212 
11213   /* Create the triangles. */
11214   for (elementnumber = 1; elementnumber <= m->inelements; elementnumber++) {
11215     maketriangle(m, b, &triangleloop);
11216     /* Mark the triangle as living. */
11217     triangleloop.tri[3] = (triangle) triangleloop.tri;
11218   }
11219 
11220   segmentmarkers = 0;
11221   if (b->poly) {
11222 #ifdef TRILIBRARY
11223     m->insegments = numberofsegments;
11224     segmentmarkers = segmentmarkerlist != (int *) NULL;
11225 #else /* not TRILIBRARY */
11226     /* Read number of segments and number of segment */
11227     /*   boundary markers from .poly file.           */
11228     stringptr = readline(inputline, polyfile, b->inpolyfilename);
11229     m->insegments = (int) strtol(stringptr, &stringptr, 0);
11230     stringptr = findfield(stringptr);
11231     if (*stringptr != '\0') {
11232       segmentmarkers = (int) strtol(stringptr, &stringptr, 0);
11233     }
11234 #endif /* not TRILIBRARY */
11235 
11236     /* Create the subsegments. */
11237     for (segmentnumber = 1; segmentnumber <= m->insegments; segmentnumber++) {
11238       makesubseg(m, &subsegloop);
11239       /* Mark the subsegment as living. */
11240       subsegloop.ss[2] = (subseg) subsegloop.ss;
11241     }
11242   }
11243 
11244 #ifdef TRILIBRARY
11245   vertexindex = 0;
11246   attribindex = 0;
11247 #else /* not TRILIBRARY */
11248   if (b->vararea) {
11249     /* Open an .area file, check for consistency with the .ele file. */
11250     if (!b->quiet) {
11251       printf("Opening %s.\n", areafilename);
11252     }
11253     areafile = fopen(areafilename, "r");
11254     if (areafile == (FILE *) NULL) {
11255       printf("  Error:  Cannot access file %s.\n", areafilename);
11256       triexit(1);
11257     }
11258     stringptr = readline(inputline, areafile, areafilename);
11259     areaelements = (int) strtol(stringptr, &stringptr, 0);
11260     if (areaelements != m->inelements) {
11261       printf("Error:  %s and %s disagree on number of triangles.\n",
11262              elefilename, areafilename);
11263       triexit(1);
11264     }
11265   }
11266 #endif /* not TRILIBRARY */
11267 
11268   if (!b->quiet) {
11269     printf("Reconstructing mesh.\n");
11270   }
11271   /* Allocate a temporary array that maps each vertex to some adjacent */
11272   /*   triangle.  I took care to allocate all the permanent memory for */
11273   /*   triangles and subsegments first.                                */
11274   vertexarray = (triangle *) trimalloc(m->vertices.items *
11275                                        (int) sizeof(triangle));
11276   /* Each vertex is initially unrepresented. */
11277   for (i = 0; i < m->vertices.items; i++) {
11278     vertexarray[i] = (triangle) m->dummytri;
11279   }
11280 
11281   if (b->verbose) {
11282     printf("  Assembling triangles.\n");
11283   }
11284   /* Read the triangles from the .ele file, and link */
11285   /*   together those that share an edge.            */
11286   traversalinit(&m->triangles);
11287   triangleloop.tri = triangletraverse(m);
11288   elementnumber = b->firstnumber;
11289   while (triangleloop.tri != (triangle *) NULL) {
11290 #ifdef TRILIBRARY
11291     /* Copy the triangle's three corners. */
11292     for (j = 0; j < 3; j++) {
11293       corner[j] = trianglelist[vertexindex++];
11294       if ((corner[j] < b->firstnumber) ||
11295           (corner[j] >= b->firstnumber + m->invertices)) {
11296         printf("Error:  Triangle %ld has an invalid vertex index.\n",
11297                elementnumber);
11298         triexit(1);
11299       }
11300     }
11301 #else /* not TRILIBRARY */
11302     /* Read triangle number and the triangle's three corners. */
11303     stringptr = readline(inputline, elefile, elefilename);
11304     for (j = 0; j < 3; j++) {
11305       stringptr = findfield(stringptr);
11306       if (*stringptr == '\0') {
11307         printf("Error:  Triangle %ld is missing vertex %d in %s.\n",
11308                elementnumber, j + 1, elefilename);
11309         triexit(1);
11310       } else {
11311         corner[j] = (int) strtol(stringptr, &stringptr, 0);
11312         if ((corner[j] < b->firstnumber) ||
11313             (corner[j] >= b->firstnumber + m->invertices)) {
11314           printf("Error:  Triangle %ld has an invalid vertex index.\n",
11315                  elementnumber);
11316           triexit(1);
11317         }
11318       }
11319     }
11320 #endif /* not TRILIBRARY */
11321 
11322     /* Find out about (and throw away) extra nodes. */
11323     for (j = 3; j < incorners; j++) {
11324 #ifdef TRILIBRARY
11325       killvertexindex = trianglelist[vertexindex++];
11326 #else /* not TRILIBRARY */
11327       stringptr = findfield(stringptr);
11328       if (*stringptr != '\0') {
11329         killvertexindex = (int) strtol(stringptr, &stringptr, 0);
11330 #endif /* not TRILIBRARY */
11331         if ((killvertexindex >= b->firstnumber) &&
11332             (killvertexindex < b->firstnumber + m->invertices)) {
11333           /* Delete the non-corner vertex if it's not already deleted. */
11334           killvertex = getvertex(m, b, killvertexindex);
11335           if (vertextype(killvertex) != DEADVERTEX) {
11336             vertexdealloc(m, killvertex);
11337           }
11338         }
11339 #ifndef TRILIBRARY
11340       }
11341 #endif /* not TRILIBRARY */
11342     }
11343 
11344     /* Read the triangle's attributes. */
11345     for (j = 0; j < m->eextras; j++) {
11346 #ifdef TRILIBRARY
11347       setelemattribute(triangleloop, j, triangleattriblist[attribindex++]);
11348 #else /* not TRILIBRARY */
11349       stringptr = findfield(stringptr);
11350       if (*stringptr == '\0') {
11351         setelemattribute(triangleloop, j, 0);
11352       } else {
11353         setelemattribute(triangleloop, j,
11354                          (REAL) strtod(stringptr, &stringptr));
11355       }
11356 #endif /* not TRILIBRARY */
11357     }
11358 
11359     if (b->vararea) {
11360 #ifdef TRILIBRARY
11361       area = trianglearealist[elementnumber - b->firstnumber];
11362 #else /* not TRILIBRARY */
11363       /* Read an area constraint from the .area file. */
11364       stringptr = readline(inputline, areafile, areafilename);
11365       stringptr = findfield(stringptr);
11366       if (*stringptr == '\0') {
11367         area = -1.0;                      /* No constraint on this triangle. */
11368       } else {
11369         area = (REAL) strtod(stringptr, &stringptr);
11370       }
11371 #endif /* not TRILIBRARY */
11372       setareabound(triangleloop, area);
11373     }
11374 
11375     /* Set the triangle's vertices. */
11376     triangleloop.orient = 0;
11377     setorg(triangleloop, getvertex(m, b, corner[0]));
11378     setdest(triangleloop, getvertex(m, b, corner[1]));
11379     setapex(triangleloop, getvertex(m, b, corner[2]));
11380     /* Try linking the triangle to others that share these vertices. */
11381     for (triangleloop.orient = 0; triangleloop.orient < 3;
11382          triangleloop.orient++) {
11383       /* Take the number for the origin of triangleloop. */
11384       aroundvertex = corner[triangleloop.orient];
11385       /* Look for other triangles having this vertex. */
11386       nexttri = vertexarray[aroundvertex - b->firstnumber];
11387       /* Link the current triangle to the next one in the stack. */
11388       triangleloop.tri[6 + triangleloop.orient] = nexttri;
11389       /* Push the current triangle onto the stack. */
11390       vertexarray[aroundvertex - b->firstnumber] = encode(triangleloop);
11391       decode(nexttri, checktri);
11392       if (checktri.tri != m->dummytri) {
11393         dest(triangleloop, tdest);
11394         apex(triangleloop, tapex);
11395         /* Look for other triangles that share an edge. */
11396         do {
11397           dest(checktri, checkdest);
11398           apex(checktri, checkapex);
11399           if (tapex == checkdest) {
11400             /* The two triangles share an edge; bond them together. */
11401             lprev(triangleloop, triangleleft);
11402             bond(triangleleft, checktri);
11403           }
11404           if (tdest == checkapex) {
11405             /* The two triangles share an edge; bond them together. */
11406             lprev(checktri, checkleft);
11407             bond(triangleloop, checkleft);
11408           }
11409           /* Find the next triangle in the stack. */
11410           nexttri = checktri.tri[6 + checktri.orient];
11411           decode(nexttri, checktri);
11412         } while (checktri.tri != m->dummytri);
11413       }
11414     }
11415     triangleloop.tri = triangletraverse(m);
11416     elementnumber++;
11417   }
11418 
11419 #ifdef TRILIBRARY
11420   vertexindex = 0;
11421 #else /* not TRILIBRARY */
11422   fclose(elefile);
11423   if (b->vararea) {
11424     fclose(areafile);
11425   }
11426 #endif /* not TRILIBRARY */
11427 
11428   hullsize = 0;                      /* Prepare to count the boundary edges. */
11429   if (b->poly) {
11430     if (b->verbose) {
11431       printf("  Marking segments in triangulation.\n");
11432     }
11433     /* Read the segments from the .poly file, and link them */
11434     /*   to their neighboring triangles.                    */
11435     boundmarker = 0;
11436     traversalinit(&m->subsegs);
11437     subsegloop.ss = subsegtraverse(m);
11438     segmentnumber = b->firstnumber;
11439     while (subsegloop.ss != (subseg *) NULL) {
11440 #ifdef TRILIBRARY
11441       end[0] = segmentlist[vertexindex++];
11442       end[1] = segmentlist[vertexindex++];
11443       if (segmentmarkers) {
11444         boundmarker = segmentmarkerlist[segmentnumber - b->firstnumber];
11445       }
11446 #else /* not TRILIBRARY */
11447       /* Read the endpoints of each segment, and possibly a boundary marker. */
11448       stringptr = readline(inputline, polyfile, b->inpolyfilename);
11449       /* Skip the first (segment number) field. */
11450       stringptr = findfield(stringptr);
11451       if (*stringptr == '\0') {
11452         printf("Error:  Segment %ld has no endpoints in %s.\n", segmentnumber,
11453                polyfilename);
11454         triexit(1);
11455       } else {
11456         end[0] = (int) strtol(stringptr, &stringptr, 0);
11457       }
11458       stringptr = findfield(stringptr);
11459       if (*stringptr == '\0') {
11460         printf("Error:  Segment %ld is missing its second endpoint in %s.\n",
11461                segmentnumber, polyfilename);
11462         triexit(1);
11463       } else {
11464         end[1] = (int) strtol(stringptr, &stringptr, 0);
11465       }
11466       if (segmentmarkers) {
11467         stringptr = findfield(stringptr);
11468         if (*stringptr == '\0') {
11469           boundmarker = 0;
11470         } else {
11471           boundmarker = (int) strtol(stringptr, &stringptr, 0);
11472         }
11473       }
11474 #endif /* not TRILIBRARY */
11475       for (j = 0; j < 2; j++) {
11476         if ((end[j] < b->firstnumber) ||
11477             (end[j] >= b->firstnumber + m->invertices)) {
11478           printf("Error:  Segment %ld has an invalid vertex index.\n",
11479                  segmentnumber);
11480           triexit(1);
11481         }
11482       }
11483 
11484       /* set the subsegment's vertices. */
11485       subsegloop.ssorient = 0;
11486       segmentorg = getvertex(m, b, end[0]);
11487       segmentdest = getvertex(m, b, end[1]);
11488       setsorg(subsegloop, segmentorg);
11489       setsdest(subsegloop, segmentdest);
11490       setsegorg(subsegloop, segmentorg);
11491       setsegdest(subsegloop, segmentdest);
11492       setmark(subsegloop, boundmarker);
11493       /* Try linking the subsegment to triangles that share these vertices. */
11494       for (subsegloop.ssorient = 0; subsegloop.ssorient < 2;
11495            subsegloop.ssorient++) {
11496         /* Take the number for the destination of subsegloop. */
11497         aroundvertex = end[1 - subsegloop.ssorient];
11498         /* Look for triangles having this vertex. */
11499         prevlink = &vertexarray[aroundvertex - b->firstnumber];
11500         nexttri = vertexarray[aroundvertex - b->firstnumber];
11501         decode(nexttri, checktri);
11502         sorg(subsegloop, shorg);
11503         notfound = 1;
11504         /* Look for triangles having this edge.  Note that I'm only       */
11505         /*   comparing each triangle's destination with the subsegment;   */
11506         /*   each triangle's apex is handled through a different vertex.  */
11507         /*   Because each triangle appears on three vertices' lists, each */
11508         /*   occurrence of a triangle on a list can (and does) represent  */
11509         /*   an edge.  In this way, most edges are represented twice, and */
11510         /*   every triangle-subsegment bond is represented once.          */
11511         while (notfound && (checktri.tri != m->dummytri)) {
11512           dest(checktri, checkdest);
11513           if (shorg == checkdest) {
11514             /* We have a match.  Remove this triangle from the list. */
11515             *prevlink = checktri.tri[6 + checktri.orient];
11516             /* Bond the subsegment to the triangle. */
11517             tsbond(checktri, subsegloop);
11518             /* Check if this is a boundary edge. */
11519             sym(checktri, checkneighbor);
11520             if (checkneighbor.tri == m->dummytri) {
11521               /* The next line doesn't insert a subsegment (because there's */
11522               /*   already one there), but it sets the boundary markers of  */
11523               /*   the existing subsegment and its vertices.                */
11524               insertsubseg(m, b, &checktri, 1);
11525               hullsize++;
11526             }
11527             notfound = 0;
11528           }
11529           /* Find the next triangle in the stack. */
11530           prevlink = &checktri.tri[6 + checktri.orient];
11531           nexttri = checktri.tri[6 + checktri.orient];
11532           decode(nexttri, checktri);
11533         }
11534       }
11535       subsegloop.ss = subsegtraverse(m);
11536       segmentnumber++;
11537     }
11538   }
11539 
11540   /* Mark the remaining edges as not being attached to any subsegment. */
11541   /* Also, count the (yet uncounted) boundary edges.                   */
11542   for (i = 0; i < m->vertices.items; i++) {
11543     /* Search the stack of triangles adjacent to a vertex. */
11544     nexttri = vertexarray[i];
11545     decode(nexttri, checktri);
11546     while (checktri.tri != m->dummytri) {
11547       /* Find the next triangle in the stack before this */
11548       /*   information gets overwritten.                 */
11549       nexttri = checktri.tri[6 + checktri.orient];
11550       /* No adjacent subsegment.  (This overwrites the stack info.) */
11551       tsdissolve(checktri);
11552       sym(checktri, checkneighbor);
11553       if (checkneighbor.tri == m->dummytri) {
11554         insertsubseg(m, b, &checktri, 1);
11555         hullsize++;
11556       }
11557       decode(nexttri, checktri);
11558     }
11559   }
11560 
11561   trifree((VOID *) vertexarray);
11562   return hullsize;
11563 }
11564 
11565 #endif /* not CDT_ONLY */
11566 
11567 /**                                                                         **/
11568 /**                                                                         **/
11569 /********* General mesh construction routines end here               *********/
11570 
11571 /********* Segment insertion begins here                             *********/
11572 /**                                                                         **/
11573 /**                                                                         **/
11574 
11575 /*****************************************************************************/
11576 /*                                                                           */
11577 /*  finddirection()   Find the first triangle on the path from one point     */
11578 /*                    to another.                                            */
11579 /*                                                                           */
11580 /*  Finds the triangle that intersects a line segment drawn from the         */
11581 /*  origin of `searchtri' to the point `searchpoint', and returns the result */
11582 /*  in `searchtri'.  The origin of `searchtri' does not change, even though  */
11583 /*  the triangle returned may differ from the one passed in.  This routine   */
11584 /*  is used to find the direction to move in to get from one point to        */
11585 /*  another.                                                                 */
11586 /*                                                                           */
11587 /*  The return value notes whether the destination or apex of the found      */
11588 /*  triangle is collinear with the two points in question.                   */
11589 /*                                                                           */
11590 /*****************************************************************************/
11591 
11592 #ifdef ANSI_DECLARATORS
11593 enum finddirectionresult finddirection(struct mesh *m, struct behavior *b,
11594                                        struct otri *searchtri,
11595                                        vertex searchpoint)
11596 #else /* not ANSI_DECLARATORS */
11597 enum finddirectionresult finddirection(m, b, searchtri, searchpoint)
11598 struct mesh *m;
11599 struct behavior *b;
11600 struct otri *searchtri;
11601 vertex searchpoint;
11602 #endif /* not ANSI_DECLARATORS */
11603 
11604 {
11605   struct otri checktri;
11606   vertex startvertex;
11607   vertex leftvertex, rightvertex;
11608   REAL leftccw, rightccw;
11609   int leftflag, rightflag;
11610   triangle ptr;           /* Temporary variable used by onext() and oprev(). */
11611 
11612   org(*searchtri, startvertex);
11613   dest(*searchtri, rightvertex);
11614   apex(*searchtri, leftvertex);
11615   /* Is `searchpoint' to the left? */
11616   leftccw = counterclockwise(m, b, searchpoint, startvertex, leftvertex);
11617   leftflag = leftccw > 0.0;
11618   /* Is `searchpoint' to the right? */
11619   rightccw = counterclockwise(m, b, startvertex, searchpoint, rightvertex);
11620   rightflag = rightccw > 0.0;
11621   if (leftflag && rightflag) {
11622     /* `searchtri' faces directly away from `searchpoint'.  We could go left */
11623     /*   or right.  Ask whether it's a triangle or a boundary on the left.   */
11624     onext(*searchtri, checktri);
11625     if (checktri.tri == m->dummytri) {
11626       leftflag = 0;
11627     } else {
11628       rightflag = 0;
11629     }
11630   }
11631   while (leftflag) {
11632     /* Turn left until satisfied. */
11633     onextself(*searchtri);
11634     if (searchtri->tri == m->dummytri) {
11635       printf("Internal error in finddirection():  Unable to find a\n");
11636       printf("  triangle leading from (%.12g, %.12g) to", startvertex[0],
11637              startvertex[1]);
11638       printf("  (%.12g, %.12g).\n", searchpoint[0], searchpoint[1]);
11639       internalerror();
11640     }
11641     apex(*searchtri, leftvertex);
11642     rightccw = leftccw;
11643     leftccw = counterclockwise(m, b, searchpoint, startvertex, leftvertex);
11644     leftflag = leftccw > 0.0;
11645   }
11646   while (rightflag) {
11647     /* Turn right until satisfied. */
11648     oprevself(*searchtri);
11649     if (searchtri->tri == m->dummytri) {
11650       printf("Internal error in finddirection():  Unable to find a\n");
11651       printf("  triangle leading from (%.12g, %.12g) to", startvertex[0],
11652              startvertex[1]);
11653       printf("  (%.12g, %.12g).\n", searchpoint[0], searchpoint[1]);
11654       internalerror();
11655     }
11656     dest(*searchtri, rightvertex);
11657     leftccw = rightccw;
11658     rightccw = counterclockwise(m, b, startvertex, searchpoint, rightvertex);
11659     rightflag = rightccw > 0.0;
11660   }
11661   if (leftccw == 0.0) {
11662     return LEFTCOLLINEAR;
11663   } else if (rightccw == 0.0) {
11664     return RIGHTCOLLINEAR;
11665   } else {
11666     return WITHIN;
11667   }
11668 }
11669 
11670 /*****************************************************************************/
11671 /*                                                                           */
11672 /*  segmentintersection()   Find the intersection of an existing segment     */
11673 /*                          and a segment that is being inserted.  Insert    */
11674 /*                          a vertex at the intersection, splitting an       */
11675 /*                          existing subsegment.                             */
11676 /*                                                                           */
11677 /*  The segment being inserted connects the apex of splittri to endpoint2.   */
11678 /*  splitsubseg is the subsegment being split, and MUST adjoin splittri.     */
11679 /*  Hence, endpoints of the subsegment being split are the origin and        */
11680 /*  destination of splittri.                                                 */
11681 /*                                                                           */
11682 /*  On completion, splittri is a handle having the newly inserted            */
11683 /*  intersection point as its origin, and endpoint1 as its destination.      */
11684 /*                                                                           */
11685 /*****************************************************************************/
11686 
11687 #ifdef ANSI_DECLARATORS
11688 void segmentintersection(struct mesh *m, struct behavior *b,
11689                          struct otri *splittri, struct osub *splitsubseg,
11690                          vertex endpoint2)
11691 #else /* not ANSI_DECLARATORS */
11692 void segmentintersection(m, b, splittri, splitsubseg, endpoint2)
11693 struct mesh *m;
11694 struct behavior *b;
11695 struct otri *splittri;
11696 struct osub *splitsubseg;
11697 vertex endpoint2;
11698 #endif /* not ANSI_DECLARATORS */
11699 
11700 {
11701   struct osub opposubseg;
11702   vertex endpoint1;
11703   vertex torg, tdest;
11704   vertex leftvertex, rightvertex;
11705   vertex newvertex;
11706   enum insertvertexresult success;
11707   enum finddirectionresult collinear;
11708   REAL ex, ey;
11709   REAL tx, ty;
11710   REAL etx, ety;
11711   REAL split, denom;
11712   int i;
11713   triangle ptr;                       /* Temporary variable used by onext(). */
11714   subseg sptr;                        /* Temporary variable used by snext(). */
11715 
11716   /* Find the other three segment endpoints. */
11717   apex(*splittri, endpoint1);
11718   org(*splittri, torg);
11719   dest(*splittri, tdest);
11720   /* Segment intersection formulae; see the Antonio reference. */
11721   tx = tdest[0] - torg[0];
11722   ty = tdest[1] - torg[1];
11723   ex = endpoint2[0] - endpoint1[0];
11724   ey = endpoint2[1] - endpoint1[1];
11725   etx = torg[0] - endpoint2[0];
11726   ety = torg[1] - endpoint2[1];
11727   denom = ty * ex - tx * ey;
11728   if (denom == 0.0) {
11729     printf("Internal error in segmentintersection():");
11730     printf("  Attempt to find intersection of parallel segments.\n");
11731     internalerror();
11732   }
11733   split = (ey * etx - ex * ety) / denom;
11734   /* Create the new vertex. */
11735   newvertex = (vertex) poolalloc(&m->vertices);
11736   /* Interpolate its coordinate and attributes. */
11737   for (i = 0; i < 2 + m->nextras; i++) {
11738     newvertex[i] = torg[i] + split * (tdest[i] - torg[i]);
11739   }
11740   setvertexmark(newvertex, mark(*splitsubseg));
11741   setvertextype(newvertex, INPUTVERTEX);
11742   if (b->verbose > 1) {
11743     printf(
11744   "  Splitting subsegment (%.12g, %.12g) (%.12g, %.12g) at (%.12g, %.12g).\n",
11745            torg[0], torg[1], tdest[0], tdest[1], newvertex[0], newvertex[1]);
11746   }
11747   /* Insert the intersection vertex.  This should always succeed. */
11748   success = insertvertex(m, b, newvertex, splittri, splitsubseg, 0, 0);
11749   if (success != SUCCESSFULVERTEX) {
11750     printf("Internal error in segmentintersection():\n");
11751     printf("  Failure to split a segment.\n");
11752     internalerror();
11753   }
11754   /* Record a triangle whose origin is the new vertex. */
11755   setvertex2tri(newvertex, encode(*splittri));
11756   if (m->steinerleft > 0) {
11757     m->steinerleft--;
11758   }
11759 
11760   /* Divide the segment into two, and correct the segment endpoints. */
11761   ssymself(*splitsubseg);
11762   spivot(*splitsubseg, opposubseg);
11763   sdissolve(*splitsubseg);
11764   sdissolve(opposubseg);
11765   do {
11766     setsegorg(*splitsubseg, newvertex);
11767     snextself(*splitsubseg);
11768   } while (splitsubseg->ss != m->dummysub);
11769   do {
11770     setsegorg(opposubseg, newvertex);
11771     snextself(opposubseg);
11772   } while (opposubseg.ss != m->dummysub);
11773 
11774   /* Inserting the vertex may have caused edge flips.  We wish to rediscover */
11775   /*   the edge connecting endpoint1 to the new intersection vertex.         */
11776   collinear = finddirection(m, b, splittri, endpoint1);
11777   dest(*splittri, rightvertex);
11778   apex(*splittri, leftvertex);
11779   if ((leftvertex[0] == endpoint1[0]) && (leftvertex[1] == endpoint1[1])) {
11780     onextself(*splittri);
11781   } else if ((rightvertex[0] != endpoint1[0]) ||
11782              (rightvertex[1] != endpoint1[1])) {
11783     printf("Internal error in segmentintersection():\n");
11784     printf("  Topological inconsistency after splitting a segment.\n");
11785     internalerror();
11786   }
11787   /* `splittri' should have destination endpoint1. */
11788 }
11789 
11790 /*****************************************************************************/
11791 /*                                                                           */
11792 /*  scoutsegment()   Scout the first triangle on the path from one endpoint  */
11793 /*                   to another, and check for completion (reaching the      */
11794 /*                   second endpoint), a collinear vertex, or the            */
11795 /*                   intersection of two segments.                           */
11796 /*                                                                           */
11797 /*  Returns one if the entire segment is successfully inserted, and zero if  */
11798 /*  the job must be finished by conformingedge() or constrainededge().       */
11799 /*                                                                           */
11800 /*  If the first triangle on the path has the second endpoint as its         */
11801 /*  destination or apex, a subsegment is inserted and the job is done.       */
11802 /*                                                                           */
11803 /*  If the first triangle on the path has a destination or apex that lies on */
11804 /*  the segment, a subsegment is inserted connecting the first endpoint to   */
11805 /*  the collinear vertex, and the search is continued from the collinear     */
11806 /*  vertex.                                                                  */
11807 /*                                                                           */
11808 /*  If the first triangle on the path has a subsegment opposite its origin,  */
11809 /*  then there is a segment that intersects the segment being inserted.      */
11810 /*  Their intersection vertex is inserted, splitting the subsegment.         */
11811 /*                                                                           */
11812 /*****************************************************************************/
11813 
11814 #ifdef ANSI_DECLARATORS
11815 int scoutsegment(struct mesh *m, struct behavior *b, struct otri *searchtri,
11816                  vertex endpoint2, int newmark)
11817 #else /* not ANSI_DECLARATORS */
11818 int scoutsegment(m, b, searchtri, endpoint2, newmark)
11819 struct mesh *m;
11820 struct behavior *b;
11821 struct otri *searchtri;
11822 vertex endpoint2;
11823 int newmark;
11824 #endif /* not ANSI_DECLARATORS */
11825 
11826 {
11827   struct otri crosstri;
11828   struct osub crosssubseg;
11829   vertex leftvertex, rightvertex;
11830   enum finddirectionresult collinear;
11831   subseg sptr;                      /* Temporary variable used by tspivot(). */
11832 
11833   collinear = finddirection(m, b, searchtri, endpoint2);
11834   dest(*searchtri, rightvertex);
11835   apex(*searchtri, leftvertex);
11836   if (((leftvertex[0] == endpoint2[0]) && (leftvertex[1] == endpoint2[1])) ||
11837       ((rightvertex[0] == endpoint2[0]) && (rightvertex[1] == endpoint2[1]))) {
11838     /* The segment is already an edge in the mesh. */
11839     if ((leftvertex[0] == endpoint2[0]) && (leftvertex[1] == endpoint2[1])) {
11840       lprevself(*searchtri);
11841     }
11842     /* Insert a subsegment, if there isn't already one there. */
11843     insertsubseg(m, b, searchtri, newmark);
11844     return 1;
11845   } else if (collinear == LEFTCOLLINEAR) {
11846     /* We've collided with a vertex between the segment's endpoints. */
11847     /* Make the collinear vertex be the triangle's origin. */
11848     lprevself(*searchtri);
11849     insertsubseg(m, b, searchtri, newmark);
11850     /* Insert the remainder of the segment. */
11851     return scoutsegment(m, b, searchtri, endpoint2, newmark);
11852   } else if (collinear == RIGHTCOLLINEAR) {
11853     /* We've collided with a vertex between the segment's endpoints. */
11854     insertsubseg(m, b, searchtri, newmark);
11855     /* Make the collinear vertex be the triangle's origin. */
11856     lnextself(*searchtri);
11857     /* Insert the remainder of the segment. */
11858     return scoutsegment(m, b, searchtri, endpoint2, newmark);
11859   } else {
11860     lnext(*searchtri, crosstri);
11861     tspivot(crosstri, crosssubseg);
11862     /* Check for a crossing segment. */
11863     if (crosssubseg.ss == m->dummysub) {
11864       return 0;
11865     } else {
11866       /* Insert a vertex at the intersection. */
11867       segmentintersection(m, b, &crosstri, &crosssubseg, endpoint2);
11868       otricopy(crosstri, *searchtri);
11869       insertsubseg(m, b, searchtri, newmark);
11870       /* Insert the remainder of the segment. */
11871       return scoutsegment(m, b, searchtri, endpoint2, newmark);
11872     }
11873   }
11874 }
11875 
11876 /*****************************************************************************/
11877 /*                                                                           */
11878 /*  conformingedge()   Force a segment into a conforming Delaunay            */
11879 /*                     triangulation by inserting a vertex at its midpoint,  */
11880 /*                     and recursively forcing in the two half-segments if   */
11881 /*                     necessary.                                            */
11882 /*                                                                           */
11883 /*  Generates a sequence of subsegments connecting `endpoint1' to            */
11884 /*  `endpoint2'.  `newmark' is the boundary marker of the segment, assigned  */
11885 /*  to each new splitting vertex and subsegment.                             */
11886 /*                                                                           */
11887 /*  Note that conformingedge() does not always maintain the conforming       */
11888 /*  Delaunay property.  Once inserted, segments are locked into place;       */
11889 /*  vertices inserted later (to force other segments in) may render these    */
11890 /*  fixed segments non-Delaunay.  The conforming Delaunay property will be   */
11891 /*  restored by enforcequality() by splitting encroached subsegments.        */
11892 /*                                                                           */
11893 /*****************************************************************************/
11894 
11895 #ifndef REDUCED
11896 #ifndef CDT_ONLY
11897 
11898 #ifdef ANSI_DECLARATORS
11899 void conformingedge(struct mesh *m, struct behavior *b,
11900                     vertex endpoint1, vertex endpoint2, int newmark)
11901 #else /* not ANSI_DECLARATORS */
11902 void conformingedge(m, b, endpoint1, endpoint2, newmark)
11903 struct mesh *m;
11904 struct behavior *b;
11905 vertex endpoint1;
11906 vertex endpoint2;
11907 int newmark;
11908 #endif /* not ANSI_DECLARATORS */
11909 
11910 {
11911   struct otri searchtri1, searchtri2;
11912   struct osub brokensubseg;
11913   vertex newvertex;
11914   vertex midvertex1, midvertex2;
11915   enum insertvertexresult success;
11916   int i;
11917   subseg sptr;                      /* Temporary variable used by tspivot(). */
11918 
11919   if (b->verbose > 2) {
11920     printf("Forcing segment into triangulation by recursive splitting:\n");
11921     printf("  (%.12g, %.12g) (%.12g, %.12g)\n", endpoint1[0], endpoint1[1],
11922            endpoint2[0], endpoint2[1]);
11923   }
11924   /* Create a new vertex to insert in the middle of the segment. */
11925   newvertex = (vertex) poolalloc(&m->vertices);
11926   /* Interpolate coordinates and attributes. */
11927   for (i = 0; i < 2 + m->nextras; i++) {
11928     newvertex[i] = 0.5 * (endpoint1[i] + endpoint2[i]);
11929   }
11930   setvertexmark(newvertex, newmark);
11931   setvertextype(newvertex, SEGMENTVERTEX);
11932   /* No known triangle to search from. */
11933   searchtri1.tri = m->dummytri;
11934   /* Attempt to insert the new vertex. */
11935   success = insertvertex(m, b, newvertex, &searchtri1, (struct osub *) NULL,
11936                          0, 0);
11937   if (success == DUPLICATEVERTEX) {
11938     if (b->verbose > 2) {
11939       printf("  Segment intersects existing vertex (%.12g, %.12g).\n",
11940              newvertex[0], newvertex[1]);
11941     }
11942     /* Use the vertex that's already there. */
11943     vertexdealloc(m, newvertex);
11944     org(searchtri1, newvertex);
11945   } else {
11946     if (success == VIOLATINGVERTEX) {
11947       if (b->verbose > 2) {
11948         printf("  Two segments intersect at (%.12g, %.12g).\n",
11949                newvertex[0], newvertex[1]);
11950       }
11951       /* By fluke, we've landed right on another segment.  Split it. */
11952       tspivot(searchtri1, brokensubseg);
11953       success = insertvertex(m, b, newvertex, &searchtri1, &brokensubseg,
11954                              0, 0);
11955       if (success != SUCCESSFULVERTEX) {
11956         printf("Internal error in conformingedge():\n");
11957         printf("  Failure to split a segment.\n");
11958         internalerror();
11959       }
11960     }
11961     /* The vertex has been inserted successfully. */
11962     if (m->steinerleft > 0) {
11963       m->steinerleft--;
11964     }
11965   }
11966   otricopy(searchtri1, searchtri2);
11967   /* `searchtri1' and `searchtri2' are fastened at their origins to         */
11968   /*   `newvertex', and will be directed toward `endpoint1' and `endpoint2' */
11969   /*   respectively.  First, we must get `searchtri2' out of the way so it  */
11970   /*   won't be invalidated during the insertion of the first half of the   */
11971   /*   segment.                                                             */
11972   finddirection(m, b, &searchtri2, endpoint2);
11973   if (!scoutsegment(m, b, &searchtri1, endpoint1, newmark)) {
11974     /* The origin of searchtri1 may have changed if a collision with an */
11975     /*   intervening vertex on the segment occurred.                    */
11976     org(searchtri1, midvertex1);
11977     conformingedge(m, b, midvertex1, endpoint1, newmark);
11978   }
11979   if (!scoutsegment(m, b, &searchtri2, endpoint2, newmark)) {
11980     /* The origin of searchtri2 may have changed if a collision with an */
11981     /*   intervening vertex on the segment occurred.                    */
11982     org(searchtri2, midvertex2);
11983     conformingedge(m, b, midvertex2, endpoint2, newmark);
11984   }
11985 }
11986 
11987 #endif /* not CDT_ONLY */
11988 #endif /* not REDUCED */
11989 
11990 /*****************************************************************************/
11991 /*                                                                           */
11992 /*  delaunayfixup()   Enforce the Delaunay condition at an edge, fanning out */
11993 /*                    recursively from an existing vertex.  Pay special      */
11994 /*                    attention to stacking inverted triangles.              */
11995 /*                                                                           */
11996 /*  This is a support routine for inserting segments into a constrained      */
11997 /*  Delaunay triangulation.                                                  */
11998 /*                                                                           */
11999 /*  The origin of fixuptri is treated as if it has just been inserted, and   */
12000 /*  the local Delaunay condition needs to be enforced.  It is only enforced  */
12001 /*  in one sector, however, that being the angular range defined by          */
12002 /*  fixuptri.                                                                */
12003 /*                                                                           */
12004 /*  This routine also needs to make decisions regarding the "stacking" of    */
12005 /*  triangles.  (Read the description of constrainededge() below before      */
12006 /*  reading on here, so you understand the algorithm.)  If the position of   */
12007 /*  the new vertex (the origin of fixuptri) indicates that the vertex before */
12008 /*  it on the polygon is a reflex vertex, then "stack" the triangle by       */
12009 /*  doing nothing.  (fixuptri is an inverted triangle, which is how stacked  */
12010 /*  triangles are identified.)                                               */
12011 /*                                                                           */
12012 /*  Otherwise, check whether the vertex before that was a reflex vertex.     */
12013 /*  If so, perform an edge flip, thereby eliminating an inverted triangle    */
12014 /*  (popping it off the stack).  The edge flip may result in the creation    */
12015 /*  of a new inverted triangle, depending on whether or not the new vertex   */
12016 /*  is visible to the vertex three edges behind on the polygon.              */
12017 /*                                                                           */
12018 /*  If neither of the two vertices behind the new vertex are reflex          */
12019 /*  vertices, fixuptri and fartri, the triangle opposite it, are not         */
12020 /*  inverted; hence, ensure that the edge between them is locally Delaunay.  */
12021 /*                                                                           */
12022 /*  `leftside' indicates whether or not fixuptri is to the left of the       */
12023 /*  segment being inserted.  (Imagine that the segment is pointing up from   */
12024 /*  endpoint1 to endpoint2.)                                                 */
12025 /*                                                                           */
12026 /*****************************************************************************/
12027 
12028 #ifdef ANSI_DECLARATORS
12029 void delaunayfixup(struct mesh *m, struct behavior *b,
12030                    struct otri *fixuptri, int leftside)
12031 #else /* not ANSI_DECLARATORS */
12032 void delaunayfixup(m, b, fixuptri, leftside)
12033 struct mesh *m;
12034 struct behavior *b;
12035 struct otri *fixuptri;
12036 int leftside;
12037 #endif /* not ANSI_DECLARATORS */
12038 
12039 {
12040   struct otri neartri;
12041   struct otri fartri;
12042   struct osub faredge;
12043   vertex nearvertex, leftvertex, rightvertex, farvertex;
12044   triangle ptr;                         /* Temporary variable used by sym(). */
12045   subseg sptr;                      /* Temporary variable used by tspivot(). */
12046 
12047   lnext(*fixuptri, neartri);
12048   sym(neartri, fartri);
12049   /* Check if the edge opposite the origin of fixuptri can be flipped. */
12050   if (fartri.tri == m->dummytri) {
12051     return;
12052   }
12053   tspivot(neartri, faredge);
12054   if (faredge.ss != m->dummysub) {
12055     return;
12056   }
12057   /* Find all the relevant vertices. */
12058   apex(neartri, nearvertex);
12059   org(neartri, leftvertex);
12060   dest(neartri, rightvertex);
12061   apex(fartri, farvertex);
12062   /* Check whether the previous polygon vertex is a reflex vertex. */
12063   if (leftside) {
12064     if (counterclockwise(m, b, nearvertex, leftvertex, farvertex) <= 0.0) {
12065       /* leftvertex is a reflex vertex too.  Nothing can */
12066       /*   be done until a convex section is found.      */
12067       return;
12068     }
12069   } else {
12070     if (counterclockwise(m, b, farvertex, rightvertex, nearvertex) <= 0.0) {
12071       /* rightvertex is a reflex vertex too.  Nothing can */
12072       /*   be done until a convex section is found.       */
12073       return;
12074     }
12075   }
12076   if (counterclockwise(m, b, rightvertex, leftvertex, farvertex) > 0.0) {
12077     /* fartri is not an inverted triangle, and farvertex is not a reflex */
12078     /*   vertex.  As there are no reflex vertices, fixuptri isn't an     */
12079     /*   inverted triangle, either.  Hence, test the edge between the    */
12080     /*   triangles to ensure it is locally Delaunay.                     */
12081     if (incircle(m, b, leftvertex, farvertex, rightvertex, nearvertex) <=
12082         0.0) {
12083       return;
12084     }
12085     /* Not locally Delaunay; go on to an edge flip. */
12086   }        /* else fartri is inverted; remove it from the stack by flipping. */
12087   flip(m, b, &neartri);
12088   lprevself(*fixuptri);    /* Restore the origin of fixuptri after the flip. */
12089   /* Recursively process the two triangles that result from the flip. */
12090   delaunayfixup(m, b, fixuptri, leftside);
12091   delaunayfixup(m, b, &fartri, leftside);
12092 }
12093 
12094 /*****************************************************************************/
12095 /*                                                                           */
12096 /*  constrainededge()   Force a segment into a constrained Delaunay          */
12097 /*                      triangulation by deleting the triangles it           */
12098 /*                      intersects, and triangulating the polygons that      */
12099 /*                      form on each side of it.                             */
12100 /*                                                                           */
12101 /*  Generates a single subsegment connecting `endpoint1' to `endpoint2'.     */
12102 /*  The triangle `starttri' has `endpoint1' as its origin.  `newmark' is the */
12103 /*  boundary marker of the segment.                                          */
12104 /*                                                                           */
12105 /*  To insert a segment, every triangle whose interior intersects the        */
12106 /*  segment is deleted.  The union of these deleted triangles is a polygon   */
12107 /*  (which is not necessarily monotone, but is close enough), which is       */
12108 /*  divided into two polygons by the new segment.  This routine's task is    */
12109 /*  to generate the Delaunay triangulation of these two polygons.            */
12110 /*                                                                           */
12111 /*  You might think of this routine's behavior as a two-step process.  The   */
12112 /*  first step is to walk from endpoint1 to endpoint2, flipping each edge    */
12113 /*  encountered.  This step creates a fan of edges connected to endpoint1,   */
12114 /*  including the desired edge to endpoint2.  The second step enforces the   */
12115 /*  Delaunay condition on each side of the segment in an incremental manner: */
12116 /*  proceeding along the polygon from endpoint1 to endpoint2 (this is done   */
12117 /*  independently on each side of the segment), each vertex is "enforced"    */
12118 /*  as if it had just been inserted, but affecting only the previous         */
12119 /*  vertices.  The result is the same as if the vertices had been inserted   */
12120 /*  in the order they appear on the polygon, so the result is Delaunay.      */
12121 /*                                                                           */
12122 /*  In truth, constrainededge() interleaves these two steps.  The procedure  */
12123 /*  walks from endpoint1 to endpoint2, and each time an edge is encountered  */
12124 /*  and flipped, the newly exposed vertex (at the far end of the flipped     */
12125 /*  edge) is "enforced" upon the previously flipped edges, usually affecting */
12126 /*  only one side of the polygon (depending upon which side of the segment   */
12127 /*  the vertex falls on).                                                    */
12128 /*                                                                           */
12129 /*  The algorithm is complicated by the need to handle polygons that are not */
12130 /*  convex.  Although the polygon is not necessarily monotone, it can be     */
12131 /*  triangulated in a manner similar to the stack-based algorithms for       */
12132 /*  monotone polygons.  For each reflex vertex (local concavity) of the      */
12133 /*  polygon, there will be an inverted triangle formed by one of the edge    */
12134 /*  flips.  (An inverted triangle is one with negative area - that is, its   */
12135 /*  vertices are arranged in clockwise order - and is best thought of as a   */
12136 /*  wrinkle in the fabric of the mesh.)  Each inverted triangle can be       */
12137 /*  thought of as a reflex vertex pushed on the stack, waiting to be fixed   */
12138 /*  later.                                                                   */
12139 /*                                                                           */
12140 /*  A reflex vertex is popped from the stack when a vertex is inserted that  */
12141 /*  is visible to the reflex vertex.  (However, if the vertex behind the     */
12142 /*  reflex vertex is not visible to the reflex vertex, a new inverted        */
12143 /*  triangle will take its place on the stack.)  These details are handled   */
12144 /*  by the delaunayfixup() routine above.                                    */
12145 /*                                                                           */
12146 /*****************************************************************************/
12147 
12148 #ifdef ANSI_DECLARATORS
12149 void constrainededge(struct mesh *m, struct behavior *b,
12150                      struct otri *starttri, vertex endpoint2, int newmark)
12151 #else /* not ANSI_DECLARATORS */
12152 void constrainededge(m, b, starttri, endpoint2, newmark)
12153 struct mesh *m;
12154 struct behavior *b;
12155 struct otri *starttri;
12156 vertex endpoint2;
12157 int newmark;
12158 #endif /* not ANSI_DECLARATORS */
12159 
12160 {
12161   struct otri fixuptri, fixuptri2;
12162   struct osub crosssubseg;
12163   vertex endpoint1;
12164   vertex farvertex;
12165   REAL area;
12166   int collision;
12167   int done;
12168   triangle ptr;             /* Temporary variable used by sym() and oprev(). */
12169   subseg sptr;                      /* Temporary variable used by tspivot(). */
12170 
12171   org(*starttri, endpoint1);
12172   lnext(*starttri, fixuptri);
12173   flip(m, b, &fixuptri);
12174   /* `collision' indicates whether we have found a vertex directly */
12175   /*   between endpoint1 and endpoint2.                            */
12176   collision = 0;
12177   done = 0;
12178   do {
12179     org(fixuptri, farvertex);
12180     /* `farvertex' is the extreme point of the polygon we are "digging" */
12181     /*   to get from endpoint1 to endpoint2.                           */
12182     if ((farvertex[0] == endpoint2[0]) && (farvertex[1] == endpoint2[1])) {
12183       oprev(fixuptri, fixuptri2);
12184       /* Enforce the Delaunay condition around endpoint2. */
12185       delaunayfixup(m, b, &fixuptri, 0);
12186       delaunayfixup(m, b, &fixuptri2, 1);
12187       done = 1;
12188     } else {
12189       /* Check whether farvertex is to the left or right of the segment */
12190       /*   being inserted, to decide which edge of fixuptri to dig      */
12191       /*   through next.                                                */
12192       area = counterclockwise(m, b, endpoint1, endpoint2, farvertex);
12193       if (area == 0.0) {
12194         /* We've collided with a vertex between endpoint1 and endpoint2. */
12195         collision = 1;
12196         oprev(fixuptri, fixuptri2);
12197         /* Enforce the Delaunay condition around farvertex. */
12198         delaunayfixup(m, b, &fixuptri, 0);
12199         delaunayfixup(m, b, &fixuptri2, 1);
12200         done = 1;
12201       } else {
12202         if (area > 0.0) {        /* farvertex is to the left of the segment. */
12203           oprev(fixuptri, fixuptri2);
12204           /* Enforce the Delaunay condition around farvertex, on the */
12205           /*   left side of the segment only.                        */
12206           delaunayfixup(m, b, &fixuptri2, 1);
12207           /* Flip the edge that crosses the segment.  After the edge is */
12208           /*   flipped, one of its endpoints is the fan vertex, and the */
12209           /*   destination of fixuptri is the fan vertex.               */
12210           lprevself(fixuptri);
12211         } else {                /* farvertex is to the right of the segment. */
12212           delaunayfixup(m, b, &fixuptri, 0);
12213           /* Flip the edge that crosses the segment.  After the edge is */
12214           /*   flipped, one of its endpoints is the fan vertex, and the */
12215           /*   destination of fixuptri is the fan vertex.               */
12216           oprevself(fixuptri);
12217         }
12218         /* Check for two intersecting segments. */
12219         tspivot(fixuptri, crosssubseg);
12220         if (crosssubseg.ss == m->dummysub) {
12221           flip(m, b, &fixuptri);    /* May create inverted triangle at left. */
12222         } else {
12223           /* We've collided with a segment between endpoint1 and endpoint2. */
12224           collision = 1;
12225           /* Insert a vertex at the intersection. */
12226           segmentintersection(m, b, &fixuptri, &crosssubseg, endpoint2);
12227           done = 1;
12228         }
12229       }
12230     }
12231   } while (!done);
12232   /* Insert a subsegment to make the segment permanent. */
12233   insertsubseg(m, b, &fixuptri, newmark);
12234   /* If there was a collision with an interceding vertex, install another */
12235   /*   segment connecting that vertex with endpoint2.                     */
12236   if (collision) {
12237     /* Insert the remainder of the segment. */
12238     if (!scoutsegment(m, b, &fixuptri, endpoint2, newmark)) {
12239       constrainededge(m, b, &fixuptri, endpoint2, newmark);
12240     }
12241   }
12242 }
12243 
12244 /*****************************************************************************/
12245 /*                                                                           */
12246 /*  insertsegment()   Insert a PSLG segment into a triangulation.            */
12247 /*                                                                           */
12248 /*****************************************************************************/
12249 
12250 #ifdef ANSI_DECLARATORS
12251 void insertsegment(struct mesh *m, struct behavior *b,
12252                    vertex endpoint1, vertex endpoint2, int newmark)
12253 #else /* not ANSI_DECLARATORS */
12254 void insertsegment(m, b, endpoint1, endpoint2, newmark)
12255 struct mesh *m;
12256 struct behavior *b;
12257 vertex endpoint1;
12258 vertex endpoint2;
12259 int newmark;
12260 #endif /* not ANSI_DECLARATORS */
12261 
12262 {
12263   struct otri searchtri1, searchtri2;
12264   triangle encodedtri;
12265   vertex checkvertex;
12266   triangle ptr;                         /* Temporary variable used by sym(). */
12267 
12268   if (b->verbose > 1) {
12269     printf("  Connecting (%.12g, %.12g) to (%.12g, %.12g).\n",
12270            endpoint1[0], endpoint1[1], endpoint2[0], endpoint2[1]);
12271   }
12272 
12273   /* Find a triangle whose origin is the segment's first endpoint. */
12274   checkvertex = (vertex) NULL;
12275   encodedtri = vertex2tri(endpoint1);
12276   if (encodedtri != (triangle) NULL) {
12277     decode(encodedtri, searchtri1);
12278     org(searchtri1, checkvertex);
12279   }
12280   if (checkvertex != endpoint1) {
12281     /* Find a boundary triangle to search from. */
12282     searchtri1.tri = m->dummytri;
12283     searchtri1.orient = 0;
12284     symself(searchtri1);
12285     /* Search for the segment's first endpoint by point location. */
12286     if (locate(m, b, endpoint1, &searchtri1) != ONVERTEX) {
12287       printf(
12288         "Internal error in insertsegment():  Unable to locate PSLG vertex\n");
12289       printf("  (%.12g, %.12g) in triangulation.\n",
12290              endpoint1[0], endpoint1[1]);
12291       internalerror();
12292     }
12293   }
12294   /* Remember this triangle to improve subsequent point location. */
12295   otricopy(searchtri1, m->recenttri);
12296   /* Scout the beginnings of a path from the first endpoint */
12297   /*   toward the second.                                   */
12298   if (scoutsegment(m, b, &searchtri1, endpoint2, newmark)) {
12299     /* The segment was easily inserted. */
12300     return;
12301   }
12302   /* The first endpoint may have changed if a collision with an intervening */
12303   /*   vertex on the segment occurred.                                      */
12304   org(searchtri1, endpoint1);
12305 
12306   /* Find a triangle whose origin is the segment's second endpoint. */
12307   checkvertex = (vertex) NULL;
12308   encodedtri = vertex2tri(endpoint2);
12309   if (encodedtri != (triangle) NULL) {
12310     decode(encodedtri, searchtri2);
12311     org(searchtri2, checkvertex);
12312   }
12313   if (checkvertex != endpoint2) {
12314     /* Find a boundary triangle to search from. */
12315     searchtri2.tri = m->dummytri;
12316     searchtri2.orient = 0;
12317     symself(searchtri2);
12318     /* Search for the segment's second endpoint by point location. */
12319     if (locate(m, b, endpoint2, &searchtri2) != ONVERTEX) {
12320       printf(
12321         "Internal error in insertsegment():  Unable to locate PSLG vertex\n");
12322       printf("  (%.12g, %.12g) in triangulation.\n",
12323              endpoint2[0], endpoint2[1]);
12324       internalerror();
12325     }
12326   }
12327   /* Remember this triangle to improve subsequent point location. */
12328   otricopy(searchtri2, m->recenttri);
12329   /* Scout the beginnings of a path from the second endpoint */
12330   /*   toward the first.                                     */
12331   if (scoutsegment(m, b, &searchtri2, endpoint1, newmark)) {
12332     /* The segment was easily inserted. */
12333     return;
12334   }
12335   /* The second endpoint may have changed if a collision with an intervening */
12336   /*   vertex on the segment occurred.                                       */
12337   org(searchtri2, endpoint2);
12338 
12339 #ifndef REDUCED
12340 #ifndef CDT_ONLY
12341   if (b->splitseg) {
12342     /* Insert vertices to force the segment into the triangulation. */
12343     conformingedge(m, b, endpoint1, endpoint2, newmark);
12344   } else {
12345 #endif /* not CDT_ONLY */
12346 #endif /* not REDUCED */
12347     /* Insert the segment directly into the triangulation. */
12348     constrainededge(m, b, &searchtri1, endpoint2, newmark);
12349 #ifndef REDUCED
12350 #ifndef CDT_ONLY
12351   }
12352 #endif /* not CDT_ONLY */
12353 #endif /* not REDUCED */
12354 }
12355 
12356 /*****************************************************************************/
12357 /*                                                                           */
12358 /*  markhull()   Cover the convex hull of a triangulation with subsegments.  */
12359 /*                                                                           */
12360 /*****************************************************************************/
12361 
12362 #ifdef ANSI_DECLARATORS
12363 void markhull(struct mesh *m, struct behavior *b)
12364 #else /* not ANSI_DECLARATORS */
12365 void markhull(m, b)
12366 struct mesh *m;
12367 struct behavior *b;
12368 #endif /* not ANSI_DECLARATORS */
12369 
12370 {
12371   struct otri hulltri;
12372   struct otri nexttri;
12373   struct otri starttri;
12374   triangle ptr;             /* Temporary variable used by sym() and oprev(). */
12375 
12376   /* Find a triangle handle on the hull. */
12377   hulltri.tri = m->dummytri;
12378   hulltri.orient = 0;
12379   symself(hulltri);
12380   /* Remember where we started so we know when to stop. */
12381   otricopy(hulltri, starttri);
12382   /* Go once counterclockwise around the convex hull. */
12383   do {
12384     /* Create a subsegment if there isn't already one here. */
12385     insertsubseg(m, b, &hulltri, 1);
12386     /* To find the next hull edge, go clockwise around the next vertex. */
12387     lnextself(hulltri);
12388     oprev(hulltri, nexttri);
12389     while (nexttri.tri != m->dummytri) {
12390       otricopy(nexttri, hulltri);
12391       oprev(hulltri, nexttri);
12392     }
12393   } while (!otriequal(hulltri, starttri));
12394 }
12395 
12396 /*****************************************************************************/
12397 /*                                                                           */
12398 /*  formskeleton()   Create the segments of a triangulation, including PSLG  */
12399 /*                   segments and edges on the convex hull.                  */
12400 /*                                                                           */
12401 /*  The PSLG segments are read from a .poly file.  The return value is the   */
12402 /*  number of segments in the file.                                          */
12403 /*                                                                           */
12404 /*****************************************************************************/
12405 
12406 #ifdef TRILIBRARY
12407 
12408 #ifdef ANSI_DECLARATORS
12409 void formskeleton(struct mesh *m, struct behavior *b, int *segmentlist,
12410                   int *segmentmarkerlist, int numberofsegments)
12411 #else /* not ANSI_DECLARATORS */
12412 void formskeleton(m, b, segmentlist, segmentmarkerlist, numberofsegments)
12413 struct mesh *m;
12414 struct behavior *b;
12415 int *segmentlist;
12416 int *segmentmarkerlist;
12417 int numberofsegments;
12418 #endif /* not ANSI_DECLARATORS */
12419 
12420 #else /* not TRILIBRARY */
12421 
12422 #ifdef ANSI_DECLARATORS
12423 void formskeleton(struct mesh *m, struct behavior *b,
12424                   FILE *polyfile, char *polyfilename)
12425 #else /* not ANSI_DECLARATORS */
12426 void formskeleton(m, b, polyfile, polyfilename)
12427 struct mesh *m;
12428 struct behavior *b;
12429 FILE *polyfile;
12430 char *polyfilename;
12431 #endif /* not ANSI_DECLARATORS */
12432 
12433 #endif /* not TRILIBRARY */
12434 
12435 {
12436 #ifdef TRILIBRARY
12437   char polyfilename[6];
12438   int index;
12439 #else /* not TRILIBRARY */
12440   char inputline[INPUTLINESIZE];
12441   char *stringptr;
12442 #endif /* not TRILIBRARY */
12443   vertex endpoint1, endpoint2;
12444   int segmentmarkers;
12445   int end1, end2;
12446   int boundmarker;
12447   int i;
12448 
12449   if (b->poly) {
12450     if (!b->quiet) {
12451       printf("Recovering segments in Delaunay triangulation.\n");
12452     }
12453 #ifdef TRILIBRARY
12454     strcpy(polyfilename, "input");
12455     m->insegments = numberofsegments;
12456     segmentmarkers = segmentmarkerlist != (int *) NULL;
12457     index = 0;
12458 #else /* not TRILIBRARY */
12459     /* Read the segments from a .poly file. */
12460     /* Read number of segments and number of boundary markers. */
12461     stringptr = readline(inputline, polyfile, polyfilename);
12462     m->insegments = (int) strtol(stringptr, &stringptr, 0);
12463     stringptr = findfield(stringptr);
12464     if (*stringptr == '\0') {
12465       segmentmarkers = 0;
12466     } else {
12467       segmentmarkers = (int) strtol(stringptr, &stringptr, 0);
12468     }
12469 #endif /* not TRILIBRARY */
12470     /* If the input vertices are collinear, there is no triangulation, */
12471     /*   so don't try to insert segments.                              */
12472     if (m->triangles.items == 0) {
12473       return;
12474     }
12475 
12476     /* If segments are to be inserted, compute a mapping */
12477     /*   from vertices to triangles.                     */
12478     if (m->insegments > 0) {
12479       makevertexmap(m, b);
12480       if (b->verbose) {
12481         printf("  Recovering PSLG segments.\n");
12482       }
12483     }
12484 
12485     boundmarker = 0;
12486     /* Read and insert the segments. */
12487     for (i = 0; i < m->insegments; i++) {
12488 #ifdef TRILIBRARY
12489       end1 = segmentlist[index++];
12490       end2 = segmentlist[index++];
12491       if (segmentmarkers) {
12492         boundmarker = segmentmarkerlist[i];
12493       }
12494 #else /* not TRILIBRARY */
12495       stringptr = readline(inputline, polyfile, b->inpolyfilename);
12496       stringptr = findfield(stringptr);
12497       if (*stringptr == '\0') {
12498         printf("Error:  Segment %d has no endpoints in %s.\n",
12499                b->firstnumber + i, polyfilename);
12500         triexit(1);
12501       } else {
12502         end1 = (int) strtol(stringptr, &stringptr, 0);
12503       }
12504       stringptr = findfield(stringptr);
12505       if (*stringptr == '\0') {
12506         printf("Error:  Segment %d is missing its second endpoint in %s.\n",
12507                b->firstnumber + i, polyfilename);
12508         triexit(1);
12509       } else {
12510         end2 = (int) strtol(stringptr, &stringptr, 0);
12511       }
12512       if (segmentmarkers) {
12513         stringptr = findfield(stringptr);
12514         if (*stringptr == '\0') {
12515           boundmarker = 0;
12516         } else {
12517           boundmarker = (int) strtol(stringptr, &stringptr, 0);
12518         }
12519       }
12520 #endif /* not TRILIBRARY */
12521       if ((end1 < b->firstnumber) ||
12522           (end1 >= b->firstnumber + m->invertices)) {
12523         if (!b->quiet) {
12524           printf("Warning:  Invalid first endpoint of segment %d in %s.\n",
12525                  b->firstnumber + i, polyfilename);
12526         }
12527       } else if ((end2 < b->firstnumber) ||
12528                  (end2 >= b->firstnumber + m->invertices)) {
12529         if (!b->quiet) {
12530           printf("Warning:  Invalid second endpoint of segment %d in %s.\n",
12531                  b->firstnumber + i, polyfilename);
12532         }
12533       } else {
12534         /* Find the vertices numbered `end1' and `end2'. */
12535         endpoint1 = getvertex(m, b, end1);
12536         endpoint2 = getvertex(m, b, end2);
12537         if ((endpoint1[0] == endpoint2[0]) && (endpoint1[1] == endpoint2[1])) {
12538           if (!b->quiet) {
12539             printf("Warning:  Endpoints of segment %d are coincident in %s.\n",
12540                    b->firstnumber + i, polyfilename);
12541           }
12542         } else {
12543           insertsegment(m, b, endpoint1, endpoint2, boundmarker);
12544         }
12545       }
12546     }
12547   } else {
12548     m->insegments = 0;
12549   }
12550   if (b->convex || !b->poly) {
12551     /* Enclose the convex hull with subsegments. */
12552     if (b->verbose) {
12553       printf("  Enclosing convex hull with segments.\n");
12554     }
12555     markhull(m, b);
12556   }
12557 }
12558 
12559 /**                                                                         **/
12560 /**                                                                         **/
12561 /********* Segment insertion ends here                               *********/
12562 
12563 /********* Carving out holes and concavities begins here             *********/
12564 /**                                                                         **/
12565 /**                                                                         **/
12566 
12567 /*****************************************************************************/
12568 /*                                                                           */
12569 /*  infecthull()   Virally infect all of the triangles of the convex hull    */
12570 /*                 that are not protected by subsegments.  Where there are   */
12571 /*                 subsegments, set boundary markers as appropriate.         */
12572 /*                                                                           */
12573 /*****************************************************************************/
12574 
12575 #ifdef ANSI_DECLARATORS
12576 void infecthull(struct mesh *m, struct behavior *b)
12577 #else /* not ANSI_DECLARATORS */
12578 void infecthull(m, b)
12579 struct mesh *m;
12580 struct behavior *b;
12581 #endif /* not ANSI_DECLARATORS */
12582 
12583 {
12584   struct otri hulltri;
12585   struct otri nexttri;
12586   struct otri starttri;
12587   struct osub hullsubseg;
12588   triangle **deadtriangle;
12589   vertex horg, hdest;
12590   triangle ptr;                         /* Temporary variable used by sym(). */
12591   subseg sptr;                      /* Temporary variable used by tspivot(). */
12592 
12593   if (b->verbose) {
12594     printf("  Marking concavities (external triangles) for elimination.\n");
12595   }
12596   /* Find a triangle handle on the hull. */
12597   hulltri.tri = m->dummytri;
12598   hulltri.orient = 0;
12599   symself(hulltri);
12600   /* Remember where we started so we know when to stop. */
12601   otricopy(hulltri, starttri);
12602   /* Go once counterclockwise around the convex hull. */
12603   do {
12604     /* Ignore triangles that are already infected. */
12605     if (!infected(hulltri)) {
12606       /* Is the triangle protected by a subsegment? */
12607       tspivot(hulltri, hullsubseg);
12608       if (hullsubseg.ss == m->dummysub) {
12609         /* The triangle is not protected; infect it. */
12610         if (!infected(hulltri)) {
12611           infect(hulltri);
12612           deadtriangle = (triangle **) poolalloc(&m->viri);
12613           *deadtriangle = hulltri.tri;
12614         }
12615       } else {
12616         /* The triangle is protected; set boundary markers if appropriate. */
12617         if (mark(hullsubseg) == 0) {
12618           setmark(hullsubseg, 1);
12619           org(hulltri, horg);
12620           dest(hulltri, hdest);
12621           if (vertexmark(horg) == 0) {
12622             setvertexmark(horg, 1);
12623           }
12624           if (vertexmark(hdest) == 0) {
12625             setvertexmark(hdest, 1);
12626           }
12627         }
12628       }
12629     }
12630     /* To find the next hull edge, go clockwise around the next vertex. */
12631     lnextself(hulltri);
12632     oprev(hulltri, nexttri);
12633     while (nexttri.tri != m->dummytri) {
12634       otricopy(nexttri, hulltri);
12635       oprev(hulltri, nexttri);
12636     }
12637   } while (!otriequal(hulltri, starttri));
12638 }
12639 
12640 /*****************************************************************************/
12641 /*                                                                           */
12642 /*  plague()   Spread the virus from all infected triangles to any neighbors */
12643 /*             not protected by subsegments.  Delete all infected triangles. */
12644 /*                                                                           */
12645 /*  This is the procedure that actually creates holes and concavities.       */
12646 /*                                                                           */
12647 /*  This procedure operates in two phases.  The first phase identifies all   */
12648 /*  the triangles that will die, and marks them as infected.  They are       */
12649 /*  marked to ensure that each triangle is added to the virus pool only      */
12650 /*  once, so the procedure will terminate.                                   */
12651 /*                                                                           */
12652 /*  The second phase actually eliminates the infected triangles.  It also    */
12653 /*  eliminates orphaned vertices.                                            */
12654 /*                                                                           */
12655 /*****************************************************************************/
12656 
12657 #ifdef ANSI_DECLARATORS
12658 void plague(struct mesh *m, struct behavior *b)
12659 #else /* not ANSI_DECLARATORS */
12660 void plague(m, b)
12661 struct mesh *m;
12662 struct behavior *b;
12663 #endif /* not ANSI_DECLARATORS */
12664 
12665 {
12666   struct otri testtri;
12667   struct otri neighbor;
12668   triangle **virusloop;
12669   triangle **deadtriangle;
12670   struct osub neighborsubseg;
12671   vertex testvertex;
12672   vertex norg, ndest;
12673   vertex deadorg, deaddest, deadapex;
12674   int killorg;
12675   triangle ptr;             /* Temporary variable used by sym() and onext(). */
12676   subseg sptr;                      /* Temporary variable used by tspivot(). */
12677 
12678   if (b->verbose) {
12679     printf("  Marking neighbors of marked triangles.\n");
12680   }
12681   /* Loop through all the infected triangles, spreading the virus to */
12682   /*   their neighbors, then to their neighbors' neighbors.          */
12683   traversalinit(&m->viri);
12684   virusloop = (triangle **) traverse(&m->viri);
12685   while (virusloop != (triangle **) NULL) {
12686     testtri.tri = *virusloop;
12687     /* A triangle is marked as infected by messing with one of its pointers */
12688     /*   to subsegments, setting it to an illegal value.  Hence, we have to */
12689     /*   temporarily uninfect this triangle so that we can examine its      */
12690     /*   adjacent subsegments.                                              */
12691     uninfect(testtri);
12692     if (b->verbose > 2) {
12693       /* Assign the triangle an orientation for convenience in */
12694       /*   checking its vertices.                              */
12695       testtri.orient = 0;
12696       org(testtri, deadorg);
12697       dest(testtri, deaddest);
12698       apex(testtri, deadapex);
12699       printf("    Checking (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
12700              deadorg[0], deadorg[1], deaddest[0], deaddest[1],
12701              deadapex[0], deadapex[1]);
12702     }
12703     /* Check each of the triangle's three neighbors. */
12704     for (testtri.orient = 0; testtri.orient < 3; testtri.orient++) {
12705       /* Find the neighbor. */
12706       sym(testtri, neighbor);
12707       /* Check for a subsegment between the triangle and its neighbor. */
12708       tspivot(testtri, neighborsubseg);
12709       /* Check if the neighbor is nonexistent or already infected. */
12710       if ((neighbor.tri == m->dummytri) || infected(neighbor)) {
12711         if (neighborsubseg.ss != m->dummysub) {
12712           /* There is a subsegment separating the triangle from its      */
12713           /*   neighbor, but both triangles are dying, so the subsegment */
12714           /*   dies too.                                                 */
12715           subsegdealloc(m, neighborsubseg.ss);
12716           if (neighbor.tri != m->dummytri) {
12717             /* Make sure the subsegment doesn't get deallocated again */
12718             /*   later when the infected neighbor is visited.         */
12719             uninfect(neighbor);
12720             tsdissolve(neighbor);
12721             infect(neighbor);
12722           }
12723         }
12724       } else {                   /* The neighbor exists and is not infected. */
12725         if (neighborsubseg.ss == m->dummysub) {
12726           /* There is no subsegment protecting the neighbor, so */
12727           /*   the neighbor becomes infected.                   */
12728           if (b->verbose > 2) {
12729             org(neighbor, deadorg);
12730             dest(neighbor, deaddest);
12731             apex(neighbor, deadapex);
12732             printf(
12733               "    Marking (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
12734                    deadorg[0], deadorg[1], deaddest[0], deaddest[1],
12735                    deadapex[0], deadapex[1]);
12736           }
12737           infect(neighbor);
12738           /* Ensure that the neighbor's neighbors will be infected. */
12739           deadtriangle = (triangle **) poolalloc(&m->viri);
12740           *deadtriangle = neighbor.tri;
12741         } else {               /* The neighbor is protected by a subsegment. */
12742           /* Remove this triangle from the subsegment. */
12743           stdissolve(neighborsubseg);
12744           /* The subsegment becomes a boundary.  Set markers accordingly. */
12745           if (mark(neighborsubseg) == 0) {
12746             setmark(neighborsubseg, 1);
12747           }
12748           org(neighbor, norg);
12749           dest(neighbor, ndest);
12750           if (vertexmark(norg) == 0) {
12751             setvertexmark(norg, 1);
12752           }
12753           if (vertexmark(ndest) == 0) {
12754             setvertexmark(ndest, 1);
12755           }
12756         }
12757       }
12758     }
12759     /* Remark the triangle as infected, so it doesn't get added to the */
12760     /*   virus pool again.                                             */
12761     infect(testtri);
12762     virusloop = (triangle **) traverse(&m->viri);
12763   }
12764 
12765   if (b->verbose) {
12766     printf("  Deleting marked triangles.\n");
12767   }
12768 
12769   traversalinit(&m->viri);
12770   virusloop = (triangle **) traverse(&m->viri);
12771   while (virusloop != (triangle **) NULL) {
12772     testtri.tri = *virusloop;
12773 
12774     /* Check each of the three corners of the triangle for elimination. */
12775     /*   This is done by walking around each vertex, checking if it is  */
12776     /*   still connected to at least one live triangle.                 */
12777     for (testtri.orient = 0; testtri.orient < 3; testtri.orient++) {
12778       org(testtri, testvertex);
12779       /* Check if the vertex has already been tested. */
12780       if (testvertex != (vertex) NULL) {
12781         killorg = 1;
12782         /* Mark the corner of the triangle as having been tested. */
12783         setorg(testtri, NULL);
12784         /* Walk counterclockwise about the vertex. */
12785         onext(testtri, neighbor);
12786         /* Stop upon reaching a boundary or the starting triangle. */
12787         while ((neighbor.tri != m->dummytri) &&
12788                (!otriequal(neighbor, testtri))) {
12789           if (infected(neighbor)) {
12790             /* Mark the corner of this triangle as having been tested. */
12791             setorg(neighbor, NULL);
12792           } else {
12793             /* A live triangle.  The vertex survives. */
12794             killorg = 0;
12795           }
12796           /* Walk counterclockwise about the vertex. */
12797           onextself(neighbor);
12798         }
12799         /* If we reached a boundary, we must walk clockwise as well. */
12800         if (neighbor.tri == m->dummytri) {
12801           /* Walk clockwise about the vertex. */
12802           oprev(testtri, neighbor);
12803           /* Stop upon reaching a boundary. */
12804           while (neighbor.tri != m->dummytri) {
12805             if (infected(neighbor)) {
12806             /* Mark the corner of this triangle as having been tested. */
12807               setorg(neighbor, NULL);
12808             } else {
12809               /* A live triangle.  The vertex survives. */
12810               killorg = 0;
12811             }
12812             /* Walk clockwise about the vertex. */
12813             oprevself(neighbor);
12814           }
12815         }
12816         if (killorg) {
12817           if (b->verbose > 1) {
12818             printf("    Deleting vertex (%.12g, %.12g)\n",
12819                    testvertex[0], testvertex[1]);
12820           }
12821           setvertextype(testvertex, UNDEADVERTEX);
12822           m->undeads++;
12823         }
12824       }
12825     }
12826 
12827     /* Record changes in the number of boundary edges, and disconnect */
12828     /*   dead triangles from their neighbors.                         */
12829     for (testtri.orient = 0; testtri.orient < 3; testtri.orient++) {
12830       sym(testtri, neighbor);
12831       if (neighbor.tri == m->dummytri) {
12832         /* There is no neighboring triangle on this edge, so this edge    */
12833         /*   is a boundary edge.  This triangle is being deleted, so this */
12834         /*   boundary edge is deleted.                                    */
12835         m->hullsize--;
12836       } else {
12837         /* Disconnect the triangle from its neighbor. */
12838         dissolve(neighbor);
12839         /* There is a neighboring triangle on this edge, so this edge */
12840         /*   becomes a boundary edge when this triangle is deleted.   */
12841         m->hullsize++;
12842       }
12843     }
12844     /* Return the dead triangle to the pool of triangles. */
12845     triangledealloc(m, testtri.tri);
12846     virusloop = (triangle **) traverse(&m->viri);
12847   }
12848   /* Empty the virus pool. */
12849   poolrestart(&m->viri);
12850 }
12851 
12852 /*****************************************************************************/
12853 /*                                                                           */
12854 /*  regionplague()   Spread regional attributes and/or area constraints      */
12855 /*                   (from a .poly file) throughout the mesh.                */
12856 /*                                                                           */
12857 /*  This procedure operates in two phases.  The first phase spreads an       */
12858 /*  attribute and/or an area constraint through a (segment-bounded) region.  */
12859 /*  The triangles are marked to ensure that each triangle is added to the    */
12860 /*  virus pool only once, so the procedure will terminate.                   */
12861 /*                                                                           */
12862 /*  The second phase uninfects all infected triangles, returning them to     */
12863 /*  normal.                                                                  */
12864 /*                                                                           */
12865 /*****************************************************************************/
12866 
12867 #ifdef ANSI_DECLARATORS
12868 void regionplague(struct mesh *m, struct behavior *b,
12869                   REAL attribute, REAL area)
12870 #else /* not ANSI_DECLARATORS */
12871 void regionplague(m, b, attribute, area)
12872 struct mesh *m;
12873 struct behavior *b;
12874 REAL attribute;
12875 REAL area;
12876 #endif /* not ANSI_DECLARATORS */
12877 
12878 {
12879   struct otri testtri;
12880   struct otri neighbor;
12881   triangle **virusloop;
12882   triangle **regiontri;
12883   struct osub neighborsubseg;
12884   vertex regionorg, regiondest, regionapex;
12885   triangle ptr;             /* Temporary variable used by sym() and onext(). */
12886   subseg sptr;                      /* Temporary variable used by tspivot(). */
12887 
12888   if (b->verbose > 1) {
12889     printf("  Marking neighbors of marked triangles.\n");
12890   }
12891   /* Loop through all the infected triangles, spreading the attribute      */
12892   /*   and/or area constraint to their neighbors, then to their neighbors' */
12893   /*   neighbors.                                                          */
12894   traversalinit(&m->viri);
12895   virusloop = (triangle **) traverse(&m->viri);
12896   while (virusloop != (triangle **) NULL) {
12897     testtri.tri = *virusloop;
12898     /* A triangle is marked as infected by messing with one of its pointers */
12899     /*   to subsegments, setting it to an illegal value.  Hence, we have to */
12900     /*   temporarily uninfect this triangle so that we can examine its      */
12901     /*   adjacent subsegments.                                              */
12902     uninfect(testtri);
12903     if (b->regionattrib) {
12904       /* Set an attribute. */
12905       setelemattribute(testtri, m->eextras, attribute);
12906     }
12907     if (b->vararea) {
12908       /* Set an area constraint. */
12909       setareabound(testtri, area);
12910     }
12911     if (b->verbose > 2) {
12912       /* Assign the triangle an orientation for convenience in */
12913       /*   checking its vertices.                              */
12914       testtri.orient = 0;
12915       org(testtri, regionorg);
12916       dest(testtri, regiondest);
12917       apex(testtri, regionapex);
12918       printf("    Checking (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
12919              regionorg[0], regionorg[1], regiondest[0], regiondest[1],
12920              regionapex[0], regionapex[1]);
12921     }
12922     /* Check each of the triangle's three neighbors. */
12923     for (testtri.orient = 0; testtri.orient < 3; testtri.orient++) {
12924       /* Find the neighbor. */
12925       sym(testtri, neighbor);
12926       /* Check for a subsegment between the triangle and its neighbor. */
12927       tspivot(testtri, neighborsubseg);
12928       /* Make sure the neighbor exists, is not already infected, and */
12929       /*   isn't protected by a subsegment.                          */
12930       if ((neighbor.tri != m->dummytri) && !infected(neighbor)
12931           && (neighborsubseg.ss == m->dummysub)) {
12932         if (b->verbose > 2) {
12933           org(neighbor, regionorg);
12934           dest(neighbor, regiondest);
12935           apex(neighbor, regionapex);
12936           printf("    Marking (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
12937                  regionorg[0], regionorg[1], regiondest[0], regiondest[1],
12938                  regionapex[0], regionapex[1]);
12939         }
12940         /* Infect the neighbor. */
12941         infect(neighbor);
12942         /* Ensure that the neighbor's neighbors will be infected. */
12943         regiontri = (triangle **) poolalloc(&m->viri);
12944         *regiontri = neighbor.tri;
12945       }
12946     }
12947     /* Remark the triangle as infected, so it doesn't get added to the */
12948     /*   virus pool again.                                             */
12949     infect(testtri);
12950     virusloop = (triangle **) traverse(&m->viri);
12951   }
12952 
12953   /* Uninfect all triangles. */
12954   if (b->verbose > 1) {
12955     printf("  Unmarking marked triangles.\n");
12956   }
12957   traversalinit(&m->viri);
12958   virusloop = (triangle **) traverse(&m->viri);
12959   while (virusloop != (triangle **) NULL) {
12960     testtri.tri = *virusloop;
12961     uninfect(testtri);
12962     virusloop = (triangle **) traverse(&m->viri);
12963   }
12964   /* Empty the virus pool. */
12965   poolrestart(&m->viri);
12966 }
12967 
12968 /*****************************************************************************/
12969 /*                                                                           */
12970 /*  carveholes()   Find the holes and infect them.  Find the area            */
12971 /*                 constraints and infect them.  Infect the convex hull.     */
12972 /*                 Spread the infection and kill triangles.  Spread the      */
12973 /*                 area constraints.                                         */
12974 /*                                                                           */
12975 /*  This routine mainly calls other routines to carry out all these          */
12976 /*  functions.                                                               */
12977 /*                                                                           */
12978 /*****************************************************************************/
12979 
12980 #ifdef ANSI_DECLARATORS
12981 void carveholes(struct mesh *m, struct behavior *b, REAL *holelist, int holes,
12982                 REAL *regionlist, int regions)
12983 #else /* not ANSI_DECLARATORS */
12984 void carveholes(m, b, holelist, holes, regionlist, regions)
12985 struct mesh *m;
12986 struct behavior *b;
12987 REAL *holelist;
12988 int holes;
12989 REAL *regionlist;
12990 int regions;
12991 #endif /* not ANSI_DECLARATORS */
12992 
12993 {
12994   struct otri searchtri;
12995   struct otri triangleloop;
12996   struct otri *regiontris;
12997   triangle **holetri;
12998   triangle **regiontri;
12999   vertex searchorg, searchdest;
13000   enum locateresult intersect;
13001   int i;
13002   triangle ptr;                         /* Temporary variable used by sym(). */
13003 
13004   if (!(b->quiet || (b->noholes && b->convex))) {
13005     printf("Removing unwanted triangles.\n");
13006     if (b->verbose && (holes > 0)) {
13007       printf("  Marking holes for elimination.\n");
13008     }
13009   }
13010 
13011   if (regions > 0) {
13012     /* Allocate storage for the triangles in which region points fall. */
13013     regiontris = (struct otri *) trimalloc(regions *
13014                                            (int) sizeof(struct otri));
13015   } else {
13016     regiontris = (struct otri *) NULL;
13017   }
13018 
13019   if (((holes > 0) && !b->noholes) || !b->convex || (regions > 0)) {
13020     /* Initialize a pool of viri to be used for holes, concavities, */
13021     /*   regional attributes, and/or regional area constraints.     */
13022     poolinit(&m->viri, sizeof(triangle *), VIRUSPERBLOCK, VIRUSPERBLOCK, 0);
13023   }
13024 
13025   if (!b->convex) {
13026     /* Mark as infected any unprotected triangles on the boundary. */
13027     /*   This is one way by which concavities are created.         */
13028     infecthull(m, b);
13029   }
13030 
13031   if ((holes > 0) && !b->noholes) {
13032     /* Infect each triangle in which a hole lies. */
13033     for (i = 0; i < 2 * holes; i += 2) {
13034       /* Ignore holes that aren't within the bounds of the mesh. */
13035       if ((holelist[i] >= m->xmin) && (holelist[i] <= m->xmax)
13036           && (holelist[i + 1] >= m->ymin) && (holelist[i + 1] <= m->ymax)) {
13037         /* Start searching from some triangle on the outer boundary. */
13038         searchtri.tri = m->dummytri;
13039         searchtri.orient = 0;
13040         symself(searchtri);
13041         /* Ensure that the hole is to the left of this boundary edge; */
13042         /*   otherwise, locate() will falsely report that the hole    */
13043         /*   falls within the starting triangle.                      */
13044         org(searchtri, searchorg);
13045         dest(searchtri, searchdest);
13046         if (counterclockwise(m, b, searchorg, searchdest, &holelist[i]) >
13047             0.0) {
13048           /* Find a triangle that contains the hole. */
13049           intersect = locate(m, b, &holelist[i], &searchtri);
13050           if ((intersect != OUTSIDE) && (!infected(searchtri))) {
13051             /* Infect the triangle.  This is done by marking the triangle  */
13052             /*   as infected and including the triangle in the virus pool. */
13053             infect(searchtri);
13054             holetri = (triangle **) poolalloc(&m->viri);
13055             *holetri = searchtri.tri;
13056           }
13057         }
13058       }
13059     }
13060   }
13061 
13062   /* Now, we have to find all the regions BEFORE we carve the holes, because */
13063   /*   locate() won't work when the triangulation is no longer convex.       */
13064   /*   (Incidentally, this is the reason why regional attributes and area    */
13065   /*   constraints can't be used when refining a preexisting mesh, which     */
13066   /*   might not be convex; they can only be used with a freshly             */
13067   /*   triangulated PSLG.)                                                   */
13068   if (regions > 0) {
13069     /* Find the starting triangle for each region. */
13070     for (i = 0; i < regions; i++) {
13071       regiontris[i].tri = m->dummytri;
13072       /* Ignore region points that aren't within the bounds of the mesh. */
13073       if ((regionlist[4 * i] >= m->xmin) && (regionlist[4 * i] <= m->xmax) &&
13074           (regionlist[4 * i + 1] >= m->ymin) &&
13075           (regionlist[4 * i + 1] <= m->ymax)) {
13076         /* Start searching from some triangle on the outer boundary. */
13077         searchtri.tri = m->dummytri;
13078         searchtri.orient = 0;
13079         symself(searchtri);
13080         /* Ensure that the region point is to the left of this boundary */
13081         /*   edge; otherwise, locate() will falsely report that the     */
13082         /*   region point falls within the starting triangle.           */
13083         org(searchtri, searchorg);
13084         dest(searchtri, searchdest);
13085         if (counterclockwise(m, b, searchorg, searchdest, &regionlist[4 * i]) >
13086             0.0) {
13087           /* Find a triangle that contains the region point. */
13088           intersect = locate(m, b, &regionlist[4 * i], &searchtri);
13089           if ((intersect != OUTSIDE) && (!infected(searchtri))) {
13090             /* Record the triangle for processing after the */
13091             /*   holes have been carved.                    */
13092             otricopy(searchtri, regiontris[i]);
13093           }
13094         }
13095       }
13096     }
13097   }
13098 
13099   if (m->viri.items > 0) {
13100     /* Carve the holes and concavities. */
13101     plague(m, b);
13102   }
13103   /* The virus pool should be empty now. */
13104 
13105   if (regions > 0) {
13106     if (!b->quiet) {
13107       if (b->regionattrib) {
13108         if (b->vararea) {
13109           printf("Spreading regional attributes and area constraints.\n");
13110         } else {
13111           printf("Spreading regional attributes.\n");
13112         }
13113       } else {
13114         printf("Spreading regional area constraints.\n");
13115       }
13116     }
13117     if (b->regionattrib && !b->refine) {
13118       /* Assign every triangle a regional attribute of zero. */
13119       traversalinit(&m->triangles);
13120       triangleloop.orient = 0;
13121       triangleloop.tri = triangletraverse(m);
13122       while (triangleloop.tri != (triangle *) NULL) {
13123         setelemattribute(triangleloop, m->eextras, 0.0);
13124         triangleloop.tri = triangletraverse(m);
13125       }
13126     }
13127     for (i = 0; i < regions; i++) {
13128       if (regiontris[i].tri != m->dummytri) {
13129         /* Make sure the triangle under consideration still exists. */
13130         /*   It may have been eaten by the virus.                   */
13131         if (!deadtri(regiontris[i].tri)) {
13132           /* Put one triangle in the virus pool. */
13133           infect(regiontris[i]);
13134           regiontri = (triangle **) poolalloc(&m->viri);
13135           *regiontri = regiontris[i].tri;
13136           /* Apply one region's attribute and/or area constraint. */
13137           regionplague(m, b, regionlist[4 * i + 2], regionlist[4 * i + 3]);
13138           /* The virus pool should be empty now. */
13139         }
13140       }
13141     }
13142     if (b->regionattrib && !b->refine) {
13143       /* Note the fact that each triangle has an additional attribute. */
13144       m->eextras++;
13145     }
13146   }
13147 
13148   /* Free up memory. */
13149   if (((holes > 0) && !b->noholes) || !b->convex || (regions > 0)) {
13150     pooldeinit(&m->viri);
13151   }
13152   if (regions > 0) {
13153     trifree((VOID *) regiontris);
13154   }
13155 }
13156 
13157 /**                                                                         **/
13158 /**                                                                         **/
13159 /********* Carving out holes and concavities ends here               *********/
13160 
13161 /********* Mesh quality maintenance begins here                      *********/
13162 /**                                                                         **/
13163 /**                                                                         **/
13164 
13165 /*****************************************************************************/
13166 /*                                                                           */
13167 /*  tallyencs()   Traverse the entire list of subsegments, and check each    */
13168 /*                to see if it is encroached.  If so, add it to the list.    */
13169 /*                                                                           */
13170 /*****************************************************************************/
13171 
13172 #ifndef CDT_ONLY
13173 
13174 #ifdef ANSI_DECLARATORS
13175 void tallyencs(struct mesh *m, struct behavior *b)
13176 #else /* not ANSI_DECLARATORS */
13177 void tallyencs(m, b)
13178 struct mesh *m;
13179 struct behavior *b;
13180 #endif /* not ANSI_DECLARATORS */
13181 
13182 {
13183   struct osub subsegloop;
13184   int dummy;
13185 
13186   traversalinit(&m->subsegs);
13187   subsegloop.ssorient = 0;
13188   subsegloop.ss = subsegtraverse(m);
13189   while (subsegloop.ss != (subseg *) NULL) {
13190     /* If the segment is encroached, add it to the list. */
13191     dummy = checkseg4encroach(m, b, &subsegloop);
13192     subsegloop.ss = subsegtraverse(m);
13193   }
13194 }
13195 
13196 #endif /* not CDT_ONLY */
13197 
13198 /*****************************************************************************/
13199 /*                                                                           */
13200 /*  precisionerror()  Print an error message for precision problems.         */
13201 /*                                                                           */
13202 /*****************************************************************************/
13203 
13204 #ifndef CDT_ONLY
13205 
13206 void precisionerror()
13207 {
13208   printf("Try increasing the area criterion and/or reducing the minimum\n");
13209   printf("  allowable angle so that tiny triangles are not created.\n");
13210 #ifdef SINGLE
13211   printf("Alternatively, try recompiling me with double precision\n");
13212   printf("  arithmetic (by removing \"#define SINGLE\" from the\n");
13213   printf("  source file or \"-DSINGLE\" from the makefile).\n");
13214 #endif /* SINGLE */
13215 }
13216 
13217 #endif /* not CDT_ONLY */
13218 
13219 /*****************************************************************************/
13220 /*                                                                           */
13221 /*  splitencsegs()   Split all the encroached subsegments.                   */
13222 /*                                                                           */
13223 /*  Each encroached subsegment is repaired by splitting it - inserting a     */
13224 /*  vertex at or near its midpoint.  Newly inserted vertices may encroach    */
13225 /*  upon other subsegments; these are also repaired.                         */
13226 /*                                                                           */
13227 /*  `triflaws' is a flag that specifies whether one should take note of new  */
13228 /*  bad triangles that result from inserting vertices to repair encroached   */
13229 /*  subsegments.                                                             */
13230 /*                                                                           */
13231 /*****************************************************************************/
13232 
13233 #ifndef CDT_ONLY
13234 
13235 #ifdef ANSI_DECLARATORS
13236 void splitencsegs(struct mesh *m, struct behavior *b, int triflaws)
13237 #else /* not ANSI_DECLARATORS */
13238 void splitencsegs(m, b, triflaws)
13239 struct mesh *m;
13240 struct behavior *b;
13241 int triflaws;
13242 #endif /* not ANSI_DECLARATORS */
13243 
13244 {
13245   struct otri enctri;
13246   struct otri testtri;
13247   struct osub testsh;
13248   struct osub currentenc;
13249   struct badsubseg *encloop;
13250   vertex eorg, edest, eapex;
13251   vertex newvertex;
13252   enum insertvertexresult success;
13253   REAL segmentlength, nearestpoweroftwo;
13254   REAL split;
13255   REAL multiplier, divisor;
13256   int acuteorg, acuteorg2, acutedest, acutedest2;
13257   int dummy;
13258   int i;
13259   triangle ptr;                     /* Temporary variable used by stpivot(). */
13260   subseg sptr;                        /* Temporary variable used by snext(). */
13261 
13262   /* Note that steinerleft == -1 if an unlimited number */
13263   /*   of Steiner points is allowed.                    */
13264   while ((m->badsubsegs.items > 0) && (m->steinerleft != 0)) {
13265     traversalinit(&m->badsubsegs);
13266     encloop = badsubsegtraverse(m);
13267     while ((encloop != (struct badsubseg *) NULL) && (m->steinerleft != 0)) {
13268       sdecode(encloop->encsubseg, currentenc);
13269       sorg(currentenc, eorg);
13270       sdest(currentenc, edest);
13271       /* Make sure that this segment is still the same segment it was   */
13272       /*   when it was determined to be encroached.  If the segment was */
13273       /*   enqueued multiple times (because several newly inserted      */
13274       /*   vertices encroached it), it may have already been split.     */
13275       if (!deadsubseg(currentenc.ss) &&
13276           (eorg == encloop->subsegorg) && (edest == encloop->subsegdest)) {
13277         /* To decide where to split a segment, we need to know if the   */
13278         /*   segment shares an endpoint with an adjacent segment.       */
13279         /*   The concern is that, if we simply split every encroached   */
13280         /*   segment in its center, two adjacent segments with a small  */
13281         /*   angle between them might lead to an infinite loop; each    */
13282         /*   vertex added to split one segment will encroach upon the   */
13283         /*   other segment, which must then be split with a vertex that */
13284         /*   will encroach upon the first segment, and so on forever.   */
13285         /* To avoid this, imagine a set of concentric circles, whose    */
13286         /*   radii are powers of two, about each segment endpoint.      */
13287         /*   These concentric circles determine where the segment is    */
13288         /*   split.  (If both endpoints are shared with adjacent        */
13289         /*   segments, split the segment in the middle, and apply the   */
13290         /*   concentric circles for later splittings.)                  */
13291 
13292         /* Is the origin shared with another segment? */
13293         stpivot(currentenc, enctri);
13294         lnext(enctri, testtri);
13295         tspivot(testtri, testsh);
13296         acuteorg = testsh.ss != m->dummysub;
13297         /* Is the destination shared with another segment? */
13298         lnextself(testtri);
13299         tspivot(testtri, testsh);
13300         acutedest = testsh.ss != m->dummysub;
13301 
13302         /* If we're using Chew's algorithm (rather than Ruppert's) */
13303         /*   to define encroachment, delete free vertices from the */
13304         /*   subsegment's diametral circle.                        */
13305         if (!b->conformdel && !acuteorg && !acutedest) {
13306           apex(enctri, eapex);
13307           while ((vertextype(eapex) == FREEVERTEX) &&
13308                  ((eorg[0] - eapex[0]) * (edest[0] - eapex[0]) +
13309                   (eorg[1] - eapex[1]) * (edest[1] - eapex[1]) < 0.0)) {
13310             deletevertex(m, b, &testtri);
13311             stpivot(currentenc, enctri);
13312             apex(enctri, eapex);
13313             lprev(enctri, testtri);
13314           }
13315         }
13316 
13317         /* Now, check the other side of the segment, if there's a triangle */
13318         /*   there.                                                        */
13319         sym(enctri, testtri);
13320         if (testtri.tri != m->dummytri) {
13321           /* Is the destination shared with another segment? */
13322           lnextself(testtri);
13323           tspivot(testtri, testsh);
13324           acutedest2 = testsh.ss != m->dummysub;
13325           acutedest = acutedest || acutedest2;
13326           /* Is the origin shared with another segment? */
13327           lnextself(testtri);
13328           tspivot(testtri, testsh);
13329           acuteorg2 = testsh.ss != m->dummysub;
13330           acuteorg = acuteorg || acuteorg2;
13331 
13332           /* Delete free vertices from the subsegment's diametral circle. */
13333           if (!b->conformdel && !acuteorg2 && !acutedest2) {
13334             org(testtri, eapex);
13335             while ((vertextype(eapex) == FREEVERTEX) &&
13336                    ((eorg[0] - eapex[0]) * (edest[0] - eapex[0]) +
13337                     (eorg[1] - eapex[1]) * (edest[1] - eapex[1]) < 0.0)) {
13338               deletevertex(m, b, &testtri);
13339               sym(enctri, testtri);
13340               apex(testtri, eapex);
13341               lprevself(testtri);
13342             }
13343           }
13344         }
13345 
13346         /* Use the concentric circles if exactly one endpoint is shared */
13347         /*   with another adjacent segment.                             */
13348         if (acuteorg || acutedest) {
13349           segmentlength = sqrt((edest[0] - eorg[0]) * (edest[0] - eorg[0]) +
13350                                (edest[1] - eorg[1]) * (edest[1] - eorg[1]));
13351           /* Find the power of two that most evenly splits the segment.  */
13352           /*   The worst case is a 2:1 ratio between subsegment lengths. */
13353           nearestpoweroftwo = 1.0;
13354           while (segmentlength > 3.0 * nearestpoweroftwo) {
13355             nearestpoweroftwo *= 2.0;
13356           }
13357           while (segmentlength < 1.5 * nearestpoweroftwo) {
13358             nearestpoweroftwo *= 0.5;
13359           }
13360           /* Where do we split the segment? */
13361           split = nearestpoweroftwo / segmentlength;
13362           if (acutedest) {
13363             split = 1.0 - split;
13364           }
13365         } else {
13366           /* If we're not worried about adjacent segments, split */
13367           /*   this segment in the middle.                       */
13368           split = 0.5;
13369         }
13370 
13371         /* Create the new vertex. */
13372         newvertex = (vertex) poolalloc(&m->vertices);
13373         /* Interpolate its coordinate and attributes. */
13374         for (i = 0; i < 2 + m->nextras; i++) {
13375           newvertex[i] = eorg[i] + split * (edest[i] - eorg[i]);
13376         }
13377 
13378         if (!b->noexact) {
13379           /* Roundoff in the above calculation may yield a `newvertex'   */
13380           /*   that is not precisely collinear with `eorg' and `edest'.  */
13381           /*   Improve collinearity by one step of iterative refinement. */
13382           multiplier = counterclockwise(m, b, eorg, edest, newvertex);
13383           divisor = ((eorg[0] - edest[0]) * (eorg[0] - edest[0]) +
13384                      (eorg[1] - edest[1]) * (eorg[1] - edest[1]));
13385           if ((multiplier != 0.0) && (divisor != 0.0)) {
13386             multiplier = multiplier / divisor;
13387             /* Watch out for NANs. */
13388             if (multiplier == multiplier) {
13389               newvertex[0] += multiplier * (edest[1] - eorg[1]);
13390               newvertex[1] += multiplier * (eorg[0] - edest[0]);
13391             }
13392           }
13393         }
13394 
13395         setvertexmark(newvertex, mark(currentenc));
13396         setvertextype(newvertex, SEGMENTVERTEX);
13397         if (b->verbose > 1) {
13398           printf(
13399   "  Splitting subsegment (%.12g, %.12g) (%.12g, %.12g) at (%.12g, %.12g).\n",
13400                  eorg[0], eorg[1], edest[0], edest[1],
13401                  newvertex[0], newvertex[1]);
13402         }
13403         /* Check whether the new vertex lies on an endpoint. */
13404         if (((newvertex[0] == eorg[0]) && (newvertex[1] == eorg[1])) ||
13405             ((newvertex[0] == edest[0]) && (newvertex[1] == edest[1]))) {
13406           printf("Error:  Ran out of precision at (%.12g, %.12g).\n",
13407                  newvertex[0], newvertex[1]);
13408           printf("I attempted to split a segment to a smaller size than\n");
13409           printf("  can be accommodated by the finite precision of\n");
13410           printf("  floating point arithmetic.\n");
13411           precisionerror();
13412           triexit(1);
13413         }
13414         /* Insert the splitting vertex.  This should always succeed. */
13415         success = insertvertex(m, b, newvertex, &enctri, &currentenc,
13416                                1, triflaws);
13417         if ((success != SUCCESSFULVERTEX) && (success != ENCROACHINGVERTEX)) {
13418           printf("Internal error in splitencsegs():\n");
13419           printf("  Failure to split a segment.\n");
13420           internalerror();
13421         }
13422         if (m->steinerleft > 0) {
13423           m->steinerleft--;
13424         }
13425         /* Check the two new subsegments to see if they're encroached. */
13426         dummy = checkseg4encroach(m, b, &currentenc);
13427         snextself(currentenc);
13428         dummy = checkseg4encroach(m, b, &currentenc);
13429       }
13430 
13431       badsubsegdealloc(m, encloop);
13432       encloop = badsubsegtraverse(m);
13433     }
13434   }
13435 }
13436 
13437 #endif /* not CDT_ONLY */
13438 
13439 /*****************************************************************************/
13440 /*                                                                           */
13441 /*  tallyfaces()   Test every triangle in the mesh for quality measures.     */
13442 /*                                                                           */
13443 /*****************************************************************************/
13444 
13445 #ifndef CDT_ONLY
13446 
13447 #ifdef ANSI_DECLARATORS
13448 void tallyfaces(struct mesh *m, struct behavior *b)
13449 #else /* not ANSI_DECLARATORS */
13450 void tallyfaces(m, b)
13451 struct mesh *m;
13452 struct behavior *b;
13453 #endif /* not ANSI_DECLARATORS */
13454 
13455 {
13456   struct otri triangleloop;
13457 
13458   if (b->verbose) {
13459     printf("  Making a list of bad triangles.\n");
13460   }
13461   traversalinit(&m->triangles);
13462   triangleloop.orient = 0;
13463   triangleloop.tri = triangletraverse(m);
13464   while (triangleloop.tri != (triangle *) NULL) {
13465     /* If the triangle is bad, enqueue it. */
13466     testtriangle(m, b, &triangleloop);
13467     triangleloop.tri = triangletraverse(m);
13468   }
13469 }
13470 
13471 #endif /* not CDT_ONLY */
13472 
13473 /*****************************************************************************/
13474 /*                                                                           */
13475 /*  splittriangle()   Inserts a vertex at the circumcenter of a triangle.    */
13476 /*                    Deletes the newly inserted vertex if it encroaches     */
13477 /*                    upon a segment.                                        */
13478 /*                                                                           */
13479 /*****************************************************************************/
13480 
13481 #ifndef CDT_ONLY
13482 
13483 #ifdef ANSI_DECLARATORS
13484 void splittriangle(struct mesh *m, struct behavior *b,
13485                    struct badtriang *badtri)
13486 #else /* not ANSI_DECLARATORS */
13487 void splittriangle(m, b, badtri)
13488 struct mesh *m;
13489 struct behavior *b;
13490 struct badtriang *badtri;
13491 #endif /* not ANSI_DECLARATORS */
13492 
13493 {
13494   struct otri badotri;
13495   vertex borg, bdest, bapex;
13496   vertex newvertex;
13497   REAL xi, eta;
13498   enum insertvertexresult success;
13499   int errorflag;
13500   int i;
13501 
13502   decode(badtri->poortri, badotri);
13503   org(badotri, borg);
13504   dest(badotri, bdest);
13505   apex(badotri, bapex);
13506   /* Make sure that this triangle is still the same triangle it was      */
13507   /*   when it was tested and determined to be of bad quality.           */
13508   /*   Subsequent transformations may have made it a different triangle. */
13509   if (!deadtri(badotri.tri) && (borg == badtri->triangorg) &&
13510       (bdest == badtri->triangdest) && (bapex == badtri->triangapex)) {
13511     if (b->verbose > 1) {
13512       printf("  Splitting this triangle at its circumcenter:\n");
13513       printf("    (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n", borg[0],
13514              borg[1], bdest[0], bdest[1], bapex[0], bapex[1]);
13515     }
13516 
13517     errorflag = 0;
13518     /* Create a new vertex at the triangle's circumcenter. */
13519     newvertex = (vertex) poolalloc(&m->vertices);
13520     findcircumcenter(m, b, borg, bdest, bapex, newvertex, &xi, &eta, 1);
13521 
13522     /* Check whether the new vertex lies on a triangle vertex. */
13523     if (((newvertex[0] == borg[0]) && (newvertex[1] == borg[1])) ||
13524         ((newvertex[0] == bdest[0]) && (newvertex[1] == bdest[1])) ||
13525         ((newvertex[0] == bapex[0]) && (newvertex[1] == bapex[1]))) {
13526       if (!b->quiet) {
13527         printf(
13528              "Warning:  New vertex (%.12g, %.12g) falls on existing vertex.\n",
13529                newvertex[0], newvertex[1]);
13530         errorflag = 1;
13531       }
13532       vertexdealloc(m, newvertex);
13533     } else {
13534       for (i = 2; i < 2 + m->nextras; i++) {
13535         /* Interpolate the vertex attributes at the circumcenter. */
13536         newvertex[i] = borg[i] + xi * (bdest[i] - borg[i])
13537                               + eta * (bapex[i] - borg[i]);
13538       }
13539       /* The new vertex must be in the interior, and therefore is a */
13540       /*   free vertex with a marker of zero.                       */
13541       setvertexmark(newvertex, 0);
13542       setvertextype(newvertex, FREEVERTEX);
13543 
13544       /* Ensure that the handle `badotri' does not represent the longest  */
13545       /*   edge of the triangle.  This ensures that the circumcenter must */
13546       /*   fall to the left of this edge, so point location will work.    */
13547       /*   (If the angle org-apex-dest exceeds 90 degrees, then the       */
13548       /*   circumcenter lies outside the org-dest edge, and eta is        */
13549       /*   negative.  Roundoff error might prevent eta from being         */
13550       /*   negative when it should be, so I test eta against xi.)         */
13551       if (eta < xi) {
13552         lprevself(badotri);
13553       }
13554 
13555       /* Insert the circumcenter, searching from the edge of the triangle, */
13556       /*   and maintain the Delaunay property of the triangulation.        */
13557       success = insertvertex(m, b, newvertex, &badotri, (struct osub *) NULL,
13558                              1, 1);
13559       if (success == SUCCESSFULVERTEX) {
13560         if (m->steinerleft > 0) {
13561           m->steinerleft--;
13562         }
13563       } else if (success == ENCROACHINGVERTEX) {
13564         /* If the newly inserted vertex encroaches upon a subsegment, */
13565         /*   delete the new vertex.                                   */
13566         undovertex(m, b);
13567         if (b->verbose > 1) {
13568           printf("  Rejecting (%.12g, %.12g).\n", newvertex[0], newvertex[1]);
13569         }
13570         vertexdealloc(m, newvertex);
13571       } else if (success == VIOLATINGVERTEX) {
13572         /* Failed to insert the new vertex, but some subsegment was */
13573         /*   marked as being encroached.                            */
13574         vertexdealloc(m, newvertex);
13575       } else {                                 /* success == DUPLICATEVERTEX */
13576         /* Couldn't insert the new vertex because a vertex is already there. */
13577         if (!b->quiet) {
13578           printf(
13579             "Warning:  New vertex (%.12g, %.12g) falls on existing vertex.\n",
13580                  newvertex[0], newvertex[1]);
13581           errorflag = 1;
13582         }
13583         vertexdealloc(m, newvertex);
13584       }
13585     }
13586     if (errorflag) {
13587       if (b->verbose) {
13588         printf("  The new vertex is at the circumcenter of triangle\n");
13589         printf("    (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
13590                borg[0], borg[1], bdest[0], bdest[1], bapex[0], bapex[1]);
13591       }
13592       printf("This probably means that I am trying to refine triangles\n");
13593       printf("  to a smaller size than can be accommodated by the finite\n");
13594       printf("  precision of floating point arithmetic.  (You can be\n");
13595       printf("  sure of this if I fail to terminate.)\n");
13596       precisionerror();
13597     }
13598   }
13599 }
13600 
13601 #endif /* not CDT_ONLY */
13602 
13603 /*****************************************************************************/
13604 /*                                                                           */
13605 /*  enforcequality()   Remove all the encroached subsegments and bad         */
13606 /*                     triangles from the triangulation.                     */
13607 /*                                                                           */
13608 /*****************************************************************************/
13609 
13610 #ifndef CDT_ONLY
13611 
13612 #ifdef ANSI_DECLARATORS
13613 void enforcequality(struct mesh *m, struct behavior *b)
13614 #else /* not ANSI_DECLARATORS */
13615 void enforcequality(m, b)
13616 struct mesh *m;
13617 struct behavior *b;
13618 #endif /* not ANSI_DECLARATORS */
13619 
13620 {
13621   struct badtriang *badtri;
13622   int i;
13623 
13624   if (!b->quiet) {
13625     printf("Adding Steiner points to enforce quality.\n");
13626   }
13627   /* Initialize the pool of encroached subsegments. */
13628   poolinit(&m->badsubsegs, sizeof(struct badsubseg), BADSUBSEGPERBLOCK,
13629            BADSUBSEGPERBLOCK, 0);
13630   if (b->verbose) {
13631     printf("  Looking for encroached subsegments.\n");
13632   }
13633   /* Test all segments to see if they're encroached. */
13634   tallyencs(m, b);
13635   if (b->verbose && (m->badsubsegs.items > 0)) {
13636     printf("  Splitting encroached subsegments.\n");
13637   }
13638   /* Fix encroached subsegments without noting bad triangles. */
13639   splitencsegs(m, b, 0);
13640   /* At this point, if we haven't run out of Steiner points, the */
13641   /*   triangulation should be (conforming) Delaunay.            */
13642 
13643   /* Next, we worry about enforcing triangle quality. */
13644   if ((b->minangle > 0.0) || b->vararea || b->fixedarea || b->usertest) {
13645     /* Initialize the pool of bad triangles. */
13646     poolinit(&m->badtriangles, sizeof(struct badtriang), BADTRIPERBLOCK,
13647              BADTRIPERBLOCK, 0);
13648     /* Initialize the queues of bad triangles. */
13649     for (i = 0; i < 4096; i++) {
13650       m->queuefront[i] = (struct badtriang *) NULL;
13651     }
13652     m->firstnonemptyq = -1;
13653     /* Test all triangles to see if they're bad. */
13654     tallyfaces(m, b);
13655     /* Initialize the pool of recently flipped triangles. */
13656     poolinit(&m->flipstackers, sizeof(struct flipstacker), FLIPSTACKERPERBLOCK,
13657              FLIPSTACKERPERBLOCK, 0);
13658     m->checkquality = 1;
13659     if (b->verbose) {
13660       printf("  Splitting bad triangles.\n");
13661     }
13662     while ((m->badtriangles.items > 0) && (m->steinerleft != 0)) {
13663       /* Fix one bad triangle by inserting a vertex at its circumcenter. */
13664       badtri = dequeuebadtriang(m);
13665       splittriangle(m, b, badtri);
13666       if (m->badsubsegs.items > 0) {
13667         /* Put bad triangle back in queue for another try later. */
13668         enqueuebadtriang(m, b, badtri);
13669         /* Fix any encroached subsegments that resulted. */
13670         /*   Record any new bad triangles that result.   */
13671         splitencsegs(m, b, 1);
13672       } else {
13673         /* Return the bad triangle to the pool. */
13674         pooldealloc(&m->badtriangles, (VOID *) badtri);
13675       }
13676     }
13677   }
13678   /* At this point, if the "-D" switch was selected and we haven't run out  */
13679   /*   of Steiner points, the triangulation should be (conforming) Delaunay */
13680   /*   and have no low-quality triangles.                                   */
13681 
13682   /* Might we have run out of Steiner points too soon? */
13683   if (!b->quiet && b->conformdel && (m->badsubsegs.items > 0) &&
13684       (m->steinerleft == 0)) {
13685     printf("\nWarning:  I ran out of Steiner points, but the mesh has\n");
13686     if (m->badsubsegs.items == 1) {
13687       printf("  one encroached subsegment, and therefore might not be truly\n"
13688              );
13689     } else {
13690       printf("  %ld encroached subsegments, and therefore might not be truly\n"
13691              , m->badsubsegs.items);
13692     }
13693     printf("  Delaunay.  If the Delaunay property is important to you,\n");
13694     printf("  try increasing the number of Steiner points (controlled by\n");
13695     printf("  the -S switch) slightly and try again.\n\n");
13696   }
13697 }
13698 
13699 #endif /* not CDT_ONLY */
13700 
13701 /**                                                                         **/
13702 /**                                                                         **/
13703 /********* Mesh quality maintenance ends here                        *********/
13704 
13705 /*****************************************************************************/
13706 /*                                                                           */
13707 /*  highorder()   Create extra nodes for quadratic subparametric elements.   */
13708 /*                                                                           */
13709 /*****************************************************************************/
13710 
13711 #ifdef ANSI_DECLARATORS
13712 void highorder(struct mesh *m, struct behavior *b)
13713 #else /* not ANSI_DECLARATORS */
13714 void highorder(m, b)
13715 struct mesh *m;
13716 struct behavior *b;
13717 #endif /* not ANSI_DECLARATORS */
13718 
13719 {
13720   struct otri triangleloop, trisym;
13721   struct osub checkmark;
13722   vertex newvertex;
13723   vertex torg, tdest;
13724   int i;
13725   triangle ptr;                         /* Temporary variable used by sym(). */
13726   subseg sptr;                      /* Temporary variable used by tspivot(). */
13727 
13728   if (!b->quiet) {
13729     printf("Adding vertices for second-order triangles.\n");
13730   }
13731   /* The following line ensures that dead items in the pool of nodes    */
13732   /*   cannot be allocated for the extra nodes associated with high     */
13733   /*   order elements.  This ensures that the primary nodes (at the     */
13734   /*   corners of elements) will occur earlier in the output files, and */
13735   /*   have lower indices, than the extra nodes.                        */
13736   m->vertices.deaditemstack = (VOID *) NULL;
13737 
13738   traversalinit(&m->triangles);
13739   triangleloop.tri = triangletraverse(m);
13740   /* To loop over the set of edges, loop over all triangles, and look at   */
13741   /*   the three edges of each triangle.  If there isn't another triangle  */
13742   /*   adjacent to the edge, operate on the edge.  If there is another     */
13743   /*   adjacent triangle, operate on the edge only if the current triangle */
13744   /*   has a smaller pointer than its neighbor.  This way, each edge is    */
13745   /*   considered only once.                                               */
13746   while (triangleloop.tri != (triangle *) NULL) {
13747     for (triangleloop.orient = 0; triangleloop.orient < 3;
13748          triangleloop.orient++) {
13749       sym(triangleloop, trisym);
13750       if ((triangleloop.tri < trisym.tri) || (trisym.tri == m->dummytri)) {
13751         org(triangleloop, torg);
13752         dest(triangleloop, tdest);
13753         /* Create a new node in the middle of the edge.  Interpolate */
13754         /*   its attributes.                                         */
13755         newvertex = (vertex) poolalloc(&m->vertices);
13756         for (i = 0; i < 2 + m->nextras; i++) {
13757           newvertex[i] = 0.5 * (torg[i] + tdest[i]);
13758         }
13759         /* Set the new node's marker to zero or one, depending on */
13760         /*   whether it lies on a boundary.                       */
13761         setvertexmark(newvertex, trisym.tri == m->dummytri);
13762         setvertextype(newvertex,
13763                       trisym.tri == m->dummytri ? FREEVERTEX : SEGMENTVERTEX);
13764         if (b->usesegments) {
13765           tspivot(triangleloop, checkmark);
13766           /* If this edge is a segment, transfer the marker to the new node. */
13767           if (checkmark.ss != m->dummysub) {
13768             setvertexmark(newvertex, mark(checkmark));
13769             setvertextype(newvertex, SEGMENTVERTEX);
13770           }
13771         }
13772         if (b->verbose > 1) {
13773           printf("  Creating (%.12g, %.12g).\n", newvertex[0], newvertex[1]);
13774         }
13775         /* Record the new node in the (one or two) adjacent elements. */
13776         triangleloop.tri[m->highorderindex + triangleloop.orient] =
13777                 (triangle) newvertex;
13778         if (trisym.tri != m->dummytri) {
13779           trisym.tri[m->highorderindex + trisym.orient] = (triangle) newvertex;
13780         }
13781       }
13782     }
13783     triangleloop.tri = triangletraverse(m);
13784   }
13785 }
13786 
13787 /********* File I/O routines begin here                              *********/
13788 /**                                                                         **/
13789 /**                                                                         **/
13790 
13791 /*****************************************************************************/
13792 /*                                                                           */
13793 /*  readline()   Read a nonempty line from a file.                           */
13794 /*                                                                           */
13795 /*  A line is considered "nonempty" if it contains something that looks like */
13796 /*  a number.  Comments (prefaced by `#') are ignored.                       */
13797 /*                                                                           */
13798 /*****************************************************************************/
13799 
13800 #ifndef TRILIBRARY
13801 
13802 #ifdef ANSI_DECLARATORS
13803 char *readline(char *string, FILE *infile, char *infilename)
13804 #else /* not ANSI_DECLARATORS */
13805 char *readline(string, infile, infilename)
13806 char *string;
13807 FILE *infile;
13808 char *infilename;
13809 #endif /* not ANSI_DECLARATORS */
13810 
13811 {
13812   char *result;
13813 
13814   /* Search for something that looks like a number. */
13815   do {
13816     result = fgets(string, INPUTLINESIZE, infile);
13817     if (result == (char *) NULL) {
13818       printf("  Error:  Unexpected end of file in %s.\n", infilename);
13819       triexit(1);
13820     }
13821     /* Skip anything that doesn't look like a number, a comment, */
13822     /*   or the end of a line.                                   */
13823     while ((*result != '\0') && (*result != '#')
13824            && (*result != '.') && (*result != '+') && (*result != '-')
13825            && ((*result < '0') || (*result > '9'))) {
13826       result++;
13827     }
13828   /* If it's a comment or end of line, read another line and try again. */
13829   } while ((*result == '#') || (*result == '\0'));
13830   return result;
13831 }
13832 
13833 #endif /* not TRILIBRARY */
13834 
13835 /*****************************************************************************/
13836 /*                                                                           */
13837 /*  findfield()   Find the next field of a string.                           */
13838 /*                                                                           */
13839 /*  Jumps past the current field by searching for whitespace, then jumps     */
13840 /*  past the whitespace to find the next field.                              */
13841 /*                                                                           */
13842 /*****************************************************************************/
13843 
13844 #ifndef TRILIBRARY
13845 
13846 #ifdef ANSI_DECLARATORS
13847 char *findfield(char *string)
13848 #else /* not ANSI_DECLARATORS */
13849 char *findfield(string)
13850 char *string;
13851 #endif /* not ANSI_DECLARATORS */
13852 
13853 {
13854   char *result;
13855 
13856   result = string;
13857   /* Skip the current field.  Stop upon reaching whitespace. */
13858   while ((*result != '\0') && (*result != '#')
13859          && (*result != ' ') && (*result != '\t')) {
13860     result++;
13861   }
13862   /* Now skip the whitespace and anything else that doesn't look like a */
13863   /*   number, a comment, or the end of a line.                         */
13864   while ((*result != '\0') && (*result != '#')
13865          && (*result != '.') && (*result != '+') && (*result != '-')
13866          && ((*result < '0') || (*result > '9'))) {
13867     result++;
13868   }
13869   /* Check for a comment (prefixed with `#'). */
13870   if (*result == '#') {
13871     *result = '\0';
13872   }
13873   return result;
13874 }
13875 
13876 #endif /* not TRILIBRARY */
13877 
13878 /*****************************************************************************/
13879 /*                                                                           */
13880 /*  readnodes()   Read the vertices from a file, which may be a .node or     */
13881 /*                .poly file.                                                */
13882 /*                                                                           */
13883 /*****************************************************************************/
13884 
13885 #ifndef TRILIBRARY
13886 
13887 #ifdef ANSI_DECLARATORS
13888 void readnodes(struct mesh *m, struct behavior *b, char *nodefilename,
13889                char *polyfilename, FILE **polyfile)
13890 #else /* not ANSI_DECLARATORS */
13891 void readnodes(m, b, nodefilename, polyfilename, polyfile)
13892 struct mesh *m;
13893 struct behavior *b;
13894 char *nodefilename;
13895 char *polyfilename;
13896 FILE **polyfile;
13897 #endif /* not ANSI_DECLARATORS */
13898 
13899 {
13900   FILE *infile;
13901   vertex vertexloop;
13902   char inputline[INPUTLINESIZE];
13903   char *stringptr;
13904   char *infilename;
13905   REAL x, y;
13906   int firstnode;
13907   int nodemarkers;
13908   int currentmarker;
13909   int i, j;
13910 
13911   if (b->poly) {
13912     /* Read the vertices from a .poly file. */
13913     if (!b->quiet) {
13914       printf("Opening %s.\n", polyfilename);
13915     }
13916     *polyfile = fopen(polyfilename, "r");
13917     if (*polyfile == (FILE *) NULL) {
13918       printf("  Error:  Cannot access file %s.\n", polyfilename);
13919       triexit(1);
13920     }
13921     /* Read number of vertices, number of dimensions, number of vertex */
13922     /*   attributes, and number of boundary markers.                   */
13923     stringptr = readline(inputline, *polyfile, polyfilename);
13924     m->invertices = (int) strtol(stringptr, &stringptr, 0);
13925     stringptr = findfield(stringptr);
13926     if (*stringptr == '\0') {
13927       m->mesh_dim = 2;
13928     } else {
13929       m->mesh_dim = (int) strtol(stringptr, &stringptr, 0);
13930     }
13931     stringptr = findfield(stringptr);
13932     if (*stringptr == '\0') {
13933       m->nextras = 0;
13934     } else {
13935       m->nextras = (int) strtol(stringptr, &stringptr, 0);
13936     }
13937     stringptr = findfield(stringptr);
13938     if (*stringptr == '\0') {
13939       nodemarkers = 0;
13940     } else {
13941       nodemarkers = (int) strtol(stringptr, &stringptr, 0);
13942     }
13943     if (m->invertices > 0) {
13944       infile = *polyfile;
13945       infilename = polyfilename;
13946       m->readnodefile = 0;
13947     } else {
13948       /* If the .poly file claims there are zero vertices, that means that */
13949       /*   the vertices should be read from a separate .node file.         */
13950       m->readnodefile = 1;
13951       infilename = nodefilename;
13952     }
13953   } else {
13954     m->readnodefile = 1;
13955     infilename = nodefilename;
13956     *polyfile = (FILE *) NULL;
13957   }
13958 
13959   if (m->readnodefile) {
13960     /* Read the vertices from a .node file. */
13961     if (!b->quiet) {
13962       printf("Opening %s.\n", nodefilename);
13963     }
13964     infile = fopen(nodefilename, "r");
13965     if (infile == (FILE *) NULL) {
13966       printf("  Error:  Cannot access file %s.\n", nodefilename);
13967       triexit(1);
13968     }
13969     /* Read number of vertices, number of dimensions, number of vertex */
13970     /*   attributes, and number of boundary markers.                   */
13971     stringptr = readline(inputline, infile, nodefilename);
13972     m->invertices = (int) strtol(stringptr, &stringptr, 0);
13973     stringptr = findfield(stringptr);
13974     if (*stringptr == '\0') {
13975       m->mesh_dim = 2;
13976     } else {
13977       m->mesh_dim = (int) strtol(stringptr, &stringptr, 0);
13978     }
13979     stringptr = findfield(stringptr);
13980     if (*stringptr == '\0') {
13981       m->nextras = 0;
13982     } else {
13983       m->nextras = (int) strtol(stringptr, &stringptr, 0);
13984     }
13985     stringptr = findfield(stringptr);
13986     if (*stringptr == '\0') {
13987       nodemarkers = 0;
13988     } else {
13989       nodemarkers = (int) strtol(stringptr, &stringptr, 0);
13990     }
13991   }
13992 
13993   if (m->invertices < 3) {
13994     printf("Error:  Input must have at least three input vertices.\n");
13995     triexit(1);
13996   }
13997   if (m->mesh_dim != 2) {
13998     printf("Error:  Triangle only works with two-dimensional meshes.\n");
13999     triexit(1);
14000   }
14001   if (m->nextras == 0) {
14002     b->weighted = 0;
14003   }
14004 
14005   initializevertexpool(m, b);
14006 
14007   /* Read the vertices. */
14008   for (i = 0; i < m->invertices; i++) {
14009     vertexloop = (vertex) poolalloc(&m->vertices);
14010     stringptr = readline(inputline, infile, infilename);
14011     if (i == 0) {
14012       firstnode = (int) strtol(stringptr, &stringptr, 0);
14013       if ((firstnode == 0) || (firstnode == 1)) {
14014         b->firstnumber = firstnode;
14015       }
14016     }
14017     stringptr = findfield(stringptr);
14018     if (*stringptr == '\0') {
14019       printf("Error:  Vertex %d has no x coordinate.\n", b->firstnumber + i);
14020       triexit(1);
14021     }
14022     x = (REAL) strtod(stringptr, &stringptr);
14023     stringptr = findfield(stringptr);
14024     if (*stringptr == '\0') {
14025       printf("Error:  Vertex %d has no y coordinate.\n", b->firstnumber + i);
14026       triexit(1);
14027     }
14028     y = (REAL) strtod(stringptr, &stringptr);
14029     vertexloop[0] = x;
14030     vertexloop[1] = y;
14031     /* Read the vertex attributes. */
14032     for (j = 2; j < 2 + m->nextras; j++) {
14033       stringptr = findfield(stringptr);
14034       if (*stringptr == '\0') {
14035         vertexloop[j] = 0.0;
14036       } else {
14037         vertexloop[j] = (REAL) strtod(stringptr, &stringptr);
14038       }
14039     }
14040     if (nodemarkers) {
14041       /* Read a vertex marker. */
14042       stringptr = findfield(stringptr);
14043       if (*stringptr == '\0') {
14044         setvertexmark(vertexloop, 0);
14045       } else {
14046         currentmarker = (int) strtol(stringptr, &stringptr, 0);
14047         setvertexmark(vertexloop, currentmarker);
14048       }
14049     } else {
14050       /* If no markers are specified in the file, they default to zero. */
14051       setvertexmark(vertexloop, 0);
14052     }
14053     setvertextype(vertexloop, INPUTVERTEX);
14054     /* Determine the smallest and largest x and y coordinates. */
14055     if (i == 0) {
14056       m->xmin = m->xmax = x;
14057       m->ymin = m->ymax = y;
14058     } else {
14059       m->xmin = (x < m->xmin) ? x : m->xmin;
14060       m->xmax = (x > m->xmax) ? x : m->xmax;
14061       m->ymin = (y < m->ymin) ? y : m->ymin;
14062       m->ymax = (y > m->ymax) ? y : m->ymax;
14063     }
14064   }
14065   if (m->readnodefile) {
14066     fclose(infile);
14067   }
14068 
14069   /* Nonexistent x value used as a flag to mark circle events in sweepline */
14070   /*   Delaunay algorithm.                                                 */
14071   m->xminextreme = 10 * m->xmin - 9 * m->xmax;
14072 }
14073 
14074 #endif /* not TRILIBRARY */
14075 
14076 /*****************************************************************************/
14077 /*                                                                           */
14078 /*  transfernodes()   Read the vertices from memory.                         */
14079 /*                                                                           */
14080 /*****************************************************************************/
14081 
14082 #ifdef TRILIBRARY
14083 
14084 #ifdef ANSI_DECLARATORS
14085 void transfernodes(struct mesh *m, struct behavior *b, REAL *pointlist,
14086                    REAL *pointattriblist, int *pointmarkerlist,
14087                    int numberofpoints, int numberofpointattribs)
14088 #else /* not ANSI_DECLARATORS */
14089 void transfernodes(m, b, pointlist, pointattriblist, pointmarkerlist,
14090                    numberofpoints, numberofpointattribs)
14091 struct mesh *m;
14092 struct behavior *b;
14093 REAL *pointlist;
14094 REAL *pointattriblist;
14095 int *pointmarkerlist;
14096 int numberofpoints;
14097 int numberofpointattribs;
14098 #endif /* not ANSI_DECLARATORS */
14099 
14100 {
14101   vertex vertexloop;
14102   REAL x, y;
14103   int i, j;
14104   int coordindex;
14105   int attribindex;
14106 
14107   m->invertices = numberofpoints;
14108   m->mesh_dim = 2;
14109   m->nextras = numberofpointattribs;
14110   m->readnodefile = 0;
14111   if (m->invertices < 3) {
14112     printf("Error:  Input must have at least three input vertices.\n");
14113     triexit(1);
14114   }
14115   if (m->nextras == 0) {
14116     b->weighted = 0;
14117   }
14118 
14119   initializevertexpool(m, b);
14120 
14121   /* Read the vertices. */
14122   coordindex = 0;
14123   attribindex = 0;
14124   for (i = 0; i < m->invertices; i++) {
14125     vertexloop = (vertex) poolalloc(&m->vertices);
14126     /* Read the vertex coordinates. */
14127     x = vertexloop[0] = pointlist[coordindex++];
14128     y = vertexloop[1] = pointlist[coordindex++];
14129     /* Read the vertex attributes. */
14130     for (j = 0; j < numberofpointattribs; j++) {
14131       vertexloop[2 + j] = pointattriblist[attribindex++];
14132     }
14133     if (pointmarkerlist != (int *) NULL) {
14134       /* Read a vertex marker. */
14135       setvertexmark(vertexloop, pointmarkerlist[i]);
14136     } else {
14137       /* If no markers are specified, they default to zero. */
14138       setvertexmark(vertexloop, 0);
14139     }
14140     setvertextype(vertexloop, INPUTVERTEX);
14141     /* Determine the smallest and largest x and y coordinates. */
14142     if (i == 0) {
14143       m->xmin = m->xmax = x;
14144       m->ymin = m->ymax = y;
14145     } else {
14146       m->xmin = (x < m->xmin) ? x : m->xmin;
14147       m->xmax = (x > m->xmax) ? x : m->xmax;
14148       m->ymin = (y < m->ymin) ? y : m->ymin;
14149       m->ymax = (y > m->ymax) ? y : m->ymax;
14150     }
14151   }
14152 
14153   /* Nonexistent x value used as a flag to mark circle events in sweepline */
14154   /*   Delaunay algorithm.                                                 */
14155   m->xminextreme = 10 * m->xmin - 9 * m->xmax;
14156 }
14157 
14158 #endif /* TRILIBRARY */
14159 
14160 /*****************************************************************************/
14161 /*                                                                           */
14162 /*  readholes()   Read the holes, and possibly regional attributes and area  */
14163 /*                constraints, from a .poly file.                            */
14164 /*                                                                           */
14165 /*****************************************************************************/
14166 
14167 #ifndef TRILIBRARY
14168 
14169 #ifdef ANSI_DECLARATORS
14170 void readholes(struct mesh *m, struct behavior *b,
14171                FILE *polyfile, char *polyfilename, REAL **hlist, int *holes,
14172                REAL **rlist, int *regions)
14173 #else /* not ANSI_DECLARATORS */
14174 void readholes(m, b, polyfile, polyfilename, hlist, holes, rlist, regions)
14175 struct mesh *m;
14176 struct behavior *b;
14177 FILE *polyfile;
14178 char *polyfilename;
14179 REAL **hlist;
14180 int *holes;
14181 REAL **rlist;
14182 int *regions;
14183 #endif /* not ANSI_DECLARATORS */
14184 
14185 {
14186   REAL *holelist;
14187   REAL *regionlist;
14188   char inputline[INPUTLINESIZE];
14189   char *stringptr;
14190   int index;
14191   int i;
14192 
14193   /* Read the holes. */
14194   stringptr = readline(inputline, polyfile, polyfilename);
14195   *holes = (int) strtol(stringptr, &stringptr, 0);
14196   if (*holes > 0) {
14197     holelist = (REAL *) trimalloc(2 * *holes * (int) sizeof(REAL));
14198     *hlist = holelist;
14199     for (i = 0; i < 2 * *holes; i += 2) {
14200       stringptr = readline(inputline, polyfile, polyfilename);
14201       stringptr = findfield(stringptr);
14202       if (*stringptr == '\0') {
14203         printf("Error:  Hole %d has no x coordinate.\n",
14204                b->firstnumber + (i >> 1));
14205         triexit(1);
14206       } else {
14207         holelist[i] = (REAL) strtod(stringptr, &stringptr);
14208       }
14209       stringptr = findfield(stringptr);
14210       if (*stringptr == '\0') {
14211         printf("Error:  Hole %d has no y coordinate.\n",
14212                b->firstnumber + (i >> 1));
14213         triexit(1);
14214       } else {
14215         holelist[i + 1] = (REAL) strtod(stringptr, &stringptr);
14216       }
14217     }
14218   } else {
14219     *hlist = (REAL *) NULL;
14220   }
14221 
14222 #ifndef CDT_ONLY
14223   if ((b->regionattrib || b->vararea) && !b->refine) {
14224     /* Read the area constraints. */
14225     stringptr = readline(inputline, polyfile, polyfilename);
14226     *regions = (int) strtol(stringptr, &stringptr, 0);
14227     if (*regions > 0) {
14228       regionlist = (REAL *) trimalloc(4 * *regions * (int) sizeof(REAL));
14229       *rlist = regionlist;
14230       index = 0;
14231       for (i = 0; i < *regions; i++) {
14232         stringptr = readline(inputline, polyfile, polyfilename);
14233         stringptr = findfield(stringptr);
14234         if (*stringptr == '\0') {
14235           printf("Error:  Region %d has no x coordinate.\n",
14236                  b->firstnumber + i);
14237           triexit(1);
14238         } else {
14239           regionlist[index++] = (REAL) strtod(stringptr, &stringptr);
14240         }
14241         stringptr = findfield(stringptr);
14242         if (*stringptr == '\0') {
14243           printf("Error:  Region %d has no y coordinate.\n",
14244                  b->firstnumber + i);
14245           triexit(1);
14246         } else {
14247           regionlist[index++] = (REAL) strtod(stringptr, &stringptr);
14248         }
14249         stringptr = findfield(stringptr);
14250         if (*stringptr == '\0') {
14251           printf(
14252             "Error:  Region %d has no region attribute or area constraint.\n",
14253                  b->firstnumber + i);
14254           triexit(1);
14255         } else {
14256           regionlist[index++] = (REAL) strtod(stringptr, &stringptr);
14257         }
14258         stringptr = findfield(stringptr);
14259         if (*stringptr == '\0') {
14260           regionlist[index] = regionlist[index - 1];
14261         } else {
14262           regionlist[index] = (REAL) strtod(stringptr, &stringptr);
14263         }
14264         index++;
14265       }
14266     }
14267   } else {
14268     /* Set `*regions' to zero to avoid an accidental free() later. */
14269     *regions = 0;
14270     *rlist = (REAL *) NULL;
14271   }
14272 #endif /* not CDT_ONLY */
14273 
14274   fclose(polyfile);
14275 }
14276 
14277 #endif /* not TRILIBRARY */
14278 
14279 /*****************************************************************************/
14280 /*                                                                           */
14281 /*  finishfile()   Write the command line to the output file so the user     */
14282 /*                 can remember how the file was generated.  Close the file. */
14283 /*                                                                           */
14284 /*****************************************************************************/
14285 
14286 #ifndef TRILIBRARY
14287 
14288 #ifdef ANSI_DECLARATORS
14289 void finishfile(FILE *outfile, int argc, char **argv)
14290 #else /* not ANSI_DECLARATORS */
14291 void finishfile(outfile, argc, argv)
14292 FILE *outfile;
14293 int argc;
14294 char **argv;
14295 #endif /* not ANSI_DECLARATORS */
14296 
14297 {
14298   int i;
14299 
14300   fprintf(outfile, "# Generated by");
14301   for (i = 0; i < argc; i++) {
14302     fprintf(outfile, " ");
14303     fputs(argv[i], outfile);
14304   }
14305   fprintf(outfile, "\n");
14306   fclose(outfile);
14307 }
14308 
14309 #endif /* not TRILIBRARY */
14310 
14311 /*****************************************************************************/
14312 /*                                                                           */
14313 /*  writenodes()   Number the vertices and write them to a .node file.       */
14314 /*                                                                           */
14315 /*  To save memory, the vertex numbers are written over the boundary markers */
14316 /*  after the vertices are written to a file.                                */
14317 /*                                                                           */
14318 /*****************************************************************************/
14319 
14320 #ifdef TRILIBRARY
14321 
14322 #ifdef ANSI_DECLARATORS
14323 void writenodes(struct mesh *m, struct behavior *b, REAL **pointlist,
14324                 REAL **pointattriblist, int **pointmarkerlist)
14325 #else /* not ANSI_DECLARATORS */
14326 void writenodes(m, b, pointlist, pointattriblist, pointmarkerlist)
14327 struct mesh *m;
14328 struct behavior *b;
14329 REAL **pointlist;
14330 REAL **pointattriblist;
14331 int **pointmarkerlist;
14332 #endif /* not ANSI_DECLARATORS */
14333 
14334 #else /* not TRILIBRARY */
14335 
14336 #ifdef ANSI_DECLARATORS
14337 void writenodes(struct mesh *m, struct behavior *b, char *nodefilename,
14338                 int argc, char **argv)
14339 #else /* not ANSI_DECLARATORS */
14340 void writenodes(m, b, nodefilename, argc, argv)
14341 struct mesh *m;
14342 struct behavior *b;
14343 char *nodefilename;
14344 int argc;
14345 char **argv;
14346 #endif /* not ANSI_DECLARATORS */
14347 
14348 #endif /* not TRILIBRARY */
14349 
14350 {
14351 #ifdef TRILIBRARY
14352   REAL *plist;
14353   REAL *palist;
14354   int *pmlist;
14355   int coordindex;
14356   int attribindex;
14357 #else /* not TRILIBRARY */
14358   FILE *outfile;
14359 #endif /* not TRILIBRARY */
14360   vertex vertexloop;
14361   long outvertices;
14362   int vertexnumber;
14363   int i;
14364 
14365   if (b->jettison) {
14366     outvertices = m->vertices.items - m->undeads;
14367   } else {
14368     outvertices = m->vertices.items;
14369   }
14370 
14371 #ifdef TRILIBRARY
14372   if (!b->quiet) {
14373     printf("Writing vertices.\n");
14374   }
14375   /* Allocate memory for output vertices if necessary. */
14376   if (*pointlist == (REAL *) NULL) {
14377     *pointlist = (REAL *) trimalloc((int) (outvertices * 2 * sizeof(REAL)));
14378   }
14379   /* Allocate memory for output vertex attributes if necessary. */
14380   if ((m->nextras > 0) && (*pointattriblist == (REAL *) NULL)) {
14381     *pointattriblist = (REAL *) trimalloc((int) (outvertices * m->nextras *
14382                                                  sizeof(REAL)));
14383   }
14384   /* Allocate memory for output vertex markers if necessary. */
14385   if (!b->nobound && (*pointmarkerlist == (int *) NULL)) {
14386     *pointmarkerlist = (int *) trimalloc((int) (outvertices * sizeof(int)));
14387   }
14388   plist = *pointlist;
14389   palist = *pointattriblist;
14390   pmlist = *pointmarkerlist;
14391   coordindex = 0;
14392   attribindex = 0;
14393 #else /* not TRILIBRARY */
14394   if (!b->quiet) {
14395     printf("Writing %s.\n", nodefilename);
14396   }
14397   outfile = fopen(nodefilename, "w");
14398   if (outfile == (FILE *) NULL) {
14399     printf("  Error:  Cannot create file %s.\n", nodefilename);
14400     triexit(1);
14401   }
14402   /* Number of vertices, number of dimensions, number of vertex attributes, */
14403   /*   and number of boundary markers (zero or one).                        */
14404   fprintf(outfile, "%ld  %d  %d  %d\n", outvertices, m->mesh_dim,
14405           m->nextras, 1 - b->nobound);
14406 #endif /* not TRILIBRARY */
14407 
14408   traversalinit(&m->vertices);
14409   vertexnumber = b->firstnumber;
14410   vertexloop = vertextraverse(m);
14411   while (vertexloop != (vertex) NULL) {
14412     if (!b->jettison || (vertextype(vertexloop) != UNDEADVERTEX)) {
14413 #ifdef TRILIBRARY
14414       /* X and y coordinates. */
14415       plist[coordindex++] = vertexloop[0];
14416       plist[coordindex++] = vertexloop[1];
14417       /* Vertex attributes. */
14418       for (i = 0; i < m->nextras; i++) {
14419         palist[attribindex++] = vertexloop[2 + i];
14420       }
14421       if (!b->nobound) {
14422         /* Copy the boundary marker. */
14423         pmlist[vertexnumber - b->firstnumber] = vertexmark(vertexloop);
14424       }
14425 #else /* not TRILIBRARY */
14426       /* Vertex number, x and y coordinates. */
14427       fprintf(outfile, "%4d    %.17g  %.17g", vertexnumber, vertexloop[0],
14428               vertexloop[1]);
14429       for (i = 0; i < m->nextras; i++) {
14430         /* Write an attribute. */
14431         fprintf(outfile, "  %.17g", vertexloop[i + 2]);
14432       }
14433       if (b->nobound) {
14434         fprintf(outfile, "\n");
14435       } else {
14436         /* Write the boundary marker. */
14437         fprintf(outfile, "    %d\n", vertexmark(vertexloop));
14438       }
14439 #endif /* not TRILIBRARY */
14440 
14441       setvertexmark(vertexloop, vertexnumber);
14442       vertexnumber++;
14443     }
14444     vertexloop = vertextraverse(m);
14445   }
14446 
14447 #ifndef TRILIBRARY
14448   finishfile(outfile, argc, argv);
14449 #endif /* not TRILIBRARY */
14450 }
14451 
14452 /*****************************************************************************/
14453 /*                                                                           */
14454 /*  numbernodes()   Number the vertices.                                     */
14455 /*                                                                           */
14456 /*  Each vertex is assigned a marker equal to its number.                    */
14457 /*                                                                           */
14458 /*  Used when writenodes() is not called because no .node file is written.   */
14459 /*                                                                           */
14460 /*****************************************************************************/
14461 
14462 #ifdef ANSI_DECLARATORS
14463 void numbernodes(struct mesh *m, struct behavior *b)
14464 #else /* not ANSI_DECLARATORS */
14465 void numbernodes(m, b)
14466 struct mesh *m;
14467 struct behavior *b;
14468 #endif /* not ANSI_DECLARATORS */
14469 
14470 {
14471   vertex vertexloop;
14472   int vertexnumber;
14473 
14474   traversalinit(&m->vertices);
14475   vertexnumber = b->firstnumber;
14476   vertexloop = vertextraverse(m);
14477   while (vertexloop != (vertex) NULL) {
14478     setvertexmark(vertexloop, vertexnumber);
14479     if (!b->jettison || (vertextype(vertexloop) != UNDEADVERTEX)) {
14480       vertexnumber++;
14481     }
14482     vertexloop = vertextraverse(m);
14483   }
14484 }
14485 
14486 /*****************************************************************************/
14487 /*                                                                           */
14488 /*  writeelements()   Write the triangles to an .ele file.                   */
14489 /*                                                                           */
14490 /*****************************************************************************/
14491 
14492 #ifdef TRILIBRARY
14493 
14494 #ifdef ANSI_DECLARATORS
14495 void writeelements(struct mesh *m, struct behavior *b,
14496                    int **trianglelist, REAL **triangleattriblist)
14497 #else /* not ANSI_DECLARATORS */
14498 void writeelements(m, b, trianglelist, triangleattriblist)
14499 struct mesh *m;
14500 struct behavior *b;
14501 int **trianglelist;
14502 REAL **triangleattriblist;
14503 #endif /* not ANSI_DECLARATORS */
14504 
14505 #else /* not TRILIBRARY */
14506 
14507 #ifdef ANSI_DECLARATORS
14508 void writeelements(struct mesh *m, struct behavior *b, char *elefilename,
14509                    int argc, char **argv)
14510 #else /* not ANSI_DECLARATORS */
14511 void writeelements(m, b, elefilename, argc, argv)
14512 struct mesh *m;
14513 struct behavior *b;
14514 char *elefilename;
14515 int argc;
14516 char **argv;
14517 #endif /* not ANSI_DECLARATORS */
14518 
14519 #endif /* not TRILIBRARY */
14520 
14521 {
14522 #ifdef TRILIBRARY
14523   int *tlist;
14524   REAL *talist;
14525   int vertexindex;
14526   int attribindex;
14527 #else /* not TRILIBRARY */
14528   FILE *outfile;
14529 #endif /* not TRILIBRARY */
14530   struct otri triangleloop;
14531   vertex p1, p2, p3;
14532   vertex mid1, mid2, mid3;
14533   long elementnumber;
14534   int i;
14535 
14536 #ifdef TRILIBRARY
14537   if (!b->quiet) {
14538     printf("Writing triangles.\n");
14539   }
14540   /* Allocate memory for output triangles if necessary. */
14541   if (*trianglelist == (int *) NULL) {
14542     *trianglelist = (int *) trimalloc((int) (m->triangles.items *
14543                                              ((b->order + 1) * (b->order + 2) /
14544                                               2) * sizeof(int)));
14545   }
14546   /* Allocate memory for output triangle attributes if necessary. */
14547   if ((m->eextras > 0) && (*triangleattriblist == (REAL *) NULL)) {
14548     *triangleattriblist = (REAL *) trimalloc((int) (m->triangles.items *
14549                                                     m->eextras *
14550                                                     sizeof(REAL)));
14551   }
14552   tlist = *trianglelist;
14553   talist = *triangleattriblist;
14554   vertexindex = 0;
14555   attribindex = 0;
14556 #else /* not TRILIBRARY */
14557   if (!b->quiet) {
14558     printf("Writing %s.\n", elefilename);
14559   }
14560   outfile = fopen(elefilename, "w");
14561   if (outfile == (FILE *) NULL) {
14562     printf("  Error:  Cannot create file %s.\n", elefilename);
14563     triexit(1);
14564   }
14565   /* Number of triangles, vertices per triangle, attributes per triangle. */
14566   fprintf(outfile, "%ld  %d  %d\n", m->triangles.items,
14567           (b->order + 1) * (b->order + 2) / 2, m->eextras);
14568 #endif /* not TRILIBRARY */
14569 
14570   traversalinit(&m->triangles);
14571   triangleloop.tri = triangletraverse(m);
14572   triangleloop.orient = 0;
14573   elementnumber = b->firstnumber;
14574   while (triangleloop.tri != (triangle *) NULL) {
14575     org(triangleloop, p1);
14576     dest(triangleloop, p2);
14577     apex(triangleloop, p3);
14578     if (b->order == 1) {
14579 #ifdef TRILIBRARY
14580       tlist[vertexindex++] = vertexmark(p1);
14581       tlist[vertexindex++] = vertexmark(p2);
14582       tlist[vertexindex++] = vertexmark(p3);
14583 #else /* not TRILIBRARY */
14584       /* Triangle number, indices for three vertices. */
14585       fprintf(outfile, "%4ld    %4d  %4d  %4d", elementnumber,
14586               vertexmark(p1), vertexmark(p2), vertexmark(p3));
14587 #endif /* not TRILIBRARY */
14588     } else {
14589       mid1 = (vertex) triangleloop.tri[m->highorderindex + 1];
14590       mid2 = (vertex) triangleloop.tri[m->highorderindex + 2];
14591       mid3 = (vertex) triangleloop.tri[m->highorderindex];
14592 #ifdef TRILIBRARY
14593       tlist[vertexindex++] = vertexmark(p1);
14594       tlist[vertexindex++] = vertexmark(p2);
14595       tlist[vertexindex++] = vertexmark(p3);
14596       tlist[vertexindex++] = vertexmark(mid1);
14597       tlist[vertexindex++] = vertexmark(mid2);
14598       tlist[vertexindex++] = vertexmark(mid3);
14599 #else /* not TRILIBRARY */
14600       /* Triangle number, indices for six vertices. */
14601       fprintf(outfile, "%4ld    %4d  %4d  %4d  %4d  %4d  %4d", elementnumber,
14602               vertexmark(p1), vertexmark(p2), vertexmark(p3), vertexmark(mid1),
14603               vertexmark(mid2), vertexmark(mid3));
14604 #endif /* not TRILIBRARY */
14605     }
14606 
14607 #ifdef TRILIBRARY
14608     for (i = 0; i < m->eextras; i++) {
14609       talist[attribindex++] = elemattribute(triangleloop, i);
14610     }
14611 #else /* not TRILIBRARY */
14612     for (i = 0; i < m->eextras; i++) {
14613       fprintf(outfile, "  %.17g", elemattribute(triangleloop, i));
14614     }
14615     fprintf(outfile, "\n");
14616 #endif /* not TRILIBRARY */
14617 
14618     triangleloop.tri = triangletraverse(m);
14619     elementnumber++;
14620   }
14621 
14622 #ifndef TRILIBRARY
14623   finishfile(outfile, argc, argv);
14624 #endif /* not TRILIBRARY */
14625 }
14626 
14627 /*****************************************************************************/
14628 /*                                                                           */
14629 /*  writepoly()   Write the segments and holes to a .poly file.              */
14630 /*                                                                           */
14631 /*****************************************************************************/
14632 
14633 #ifdef TRILIBRARY
14634 
14635 #ifdef ANSI_DECLARATORS
14636 void writepoly(struct mesh *m, struct behavior *b,
14637                int **segmentlist, int **segmentmarkerlist)
14638 #else /* not ANSI_DECLARATORS */
14639 void writepoly(m, b, segmentlist, segmentmarkerlist)
14640 struct mesh *m;
14641 struct behavior *b;
14642 int **segmentlist;
14643 int **segmentmarkerlist;
14644 #endif /* not ANSI_DECLARATORS */
14645 
14646 #else /* not TRILIBRARY */
14647 
14648 #ifdef ANSI_DECLARATORS
14649 void writepoly(struct mesh *m, struct behavior *b, char *polyfilename,
14650                REAL *holelist, int holes, REAL *regionlist, int regions,
14651                int argc, char **argv)
14652 #else /* not ANSI_DECLARATORS */
14653 void writepoly(m, b, polyfilename, holelist, holes, regionlist, regions,
14654                argc, argv)
14655 struct mesh *m;
14656 struct behavior *b;
14657 char *polyfilename;
14658 REAL *holelist;
14659 int holes;
14660 REAL *regionlist;
14661 int regions;
14662 int argc;
14663 char **argv;
14664 #endif /* not ANSI_DECLARATORS */
14665 
14666 #endif /* not TRILIBRARY */
14667 
14668 {
14669 #ifdef TRILIBRARY
14670   int *slist;
14671   int *smlist;
14672   int index;
14673 #else /* not TRILIBRARY */
14674   FILE *outfile;
14675   long holenumber, regionnumber;
14676 #endif /* not TRILIBRARY */
14677   struct osub subsegloop;
14678   vertex endpoint1, endpoint2;
14679   long subsegnumber;
14680 
14681 #ifdef TRILIBRARY
14682   if (!b->quiet) {
14683     printf("Writing segments.\n");
14684   }
14685   /* Allocate memory for output segments if necessary. */
14686   if (*segmentlist == (int *) NULL) {
14687     *segmentlist = (int *) trimalloc((int) (m->subsegs.items * 2 *
14688                                             sizeof(int)));
14689   }
14690   /* Allocate memory for output segment markers if necessary. */
14691   if (!b->nobound && (*segmentmarkerlist == (int *) NULL)) {
14692     *segmentmarkerlist = (int *) trimalloc((int) (m->subsegs.items *
14693                                                   sizeof(int)));
14694   }
14695   slist = *segmentlist;
14696   smlist = *segmentmarkerlist;
14697   index = 0;
14698 #else /* not TRILIBRARY */
14699   if (!b->quiet) {
14700     printf("Writing %s.\n", polyfilename);
14701   }
14702   outfile = fopen(polyfilename, "w");
14703   if (outfile == (FILE *) NULL) {
14704     printf("  Error:  Cannot create file %s.\n", polyfilename);
14705     triexit(1);
14706   }
14707   /* The zero indicates that the vertices are in a separate .node file. */
14708   /*   Followed by number of dimensions, number of vertex attributes,   */
14709   /*   and number of boundary markers (zero or one).                    */
14710   fprintf(outfile, "%d  %d  %d  %d\n", 0, m->mesh_dim, m->nextras,
14711           1 - b->nobound);
14712   /* Number of segments, number of boundary markers (zero or one). */
14713   fprintf(outfile, "%ld  %d\n", m->subsegs.items, 1 - b->nobound);
14714 #endif /* not TRILIBRARY */
14715 
14716   traversalinit(&m->subsegs);
14717   subsegloop.ss = subsegtraverse(m);
14718   subsegloop.ssorient = 0;
14719   subsegnumber = b->firstnumber;
14720   while (subsegloop.ss != (subseg *) NULL) {
14721     sorg(subsegloop, endpoint1);
14722     sdest(subsegloop, endpoint2);
14723 #ifdef TRILIBRARY
14724     /* Copy indices of the segment's two endpoints. */
14725     slist[index++] = vertexmark(endpoint1);
14726     slist[index++] = vertexmark(endpoint2);
14727     if (!b->nobound) {
14728       /* Copy the boundary marker. */
14729       smlist[subsegnumber - b->firstnumber] = mark(subsegloop);
14730     }
14731 #else /* not TRILIBRARY */
14732     /* Segment number, indices of its two endpoints, and possibly a marker. */
14733     if (b->nobound) {
14734       fprintf(outfile, "%4ld    %4d  %4d\n", subsegnumber,
14735               vertexmark(endpoint1), vertexmark(endpoint2));
14736     } else {
14737       fprintf(outfile, "%4ld    %4d  %4d    %4d\n", subsegnumber,
14738               vertexmark(endpoint1), vertexmark(endpoint2), mark(subsegloop));
14739     }
14740 #endif /* not TRILIBRARY */
14741 
14742     subsegloop.ss = subsegtraverse(m);
14743     subsegnumber++;
14744   }
14745 
14746 #ifndef TRILIBRARY
14747 #ifndef CDT_ONLY
14748   fprintf(outfile, "%d\n", holes);
14749   if (holes > 0) {
14750     for (holenumber = 0; holenumber < holes; holenumber++) {
14751       /* Hole number, x and y coordinates. */
14752       fprintf(outfile, "%4ld   %.17g  %.17g\n", b->firstnumber + holenumber,
14753               holelist[2 * holenumber], holelist[2 * holenumber + 1]);
14754     }
14755   }
14756   if (regions > 0) {
14757     fprintf(outfile, "%d\n", regions);
14758     for (regionnumber = 0; regionnumber < regions; regionnumber++) {
14759       /* Region number, x and y coordinates, attribute, maximum area. */
14760       fprintf(outfile, "%4ld   %.17g  %.17g  %.17g  %.17g\n",
14761               b->firstnumber + regionnumber,
14762               regionlist[4 * regionnumber], regionlist[4 * regionnumber + 1],
14763               regionlist[4 * regionnumber + 2],
14764               regionlist[4 * regionnumber + 3]);
14765     }
14766   }
14767 #endif /* not CDT_ONLY */
14768 
14769   finishfile(outfile, argc, argv);
14770 #endif /* not TRILIBRARY */
14771 }
14772 
14773 /*****************************************************************************/
14774 /*                                                                           */
14775 /*  writeedges()   Write the edges to an .edge file.                         */
14776 /*                                                                           */
14777 /*****************************************************************************/
14778 
14779 #ifdef TRILIBRARY
14780 
14781 #ifdef ANSI_DECLARATORS
14782 void writeedges(struct mesh *m, struct behavior *b,
14783                 int **edgelist, int **edgemarkerlist)
14784 #else /* not ANSI_DECLARATORS */
14785 void writeedges(m, b, edgelist, edgemarkerlist)
14786 struct mesh *m;
14787 struct behavior *b;
14788 int **edgelist;
14789 int **edgemarkerlist;
14790 #endif /* not ANSI_DECLARATORS */
14791 
14792 #else /* not TRILIBRARY */
14793 
14794 #ifdef ANSI_DECLARATORS
14795 void writeedges(struct mesh *m, struct behavior *b, char *edgefilename,
14796                 int argc, char **argv)
14797 #else /* not ANSI_DECLARATORS */
14798 void writeedges(m, b, edgefilename, argc, argv)
14799 struct mesh *m;
14800 struct behavior *b;
14801 char *edgefilename;
14802 int argc;
14803 char **argv;
14804 #endif /* not ANSI_DECLARATORS */
14805 
14806 #endif /* not TRILIBRARY */
14807 
14808 {
14809 #ifdef TRILIBRARY
14810   int *elist;
14811   int *emlist;
14812   int index;
14813 #else /* not TRILIBRARY */
14814   FILE *outfile;
14815 #endif /* not TRILIBRARY */
14816   struct otri triangleloop, trisym;
14817   struct osub checkmark;
14818   vertex p1, p2;
14819   long edgenumber;
14820   triangle ptr;                         /* Temporary variable used by sym(). */
14821   subseg sptr;                      /* Temporary variable used by tspivot(). */
14822 
14823 #ifdef TRILIBRARY
14824   if (!b->quiet) {
14825     printf("Writing edges.\n");
14826   }
14827   /* Allocate memory for edges if necessary. */
14828   if (*edgelist == (int *) NULL) {
14829     *edgelist = (int *) trimalloc((int) (m->edges * 2 * sizeof(int)));
14830   }
14831   /* Allocate memory for edge markers if necessary. */
14832   if (!b->nobound && (*edgemarkerlist == (int *) NULL)) {
14833     *edgemarkerlist = (int *) trimalloc((int) (m->edges * sizeof(int)));
14834   }
14835   elist = *edgelist;
14836   emlist = *edgemarkerlist;
14837   index = 0;
14838 #else /* not TRILIBRARY */
14839   if (!b->quiet) {
14840     printf("Writing %s.\n", edgefilename);
14841   }
14842   outfile = fopen(edgefilename, "w");
14843   if (outfile == (FILE *) NULL) {
14844     printf("  Error:  Cannot create file %s.\n", edgefilename);
14845     triexit(1);
14846   }
14847   /* Number of edges, number of boundary markers (zero or one). */
14848   fprintf(outfile, "%ld  %d\n", m->edges, 1 - b->nobound);
14849 #endif /* not TRILIBRARY */
14850 
14851   traversalinit(&m->triangles);
14852   triangleloop.tri = triangletraverse(m);
14853   edgenumber = b->firstnumber;
14854   /* To loop over the set of edges, loop over all triangles, and look at   */
14855   /*   the three edges of each triangle.  If there isn't another triangle  */
14856   /*   adjacent to the edge, operate on the edge.  If there is another     */
14857   /*   adjacent triangle, operate on the edge only if the current triangle */
14858   /*   has a smaller pointer than its neighbor.  This way, each edge is    */
14859   /*   considered only once.                                               */
14860   while (triangleloop.tri != (triangle *) NULL) {
14861     for (triangleloop.orient = 0; triangleloop.orient < 3;
14862          triangleloop.orient++) {
14863       sym(triangleloop, trisym);
14864       if ((triangleloop.tri < trisym.tri) || (trisym.tri == m->dummytri)) {
14865         org(triangleloop, p1);
14866         dest(triangleloop, p2);
14867 #ifdef TRILIBRARY
14868         elist[index++] = vertexmark(p1);
14869         elist[index++] = vertexmark(p2);
14870 #endif /* TRILIBRARY */
14871         if (b->nobound) {
14872 #ifndef TRILIBRARY
14873           /* Edge number, indices of two endpoints. */
14874           fprintf(outfile, "%4ld   %d  %d\n", edgenumber,
14875                   vertexmark(p1), vertexmark(p2));
14876 #endif /* not TRILIBRARY */
14877         } else {
14878           /* Edge number, indices of two endpoints, and a boundary marker. */
14879           /*   If there's no subsegment, the boundary marker is zero.      */
14880           if (b->usesegments) {
14881             tspivot(triangleloop, checkmark);
14882             if (checkmark.ss == m->dummysub) {
14883 #ifdef TRILIBRARY
14884               emlist[edgenumber - b->firstnumber] = 0;
14885 #else /* not TRILIBRARY */
14886               fprintf(outfile, "%4ld   %d  %d  %d\n", edgenumber,
14887                       vertexmark(p1), vertexmark(p2), 0);
14888 #endif /* not TRILIBRARY */
14889             } else {
14890 #ifdef TRILIBRARY
14891               emlist[edgenumber - b->firstnumber] = mark(checkmark);
14892 #else /* not TRILIBRARY */
14893               fprintf(outfile, "%4ld   %d  %d  %d\n", edgenumber,
14894                       vertexmark(p1), vertexmark(p2), mark(checkmark));
14895 #endif /* not TRILIBRARY */
14896             }
14897           } else {
14898 #ifdef TRILIBRARY
14899             emlist[edgenumber - b->firstnumber] = trisym.tri == m->dummytri;
14900 #else /* not TRILIBRARY */
14901             fprintf(outfile, "%4ld   %d  %d  %d\n", edgenumber,
14902                     vertexmark(p1), vertexmark(p2), trisym.tri == m->dummytri);
14903 #endif /* not TRILIBRARY */
14904           }
14905         }
14906         edgenumber++;
14907       }
14908     }
14909     triangleloop.tri = triangletraverse(m);
14910   }
14911 
14912 #ifndef TRILIBRARY
14913   finishfile(outfile, argc, argv);
14914 #endif /* not TRILIBRARY */
14915 }
14916 
14917 /*****************************************************************************/
14918 /*                                                                           */
14919 /*  writevoronoi()   Write the Voronoi diagram to a .v.node and .v.edge      */
14920 /*                   file.                                                   */
14921 /*                                                                           */
14922 /*  The Voronoi diagram is the geometric dual of the Delaunay triangulation. */
14923 /*  Hence, the Voronoi vertices are listed by traversing the Delaunay        */
14924 /*  triangles, and the Voronoi edges are listed by traversing the Delaunay   */
14925 /*  edges.                                                                   */
14926 /*                                                                           */
14927 /*  WARNING:  In order to assign numbers to the Voronoi vertices, this       */
14928 /*  procedure messes up the subsegments or the extra nodes of every          */
14929 /*  element.  Hence, you should call this procedure last.                    */
14930 /*                                                                           */
14931 /*****************************************************************************/
14932 
14933 #ifdef TRILIBRARY
14934 
14935 #ifdef ANSI_DECLARATORS
14936 void writevoronoi(struct mesh *m, struct behavior *b, REAL **vpointlist,
14937                   REAL **vpointattriblist, int **vpointmarkerlist,
14938                   int **vedgelist, int **vedgemarkerlist, REAL **vnormlist)
14939 #else /* not ANSI_DECLARATORS */
14940 void writevoronoi(m, b, vpointlist, vpointattriblist, vpointmarkerlist,
14941                   vedgelist, vedgemarkerlist, vnormlist)
14942 struct mesh *m;
14943 struct behavior *b;
14944 REAL **vpointlist;
14945 REAL **vpointattriblist;
14946 int **vpointmarkerlist;
14947 int **vedgelist;
14948 int **vedgemarkerlist;
14949 REAL **vnormlist;
14950 #endif /* not ANSI_DECLARATORS */
14951 
14952 #else /* not TRILIBRARY */
14953 
14954 #ifdef ANSI_DECLARATORS
14955 void writevoronoi(struct mesh *m, struct behavior *b, char *vnodefilename,
14956                   char *vedgefilename, int argc, char **argv)
14957 #else /* not ANSI_DECLARATORS */
14958 void writevoronoi(m, b, vnodefilename, vedgefilename, argc, argv)
14959 struct mesh *m;
14960 struct behavior *b;
14961 char *vnodefilename;
14962 char *vedgefilename;
14963 int argc;
14964 char **argv;
14965 #endif /* not ANSI_DECLARATORS */
14966 
14967 #endif /* not TRILIBRARY */
14968 
14969 {
14970 #ifdef TRILIBRARY
14971   REAL *plist;
14972   REAL *palist;
14973   int *elist;
14974   REAL *normlist;
14975   int coordindex;
14976   int attribindex;
14977 #else /* not TRILIBRARY */
14978   FILE *outfile;
14979 #endif /* not TRILIBRARY */
14980   struct otri triangleloop, trisym;
14981   vertex torg, tdest, tapex;
14982   REAL circumcenter[2];
14983   REAL xi, eta;
14984   long vnodenumber, vedgenumber;
14985   int p1, p2;
14986   int i;
14987   triangle ptr;                         /* Temporary variable used by sym(). */
14988 
14989 #ifdef TRILIBRARY
14990   if (!b->quiet) {
14991     printf("Writing Voronoi vertices.\n");
14992   }
14993   /* Allocate memory for Voronoi vertices if necessary. */
14994   if (*vpointlist == (REAL *) NULL) {
14995     *vpointlist = (REAL *) trimalloc((int) (m->triangles.items * 2 *
14996                                             sizeof(REAL)));
14997   }
14998   /* Allocate memory for Voronoi vertex attributes if necessary. */
14999   if (*vpointattriblist == (REAL *) NULL) {
15000     *vpointattriblist = (REAL *) trimalloc((int) (m->triangles.items *
15001                                                   m->nextras * sizeof(REAL)));
15002   }
15003   *vpointmarkerlist = (int *) NULL;
15004   plist = *vpointlist;
15005   palist = *vpointattriblist;
15006   coordindex = 0;
15007   attribindex = 0;
15008 #else /* not TRILIBRARY */
15009   if (!b->quiet) {
15010     printf("Writing %s.\n", vnodefilename);
15011   }
15012   outfile = fopen(vnodefilename, "w");
15013   if (outfile == (FILE *) NULL) {
15014     printf("  Error:  Cannot create file %s.\n", vnodefilename);
15015     triexit(1);
15016   }
15017   /* Number of triangles, two dimensions, number of vertex attributes, */
15018   /*   no markers.                                                     */
15019   fprintf(outfile, "%ld  %d  %d  %d\n", m->triangles.items, 2, m->nextras, 0);
15020 #endif /* not TRILIBRARY */
15021 
15022   traversalinit(&m->triangles);
15023   triangleloop.tri = triangletraverse(m);
15024   triangleloop.orient = 0;
15025   vnodenumber = b->firstnumber;
15026   while (triangleloop.tri != (triangle *) NULL) {
15027     org(triangleloop, torg);
15028     dest(triangleloop, tdest);
15029     apex(triangleloop, tapex);
15030     findcircumcenter(m, b, torg, tdest, tapex, circumcenter, &xi, &eta, 0);
15031 #ifdef TRILIBRARY
15032     /* X and y coordinates. */
15033     plist[coordindex++] = circumcenter[0];
15034     plist[coordindex++] = circumcenter[1];
15035     for (i = 2; i < 2 + m->nextras; i++) {
15036       /* Interpolate the vertex attributes at the circumcenter. */
15037       palist[attribindex++] = torg[i] + xi * (tdest[i] - torg[i])
15038                                      + eta * (tapex[i] - torg[i]);
15039     }
15040 #else /* not TRILIBRARY */
15041     /* Voronoi vertex number, x and y coordinates. */
15042     fprintf(outfile, "%4ld    %.17g  %.17g", vnodenumber, circumcenter[0],
15043             circumcenter[1]);
15044     for (i = 2; i < 2 + m->nextras; i++) {
15045       /* Interpolate the vertex attributes at the circumcenter. */
15046       fprintf(outfile, "  %.17g", torg[i] + xi * (tdest[i] - torg[i])
15047                                          + eta * (tapex[i] - torg[i]));
15048     }
15049     fprintf(outfile, "\n");
15050 #endif /* not TRILIBRARY */
15051 
15052     * (int *) (triangleloop.tri + 6) = (int) vnodenumber;
15053     triangleloop.tri = triangletraverse(m);
15054     vnodenumber++;
15055   }
15056 
15057 #ifndef TRILIBRARY
15058   finishfile(outfile, argc, argv);
15059 #endif /* not TRILIBRARY */
15060 
15061 #ifdef TRILIBRARY
15062   if (!b->quiet) {
15063     printf("Writing Voronoi edges.\n");
15064   }
15065   /* Allocate memory for output Voronoi edges if necessary. */
15066   if (*vedgelist == (int *) NULL) {
15067     *vedgelist = (int *) trimalloc((int) (m->edges * 2 * sizeof(int)));
15068   }
15069   *vedgemarkerlist = (int *) NULL;
15070   /* Allocate memory for output Voronoi norms if necessary. */
15071   if (*vnormlist == (REAL *) NULL) {
15072     *vnormlist = (REAL *) trimalloc((int) (m->edges * 2 * sizeof(REAL)));
15073   }
15074   elist = *vedgelist;
15075   normlist = *vnormlist;
15076   coordindex = 0;
15077 #else /* not TRILIBRARY */
15078   if (!b->quiet) {
15079     printf("Writing %s.\n", vedgefilename);
15080   }
15081   outfile = fopen(vedgefilename, "w");
15082   if (outfile == (FILE *) NULL) {
15083     printf("  Error:  Cannot create file %s.\n", vedgefilename);
15084     triexit(1);
15085   }
15086   /* Number of edges, zero boundary markers. */
15087   fprintf(outfile, "%ld  %d\n", m->edges, 0);
15088 #endif /* not TRILIBRARY */
15089 
15090   traversalinit(&m->triangles);
15091   triangleloop.tri = triangletraverse(m);
15092   vedgenumber = b->firstnumber;
15093   /* To loop over the set of edges, loop over all triangles, and look at   */
15094   /*   the three edges of each triangle.  If there isn't another triangle  */
15095   /*   adjacent to the edge, operate on the edge.  If there is another     */
15096   /*   adjacent triangle, operate on the edge only if the current triangle */
15097   /*   has a smaller pointer than its neighbor.  This way, each edge is    */
15098   /*   considered only once.                                               */
15099   while (triangleloop.tri != (triangle *) NULL) {
15100     for (triangleloop.orient = 0; triangleloop.orient < 3;
15101          triangleloop.orient++) {
15102       sym(triangleloop, trisym);
15103       if ((triangleloop.tri < trisym.tri) || (trisym.tri == m->dummytri)) {
15104         /* Find the number of this triangle (and Voronoi vertex). */
15105         p1 = * (int *) (triangleloop.tri + 6);
15106         if (trisym.tri == m->dummytri) {
15107           org(triangleloop, torg);
15108           dest(triangleloop, tdest);
15109 #ifdef TRILIBRARY
15110           /* Copy an infinite ray.  Index of one endpoint, and -1. */
15111           elist[coordindex] = p1;
15112           normlist[coordindex++] = tdest[1] - torg[1];
15113           elist[coordindex] = -1;
15114           normlist[coordindex++] = torg[0] - tdest[0];
15115 #else /* not TRILIBRARY */
15116           /* Write an infinite ray.  Edge number, index of one endpoint, -1, */
15117           /*   and x and y coordinates of a vector representing the          */
15118           /*   direction of the ray.                                         */
15119           fprintf(outfile, "%4ld   %d  %d   %.17g  %.17g\n", vedgenumber,
15120                   p1, -1, tdest[1] - torg[1], torg[0] - tdest[0]);
15121 #endif /* not TRILIBRARY */
15122         } else {
15123           /* Find the number of the adjacent triangle (and Voronoi vertex). */
15124           p2 = * (int *) (trisym.tri + 6);
15125           /* Finite edge.  Write indices of two endpoints. */
15126 #ifdef TRILIBRARY
15127           elist[coordindex] = p1;
15128           normlist[coordindex++] = 0.0;
15129           elist[coordindex] = p2;
15130           normlist[coordindex++] = 0.0;
15131 #else /* not TRILIBRARY */
15132           fprintf(outfile, "%4ld   %d  %d\n", vedgenumber, p1, p2);
15133 #endif /* not TRILIBRARY */
15134         }
15135         vedgenumber++;
15136       }
15137     }
15138     triangleloop.tri = triangletraverse(m);
15139   }
15140 
15141 #ifndef TRILIBRARY
15142   finishfile(outfile, argc, argv);
15143 #endif /* not TRILIBRARY */
15144 }
15145 
15146 #ifdef TRILIBRARY
15147 
15148 #ifdef ANSI_DECLARATORS
15149 void writeneighbors(struct mesh *m, struct behavior *b, int **neighborlist)
15150 #else /* not ANSI_DECLARATORS */
15151 void writeneighbors(m, b, neighborlist)
15152 struct mesh *m;
15153 struct behavior *b;
15154 int **neighborlist;
15155 #endif /* not ANSI_DECLARATORS */
15156 
15157 #else /* not TRILIBRARY */
15158 
15159 #ifdef ANSI_DECLARATORS
15160 void writeneighbors(struct mesh *m, struct behavior *b, char *neighborfilename,
15161                     int argc, char **argv)
15162 #else /* not ANSI_DECLARATORS */
15163 void writeneighbors(m, b, neighborfilename, argc, argv)
15164 struct mesh *m;
15165 struct behavior *b;
15166 char *neighborfilename;
15167 int argc;
15168 char **argv;
15169 #endif /* not ANSI_DECLARATORS */
15170 
15171 #endif /* not TRILIBRARY */
15172 
15173 {
15174 #ifdef TRILIBRARY
15175   int *nlist;
15176   int index;
15177 #else /* not TRILIBRARY */
15178   FILE *outfile;
15179 #endif /* not TRILIBRARY */
15180   struct otri triangleloop, trisym;
15181   long elementnumber;
15182   int neighbor1, neighbor2, neighbor3;
15183   triangle ptr;                         /* Temporary variable used by sym(). */
15184 
15185 #ifdef TRILIBRARY
15186   if (!b->quiet) {
15187     printf("Writing neighbors.\n");
15188   }
15189   /* Allocate memory for neighbors if necessary. */
15190   if (*neighborlist == (int *) NULL) {
15191     *neighborlist = (int *) trimalloc((int) (m->triangles.items * 3 *
15192                                              sizeof(int)));
15193   }
15194   nlist = *neighborlist;
15195   index = 0;
15196 #else /* not TRILIBRARY */
15197   if (!b->quiet) {
15198     printf("Writing %s.\n", neighborfilename);
15199   }
15200   outfile = fopen(neighborfilename, "w");
15201   if (outfile == (FILE *) NULL) {
15202     printf("  Error:  Cannot create file %s.\n", neighborfilename);
15203     triexit(1);
15204   }
15205   /* Number of triangles, three neighbors per triangle. */
15206   fprintf(outfile, "%ld  %d\n", m->triangles.items, 3);
15207 #endif /* not TRILIBRARY */
15208 
15209   traversalinit(&m->triangles);
15210   triangleloop.tri = triangletraverse(m);
15211   triangleloop.orient = 0;
15212   elementnumber = b->firstnumber;
15213   while (triangleloop.tri != (triangle *) NULL) {
15214     * (int *) (triangleloop.tri + 6) = (int) elementnumber;
15215     triangleloop.tri = triangletraverse(m);
15216     elementnumber++;
15217   }
15218   * (int *) (m->dummytri + 6) = -1;
15219 
15220   traversalinit(&m->triangles);
15221   triangleloop.tri = triangletraverse(m);
15222   elementnumber = b->firstnumber;
15223   while (triangleloop.tri != (triangle *) NULL) {
15224     triangleloop.orient = 1;
15225     sym(triangleloop, trisym);
15226     neighbor1 = * (int *) (trisym.tri + 6);
15227     triangleloop.orient = 2;
15228     sym(triangleloop, trisym);
15229     neighbor2 = * (int *) (trisym.tri + 6);
15230     triangleloop.orient = 0;
15231     sym(triangleloop, trisym);
15232     neighbor3 = * (int *) (trisym.tri + 6);
15233 #ifdef TRILIBRARY
15234     nlist[index++] = neighbor1;
15235     nlist[index++] = neighbor2;
15236     nlist[index++] = neighbor3;
15237 #else /* not TRILIBRARY */
15238     /* Triangle number, neighboring triangle numbers. */
15239     fprintf(outfile, "%4ld    %d  %d  %d\n", elementnumber,
15240             neighbor1, neighbor2, neighbor3);
15241 #endif /* not TRILIBRARY */
15242 
15243     triangleloop.tri = triangletraverse(m);
15244     elementnumber++;
15245   }
15246 
15247 #ifndef TRILIBRARY
15248   finishfile(outfile, argc, argv);
15249 #endif /* not TRILIBRARY */
15250 }
15251 
15252 /*****************************************************************************/
15253 /*                                                                           */
15254 /*  writeoff()   Write the triangulation to an .off file.                    */
15255 /*                                                                           */
15256 /*  OFF stands for the Object File Format, a format used by the Geometry     */
15257 /*  Center's Geomview package.                                               */
15258 /*                                                                           */
15259 /*****************************************************************************/
15260 
15261 #ifndef TRILIBRARY
15262 
15263 #ifdef ANSI_DECLARATORS
15264 void writeoff(struct mesh *m, struct behavior *b, char *offfilename,
15265               int argc, char **argv)
15266 #else /* not ANSI_DECLARATORS */
15267 void writeoff(m, b, offfilename, argc, argv)
15268 struct mesh *m;
15269 struct behavior *b;
15270 char *offfilename;
15271 int argc;
15272 char **argv;
15273 #endif /* not ANSI_DECLARATORS */
15274 
15275 {
15276   FILE *outfile;
15277   struct otri triangleloop;
15278   vertex vertexloop;
15279   vertex p1, p2, p3;
15280   long outvertices;
15281 
15282   if (!b->quiet) {
15283     printf("Writing %s.\n", offfilename);
15284   }
15285 
15286   if (b->jettison) {
15287     outvertices = m->vertices.items - m->undeads;
15288   } else {
15289     outvertices = m->vertices.items;
15290   }
15291 
15292   outfile = fopen(offfilename, "w");
15293   if (outfile == (FILE *) NULL) {
15294     printf("  Error:  Cannot create file %s.\n", offfilename);
15295     triexit(1);
15296   }
15297   /* Number of vertices, triangles, and edges. */
15298   fprintf(outfile, "OFF\n%ld  %ld  %ld\n", outvertices, m->triangles.items,
15299           m->edges);
15300 
15301   /* Write the vertices. */
15302   traversalinit(&m->vertices);
15303   vertexloop = vertextraverse(m);
15304   while (vertexloop != (vertex) NULL) {
15305     if (!b->jettison || (vertextype(vertexloop) != UNDEADVERTEX)) {
15306       /* The "0.0" is here because the OFF format uses 3D coordinates. */
15307       fprintf(outfile, " %.17g  %.17g  %.17g\n", vertexloop[0], vertexloop[1],
15308               0.0);
15309     }
15310     vertexloop = vertextraverse(m);
15311   }
15312 
15313   /* Write the triangles. */
15314   traversalinit(&m->triangles);
15315   triangleloop.tri = triangletraverse(m);
15316   triangleloop.orient = 0;
15317   while (triangleloop.tri != (triangle *) NULL) {
15318     org(triangleloop, p1);
15319     dest(triangleloop, p2);
15320     apex(triangleloop, p3);
15321     /* The "3" means a three-vertex polygon. */
15322     fprintf(outfile, " 3   %4d  %4d  %4d\n", vertexmark(p1) - b->firstnumber,
15323             vertexmark(p2) - b->firstnumber, vertexmark(p3) - b->firstnumber);
15324     triangleloop.tri = triangletraverse(m);
15325   }
15326   finishfile(outfile, argc, argv);
15327 }
15328 
15329 #endif /* not TRILIBRARY */
15330 
15331 /**                                                                         **/
15332 /**                                                                         **/
15333 /********* File I/O routines end here                                *********/
15334 
15335 /*****************************************************************************/
15336 /*                                                                           */
15337 /*  quality_statistics()   Print statistics about the quality of the mesh.   */
15338 /*                                                                           */
15339 /*****************************************************************************/
15340 
15341 #ifdef ANSI_DECLARATORS
15342 void quality_statistics(struct mesh *m, struct behavior *b)
15343 #else /* not ANSI_DECLARATORS */
15344 void quality_statistics(m, b)
15345 struct mesh *m;
15346 struct behavior *b;
15347 #endif /* not ANSI_DECLARATORS */
15348 
15349 {
15350   struct otri triangleloop;
15351   vertex p[3];
15352   REAL cossquaretable[8];
15353   REAL ratiotable[16];
15354   REAL dx[3], dy[3];
15355   REAL edgelength[3];
15356   REAL dotproduct;
15357   REAL cossquare;
15358   REAL triarea;
15359   REAL shortest, longest;
15360   REAL trilongest2;
15361   REAL smallestarea, biggestarea;
15362   REAL triminaltitude2;
15363   REAL minaltitude;
15364   REAL triaspect2;
15365   REAL worstaspect;
15366   REAL smallestangle, biggestangle;
15367   REAL radconst, degconst;
15368   int angletable[18];
15369   int aspecttable[16];
15370   int aspectindex;
15371   int tendegree;
15372   int acutebiggest;
15373   int i, ii, j, k;
15374 
15375   printf("Mesh quality statistics:\n\n");
15376   radconst = PI / 18.0;
15377   degconst = 180.0 / PI;
15378   for (i = 0; i < 8; i++) {
15379     cossquaretable[i] = cos(radconst * (REAL) (i + 1));
15380     cossquaretable[i] = cossquaretable[i] * cossquaretable[i];
15381   }
15382   for (i = 0; i < 18; i++) {
15383     angletable[i] = 0;
15384   }
15385 
15386   ratiotable[0]  =      1.5;      ratiotable[1]  =     2.0;
15387   ratiotable[2]  =      2.5;      ratiotable[3]  =     3.0;
15388   ratiotable[4]  =      4.0;      ratiotable[5]  =     6.0;
15389   ratiotable[6]  =     10.0;      ratiotable[7]  =    15.0;
15390   ratiotable[8]  =     25.0;      ratiotable[9]  =    50.0;
15391   ratiotable[10] =    100.0;      ratiotable[11] =   300.0;
15392   ratiotable[12] =   1000.0;      ratiotable[13] = 10000.0;
15393   ratiotable[14] = 100000.0;      ratiotable[15] =     0.0;
15394   for (i = 0; i < 16; i++) {
15395     aspecttable[i] = 0;
15396   }
15397 
15398   worstaspect = 0.0;
15399   minaltitude = m->xmax - m->xmin + m->ymax - m->ymin;
15400   minaltitude = minaltitude * minaltitude;
15401   shortest = minaltitude;
15402   longest = 0.0;
15403   smallestarea = minaltitude;
15404   biggestarea = 0.0;
15405   worstaspect = 0.0;
15406   smallestangle = 0.0;
15407   biggestangle = 2.0;
15408   acutebiggest = 1;
15409 
15410   traversalinit(&m->triangles);
15411   triangleloop.tri = triangletraverse(m);
15412   triangleloop.orient = 0;
15413   while (triangleloop.tri != (triangle *) NULL) {
15414     org(triangleloop, p[0]);
15415     dest(triangleloop, p[1]);
15416     apex(triangleloop, p[2]);
15417     trilongest2 = 0.0;
15418 
15419     for (i = 0; i < 3; i++) {
15420       j = plus1mod3[i];
15421       k = minus1mod3[i];
15422       dx[i] = p[j][0] - p[k][0];
15423       dy[i] = p[j][1] - p[k][1];
15424       edgelength[i] = dx[i] * dx[i] + dy[i] * dy[i];
15425       if (edgelength[i] > trilongest2) {
15426         trilongest2 = edgelength[i];
15427       }
15428       if (edgelength[i] > longest) {
15429         longest = edgelength[i];
15430       }
15431       if (edgelength[i] < shortest) {
15432         shortest = edgelength[i];
15433       }
15434     }
15435 
15436     triarea = counterclockwise(m, b, p[0], p[1], p[2]);
15437     if (triarea < smallestarea) {
15438       smallestarea = triarea;
15439     }
15440     if (triarea > biggestarea) {
15441       biggestarea = triarea;
15442     }
15443     triminaltitude2 = triarea * triarea / trilongest2;
15444     if (triminaltitude2 < minaltitude) {
15445       minaltitude = triminaltitude2;
15446     }
15447     triaspect2 = trilongest2 / triminaltitude2;
15448     if (triaspect2 > worstaspect) {
15449       worstaspect = triaspect2;
15450     }
15451     aspectindex = 0;
15452     while ((triaspect2 > ratiotable[aspectindex] * ratiotable[aspectindex])
15453            && (aspectindex < 15)) {
15454       aspectindex++;
15455     }
15456     aspecttable[aspectindex]++;
15457 
15458     for (i = 0; i < 3; i++) {
15459       j = plus1mod3[i];
15460       k = minus1mod3[i];
15461       dotproduct = dx[j] * dx[k] + dy[j] * dy[k];
15462       cossquare = dotproduct * dotproduct / (edgelength[j] * edgelength[k]);
15463       tendegree = 8;
15464       for (ii = 7; ii >= 0; ii--) {
15465         if (cossquare > cossquaretable[ii]) {
15466           tendegree = ii;
15467         }
15468       }
15469       if (dotproduct <= 0.0) {
15470         angletable[tendegree]++;
15471         if (cossquare > smallestangle) {
15472           smallestangle = cossquare;
15473         }
15474         if (acutebiggest && (cossquare < biggestangle)) {
15475           biggestangle = cossquare;
15476         }
15477       } else {
15478         angletable[17 - tendegree]++;
15479         if (acutebiggest || (cossquare > biggestangle)) {
15480           biggestangle = cossquare;
15481           acutebiggest = 0;
15482         }
15483       }
15484     }
15485     triangleloop.tri = triangletraverse(m);
15486   }
15487 
15488   shortest = sqrt(shortest);
15489   longest = sqrt(longest);
15490   minaltitude = sqrt(minaltitude);
15491   worstaspect = sqrt(worstaspect);
15492   smallestarea *= 0.5;
15493   biggestarea *= 0.5;
15494   if (smallestangle >= 1.0) {
15495     smallestangle = 0.0;
15496   } else {
15497     smallestangle = degconst * acos(sqrt(smallestangle));
15498   }
15499   if (biggestangle >= 1.0) {
15500     biggestangle = 180.0;
15501   } else {
15502     if (acutebiggest) {
15503       biggestangle = degconst * acos(sqrt(biggestangle));
15504     } else {
15505       biggestangle = 180.0 - degconst * acos(sqrt(biggestangle));
15506     }
15507   }
15508 
15509   printf("  Smallest area: %16.5g   |  Largest area: %16.5g\n",
15510          smallestarea, biggestarea);
15511   printf("  Shortest edge: %16.5g   |  Longest edge: %16.5g\n",
15512          shortest, longest);
15513   printf("  Shortest altitude: %12.5g   |  Largest aspect ratio: %8.5g\n\n",
15514          minaltitude, worstaspect);
15515 
15516   printf("  Triangle aspect ratio histogram:\n");
15517   printf("  1.1547 - %-6.6g    :  %8d    | %6.6g - %-6.6g     :  %8d\n",
15518          ratiotable[0], aspecttable[0], ratiotable[7], ratiotable[8],
15519          aspecttable[8]);
15520   for (i = 1; i < 7; i++) {
15521     printf("  %6.6g - %-6.6g    :  %8d    | %6.6g - %-6.6g     :  %8d\n",
15522            ratiotable[i - 1], ratiotable[i], aspecttable[i],
15523            ratiotable[i + 7], ratiotable[i + 8], aspecttable[i + 8]);
15524   }
15525   printf("  %6.6g - %-6.6g    :  %8d    | %6.6g -            :  %8d\n",
15526          ratiotable[6], ratiotable[7], aspecttable[7], ratiotable[14],
15527          aspecttable[15]);
15528   printf("  (Aspect ratio is longest edge divided by shortest altitude)\n\n");
15529 
15530   printf("  Smallest angle: %15.5g   |  Largest angle: %15.5g\n\n",
15531          smallestangle, biggestangle);
15532 
15533   printf("  Angle histogram:\n");
15534   for (i = 0; i < 9; i++) {
15535     printf("    %3d - %3d degrees:  %8d    |    %3d - %3d degrees:  %8d\n",
15536            i * 10, i * 10 + 10, angletable[i],
15537            i * 10 + 90, i * 10 + 100, angletable[i + 9]);
15538   }
15539   printf("\n");
15540 }
15541 
15542 /*****************************************************************************/
15543 /*                                                                           */
15544 /*  statistics()   Print all sorts of cool facts.                            */
15545 /*                                                                           */
15546 /*****************************************************************************/
15547 
15548 #ifdef ANSI_DECLARATORS
15549 void statistics(struct mesh *m, struct behavior *b)
15550 #else /* not ANSI_DECLARATORS */
15551 void statistics(m, b)
15552 struct mesh *m;
15553 struct behavior *b;
15554 #endif /* not ANSI_DECLARATORS */
15555 
15556 {
15557   printf("\nStatistics:\n\n");
15558   printf("  Input vertices: %d\n", m->invertices);
15559   if (b->refine) {
15560     printf("  Input triangles: %d\n", m->inelements);
15561   }
15562   if (b->poly) {
15563     printf("  Input segments: %d\n", m->insegments);
15564     if (!b->refine) {
15565       printf("  Input holes: %d\n", m->holes);
15566     }
15567   }
15568 
15569   printf("\n  Mesh vertices: %ld\n", m->vertices.items - m->undeads);
15570   printf("  Mesh triangles: %ld\n", m->triangles.items);
15571   printf("  Mesh edges: %ld\n", m->edges);
15572   printf("  Mesh exterior boundary edges: %ld\n", m->hullsize);
15573   if (b->poly || b->refine) {
15574     printf("  Mesh interior boundary edges: %ld\n",
15575            m->subsegs.items - m->hullsize);
15576     printf("  Mesh subsegments (constrained edges): %ld\n",
15577            m->subsegs.items);
15578   }
15579   printf("\n");
15580 
15581   if (b->verbose) {
15582     quality_statistics(m, b);
15583     printf("Memory allocation statistics:\n\n");
15584     printf("  Maximum number of vertices: %ld\n", m->vertices.maxitems);
15585     printf("  Maximum number of triangles: %ld\n", m->triangles.maxitems);
15586     if (m->subsegs.maxitems > 0) {
15587       printf("  Maximum number of subsegments: %ld\n", m->subsegs.maxitems);
15588     }
15589     if (m->viri.maxitems > 0) {
15590       printf("  Maximum number of viri: %ld\n", m->viri.maxitems);
15591     }
15592     if (m->badsubsegs.maxitems > 0) {
15593       printf("  Maximum number of encroached subsegments: %ld\n",
15594              m->badsubsegs.maxitems);
15595     }
15596     if (m->badtriangles.maxitems > 0) {
15597       printf("  Maximum number of bad triangles: %ld\n",
15598              m->badtriangles.maxitems);
15599     }
15600     if (m->flipstackers.maxitems > 0) {
15601       printf("  Maximum number of stacked triangle flips: %ld\n",
15602              m->flipstackers.maxitems);
15603     }
15604     if (m->splaynodes.maxitems > 0) {
15605       printf("  Maximum number of splay tree nodes: %ld\n",
15606              m->splaynodes.maxitems);
15607     }
15608     printf("  Approximate heap memory use (bytes): %ld\n\n",
15609            m->vertices.maxitems * m->vertices.itembytes +
15610            m->triangles.maxitems * m->triangles.itembytes +
15611            m->subsegs.maxitems * m->subsegs.itembytes +
15612            m->viri.maxitems * m->viri.itembytes +
15613            m->badsubsegs.maxitems * m->badsubsegs.itembytes +
15614            m->badtriangles.maxitems * m->badtriangles.itembytes +
15615            m->flipstackers.maxitems * m->flipstackers.itembytes +
15616            m->splaynodes.maxitems * m->splaynodes.itembytes);
15617 
15618     printf("Algorithmic statistics:\n\n");
15619     if (!b->weighted) {
15620       printf("  Number of incircle tests: %ld\n", m->incirclecount);
15621     } else {
15622       printf("  Number of 3D orientation tests: %ld\n", m->orient3dcount);
15623     }
15624     printf("  Number of 2D orientation tests: %ld\n", m->counterclockcount);
15625     if (m->hyperbolacount > 0) {
15626       printf("  Number of right-of-hyperbola tests: %ld\n",
15627              m->hyperbolacount);
15628     }
15629     if (m->circletopcount > 0) {
15630       printf("  Number of circle top computations: %ld\n",
15631              m->circletopcount);
15632     }
15633     if (m->circumcentercount > 0) {
15634       printf("  Number of triangle circumcenter computations: %ld\n",
15635              m->circumcentercount);
15636     }
15637     printf("\n");
15638   }
15639 }
15640 
15641 /*****************************************************************************/
15642 /*                                                                           */
15643 /*  main() or triangulate()   Gosh, do everything.                           */
15644 /*                                                                           */
15645 /*  The sequence is roughly as follows.  Many of these steps can be skipped, */
15646 /*  depending on the command line switches.                                  */
15647 /*                                                                           */
15648 /*  - Initialize constants and parse the command line.                       */
15649 /*  - Read the vertices from a file and either                               */
15650 /*    - triangulate them (no -r), or                                         */
15651 /*    - read an old mesh from files and reconstruct it (-r).                 */
15652 /*  - Insert the PSLG segments (-p), and possibly segments on the convex     */
15653 /*      hull (-c).                                                           */
15654 /*  - Read the holes (-p), regional attributes (-pA), and regional area      */
15655 /*      constraints (-pa).  Carve the holes and concavities, and spread the  */
15656 /*      regional attributes and area constraints.                            */
15657 /*  - Enforce the constraints on minimum angle (-q) and maximum area (-a).   */
15658 /*      Also enforce the conforming Delaunay property (-q and -a).           */
15659 /*  - Compute the number of edges in the resulting mesh.                     */
15660 /*  - Promote the mesh's linear triangles to higher order elements (-o).     */
15661 /*  - Write the output files and print the statistics.                       */
15662 /*  - Check the consistency and Delaunay property of the mesh (-C).          */
15663 /*                                                                           */
15664 /*****************************************************************************/
15665 
15666 #ifdef TRILIBRARY
15667 
15668 #ifdef ANSI_DECLARATORS
15669 void triangulate(char *triswitches, struct triangulateio *in,
15670                  struct triangulateio *out, struct triangulateio *vorout)
15671 #else /* not ANSI_DECLARATORS */
15672 void triangulate(triswitches, in, out, vorout)
15673 char *triswitches;
15674 struct triangulateio *in;
15675 struct triangulateio *out;
15676 struct triangulateio *vorout;
15677 #endif /* not ANSI_DECLARATORS */
15678 
15679 #else /* not TRILIBRARY */
15680 
15681 #ifdef ANSI_DECLARATORS
15682 int main(int argc, char **argv)
15683 #else /* not ANSI_DECLARATORS */
15684 int main(argc, argv)
15685 int argc;
15686 char **argv;
15687 #endif /* not ANSI_DECLARATORS */
15688 
15689 #endif /* not TRILIBRARY */
15690 
15691 {
15692   struct mesh m;
15693   struct behavior b;
15694   REAL *holearray;                                        /* Array of holes. */
15695   REAL *regionarray;   /* Array of regional attributes and area constraints. */
15696 #ifndef TRILIBRARY
15697   FILE *polyfile;
15698 #endif /* not TRILIBRARY */
15699 #ifndef NO_TIMER
15700   /* Variables for timing the performance of Triangle.  The types are */
15701   /*   defined in sys/time.h.                                         */
15702   struct timeval tv0, tv1, tv2, tv3, tv4, tv5, tv6;
15703   struct timezone tz;
15704 #endif /* not NO_TIMER */
15705 
15706 #ifndef NO_TIMER
15707   gettimeofday(&tv0, &tz);
15708 #endif /* not NO_TIMER */
15709 
15710   triangleinit(&m);
15711 #ifdef TRILIBRARY
15712   parsecommandline(1, &triswitches, &b);
15713 #else /* not TRILIBRARY */
15714   parsecommandline(argc, argv, &b);
15715 #endif /* not TRILIBRARY */
15716   m.steinerleft = b.steiner;
15717 
15718 #ifdef TRILIBRARY
15719   transfernodes(&m, &b, in->pointlist, in->pointattributelist,
15720                 in->pointmarkerlist, in->numberofpoints,
15721                 in->numberofpointattributes);
15722 #else /* not TRILIBRARY */
15723   readnodes(&m, &b, b.innodefilename, b.inpolyfilename, &polyfile);
15724 #endif /* not TRILIBRARY */
15725 
15726 #ifndef NO_TIMER
15727   if (!b.quiet) {
15728     gettimeofday(&tv1, &tz);
15729   }
15730 #endif /* not NO_TIMER */
15731 
15732 #ifdef CDT_ONLY
15733   m.hullsize = delaunay(&m, &b);                /* Triangulate the vertices. */
15734 #else /* not CDT_ONLY */
15735   if (b.refine) {
15736     /* Read and reconstruct a mesh. */
15737 #ifdef TRILIBRARY
15738     m.hullsize = reconstruct(&m, &b, in->trianglelist,
15739                              in->triangleattributelist, in->trianglearealist,
15740                              in->numberoftriangles, in->numberofcorners,
15741                              in->numberoftriangleattributes,
15742                              in->segmentlist, in->segmentmarkerlist,
15743                              in->numberofsegments);
15744 #else /* not TRILIBRARY */
15745     m.hullsize = reconstruct(&m, &b, b.inelefilename, b.areafilename,
15746                              b.inpolyfilename, polyfile);
15747 #endif /* not TRILIBRARY */
15748   } else {
15749     m.hullsize = delaunay(&m, &b);              /* Triangulate the vertices. */
15750   }
15751 #endif /* not CDT_ONLY */
15752 
15753 #ifndef NO_TIMER
15754   if (!b.quiet) {
15755     gettimeofday(&tv2, &tz);
15756     if (b.refine) {
15757       printf("Mesh reconstruction");
15758     } else {
15759       printf("Delaunay");
15760     }
15761     printf(" milliseconds:  %ld\n", 1000l * (tv2.tv_sec - tv1.tv_sec) +
15762            (tv2.tv_usec - tv1.tv_usec) / 1000l);
15763   }
15764 #endif /* not NO_TIMER */
15765 
15766   /* Ensure that no vertex can be mistaken for a triangular bounding */
15767   /*   box vertex in insertvertex().                                 */
15768   m.infvertex1 = (vertex) NULL;
15769   m.infvertex2 = (vertex) NULL;
15770   m.infvertex3 = (vertex) NULL;
15771 
15772   if (b.usesegments) {
15773     m.checksegments = 1;                /* Segments will be introduced next. */
15774     if (!b.refine) {
15775       /* Insert PSLG segments and/or convex hull segments. */
15776 #ifdef TRILIBRARY
15777       formskeleton(&m, &b, in->segmentlist,
15778                    in->segmentmarkerlist, in->numberofsegments);
15779 #else /* not TRILIBRARY */
15780       formskeleton(&m, &b, polyfile, b.inpolyfilename);
15781 #endif /* not TRILIBRARY */
15782     }
15783   }
15784 
15785 #ifndef NO_TIMER
15786   if (!b.quiet) {
15787     gettimeofday(&tv3, &tz);
15788     if (b.usesegments && !b.refine) {
15789       printf("Segment milliseconds:  %ld\n",
15790              1000l * (tv3.tv_sec - tv2.tv_sec) +
15791              (tv3.tv_usec - tv2.tv_usec) / 1000l);
15792     }
15793   }
15794 #endif /* not NO_TIMER */
15795 
15796   if (b.poly && (m.triangles.items > 0)) {
15797 #ifdef TRILIBRARY
15798     holearray = in->holelist;
15799     m.holes = in->numberofholes;
15800     regionarray = in->regionlist;
15801     m.regions = in->numberofregions;
15802 #else /* not TRILIBRARY */
15803     readholes(&m, &b, polyfile, b.inpolyfilename, &holearray, &m.holes,
15804               &regionarray, &m.regions);
15805 #endif /* not TRILIBRARY */
15806     if (!b.refine) {
15807       /* Carve out holes and concavities. */
15808       carveholes(&m, &b, holearray, m.holes, regionarray, m.regions);
15809     }
15810   } else {
15811     /* Without a PSLG, there can be no holes or regional attributes   */
15812     /*   or area constraints.  The following are set to zero to avoid */
15813     /*   an accidental free() later.                                  */
15814     m.holes = 0;
15815     m.regions = 0;
15816   }
15817 
15818 #ifndef NO_TIMER
15819   if (!b.quiet) {
15820     gettimeofday(&tv4, &tz);
15821     if (b.poly && !b.refine) {
15822       printf("Hole milliseconds:  %ld\n", 1000l * (tv4.tv_sec - tv3.tv_sec) +
15823              (tv4.tv_usec - tv3.tv_usec) / 1000l);
15824     }
15825   }
15826 #endif /* not NO_TIMER */
15827 
15828 #ifndef CDT_ONLY
15829   if (b.quality && (m.triangles.items > 0)) {
15830     enforcequality(&m, &b);           /* Enforce angle and area constraints. */
15831   }
15832 #endif /* not CDT_ONLY */
15833 
15834 #ifndef NO_TIMER
15835   if (!b.quiet) {
15836     gettimeofday(&tv5, &tz);
15837 #ifndef CDT_ONLY
15838     if (b.quality) {
15839       printf("Quality milliseconds:  %ld\n",
15840              1000l * (tv5.tv_sec - tv4.tv_sec) +
15841              (tv5.tv_usec - tv4.tv_usec) / 1000l);
15842     }
15843 #endif /* not CDT_ONLY */
15844   }
15845 #endif /* not NO_TIMER */
15846 
15847   /* Calculate the number of edges. */
15848   m.edges = (3l * m.triangles.items + m.hullsize) / 2l;
15849 
15850   if (b.order > 1) {
15851     highorder(&m, &b);       /* Promote elements to higher polynomial order. */
15852   }
15853   if (!b.quiet) {
15854     printf("\n");
15855   }
15856 
15857 #ifdef TRILIBRARY
15858   if (b.jettison) {
15859     out->numberofpoints = m.vertices.items - m.undeads;
15860   } else {
15861     out->numberofpoints = m.vertices.items;
15862   }
15863   out->numberofpointattributes = m.nextras;
15864   out->numberoftriangles = m.triangles.items;
15865   out->numberofcorners = (b.order + 1) * (b.order + 2) / 2;
15866   out->numberoftriangleattributes = m.eextras;
15867   out->numberofedges = m.edges;
15868   if (b.usesegments) {
15869     out->numberofsegments = m.subsegs.items;
15870   } else {
15871     out->numberofsegments = m.hullsize;
15872   }
15873   if (vorout != (struct triangulateio *) NULL) {
15874     vorout->numberofpoints = m.triangles.items;
15875     vorout->numberofpointattributes = m.nextras;
15876     vorout->numberofedges = m.edges;
15877   }
15878 #endif /* TRILIBRARY */
15879   /* If not using iteration numbers, don't write a .node file if one was */
15880   /*   read, because the original one would be overwritten!              */
15881   if (b.nonodewritten || (b.noiterationnum && m.readnodefile)) {
15882     if (!b.quiet) {
15883 #ifdef TRILIBRARY
15884       printf("NOT writing vertices.\n");
15885 #else /* not TRILIBRARY */
15886       printf("NOT writing a .node file.\n");
15887 #endif /* not TRILIBRARY */
15888     }
15889     numbernodes(&m, &b);         /* We must remember to number the vertices. */
15890   } else {
15891     /* writenodes() numbers the vertices too. */
15892 #ifdef TRILIBRARY
15893     writenodes(&m, &b, &out->pointlist, &out->pointattributelist,
15894                &out->pointmarkerlist);
15895 #else /* not TRILIBRARY */
15896     writenodes(&m, &b, b.outnodefilename, argc, argv);
15897 #endif /* TRILIBRARY */
15898   }
15899   if (b.noelewritten) {
15900     if (!b.quiet) {
15901 #ifdef TRILIBRARY
15902       printf("NOT writing triangles.\n");
15903 #else /* not TRILIBRARY */
15904       printf("NOT writing an .ele file.\n");
15905 #endif /* not TRILIBRARY */
15906     }
15907   } else {
15908 #ifdef TRILIBRARY
15909     writeelements(&m, &b, &out->trianglelist, &out->triangleattributelist);
15910 #else /* not TRILIBRARY */
15911     writeelements(&m, &b, b.outelefilename, argc, argv);
15912 #endif /* not TRILIBRARY */
15913   }
15914   /* The -c switch (convex switch) causes a PSLG to be written */
15915   /*   even if none was read.                                  */
15916   if (b.poly || b.convex) {
15917     /* If not using iteration numbers, don't overwrite the .poly file. */
15918     if (b.nopolywritten || b.noiterationnum) {
15919       if (!b.quiet) {
15920 #ifdef TRILIBRARY
15921         printf("NOT writing segments.\n");
15922 #else /* not TRILIBRARY */
15923         printf("NOT writing a .poly file.\n");
15924 #endif /* not TRILIBRARY */
15925       }
15926     } else {
15927 #ifdef TRILIBRARY
15928       writepoly(&m, &b, &out->segmentlist, &out->segmentmarkerlist);
15929       out->numberofholes = m.holes;
15930       out->numberofregions = m.regions;
15931       if (b.poly) {
15932         out->holelist = in->holelist;
15933         out->regionlist = in->regionlist;
15934       } else {
15935         out->holelist = (REAL *) NULL;
15936         out->regionlist = (REAL *) NULL;
15937       }
15938 #else /* not TRILIBRARY */
15939       writepoly(&m, &b, b.outpolyfilename, holearray, m.holes, regionarray,
15940                 m.regions, argc, argv);
15941 #endif /* not TRILIBRARY */
15942     }
15943   }
15944 #ifndef TRILIBRARY
15945 #ifndef CDT_ONLY
15946   if (m.regions > 0) {
15947     trifree((VOID *) regionarray);
15948   }
15949 #endif /* not CDT_ONLY */
15950   if (m.holes > 0) {
15951     trifree((VOID *) holearray);
15952   }
15953   if (b.geomview) {
15954     writeoff(&m, &b, b.offfilename, argc, argv);
15955   }
15956 #endif /* not TRILIBRARY */
15957   if (b.edgesout) {
15958 #ifdef TRILIBRARY
15959     writeedges(&m, &b, &out->edgelist, &out->edgemarkerlist);
15960 #else /* not TRILIBRARY */
15961     writeedges(&m, &b, b.edgefilename, argc, argv);
15962 #endif /* not TRILIBRARY */
15963   }
15964   if (b.voronoi) {
15965 #ifdef TRILIBRARY
15966     writevoronoi(&m, &b, &vorout->pointlist, &vorout->pointattributelist,
15967                  &vorout->pointmarkerlist, &vorout->edgelist,
15968                  &vorout->edgemarkerlist, &vorout->normlist);
15969 #else /* not TRILIBRARY */
15970     writevoronoi(&m, &b, b.vnodefilename, b.vedgefilename, argc, argv);
15971 #endif /* not TRILIBRARY */
15972   }
15973   if (b.neighbors) {
15974 #ifdef TRILIBRARY
15975     writeneighbors(&m, &b, &out->neighborlist);
15976 #else /* not TRILIBRARY */
15977     writeneighbors(&m, &b, b.neighborfilename, argc, argv);
15978 #endif /* not TRILIBRARY */
15979   }
15980 
15981   if (!b.quiet) {
15982 #ifndef NO_TIMER
15983     gettimeofday(&tv6, &tz);
15984     printf("\nOutput milliseconds:  %ld\n",
15985            1000l * (tv6.tv_sec - tv5.tv_sec) +
15986            (tv6.tv_usec - tv5.tv_usec) / 1000l);
15987     printf("Total running milliseconds:  %ld\n",
15988            1000l * (tv6.tv_sec - tv0.tv_sec) +
15989            (tv6.tv_usec - tv0.tv_usec) / 1000l);
15990 #endif /* not NO_TIMER */
15991 
15992     statistics(&m, &b);
15993   }
15994 
15995 #ifndef REDUCED
15996   if (b.docheck) {
15997     checkmesh(&m, &b);
15998     checkdelaunay(&m, &b);
15999   }
16000 #endif /* not REDUCED */
16001 
16002   triangledeinit(&m, &b);
16003 #ifndef TRILIBRARY
16004   return 0;
16005 #endif /* not TRILIBRARY */
16006 }
16007