1 /* Preamble:
2  * (1) This is a slightly modified version of triangle.c that allows it to be
3  * compiled on both Windows and Linux/OSX/Unix with 32- or 64-bits.  The
4  * problem is the extensive use of "long" which is 4 bytes on Windows and
5  * 8 bytes on the others. The effects of this problem started to manifest
6  * (crashes) only on binaries compiled with VS2012 and run on Windows 8.
7  * Although not tested it is likely that MinGW64 binaries are affected too.
8  *
9  * GMT Team, June 2013.
10  *
11  * (2) While containing lots of local functions, none are declared static.
12  * This means they are all exported in the shared library.  We have thus
13  * added the "static" keyword before all the function declarations other
14  * than triangulate, which is the only one we are using from GMT.
15  * Likewise we extended the #ifndef CDT_ONLY and #ifndef REDUCED pragmas
16  * to the internal functions that are used only when those switches are
17  * actually defined.
18  *
19  * GMT Team, March 2016.
20  *
21  * Declaration of type LONG:
22  */
23 
24 #if defined(_WIN64) || defined(__MINGW64__)
25 #define LONG __int64    /* A signed 8-byte integer, under Windows64 */
26 #define PRIu "I64u"     /* printf format for unsigned uint64 */
27 #else
28 #define LONG long       /* A signed 4 or 8-byte integer */
29 #define PRIu "lu"
30 #endif
31 
32 /*****************************************************************************/
33 /*                                                                           */
34 /*      888888888        ,o,                          / 888                  */
35 /*         888    88o88o  "    o8888o  88o8888o o88888o 888  o88888o         */
36 /*         888    888    888       88b 888  888 888 888 888 d888  88b        */
37 /*         888    888    888  o88^o888 888  888 "88888" 888 8888oo888        */
38 /*         888    888    888 C888  888 888  888  /      888 q888             */
39 /*         888    888    888  "88o^888 888  888 Cb      888  "88oooo"        */
40 /*                                              "8oo8D                       */
41 /*                                                                           */
42 /*  A Two-Dimensional Quality Mesh Generator and Delaunay Triangulator.      */
43 /*  (triangle.c)                                                             */
44 /*                                                                           */
45 /*  Version 1.6                                                              */
46 /*  July 28, 2005                                                            */
47 /*                                                                           */
48 /*  Copyright 1993, 1995, 1997, 1998, 2002, 2005                             */
49 /*  Jonathan Richard Shewchuk                                                */
50 /*  2360 Woolsey #H                                                          */
51 /*  Berkeley, California  94705-1927                                         */
52 /*  jrs@cs.berkeley.edu                                                      */
53 /*                                                                           */
54 /*  This program may be freely redistributed under the condition that the    */
55 /*    copyright notices (including this entire header and the copyright      */
56 /*    notice printed when the `-h' switch is selected) are not removed, and  */
57 /*    no compensation is received.  Private, research, and institutional     */
58 /*    use is free.  You may distribute modified versions of this code UNDER  */
59 /*    THE CONDITION THAT THIS CODE AND ANY MODIFICATIONS MADE TO IT IN THE   */
60 /*    SAME FILE REMAIN UNDER COPYRIGHT OF THE ORIGINAL AUTHOR, BOTH SOURCE   */
61 /*    AND OBJECT CODE ARE MADE FREELY AVAILABLE WITHOUT CHARGE, AND CLEAR    */
62 /*    NOTICE IS GIVEN OF THE MODIFICATIONS.  Distribution of this code as    */
63 /*    part of a commercial system is permissible ONLY BY DIRECT ARRANGEMENT  */
64 /*    WITH THE AUTHOR.  (If you are not directly supplying this code to a    */
65 /*    customer, and you are instead telling them how they can obtain it for  */
66 /*    free, then you are not required to make any arrangement with me.)      */
67 /*                                                                           */
68 /*  Hypertext instructions for Triangle are available on the Web at          */
69 /*                                                                           */
70 /*      http://www.cs.cmu.edu/~quake/triangle.html                           */
71 /*                                                                           */
72 /*  Disclaimer:  Neither I nor Carnegie Mellon warrant this code in any way  */
73 /*    whatsoever.  This code is provided "as-is".  Use at your own risk.     */
74 /*                                                                           */
75 /*  Some of the references listed below are marked with an asterisk.  [*]    */
76 /*    These references are available for downloading from the Web page       */
77 /*                                                                           */
78 /*      http://www.cs.cmu.edu/~quake/triangle.research.html                  */
79 /*                                                                           */
80 /*  Three papers discussing aspects of Triangle are available.  A short      */
81 /*    overview appears in "Triangle:  Engineering a 2D Quality Mesh          */
82 /*    Generator and Delaunay Triangulator," in Applied Computational         */
83 /*    Geometry:  Towards Geometric Engineering, Ming C. Lin and Dinesh       */
84 /*    Manocha, editors, Lecture Notes in Computer Science volume 1148,       */
85 /*    pages 203-222, Springer-Verlag, Berlin, May 1996 (from the First ACM   */
86 /*    Workshop on Applied Computational Geometry).  [*]                      */
87 /*                                                                           */
88 /*    The algorithms are discussed in the greatest detail in "Delaunay       */
89 /*    Refinement Algorithms for Triangular Mesh Generation," Computational   */
90 /*    Geometry:  Theory and Applications 22(1-3):21-74, May 2002.  [*]       */
91 /*                                                                           */
92 /*    More detail about the data structures may be found in my dissertation: */
93 /*    "Delaunay Refinement Mesh Generation," Ph.D. thesis, Technical Report  */
94 /*    CMU-CS-97-137, School of Computer Science, Carnegie Mellon University, */
95 /*    Pittsburgh, Pennsylvania, 18 May 1997.  [*]                            */
96 /*                                                                           */
97 /*  Triangle was created as part of the Quake Project in the School of       */
98 /*    Computer Science at Carnegie Mellon University.  For further           */
99 /*    information, see Hesheng Bao, Jacobo Bielak, Omar Ghattas, Loukas F.   */
100 /*    Kallivokas, David R. O'Hallaron, Jonathan R. Shewchuk, and Jifeng Xu,  */
101 /*    "Large-scale Simulation of Elastic Wave Propagation in Heterogeneous   */
102 /*    Media on Parallel Computers," Computer Methods in Applied Mechanics    */
103 /*    and Engineering 152(1-2):85-102, 22 January 1998.                      */
104 /*                                                                           */
105 /*  Triangle's Delaunay refinement algorithm for quality mesh generation is  */
106 /*    a hybrid of one due to Jim Ruppert, "A Delaunay Refinement Algorithm   */
107 /*    for Quality 2-Dimensional Mesh Generation," Journal of Algorithms      */
108 /*    18(3):548-585, May 1995 [*], and one due to L. Paul Chew, "Guaranteed- */
109 /*    Quality Mesh Generation for Curved Surfaces," Proceedings of the Ninth */
110 /*    Annual Symposium on Computational Geometry (San Diego, California),    */
111 /*    pages 274-280, Association for Computing Machinery, May 1993,          */
112 /*    http://portal.acm.org/citation.cfm?id=161150 .                         */
113 /*                                                                           */
114 /*  The Delaunay refinement algorithm has been modified so that it meshes    */
115 /*    domains with small input angles well, as described in Gary L. Miller,  */
116 /*    Steven E. Pav, and Noel J. Walkington, "When and Why Ruppert's         */
117 /*    Algorithm Works," Twelfth International Meshing Roundtable, pages      */
118 /*    91-102, Sandia National Laboratories, September 2003.  [*]             */
119 /*                                                                           */
120 /*  My implementation of the divide-and-conquer and incremental Delaunay     */
121 /*    triangulation algorithms follows closely the presentation of Guibas    */
122 /*    and Stolfi, even though I use a triangle-based data structure instead  */
123 /*    of their quad-edge data structure.  (In fact, I originally implemented */
124 /*    Triangle using the quad-edge data structure, but the switch to a       */
125 /*    triangle-based data structure sped Triangle by a factor of two.)  The  */
126 /*    mesh manipulation primitives and the two aforementioned Delaunay       */
127 /*    triangulation algorithms are described by Leonidas J. Guibas and Jorge */
128 /*    Stolfi, "Primitives for the Manipulation of General Subdivisions and   */
129 /*    the Computation of Voronoi Diagrams," ACM Transactions on Graphics     */
130 /*    4(2):74-123, April 1985, http://portal.acm.org/citation.cfm?id=282923 .*/
131 /*                                                                           */
132 /*  Their O(n log n) divide-and-conquer algorithm is adapted from Der-Tsai   */
133 /*    Lee and Bruce J. Schachter, "Two Algorithms for Constructing the       */
134 /*    Delaunay Triangulation," International Journal of Computer and         */
135 /*    Information Science 9(3):219-242, 1980.  Triangle's improvement of the */
136 /*    divide-and-conquer algorithm by alternating between vertical and       */
137 /*    horizontal cuts was introduced by Rex A. Dwyer, "A Faster Divide-and-  */
138 /*    Conquer Algorithm for Constructing Delaunay Triangulations,"           */
139 /*    Algorithmica 2(2):137-151, 1987.                                       */
140 /*                                                                           */
141 /*  The incremental insertion algorithm was first proposed by C. L. Lawson,  */
142 /*    "Software for C1 Surface Interpolation," in Mathematical Software III, */
143 /*    John R. Rice, editor, Academic Press, New York, pp. 161-194, 1977.     */
144 /*    For point location, I use the algorithm of Ernst P. Mucke, Isaac       */
145 /*    Saias, and Binhai Zhu, "Fast Randomized Point Location Without         */
146 /*    Preprocessing in Two- and Three-Dimensional Delaunay Triangulations,"  */
147 /*    Proceedings of the Twelfth Annual Symposium on Computational Geometry, */
148 /*    ACM, May 1996.  [*]  If I were to randomize the order of vertex        */
149 /*    insertion (I currently don't bother), their result combined with the   */
150 /*    result of Kenneth L. Clarkson and Peter W. Shor, "Applications of      */
151 /*    Random Sampling in Computational Geometry II," Discrete &              */
152 /*    Computational Geometry 4(1):387-421, 1989, would yield an expected     */
153 /*    O(n^{4/3}) bound on running time.                                      */
154 /*                                                                           */
155 /*  The O(n log n) sweepline Delaunay triangulation algorithm is taken from  */
156 /*    Steven Fortune, "A Sweepline Algorithm for Voronoi Diagrams",          */
157 /*    Algorithmica 2(2):153-174, 1987.  A random sample of edges on the      */
158 /*    boundary of the triangulation are maintained in a splay tree for the   */
159 /*    purpose of point location.  Splay trees are described by Daniel        */
160 /*    Dominic Sleator and Robert Endre Tarjan, "Self-Adjusting Binary Search */
161 /*    Trees," Journal of the ACM 32(3):652-686, July 1985,                   */
162 /*    http://portal.acm.org/citation.cfm?id=3835 .                           */
163 /*                                                                           */
164 /*  The algorithms for exact computation of the signs of determinants are    */
165 /*    described in Jonathan Richard Shewchuk, "Adaptive Precision Floating-  */
166 /*    Point Arithmetic and Fast Robust Geometric Predicates," Discrete &     */
167 /*    Computational Geometry 18(3):305-363, October 1997.  (Also available   */
168 /*    as Technical Report CMU-CS-96-140, School of Computer Science,         */
169 /*    Carnegie Mellon University, Pittsburgh, Pennsylvania, May 1996.)  [*]  */
170 /*    An abbreviated version appears as Jonathan Richard Shewchuk, "Robust   */
171 /*    Adaptive Floating-Point Geometric Predicates," Proceedings of the      */
172 /*    Twelfth Annual Symposium on Computational Geometry, ACM, May 1996. [*] */
173 /*    Many of the ideas for my exact arithmetic routines originate with      */
174 /*    Douglas M. Priest, "Algorithms for Arbitrary Precision Floating Point  */
175 /*    Arithmetic," Tenth Symposium on Computer Arithmetic, pp. 132-143, IEEE */
176 /*    Computer Society Press, 1991.  [*]  Many of the ideas for the correct  */
177 /*    evaluation of the signs of determinants are taken from Steven Fortune  */
178 /*    and Christopher J. Van Wyk, "Efficient Exact Arithmetic for Computa-   */
179 /*    tional Geometry," Proceedings of the Ninth Annual Symposium on         */
180 /*    Computational Geometry, ACM, pp. 163-172, May 1993, and from Steven    */
181 /*    Fortune, "Numerical Stability of Algorithms for 2D Delaunay Triangu-   */
182 /*    lations," International Journal of Computational Geometry & Applica-   */
183 /*    tions 5(1-2):193-213, March-June 1995.                                 */
184 /*                                                                           */
185 /*  The method of inserting new vertices off-center (not precisely at the    */
186 /*    circumcenter of every poor-quality triangle) is from Alper Ungor,      */
187 /*    "Off-centers:  A New Type of Steiner Points for Computing Size-Optimal */
188 /*    Quality-Guaranteed Delaunay Triangulations," Proceedings of LATIN      */
189 /*    2004 (Buenos Aires, Argentina), April 2004.                            */
190 /*                                                                           */
191 /*  For definitions of and results involving Delaunay triangulations,        */
192 /*    constrained and conforming versions thereof, and other aspects of      */
193 /*    triangular mesh generation, see the excellent survey by Marshall Bern  */
194 /*    and David Eppstein, "Mesh Generation and Optimal Triangulation," in    */
195 /*    Computing and Euclidean Geometry, Ding-Zhu Du and Frank Hwang,         */
196 /*    editors, World Scientific, Singapore, pp. 23-90, 1992.  [*]            */
197 /*                                                                           */
198 /*  The time for incrementally adding PSLG (planar straight line graph)      */
199 /*    segments to create a constrained Delaunay triangulation is probably    */
200 /*    O(t^2) per segment in the worst case and O(t) per segment in the       */
201 /*    common case, where t is the number of triangles that intersect the     */
202 /*    segment before it is inserted.  This doesn't count point location,     */
203 /*    which can be much more expensive.  I could improve this to O(d log d)  */
204 /*    time, but d is usually quite small, so it's not worth the bother.      */
205 /*    (This note does not apply when the -s switch is used, invoking a       */
206 /*    different method is used to insert segments.)                          */
207 /*                                                                           */
208 /*  The time for deleting a vertex from a Delaunay triangulation is O(d^2)   */
209 /*    in the worst case and O(d) in the common case, where d is the degree   */
210 /*    of the vertex being deleted.  I could improve this to O(d log d) time, */
211 /*    but d is usually quite small, so it's not worth the bother.            */
212 /*                                                                           */
213 /*  Ruppert's Delaunay refinement algorithm typically generates triangles    */
214 /*    at a linear rate (constant time per triangle) after the initial        */
215 /*    triangulation is formed.  There may be pathological cases where        */
216 /*    quadratic time is required, but these never arise in practice.         */
217 /*                                                                           */
218 /*  The geometric predicates (circumcenter calculations, segment             */
219 /*    intersection formulae, etc.) appear in my "Lecture Notes on Geometric  */
220 /*    Robustness" at http://www.cs.berkeley.edu/~jrs/mesh .                  */
221 /*                                                                           */
222 /*  If you make any improvements to this code, please please please let me   */
223 /*    know, so that I may obtain the improvements.  Even if you don't change */
224 /*    the code, I'd still love to hear what it's being used for.             */
225 /*                                                                           */
226 /*****************************************************************************/
227 
228 /* For single precision (which will save some memory and reduce paging),     */
229 /*   define the symbol SINGLE by using the -DSINGLE compiler switch or by    */
230 /*   writing "#define SINGLE" below.                                         */
231 /*                                                                           */
232 /* For double precision (which will allow you to refine meshes to a smaller  */
233 /*   edge length), leave SINGLE undefined.                                   */
234 /*                                                                           */
235 /* Double precision uses more memory, but improves the resolution of the     */
236 /*   meshes you can generate with Triangle.  It also reduces the likelihood  */
237 /*   of a floating exception due to overflow.  Finally, it is much faster    */
238 /*   than single precision on 64-bit architectures like the DEC Alpha.  I    */
239 /*   recommend double precision unless you want to generate a mesh for which */
240 /*   you do not have enough memory.                                          */
241 
242 /* #define SINGLE */
243 
244 #ifdef SINGLE
245 #define REAL float
246 #else /* not SINGLE */
247 #define REAL double
248 #endif /* not SINGLE */
249 
250 /* If yours is not a Unix system, define the NO_TIMER compiler switch to     */
251 /*   remove the Unix-specific timing code.                                   */
252 
253 /* #define NO_TIMER */
254 
255 /* To insert lots of self-checks for internal errors, define the SELF_CHECK  */
256 /*   symbol.  This will slow down the program significantly.  It is best to  */
257 /*   define the symbol using the -DSELF_CHECK compiler switch, but you could */
258 /*   write "#define SELF_CHECK" below.  If you are modifying this code, I    */
259 /*   recommend you turn self-checks on until your work is debugged.          */
260 
261 /* #define SELF_CHECK */
262 
263 /* To compile Triangle as a callable object library (triangle.o), define the */
264 /*   TRILIBRARY symbol.  Read the file triangle.h for details on how to call */
265 /*   the procedure triangulate() that results.                               */
266 
267 /* #define TRILIBRARY */
268 
269 /* It is possible to generate a smaller version of Triangle using one or     */
270 /*   both of the following symbols.  Define the REDUCED symbol to eliminate  */
271 /*   all features that are primarily of research interest; specifically, the */
272 /*   -i, -F, -s, and -C switches.  Define the CDT_ONLY symbol to eliminate   */
273 /*   all meshing algorithms above and beyond constrained Delaunay            */
274 /*   triangulation; specifically, the -r, -q, -a, -u, -D, -S, and -s         */
275 /*   switches.  These reductions are most likely to be useful when           */
276 /*   generating an object library (triangle.o) by defining the TRILIBRARY    */
277 /*   symbol.                                                                 */
278 
279 /* #define REDUCED */
280 /* #define CDT_ONLY */
281 
282 /* On some machines, my exact arithmetic routines might be defeated by the   */
283 /*   use of internal extended precision floating-point registers.  The best  */
284 /*   way to solve this problem is to set the floating-point registers to use */
285 /*   single or double precision internally.  On 80x86 processors, this may   */
286 /*   be accomplished by setting the CPU86 symbol for the Microsoft C         */
287 /*   compiler, or the LINUX symbol for the gcc compiler running on Linux.    */
288 /*                                                                           */
289 /* An inferior solution is to declare certain values as `volatile', thus     */
290 /*   forcing them to be stored to memory and rounded off.  Unfortunately,    */
291 /*   this solution might slow Triangle down quite a bit.  To use volatile    */
292 /*   values, write "#define INEXACT volatile" below.  Normally, however,     */
293 /*   INEXACT should be defined to be nothing.  ("#define INEXACT".)          */
294 /*                                                                           */
295 /* For more discussion, see http://www.cs.cmu.edu/~quake/robust.pc.html .    */
296 /*   For yet more discussion, see Section 5 of my paper, "Adaptive Precision */
297 /*   Floating-Point Arithmetic and Fast Robust Geometric Predicates" (also   */
298 /*   available as Section 6.6 of my dissertation).                           */
299 
300 /* #define CPU86 */
301 /* #define LINUX */
302 
303 #define INEXACT /* Nothing */
304 /* #define INEXACT volatile */
305 
306 /* Maximum number of characters in a file name (including the null).         */
307 
308 #define FILENAMESIZE 2048
309 
310 /* Maximum number of characters in a line read from a file (including the    */
311 /*   null).                                                                  */
312 
313 #define INPUTLINESIZE 1024
314 
315 /* For efficiency, a variety of data structures are allocated in bulk.  The  */
316 /*   following constants determine how many of each structure is allocated   */
317 /*   at once.                                                                */
318 
319 #define TRIPERBLOCK 4092           /* Number of triangles allocated at once. */
320 #define SUBSEGPERBLOCK 508       /* Number of subsegments allocated at once. */
321 #define VERTEXPERBLOCK 4092         /* Number of vertices allocated at once. */
322 #define VIRUSPERBLOCK 1020   /* Number of virus triangles allocated at once. */
323 /* Number of encroached subsegments allocated at once. */
324 #define BADSUBSEGPERBLOCK 252
325 /* Number of skinny triangles allocated at once. */
326 #define BADTRIPERBLOCK 4092
327 /* Number of flipped triangles allocated at once. */
328 #define FLIPSTACKERPERBLOCK 252
329 /* Number of splay tree nodes allocated at once. */
330 #define SPLAYNODEPERBLOCK 508
331 
332 /* The vertex types.   A DEADVERTEX has been deleted entirely.  An           */
333 /*   UNDEADVERTEX is not part of the mesh, but is written to the output      */
334 /*   .node file and affects the node indexing in the other output files.     */
335 
336 #define INPUTVERTEX 0
337 #define SEGMENTVERTEX 1
338 #define FREEVERTEX 2
339 #define DEADVERTEX -32768
340 #define UNDEADVERTEX -32767
341 
342 /* The next line is used to outsmart some very stupid compilers.  If your    */
343 /*   compiler is smarter, feel free to replace the "int" with "void".        */
344 /*   Not that it matters.                                                    */
345 
346 #define VOID void
347 
348 /* Two constants for algorithms based on random sampling.  Both constants    */
349 /*   have been chosen empirically to optimize their respective algorithms.   */
350 
351 /* Used for the point location scheme of Mucke, Saias, and Zhu, to decide    */
352 /*   how large a random sample of triangles to inspect.                      */
353 
354 #define SAMPLEFACTOR 11
355 
356 /* Used in Fortune's sweepline Delaunay algorithm to determine what fraction */
357 /*   of boundary edges should be maintained in the splay tree for point      */
358 /*   location on the front.                                                  */
359 
360 #define SAMPLERATE 10
361 
362 /* A number that speaks for itself, every kissable digit.                    */
363 
364 #define PI 3.141592653589793238462643383279502884197169399375105820974944592308
365 
366 /* Another fave.                                                             */
367 
368 #define SQUAREROOTTWO 1.4142135623730950488016887242096980785696718753769480732
369 
370 /* And here's one for those of you who are intimidated by math.              */
371 
372 #define ONETHIRD 0.333333333333333333333333333333333333333333333333333333333333
373 
374 #include <stdio.h>
375 #include <stdlib.h>
376 #include <string.h>
377 #include <math.h>
378 #ifndef NO_TIMER
379 #include <sys/time.h>
380 #endif /* not NO_TIMER */
381 #include <float.h>
382 #ifdef LINUX
383 #include <fpu_control.h>
384 #endif /* LINUX */
385 #ifdef TRILIBRARY
386 #include "triangle.h"
387 #endif /* TRILIBRARY */
388 
389 /* A few forward declarations.                                               */
390 
391 #ifndef TRILIBRARY
392 char *readline();
393 char *findfield();
394 #endif /* not TRILIBRARY */
395 
396 /* Labels that signify the result of point location.  The result of a        */
397 /*   search indicates that the point falls in the interior of a triangle, on */
398 /*   an edge, on a vertex, or outside the mesh.                              */
399 
400 enum locateresult {INTRIANGLE, ONEDGE, ONVERTEX, OUTSIDE};
401 
402 /* Labels that signify the result of vertex insertion.  The result indicates */
403 /*   that the vertex was inserted with complete success, was inserted but    */
404 /*   encroaches upon a subsegment, was not inserted because it lies on a     */
405 /*   segment, or was not inserted because another vertex occupies the same   */
406 /*   location.                                                               */
407 
408 enum insertvertexresult {SUCCESSFULVERTEX, ENCROACHINGVERTEX, VIOLATINGVERTEX,
409                          DUPLICATEVERTEX};
410 
411 /* Labels that signify the result of direction finding.  The result          */
412 /*   indicates that a segment connecting the two query points falls within   */
413 /*   the direction triangle, along the left edge of the direction triangle,  */
414 /*   or along the right edge of the direction triangle.                      */
415 
416 enum finddirectionresult {WITHIN, LEFTCOLLINEAR, RIGHTCOLLINEAR};
417 
418 /*****************************************************************************/
419 /*                                                                           */
420 /*  The basic mesh data structures                                           */
421 /*                                                                           */
422 /*  There are three:  vertices, triangles, and subsegments (abbreviated      */
423 /*  `subseg').  These three data structures, linked by pointers, comprise    */
424 /*  the mesh.  A vertex simply represents a mesh vertex and its properties.  */
425 /*  A triangle is a triangle.  A subsegment is a special data structure used */
426 /*  to represent an impenetrable edge of the mesh (perhaps on the outer      */
427 /*  boundary, on the boundary of a hole, or part of an internal boundary     */
428 /*  separating two triangulated regions).  Subsegments represent boundaries, */
429 /*  defined by the user, that triangles may not lie across.                  */
430 /*                                                                           */
431 /*  A triangle consists of a list of three vertices, a list of three         */
432 /*  adjoining triangles, a list of three adjoining subsegments (when         */
433 /*  segments exist), an arbitrary number of optional user-defined            */
434 /*  floating-point attributes, and an optional area constraint.  The latter  */
435 /*  is an upper bound on the permissible area of each triangle in a region,  */
436 /*  used for mesh refinement.                                                */
437 /*                                                                           */
438 /*  For a triangle on a boundary of the mesh, some or all of the neighboring */
439 /*  triangles may not be present.  For a triangle in the interior of the     */
440 /*  mesh, often no neighboring subsegments are present.  Such absent         */
441 /*  triangles and subsegments are never represented by NULL pointers; they   */
442 /*  are represented by two special records:  `dummytri', the triangle that   */
443 /*  fills "outer space", and `dummysub', the omnipresent subsegment.         */
444 /*  `dummytri' and `dummysub' are used for several reasons; for instance,    */
445 /*  they can be dereferenced and their contents examined without violating   */
446 /*  protected memory.                                                        */
447 /*                                                                           */
448 /*  However, it is important to understand that a triangle includes other    */
449 /*  information as well.  The pointers to adjoining vertices, triangles, and */
450 /*  subsegments are ordered in a way that indicates their geometric relation */
451 /*  to each other.  Furthermore, each of these pointers contains orientation */
452 /*  information.  Each pointer to an adjoining triangle indicates which face */
453 /*  of that triangle is contacted.  Similarly, each pointer to an adjoining  */
454 /*  subsegment indicates which side of that subsegment is contacted, and how */
455 /*  the subsegment is oriented relative to the triangle.                     */
456 /*                                                                           */
457 /*  The data structure representing a subsegment may be thought to be        */
458 /*  abutting the edge of one or two triangle data structures:  either        */
459 /*  sandwiched between two triangles, or resting against one triangle on an  */
460 /*  exterior boundary or hole boundary.                                      */
461 /*                                                                           */
462 /*  A subsegment consists of a list of four vertices--the vertices of the    */
463 /*  subsegment, and the vertices of the segment it is a part of--a list of   */
464 /*  two adjoining subsegments, and a list of two adjoining triangles.  One   */
465 /*  of the two adjoining triangles may not be present (though there should   */
466 /*  always be one), and neighboring subsegments might not be present.        */
467 /*  Subsegments also store a user-defined integer "boundary marker".         */
468 /*  Typically, this integer is used to indicate what boundary conditions are */
469 /*  to be applied at that location in a finite element simulation.           */
470 /*                                                                           */
471 /*  Like triangles, subsegments maintain information about the relative      */
472 /*  orientation of neighboring objects.                                      */
473 /*                                                                           */
474 /*  Vertices are relatively simple.  A vertex is a list of floating-point    */
475 /*  numbers, starting with the x, and y coordinates, followed by an          */
476 /*  arbitrary number of optional user-defined floating-point attributes,     */
477 /*  followed by an integer boundary marker.  During the segment insertion    */
478 /*  phase, there is also a pointer from each vertex to a triangle that may   */
479 /*  contain it.  Each pointer is not always correct, but when one is, it     */
480 /*  speeds up segment insertion.  These pointers are assigned values once    */
481 /*  at the beginning of the segment insertion phase, and are not used or     */
482 /*  updated except during this phase.  Edge flipping during segment          */
483 /*  insertion will render some of them incorrect.  Hence, don't rely upon    */
484 /*  them for anything.                                                       */
485 /*                                                                           */
486 /*  Other than the exception mentioned above, vertices have no information   */
487 /*  about what triangles, subfacets, or subsegments they are linked to.      */
488 /*                                                                           */
489 /*****************************************************************************/
490 
491 /*****************************************************************************/
492 /*                                                                           */
493 /*  Handles                                                                  */
494 /*                                                                           */
495 /*  The oriented triangle (`otri') and oriented subsegment (`osub') data     */
496 /*  structures defined below do not themselves store any part of the mesh.   */
497 /*  The mesh itself is made of `triangle's, `subseg's, and `vertex's.        */
498 /*                                                                           */
499 /*  Oriented triangles and oriented subsegments will usually be referred to  */
500 /*  as "handles."  A handle is essentially a pointer into the mesh; it       */
501 /*  allows you to "hold" one particular part of the mesh.  Handles are used  */
502 /*  to specify the regions in which one is traversing and modifying the mesh.*/
503 /*  A single `triangle' may be held by many handles, or none at all.  (The   */
504 /*  latter case is not a memory leak, because the triangle is still          */
505 /*  connected to other triangles in the mesh.)                               */
506 /*                                                                           */
507 /*  An `otri' is a handle that holds a triangle.  It holds a specific edge   */
508 /*  of the triangle.  An `osub' is a handle that holds a subsegment.  It     */
509 /*  holds either the left or right side of the subsegment.                   */
510 /*                                                                           */
511 /*  Navigation about the mesh is accomplished through a set of mesh          */
512 /*  manipulation primitives, further below.  Many of these primitives take   */
513 /*  a handle and produce a new handle that holds the mesh near the first     */
514 /*  handle.  Other primitives take two handles and glue the corresponding    */
515 /*  parts of the mesh together.  The orientation of the handles is           */
516 /*  important.  For instance, when two triangles are glued together by the   */
517 /*  bond() primitive, they are glued at the edges on which the handles lie.  */
518 /*                                                                           */
519 /*  Because vertices have no information about which triangles they are      */
520 /*  attached to, I commonly represent a vertex by use of a handle whose      */
521 /*  origin is the vertex.  A single handle can simultaneously represent a    */
522 /*  triangle, an edge, and a vertex.                                         */
523 /*                                                                           */
524 /*****************************************************************************/
525 
526 /* The triangle data structure.  Each triangle contains three pointers to    */
527 /*   adjoining triangles, plus three pointers to vertices, plus three        */
528 /*   pointers to subsegments (declared below; these pointers are usually     */
529 /*   `dummysub').  It may or may not also contain user-defined attributes    */
530 /*   and/or a floating-point "area constraint."  It may also contain extra   */
531 /*   pointers for nodes, when the user asks for high-order elements.         */
532 /*   Because the size and structure of a `triangle' is not decided until     */
533 /*   runtime, I haven't simply declared the type `triangle' as a struct.     */
534 
535 typedef REAL **triangle;            /* Really:  typedef triangle *triangle   */
536 
537 /* An oriented triangle:  includes a pointer to a triangle and orientation.  */
538 /*   The orientation denotes an edge of the triangle.  Hence, there are      */
539 /*   three possible orientations.  By convention, each edge always points    */
540 /*   counterclockwise about the corresponding triangle.                      */
541 
542 struct otri {
543   triangle *tri;
544   int orient;                                         /* Ranges from 0 to 2. */
545 };
546 
547 /* The subsegment data structure.  Each subsegment contains two pointers to  */
548 /*   adjoining subsegments, plus four pointers to vertices, plus two         */
549 /*   pointers to adjoining triangles, plus one boundary marker, plus one     */
550 /*   segment number.                                                         */
551 
552 typedef REAL **subseg;                  /* Really:  typedef subseg *subseg   */
553 
554 /* An oriented subsegment:  includes a pointer to a subsegment and an        */
555 /*   orientation.  The orientation denotes a side of the edge.  Hence, there */
556 /*   are two possible orientations.  By convention, the edge is always       */
557 /*   directed so that the "side" denoted is the right side of the edge.      */
558 
559 struct osub {
560   subseg *ss;
561   int ssorient;                                       /* Ranges from 0 to 1. */
562 };
563 
564 /* The vertex data structure.  Each vertex is actually an array of REALs.    */
565 /*   The number of REALs is unknown until runtime.  An integer boundary      */
566 /*   marker, and sometimes a pointer to a triangle, is appended after the    */
567 /*   REALs.                                                                  */
568 
569 typedef REAL *vertex;
570 
571 /* A queue used to store encroached subsegments.  Each subsegment's vertices */
572 /*   are stored so that we can check whether a subsegment is still the same. */
573 
574 struct badsubseg {
575   subseg encsubseg;                             /* An encroached subsegment. */
576   vertex subsegorg, subsegdest;                         /* Its two vertices. */
577 };
578 
579 /* A queue used to store bad triangles.  The key is the square of the cosine */
580 /*   of the smallest angle of the triangle.  Each triangle's vertices are    */
581 /*   stored so that one can check whether a triangle is still the same.      */
582 
583 struct badtriang {
584   triangle poortri;                       /* A skinny or too-large triangle. */
585   REAL key;                             /* cos^2 of smallest (apical) angle. */
586   vertex triangorg, triangdest, triangapex;           /* Its three vertices. */
587   struct badtriang *nexttriang;             /* Pointer to next bad triangle. */
588 };
589 
590 /* A stack of triangles flipped during the most recent vertex insertion.     */
591 /*   The stack is used to undo the vertex insertion if the vertex encroaches */
592 /*   upon a subsegment.                                                      */
593 
594 struct flipstacker {
595   triangle flippedtri;                       /* A recently flipped triangle. */
596   struct flipstacker *prevflip;               /* Previous flip in the stack. */
597 };
598 
599 /* A node in a heap used to store events for the sweepline Delaunay          */
600 /*   algorithm.  Nodes do not point directly to their parents or children in */
601 /*   the heap.  Instead, each node knows its position in the heap, and can   */
602 /*   look up its parent and children in a separate array.  The `eventptr'    */
603 /*   points either to a `vertex' or to a triangle (in encoded format, so     */
604 /*   that an orientation is included).  In the latter case, the origin of    */
605 /*   the oriented triangle is the apex of a "circle event" of the sweepline  */
606 /*   algorithm.  To distinguish site events from circle events, all circle   */
607 /*   events are given an invalid (smaller than `xmin') x-coordinate `xkey'.  */
608 
609 struct event {
610   REAL xkey, ykey;                              /* Coordinates of the event. */
611   VOID *eventptr;      /* Can be a vertex or the location of a circle event. */
612   int heapposition;              /* Marks this event's position in the heap. */
613 };
614 
615 /* A node in the splay tree.  Each node holds an oriented ghost triangle     */
616 /*   that represents a boundary edge of the growing triangulation.  When a   */
617 /*   circle event covers two boundary edges with a triangle, so that they    */
618 /*   are no longer boundary edges, those edges are not immediately deleted   */
619 /*   from the tree; rather, they are lazily deleted when they are next       */
620 /*   encountered.  (Since only a random sample of boundary edges are kept    */
621 /*   in the tree, lazy deletion is faster.)  `keydest' is used to verify     */
622 /*   that a triangle is still the same as when it entered the splay tree; if */
623 /*   it has been rotated (due to a circle event), it no longer represents a  */
624 /*   boundary edge and should be deleted.                                    */
625 
626 struct splaynode {
627   struct otri keyedge;                     /* Lprev of an edge on the front. */
628   vertex keydest;           /* Used to verify that splay node is still live. */
629   struct splaynode *lchild, *rchild;              /* Children in splay tree. */
630 };
631 
632 /* A type used to allocate memory.  firstblock is the first block of items.  */
633 /*   nowblock is the block from which items are currently being allocated.   */
634 /*   nextitem points to the next slab of free memory for an item.            */
635 /*   deaditemstack is the head of a linked list (stack) of deallocated items */
636 /*   that can be recycled.  unallocateditems is the number of items that     */
637 /*   remain to be allocated from nowblock.                                   */
638 /*                                                                           */
639 /* Traversal is the process of walking through the entire list of items, and */
640 /*   is separate from allocation.  Note that a traversal will visit items on */
641 /*   the "deaditemstack" stack as well as live items.  pathblock points to   */
642 /*   the block currently being traversed.  pathitem points to the next item  */
643 /*   to be traversed.  pathitemsleft is the number of items that remain to   */
644 /*   be traversed in pathblock.                                              */
645 /*                                                                           */
646 /* alignbytes determines how new records should be aligned in memory.        */
647 /*   itembytes is the length of a record in bytes (after rounding up).       */
648 /*   itemsperblock is the number of items allocated at once in a single      */
649 /*   block.  itemsfirstblock is the number of items in the first block,      */
650 /*   which can vary from the others.  items is the number of currently       */
651 /*   allocated items.  maxitems is the maximum number of items that have     */
652 /*   been allocated at once; it is the current number of items plus the      */
653 /*   number of records kept on deaditemstack.                                */
654 
655 struct memorypool {
656   VOID **firstblock, **nowblock;
657   VOID *nextitem;
658   VOID *deaditemstack;
659   VOID **pathblock;
660   VOID *pathitem;
661   size_t alignbytes;
662   size_t itembytes;
663   size_t itemsperblock;
664   size_t itemsfirstblock;
665   LONG items, maxitems;
666   size_t unallocateditems;
667   size_t pathitemsleft;
668 };
669 
670 
671 /* Global constants.                                                         */
672 
673 static REAL splitter;       /* Used to split REAL factors for exact multiplication. */
674 static REAL epsilon;                             /* Floating-point machine epsilon. */
675 static REAL resulterrbound;
676 static REAL ccwerrboundA, ccwerrboundB, ccwerrboundC;
677 static REAL iccerrboundA, iccerrboundB, iccerrboundC;
678 static REAL o3derrboundA, o3derrboundB, o3derrboundC;
679 
680 /* Random number seed is not constant, but I've made it global anyway.       */
681 
682 static unsigned LONG randomseed;                     /* Current random number seed. */
683 
684 
685 /* Mesh data structure.  Triangle operates on only one mesh, but the mesh    */
686 /*   structure is used (instead of global variables) to allow reentrancy.    */
687 
688 struct mesh {
689 
690 /* Variables used to allocate memory for triangles, subsegments, vertices,   */
691 /*   viri (triangles being eaten), encroached segments, bad (skinny or too   */
692 /*   large) triangles, and splay tree nodes.                                 */
693 
694   struct memorypool triangles;
695   struct memorypool subsegs;
696   struct memorypool vertices;
697   struct memorypool viri;
698   struct memorypool badsubsegs;
699   struct memorypool badtriangles;
700   struct memorypool flipstackers;
701   struct memorypool splaynodes;
702 
703 /* Variables that maintain the bad triangle queues.  The queues are          */
704 /*   ordered from 4095 (highest priority) to 0 (lowest priority).            */
705 
706   struct badtriang *queuefront[4096];
707   struct badtriang *queuetail[4096];
708   int nextnonemptyq[4096];
709   int firstnonemptyq;
710 
711 /* Variable that maintains the stack of recently flipped triangles.          */
712 
713   struct flipstacker *lastflip;
714 
715 /* Other variables. */
716 
717   REAL xmin, xmax, ymin, ymax;                            /* x and y bounds. */
718   REAL xminextreme;      /* Nonexistent x value used as a flag in sweepline. */
719   int invertices;                               /* Number of input vertices. */
720   int inelements;                              /* Number of input triangles. */
721   int insegments;                               /* Number of input segments. */
722   int holes;                                       /* Number of input holes. */
723   int regions;                                   /* Number of input regions. */
724   int undeads;    /* Number of input vertices that don't appear in the mesh. */
725   LONG edges;                                     /* Number of output edges. */
726   int mesh_dim;                                /* Dimension (ought to be 2). */
727   int nextras;                           /* Number of attributes per vertex. */
728   int eextras;                         /* Number of attributes per triangle. */
729   LONG hullsize;                          /* Number of edges in convex hull. */
730   int steinerleft;                 /* Number of Steiner points not yet used. */
731   int vertexmarkindex;         /* Index to find boundary marker of a vertex. */
732   int vertex2triindex;     /* Index to find a triangle adjacent to a vertex. */
733   int highorderindex;  /* Index to find extra nodes for high-order elements. */
734   int elemattribindex;            /* Index to find attributes of a triangle. */
735   int areaboundindex;             /* Index to find area bound of a triangle. */
736   int checksegments;         /* Are there segments in the triangulation yet? */
737   int checkquality;                  /* Has quality triangulation begun yet? */
738   int readnodefile;                           /* Has a .node file been read? */
739   LONG samples;              /* Number of random samples for point location. */
740 
741   LONG incirclecount;                 /* Number of incircle tests performed. */
742   LONG counterclockcount;     /* Number of counterclockwise tests performed. */
743   LONG orient3dcount;           /* Number of 3D orientation tests performed. */
744   LONG hyperbolacount;      /* Number of right-of-hyperbola tests performed. */
745   LONG circumcentercount;  /* Number of circumcenter calculations performed. */
746   LONG circletopcount;       /* Number of circle top calculations performed. */
747 
748 /* Triangular bounding box vertices.                                         */
749 
750   vertex infvertex1, infvertex2, infvertex3;
751 
752 /* Pointer to the `triangle' that occupies all of "outer space."             */
753 
754   triangle *dummytri;
755   triangle *dummytribase;    /* Keep base address so we can free() it later. */
756 
757 /* Pointer to the omnipresent subsegment.  Referenced by any triangle or     */
758 /*   subsegment that isn't really connected to a subsegment at that          */
759 /*   location.                                                               */
760 
761   subseg *dummysub;
762   subseg *dummysubbase;      /* Keep base address so we can free() it later. */
763 
764 /* Pointer to a recently visited triangle.  Improves point location if       */
765 /*   proximate vertices are inserted sequentially.                           */
766 
767   struct otri recenttri;
768 
769 };                                                  /* End of `struct mesh'. */
770 
771 
772 /* Data structure for command line switches and file names.  This structure  */
773 /*   is used (instead of global variables) to allow reentrancy.              */
774 
775 struct behavior {
776 
777 /* Switches for the triangulator.                                            */
778 /*   poly: -p switch.  refine: -r switch.                                    */
779 /*   quality: -q switch.                                                     */
780 /*     minangle: minimum angle bound, specified after -q switch.             */
781 /*     goodangle: cosine squared of minangle.                                */
782 /*     offconstant: constant used to place off-center Steiner points.        */
783 /*   vararea: -a switch without number.                                      */
784 /*   fixedarea: -a switch with number.                                       */
785 /*     maxarea: maximum area bound, specified after -a switch.               */
786 /*   usertest: -u switch.                                                    */
787 /*   regionattrib: -A switch.  convex: -c switch.                            */
788 /*   weighted: 1 for -w switch, 2 for -W switch.  jettison: -j switch        */
789 /*   firstnumber: inverse of -z switch.  All items are numbered starting     */
790 /*     from `firstnumber'.                                                   */
791 /*   edgesout: -e switch.  voronoi: -v switch.                               */
792 /*   neighbors: -n switch.  geomview: -g switch.                             */
793 /*   nobound: -B switch.  nopolywritten: -P switch.                          */
794 /*   nonodewritten: -N switch.  noelewritten: -E switch.                     */
795 /*   noiterationnum: -I switch.  noholes: -O switch.                         */
796 /*   noexact: -X switch.                                                     */
797 /*   order: element order, specified after -o switch.                        */
798 /*   nobisect: count of how often -Y switch is selected.                     */
799 /*   steiner: maximum number of Steiner points, specified after -S switch.   */
800 /*   incremental: -i switch.  sweepline: -F switch.                          */
801 /*   dwyer: inverse of -l switch.                                            */
802 /*   splitseg: -s switch.                                                    */
803 /*   conformdel: -D switch.  docheck: -C switch.                             */
804 /*   quiet: -Q switch.  verbose: count of how often -V switch is selected.   */
805 /*   usesegments: -p, -r, -q, or -c switch; determines whether segments are  */
806 /*     used at all.                                                          */
807 /*                                                                           */
808 /* Read the instructions to find out the meaning of these switches.          */
809 
810   int poly, refine, quality, vararea, fixedarea, usertest;
811   int regionattrib, convex, weighted, jettison;
812   int firstnumber;
813   int edgesout, voronoi, neighbors, geomview;
814   int nobound, nopolywritten, nonodewritten, noelewritten, noiterationnum;
815   int noholes, noexact, conformdel;
816   int incremental, sweepline, dwyer;
817   int splitseg;
818   int docheck;
819   int quiet, verbose;
820   int usesegments;
821   int order;
822   int nobisect;
823   int steiner;
824   REAL minangle, goodangle, offconstant;
825   REAL maxarea;
826 
827 /* Variables for file names.                                                 */
828 
829 #ifndef TRILIBRARY
830   char innodefilename[FILENAMESIZE];
831   char inelefilename[FILENAMESIZE];
832   char inpolyfilename[FILENAMESIZE];
833   char areafilename[FILENAMESIZE];
834   char outnodefilename[FILENAMESIZE];
835   char outelefilename[FILENAMESIZE];
836   char outpolyfilename[FILENAMESIZE];
837   char edgefilename[FILENAMESIZE];
838   char vnodefilename[FILENAMESIZE];
839   char vedgefilename[FILENAMESIZE];
840   char neighborfilename[FILENAMESIZE];
841   char offfilename[FILENAMESIZE];
842 #endif /* not TRILIBRARY */
843 
844 };                                              /* End of `struct behavior'. */
845 
846 
847 /*****************************************************************************/
848 /*                                                                           */
849 /*  Mesh manipulation primitives.  Each triangle contains three pointers to  */
850 /*  other triangles, with orientations.  Each pointer points not to the      */
851 /*  first byte of a triangle, but to one of the first three bytes of a       */
852 /*  triangle.  It is necessary to extract both the triangle itself and the   */
853 /*  orientation.  To save memory, I keep both pieces of information in one   */
854 /*  pointer.  To make this possible, I assume that all triangles are aligned */
855 /*  to four-byte boundaries.  The decode() routine below decodes a pointer,  */
856 /*  extracting an orientation (in the range 0 to 2) and a pointer to the     */
857 /*  beginning of a triangle.  The encode() routine compresses a pointer to a */
858 /*  triangle and an orientation into a single pointer.  My assumptions that  */
859 /*  triangles are four-byte-aligned and that the `unsigned long' type is     */
860 /*  long enough to hold a pointer are two of the few kludges in this program.*/
861 /*                                                                           */
862 /*  Subsegments are manipulated similarly.  A pointer to a subsegment        */
863 /*  carries both an address and an orientation in the range 0 to 1.          */
864 /*                                                                           */
865 /*  The other primitives take an oriented triangle or oriented subsegment,   */
866 /*  and return an oriented triangle or oriented subsegment or vertex; or     */
867 /*  they change the connections in the data structure.                       */
868 /*                                                                           */
869 /*  Below, triangles and subsegments are denoted by their vertices.  The     */
870 /*  triangle abc has origin (org) a, destination (dest) b, and apex (apex)   */
871 /*  c.  These vertices occur in counterclockwise order about the triangle.   */
872 /*  The handle abc may simultaneously denote vertex a, edge ab, and triangle */
873 /*  abc.                                                                     */
874 /*                                                                           */
875 /*  Similarly, the subsegment ab has origin (sorg) a and destination (sdest) */
876 /*  b.  If ab is thought to be directed upward (with b directly above a),    */
877 /*  then the handle ab is thought to grasp the right side of ab, and may     */
878 /*  simultaneously denote vertex a and edge ab.                              */
879 /*                                                                           */
880 /*  An asterisk (*) denotes a vertex whose identity is unknown.              */
881 /*                                                                           */
882 /*  Given this notation, a partial list of mesh manipulation primitives      */
883 /*  follows.                                                                 */
884 /*                                                                           */
885 /*                                                                           */
886 /*  For triangles:                                                           */
887 /*                                                                           */
888 /*  sym:  Find the abutting triangle; same edge.                             */
889 /*  sym(abc) -> ba*                                                          */
890 /*                                                                           */
891 /*  lnext:  Find the next edge (counterclockwise) of a triangle.             */
892 /*  lnext(abc) -> bca                                                        */
893 /*                                                                           */
894 /*  lprev:  Find the previous edge (clockwise) of a triangle.                */
895 /*  lprev(abc) -> cab                                                        */
896 /*                                                                           */
897 /*  onext:  Find the next edge counterclockwise with the same origin.        */
898 /*  onext(abc) -> ac*                                                        */
899 /*                                                                           */
900 /*  oprev:  Find the next edge clockwise with the same origin.               */
901 /*  oprev(abc) -> a*b                                                        */
902 /*                                                                           */
903 /*  dnext:  Find the next edge counterclockwise with the same destination.   */
904 /*  dnext(abc) -> *ba                                                        */
905 /*                                                                           */
906 /*  dprev:  Find the next edge clockwise with the same destination.          */
907 /*  dprev(abc) -> cb*                                                        */
908 /*                                                                           */
909 /*  rnext:  Find the next edge (counterclockwise) of the adjacent triangle.  */
910 /*  rnext(abc) -> *a*                                                        */
911 /*                                                                           */
912 /*  rprev:  Find the previous edge (clockwise) of the adjacent triangle.     */
913 /*  rprev(abc) -> b**                                                        */
914 /*                                                                           */
915 /*  org:  Origin          dest:  Destination          apex:  Apex            */
916 /*  org(abc) -> a         dest(abc) -> b              apex(abc) -> c         */
917 /*                                                                           */
918 /*  bond:  Bond two triangles together at the respective handles.            */
919 /*  bond(abc, bad)                                                           */
920 /*                                                                           */
921 /*                                                                           */
922 /*  For subsegments:                                                         */
923 /*                                                                           */
924 /*  ssym:  Reverse the orientation of a subsegment.                          */
925 /*  ssym(ab) -> ba                                                           */
926 /*                                                                           */
927 /*  spivot:  Find adjoining subsegment with the same origin.                 */
928 /*  spivot(ab) -> a*                                                         */
929 /*                                                                           */
930 /*  snext:  Find next subsegment in sequence.                                */
931 /*  snext(ab) -> b*                                                          */
932 /*                                                                           */
933 /*  sorg:  Origin                      sdest:  Destination                   */
934 /*  sorg(ab) -> a                      sdest(ab) -> b                        */
935 /*                                                                           */
936 /*  sbond:  Bond two subsegments together at the respective origins.         */
937 /*  sbond(ab, ac)                                                            */
938 /*                                                                           */
939 /*                                                                           */
940 /*  For interacting tetrahedra and subfacets:                                */
941 /*                                                                           */
942 /*  tspivot:  Find a subsegment abutting a triangle.                         */
943 /*  tspivot(abc) -> ba                                                       */
944 /*                                                                           */
945 /*  stpivot:  Find a triangle abutting a subsegment.                         */
946 /*  stpivot(ab) -> ba*                                                       */
947 /*                                                                           */
948 /*  tsbond:  Bond a triangle to a subsegment.                                */
949 /*  tsbond(abc, ba)                                                          */
950 /*                                                                           */
951 /*****************************************************************************/
952 
953 /********* Mesh manipulation primitives begin here                   *********/
954 /**                                                                         **/
955 /**                                                                         **/
956 
957 /* Fast lookup arrays to speed some of the mesh manipulation primitives.     */
958 
959 static int plus1mod3[3] = {1, 2, 0};
960 static int minus1mod3[3] = {2, 0, 1};
961 
962 /********* Primitives for triangles                                  *********/
963 /*                                                                           */
964 /*                                                                           */
965 
966 /* decode() converts a pointer to an oriented triangle.  The orientation is  */
967 /*   extracted from the two least significant bits of the pointer.           */
968 
969 #define decode(ptr, otri)                                                     \
970   (otri).orient = (int) ((unsigned LONG) (ptr) & (unsigned LONG) 3l);         \
971   (otri).tri = (triangle *)                                                   \
972                   ((unsigned LONG) (ptr) ^ (unsigned LONG) (otri).orient)
973 
974 /* encode() compresses an oriented triangle into a single pointer.  It       */
975 /*   relies on the assumption that all triangles are aligned to four-byte    */
976 /*   boundaries, so the two least significant bits of (otri).tri are zero.   */
977 
978 #define encode(otri)                                                          \
979   (triangle) ((unsigned LONG) (otri).tri | (unsigned LONG) (otri).orient)
980 
981 /* The following handle manipulation primitives are all described by Guibas  */
982 /*   and Stolfi.  However, Guibas and Stolfi use an edge-based data          */
983 /*   structure, whereas I use a triangle-based data structure.               */
984 
985 /* sym() finds the abutting triangle, on the same edge.  Note that the edge  */
986 /*   direction is necessarily reversed, because the handle specified by an   */
987 /*   oriented triangle is directed counterclockwise around the triangle.     */
988 
989 #define sym(otri1, otri2)                                                     \
990   ptr = (otri1).tri[(otri1).orient];                                          \
991   decode(ptr, otri2);
992 
993 #define symself(otri)                                                         \
994   ptr = (otri).tri[(otri).orient];                                            \
995   decode(ptr, otri);
996 
997 /* lnext() finds the next edge (counterclockwise) of a triangle.             */
998 
999 #define lnext(otri1, otri2)                                                   \
1000   (otri2).tri = (otri1).tri;                                                  \
1001   (otri2).orient = plus1mod3[(otri1).orient]
1002 
1003 #define lnextself(otri)                                                       \
1004   (otri).orient = plus1mod3[(otri).orient]
1005 
1006 /* lprev() finds the previous edge (clockwise) of a triangle.                */
1007 
1008 #define lprev(otri1, otri2)                                                   \
1009   (otri2).tri = (otri1).tri;                                                  \
1010   (otri2).orient = minus1mod3[(otri1).orient]
1011 
1012 #define lprevself(otri)                                                       \
1013   (otri).orient = minus1mod3[(otri).orient]
1014 
1015 /* onext() spins counterclockwise around a vertex; that is, it finds the     */
1016 /*   next edge with the same origin in the counterclockwise direction.  This */
1017 /*   edge is part of a different triangle.                                   */
1018 
1019 #define onext(otri1, otri2)                                                   \
1020   lprev(otri1, otri2);                                                        \
1021   symself(otri2);
1022 
1023 #define onextself(otri)                                                       \
1024   lprevself(otri);                                                            \
1025   symself(otri);
1026 
1027 /* oprev() spins clockwise around a vertex; that is, it finds the next edge  */
1028 /*   with the same origin in the clockwise direction.  This edge is part of  */
1029 /*   a different triangle.                                                   */
1030 
1031 #define oprev(otri1, otri2)                                                   \
1032   sym(otri1, otri2);                                                          \
1033   lnextself(otri2);
1034 
1035 #define oprevself(otri)                                                       \
1036   symself(otri);                                                              \
1037   lnextself(otri);
1038 
1039 /* dnext() spins counterclockwise around a vertex; that is, it finds the     */
1040 /*   next edge with the same destination in the counterclockwise direction.  */
1041 /*   This edge is part of a different triangle.                              */
1042 
1043 #define dnext(otri1, otri2)                                                   \
1044   sym(otri1, otri2);                                                          \
1045   lprevself(otri2);
1046 
1047 #define dnextself(otri)                                                       \
1048   symself(otri);                                                              \
1049   lprevself(otri);
1050 
1051 /* dprev() spins clockwise around a vertex; that is, it finds the next edge  */
1052 /*   with the same destination in the clockwise direction.  This edge is     */
1053 /*   part of a different triangle.                                           */
1054 
1055 #define dprev(otri1, otri2)                                                   \
1056   lnext(otri1, otri2);                                                        \
1057   symself(otri2);
1058 
1059 #define dprevself(otri)                                                       \
1060   lnextself(otri);                                                            \
1061   symself(otri);
1062 
1063 /* rnext() moves one edge counterclockwise about the adjacent triangle.      */
1064 /*   (It's best understood by reading Guibas and Stolfi.  It involves        */
1065 /*   changing triangles twice.)                                              */
1066 
1067 #define rnext(otri1, otri2)                                                   \
1068   sym(otri1, otri2);                                                          \
1069   lnextself(otri2);                                                           \
1070   symself(otri2);
1071 
1072 #define rnextself(otri)                                                       \
1073   symself(otri);                                                              \
1074   lnextself(otri);                                                            \
1075   symself(otri);
1076 
1077 /* rprev() moves one edge clockwise about the adjacent triangle.             */
1078 /*   (It's best understood by reading Guibas and Stolfi.  It involves        */
1079 /*   changing triangles twice.)                                              */
1080 
1081 #define rprev(otri1, otri2)                                                   \
1082   sym(otri1, otri2);                                                          \
1083   lprevself(otri2);                                                           \
1084   symself(otri2);
1085 
1086 #define rprevself(otri)                                                       \
1087   symself(otri);                                                              \
1088   lprevself(otri);                                                            \
1089   symself(otri);
1090 
1091 /* These primitives determine or set the origin, destination, or apex of a   */
1092 /* triangle.                                                                 */
1093 
1094 #define org(otri, vertexptr)                                                  \
1095   vertexptr = (vertex) (otri).tri[plus1mod3[(otri).orient] + 3]
1096 
1097 #define dest(otri, vertexptr)                                                 \
1098   vertexptr = (vertex) (otri).tri[minus1mod3[(otri).orient] + 3]
1099 
1100 #define apex(otri, vertexptr)                                                 \
1101   vertexptr = (vertex) (otri).tri[(otri).orient + 3]
1102 
1103 #define setorg(otri, vertexptr)                                               \
1104   (otri).tri[plus1mod3[(otri).orient] + 3] = (triangle) vertexptr
1105 
1106 #define setdest(otri, vertexptr)                                              \
1107   (otri).tri[minus1mod3[(otri).orient] + 3] = (triangle) vertexptr
1108 
1109 #define setapex(otri, vertexptr)                                              \
1110   (otri).tri[(otri).orient + 3] = (triangle) vertexptr
1111 
1112 /* Bond two triangles together.                                              */
1113 
1114 #define bond(otri1, otri2)                                                    \
1115   (otri1).tri[(otri1).orient] = encode(otri2);                                \
1116   (otri2).tri[(otri2).orient] = encode(otri1)
1117 
1118 /* Dissolve a bond (from one side).  Note that the other triangle will still */
1119 /*   think it's connected to this triangle.  Usually, however, the other     */
1120 /*   triangle is being deleted entirely, or bonded to another triangle, so   */
1121 /*   it doesn't matter.                                                      */
1122 
1123 #define dissolve(otri)                                                        \
1124   (otri).tri[(otri).orient] = (triangle) m->dummytri
1125 
1126 /* Copy an oriented triangle.                                                */
1127 
1128 #define otricopy(otri1, otri2)                                                \
1129   (otri2).tri = (otri1).tri;                                                  \
1130   (otri2).orient = (otri1).orient
1131 
1132 /* Test for equality of oriented triangles.                                  */
1133 
1134 #define otriequal(otri1, otri2)                                               \
1135   (((otri1).tri == (otri2).tri) &&                                            \
1136    ((otri1).orient == (otri2).orient))
1137 
1138 /* Primitives to infect or cure a triangle with the virus.  These rely on    */
1139 /*   the assumption that all subsegments are aligned to four-byte boundaries.*/
1140 
1141 #define infect(otri)                                                          \
1142   (otri).tri[6] = (triangle)                                                  \
1143                     ((unsigned LONG) (otri).tri[6] | (unsigned LONG) 2l)
1144 
1145 #define uninfect(otri)                                                        \
1146   (otri).tri[6] = (triangle)                                                  \
1147                     ((unsigned LONG) (otri).tri[6] & ~ (unsigned LONG) 2l)
1148 
1149 /* Test a triangle for viral infection.                                      */
1150 
1151 #define infected(otri)                                                        \
1152   (((unsigned LONG) (otri).tri[6] & (unsigned LONG) 2l) != 0l)
1153 
1154 /* Check or set a triangle's attributes.                                     */
1155 
1156 #define elemattribute(otri, attnum)                                           \
1157   ((REAL *) (otri).tri)[m->elemattribindex + (attnum)]
1158 
1159 #define setelemattribute(otri, attnum, value)                                 \
1160   ((REAL *) (otri).tri)[m->elemattribindex + (attnum)] = value
1161 
1162 /* Check or set a triangle's maximum area bound.                             */
1163 
1164 #define areabound(otri)  ((REAL *) (otri).tri)[m->areaboundindex]
1165 
1166 #define setareabound(otri, value)                                             \
1167   ((REAL *) (otri).tri)[m->areaboundindex] = value
1168 
1169 /* Check or set a triangle's deallocation.  Its second pointer is set to     */
1170 /*   NULL to indicate that it is not allocated.  (Its first pointer is used  */
1171 /*   for the stack of dead items.)  Its fourth pointer (its first vertex)    */
1172 /*   is set to NULL in case a `badtriang' structure points to it.            */
1173 
1174 #define deadtri(tria)  ((tria)[1] == (triangle) NULL)
1175 
1176 #define killtri(tria)                                                         \
1177   (tria)[1] = (triangle) NULL;                                                \
1178   (tria)[3] = (triangle) NULL
1179 
1180 /********* Primitives for subsegments                                *********/
1181 /*                                                                           */
1182 /*                                                                           */
1183 
1184 /* sdecode() converts a pointer to an oriented subsegment.  The orientation  */
1185 /*   is extracted from the least significant bit of the pointer.  The two    */
1186 /*   least significant bits (one for orientation, one for viral infection)   */
1187 /*   are masked out to produce the real pointer.                             */
1188 
1189 #define sdecode(sptr, osub)                                                   \
1190   (osub).ssorient = (int) ((unsigned LONG) (sptr) & (unsigned LONG) 1l);      \
1191   (osub).ss = (subseg *)                                                      \
1192               ((unsigned LONG) (sptr) & ~ (unsigned LONG) 3l)
1193 
1194 /* sencode() compresses an oriented subsegment into a single pointer.  It    */
1195 /*   relies on the assumption that all subsegments are aligned to two-byte   */
1196 /*   boundaries, so the least significant bit of (osub).ss is zero.          */
1197 
1198 #define sencode(osub)                                                         \
1199   (subseg) ((unsigned LONG) (osub).ss | (unsigned LONG) (osub).ssorient)
1200 
1201 /* ssym() toggles the orientation of a subsegment.                           */
1202 
1203 #define ssym(osub1, osub2)                                                    \
1204   (osub2).ss = (osub1).ss;                                                    \
1205   (osub2).ssorient = 1 - (osub1).ssorient
1206 
1207 #define ssymself(osub)                                                        \
1208   (osub).ssorient = 1 - (osub).ssorient
1209 
1210 /* spivot() finds the other subsegment (from the same segment) that shares   */
1211 /*   the same origin.                                                        */
1212 
1213 #define spivot(osub1, osub2)                                                  \
1214   sptr = (osub1).ss[(osub1).ssorient];                                        \
1215   sdecode(sptr, osub2)
1216 
1217 #define spivotself(osub)                                                      \
1218   sptr = (osub).ss[(osub).ssorient];                                          \
1219   sdecode(sptr, osub)
1220 
1221 /* snext() finds the next subsegment (from the same segment) in sequence;    */
1222 /*   one whose origin is the input subsegment's destination.                 */
1223 
1224 #define snext(osub1, osub2)                                                   \
1225   sptr = (osub1).ss[1 - (osub1).ssorient];                                    \
1226   sdecode(sptr, osub2)
1227 
1228 #define snextself(osub)                                                       \
1229   sptr = (osub).ss[1 - (osub).ssorient];                                      \
1230   sdecode(sptr, osub)
1231 
1232 /* These primitives determine or set the origin or destination of a          */
1233 /*   subsegment or the segment that includes it.                             */
1234 
1235 #define sorg(osub, vertexptr)                                                 \
1236   vertexptr = (vertex) (osub).ss[2 + (osub).ssorient]
1237 
1238 #define sdest(osub, vertexptr)                                                \
1239   vertexptr = (vertex) (osub).ss[3 - (osub).ssorient]
1240 
1241 #define setsorg(osub, vertexptr)                                              \
1242   (osub).ss[2 + (osub).ssorient] = (subseg) vertexptr
1243 
1244 #define setsdest(osub, vertexptr)                                             \
1245   (osub).ss[3 - (osub).ssorient] = (subseg) vertexptr
1246 
1247 #define segorg(osub, vertexptr)                                               \
1248   vertexptr = (vertex) (osub).ss[4 + (osub).ssorient]
1249 
1250 #define segdest(osub, vertexptr)                                              \
1251   vertexptr = (vertex) (osub).ss[5 - (osub).ssorient]
1252 
1253 #define setsegorg(osub, vertexptr)                                            \
1254   (osub).ss[4 + (osub).ssorient] = (subseg) vertexptr
1255 
1256 #define setsegdest(osub, vertexptr)                                           \
1257   (osub).ss[5 - (osub).ssorient] = (subseg) vertexptr
1258 
1259 /* These primitives read or set a boundary marker.  Boundary markers are     */
1260 /*   used to hold user-defined tags for setting boundary conditions in       */
1261 /*   finite element solvers.                                                 */
1262 
1263 #define mark(osub)  (* (int *) ((osub).ss + 8))
1264 
1265 #define setmark(osub, value)                                                  \
1266   * (int *) ((osub).ss + 8) = value
1267 
1268 /* Bond two subsegments together.                                            */
1269 
1270 #define sbond(osub1, osub2)                                                   \
1271   (osub1).ss[(osub1).ssorient] = sencode(osub2);                              \
1272   (osub2).ss[(osub2).ssorient] = sencode(osub1)
1273 
1274 /* Dissolve a subsegment bond (from one side).  Note that the other          */
1275 /*   subsegment will still think it's connected to this subsegment.          */
1276 
1277 #define sdissolve(osub)                                                       \
1278   (osub).ss[(osub).ssorient] = (subseg) m->dummysub
1279 
1280 /* Copy a subsegment.                                                        */
1281 
1282 #define subsegcopy(osub1, osub2)                                              \
1283   (osub2).ss = (osub1).ss;                                                    \
1284   (osub2).ssorient = (osub1).ssorient
1285 
1286 /* Test for equality of subsegments.                                         */
1287 
1288 #define subsegequal(osub1, osub2)                                             \
1289   (((osub1).ss == (osub2).ss) &&                                              \
1290    ((osub1).ssorient == (osub2).ssorient))
1291 
1292 /* Check or set a subsegment's deallocation.  Its second pointer is set to   */
1293 /*   NULL to indicate that it is not allocated.  (Its first pointer is used  */
1294 /*   for the stack of dead items.)  Its third pointer (its first vertex)     */
1295 /*   is set to NULL in case a `badsubseg' structure points to it.            */
1296 
1297 #define deadsubseg(sub)  ((sub)[1] == (subseg) NULL)
1298 
1299 #define killsubseg(sub)                                                       \
1300   (sub)[1] = (subseg) NULL;                                                   \
1301   (sub)[2] = (subseg) NULL
1302 
1303 /********* Primitives for interacting triangles and subsegments      *********/
1304 /*                                                                           */
1305 /*                                                                           */
1306 
1307 /* tspivot() finds a subsegment abutting a triangle.                         */
1308 
1309 #define tspivot(otri, osub)                                                   \
1310   sptr = (subseg) (otri).tri[6 + (otri).orient];                              \
1311   sdecode(sptr, osub)
1312 
1313 /* stpivot() finds a triangle abutting a subsegment.  It requires that the   */
1314 /*   variable `ptr' of type `triangle' be defined.                           */
1315 
1316 #define stpivot(osub, otri)                                                   \
1317   ptr = (triangle) (osub).ss[6 + (osub).ssorient];                            \
1318   decode(ptr, otri)
1319 
1320 /* Bond a triangle to a subsegment.                                          */
1321 
1322 #define tsbond(otri, osub)                                                    \
1323   (otri).tri[6 + (otri).orient] = (triangle) sencode(osub);                   \
1324   (osub).ss[6 + (osub).ssorient] = (subseg) encode(otri)
1325 
1326 /* Dissolve a bond (from the triangle side).                                 */
1327 
1328 #define tsdissolve(otri)                                                      \
1329   (otri).tri[6 + (otri).orient] = (triangle) m->dummysub
1330 
1331 /* Dissolve a bond (from the subsegment side).                               */
1332 
1333 #define stdissolve(osub)                                                      \
1334   (osub).ss[6 + (osub).ssorient] = (subseg) m->dummytri
1335 
1336 /********* Primitives for vertices                                   *********/
1337 /*                                                                           */
1338 /*                                                                           */
1339 
1340 #define vertexmark(vx)  ((int *) (vx))[m->vertexmarkindex]
1341 
1342 #define setvertexmark(vx, value)                                              \
1343   ((int *) (vx))[m->vertexmarkindex] = value
1344 
1345 #define vertextype(vx)  ((int *) (vx))[m->vertexmarkindex + 1]
1346 
1347 #define setvertextype(vx, value)                                              \
1348   ((int *) (vx))[m->vertexmarkindex + 1] = value
1349 
1350 #define vertex2tri(vx)  ((triangle *) (vx))[m->vertex2triindex]
1351 
1352 #define setvertex2tri(vx, value)                                              \
1353   ((triangle *) (vx))[m->vertex2triindex] = value
1354 
1355 /**                                                                         **/
1356 /**                                                                         **/
1357 /********* Mesh manipulation primitives end here                     *********/
1358 
1359 /********* User-defined triangle evaluation routine begins here      *********/
1360 /**                                                                         **/
1361 /**                                                                         **/
1362 
1363 /*****************************************************************************/
1364 /*                                                                           */
1365 /*  triunsuitable()   Determine if a triangle is unsuitable, and thus must   */
1366 /*                    be further refined.                                    */
1367 /*                                                                           */
1368 /*  You may write your own procedure that decides whether or not a selected  */
1369 /*  triangle is too big (and needs to be refined).  There are two ways to do */
1370 /*  this.                                                                    */
1371 /*                                                                           */
1372 /*  (1)  Modify the procedure `triunsuitable' below, then recompile          */
1373 /*  Triangle.                                                                */
1374 /*                                                                           */
1375 /*  (2)  Define the symbol EXTERNAL_TEST (either by adding the definition    */
1376 /*  to this file, or by using the appropriate compiler switch).  This way,   */
1377 /*  you can compile triangle.c separately from your test.  Write your own    */
1378 /*  `triunsuitable' procedure in a separate C file (using the same prototype */
1379 /*  as below).  Compile it and link the object code with triangle.o.         */
1380 /*                                                                           */
1381 /*  This procedure returns 1 if the triangle is too large and should be      */
1382 /*  refined; 0 otherwise.                                                    */
1383 /*                                                                           */
1384 /*****************************************************************************/
1385 
1386 #ifndef CDT_ONLY
1387 
1388 #ifdef EXTERNAL_TEST
1389 
1390 static int triunsuitable();
1391 
1392 #else /* not EXTERNAL_TEST */
1393 
1394 #ifdef ANSI_DECLARATORS
1395 static int triunsuitable(vertex triorg, vertex tridest, vertex triapex, REAL area)
1396 #else /* not ANSI_DECLARATORS */
1397 static int triunsuitable(triorg, tridest, triapex, area)
1398 vertex triorg;                              /* The triangle's origin vertex. */
1399 vertex tridest;                        /* The triangle's destination vertex. */
1400 vertex triapex;                               /* The triangle's apex vertex. */
1401 REAL area;                                      /* The area of the triangle. */
1402 #endif /* not ANSI_DECLARATORS */
1403 
1404 {
1405   REAL dxoa, dxda, dxod;
1406   REAL dyoa, dyda, dyod;
1407   REAL oalen, dalen, odlen;
1408   REAL maxlen;
1409 
1410   dxoa = triorg[0] - triapex[0];
1411   dyoa = triorg[1] - triapex[1];
1412   dxda = tridest[0] - triapex[0];
1413   dyda = tridest[1] - triapex[1];
1414   dxod = triorg[0] - tridest[0];
1415   dyod = triorg[1] - tridest[1];
1416   /* Find the squares of the lengths of the triangle's three edges. */
1417   oalen = dxoa * dxoa + dyoa * dyoa;
1418   dalen = dxda * dxda + dyda * dyda;
1419   odlen = dxod * dxod + dyod * dyod;
1420   /* Find the square of the length of the longest edge. */
1421   maxlen = (dalen > oalen) ? dalen : oalen;
1422   maxlen = (odlen > maxlen) ? odlen : maxlen;
1423 
1424   if (maxlen > 0.05 * (triorg[0] * triorg[0] + triorg[1] * triorg[1]) + 0.02) {
1425     return 1;
1426   } else {
1427     return 0;
1428   }
1429 }
1430 
1431 #endif /* not EXTERNAL_TEST */
1432 
1433 #endif /* not CDT_ONLY */
1434 
1435 /**                                                                         **/
1436 /**                                                                         **/
1437 /********* User-defined triangle evaluation routine ends here        *********/
1438 
1439 /********* Memory allocation and program exit wrappers begin here    *********/
1440 /**                                                                         **/
1441 /**                                                                         **/
1442 
1443 #ifdef ANSI_DECLARATORS
1444 static void triexit(int status)
1445 #else /* not ANSI_DECLARATORS */
1446 static void triexit(status)
1447 int status;
1448 #endif /* not ANSI_DECLARATORS */
1449 
1450 {
1451   exit(status);
1452 }
1453 
1454 #ifdef ANSI_DECLARATORS
1455 static VOID *trimalloc(size_t size)
1456 #else /* not ANSI_DECLARATORS */
1457 static VOID *trimalloc(size)
1458 size_t size;
1459 #endif /* not ANSI_DECLARATORS */
1460 
1461 {
1462   VOID *memptr;
1463 
1464   memptr = (VOID *) malloc(size);
1465   if (memptr == (VOID *) NULL) {
1466     printf("Error: Out of memory.\n");
1467     triexit(1);
1468   }
1469   return(memptr);
1470 }
1471 
1472 #ifdef ANSI_DECLARATORS
1473 static void trifree(VOID *memptr)
1474 #else /* not ANSI_DECLARATORS */
1475 static void trifree(memptr)
1476 VOID *memptr;
1477 #endif /* not ANSI_DECLARATORS */
1478 
1479 {
1480   free(memptr);
1481 }
1482 
1483 /**                                                                         **/
1484 /**                                                                         **/
1485 /********* Memory allocation and program exit wrappers end here      *********/
1486 
1487 /********* User interaction routines begin here                      *********/
1488 /**                                                                         **/
1489 /**                                                                         **/
1490 
1491 /*****************************************************************************/
1492 /*                                                                           */
1493 /*  syntax()   Print list of command line switches.                          */
1494 /*                                                                           */
1495 /*****************************************************************************/
1496 
1497 #ifndef TRILIBRARY
1498 
syntax()1499 static void syntax()
1500 {
1501 #ifdef CDT_ONLY
1502 #ifdef REDUCED
1503   printf("triangle [-pAcjevngBPNEIOXzo_lQVh] input_file\n");
1504 #else /* not REDUCED */
1505   printf("triangle [-pAcjevngBPNEIOXzo_iFlCQVh] input_file\n");
1506 #endif /* not REDUCED */
1507 #else /* not CDT_ONLY */
1508 #ifdef REDUCED
1509   printf("triangle [-prq__a__uAcDjevngBPNEIOXzo_YS__lQVh] input_file\n");
1510 #else /* not REDUCED */
1511   printf("triangle [-prq__a__uAcDjevngBPNEIOXzo_YS__iFlsCQVh] input_file\n");
1512 #endif /* not REDUCED */
1513 #endif /* not CDT_ONLY */
1514 
1515   printf("    -p  Triangulates a Planar Straight Line Graph (.poly file).\n");
1516 #ifndef CDT_ONLY
1517   printf("    -r  Refines a previously generated mesh.\n");
1518   printf(
1519     "    -q  Quality mesh generation.  A minimum angle may be specified.\n");
1520   printf("    -a  Applies a maximum triangle area constraint.\n");
1521   printf("    -u  Applies a user-defined triangle constraint.\n");
1522 #endif /* not CDT_ONLY */
1523   printf(
1524     "    -A  Applies attributes to identify triangles in certain regions.\n");
1525   printf("    -c  Encloses the convex hull with segments.\n");
1526 #ifndef CDT_ONLY
1527   printf("    -D  Conforming Delaunay:  all triangles are truly Delaunay.\n");
1528 #endif /* not CDT_ONLY */
1529 /*
1530   printf("    -w  Weighted Delaunay triangulation.\n");
1531   printf("    -W  Regular triangulation (lower hull of a height field).\n");
1532 */
1533   printf("    -j  Jettison unused vertices from output .node file.\n");
1534   printf("    -e  Generates an edge list.\n");
1535   printf("    -v  Generates a Voronoi diagram.\n");
1536   printf("    -n  Generates a list of triangle neighbors.\n");
1537   printf("    -g  Generates an .off file for Geomview.\n");
1538   printf("    -B  Suppresses output of boundary information.\n");
1539   printf("    -P  Suppresses output of .poly file.\n");
1540   printf("    -N  Suppresses output of .node file.\n");
1541   printf("    -E  Suppresses output of .ele file.\n");
1542   printf("    -I  Suppresses mesh iteration numbers.\n");
1543   printf("    -O  Ignores holes in .poly file.\n");
1544   printf("    -X  Suppresses use of exact arithmetic.\n");
1545   printf("    -z  Numbers all items starting from zero (rather than one).\n");
1546   printf("    -o2 Generates second-order subparametric elements.\n");
1547 #ifndef CDT_ONLY
1548   printf("    -Y  Suppresses boundary segment splitting.\n");
1549   printf("    -S  Specifies maximum number of added Steiner points.\n");
1550 #endif /* not CDT_ONLY */
1551 #ifndef REDUCED
1552   printf("    -i  Uses incremental method, rather than divide-and-conquer.\n");
1553   printf("    -F  Uses Fortune's sweepline algorithm, rather than d-and-c.\n");
1554 #endif /* not REDUCED */
1555   printf("    -l  Uses vertical cuts only, rather than alternating cuts.\n");
1556 #ifndef REDUCED
1557 #ifndef CDT_ONLY
1558   printf(
1559     "    -s  Force segments into mesh by splitting (instead of using CDT).\n");
1560 #endif /* not CDT_ONLY */
1561   printf("    -C  Check consistency of final mesh.\n");
1562 #endif /* not REDUCED */
1563   printf("    -Q  Quiet:  No terminal output except errors.\n");
1564   printf("    -V  Verbose:  Detailed information on what I'm doing.\n");
1565   printf("    -h  Help:  Detailed instructions for Triangle.\n");
1566   triexit(0);
1567 }
1568 
1569 #endif /* not TRILIBRARY */
1570 
1571 /*****************************************************************************/
1572 /*                                                                           */
1573 /*  info()   Print out complete instructions.                                */
1574 /*                                                                           */
1575 /*****************************************************************************/
1576 
1577 #ifndef TRILIBRARY
1578 
info()1579 static void info()
1580 {
1581   printf("Triangle\n");
1582   printf(
1583 "A Two-Dimensional Quality Mesh Generator and Delaunay Triangulator.\n");
1584   printf("Version 1.6\n\n");
1585   printf(
1586 "Copyright 1993, 1995, 1997, 1998, 2002, 2005 Jonathan Richard Shewchuk\n");
1587   printf("2360 Woolsey #H / Berkeley, California 94705-1927\n");
1588   printf("Bugs/comments to jrs@cs.berkeley.edu\n");
1589   printf(
1590 "Created as part of the Quake project (tools for earthquake simulation).\n");
1591   printf(
1592 "Supported in part by NSF Grant CMS-9318163 and an NSERC 1967 Scholarship.\n");
1593   printf("There is no warranty whatsoever.  Use at your own risk.\n");
1594 #ifdef SINGLE
1595   printf("This executable is compiled for single precision arithmetic.\n\n\n");
1596 #else /* not SINGLE */
1597   printf("This executable is compiled for double precision arithmetic.\n\n\n");
1598 #endif /* not SINGLE */
1599   printf(
1600 "Triangle generates exact Delaunay triangulations, constrained Delaunay\n");
1601   printf(
1602 "triangulations, conforming Delaunay triangulations, Voronoi diagrams, and\n");
1603   printf(
1604 "high-quality triangular meshes.  The latter can be generated with no small\n"
1605 );
1606   printf(
1607 "or large angles, and are thus suitable for finite element analysis.  If no\n"
1608 );
1609   printf(
1610 "command line switch is specified, your .node input file is read, and the\n");
1611   printf(
1612 "Delaunay triangulation is returned in .node and .ele output files.  The\n");
1613   printf("command syntax is:\n\n");
1614   printf("triangle [-prq__a__uAcDjevngBPNEIOXzo_YS__iFlsCQVh] input_file\n\n");
1615   printf(
1616 "Underscores indicate that numbers may optionally follow certain switches.\n");
1617   printf(
1618 "Do not leave any space between a switch and its numeric parameter.\n");
1619   printf(
1620 "input_file must be a file with extension .node, or extension .poly if the\n");
1621   printf(
1622 "-p switch is used.  If -r is used, you must supply .node and .ele files,\n");
1623   printf(
1624 "and possibly a .poly file and an .area file as well.  The formats of these\n"
1625 );
1626   printf("files are described below.\n\n");
1627   printf("Command Line Switches:\n\n");
1628   printf(
1629 "    -p  Reads a Planar Straight Line Graph (.poly file), which can specify\n"
1630 );
1631   printf(
1632 "        vertices, segments, holes, regional attributes, and regional area\n");
1633   printf(
1634 "        constraints.  Generates a constrained Delaunay triangulation (CDT)\n"
1635 );
1636   printf(
1637 "        fitting the input; or, if -s, -q, -a, or -u is used, a conforming\n");
1638   printf(
1639 "        constrained Delaunay triangulation (CCDT).  If you want a truly\n");
1640   printf(
1641 "        Delaunay (not just constrained Delaunay) triangulation, use -D as\n");
1642   printf(
1643 "        well.  When -p is not used, Triangle reads a .node file by default.\n"
1644 );
1645   printf(
1646 "    -r  Refines a previously generated mesh.  The mesh is read from a .node\n"
1647 );
1648   printf(
1649 "        file and an .ele file.  If -p is also used, a .poly file is read\n");
1650   printf(
1651 "        and used to constrain segments in the mesh.  If -a is also used\n");
1652   printf(
1653 "        (with no number following), an .area file is read and used to\n");
1654   printf(
1655 "        impose area constraints on the mesh.  Further details on refinement\n"
1656 );
1657   printf("        appear below.\n");
1658   printf(
1659 "    -q  Quality mesh generation by Delaunay refinement (a hybrid of Paul\n");
1660   printf(
1661 "        Chew's and Jim Ruppert's algorithms).  Adds vertices to the mesh to\n"
1662 );
1663   printf(
1664 "        ensure that all angles are between 20 and 140 degrees.  An\n");
1665   printf(
1666 "        alternative bound on the minimum angle, replacing 20 degrees, may\n");
1667   printf(
1668 "        be specified after the `q'.  The specified angle may include a\n");
1669   printf(
1670 "        decimal point, but not exponential notation.  Note that a bound of\n"
1671 );
1672   printf(
1673 "        theta degrees on the smallest angle also implies a bound of\n");
1674   printf(
1675 "        (180 - 2 theta) on the largest angle.  If the minimum angle is 28.6\n"
1676 );
1677   printf(
1678 "        degrees or smaller, Triangle is mathematically guaranteed to\n");
1679   printf(
1680 "        terminate (assuming infinite precision arithmetic--Triangle may\n");
1681   printf(
1682 "        fail to terminate if you run out of precision).  In practice,\n");
1683   printf(
1684 "        Triangle often succeeds for minimum angles up to 34 degrees.  For\n");
1685   printf(
1686 "        some meshes, however, you might need to reduce the minimum angle to\n"
1687 );
1688   printf(
1689 "        avoid problems associated with insufficient floating-point\n");
1690   printf("        precision.\n");
1691   printf(
1692 "    -a  Imposes a maximum triangle area.  If a number follows the `a', no\n");
1693   printf(
1694 "        triangle is generated whose area is larger than that number.  If no\n"
1695 );
1696   printf(
1697 "        number is specified, an .area file (if -r is used) or .poly file\n");
1698   printf(
1699 "        (if -r is not used) specifies a set of maximum area constraints.\n");
1700   printf(
1701 "        An .area file contains a separate area constraint for each\n");
1702   printf(
1703 "        triangle, and is useful for refining a finite element mesh based on\n"
1704 );
1705   printf(
1706 "        a posteriori error estimates.  A .poly file can optionally contain\n"
1707 );
1708   printf(
1709 "        an area constraint for each segment-bounded region, thereby\n");
1710   printf(
1711 "        controlling triangle densities in a first triangulation of a PSLG.\n"
1712 );
1713   printf(
1714 "        You can impose both a fixed area constraint and a varying area\n");
1715   printf(
1716 "        constraint by invoking the -a switch twice, once with and once\n");
1717   printf(
1718 "        without a number following.  Each area specified may include a\n");
1719   printf("        decimal point.\n");
1720   printf(
1721 "    -u  Imposes a user-defined constraint on triangle size.  There are two\n"
1722 );
1723   printf(
1724 "        ways to use this feature.  One is to edit the triunsuitable()\n");
1725   printf(
1726 "        procedure in triangle.c to encode any constraint you like, then\n");
1727   printf(
1728 "        recompile Triangle.  The other is to compile triangle.c with the\n");
1729   printf(
1730 "        EXTERNAL_TEST symbol set (compiler switch -DEXTERNAL_TEST), then\n");
1731   printf(
1732 "        link Triangle with a separate object file that implements\n");
1733   printf(
1734 "        triunsuitable().  In either case, the -u switch causes the user-\n");
1735   printf("        defined test to be applied to every triangle.\n");
1736   printf(
1737 "    -A  Assigns an additional floating-point attribute to each triangle\n");
1738   printf(
1739 "        that identifies what segment-bounded region each triangle belongs\n");
1740   printf(
1741 "        to.  Attributes are assigned to regions by the .poly file.  If a\n");
1742   printf(
1743 "        region is not explicitly marked by the .poly file, triangles in\n");
1744   printf(
1745 "        that region are assigned an attribute of zero.  The -A switch has\n");
1746   printf(
1747 "        an effect only when the -p switch is used and the -r switch is not.\n"
1748 );
1749   printf(
1750 "    -c  Creates segments on the convex hull of the triangulation.  If you\n");
1751   printf(
1752 "        are triangulating a vertex set, this switch causes a .poly file to\n"
1753 );
1754   printf(
1755 "        be written, containing all edges of the convex hull.  If you are\n");
1756   printf(
1757 "        triangulating a PSLG, this switch specifies that the whole convex\n");
1758   printf(
1759 "        hull of the PSLG should be triangulated, regardless of what\n");
1760   printf(
1761 "        segments the PSLG has.  If you do not use this switch when\n");
1762   printf(
1763 "        triangulating a PSLG, Triangle assumes that you have identified the\n"
1764 );
1765   printf(
1766 "        region to be triangulated by surrounding it with segments of the\n");
1767   printf(
1768 "        input PSLG.  Beware:  if you are not careful, this switch can cause\n"
1769 );
1770   printf(
1771 "        the introduction of an extremely thin angle between a PSLG segment\n"
1772 );
1773   printf(
1774 "        and a convex hull segment, which can cause overrefinement (and\n");
1775   printf(
1776 "        possibly failure if Triangle runs out of precision).  If you are\n");
1777   printf(
1778 "        refining a mesh, the -c switch works differently:  it causes a\n");
1779   printf(
1780 "        .poly file to be written containing the boundary edges of the mesh\n"
1781 );
1782   printf("        (useful if no .poly file was read).\n");
1783   printf(
1784 "    -D  Conforming Delaunay triangulation:  use this switch if you want to\n"
1785 );
1786   printf(
1787 "        ensure that all the triangles in the mesh are Delaunay, and not\n");
1788   printf(
1789 "        merely constrained Delaunay; or if you want to ensure that all the\n"
1790 );
1791   printf(
1792 "        Voronoi vertices lie within the triangulation.  (Some finite volume\n"
1793 );
1794   printf(
1795 "        methods have this requirement.)  This switch invokes Ruppert's\n");
1796   printf(
1797 "        original algorithm, which splits every subsegment whose diametral\n");
1798   printf(
1799 "        circle is encroached.  It usually increases the number of vertices\n"
1800 );
1801   printf("        and triangles.\n");
1802   printf(
1803 "    -j  Jettisons vertices that are not part of the final triangulation\n");
1804   printf(
1805 "        from the output .node file.  By default, Triangle copies all\n");
1806   printf(
1807 "        vertices in the input .node file to the output .node file, in the\n");
1808   printf(
1809 "        same order, so their indices do not change.  The -j switch prevents\n"
1810 );
1811   printf(
1812 "        duplicated input vertices, or vertices `eaten' by holes, from\n");
1813   printf(
1814 "        appearing in the output .node file.  Thus, if two input vertices\n");
1815   printf(
1816 "        have exactly the same coordinates, only the first appears in the\n");
1817   printf(
1818 "        output.  If any vertices are jettisoned, the vertex numbering in\n");
1819   printf(
1820 "        the output .node file differs from that of the input .node file.\n");
1821   printf(
1822 "    -e  Outputs (to an .edge file) a list of edges of the triangulation.\n");
1823   printf(
1824 "    -v  Outputs the Voronoi diagram associated with the triangulation.\n");
1825   printf(
1826 "        Does not attempt to detect degeneracies, so some Voronoi vertices\n");
1827   printf(
1828 "        may be duplicated.  See the discussion of Voronoi diagrams below.\n");
1829   printf(
1830 "    -n  Outputs (to a .neigh file) a list of triangles neighboring each\n");
1831   printf("        triangle.\n");
1832   printf(
1833 "    -g  Outputs the mesh to an Object File Format (.off) file, suitable for\n"
1834 );
1835   printf("        viewing with the Geometry Center's Geomview package.\n");
1836   printf(
1837 "    -B  No boundary markers in the output .node, .poly, and .edge output\n");
1838   printf(
1839 "        files.  See the detailed discussion of boundary markers below.\n");
1840   printf(
1841 "    -P  No output .poly file.  Saves disk space, but you lose the ability\n");
1842   printf(
1843 "        to maintain constraining segments on later refinements of the mesh.\n"
1844 );
1845   printf("    -N  No output .node file.\n");
1846   printf("    -E  No output .ele file.\n");
1847   printf(
1848 "    -I  No iteration numbers.  Suppresses the output of .node and .poly\n");
1849   printf(
1850 "        files, so your input files won't be overwritten.  (If your input is\n"
1851 );
1852   printf(
1853 "        a .poly file only, a .node file is written.)  Cannot be used with\n");
1854   printf(
1855 "        the -r switch, because that would overwrite your input .ele file.\n");
1856   printf(
1857 "        Shouldn't be used with the -q, -a, -u, or -s switch if you are\n");
1858   printf(
1859 "        using a .node file for input, because no .node file is written, so\n"
1860 );
1861   printf("        there is no record of any added Steiner points.\n");
1862   printf("    -O  No holes.  Ignores the holes in the .poly file.\n");
1863   printf(
1864 "    -X  No exact arithmetic.  Normally, Triangle uses exact floating-point\n"
1865 );
1866   printf(
1867 "        arithmetic for certain tests if it thinks the inexact tests are not\n"
1868 );
1869   printf(
1870 "        accurate enough.  Exact arithmetic ensures the robustness of the\n");
1871   printf(
1872 "        triangulation algorithms, despite floating-point roundoff error.\n");
1873   printf(
1874 "        Disabling exact arithmetic with the -X switch causes a small\n");
1875   printf(
1876 "        improvement in speed and creates the possibility that Triangle will\n"
1877 );
1878   printf("        fail to produce a valid mesh.  Not recommended.\n");
1879   printf(
1880 "    -z  Numbers all items starting from zero (rather than one).  Note that\n"
1881 );
1882   printf(
1883 "        this switch is normally overridden by the value used to number the\n"
1884 );
1885   printf(
1886 "        first vertex of the input .node or .poly file.  However, this\n");
1887   printf(
1888 "        switch is useful when calling Triangle from another program.\n");
1889   printf(
1890 "    -o2 Generates second-order subparametric elements with six nodes each.\n"
1891 );
1892   printf(
1893 "    -Y  No new vertices on the boundary.  This switch is useful when the\n");
1894   printf(
1895 "        mesh boundary must be preserved so that it conforms to some\n");
1896   printf(
1897 "        adjacent mesh.  Be forewarned that you will probably sacrifice much\n"
1898 );
1899   printf(
1900 "        of the quality of the mesh; Triangle will try, but the resulting\n");
1901   printf(
1902 "        mesh may contain poorly shaped triangles.  Works well if all the\n");
1903   printf(
1904 "        boundary vertices are closely spaced.  Specify this switch twice\n");
1905   printf(
1906 "        (`-YY') to prevent all segment splitting, including internal\n");
1907   printf("        boundaries.\n");
1908   printf(
1909 "    -S  Specifies the maximum number of Steiner points (vertices that are\n");
1910   printf(
1911 "        not in the input, but are added to meet the constraints on minimum\n"
1912 );
1913   printf(
1914 "        angle and maximum area).  The default is to allow an unlimited\n");
1915   printf(
1916 "        number.  If you specify this switch with no number after it,\n");
1917   printf(
1918 "        the limit is set to zero.  Triangle always adds vertices at segment\n"
1919 );
1920   printf(
1921 "        intersections, even if it needs to use more vertices than the limit\n"
1922 );
1923   printf(
1924 "        you set.  When Triangle inserts segments by splitting (-s), it\n");
1925   printf(
1926 "        always adds enough vertices to ensure that all the segments of the\n"
1927 );
1928   printf("        PLSG are recovered, ignoring the limit if necessary.\n");
1929   printf(
1930 "    -i  Uses an incremental rather than a divide-and-conquer algorithm to\n");
1931   printf(
1932 "        construct a Delaunay triangulation.  Try it if the divide-and-\n");
1933   printf("        conquer algorithm fails.\n");
1934   printf(
1935 "    -F  Uses Steven Fortune's sweepline algorithm to construct a Delaunay\n");
1936   printf(
1937 "        triangulation.  Warning:  does not use exact arithmetic for all\n");
1938   printf("        calculations.  An exact result is not guaranteed.\n");
1939   printf(
1940 "    -l  Uses only vertical cuts in the divide-and-conquer algorithm.  By\n");
1941   printf(
1942 "        default, Triangle alternates between vertical and horizontal cuts,\n"
1943 );
1944   printf(
1945 "        which usually improve the speed except with vertex sets that are\n");
1946   printf(
1947 "        small or short and wide.  This switch is primarily of theoretical\n");
1948   printf("        interest.\n");
1949   printf(
1950 "    -s  Specifies that segments should be forced into the triangulation by\n"
1951 );
1952   printf(
1953 "        recursively splitting them at their midpoints, rather than by\n");
1954   printf(
1955 "        generating a constrained Delaunay triangulation.  Segment splitting\n"
1956 );
1957   printf(
1958 "        is true to Ruppert's original algorithm, but can create needlessly\n"
1959 );
1960   printf(
1961 "        small triangles.  This switch is primarily of theoretical interest.\n"
1962 );
1963   printf(
1964 "    -C  Check the consistency of the final mesh.  Uses exact arithmetic for\n"
1965 );
1966   printf(
1967 "        checking, even if the -X switch is used.  Useful if you suspect\n");
1968   printf("        Triangle is buggy.\n");
1969   printf(
1970 "    -Q  Quiet:  Suppresses all explanation of what Triangle is doing,\n");
1971   printf("        unless an error occurs.\n");
1972   printf(
1973 "    -V  Verbose:  Gives detailed information about what Triangle is doing.\n"
1974 );
1975   printf(
1976 "        Add more `V's for increasing amount of detail.  `-V' is most\n");
1977   printf(
1978 "        useful; itgives information on algorithmic progress and much more\n");
1979   printf(
1980 "        detailed statistics.  `-VV' gives vertex-by-vertex details, and\n");
1981   printf(
1982 "        prints so much that Triangle runs much more slowly.  `-VVVV' gives\n"
1983 );
1984   printf("        information only a debugger could love.\n");
1985   printf("    -h  Help:  Displays these instructions.\n");
1986   printf("\n");
1987   printf("Definitions:\n");
1988   printf("\n");
1989   printf(
1990 "  A Delaunay triangulation of a vertex set is a triangulation whose\n");
1991   printf(
1992 "  vertices are the vertex set, that covers the convex hull of the vertex\n");
1993   printf(
1994 "  set.  A Delaunay triangulation has the property that no vertex lies\n");
1995   printf(
1996 "  inside the circumscribing circle (circle that passes through all three\n");
1997   printf("  vertices) of any triangle in the triangulation.\n\n");
1998   printf(
1999 "  A Voronoi diagram of a vertex set is a subdivision of the plane into\n");
2000   printf(
2001 "  polygonal cells (some of which may be unbounded, meaning infinitely\n");
2002   printf(
2003 "  large), where each cell is the set of points in the plane that are closer\n"
2004 );
2005   printf(
2006 "  to some input vertex than to any other input vertex.  The Voronoi diagram\n"
2007 );
2008   printf("  is a geometric dual of the Delaunay triangulation.\n\n");
2009   printf(
2010 "  A Planar Straight Line Graph (PSLG) is a set of vertices and segments.\n");
2011   printf(
2012 "  Segments are simply edges, whose endpoints are all vertices in the PSLG.\n"
2013 );
2014   printf(
2015 "  Segments may intersect each other only at their endpoints.  The file\n");
2016   printf("  format for PSLGs (.poly files) is described below.\n\n");
2017   printf(
2018 "  A constrained Delaunay triangulation (CDT) of a PSLG is similar to a\n");
2019   printf(
2020 "  Delaunay triangulation, but each PSLG segment is present as a single edge\n"
2021 );
2022   printf(
2023 "  of the CDT.  (A constrained Delaunay triangulation is not truly a\n");
2024   printf(
2025 "  Delaunay triangulation, because some of its triangles might not be\n");
2026   printf(
2027 "  Delaunay.)  By definition, a CDT does not have any vertices other than\n");
2028   printf(
2029 "  those specified in the input PSLG.  Depending on context, a CDT might\n");
2030   printf(
2031 "  cover the convex hull of the PSLG, or it might cover only a segment-\n");
2032   printf("  bounded region (e.g. a polygon).\n\n");
2033   printf(
2034 "  A conforming Delaunay triangulation of a PSLG is a triangulation in which\n"
2035 );
2036   printf(
2037 "  each triangle is truly Delaunay, and each PSLG segment is represented by\n"
2038 );
2039   printf(
2040 "  a linear contiguous sequence of edges of the triangulation.  New vertices\n"
2041 );
2042   printf(
2043 "  (not part of the PSLG) may appear, and each input segment may have been\n");
2044   printf(
2045 "  subdivided into shorter edges (subsegments) by these additional vertices.\n"
2046 );
2047   printf(
2048 "  The new vertices are frequently necessary to maintain the Delaunay\n");
2049   printf("  property while ensuring that every segment is represented.\n\n");
2050   printf(
2051 "  A conforming constrained Delaunay triangulation (CCDT) of a PSLG is a\n");
2052   printf(
2053 "  triangulation of a PSLG whose triangles are constrained Delaunay.  New\n");
2054   printf("  vertices may appear, and input segments may be subdivided into\n");
2055   printf(
2056 "  subsegments, but not to guarantee that segments are respected; rather, to\n"
2057 );
2058   printf(
2059 "  improve the quality of the triangles.  The high-quality meshes produced\n");
2060   printf(
2061 "  by the -q switch are usually CCDTs, but can be made conforming Delaunay\n");
2062   printf("  with the -D switch.\n\n");
2063   printf("File Formats:\n\n");
2064   printf(
2065 "  All files may contain comments prefixed by the character '#'.  Vertices,\n"
2066 );
2067   printf(
2068 "  triangles, edges, holes, and maximum area constraints must be numbered\n");
2069   printf(
2070 "  consecutively, starting from either 1 or 0.  Whichever you choose, all\n");
2071   printf(
2072 "  input files must be consistent; if the vertices are numbered from 1, so\n");
2073   printf(
2074 "  must be all other objects.  Triangle automatically detects your choice\n");
2075   printf(
2076 "  while reading the .node (or .poly) file.  (When calling Triangle from\n");
2077   printf(
2078 "  another program, use the -z switch if you wish to number objects from\n");
2079   printf("  zero.)  Examples of these file formats are given below.\n\n");
2080   printf("  .node files:\n");
2081   printf(
2082 "    First line:  <# of vertices> <dimension (must be 2)> <# of attributes>\n"
2083 );
2084   printf(
2085 "                                           <# of boundary markers (0 or 1)>\n"
2086 );
2087   printf(
2088 "    Remaining lines:  <vertex #> <x> <y> [attributes] [boundary marker]\n");
2089   printf("\n");
2090   printf(
2091 "    The attributes, which are typically floating-point values of physical\n");
2092   printf(
2093 "    quantities (such as mass or conductivity) associated with the nodes of\n"
2094 );
2095   printf(
2096 "    a finite element mesh, are copied unchanged to the output mesh.  If -q,\n"
2097 );
2098   printf(
2099 "    -a, -u, -D, or -s is selected, each new Steiner point added to the mesh\n"
2100 );
2101   printf("    has attributes assigned to it by linear interpolation.\n\n");
2102   printf(
2103 "    If the fourth entry of the first line is `1', the last column of the\n");
2104   printf(
2105 "    remainder of the file is assumed to contain boundary markers.  Boundary\n"
2106 );
2107   printf(
2108 "    markers are used to identify boundary vertices and vertices resting on\n"
2109 );
2110   printf(
2111 "    PSLG segments; a complete description appears in a section below.  The\n"
2112 );
2113   printf(
2114 "    .node file produced by Triangle contains boundary markers in the last\n");
2115   printf("    column unless they are suppressed by the -B switch.\n\n");
2116   printf("  .ele files:\n");
2117   printf(
2118 "    First line:  <# of triangles> <nodes per triangle> <# of attributes>\n");
2119   printf(
2120 "    Remaining lines:  <triangle #> <node> <node> <node> ... [attributes]\n");
2121   printf("\n");
2122   printf(
2123 "    Nodes are indices into the corresponding .node file.  The first three\n");
2124   printf(
2125 "    nodes are the corner vertices, and are listed in counterclockwise order\n"
2126 );
2127   printf(
2128 "    around each triangle.  (The remaining nodes, if any, depend on the type\n"
2129 );
2130   printf("    of finite element used.)\n\n");
2131   printf(
2132 "    The attributes are just like those of .node files.  Because there is no\n"
2133 );
2134   printf(
2135 "    simple mapping from input to output triangles, Triangle attempts to\n");
2136   printf(
2137 "    interpolate attributes, and may cause a lot of diffusion of attributes\n"
2138 );
2139   printf(
2140 "    among nearby triangles as the triangulation is refined.  Attributes do\n"
2141 );
2142   printf("    not diffuse across segments, so attributes used to identify\n");
2143   printf("    segment-bounded regions remain intact.\n\n");
2144   printf(
2145 "    In .ele files produced by Triangle, each triangular element has three\n");
2146   printf(
2147 "    nodes (vertices) unless the -o2 switch is used, in which case\n");
2148   printf(
2149 "    subparametric quadratic elements with six nodes each are generated.\n");
2150   printf(
2151 "    The first three nodes are the corners in counterclockwise order, and\n");
2152   printf(
2153 "    the fourth, fifth, and sixth nodes lie on the midpoints of the edges\n");
2154   printf(
2155 "    opposite the first, second, and third vertices, respectively.\n");
2156   printf("\n");
2157   printf("  .poly files:\n");
2158   printf(
2159 "    First line:  <# of vertices> <dimension (must be 2)> <# of attributes>\n"
2160 );
2161   printf(
2162 "                                           <# of boundary markers (0 or 1)>\n"
2163 );
2164   printf(
2165 "    Following lines:  <vertex #> <x> <y> [attributes] [boundary marker]\n");
2166   printf("    One line:  <# of segments> <# of boundary markers (0 or 1)>\n");
2167   printf(
2168 "    Following lines:  <segment #> <endpoint> <endpoint> [boundary marker]\n");
2169   printf("    One line:  <# of holes>\n");
2170   printf("    Following lines:  <hole #> <x> <y>\n");
2171   printf(
2172 "    Optional line:  <# of regional attributes and/or area constraints>\n");
2173   printf(
2174 "    Optional following lines:  <region #> <x> <y> <attribute> <max area>\n");
2175   printf("\n");
2176   printf(
2177 "    A .poly file represents a PSLG, as well as some additional information.\n"
2178 );
2179   printf(
2180 "    The first section lists all the vertices, and is identical to the\n");
2181   printf(
2182 "    format of .node files.  <# of vertices> may be set to zero to indicate\n"
2183 );
2184   printf(
2185 "    that the vertices are listed in a separate .node file; .poly files\n");
2186   printf(
2187 "    produced by Triangle always have this format.  A vertex set represented\n"
2188 );
2189   printf(
2190 "    this way has the advantage that it may easily be triangulated with or\n");
2191   printf(
2192 "    without segments (depending on whether the -p switch is invoked).\n");
2193   printf("\n");
2194   printf(
2195 "    The second section lists the segments.  Segments are edges whose\n");
2196   printf(
2197 "    presence in the triangulation is enforced.  (Depending on the choice of\n"
2198 );
2199   printf(
2200 "    switches, segment might be subdivided into smaller edges).  Each\n");
2201   printf(
2202 "    segment is specified by listing the indices of its two endpoints.  This\n"
2203 );
2204   printf(
2205 "    means that you must include its endpoints in the vertex list.  Each\n");
2206   printf("    segment, like each point, may have a boundary marker.\n\n");
2207   printf(
2208 "    If -q, -a, -u, and -s are not selected, Triangle produces a constrained\n"
2209 );
2210   printf(
2211 "    Delaunay triangulation (CDT), in which each segment appears as a single\n"
2212 );
2213   printf(
2214 "    edge in the triangulation.  If -q, -a, -u, or -s is selected, Triangle\n"
2215 );
2216   printf(
2217 "    produces a conforming constrained Delaunay triangulation (CCDT), in\n");
2218   printf(
2219 "    which segments may be subdivided into smaller edges.  If -D is\n");
2220   printf(
2221 "    selected, Triangle produces a conforming Delaunay triangulation, so\n");
2222   printf(
2223 "    that every triangle is Delaunay, and not just constrained Delaunay.\n");
2224   printf("\n");
2225   printf(
2226 "    The third section lists holes (and concavities, if -c is selected) in\n");
2227   printf(
2228 "    the triangulation.  Holes are specified by identifying a point inside\n");
2229   printf(
2230 "    each hole.  After the triangulation is formed, Triangle creates holes\n");
2231   printf(
2232 "    by eating triangles, spreading out from each hole point until its\n");
2233   printf(
2234 "    progress is blocked by segments in the PSLG.  You must be careful to\n");
2235   printf(
2236 "    enclose each hole in segments, or your whole triangulation might be\n");
2237   printf(
2238 "    eaten away.  If the two triangles abutting a segment are eaten, the\n");
2239   printf(
2240 "    segment itself is also eaten.  Do not place a hole directly on a\n");
2241   printf("    segment; if you do, Triangle chooses one side of the segment\n");
2242   printf("    arbitrarily.\n\n");
2243   printf(
2244 "    The optional fourth section lists regional attributes (to be assigned\n");
2245   printf(
2246 "    to all triangles in a region) and regional constraints on the maximum\n");
2247   printf(
2248 "    triangle area.  Triangle reads this section only if the -A switch is\n");
2249   printf(
2250 "    used or the -a switch is used without a number following it, and the -r\n"
2251 );
2252   printf(
2253 "    switch is not used.  Regional attributes and area constraints are\n");
2254   printf(
2255 "    propagated in the same manner as holes:  you specify a point for each\n");
2256   printf(
2257 "    attribute and/or constraint, and the attribute and/or constraint\n");
2258   printf(
2259 "    affects the whole region (bounded by segments) containing the point.\n");
2260   printf(
2261 "    If two values are written on a line after the x and y coordinate, the\n");
2262   printf(
2263 "    first such value is assumed to be a regional attribute (but is only\n");
2264   printf(
2265 "    applied if the -A switch is selected), and the second value is assumed\n"
2266 );
2267   printf(
2268 "    to be a regional area constraint (but is only applied if the -a switch\n"
2269 );
2270   printf(
2271 "    is selected).  You may specify just one value after the coordinates,\n");
2272   printf(
2273 "    which can serve as both an attribute and an area constraint, depending\n"
2274 );
2275   printf(
2276 "    on the choice of switches.  If you are using the -A and -a switches\n");
2277   printf(
2278 "    simultaneously and wish to assign an attribute to some region without\n");
2279   printf("    imposing an area constraint, use a negative maximum area.\n\n");
2280   printf(
2281 "    When a triangulation is created from a .poly file, you must either\n");
2282   printf(
2283 "    enclose the entire region to be triangulated in PSLG segments, or\n");
2284   printf(
2285 "    use the -c switch, which automatically creates extra segments that\n");
2286   printf(
2287 "    enclose the convex hull of the PSLG.  If you do not use the -c switch,\n"
2288 );
2289   printf(
2290 "    Triangle eats all triangles that are not enclosed by segments; if you\n");
2291   printf(
2292 "    are not careful, your whole triangulation may be eaten away.  If you do\n"
2293 );
2294   printf(
2295 "    use the -c switch, you can still produce concavities by the appropriate\n"
2296 );
2297   printf(
2298 "    placement of holes just inside the boundary of the convex hull.\n");
2299   printf("\n");
2300   printf(
2301 "    An ideal PSLG has no intersecting segments, nor any vertices that lie\n");
2302   printf(
2303 "    upon segments (except, of course, the endpoints of each segment).  You\n"
2304 );
2305   printf(
2306 "    aren't required to make your .poly files ideal, but you should be aware\n"
2307 );
2308   printf(
2309 "    of what can go wrong.  Segment intersections are relatively safe--\n");
2310   printf(
2311 "    Triangle calculates the intersection points for you and adds them to\n");
2312   printf(
2313 "    the triangulation--as long as your machine's floating-point precision\n");
2314   printf(
2315 "    doesn't become a problem.  You are tempting the fates if you have three\n"
2316 );
2317   printf(
2318 "    segments that cross at the same location, and expect Triangle to figure\n"
2319 );
2320   printf(
2321 "    out where the intersection point is.  Thanks to floating-point roundoff\n"
2322 );
2323   printf(
2324 "    error, Triangle will probably decide that the three segments intersect\n"
2325 );
2326   printf(
2327 "    at three different points, and you will find a minuscule triangle in\n");
2328   printf(
2329 "    your output--unless Triangle tries to refine the tiny triangle, uses\n");
2330   printf(
2331 "    up the last bit of machine precision, and fails to terminate at all.\n");
2332   printf(
2333 "    You're better off putting the intersection point in the input files,\n");
2334   printf(
2335 "    and manually breaking up each segment into two.  Similarly, if you\n");
2336   printf(
2337 "    place a vertex at the middle of a segment, and hope that Triangle will\n"
2338 );
2339   printf(
2340 "    break up the segment at that vertex, you might get lucky.  On the other\n"
2341 );
2342   printf(
2343 "    hand, Triangle might decide that the vertex doesn't lie precisely on\n");
2344   printf(
2345 "    the segment, and you'll have a needle-sharp triangle in your output--or\n"
2346 );
2347   printf("    a lot of tiny triangles if you're generating a quality mesh.\n");
2348   printf("\n");
2349   printf(
2350 "    When Triangle reads a .poly file, it also writes a .poly file, which\n");
2351   printf(
2352 "    includes all the subsegments--the edges that are parts of input\n");
2353   printf(
2354 "    segments.  If the -c switch is used, the output .poly file also\n");
2355   printf(
2356 "    includes all of the edges on the convex hull.  Hence, the output .poly\n"
2357 );
2358   printf(
2359 "    file is useful for finding edges associated with input segments and for\n"
2360 );
2361   printf(
2362 "    setting boundary conditions in finite element simulations.  Moreover,\n");
2363   printf(
2364 "    you will need the output .poly file if you plan to refine the output\n");
2365   printf(
2366 "    mesh, and don't want segments to be missing in later triangulations.\n");
2367   printf("\n");
2368   printf("  .area files:\n");
2369   printf("    First line:  <# of triangles>\n");
2370   printf("    Following lines:  <triangle #> <maximum area>\n");
2371   printf("\n");
2372   printf(
2373 "    An .area file associates with each triangle a maximum area that is used\n"
2374 );
2375   printf(
2376 "    for mesh refinement.  As with other file formats, every triangle must\n");
2377   printf(
2378 "    be represented, and the triangles must be numbered consecutively.  A\n");
2379   printf(
2380 "    triangle may be left unconstrained by assigning it a negative maximum\n");
2381   printf("    area.\n\n");
2382   printf("  .edge files:\n");
2383   printf("    First line:  <# of edges> <# of boundary markers (0 or 1)>\n");
2384   printf(
2385 "    Following lines:  <edge #> <endpoint> <endpoint> [boundary marker]\n");
2386   printf("\n");
2387   printf(
2388 "    Endpoints are indices into the corresponding .node file.  Triangle can\n"
2389 );
2390   printf(
2391 "    produce .edge files (use the -e switch), but cannot read them.  The\n");
2392   printf(
2393 "    optional column of boundary markers is suppressed by the -B switch.\n");
2394   printf("\n");
2395   printf(
2396 "    In Voronoi diagrams, one also finds a special kind of edge that is an\n");
2397   printf(
2398 "    infinite ray with only one endpoint.  For these edges, a different\n");
2399   printf("    format is used:\n\n");
2400   printf("        <edge #> <endpoint> -1 <direction x> <direction y>\n\n");
2401   printf(
2402 "    The `direction' is a floating-point vector that indicates the direction\n"
2403 );
2404   printf("    of the infinite ray.\n\n");
2405   printf("  .neigh files:\n");
2406   printf(
2407 "    First line:  <# of triangles> <# of neighbors per triangle (always 3)>\n"
2408 );
2409   printf(
2410 "    Following lines:  <triangle #> <neighbor> <neighbor> <neighbor>\n");
2411   printf("\n");
2412   printf(
2413 "    Neighbors are indices into the corresponding .ele file.  An index of -1\n"
2414 );
2415   printf(
2416 "    indicates no neighbor (because the triangle is on an exterior\n");
2417   printf(
2418 "    boundary).  The first neighbor of triangle i is opposite the first\n");
2419   printf("    corner of triangle i, and so on.\n\n");
2420   printf(
2421 "    Triangle can produce .neigh files (use the -n switch), but cannot read\n"
2422 );
2423   printf("    them.\n\n");
2424   printf("Boundary Markers:\n\n");
2425   printf(
2426 "  Boundary markers are tags used mainly to identify which output vertices\n");
2427   printf(
2428 "  and edges are associated with which PSLG segment, and to identify which\n");
2429   printf(
2430 "  vertices and edges occur on a boundary of the triangulation.  A common\n");
2431   printf(
2432 "  use is to determine where boundary conditions should be applied to a\n");
2433   printf(
2434 "  finite element mesh.  You can prevent boundary markers from being written\n"
2435 );
2436   printf("  into files produced by Triangle by using the -B switch.\n\n");
2437   printf(
2438 "  The boundary marker associated with each segment in an output .poly file\n"
2439 );
2440   printf("  and each edge in an output .edge file is chosen as follows:\n");
2441   printf(
2442 "    - If an output edge is part or all of a PSLG segment with a nonzero\n");
2443   printf(
2444 "      boundary marker, then the edge is assigned the same marker.\n");
2445   printf(
2446 "    - Otherwise, if the edge lies on a boundary of the triangulation\n");
2447   printf(
2448 "      (even the boundary of a hole), then the edge is assigned the marker\n");
2449   printf("      one (1).\n");
2450   printf("    - Otherwise, the edge is assigned the marker zero (0).\n");
2451   printf(
2452 "  The boundary marker associated with each vertex in an output .node file\n");
2453   printf("  is chosen as follows:\n");
2454   printf(
2455 "    - If a vertex is assigned a nonzero boundary marker in the input file,\n"
2456 );
2457   printf(
2458 "      then it is assigned the same marker in the output .node file.\n");
2459   printf(
2460 "    - Otherwise, if the vertex lies on a PSLG segment (even if it is an\n");
2461   printf(
2462 "      endpoint of the segment) with a nonzero boundary marker, then the\n");
2463   printf(
2464 "      vertex is assigned the same marker.  If the vertex lies on several\n");
2465   printf("      such segments, one of the markers is chosen arbitrarily.\n");
2466   printf(
2467 "    - Otherwise, if the vertex occurs on a boundary of the triangulation,\n");
2468   printf("      then the vertex is assigned the marker one (1).\n");
2469   printf("    - Otherwise, the vertex is assigned the marker zero (0).\n");
2470   printf("\n");
2471   printf(
2472 "  If you want Triangle to determine for you which vertices and edges are on\n"
2473 );
2474   printf(
2475 "  the boundary, assign them the boundary marker zero (or use no markers at\n"
2476 );
2477   printf(
2478 "  all) in your input files.  In the output files, all boundary vertices,\n");
2479   printf("  edges, and segments will be assigned the value one.\n\n");
2480   printf("Triangulation Iteration Numbers:\n\n");
2481   printf(
2482 "  Because Triangle can read and refine its own triangulations, input\n");
2483   printf(
2484 "  and output files have iteration numbers.  For instance, Triangle might\n");
2485   printf(
2486 "  read the files mesh.3.node, mesh.3.ele, and mesh.3.poly, refine the\n");
2487   printf(
2488 "  triangulation, and output the files mesh.4.node, mesh.4.ele, and\n");
2489   printf("  mesh.4.poly.  Files with no iteration number are treated as if\n");
2490   printf(
2491 "  their iteration number is zero; hence, Triangle might read the file\n");
2492   printf(
2493 "  points.node, triangulate it, and produce the files points.1.node and\n");
2494   printf("  points.1.ele.\n\n");
2495   printf(
2496 "  Iteration numbers allow you to create a sequence of successively finer\n");
2497   printf(
2498 "  meshes suitable for multigrid methods.  They also allow you to produce a\n"
2499 );
2500   printf(
2501 "  sequence of meshes using error estimate-driven mesh refinement.\n");
2502   printf("\n");
2503   printf(
2504 "  If you're not using refinement or quality meshing, and you don't like\n");
2505   printf(
2506 "  iteration numbers, use the -I switch to disable them.  This switch also\n");
2507   printf(
2508 "  disables output of .node and .poly files to prevent your input files from\n"
2509 );
2510   printf(
2511 "  being overwritten.  (If the input is a .poly file that contains its own\n");
2512   printf(
2513 "  points, a .node file is written.  This can be quite convenient for\n");
2514   printf("  computing CDTs or quality meshes.)\n\n");
2515   printf("Examples of How to Use Triangle:\n\n");
2516   printf(
2517 "  `triangle dots' reads vertices from dots.node, and writes their Delaunay\n"
2518 );
2519   printf(
2520 "  triangulation to dots.1.node and dots.1.ele.  (dots.1.node is identical\n");
2521   printf(
2522 "  to dots.node.)  `triangle -I dots' writes the triangulation to dots.ele\n");
2523   printf(
2524 "  instead.  (No additional .node file is needed, so none is written.)\n");
2525   printf("\n");
2526   printf(
2527 "  `triangle -pe object.1' reads a PSLG from object.1.poly (and possibly\n");
2528   printf(
2529 "  object.1.node, if the vertices are omitted from object.1.poly) and writes\n"
2530 );
2531   printf(
2532 "  its constrained Delaunay triangulation to object.2.node and object.2.ele.\n"
2533 );
2534   printf(
2535 "  The segments are copied to object.2.poly, and all edges are written to\n");
2536   printf("  object.2.edge.\n\n");
2537   printf(
2538 "  `triangle -pq31.5a.1 object' reads a PSLG from object.poly (and possibly\n"
2539 );
2540   printf(
2541 "  object.node), generates a mesh whose angles are all between 31.5 and 117\n"
2542 );
2543   printf(
2544 "  degrees and whose triangles all have areas of 0.1 or less, and writes the\n"
2545 );
2546   printf(
2547 "  mesh to object.1.node and object.1.ele.  Each segment may be broken up\n");
2548   printf("  into multiple subsegments; these are written to object.1.poly.\n");
2549   printf("\n");
2550   printf(
2551 "  Here is a sample file `box.poly' describing a square with a square hole:\n"
2552 );
2553   printf("\n");
2554   printf(
2555 "    # A box with eight vertices in 2D, no attributes, one boundary marker.\n"
2556 );
2557   printf("    8 2 0 1\n");
2558   printf("     # Outer box has these vertices:\n");
2559   printf("     1   0 0   0\n");
2560   printf("     2   0 3   0\n");
2561   printf("     3   3 0   0\n");
2562   printf("     4   3 3   33     # A special marker for this vertex.\n");
2563   printf("     # Inner square has these vertices:\n");
2564   printf("     5   1 1   0\n");
2565   printf("     6   1 2   0\n");
2566   printf("     7   2 1   0\n");
2567   printf("     8   2 2   0\n");
2568   printf("    # Five segments with boundary markers.\n");
2569   printf("    5 1\n");
2570   printf("     1   1 2   5      # Left side of outer box.\n");
2571   printf("     # Square hole has these segments:\n");
2572   printf("     2   5 7   0\n");
2573   printf("     3   7 8   0\n");
2574   printf("     4   8 6   10\n");
2575   printf("     5   6 5   0\n");
2576   printf("    # One hole in the middle of the inner square.\n");
2577   printf("    1\n");
2578   printf("     1   1.5 1.5\n");
2579   printf("\n");
2580   printf(
2581 "  Note that some segments are missing from the outer square, so you must\n");
2582   printf(
2583 "  use the `-c' switch.  After `triangle -pqc box.poly', here is the output\n"
2584 );
2585   printf(
2586 "  file `box.1.node', with twelve vertices.  The last four vertices were\n");
2587   printf(
2588 "  added to meet the angle constraint.  Vertices 1, 2, and 9 have markers\n");
2589   printf(
2590 "  from segment 1.  Vertices 6 and 8 have markers from segment 4.  All the\n");
2591   printf(
2592 "  other vertices but 4 have been marked to indicate that they lie on a\n");
2593   printf("  boundary.\n\n");
2594   printf("    12  2  0  1\n");
2595   printf("       1    0   0      5\n");
2596   printf("       2    0   3      5\n");
2597   printf("       3    3   0      1\n");
2598   printf("       4    3   3     33\n");
2599   printf("       5    1   1      1\n");
2600   printf("       6    1   2     10\n");
2601   printf("       7    2   1      1\n");
2602   printf("       8    2   2     10\n");
2603   printf("       9    0   1.5    5\n");
2604   printf("      10    1.5   0    1\n");
2605   printf("      11    3   1.5    1\n");
2606   printf("      12    1.5   3    1\n");
2607   printf("    # Generated by triangle -pqc box.poly\n");
2608   printf("\n");
2609   printf("  Here is the output file `box.1.ele', with twelve triangles.\n");
2610   printf("\n");
2611   printf("    12  3  0\n");
2612   printf("       1     5   6   9\n");
2613   printf("       2    10   3   7\n");
2614   printf("       3     6   8  12\n");
2615   printf("       4     9   1   5\n");
2616   printf("       5     6   2   9\n");
2617   printf("       6     7   3  11\n");
2618   printf("       7    11   4   8\n");
2619   printf("       8     7   5  10\n");
2620   printf("       9    12   2   6\n");
2621   printf("      10     8   7  11\n");
2622   printf("      11     5   1  10\n");
2623   printf("      12     8   4  12\n");
2624   printf("    # Generated by triangle -pqc box.poly\n\n");
2625   printf(
2626 "  Here is the output file `box.1.poly'.  Note that segments have been added\n"
2627 );
2628   printf(
2629 "  to represent the convex hull, and some segments have been subdivided by\n");
2630   printf(
2631 "  newly added vertices.  Note also that <# of vertices> is set to zero to\n");
2632   printf("  indicate that the vertices should be read from the .node file.\n");
2633   printf("\n");
2634   printf("    0  2  0  1\n");
2635   printf("    12  1\n");
2636   printf("       1     1   9     5\n");
2637   printf("       2     5   7     1\n");
2638   printf("       3     8   7     1\n");
2639   printf("       4     6   8    10\n");
2640   printf("       5     5   6     1\n");
2641   printf("       6     3  10     1\n");
2642   printf("       7     4  11     1\n");
2643   printf("       8     2  12     1\n");
2644   printf("       9     9   2     5\n");
2645   printf("      10    10   1     1\n");
2646   printf("      11    11   3     1\n");
2647   printf("      12    12   4     1\n");
2648   printf("    1\n");
2649   printf("       1   1.5 1.5\n");
2650   printf("    # Generated by triangle -pqc box.poly\n");
2651   printf("\n");
2652   printf("Refinement and Area Constraints:\n");
2653   printf("\n");
2654   printf(
2655 "  The -r switch causes a mesh (.node and .ele files) to be read and\n");
2656   printf(
2657 "  refined.  If the -p switch is also used, a .poly file is read and used to\n"
2658 );
2659   printf(
2660 "  specify edges that are constrained and cannot be eliminated (although\n");
2661   printf(
2662 "  they can be subdivided into smaller edges) by the refinement process.\n");
2663   printf("\n");
2664   printf(
2665 "  When you refine a mesh, you generally want to impose tighter constraints.\n"
2666 );
2667   printf(
2668 "  One way to accomplish this is to use -q with a larger angle, or -a\n");
2669   printf(
2670 "  followed by a smaller area than you used to generate the mesh you are\n");
2671   printf(
2672 "  refining.  Another way to do this is to create an .area file, which\n");
2673   printf(
2674 "  specifies a maximum area for each triangle, and use the -a switch\n");
2675   printf(
2676 "  (without a number following).  Each triangle's area constraint is applied\n"
2677 );
2678   printf(
2679 "  to that triangle.  Area constraints tend to diffuse as the mesh is\n");
2680   printf(
2681 "  refined, so if there are large variations in area constraint between\n");
2682   printf(
2683 "  adjacent triangles, you may not get the results you want.  In that case,\n"
2684 );
2685   printf(
2686 "  consider instead using the -u switch and writing a C procedure that\n");
2687   printf("  determines which triangles are too large.\n\n");
2688   printf(
2689 "  If you are refining a mesh composed of linear (three-node) elements, the\n"
2690 );
2691   printf(
2692 "  output mesh contains all the nodes present in the input mesh, in the same\n"
2693 );
2694   printf(
2695 "  order, with new nodes added at the end of the .node file.  However, the\n");
2696   printf(
2697 "  refinement is not hierarchical: there is no guarantee that each output\n");
2698   printf(
2699 "  element is contained in a single input element.  Often, an output element\n"
2700 );
2701   printf(
2702 "  can overlap two or three input elements, and some input edges are not\n");
2703   printf(
2704 "  present in the output mesh.  Hence, a sequence of refined meshes forms a\n"
2705 );
2706   printf(
2707 "  hierarchy of nodes, but not a hierarchy of elements.  If you refine a\n");
2708   printf(
2709 "  mesh of higher-order elements, the hierarchical property applies only to\n"
2710 );
2711   printf(
2712 "  the nodes at the corners of an element; the midpoint nodes on each edge\n");
2713   printf("  are discarded before the mesh is refined.\n\n");
2714   printf(
2715 "  Maximum area constraints in .poly files operate differently from those in\n"
2716 );
2717   printf(
2718 "  .area files.  A maximum area in a .poly file applies to the whole\n");
2719   printf(
2720 "  (segment-bounded) region in which a point falls, whereas a maximum area\n");
2721   printf(
2722 "  in an .area file applies to only one triangle.  Area constraints in .poly\n"
2723 );
2724   printf(
2725 "  files are used only when a mesh is first generated, whereas area\n");
2726   printf(
2727 "  constraints in .area files are used only to refine an existing mesh, and\n"
2728 );
2729   printf(
2730 "  are typically based on a posteriori error estimates resulting from a\n");
2731   printf("  finite element simulation on that mesh.\n\n");
2732   printf(
2733 "  `triangle -rq25 object.1' reads object.1.node and object.1.ele, then\n");
2734   printf(
2735 "  refines the triangulation to enforce a 25 degree minimum angle, and then\n"
2736 );
2737   printf(
2738 "  writes the refined triangulation to object.2.node and object.2.ele.\n");
2739   printf("\n");
2740   printf(
2741 "  `triangle -rpaa6.2 z.3' reads z.3.node, z.3.ele, z.3.poly, and z.3.area.\n"
2742 );
2743   printf(
2744 "  After reconstructing the mesh and its subsegments, Triangle refines the\n");
2745   printf(
2746 "  mesh so that no triangle has area greater than 6.2, and furthermore the\n");
2747   printf(
2748 "  triangles satisfy the maximum area constraints in z.3.area.  No angle\n");
2749   printf(
2750 "  bound is imposed at all.  The output is written to z.4.node, z.4.ele, and\n"
2751 );
2752   printf("  z.4.poly.\n\n");
2753   printf(
2754 "  The sequence `triangle -qa1 x', `triangle -rqa.3 x.1', `triangle -rqa.1\n");
2755   printf(
2756 "  x.2' creates a sequence of successively finer meshes x.1, x.2, and x.3,\n");
2757   printf("  suitable for multigrid.\n\n");
2758   printf("Convex Hulls and Mesh Boundaries:\n\n");
2759   printf(
2760 "  If the input is a vertex set (not a PSLG), Triangle produces its convex\n");
2761   printf(
2762 "  hull as a by-product in the output .poly file if you use the -c switch.\n");
2763   printf(
2764 "  There are faster algorithms for finding a two-dimensional convex hull\n");
2765   printf("  than triangulation, of course, but this one comes for free.\n\n");
2766   printf(
2767 "  If the input is an unconstrained mesh (you are using the -r switch but\n");
2768   printf(
2769 "  not the -p switch), Triangle produces a list of its boundary edges\n");
2770   printf(
2771 "  (including hole boundaries) as a by-product when you use the -c switch.\n");
2772   printf(
2773 "  If you also use the -p switch, the output .poly file contains all the\n");
2774   printf("  segments from the input .poly file as well.\n\n");
2775   printf("Voronoi Diagrams:\n\n");
2776   printf(
2777 "  The -v switch produces a Voronoi diagram, in files suffixed .v.node and\n");
2778   printf(
2779 "  .v.edge.  For example, `triangle -v points' reads points.node, produces\n");
2780   printf(
2781 "  its Delaunay triangulation in points.1.node and points.1.ele, and\n");
2782   printf(
2783 "  produces its Voronoi diagram in points.1.v.node and points.1.v.edge.  The\n"
2784 );
2785   printf(
2786 "  .v.node file contains a list of all Voronoi vertices, and the .v.edge\n");
2787   printf(
2788 "  file contains a list of all Voronoi edges, some of which may be infinite\n"
2789 );
2790   printf(
2791 "  rays.  (The choice of filenames makes it easy to run the set of Voronoi\n");
2792   printf("  vertices through Triangle, if so desired.)\n\n");
2793   printf(
2794 "  This implementation does not use exact arithmetic to compute the Voronoi\n"
2795 );
2796   printf(
2797 "  vertices, and does not check whether neighboring vertices are identical.\n"
2798 );
2799   printf(
2800 "  Be forewarned that if the Delaunay triangulation is degenerate or\n");
2801   printf(
2802 "  near-degenerate, the Voronoi diagram may have duplicate vertices or\n");
2803   printf("  crossing edges.\n\n");
2804   printf(
2805 "  The result is a valid Voronoi diagram only if Triangle's output is a true\n"
2806 );
2807   printf(
2808 "  Delaunay triangulation.  The Voronoi output is usually meaningless (and\n");
2809   printf(
2810 "  may contain crossing edges and other pathology) if the output is a CDT or\n"
2811 );
2812   printf(
2813 "  CCDT, or if it has holes or concavities.  If the triangulated domain is\n");
2814   printf(
2815 "  convex and has no holes, you can use -D switch to force Triangle to\n");
2816   printf(
2817 "  construct a conforming Delaunay triangulation instead of a CCDT, so the\n");
2818   printf("  Voronoi diagram will be valid.\n\n");
2819   printf("Mesh Topology:\n\n");
2820   printf(
2821 "  You may wish to know which triangles are adjacent to a certain Delaunay\n");
2822   printf(
2823 "  edge in an .edge file, which Voronoi cells are adjacent to a certain\n");
2824   printf(
2825 "  Voronoi edge in a .v.edge file, or which Voronoi cells are adjacent to\n");
2826   printf(
2827 "  each other.  All of this information can be found by cross-referencing\n");
2828   printf(
2829 "  output files with the recollection that the Delaunay triangulation and\n");
2830   printf("  the Voronoi diagram are planar duals.\n\n");
2831   printf(
2832 "  Specifically, edge i of an .edge file is the dual of Voronoi edge i of\n");
2833   printf(
2834 "  the corresponding .v.edge file, and is rotated 90 degrees counterclock-\n");
2835   printf(
2836 "  wise from the Voronoi edge.  Triangle j of an .ele file is the dual of\n");
2837   printf(
2838 "  vertex j of the corresponding .v.node file.  Voronoi cell k is the dual\n");
2839   printf("  of vertex k of the corresponding .node file.\n\n");
2840   printf(
2841 "  Hence, to find the triangles adjacent to a Delaunay edge, look at the\n");
2842   printf(
2843 "  vertices of the corresponding Voronoi edge.  If the endpoints of a\n");
2844   printf(
2845 "  Voronoi edge are Voronoi vertices 2 and 6 respectively, then triangles 2\n"
2846 );
2847   printf(
2848 "  and 6 adjoin the left and right sides of the corresponding Delaunay edge,\n"
2849 );
2850   printf(
2851 "  respectively.  To find the Voronoi cells adjacent to a Voronoi edge, look\n"
2852 );
2853   printf(
2854 "  at the endpoints of the corresponding Delaunay edge.  If the endpoints of\n"
2855 );
2856   printf(
2857 "  a Delaunay edge are input vertices 7 and 12, then Voronoi cells 7 and 12\n"
2858 );
2859   printf(
2860 "  adjoin the right and left sides of the corresponding Voronoi edge,\n");
2861   printf(
2862 "  respectively.  To find which Voronoi cells are adjacent to each other,\n");
2863   printf("  just read the list of Delaunay edges.\n\n");
2864   printf(
2865 "  Triangle does not write a list of the edges adjoining each Voronoi cell,\n"
2866 );
2867   printf(
2868 "  but you can reconstructed it straightforwardly.  For instance, to find\n");
2869   printf(
2870 "  all the edges of Voronoi cell 1, search the output .edge file for every\n");
2871   printf(
2872 "  edge that has input vertex 1 as an endpoint.  The corresponding dual\n");
2873   printf(
2874 "  edges in the output .v.edge file form the boundary of Voronoi cell 1.\n");
2875   printf("\n");
2876   printf(
2877 "  For each Voronoi vertex, the .neigh file gives a list of the three\n");
2878   printf(
2879 "  Voronoi vertices attached to it.  You might find this more convenient\n");
2880   printf("  than the .v.edge file.\n\n");
2881   printf("Quadratic Elements:\n\n");
2882   printf(
2883 "  Triangle generates meshes with subparametric quadratic elements if the\n");
2884   printf(
2885 "  -o2 switch is specified.  Quadratic elements have six nodes per element,\n"
2886 );
2887   printf(
2888 "  rather than three.  `Subparametric' means that the edges of the triangles\n"
2889 );
2890   printf(
2891 "  are always straight, so that subparametric quadratic elements are\n");
2892   printf(
2893 "  geometrically identical to linear elements, even though they can be used\n"
2894 );
2895   printf(
2896 "  with quadratic interpolating functions.  The three extra nodes of an\n");
2897   printf(
2898 "  element fall at the midpoints of the three edges, with the fourth, fifth,\n"
2899 );
2900   printf(
2901 "  and sixth nodes appearing opposite the first, second, and third corners\n");
2902   printf("  respectively.\n\n");
2903   printf("Domains with Small Angles:\n\n");
2904   printf(
2905 "  If two input segments adjoin each other at a small angle, clearly the -q\n"
2906 );
2907   printf(
2908 "  switch cannot remove the small angle.  Moreover, Triangle may have no\n");
2909   printf(
2910 "  choice but to generate additional triangles whose smallest angles are\n");
2911   printf(
2912 "  smaller than the specified bound.  However, these triangles only appear\n");
2913   printf(
2914 "  between input segments separated by small angles.  Moreover, if you\n");
2915   printf(
2916 "  request a minimum angle of theta degrees, Triangle will generally produce\n"
2917 );
2918   printf(
2919 "  no angle larger than 180 - 2 theta, even if it is forced to compromise on\n"
2920 );
2921   printf("  the minimum angle.\n\n");
2922   printf("Statistics:\n\n");
2923   printf(
2924 "  After generating a mesh, Triangle prints a count of entities in the\n");
2925   printf(
2926 "  output mesh, including the number of vertices, triangles, edges, exterior\n"
2927 );
2928   printf(
2929 "  boundary edges (i.e. subsegments on the boundary of the triangulation,\n");
2930   printf(
2931 "  including hole boundaries), interior boundary edges (i.e. subsegments of\n"
2932 );
2933   printf(
2934 "  input segments not on the boundary), and total subsegments.  If you've\n");
2935   printf(
2936 "  forgotten the statistics for an existing mesh, run Triangle on that mesh\n"
2937 );
2938   printf(
2939 "  with the -rNEP switches to read the mesh and print the statistics without\n"
2940 );
2941   printf(
2942 "  writing any files.  Use -rpNEP if you've got a .poly file for the mesh.\n");
2943   printf("\n");
2944   printf(
2945 "  The -V switch produces extended statistics, including a rough estimate\n");
2946   printf(
2947 "  of memory use, the number of calls to geometric predicates, and\n");
2948   printf(
2949 "  histograms of the angles and the aspect ratios of the triangles in the\n");
2950   printf("  mesh.\n\n");
2951   printf("Exact Arithmetic:\n\n");
2952   printf(
2953 "  Triangle uses adaptive exact arithmetic to perform what computational\n");
2954   printf(
2955 "  geometers call the `orientation' and `incircle' tests.  If the floating-\n"
2956 );
2957   printf(
2958 "  point arithmetic of your machine conforms to the IEEE 754 standard (as\n");
2959   printf(
2960 "  most workstations do), and does not use extended precision internal\n");
2961   printf(
2962 "  floating-point registers, then your output is guaranteed to be an\n");
2963   printf(
2964 "  absolutely true Delaunay or constrained Delaunay triangulation, roundoff\n"
2965 );
2966   printf(
2967 "  error notwithstanding.  The word `adaptive' implies that these arithmetic\n"
2968 );
2969   printf(
2970 "  routines compute the result only to the precision necessary to guarantee\n"
2971 );
2972   printf(
2973 "  correctness, so they are usually nearly as fast as their approximate\n");
2974   printf("  counterparts.\n\n");
2975   printf(
2976 "  May CPUs, including Intel x86 processors, have extended precision\n");
2977   printf(
2978 "  floating-point registers.  These must be reconfigured so their precision\n"
2979 );
2980   printf(
2981 "  is reduced to memory precision.  Triangle does this if it is compiled\n");
2982   printf("  correctly.  See the makefile for details.\n\n");
2983   printf(
2984 "  The exact tests can be disabled with the -X switch.  On most inputs, this\n"
2985 );
2986   printf(
2987 "  switch reduces the computation time by about eight percent--it's not\n");
2988   printf(
2989 "  worth the risk.  There are rare difficult inputs (having many collinear\n");
2990   printf(
2991 "  and cocircular vertices), however, for which the difference in speed\n");
2992   printf(
2993 "  could be a factor of two.  Be forewarned that these are precisely the\n");
2994   printf(
2995 "  inputs most likely to cause errors if you use the -X switch.  Hence, the\n"
2996 );
2997   printf("  -X switch is not recommended.\n\n");
2998   printf(
2999 "  Unfortunately, the exact tests don't solve every numerical problem.\n");
3000   printf(
3001 "  Exact arithmetic is not used to compute the positions of new vertices,\n");
3002   printf(
3003 "  because the bit complexity of vertex coordinates would grow without\n");
3004   printf(
3005 "  bound.  Hence, segment intersections aren't computed exactly; in very\n");
3006   printf(
3007 "  unusual cases, roundoff error in computing an intersection point might\n");
3008   printf(
3009 "  actually lead to an inverted triangle and an invalid triangulation.\n");
3010   printf(
3011 "  (This is one reason to specify your own intersection points in your .poly\n"
3012 );
3013   printf(
3014 "  files.)  Similarly, exact arithmetic is not used to compute the vertices\n"
3015 );
3016   printf("  of the Voronoi diagram.\n\n");
3017   printf(
3018 "  Another pair of problems not solved by the exact arithmetic routines is\n");
3019   printf(
3020 "  underflow and overflow.  If Triangle is compiled for double precision\n");
3021   printf(
3022 "  arithmetic, I believe that Triangle's geometric predicates work correctly\n"
3023 );
3024   printf(
3025 "  if the exponent of every input coordinate falls in the range [-148, 201].\n"
3026 );
3027   printf(
3028 "  Underflow can silently prevent the orientation and incircle tests from\n");
3029   printf(
3030 "  being performed exactly, while overflow typically causes a floating\n");
3031   printf("  exception.\n\n");
3032   printf("Calling Triangle from Another Program:\n\n");
3033   printf("  Read the file triangle.h for details.\n\n");
3034   printf("Troubleshooting:\n\n");
3035   printf("  Please read this section before mailing me bugs.\n\n");
3036   printf("  `My output mesh has no triangles!'\n\n");
3037   printf(
3038 "    If you're using a PSLG, you've probably failed to specify a proper set\n"
3039 );
3040   printf(
3041 "    of bounding segments, or forgotten to use the -c switch.  Or you may\n");
3042   printf(
3043 "    have placed a hole badly, thereby eating all your triangles.  To test\n");
3044   printf("    these possibilities, try again with the -c and -O switches.\n");
3045   printf(
3046 "    Alternatively, all your input vertices may be collinear, in which case\n"
3047 );
3048   printf("    you can hardly expect to triangulate them.\n\n");
3049   printf("  `Triangle doesn't terminate, or just crashes.'\n\n");
3050   printf(
3051 "    Bad things can happen when triangles get so small that the distance\n");
3052   printf(
3053 "    between their vertices isn't much larger than the precision of your\n");
3054   printf(
3055 "    machine's arithmetic.  If you've compiled Triangle for single-precision\n"
3056 );
3057   printf(
3058 "    arithmetic, you might do better by recompiling it for double-precision.\n"
3059 );
3060   printf(
3061 "    Then again, you might just have to settle for more lenient constraints\n"
3062 );
3063   printf(
3064 "    on the minimum angle and the maximum area than you had planned.\n");
3065   printf("\n");
3066   printf(
3067 "    You can minimize precision problems by ensuring that the origin lies\n");
3068   printf(
3069 "    inside your vertex set, or even inside the densest part of your\n");
3070   printf(
3071 "    mesh.  If you're triangulating an object whose x-coordinates all fall\n");
3072   printf(
3073 "    between 6247133 and 6247134, you're not leaving much floating-point\n");
3074   printf("    precision for Triangle to work with.\n\n");
3075   printf(
3076 "    Precision problems can occur covertly if the input PSLG contains two\n");
3077   printf(
3078 "    segments that meet (or intersect) at an extremely small angle, or if\n");
3079   printf(
3080 "    such an angle is introduced by the -c switch.  If you don't realize\n");
3081   printf(
3082 "    that a tiny angle is being formed, you might never discover why\n");
3083   printf(
3084 "    Triangle is crashing.  To check for this possibility, use the -S switch\n"
3085 );
3086   printf(
3087 "    (with an appropriate limit on the number of Steiner points, found by\n");
3088   printf(
3089 "    trial-and-error) to stop Triangle early, and view the output .poly file\n"
3090 );
3091   printf(
3092 "    with Show Me (described below).  Look carefully for regions where dense\n"
3093 );
3094   printf(
3095 "    clusters of vertices are forming and for small angles between segments.\n"
3096 );
3097   printf(
3098 "    Zoom in closely, as such segments might look like a single segment from\n"
3099 );
3100   printf("    a distance.\n\n");
3101   printf(
3102 "    If some of the input values are too large, Triangle may suffer a\n");
3103   printf(
3104 "    floating exception due to overflow when attempting to perform an\n");
3105   printf(
3106 "    orientation or incircle test.  (Read the section on exact arithmetic\n");
3107   printf(
3108 "    above.)  Again, I recommend compiling Triangle for double (rather\n");
3109   printf("    than single) precision arithmetic.\n\n");
3110   printf(
3111 "    Unexpected problems can arise if you use quality meshing (-q, -a, or\n");
3112   printf(
3113 "    -u) with an input that is not segment-bounded--that is, if your input\n");
3114   printf(
3115 "    is a vertex set, or you're using the -c switch.  If the convex hull of\n"
3116 );
3117   printf(
3118 "    your input vertices has collinear vertices on its boundary, an input\n");
3119   printf(
3120 "    vertex that you think lies on the convex hull might actually lie just\n");
3121   printf(
3122 "    inside the convex hull.  If so, the vertex and the nearby convex hull\n");
3123   printf(
3124 "    edge form an extremely thin triangle.  When Triangle tries to refine\n");
3125   printf(
3126 "    the mesh to enforce angle and area constraints, Triangle might generate\n"
3127 );
3128   printf(
3129 "    extremely tiny triangles, or it might fail because of insufficient\n");
3130   printf("    floating-point precision.\n\n");
3131   printf(
3132 "  `The numbering of the output vertices doesn't match the input vertices.'\n"
3133 );
3134   printf("\n");
3135   printf(
3136 "    You may have had duplicate input vertices, or you may have eaten some\n");
3137   printf(
3138 "    of your input vertices with a hole, or by placing them outside the area\n"
3139 );
3140   printf(
3141 "    enclosed by segments.  In any case, you can solve the problem by not\n");
3142   printf("    using the -j switch.\n\n");
3143   printf(
3144 "  `Triangle executes without incident, but when I look at the resulting\n");
3145   printf(
3146 "  mesh, it has overlapping triangles or other geometric inconsistencies.'\n");
3147   printf("\n");
3148   printf(
3149 "    If you select the -X switch, Triangle occasionally makes mistakes due\n");
3150   printf(
3151 "    to floating-point roundoff error.  Although these errors are rare,\n");
3152   printf(
3153 "    don't use the -X switch.  If you still have problems, please report the\n"
3154 );
3155   printf("    bug.\n\n");
3156   printf(
3157 "  `Triangle executes without incident, but when I look at the resulting\n");
3158   printf("  Voronoi diagram, it has overlapping edges or other geometric\n");
3159   printf("  inconsistencies.'\n");
3160   printf("\n");
3161   printf(
3162 "    If your input is a PSLG (-p), you can only expect a meaningful Voronoi\n"
3163 );
3164   printf(
3165 "    diagram if the domain you are triangulating is convex and free of\n");
3166   printf(
3167 "    holes, and you use the -D switch to construct a conforming Delaunay\n");
3168   printf("    triangulation (instead of a CDT or CCDT).\n\n");
3169   printf(
3170 "  Strange things can happen if you've taken liberties with your PSLG.  Do\n");
3171   printf(
3172 "  you have a vertex lying in the middle of a segment?  Triangle sometimes\n");
3173   printf(
3174 "  copes poorly with that sort of thing.  Do you want to lay out a collinear\n"
3175 );
3176   printf(
3177 "  row of evenly spaced, segment-connected vertices?  Have you simply\n");
3178   printf(
3179 "  defined one long segment connecting the leftmost vertex to the rightmost\n"
3180 );
3181   printf(
3182 "  vertex, and a bunch of vertices lying along it?  This method occasionally\n"
3183 );
3184   printf(
3185 "  works, especially with horizontal and vertical lines, but often it\n");
3186   printf(
3187 "  doesn't, and you'll have to connect each adjacent pair of vertices with a\n"
3188 );
3189   printf("  separate segment.  If you don't like it, tough.\n\n");
3190   printf(
3191 "  Furthermore, if you have segments that intersect other than at their\n");
3192   printf(
3193 "  endpoints, try not to let the intersections fall extremely close to PSLG\n"
3194 );
3195   printf("  vertices or each other.\n\n");
3196   printf(
3197 "  If you have problems refining a triangulation not produced by Triangle:\n");
3198   printf(
3199 "  Are you sure the triangulation is geometrically valid?  Is it formatted\n");
3200   printf(
3201 "  correctly for Triangle?  Are the triangles all listed so the first three\n"
3202 );
3203   printf(
3204 "  vertices are their corners in counterclockwise order?  Are all of the\n");
3205   printf(
3206 "  triangles constrained Delaunay?  Triangle's Delaunay refinement algorithm\n"
3207 );
3208   printf("  assumes that it starts with a CDT.\n\n");
3209   printf("Show Me:\n\n");
3210   printf(
3211 "  Triangle comes with a separate program named `Show Me', whose primary\n");
3212   printf(
3213 "  purpose is to draw meshes on your screen or in PostScript.  Its secondary\n"
3214 );
3215   printf(
3216 "  purpose is to check the validity of your input files, and do so more\n");
3217   printf(
3218 "  thoroughly than Triangle does.  Unlike Triangle, Show Me requires that\n");
3219   printf(
3220 "  you have the X Windows system.  Sorry, Microsoft Windows users.\n");
3221   printf("\n");
3222   printf("Triangle on the Web:\n");
3223   printf("\n");
3224   printf("  To see an illustrated version of these instructions, check out\n");
3225   printf("\n");
3226   printf("    http://www.cs.cmu.edu/~quake/triangle.html\n");
3227   printf("\n");
3228   printf("A Brief Plea:\n");
3229   printf("\n");
3230   printf(
3231 "  If you use Triangle, and especially if you use it to accomplish real\n");
3232   printf(
3233 "  work, I would like very much to hear from you.  A short letter or email\n");
3234   printf(
3235 "  (to jrs@cs.berkeley.edu) describing how you use Triangle will mean a lot\n"
3236 );
3237   printf(
3238 "  to me.  The more people I know are using this program, the more easily I\n"
3239 );
3240   printf(
3241 "  can justify spending time on improvements, which in turn will benefit\n");
3242   printf(
3243 "  you.  Also, I can put you on a list to receive email whenever a new\n");
3244   printf("  version of Triangle is available.\n\n");
3245   printf(
3246 "  If you use a mesh generated by Triangle in a publication, please include\n"
3247 );
3248   printf(
3249 "  an acknowledgment as well.  And please spell Triangle with a capital `T'!\n"
3250 );
3251   printf(
3252 "  If you want to include a citation, use `Jonathan Richard Shewchuk,\n");
3253   printf(
3254 "  ``Triangle: Engineering a 2D Quality Mesh Generator and Delaunay\n");
3255   printf(
3256 "  Triangulator,'' in Applied Computational Geometry:  Towards Geometric\n");
3257   printf(
3258 "  Engineering (Ming C. Lin and Dinesh Manocha, editors), volume 1148 of\n");
3259   printf(
3260 "  Lecture Notes in Computer Science, pages 203-222, Springer-Verlag,\n");
3261   printf(
3262 "  Berlin, May 1996.  (From the First ACM Workshop on Applied Computational\n"
3263 );
3264   printf("  Geometry.)'\n\n");
3265   printf("Research credit:\n\n");
3266   printf(
3267 "  Of course, I can take credit for only a fraction of the ideas that made\n");
3268   printf(
3269 "  this mesh generator possible.  Triangle owes its existence to the efforts\n"
3270 );
3271   printf(
3272 "  of many fine computational geometers and other researchers, including\n");
3273   printf(
3274 "  Marshall Bern, L. Paul Chew, Kenneth L. Clarkson, Boris Delaunay, Rex A.\n"
3275 );
3276   printf(
3277 "  Dwyer, David Eppstein, Steven Fortune, Leonidas J. Guibas, Donald E.\n");
3278   printf(
3279 "  Knuth, Charles L. Lawson, Der-Tsai Lee, Gary L. Miller, Ernst P. Mucke,\n");
3280   printf(
3281 "  Steven E. Pav, Douglas M. Priest, Jim Ruppert, Isaac Saias, Bruce J.\n");
3282   printf(
3283 "  Schachter, Micha Sharir, Peter W. Shor, Daniel D. Sleator, Jorge Stolfi,\n"
3284 );
3285   printf("  Robert E. Tarjan, Alper Ungor, Christopher J. Van Wyk, Noel J.\n");
3286   printf(
3287 "  Walkington, and Binhai Zhu.  See the comments at the beginning of the\n");
3288   printf("  source code for references.\n\n");
3289   triexit(0);
3290 }
3291 
3292 #endif /* not TRILIBRARY */
3293 
3294 /*****************************************************************************/
3295 /*                                                                           */
3296 /*  internalerror()   Ask the user to send me the defective product.  Exit.  */
3297 /*                                                                           */
3298 /*****************************************************************************/
3299 
internalerror()3300 static void internalerror()
3301 {
3302   printf("  Please report this bug to jrs@cs.berkeley.edu\n");
3303   printf("  Include the message above, your input data set, and the exact\n");
3304   printf("    command line you used to run Triangle.\n");
3305   triexit(1);
3306 }
3307 
3308 /*****************************************************************************/
3309 /*                                                                           */
3310 /*  parsecommandline()   Read the command line, identify switches, and set   */
3311 /*                       up options and file names.                          */
3312 /*                                                                           */
3313 /*****************************************************************************/
3314 
3315 #ifdef ANSI_DECLARATORS
3316 static void parsecommandline(int argc, char **argv, struct behavior *b)
3317 #else /* not ANSI_DECLARATORS */
3318 static void parsecommandline(argc, argv, b)
3319 int argc;
3320 char **argv;
3321 struct behavior *b;
3322 #endif /* not ANSI_DECLARATORS */
3323 
3324 {
3325 #ifdef TRILIBRARY
3326 #define STARTINDEX 0
3327 #else /* not TRILIBRARY */
3328 #define STARTINDEX 1
3329   int increment;
3330   int meshnumber;
3331 #endif /* not TRILIBRARY */
3332 #ifndef CDT_ONLY
3333   int k;
3334   char workstring[FILENAMESIZE];
3335 #endif
3336   int i, j;
3337 
3338   b->poly = b->refine = b->quality = 0;
3339   b->vararea = b->fixedarea = b->usertest = 0;
3340   b->regionattrib = b->convex = b->weighted = b->jettison = 0;
3341   b->firstnumber = 1;
3342   b->edgesout = b->voronoi = b->neighbors = b->geomview = 0;
3343   b->nobound = b->nopolywritten = b->nonodewritten = b->noelewritten = 0;
3344   b->noiterationnum = 0;
3345   b->noholes = b->noexact = 0;
3346   b->incremental = b->sweepline = 0;
3347   b->dwyer = 1;
3348   b->splitseg = 0;
3349   b->docheck = 0;
3350   b->nobisect = 0;
3351   b->conformdel = 0;
3352   b->steiner = -1;
3353   b->order = 1;
3354   b->minangle = 0.0;
3355   b->maxarea = -1.0;
3356   b->quiet = b->verbose = 0;
3357 #ifndef TRILIBRARY
3358   b->innodefilename[0] = '\0';
3359 #endif /* not TRILIBRARY */
3360 
3361   for (i = STARTINDEX; i < argc; i++) {
3362 #ifndef TRILIBRARY
3363     if (argv[i][0] == '-') {
3364 #endif /* not TRILIBRARY */
3365       for (j = STARTINDEX; argv[i][j] != '\0'; j++) {
3366         if (argv[i][j] == 'p') {
3367           b->poly = 1;
3368 	}
3369 #ifndef CDT_ONLY
3370         if (argv[i][j] == 'r') {
3371           b->refine = 1;
3372 	}
3373         if (argv[i][j] == 'q') {
3374           b->quality = 1;
3375           if (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) ||
3376               (argv[i][j + 1] == '.')) {
3377             k = 0;
3378             while (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) ||
3379                    (argv[i][j + 1] == '.')) {
3380               j++;
3381               workstring[k] = argv[i][j];
3382               k++;
3383             }
3384             workstring[k] = '\0';
3385             b->minangle = (REAL) strtod(workstring, (char **) NULL);
3386 	  } else {
3387             b->minangle = 20.0;
3388 	  }
3389 	}
3390         if (argv[i][j] == 'a') {
3391           b->quality = 1;
3392           if (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) ||
3393               (argv[i][j + 1] == '.')) {
3394             b->fixedarea = 1;
3395             k = 0;
3396             while (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) ||
3397                    (argv[i][j + 1] == '.')) {
3398               j++;
3399               workstring[k] = argv[i][j];
3400               k++;
3401             }
3402             workstring[k] = '\0';
3403             b->maxarea = (REAL) strtod(workstring, (char **) NULL);
3404             if (b->maxarea <= 0.0) {
3405               printf("Error: Maximum area must be greater than zero.\n");
3406               triexit(1);
3407 	    }
3408 	  } else {
3409             b->vararea = 1;
3410 	  }
3411 	}
3412         if (argv[i][j] == 'u') {
3413           b->quality = 1;
3414           b->usertest = 1;
3415         }
3416 #endif /* not CDT_ONLY */
3417         if (argv[i][j] == 'A') {
3418           b->regionattrib = 1;
3419         }
3420         if (argv[i][j] == 'c') {
3421           b->convex = 1;
3422         }
3423         if (argv[i][j] == 'w') {
3424           b->weighted = 1;
3425         }
3426         if (argv[i][j] == 'W') {
3427           b->weighted = 2;
3428         }
3429         if (argv[i][j] == 'j') {
3430           b->jettison = 1;
3431         }
3432         if (argv[i][j] == 'z') {
3433           b->firstnumber = 0;
3434         }
3435         if (argv[i][j] == 'e') {
3436           b->edgesout = 1;
3437 	}
3438         if (argv[i][j] == 'v') {
3439           b->voronoi = 1;
3440 	}
3441         if (argv[i][j] == 'n') {
3442           b->neighbors = 1;
3443 	}
3444         if (argv[i][j] == 'g') {
3445           b->geomview = 1;
3446 	}
3447         if (argv[i][j] == 'B') {
3448           b->nobound = 1;
3449 	}
3450         if (argv[i][j] == 'P') {
3451           b->nopolywritten = 1;
3452 	}
3453         if (argv[i][j] == 'N') {
3454           b->nonodewritten = 1;
3455 	}
3456         if (argv[i][j] == 'E') {
3457           b->noelewritten = 1;
3458 	}
3459 #ifndef TRILIBRARY
3460         if (argv[i][j] == 'I') {
3461           b->noiterationnum = 1;
3462 	}
3463 #endif /* not TRILIBRARY */
3464         if (argv[i][j] == 'O') {
3465           b->noholes = 1;
3466 	}
3467         if (argv[i][j] == 'X') {
3468           b->noexact = 1;
3469 	}
3470         if (argv[i][j] == 'o') {
3471           if (argv[i][j + 1] == '2') {
3472             j++;
3473             b->order = 2;
3474           }
3475 	}
3476 #ifndef CDT_ONLY
3477         if (argv[i][j] == 'Y') {
3478           b->nobisect++;
3479 	}
3480         if (argv[i][j] == 'S') {
3481           b->steiner = 0;
3482           while ((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) {
3483             j++;
3484             b->steiner = b->steiner * 10 + (int) (argv[i][j] - '0');
3485           }
3486         }
3487 #endif /* not CDT_ONLY */
3488 #ifndef REDUCED
3489         if (argv[i][j] == 'i') {
3490           b->incremental = 1;
3491         }
3492         if (argv[i][j] == 'F') {
3493           b->sweepline = 1;
3494         }
3495 #endif /* not REDUCED */
3496         if (argv[i][j] == 'l') {
3497           b->dwyer = 0;
3498         }
3499 #ifndef REDUCED
3500 #ifndef CDT_ONLY
3501         if (argv[i][j] == 's') {
3502           b->splitseg = 1;
3503         }
3504         if ((argv[i][j] == 'D') || (argv[i][j] == 'L')) {
3505           b->quality = 1;
3506           b->conformdel = 1;
3507         }
3508 #endif /* not CDT_ONLY */
3509         if (argv[i][j] == 'C') {
3510           b->docheck = 1;
3511         }
3512 #endif /* not REDUCED */
3513         if (argv[i][j] == 'Q') {
3514           b->quiet = 1;
3515         }
3516         if (argv[i][j] == 'V') {
3517           b->verbose++;
3518         }
3519 #ifndef TRILIBRARY
3520         if ((argv[i][j] == 'h') || (argv[i][j] == 'H') ||
3521             (argv[i][j] == '?')) {
3522           info();
3523 	}
3524 #endif /* not TRILIBRARY */
3525       }
3526 #ifndef TRILIBRARY
3527     } else {
3528       strncpy(b->innodefilename, argv[i], FILENAMESIZE - 1);
3529       b->innodefilename[FILENAMESIZE - 1] = '\0';
3530     }
3531 #endif /* not TRILIBRARY */
3532   }
3533 #ifndef TRILIBRARY
3534   if (b->innodefilename[0] == '\0') {
3535     syntax();
3536   }
3537   if (!strcmp(&b->innodefilename[strlen(b->innodefilename) - 5], ".node")) {
3538     b->innodefilename[strlen(b->innodefilename) - 5] = '\0';
3539   }
3540   if (!strcmp(&b->innodefilename[strlen(b->innodefilename) - 5], ".poly")) {
3541     b->innodefilename[strlen(b->innodefilename) - 5] = '\0';
3542     b->poly = 1;
3543   }
3544 #ifndef CDT_ONLY
3545   if (!strcmp(&b->innodefilename[strlen(b->innodefilename) - 4], ".ele")) {
3546     b->innodefilename[strlen(b->innodefilename) - 4] = '\0';
3547     b->refine = 1;
3548   }
3549   if (!strcmp(&b->innodefilename[strlen(b->innodefilename) - 5], ".area")) {
3550     b->innodefilename[strlen(b->innodefilename) - 5] = '\0';
3551     b->refine = 1;
3552     b->quality = 1;
3553     b->vararea = 1;
3554   }
3555 #endif /* not CDT_ONLY */
3556 #endif /* not TRILIBRARY */
3557   b->usesegments = b->poly || b->refine || b->quality || b->convex;
3558   b->goodangle = cos(b->minangle * PI / 180.0);
3559   if (b->goodangle == 1.0) {
3560     b->offconstant = 0.0;
3561   } else {
3562     b->offconstant = 0.475 * sqrt((1.0 + b->goodangle) / (1.0 - b->goodangle));
3563   }
3564   b->goodangle *= b->goodangle;
3565   if (b->refine && b->noiterationnum) {
3566     printf(
3567       "Error: You cannot use the -I switch when refining a triangulation.\n");
3568     triexit(1);
3569   }
3570   /* Be careful not to allocate space for element area constraints that */
3571   /*   will never be assigned any value (other than the default -1.0).  */
3572   if (!b->refine && !b->poly) {
3573     b->vararea = 0;
3574   }
3575   /* Be careful not to add an extra attribute to each element unless the */
3576   /*   input supports it (PSLG in, but not refining a preexisting mesh). */
3577   if (b->refine || !b->poly) {
3578     b->regionattrib = 0;
3579   }
3580   /* Regular/weighted triangulations are incompatible with PSLGs */
3581   /*   and meshing.                                              */
3582   if (b->weighted && (b->poly || b->quality)) {
3583     b->weighted = 0;
3584     if (!b->quiet) {
3585       printf("Warning:  weighted triangulations (-w, -W) are incompatible\n");
3586       printf("  with PSLGs (-p) and meshing (-q, -a, -u).  Weights ignored.\n"
3587              );
3588     }
3589   }
3590   if (b->jettison && b->nonodewritten && !b->quiet) {
3591     printf("Warning:  -j and -N switches are somewhat incompatible.\n");
3592     printf("  If any vertices are jettisoned, you will need the output\n");
3593     printf("  .node file to reconstruct the new node indices.");
3594   }
3595 
3596 #ifndef TRILIBRARY
3597   strcpy(b->inpolyfilename, b->innodefilename);
3598   strcpy(b->inelefilename, b->innodefilename);
3599   strcpy(b->areafilename, b->innodefilename);
3600   increment = 0;
3601   strcpy(workstring, b->innodefilename);
3602   j = 1;
3603   while (workstring[j] != '\0') {
3604     if ((workstring[j] == '.') && (workstring[j + 1] != '\0')) {
3605       increment = j + 1;
3606     }
3607     j++;
3608   }
3609   meshnumber = 0;
3610   if (increment > 0) {
3611     j = increment;
3612     do {
3613       if ((workstring[j] >= '0') && (workstring[j] <= '9')) {
3614         meshnumber = meshnumber * 10 + (int) (workstring[j] - '0');
3615       } else {
3616         increment = 0;
3617       }
3618       j++;
3619     } while (workstring[j] != '\0');
3620   }
3621   if (b->noiterationnum) {
3622     strcpy(b->outnodefilename, b->innodefilename);
3623     strcpy(b->outelefilename, b->innodefilename);
3624     strcpy(b->edgefilename, b->innodefilename);
3625     strcpy(b->vnodefilename, b->innodefilename);
3626     strcpy(b->vedgefilename, b->innodefilename);
3627     strcpy(b->neighborfilename, b->innodefilename);
3628     strcpy(b->offfilename, b->innodefilename);
3629     strcat(b->outnodefilename, ".node");
3630     strcat(b->outelefilename, ".ele");
3631     strcat(b->edgefilename, ".edge");
3632     strcat(b->vnodefilename, ".v.node");
3633     strcat(b->vedgefilename, ".v.edge");
3634     strcat(b->neighborfilename, ".neigh");
3635     strcat(b->offfilename, ".off");
3636   } else if (increment == 0) {
3637     strcpy(b->outnodefilename, b->innodefilename);
3638     strcpy(b->outpolyfilename, b->innodefilename);
3639     strcpy(b->outelefilename, b->innodefilename);
3640     strcpy(b->edgefilename, b->innodefilename);
3641     strcpy(b->vnodefilename, b->innodefilename);
3642     strcpy(b->vedgefilename, b->innodefilename);
3643     strcpy(b->neighborfilename, b->innodefilename);
3644     strcpy(b->offfilename, b->innodefilename);
3645     strcat(b->outnodefilename, ".1.node");
3646     strcat(b->outpolyfilename, ".1.poly");
3647     strcat(b->outelefilename, ".1.ele");
3648     strcat(b->edgefilename, ".1.edge");
3649     strcat(b->vnodefilename, ".1.v.node");
3650     strcat(b->vedgefilename, ".1.v.edge");
3651     strcat(b->neighborfilename, ".1.neigh");
3652     strcat(b->offfilename, ".1.off");
3653   } else {
3654     workstring[increment] = '%';
3655     workstring[increment + 1] = 'd';
3656     workstring[increment + 2] = '\0';
3657     sprintf(b->outnodefilename, workstring, meshnumber + 1);
3658     strcpy(b->outpolyfilename, b->outnodefilename);
3659     strcpy(b->outelefilename, b->outnodefilename);
3660     strcpy(b->edgefilename, b->outnodefilename);
3661     strcpy(b->vnodefilename, b->outnodefilename);
3662     strcpy(b->vedgefilename, b->outnodefilename);
3663     strcpy(b->neighborfilename, b->outnodefilename);
3664     strcpy(b->offfilename, b->outnodefilename);
3665     strcat(b->outnodefilename, ".node");
3666     strcat(b->outpolyfilename, ".poly");
3667     strcat(b->outelefilename, ".ele");
3668     strcat(b->edgefilename, ".edge");
3669     strcat(b->vnodefilename, ".v.node");
3670     strcat(b->vedgefilename, ".v.edge");
3671     strcat(b->neighborfilename, ".neigh");
3672     strcat(b->offfilename, ".off");
3673   }
3674   strcat(b->innodefilename, ".node");
3675   strcat(b->inpolyfilename, ".poly");
3676   strcat(b->inelefilename, ".ele");
3677   strcat(b->areafilename, ".area");
3678 #endif /* not TRILIBRARY */
3679 }
3680 
3681 /**                                                                         **/
3682 /**                                                                         **/
3683 /********* User interaction routines begin here                      *********/
3684 
3685 /********* Debugging routines begin here                             *********/
3686 /**                                                                         **/
3687 /**                                                                         **/
3688 
3689 /*****************************************************************************/
3690 /*                                                                           */
3691 /*  printtriangle()   Print out the details of an oriented triangle.         */
3692 /*                                                                           */
3693 /*  I originally wrote this procedure to simplify debugging; it can be       */
3694 /*  called directly from the debugger, and presents information about an     */
3695 /*  oriented triangle in digestible form.  It's also used when the           */
3696 /*  highest level of verbosity (`-VVV') is specified.                        */
3697 /*                                                                           */
3698 /*****************************************************************************/
3699 
3700 #ifdef ANSI_DECLARATORS
3701 static void printtriangle(struct mesh *m, struct behavior *b, struct otri *t)
3702 #else /* not ANSI_DECLARATORS */
3703 static void printtriangle(m, b, t)
3704 struct mesh *m;
3705 struct behavior *b;
3706 struct otri *t;
3707 #endif /* not ANSI_DECLARATORS */
3708 
3709 {
3710   struct otri printtri;
3711   struct osub printsh;
3712   vertex printvertex;
3713 
3714   printf("triangle x%" PRIu " with orientation %d:\n", (unsigned LONG) t->tri, t->orient);
3715   decode(t->tri[0], printtri);
3716   if (printtri.tri == m->dummytri) {
3717     printf("    [0] = Outer space\n");
3718   } else {
3719     printf("    [0] = x%" PRIu "  %d\n", (unsigned LONG) printtri.tri, printtri.orient);
3720   }
3721   decode(t->tri[1], printtri);
3722   if (printtri.tri == m->dummytri) {
3723     printf("    [1] = Outer space\n");
3724   } else {
3725     printf("    [1] = x%" PRIu "  %d\n", (unsigned LONG) printtri.tri, printtri.orient);
3726   }
3727   decode(t->tri[2], printtri);
3728   if (printtri.tri == m->dummytri) {
3729     printf("    [2] = Outer space\n");
3730   } else {
3731     printf("    [2] = x%" PRIu "  %d\n", (unsigned LONG) printtri.tri, printtri.orient);
3732   }
3733 
3734   org(*t, printvertex);
3735   if (printvertex == (vertex) NULL)
3736     printf("    Origin[%d] = NULL\n", (t->orient + 1) % 3 + 3);
3737   else
3738     printf("    Origin[%d] = x%" PRIu "  (%.12g, %.12g)\n",
3739            (t->orient + 1) % 3 + 3, (unsigned LONG) printvertex, printvertex[0], printvertex[1]); dest(*t, printvertex);
3740   if (printvertex == (vertex) NULL)
3741     printf("    Dest  [%d] = NULL\n", (t->orient + 2) % 3 + 3);
3742   else
3743     printf("    Dest  [%d] = x%" PRIu "  (%.12g, %.12g)\n",
3744            (t->orient + 2) % 3 + 3, (unsigned LONG) printvertex, printvertex[0], printvertex[1]); apex(*t, printvertex);
3745   if (printvertex == (vertex) NULL)
3746     printf("    Apex  [%d] = NULL\n", t->orient + 3);
3747   else
3748     printf("    Apex  [%d] = x%" PRIu "  (%.12g, %.12g)\n", t->orient + 3, (unsigned LONG) printvertex, printvertex[0], printvertex[1]);
3749 
3750   if (b->usesegments) {
3751     sdecode(t->tri[6], printsh);
3752     if (printsh.ss != m->dummysub) {
3753       printf("    [6] = x%" PRIu "  %d\n", (unsigned LONG) printsh.ss, printsh.ssorient);
3754     }
3755     sdecode(t->tri[7], printsh);
3756     if (printsh.ss != m->dummysub) {
3757       printf("    [7] = x%" PRIu "  %d\n", (unsigned LONG) printsh.ss, printsh.ssorient);
3758     }
3759     sdecode(t->tri[8], printsh);
3760     if (printsh.ss != m->dummysub) {
3761       printf("    [8] = x%" PRIu "  %d\n", (unsigned LONG) printsh.ss, printsh.ssorient);
3762     }
3763   }
3764 
3765   if (b->vararea) {
3766     printf("    Area constraint:  %.4g\n", areabound(*t));
3767   }
3768 }
3769 
3770 /*****************************************************************************/
3771 /*                                                                           */
3772 /*  printsubseg()   Print out the details of an oriented subsegment.         */
3773 /*                                                                           */
3774 /*  I originally wrote this procedure to simplify debugging; it can be       */
3775 /*  called directly from the debugger, and presents information about an     */
3776 /*  oriented subsegment in digestible form.  It's also used when the highest */
3777 /*  level of verbosity (`-VVV') is specified.                                */
3778 /*                                                                           */
3779 /*****************************************************************************/
3780 
3781 #ifdef ANSI_DECLARATORS
3782 static void printsubseg(struct mesh *m, struct behavior *b, struct osub *s)
3783 #else /* not ANSI_DECLARATORS */
3784 static void printsubseg(m, b, s)
3785 struct mesh *m;
3786 struct behavior *b;
3787 struct osub *s;
3788 #endif /* not ANSI_DECLARATORS */
3789 
3790 {
3791   struct osub printsh;
3792   struct otri printtri;
3793   vertex printvertex;
3794   (void)(b);
3795   printf("subsegment x%" PRIu " with orientation %d and mark %d:\n",
3796          (unsigned LONG) s->ss, s->ssorient, mark(*s));
3797   sdecode(s->ss[0], printsh);
3798   if (printsh.ss == m->dummysub) {
3799     printf("    [0] = No subsegment\n");
3800   } else {
3801     printf("    [0] = x%" PRIu "  %d\n", (unsigned LONG) printsh.ss, printsh.ssorient);
3802   }
3803   sdecode(s->ss[1], printsh);
3804   if (printsh.ss == m->dummysub) {
3805     printf("    [1] = No subsegment\n");
3806   } else {
3807     printf("    [1] = x%" PRIu "  %d\n", (unsigned LONG) printsh.ss, printsh.ssorient);
3808   }
3809 
3810   sorg(*s, printvertex);
3811   if (printvertex == (vertex) NULL)
3812     printf("    Origin[%d] = NULL\n", 2 + s->ssorient);
3813   else
3814     printf("    Origin[%d] = x%" PRIu "  (%.12g, %.12g)\n", 2 + s->ssorient, (unsigned LONG) printvertex, printvertex[0], printvertex[1]);
3815   sdest(*s, printvertex);
3816   if (printvertex == (vertex) NULL)
3817     printf("    Dest  [%d] = NULL\n", 3 - s->ssorient);
3818   else
3819     printf("    Dest  [%d] = x%" PRIu "  (%.12g, %.12g)\n", 3 - s->ssorient, (unsigned LONG) printvertex, printvertex[0], printvertex[1]);
3820 
3821   decode(s->ss[6], printtri);
3822   if (printtri.tri == m->dummytri) {
3823     printf("    [6] = Outer space\n");
3824   } else {
3825     printf("    [6] = x%" PRIu "  %d\n", (unsigned LONG) printtri.tri, printtri.orient);
3826   }
3827   decode(s->ss[7], printtri);
3828   if (printtri.tri == m->dummytri) {
3829     printf("    [7] = Outer space\n");
3830   } else {
3831     printf("    [7] = x%" PRIu "  %d\n", (unsigned LONG) printtri.tri, printtri.orient);
3832   }
3833 
3834   segorg(*s, printvertex);
3835   if (printvertex == (vertex) NULL)
3836     printf("    Segment origin[%d] = NULL\n", 4 + s->ssorient);
3837   else
3838     printf("    Segment origin[%d] = x%" PRIu "  (%.12g, %.12g)\n",
3839            4 + s->ssorient, (unsigned LONG) printvertex, printvertex[0], printvertex[1]);
3840   segdest(*s, printvertex);
3841   if (printvertex == (vertex) NULL)
3842     printf("    Segment dest  [%d] = NULL\n", 5 - s->ssorient);
3843   else
3844     printf("    Segment dest  [%d] = x%" PRIu "  (%.12g, %.12g)\n",
3845            5 - s->ssorient, (unsigned LONG) printvertex, printvertex[0], printvertex[1]);
3846 }
3847 
3848 /**                                                                         **/
3849 /**                                                                         **/
3850 /********* Debugging routines end here                               *********/
3851 
3852 /********* Memory management routines begin here                     *********/
3853 /**                                                                         **/
3854 /**                                                                         **/
3855 
3856 /*****************************************************************************/
3857 /*                                                                           */
3858 /*  poolzero()   Set all of a pool's fields to zero.                         */
3859 /*                                                                           */
3860 /*  This procedure should never be called on a pool that has any memory      */
3861 /*  allocated to it, as that memory would leak.                              */
3862 /*                                                                           */
3863 /*****************************************************************************/
3864 
3865 #ifdef ANSI_DECLARATORS
3866 static void poolzero(struct memorypool *pool)
3867 #else /* not ANSI_DECLARATORS */
3868 static void poolzero(pool)
3869 struct memorypool *pool;
3870 #endif /* not ANSI_DECLARATORS */
3871 
3872 {
3873   pool->firstblock = (VOID **) NULL;
3874   pool->nowblock = (VOID **) NULL;
3875   pool->nextitem = (VOID *) NULL;
3876   pool->deaditemstack = (VOID *) NULL;
3877   pool->pathblock = (VOID **) NULL;
3878   pool->pathitem = (VOID *) NULL;
3879   pool->alignbytes = 0;
3880   pool->itembytes = 0;
3881   pool->itemsperblock = 0;
3882   pool->itemsfirstblock = 0;
3883   pool->items = 0;
3884   pool->maxitems = 0;
3885   pool->unallocateditems = 0;
3886   pool->pathitemsleft = 0;
3887 }
3888 
3889 /*****************************************************************************/
3890 /*                                                                           */
3891 /*  poolrestart()   Deallocate all items in a pool.                          */
3892 /*                                                                           */
3893 /*  The pool is returned to its starting state, except that no memory is     */
3894 /*  freed to the operating system.  Rather, the previously allocated blocks  */
3895 /*  are ready to be reused.                                                  */
3896 /*                                                                           */
3897 /*****************************************************************************/
3898 
3899 #ifdef ANSI_DECLARATORS
3900 static void poolrestart(struct memorypool *pool)
3901 #else /* not ANSI_DECLARATORS */
3902 static void poolrestart(pool)
3903 struct memorypool *pool;
3904 #endif /* not ANSI_DECLARATORS */
3905 
3906 {
3907   unsigned LONG alignptr;
3908 
3909   pool->items = 0;
3910   pool->maxitems = 0;
3911 
3912   /* Set the currently active block. */
3913   pool->nowblock = pool->firstblock;
3914   /* Find the first item in the pool.  Increment by the size of (VOID *). */
3915   alignptr = (unsigned LONG) (pool->nowblock + 1);
3916   /* Align the item on an `alignbytes'-byte boundary. */
3917   pool->nextitem = (VOID *)
3918     (alignptr + (unsigned LONG) pool->alignbytes -
3919      (alignptr % (unsigned LONG) pool->alignbytes));
3920   /* There are lots of unallocated items left in this block. */
3921   pool->unallocateditems = pool->itemsfirstblock;
3922   /* The stack of deallocated items is empty. */
3923   pool->deaditemstack = (VOID *) NULL;
3924 }
3925 
3926 /*****************************************************************************/
3927 /*                                                                           */
3928 /*  poolinit()   Initialize a pool of memory for allocation of items.        */
3929 /*                                                                           */
3930 /*  This routine initializes the machinery for allocating items.  A `pool'   */
3931 /*  is created whose records have size at least `bytecount'.  Items will be  */
3932 /*  allocated in `itemcount'-item blocks.  Each item is assumed to be a      */
3933 /*  collection of words, and either pointers or floating-point values are    */
3934 /*  assumed to be the "primary" word type.  (The "primary" word type is used */
3935 /*  to determine alignment of items.)  If `alignment' isn't zero, all items  */
3936 /*  will be `alignment'-byte aligned in memory.  `alignment' must be either  */
3937 /*  a multiple or a factor of the primary word size; powers of two are safe. */
3938 /*  `alignment' is normally used to create a few unused bits at the bottom   */
3939 /*  of each item's pointer, in which information may be stored.              */
3940 /*                                                                           */
3941 /*  Don't change this routine unless you understand it.                      */
3942 /*                                                                           */
3943 /*****************************************************************************/
3944 
3945 #ifdef ANSI_DECLARATORS
3946 static void poolinit(struct memorypool *pool, size_t bytecount, size_t itemcount,
3947               size_t firstitemcount, size_t alignment)
3948 #else /* not ANSI_DECLARATORS */
3949 static void poolinit(pool, bytecount, itemcount, firstitemcount, alignment)
3950 struct memorypool *pool;
3951 size_t bytecount;
3952 size_t itemcount;
3953 size_t firstitemcount;
3954 size_t alignment;
3955 #endif /* not ANSI_DECLARATORS */
3956 
3957 {
3958   /* Find the proper alignment, which must be at least as large as:   */
3959   /*   - The parameter `alignment'.                                   */
3960   /*   - sizeof(VOID *), so the stack of dead items can be maintained */
3961   /*       without unaligned accesses.                                */
3962   if (alignment > sizeof(VOID *)) {
3963     pool->alignbytes = alignment;
3964   } else {
3965     pool->alignbytes = sizeof(VOID *);
3966   }
3967   pool->itembytes = ((bytecount - 1) / pool->alignbytes + 1) *
3968                     pool->alignbytes;
3969   pool->itemsperblock = itemcount;
3970   if (firstitemcount == 0) {
3971     pool->itemsfirstblock = itemcount;
3972   } else {
3973     pool->itemsfirstblock = firstitemcount;
3974   }
3975 
3976   /* Allocate a block of items.  Space for `itemsfirstblock' items and one  */
3977   /*   pointer (to point to the next block) are allocated, as well as space */
3978   /*   to ensure alignment of the items.                                    */
3979   pool->firstblock = (VOID **)
3980     trimalloc(pool->itemsfirstblock * pool->itembytes + (int) sizeof(VOID *) +
3981               pool->alignbytes);
3982   /* Set the next block pointer to NULL. */
3983   *(pool->firstblock) = (VOID *) NULL;
3984   poolrestart(pool);
3985 }
3986 
3987 /*****************************************************************************/
3988 /*                                                                           */
3989 /*  pooldeinit()   Free to the operating system all memory taken by a pool.  */
3990 /*                                                                           */
3991 /*****************************************************************************/
3992 
3993 #ifdef ANSI_DECLARATORS
3994 static void pooldeinit(struct memorypool *pool)
3995 #else /* not ANSI_DECLARATORS */
3996 static void pooldeinit(pool)
3997 struct memorypool *pool;
3998 #endif /* not ANSI_DECLARATORS */
3999 
4000 {
4001   while (pool->firstblock != (VOID **) NULL) {
4002     pool->nowblock = (VOID **) *(pool->firstblock);
4003     trifree((VOID *) pool->firstblock);
4004     pool->firstblock = pool->nowblock;
4005   }
4006 }
4007 
4008 /*****************************************************************************/
4009 /*                                                                           */
4010 /*  poolalloc()   Allocate space for an item.                                */
4011 /*                                                                           */
4012 /*****************************************************************************/
4013 
4014 #ifdef ANSI_DECLARATORS
4015 static VOID *poolalloc(struct memorypool *pool)
4016 #else /* not ANSI_DECLARATORS */
4017 static VOID *poolalloc(pool)
4018 struct memorypool *pool;
4019 #endif /* not ANSI_DECLARATORS */
4020 
4021 {
4022   VOID *newitem;
4023   VOID **newblock;
4024   unsigned LONG alignptr;
4025 
4026   /* First check the linked list of dead items.  If the list is not   */
4027   /*   empty, allocate an item from the list rather than a fresh one. */
4028   if (pool->deaditemstack != (VOID *) NULL) {
4029     newitem = pool->deaditemstack;               /* Take first item in list. */
4030     pool->deaditemstack = * (VOID **) pool->deaditemstack;
4031   } else {
4032     /* Check if there are any free items left in the current block. */
4033     if (pool->unallocateditems == 0) {
4034       /* Check if another block must be allocated. */
4035       if (*(pool->nowblock) == (VOID *) NULL) {
4036         /* Allocate a new block of items, pointed to by the previous block. */
4037         newblock = (VOID **) trimalloc(pool->itemsperblock * pool->itembytes +
4038                                        (int) sizeof(VOID *) +
4039                                        pool->alignbytes);
4040         *(pool->nowblock) = (VOID *) newblock;
4041         /* The next block pointer is NULL. */
4042         *newblock = (VOID *) NULL;
4043       }
4044 
4045       /* Move to the new block. */
4046       pool->nowblock = (VOID **) *(pool->nowblock);
4047       /* Find the first item in the block.    */
4048       /*   Increment by the size of (VOID *). */
4049       alignptr = (unsigned LONG) (pool->nowblock + 1);
4050       /* Align the item on an `alignbytes'-byte boundary. */
4051       pool->nextitem = (VOID *)
4052         (alignptr + (unsigned LONG) pool->alignbytes -
4053          (alignptr % (unsigned LONG) pool->alignbytes));
4054       /* There are lots of unallocated items left in this block. */
4055       pool->unallocateditems = pool->itemsperblock;
4056     }
4057 
4058     /* Allocate a new item. */
4059     newitem = pool->nextitem;
4060     /* Advance `nextitem' pointer to next free item in block. */
4061     pool->nextitem = (VOID *) ((char *) pool->nextitem + pool->itembytes);
4062     pool->unallocateditems--;
4063     pool->maxitems++;
4064   }
4065   pool->items++;
4066   return newitem;
4067 }
4068 
4069 /*****************************************************************************/
4070 /*                                                                           */
4071 /*  pooldealloc()   Deallocate space for an item.                            */
4072 /*                                                                           */
4073 /*  The deallocated space is stored in a queue for later reuse.              */
4074 /*                                                                           */
4075 /*****************************************************************************/
4076 
4077 #ifdef ANSI_DECLARATORS
4078 static void pooldealloc(struct memorypool *pool, VOID *dyingitem)
4079 #else /* not ANSI_DECLARATORS */
4080 static void pooldealloc(pool, dyingitem)
4081 struct memorypool *pool;
4082 VOID *dyingitem;
4083 #endif /* not ANSI_DECLARATORS */
4084 
4085 {
4086   /* Push freshly killed item onto stack. */
4087   *((VOID **) dyingitem) = pool->deaditemstack;
4088   pool->deaditemstack = dyingitem;
4089   pool->items--;
4090 }
4091 
4092 /*****************************************************************************/
4093 /*                                                                           */
4094 /*  traversalinit()   Prepare to traverse the entire list of items.          */
4095 /*                                                                           */
4096 /*  This routine is used in conjunction with traverse().                     */
4097 /*                                                                           */
4098 /*****************************************************************************/
4099 
4100 #ifdef ANSI_DECLARATORS
4101 static void traversalinit(struct memorypool *pool)
4102 #else /* not ANSI_DECLARATORS */
4103 static void traversalinit(pool)
4104 struct memorypool *pool;
4105 #endif /* not ANSI_DECLARATORS */
4106 
4107 {
4108   unsigned LONG alignptr;
4109 
4110   /* Begin the traversal in the first block. */
4111   pool->pathblock = pool->firstblock;
4112   /* Find the first item in the block.  Increment by the size of (VOID *). */
4113   alignptr = (unsigned LONG) (pool->pathblock + 1);
4114   /* Align with item on an `alignbytes'-byte boundary. */
4115   pool->pathitem = (VOID *)
4116     (alignptr + (unsigned LONG) pool->alignbytes -
4117      (alignptr % (unsigned LONG) pool->alignbytes));
4118   /* Set the number of items left in the current block. */
4119   pool->pathitemsleft = pool->itemsfirstblock;
4120 }
4121 
4122 /*****************************************************************************/
4123 /*                                                                           */
4124 /*  traverse()   Find the next item in the list.                             */
4125 /*                                                                           */
4126 /*  This routine is used in conjunction with traversalinit().  Be forewarned */
4127 /*  that this routine successively returns all items in the list, including  */
4128 /*  deallocated ones on the deaditemqueue.  It's up to you to figure out     */
4129 /*  which ones are actually dead.  Why?  I don't want to allocate extra      */
4130 /*  space just to demarcate dead items.  It can usually be done more         */
4131 /*  space-efficiently by a routine that knows something about the structure  */
4132 /*  of the item.                                                             */
4133 /*                                                                           */
4134 /*****************************************************************************/
4135 
4136 #ifdef ANSI_DECLARATORS
4137 static VOID *traverse(struct memorypool *pool)
4138 #else /* not ANSI_DECLARATORS */
4139 static VOID *traverse(pool)
4140 struct memorypool *pool;
4141 #endif /* not ANSI_DECLARATORS */
4142 
4143 {
4144   VOID *newitem;
4145   unsigned LONG alignptr;
4146 
4147   /* Stop upon exhausting the list of items. */
4148   if (pool->pathitem == pool->nextitem) {
4149     return (VOID *) NULL;
4150   }
4151 
4152   /* Check whether any untraversed items remain in the current block. */
4153   if (pool->pathitemsleft == 0) {
4154     /* Find the next block. */
4155     pool->pathblock = (VOID **) *(pool->pathblock);
4156     /* Find the first item in the block.  Increment by the size of (VOID *). */
4157     alignptr = (unsigned LONG) (pool->pathblock + 1);
4158     /* Align with item on an `alignbytes'-byte boundary. */
4159     pool->pathitem = (VOID *)
4160       (alignptr + (unsigned LONG) pool->alignbytes -
4161        (alignptr % (unsigned LONG) pool->alignbytes));
4162     /* Set the number of items left in the current block. */
4163     pool->pathitemsleft = pool->itemsperblock;
4164   }
4165 
4166   newitem = pool->pathitem;
4167   /* Find the next item in the block. */
4168   pool->pathitem = (VOID *) ((char *) pool->pathitem + pool->itembytes);
4169   pool->pathitemsleft--;
4170   return newitem;
4171 }
4172 
4173 /*****************************************************************************/
4174 /*                                                                           */
4175 /*  dummyinit()   Initialize the triangle that fills "outer space" and the   */
4176 /*                omnipresent subsegment.                                    */
4177 /*                                                                           */
4178 /*  The triangle that fills "outer space," called `dummytri', is pointed to  */
4179 /*  by every triangle and subsegment on a boundary (be it outer or inner) of */
4180 /*  the triangulation.  Also, `dummytri' points to one of the triangles on   */
4181 /*  the convex hull (until the holes and concavities are carved), making it  */
4182 /*  possible to find a starting triangle for point location.                 */
4183 /*                                                                           */
4184 /*  The omnipresent subsegment, `dummysub', is pointed to by every triangle  */
4185 /*  or subsegment that doesn't have a full complement of real subsegments    */
4186 /*  to point to.                                                             */
4187 /*                                                                           */
4188 /*  `dummytri' and `dummysub' are generally required to fulfill only a few   */
4189 /*  invariants:  their vertices must remain NULL and `dummytri' must always  */
4190 /*  be bonded (at offset zero) to some triangle on the convex hull of the    */
4191 /*  mesh, via a boundary edge.  Otherwise, the connections of `dummytri' and */
4192 /*  `dummysub' may change willy-nilly.  This makes it possible to avoid      */
4193 /*  writing a good deal of special-case code (in the edge flip, for example) */
4194 /*  for dealing with the boundary of the mesh, places where no subsegment is */
4195 /*  present, and so forth.  Other entities are frequently bonded to          */
4196 /*  `dummytri' and `dummysub' as if they were real mesh entities, with no    */
4197 /*  harm done.                                                               */
4198 /*                                                                           */
4199 /*****************************************************************************/
4200 
4201 #ifdef ANSI_DECLARATORS
4202 static void dummyinit(struct mesh *m, struct behavior *b, int trianglebytes,
4203                int subsegbytes)
4204 #else /* not ANSI_DECLARATORS */
4205 static void dummyinit(m, b, trianglebytes, subsegbytes)
4206 struct mesh *m;
4207 struct behavior *b;
4208 int trianglebytes;
4209 int subsegbytes;
4210 #endif /* not ANSI_DECLARATORS */
4211 
4212 {
4213   unsigned LONG alignptr;
4214 
4215   /* Set up `dummytri', the `triangle' that occupies "outer space." */
4216   m->dummytribase = (triangle *) trimalloc(trianglebytes +
4217                                            m->triangles.alignbytes);
4218   /* Align `dummytri' on a `triangles.alignbytes'-byte boundary. */
4219   alignptr = (unsigned LONG) m->dummytribase;
4220   m->dummytri = (triangle *)
4221     (alignptr + (unsigned LONG) m->triangles.alignbytes -
4222      (alignptr % (unsigned LONG) m->triangles.alignbytes));
4223   /* Initialize the three adjoining triangles to be "outer space."  These  */
4224   /*   will eventually be changed by various bonding operations, but their */
4225   /*   values don't really matter, as long as they can legally be          */
4226   /*   dereferenced.                                                       */
4227   m->dummytri[0] = (triangle) m->dummytri;
4228   m->dummytri[1] = (triangle) m->dummytri;
4229   m->dummytri[2] = (triangle) m->dummytri;
4230   /* Three NULL vertices. */
4231   m->dummytri[3] = (triangle) NULL;
4232   m->dummytri[4] = (triangle) NULL;
4233   m->dummytri[5] = (triangle) NULL;
4234 
4235   if (b->usesegments) {
4236     /* Set up `dummysub', the omnipresent subsegment pointed to by any */
4237     /*   triangle side or subsegment end that isn't attached to a real */
4238     /*   subsegment.                                                   */
4239     m->dummysubbase = (subseg *) trimalloc(subsegbytes +
4240                                            m->subsegs.alignbytes);
4241     /* Align `dummysub' on a `subsegs.alignbytes'-byte boundary. */
4242     alignptr = (unsigned LONG) m->dummysubbase;
4243     m->dummysub = (subseg *)
4244       (alignptr + (unsigned LONG) m->subsegs.alignbytes -
4245        (alignptr % (unsigned LONG) m->subsegs.alignbytes));
4246     /* Initialize the two adjoining subsegments to be the omnipresent      */
4247     /*   subsegment.  These will eventually be changed by various bonding  */
4248     /*   operations, but their values don't really matter, as long as they */
4249     /*   can legally be dereferenced.                                      */
4250     m->dummysub[0] = (subseg) m->dummysub;
4251     m->dummysub[1] = (subseg) m->dummysub;
4252     /* Four NULL vertices. */
4253     m->dummysub[2] = (subseg) NULL;
4254     m->dummysub[3] = (subseg) NULL;
4255     m->dummysub[4] = (subseg) NULL;
4256     m->dummysub[5] = (subseg) NULL;
4257     /* Initialize the two adjoining triangles to be "outer space." */
4258     m->dummysub[6] = (subseg) m->dummytri;
4259     m->dummysub[7] = (subseg) m->dummytri;
4260     /* Set the boundary marker to zero. */
4261     * (int *) (m->dummysub + 8) = 0;
4262 
4263     /* Initialize the three adjoining subsegments of `dummytri' to be */
4264     /*   the omnipresent subsegment.                                  */
4265     m->dummytri[6] = (triangle) m->dummysub;
4266     m->dummytri[7] = (triangle) m->dummysub;
4267     m->dummytri[8] = (triangle) m->dummysub;
4268   }
4269 }
4270 
4271 /*****************************************************************************/
4272 /*                                                                           */
4273 /*  initializevertexpool()   Calculate the size of the vertex data structure */
4274 /*                           and initialize its memory pool.                 */
4275 /*                                                                           */
4276 /*  This routine also computes the `vertexmarkindex' and `vertex2triindex'   */
4277 /*  indices used to find values within each vertex.                          */
4278 /*                                                                           */
4279 /*****************************************************************************/
4280 
4281 #ifdef ANSI_DECLARATORS
4282 static void initializevertexpool(struct mesh *m, struct behavior *b)
4283 #else /* not ANSI_DECLARATORS */
4284 static void initializevertexpool(m, b)
4285 struct mesh *m;
4286 struct behavior *b;
4287 #endif /* not ANSI_DECLARATORS */
4288 
4289 {
4290   int vertexsize;
4291 
4292   /* The index within each vertex at which the boundary marker is found,    */
4293   /*   followed by the vertex type.  Ensure the vertex marker is aligned to */
4294   /*   a sizeof(int)-byte address.                                          */
4295   m->vertexmarkindex = ((m->mesh_dim + m->nextras) * sizeof(REAL) +
4296                         sizeof(int) - 1) /
4297                        sizeof(int);
4298   vertexsize = (m->vertexmarkindex + 2) * sizeof(int);
4299   if (b->poly) {
4300     /* The index within each vertex at which a triangle pointer is found.  */
4301     /*   Ensure the pointer is aligned to a sizeof(triangle)-byte address. */
4302     m->vertex2triindex = (vertexsize + sizeof(triangle) - 1) /
4303                          sizeof(triangle);
4304     vertexsize = (m->vertex2triindex + 1) * sizeof(triangle);
4305   }
4306 
4307   /* Initialize the pool of vertices. */
4308   poolinit(&m->vertices, vertexsize, VERTEXPERBLOCK,
4309            m->invertices > VERTEXPERBLOCK ? m->invertices : VERTEXPERBLOCK,
4310            sizeof(REAL));
4311 }
4312 
4313 /*****************************************************************************/
4314 /*                                                                           */
4315 /*  initializetrisubpools()   Calculate the sizes of the triangle and        */
4316 /*                            subsegment data structures and initialize      */
4317 /*                            their memory pools.                            */
4318 /*                                                                           */
4319 /*  This routine also computes the `highorderindex', `elemattribindex', and  */
4320 /*  `areaboundindex' indices used to find values within each triangle.       */
4321 /*                                                                           */
4322 /*****************************************************************************/
4323 
4324 #ifdef ANSI_DECLARATORS
4325 static void initializetrisubpools(struct mesh *m, struct behavior *b)
4326 #else /* not ANSI_DECLARATORS */
4327 static void initializetrisubpools(m, b)
4328 struct mesh *m;
4329 struct behavior *b;
4330 #endif /* not ANSI_DECLARATORS */
4331 
4332 {
4333   unsigned int trisize;
4334 
4335   /* The index within each triangle at which the extra nodes (above three)  */
4336   /*   associated with high order elements are found.  There are three      */
4337   /*   pointers to other triangles, three pointers to corners, and possibly */
4338   /*   three pointers to subsegments before the extra nodes.                */
4339   m->highorderindex = 6 + (b->usesegments * 3);
4340   /* The number of bytes occupied by a triangle. */
4341   trisize = ((b->order + 1) * (b->order + 2) / 2 + (m->highorderindex - 3)) *
4342             sizeof(triangle);
4343   /* The index within each triangle at which its attributes are found, */
4344   /*   where the index is measured in REALs.                           */
4345   m->elemattribindex = (trisize + sizeof(REAL) - 1) / sizeof(REAL);
4346   /* The index within each triangle at which the maximum area constraint  */
4347   /*   is found, where the index is measured in REALs.  Note that if the  */
4348   /*   `regionattrib' flag is set, an additional attribute will be added. */
4349   m->areaboundindex = m->elemattribindex + m->eextras + b->regionattrib;
4350   /* If triangle attributes or an area bound are needed, increase the number */
4351   /*   of bytes occupied by a triangle.                                      */
4352   if (b->vararea) {
4353     trisize = (m->areaboundindex + 1) * sizeof(REAL);
4354   } else if (m->eextras + b->regionattrib > 0) {
4355     trisize = m->areaboundindex * sizeof(REAL);
4356   }
4357   /* If a Voronoi diagram or triangle neighbor graph is requested, make    */
4358   /*   sure there's room to store an integer index in each triangle.  This */
4359   /*   integer index can occupy the same space as the subsegment pointers  */
4360   /*   or attributes or area constraint or extra nodes.                    */
4361   if ((b->voronoi || b->neighbors) &&
4362       (trisize < 6 * sizeof(triangle) + sizeof(int))) {
4363     trisize = 6 * sizeof(triangle) + sizeof(int);
4364   }
4365 
4366   /* Having determined the memory size of a triangle, initialize the pool. */
4367   poolinit(&m->triangles, trisize, TRIPERBLOCK,
4368            (2 * m->invertices - 2) > TRIPERBLOCK ? (2 * m->invertices - 2) :
4369            TRIPERBLOCK, 4);
4370 
4371   if (b->usesegments) {
4372     /* Initialize the pool of subsegments.  Take into account all eight */
4373     /*   pointers and one boundary marker.                              */
4374     poolinit(&m->subsegs, (int)(8 * sizeof(triangle) + sizeof(int)),
4375              SUBSEGPERBLOCK, SUBSEGPERBLOCK, 4);
4376 
4377     /* Initialize the "outer space" triangle and omnipresent subsegment. */
4378     dummyinit(m, b, (int)m->triangles.itembytes, (int)m->subsegs.itembytes);
4379   } else {
4380     /* Initialize the "outer space" triangle. */
4381     dummyinit(m, b, (int)m->triangles.itembytes, 0);
4382   }
4383 }
4384 
4385 /*****************************************************************************/
4386 /*                                                                           */
4387 /*  triangledealloc()   Deallocate space for a triangle, marking it dead.    */
4388 /*                                                                           */
4389 /*****************************************************************************/
4390 
4391 #ifdef ANSI_DECLARATORS
4392 static void triangledealloc(struct mesh *m, triangle *dyingtriangle)
4393 #else /* not ANSI_DECLARATORS */
4394 static void triangledealloc(m, dyingtriangle)
4395 struct mesh *m;
4396 triangle *dyingtriangle;
4397 #endif /* not ANSI_DECLARATORS */
4398 
4399 {
4400   /* Mark the triangle as dead.  This makes it possible to detect dead */
4401   /*   triangles when traversing the list of all triangles.            */
4402   killtri(dyingtriangle);
4403   pooldealloc(&m->triangles, (VOID *) dyingtriangle);
4404 }
4405 
4406 /*****************************************************************************/
4407 /*                                                                           */
4408 /*  triangletraverse()   Traverse the triangles, skipping dead ones.         */
4409 /*                                                                           */
4410 /*****************************************************************************/
4411 
4412 #ifdef ANSI_DECLARATORS
4413 static triangle *triangletraverse(struct mesh *m)
4414 #else /* not ANSI_DECLARATORS */
4415 static triangle *triangletraverse(m)
4416 struct mesh *m;
4417 #endif /* not ANSI_DECLARATORS */
4418 
4419 {
4420   triangle *newtriangle;
4421 
4422   do {
4423     newtriangle = (triangle *) traverse(&m->triangles);
4424     if (newtriangle == (triangle *) NULL) {
4425       return (triangle *) NULL;
4426     }
4427   } while (deadtri(newtriangle));                         /* Skip dead ones. */
4428   return newtriangle;
4429 }
4430 
4431 /*****************************************************************************/
4432 /*                                                                           */
4433 /*  subsegdealloc()   Deallocate space for a subsegment, marking it dead.    */
4434 /*                                                                           */
4435 /*****************************************************************************/
4436 
4437 #ifdef ANSI_DECLARATORS
4438 static void subsegdealloc(struct mesh *m, subseg *dyingsubseg)
4439 #else /* not ANSI_DECLARATORS */
4440 static void subsegdealloc(m, dyingsubseg)
4441 struct mesh *m;
4442 subseg *dyingsubseg;
4443 #endif /* not ANSI_DECLARATORS */
4444 
4445 {
4446   /* Mark the subsegment as dead.  This makes it possible to detect dead */
4447   /*   subsegments when traversing the list of all subsegments.          */
4448   killsubseg(dyingsubseg);
4449   pooldealloc(&m->subsegs, (VOID *) dyingsubseg);
4450 }
4451 
4452 /*****************************************************************************/
4453 /*                                                                           */
4454 /*  subsegtraverse()   Traverse the subsegments, skipping dead ones.         */
4455 /*                                                                           */
4456 /*****************************************************************************/
4457 
4458 #ifdef ANSI_DECLARATORS
4459 static subseg *subsegtraverse(struct mesh *m)
4460 #else /* not ANSI_DECLARATORS */
4461 static subseg *subsegtraverse(m)
4462 struct mesh *m;
4463 #endif /* not ANSI_DECLARATORS */
4464 
4465 {
4466   subseg *newsubseg;
4467 
4468   do {
4469     newsubseg = (subseg *) traverse(&m->subsegs);
4470     if (newsubseg == (subseg *) NULL) {
4471       return (subseg *) NULL;
4472     }
4473   } while (deadsubseg(newsubseg));                        /* Skip dead ones. */
4474   return newsubseg;
4475 }
4476 
4477 /*****************************************************************************/
4478 /*                                                                           */
4479 /*  vertexdealloc()   Deallocate space for a vertex, marking it dead.        */
4480 /*                                                                           */
4481 /*****************************************************************************/
4482 
4483 #ifndef CDT_ONLY
4484 
4485 #ifdef ANSI_DECLARATORS
4486 static void vertexdealloc(struct mesh *m, vertex dyingvertex)
4487 #else /* not ANSI_DECLARATORS */
4488 static void vertexdealloc(m, dyingvertex)
4489 struct mesh *m;
4490 vertex dyingvertex;
4491 #endif /* not ANSI_DECLARATORS */
4492 
4493 {
4494   /* Mark the vertex as dead.  This makes it possible to detect dead */
4495   /*   vertices when traversing the list of all vertices.            */
4496   setvertextype(dyingvertex, DEADVERTEX);
4497   pooldealloc(&m->vertices, (VOID *) dyingvertex);
4498 }
4499 
4500 #endif /* not CDT_ONLY */
4501 
4502 /*****************************************************************************/
4503 /*                                                                           */
4504 /*  vertextraverse()   Traverse the vertices, skipping dead ones.            */
4505 /*                                                                           */
4506 /*****************************************************************************/
4507 
4508 #ifdef ANSI_DECLARATORS
4509 static vertex vertextraverse(struct mesh *m)
4510 #else /* not ANSI_DECLARATORS */
4511 static vertex vertextraverse(m)
4512 struct mesh *m;
4513 #endif /* not ANSI_DECLARATORS */
4514 
4515 {
4516   vertex newvertex;
4517 
4518   do {
4519     newvertex = (vertex) traverse(&m->vertices);
4520     if (newvertex == (vertex) NULL) {
4521       return (vertex) NULL;
4522     }
4523   } while (vertextype(newvertex) == DEADVERTEX);          /* Skip dead ones. */
4524   return newvertex;
4525 }
4526 
4527 /*****************************************************************************/
4528 /*                                                                           */
4529 /*  badsubsegdealloc()   Deallocate space for a bad subsegment, marking it   */
4530 /*                       dead.                                               */
4531 /*                                                                           */
4532 /*****************************************************************************/
4533 
4534 #ifndef CDT_ONLY
4535 
4536 #ifdef ANSI_DECLARATORS
4537 static void badsubsegdealloc(struct mesh *m, struct badsubseg *dyingseg)
4538 #else /* not ANSI_DECLARATORS */
4539 static void badsubsegdealloc(m, dyingseg)
4540 struct mesh *m;
4541 struct badsubseg *dyingseg;
4542 #endif /* not ANSI_DECLARATORS */
4543 
4544 {
4545   /* Set subsegment's origin to NULL.  This makes it possible to detect dead */
4546   /*   badsubsegs when traversing the list of all badsubsegs             .   */
4547   dyingseg->subsegorg = (vertex) NULL;
4548   pooldealloc(&m->badsubsegs, (VOID *) dyingseg);
4549 }
4550 
4551 #endif /* not CDT_ONLY */
4552 
4553 /*****************************************************************************/
4554 /*                                                                           */
4555 /*  badsubsegtraverse()   Traverse the bad subsegments, skipping dead ones.  */
4556 /*                                                                           */
4557 /*****************************************************************************/
4558 
4559 #ifndef CDT_ONLY
4560 
4561 #ifdef ANSI_DECLARATORS
4562 struct badsubseg *badsubsegtraverse(struct mesh *m)
4563 #else /* not ANSI_DECLARATORS */
4564 struct badsubseg *badsubsegtraverse(m)
4565 struct mesh *m;
4566 #endif /* not ANSI_DECLARATORS */
4567 
4568 {
4569   struct badsubseg *newseg;
4570 
4571   do {
4572     newseg = (struct badsubseg *) traverse(&m->badsubsegs);
4573     if (newseg == (struct badsubseg *) NULL) {
4574       return (struct badsubseg *) NULL;
4575     }
4576   } while (newseg->subsegorg == (vertex) NULL);           /* Skip dead ones. */
4577   return newseg;
4578 }
4579 
4580 #endif /* not CDT_ONLY */
4581 
4582 /*****************************************************************************/
4583 /*                                                                           */
4584 /*  getvertex()   Get a specific vertex, by number, from the list.           */
4585 /*                                                                           */
4586 /*  The first vertex is number 'firstnumber'.                                */
4587 /*                                                                           */
4588 /*  Note that this takes O(n) time (with a small constant, if VERTEXPERBLOCK */
4589 /*  is large).  I don't care to take the trouble to make it work in constant */
4590 /*  time.                                                                    */
4591 /*                                                                           */
4592 /*****************************************************************************/
4593 
4594 #ifdef ANSI_DECLARATORS
4595 static vertex getvertex(struct mesh *m, struct behavior *b, unsigned int number)
4596 #else /* not ANSI_DECLARATORS */
4597 static vertex getvertex(m, b, number)
4598 struct mesh *m;
4599 struct behavior *b;
4600 unsigned int number;
4601 #endif /* not ANSI_DECLARATORS */
4602 
4603 {
4604   VOID **getblock;
4605   char *foundvertex;
4606   unsigned LONG alignptr;
4607   int current;
4608 
4609   getblock = m->vertices.firstblock;
4610   current = b->firstnumber;
4611 
4612   /* Find the right block. */
4613   if (current + m->vertices.itemsfirstblock <= number) {
4614     getblock = (VOID **) *getblock;
4615     current += (int)m->vertices.itemsfirstblock;
4616     while (current + m->vertices.itemsperblock <= number) {
4617       getblock = (VOID **) *getblock;
4618       current += (int)m->vertices.itemsperblock;
4619     }
4620   }
4621 
4622   /* Now find the right vertex. */
4623   alignptr = (unsigned LONG) (getblock + 1);
4624   foundvertex = (char *) (alignptr + (unsigned LONG) m->vertices.alignbytes -
4625                           (alignptr % (unsigned LONG) m->vertices.alignbytes));
4626   return (vertex) (foundvertex + m->vertices.itembytes * (number - current));
4627 }
4628 
4629 /*****************************************************************************/
4630 /*                                                                           */
4631 /*  triangledeinit()   Free all remaining allocated memory.                  */
4632 /*                                                                           */
4633 /*****************************************************************************/
4634 
4635 #ifdef ANSI_DECLARATORS
4636 static void triangledeinit(struct mesh *m, struct behavior *b)
4637 #else /* not ANSI_DECLARATORS */
4638 static void triangledeinit(m, b)
4639 struct mesh *m;
4640 struct behavior *b;
4641 #endif /* not ANSI_DECLARATORS */
4642 
4643 {
4644   pooldeinit(&m->triangles);
4645   trifree((VOID *) m->dummytribase);
4646   if (b->usesegments) {
4647     pooldeinit(&m->subsegs);
4648     trifree((VOID *) m->dummysubbase);
4649   }
4650   pooldeinit(&m->vertices);
4651 #ifndef CDT_ONLY
4652   if (b->quality) {
4653     pooldeinit(&m->badsubsegs);
4654     if ((b->minangle > 0.0) || b->vararea || b->fixedarea || b->usertest) {
4655       pooldeinit(&m->badtriangles);
4656       pooldeinit(&m->flipstackers);
4657     }
4658   }
4659 #endif /* not CDT_ONLY */
4660 }
4661 
4662 /**                                                                         **/
4663 /**                                                                         **/
4664 /********* Memory management routines end here                       *********/
4665 
4666 /********* Constructors begin here                                   *********/
4667 /**                                                                         **/
4668 /**                                                                         **/
4669 
4670 /*****************************************************************************/
4671 /*                                                                           */
4672 /*  maketriangle()   Create a new triangle with orientation zero.            */
4673 /*                                                                           */
4674 /*****************************************************************************/
4675 
4676 #ifdef ANSI_DECLARATORS
4677 static void maketriangle(struct mesh *m, struct behavior *b, struct otri *newotri)
4678 #else /* not ANSI_DECLARATORS */
4679 static void maketriangle(m, b, newotri)
4680 struct mesh *m;
4681 struct behavior *b;
4682 struct otri *newotri;
4683 #endif /* not ANSI_DECLARATORS */
4684 
4685 {
4686   int i;
4687 
4688   newotri->tri = (triangle *) poolalloc(&m->triangles);
4689   /* Initialize the three adjoining triangles to be "outer space". */
4690   newotri->tri[0] = (triangle) m->dummytri;
4691   newotri->tri[1] = (triangle) m->dummytri;
4692   newotri->tri[2] = (triangle) m->dummytri;
4693   /* Three NULL vertices. */
4694   newotri->tri[3] = (triangle) NULL;
4695   newotri->tri[4] = (triangle) NULL;
4696   newotri->tri[5] = (triangle) NULL;
4697   if (b->usesegments) {
4698     /* Initialize the three adjoining subsegments to be the omnipresent */
4699     /*   subsegment.                                                    */
4700     newotri->tri[6] = (triangle) m->dummysub;
4701     newotri->tri[7] = (triangle) m->dummysub;
4702     newotri->tri[8] = (triangle) m->dummysub;
4703   }
4704   for (i = 0; i < m->eextras; i++) {
4705     setelemattribute(*newotri, i, 0.0);
4706   }
4707   if (b->vararea) {
4708     setareabound(*newotri, -1.0);
4709   }
4710 
4711   newotri->orient = 0;
4712 }
4713 
4714 /*****************************************************************************/
4715 /*                                                                           */
4716 /*  makesubseg()   Create a new subsegment with orientation zero.            */
4717 /*                                                                           */
4718 /*****************************************************************************/
4719 
4720 #ifdef ANSI_DECLARATORS
4721 static void makesubseg(struct mesh *m, struct osub *newsubseg)
4722 #else /* not ANSI_DECLARATORS */
4723 static void makesubseg(m, newsubseg)
4724 struct mesh *m;
4725 struct osub *newsubseg;
4726 #endif /* not ANSI_DECLARATORS */
4727 
4728 {
4729   newsubseg->ss = (subseg *) poolalloc(&m->subsegs);
4730   /* Initialize the two adjoining subsegments to be the omnipresent */
4731   /*   subsegment.                                                  */
4732   newsubseg->ss[0] = (subseg) m->dummysub;
4733   newsubseg->ss[1] = (subseg) m->dummysub;
4734   /* Four NULL vertices. */
4735   newsubseg->ss[2] = (subseg) NULL;
4736   newsubseg->ss[3] = (subseg) NULL;
4737   newsubseg->ss[4] = (subseg) NULL;
4738   newsubseg->ss[5] = (subseg) NULL;
4739   /* Initialize the two adjoining triangles to be "outer space." */
4740   newsubseg->ss[6] = (subseg) m->dummytri;
4741   newsubseg->ss[7] = (subseg) m->dummytri;
4742   /* Set the boundary marker to zero. */
4743   setmark(*newsubseg, 0);
4744 
4745   newsubseg->ssorient = 0;
4746 }
4747 
4748 /**                                                                         **/
4749 /**                                                                         **/
4750 /********* Constructors end here                                     *********/
4751 
4752 /********* Geometric primitives begin here                           *********/
4753 /**                                                                         **/
4754 /**                                                                         **/
4755 
4756 /* The adaptive exact arithmetic geometric predicates implemented herein are */
4757 /*   described in detail in my paper, "Adaptive Precision Floating-Point     */
4758 /*   Arithmetic and Fast Robust Geometric Predicates."  See the header for a */
4759 /*   full citation.                                                          */
4760 
4761 /* Which of the following two methods of finding the absolute values is      */
4762 /*   fastest is compiler-dependent.  A few compilers can inline and optimize */
4763 /*   the fabs() call; but most will incur the overhead of a function call,   */
4764 /*   which is disastrously slow.  A faster way on IEEE machines might be to  */
4765 /*   mask the appropriate bit, but that's difficult to do in C without       */
4766 /*   forcing the value to be stored to memory (rather than be kept in the    */
4767 /*   register to which the optimizer assigned it).                           */
4768 
4769 #define Absolute(a)  ((a) >= 0.0 ? (a) : -(a))
4770 /* #define Absolute(a)  fabs(a) */
4771 
4772 /* Many of the operations are broken up into two pieces, a main part that    */
4773 /*   performs an approximate operation, and a "tail" that computes the       */
4774 /*   roundoff error of that operation.                                       */
4775 /*                                                                           */
4776 /* The operations Fast_Two_Sum(), Fast_Two_Diff(), Two_Sum(), Two_Diff(),    */
4777 /*   Split(), and Two_Product() are all implemented as described in the      */
4778 /*   reference.  Each of these macros requires certain variables to be       */
4779 /*   defined in the calling routine.  The variables `bvirt', `c', `abig',    */
4780 /*   `_i', `_j', `_k', `_l', `_m', and `_n' are declared `INEXACT' because   */
4781 /*   they store the result of an operation that may incur roundoff error.    */
4782 /*   The input parameter `x' (or the highest numbered `x_' parameter) must   */
4783 /*   also be declared `INEXACT'.                                             */
4784 
4785 #define Fast_Two_Sum_Tail(a, b, x, y) \
4786   bvirt = x - a; \
4787   y = b - bvirt
4788 
4789 #define Fast_Two_Sum(a, b, x, y) \
4790   x = (REAL) (a + b); \
4791   Fast_Two_Sum_Tail(a, b, x, y)
4792 
4793 #define Two_Sum_Tail(a, b, x, y) \
4794   bvirt = (REAL) (x - a); \
4795   avirt = x - bvirt; \
4796   bround = b - bvirt; \
4797   around = a - avirt; \
4798   y = around + bround
4799 
4800 #define Two_Sum(a, b, x, y) \
4801   x = (REAL) (a + b); \
4802   Two_Sum_Tail(a, b, x, y)
4803 
4804 #define Two_Diff_Tail(a, b, x, y) \
4805   bvirt = (REAL) (a - x); \
4806   avirt = x + bvirt; \
4807   bround = bvirt - b; \
4808   around = a - avirt; \
4809   y = around + bround
4810 
4811 #define Two_Diff(a, b, x, y) \
4812   x = (REAL) (a - b); \
4813   Two_Diff_Tail(a, b, x, y)
4814 
4815 #define Split(a, ahi, alo) \
4816   c = (REAL) (splitter * a); \
4817   abig = (REAL) (c - a); \
4818   ahi = c - abig; \
4819   alo = a - ahi
4820 
4821 #define Two_Product_Tail(a, b, x, y) \
4822   Split(a, ahi, alo); \
4823   Split(b, bhi, blo); \
4824   err1 = x - (ahi * bhi); \
4825   err2 = err1 - (alo * bhi); \
4826   err3 = err2 - (ahi * blo); \
4827   y = (alo * blo) - err3
4828 
4829 #define Two_Product(a, b, x, y) \
4830   x = (REAL) (a * b); \
4831   Two_Product_Tail(a, b, x, y)
4832 
4833 /* Two_Product_Presplit() is Two_Product() where one of the inputs has       */
4834 /*   already been split.  Avoids redundant splitting.                        */
4835 
4836 #define Two_Product_Presplit(a, b, bhi, blo, x, y) \
4837   x = (REAL) (a * b); \
4838   Split(a, ahi, alo); \
4839   err1 = x - (ahi * bhi); \
4840   err2 = err1 - (alo * bhi); \
4841   err3 = err2 - (ahi * blo); \
4842   y = (alo * blo) - err3
4843 
4844 /* Square() can be done more quickly than Two_Product().                     */
4845 
4846 #define Square_Tail(a, x, y) \
4847   Split(a, ahi, alo); \
4848   err1 = x - (ahi * ahi); \
4849   err3 = err1 - ((ahi + ahi) * alo); \
4850   y = (alo * alo) - err3
4851 
4852 #define Square(a, x, y) \
4853   x = (REAL) (a * a); \
4854   Square_Tail(a, x, y)
4855 
4856 /* Macros for summing expansions of various fixed lengths.  These are all    */
4857 /*   unrolled versions of Expansion_Sum().                                   */
4858 
4859 #define Two_One_Sum(a1, a0, b, x2, x1, x0) \
4860   Two_Sum(a0, b , _i, x0); \
4861   Two_Sum(a1, _i, x2, x1)
4862 
4863 #define Two_One_Diff(a1, a0, b, x2, x1, x0) \
4864   Two_Diff(a0, b , _i, x0); \
4865   Two_Sum( a1, _i, x2, x1)
4866 
4867 #define Two_Two_Sum(a1, a0, b1, b0, x3, x2, x1, x0) \
4868   Two_One_Sum(a1, a0, b0, _j, _0, x0); \
4869   Two_One_Sum(_j, _0, b1, x3, x2, x1)
4870 
4871 #define Two_Two_Diff(a1, a0, b1, b0, x3, x2, x1, x0) \
4872   Two_One_Diff(a1, a0, b0, _j, _0, x0); \
4873   Two_One_Diff(_j, _0, b1, x3, x2, x1)
4874 
4875 /* Macro for multiplying a two-component expansion by a single component.    */
4876 
4877 #define Two_One_Product(a1, a0, b, x3, x2, x1, x0) \
4878   Split(b, bhi, blo); \
4879   Two_Product_Presplit(a0, b, bhi, blo, _i, x0); \
4880   Two_Product_Presplit(a1, b, bhi, blo, _j, _0); \
4881   Two_Sum(_i, _0, _k, x1); \
4882   Fast_Two_Sum(_j, _k, x3, x2)
4883 
4884 /*****************************************************************************/
4885 /*                                                                           */
4886 /*  exactinit()   Initialize the variables used for exact arithmetic.        */
4887 /*                                                                           */
4888 /*  `epsilon' is the largest power of two such that 1.0 + epsilon = 1.0 in   */
4889 /*  floating-point arithmetic.  `epsilon' bounds the relative roundoff       */
4890 /*  error.  It is used for floating-point error analysis.                    */
4891 /*                                                                           */
4892 /*  `splitter' is used to split floating-point numbers into two half-        */
4893 /*  length significands for exact multiplication.                            */
4894 /*                                                                           */
4895 /*  I imagine that a highly optimizing compiler might be too smart for its   */
4896 /*  own good, and somehow cause this routine to fail, if it pretends that    */
4897 /*  floating-point arithmetic is too much like real arithmetic.              */
4898 /*                                                                           */
4899 /*  Don't change this routine unless you fully understand it.                */
4900 /*                                                                           */
4901 /*****************************************************************************/
4902 
exactinit()4903 static void exactinit()
4904 {
4905   REAL half;
4906   REAL check, lastcheck;
4907   int every_other;
4908 #ifdef LINUX
4909   int cword;
4910 #endif /* LINUX */
4911 
4912 #ifdef CPU86
4913 #ifdef SINGLE
4914   _control87(_PC_24, _MCW_PC); /* Set FPU control word for single precision. */
4915 #else /* not SINGLE */
4916   _control87(_PC_53, _MCW_PC); /* Set FPU control word for double precision. */
4917 #endif /* not SINGLE */
4918 #endif /* CPU86 */
4919 #ifdef LINUX
4920 #ifdef SINGLE
4921   /*  cword = 4223; */
4922   cword = 4210;                 /* set FPU control word for single precision */
4923 #else /* not SINGLE */
4924   /*  cword = 4735; */
4925   cword = 4722;                 /* set FPU control word for double precision */
4926 #endif /* not SINGLE */
4927   _FPU_SETCW(cword);
4928 #endif /* LINUX */
4929 
4930   every_other = 1;
4931   half = 0.5;
4932   epsilon = 1.0;
4933   splitter = 1.0;
4934   check = 1.0;
4935   /* Repeatedly divide `epsilon' by two until it is too small to add to      */
4936   /*   one without causing roundoff.  (Also check if the sum is equal to     */
4937   /*   the previous sum, for machines that round up instead of using exact   */
4938   /*   rounding.  Not that these routines will work on such machines.)       */
4939   do {
4940     lastcheck = check;
4941     epsilon *= half;
4942     if (every_other) {
4943       splitter *= 2.0;
4944     }
4945     every_other = !every_other;
4946     check = 1.0 + epsilon;
4947   } while ((check != 1.0) && (check != lastcheck));
4948   splitter += 1.0;
4949   /* Error bounds for orientation and incircle tests. */
4950   resulterrbound = (3.0 + 8.0 * epsilon) * epsilon;
4951   ccwerrboundA = (3.0 + 16.0 * epsilon) * epsilon;
4952   ccwerrboundB = (2.0 + 12.0 * epsilon) * epsilon;
4953   ccwerrboundC = (9.0 + 64.0 * epsilon) * epsilon * epsilon;
4954   iccerrboundA = (10.0 + 96.0 * epsilon) * epsilon;
4955   iccerrboundB = (4.0 + 48.0 * epsilon) * epsilon;
4956   iccerrboundC = (44.0 + 576.0 * epsilon) * epsilon * epsilon;
4957   o3derrboundA = (7.0 + 56.0 * epsilon) * epsilon;
4958   o3derrboundB = (3.0 + 28.0 * epsilon) * epsilon;
4959   o3derrboundC = (26.0 + 288.0 * epsilon) * epsilon * epsilon;
4960 }
4961 
4962 /*****************************************************************************/
4963 /*                                                                           */
4964 /*  fast_expansion_sum_zeroelim()   Sum two expansions, eliminating zero     */
4965 /*                                  components from the output expansion.    */
4966 /*                                                                           */
4967 /*  Sets h = e + f.  See my Robust Predicates paper for details.             */
4968 /*                                                                           */
4969 /*  If round-to-even is used (as with IEEE 754), maintains the strongly      */
4970 /*  nonoverlapping property.  (That is, if e is strongly nonoverlapping, h   */
4971 /*  will be also.)  Does NOT maintain the nonoverlapping or nonadjacent      */
4972 /*  properties.                                                              */
4973 /*                                                                           */
4974 /*****************************************************************************/
4975 
4976 #ifdef ANSI_DECLARATORS
4977 static int fast_expansion_sum_zeroelim(int elen, REAL *e, int flen, REAL *f, REAL *h)
4978 #else /* not ANSI_DECLARATORS */
4979 static int fast_expansion_sum_zeroelim(elen, e, flen, f, h)  /* h cannot be e or f. */
4980 int elen;
4981 REAL *e;
4982 int flen;
4983 REAL *f;
4984 REAL *h;
4985 #endif /* not ANSI_DECLARATORS */
4986 
4987 {
4988   REAL Q;
4989   INEXACT REAL Qnew;
4990   INEXACT REAL hh;
4991   INEXACT REAL bvirt;
4992   REAL avirt, bround, around;
4993   int eindex, findex, hindex;
4994   REAL enow, fnow;
4995 
4996   enow = e[0];
4997   fnow = f[0];
4998   eindex = findex = 0;
4999   if ((fnow > enow) == (fnow > -enow)) {
5000     Q = enow;
5001     enow = e[++eindex];
5002   } else {
5003     Q = fnow;
5004     fnow = f[++findex];
5005   }
5006   hindex = 0;
5007   if ((eindex < elen) && (findex < flen)) {
5008     if ((fnow > enow) == (fnow > -enow)) {
5009       Fast_Two_Sum(enow, Q, Qnew, hh);
5010       enow = e[++eindex];
5011     } else {
5012       Fast_Two_Sum(fnow, Q, Qnew, hh);
5013       fnow = f[++findex];
5014     }
5015     Q = Qnew;
5016     if (hh != 0.0) {
5017       h[hindex++] = hh;
5018     }
5019     while ((eindex < elen) && (findex < flen)) {
5020       if ((fnow > enow) == (fnow > -enow)) {
5021         Two_Sum(Q, enow, Qnew, hh);
5022         enow = e[++eindex];
5023       } else {
5024         Two_Sum(Q, fnow, Qnew, hh);
5025         fnow = f[++findex];
5026       }
5027       Q = Qnew;
5028       if (hh != 0.0) {
5029         h[hindex++] = hh;
5030       }
5031     }
5032   }
5033   while (eindex < elen) {
5034     Two_Sum(Q, enow, Qnew, hh);
5035     enow = e[++eindex];
5036     Q = Qnew;
5037     if (hh != 0.0) {
5038       h[hindex++] = hh;
5039     }
5040   }
5041   while (findex < flen) {
5042     Two_Sum(Q, fnow, Qnew, hh);
5043     fnow = f[++findex];
5044     Q = Qnew;
5045     if (hh != 0.0) {
5046       h[hindex++] = hh;
5047     }
5048   }
5049   if ((Q != 0.0) || (hindex == 0)) {
5050     h[hindex++] = Q;
5051   }
5052   return hindex;
5053 }
5054 
5055 /*****************************************************************************/
5056 /*                                                                           */
5057 /*  scale_expansion_zeroelim()   Multiply an expansion by a scalar,          */
5058 /*                               eliminating zero components from the        */
5059 /*                               output expansion.                           */
5060 /*                                                                           */
5061 /*  Sets h = be.  See my Robust Predicates paper for details.                */
5062 /*                                                                           */
5063 /*  Maintains the nonoverlapping property.  If round-to-even is used (as     */
5064 /*  with IEEE 754), maintains the strongly nonoverlapping and nonadjacent    */
5065 /*  properties as well.  (That is, if e has one of these properties, so      */
5066 /*  will h.)                                                                 */
5067 /*                                                                           */
5068 /*****************************************************************************/
5069 
5070 #ifdef ANSI_DECLARATORS
5071 static int scale_expansion_zeroelim(int elen, REAL *e, REAL b, REAL *h)
5072 #else /* not ANSI_DECLARATORS */
5073 static int scale_expansion_zeroelim(elen, e, b, h)   /* e and h cannot be the same. */
5074 int elen;
5075 REAL *e;
5076 REAL b;
5077 REAL *h;
5078 #endif /* not ANSI_DECLARATORS */
5079 
5080 {
5081   INEXACT REAL Q, sum;
5082   REAL hh;
5083   INEXACT REAL product1;
5084   REAL product0;
5085   int eindex, hindex;
5086   REAL enow;
5087   INEXACT REAL bvirt;
5088   REAL avirt, bround, around;
5089   INEXACT REAL c;
5090   INEXACT REAL abig;
5091   REAL ahi, alo, bhi, blo;
5092   REAL err1, err2, err3;
5093 
5094   Split(b, bhi, blo);
5095   Two_Product_Presplit(e[0], b, bhi, blo, Q, hh);
5096   hindex = 0;
5097   if (hh != 0) {
5098     h[hindex++] = hh;
5099   }
5100   for (eindex = 1; eindex < elen; eindex++) {
5101     enow = e[eindex];
5102     Two_Product_Presplit(enow, b, bhi, blo, product1, product0);
5103     Two_Sum(Q, product0, sum, hh);
5104     if (hh != 0) {
5105       h[hindex++] = hh;
5106     }
5107     Fast_Two_Sum(product1, sum, Q, hh);
5108     if (hh != 0) {
5109       h[hindex++] = hh;
5110     }
5111   }
5112   if ((Q != 0.0) || (hindex == 0)) {
5113     h[hindex++] = Q;
5114   }
5115   return hindex;
5116 }
5117 
5118 /*****************************************************************************/
5119 /*                                                                           */
5120 /*  estimate()   Produce a one-word estimate of an expansion's value.        */
5121 /*                                                                           */
5122 /*  See my Robust Predicates paper for details.                              */
5123 /*                                                                           */
5124 /*****************************************************************************/
5125 
5126 #ifdef ANSI_DECLARATORS
5127 static REAL estimate(int elen, REAL *e)
5128 #else /* not ANSI_DECLARATORS */
5129 static REAL estimate(elen, e)
5130 int elen;
5131 REAL *e;
5132 #endif /* not ANSI_DECLARATORS */
5133 
5134 {
5135   REAL Q;
5136   int eindex;
5137 
5138   Q = e[0];
5139   for (eindex = 1; eindex < elen; eindex++) {
5140     Q += e[eindex];
5141   }
5142   return Q;
5143 }
5144 
5145 /*****************************************************************************/
5146 /*                                                                           */
5147 /*  counterclockwise()   Return a positive value if the points pa, pb, and   */
5148 /*                       pc occur in counterclockwise order; a negative      */
5149 /*                       value if they occur in clockwise order; and zero    */
5150 /*                       if they are collinear.  The result is also a rough  */
5151 /*                       approximation of twice the signed area of the       */
5152 /*                       triangle defined by the three points.               */
5153 /*                                                                           */
5154 /*  Uses exact arithmetic if necessary to ensure a correct answer.  The      */
5155 /*  result returned is the determinant of a matrix.  This determinant is     */
5156 /*  computed adaptively, in the sense that exact arithmetic is used only to  */
5157 /*  the degree it is needed to ensure that the returned value has the        */
5158 /*  correct sign.  Hence, this function is usually quite fast, but will run  */
5159 /*  more slowly when the input points are collinear or nearly so.            */
5160 /*                                                                           */
5161 /*  See my Robust Predicates paper for details.                              */
5162 /*                                                                           */
5163 /*****************************************************************************/
5164 
5165 #ifdef ANSI_DECLARATORS
5166 static REAL counterclockwiseadapt(vertex pa, vertex pb, vertex pc, REAL detsum)
5167 #else /* not ANSI_DECLARATORS */
5168 static REAL counterclockwiseadapt(pa, pb, pc, detsum)
5169 vertex pa;
5170 vertex pb;
5171 vertex pc;
5172 REAL detsum;
5173 #endif /* not ANSI_DECLARATORS */
5174 
5175 {
5176   INEXACT REAL acx, acy, bcx, bcy;
5177   REAL acxtail, acytail, bcxtail, bcytail;
5178   INEXACT REAL detleft, detright;
5179   REAL detlefttail, detrighttail;
5180   REAL det, errbound;
5181   REAL B[4], C1[8], C2[12], D[16];
5182   INEXACT REAL B3;
5183   int C1length, C2length, Dlength;
5184   REAL u[4];
5185   INEXACT REAL u3;
5186   INEXACT REAL s1, t1;
5187   REAL s0, t0;
5188 
5189   INEXACT REAL bvirt;
5190   REAL avirt, bround, around;
5191   INEXACT REAL c;
5192   INEXACT REAL abig;
5193   REAL ahi, alo, bhi, blo;
5194   REAL err1, err2, err3;
5195   INEXACT REAL _i, _j;
5196   REAL _0;
5197 
5198   acx = (REAL) (pa[0] - pc[0]);
5199   bcx = (REAL) (pb[0] - pc[0]);
5200   acy = (REAL) (pa[1] - pc[1]);
5201   bcy = (REAL) (pb[1] - pc[1]);
5202 
5203   Two_Product(acx, bcy, detleft, detlefttail);
5204   Two_Product(acy, bcx, detright, detrighttail);
5205 
5206   Two_Two_Diff(detleft, detlefttail, detright, detrighttail,
5207                B3, B[2], B[1], B[0]);
5208   B[3] = B3;
5209 
5210   det = estimate(4, B);
5211   errbound = ccwerrboundB * detsum;
5212   if ((det >= errbound) || (-det >= errbound)) {
5213     return det;
5214   }
5215 
5216   Two_Diff_Tail(pa[0], pc[0], acx, acxtail);
5217   Two_Diff_Tail(pb[0], pc[0], bcx, bcxtail);
5218   Two_Diff_Tail(pa[1], pc[1], acy, acytail);
5219   Two_Diff_Tail(pb[1], pc[1], bcy, bcytail);
5220 
5221   if ((acxtail == 0.0) && (acytail == 0.0)
5222       && (bcxtail == 0.0) && (bcytail == 0.0)) {
5223     return det;
5224   }
5225 
5226   errbound = ccwerrboundC * detsum + resulterrbound * Absolute(det);
5227   det += (acx * bcytail + bcy * acxtail)
5228        - (acy * bcxtail + bcx * acytail);
5229   if ((det >= errbound) || (-det >= errbound)) {
5230     return det;
5231   }
5232 
5233   Two_Product(acxtail, bcy, s1, s0);
5234   Two_Product(acytail, bcx, t1, t0);
5235   Two_Two_Diff(s1, s0, t1, t0, u3, u[2], u[1], u[0]);
5236   u[3] = u3;
5237   C1length = fast_expansion_sum_zeroelim(4, B, 4, u, C1);
5238 
5239   Two_Product(acx, bcytail, s1, s0);
5240   Two_Product(acy, bcxtail, t1, t0);
5241   Two_Two_Diff(s1, s0, t1, t0, u3, u[2], u[1], u[0]);
5242   u[3] = u3;
5243   C2length = fast_expansion_sum_zeroelim(C1length, C1, 4, u, C2);
5244 
5245   Two_Product(acxtail, bcytail, s1, s0);
5246   Two_Product(acytail, bcxtail, t1, t0);
5247   Two_Two_Diff(s1, s0, t1, t0, u3, u[2], u[1], u[0]);
5248   u[3] = u3;
5249   Dlength = fast_expansion_sum_zeroelim(C2length, C2, 4, u, D);
5250 
5251   return(D[Dlength - 1]);
5252 }
5253 
5254 #ifdef ANSI_DECLARATORS
5255 static REAL counterclockwise(struct mesh *m, struct behavior *b,
5256                       vertex pa, vertex pb, vertex pc)
5257 #else /* not ANSI_DECLARATORS */
5258 static REAL counterclockwise(m, b, pa, pb, pc)
5259 struct mesh *m;
5260 struct behavior *b;
5261 vertex pa;
5262 vertex pb;
5263 vertex pc;
5264 #endif /* not ANSI_DECLARATORS */
5265 
5266 {
5267   REAL detleft, detright, det;
5268   REAL detsum, errbound;
5269 
5270   m->counterclockcount++;
5271 
5272   detleft = (pa[0] - pc[0]) * (pb[1] - pc[1]);
5273   detright = (pa[1] - pc[1]) * (pb[0] - pc[0]);
5274   det = detleft - detright;
5275 
5276   if (b->noexact) {
5277     return det;
5278   }
5279 
5280   if (detleft > 0.0) {
5281     if (detright <= 0.0) {
5282       return det;
5283     } else {
5284       detsum = detleft + detright;
5285     }
5286   } else if (detleft < 0.0) {
5287     if (detright >= 0.0) {
5288       return det;
5289     } else {
5290       detsum = -detleft - detright;
5291     }
5292   } else {
5293     return det;
5294   }
5295 
5296   errbound = ccwerrboundA * detsum;
5297   if ((det >= errbound) || (-det >= errbound)) {
5298     return det;
5299   }
5300 
5301   return counterclockwiseadapt(pa, pb, pc, detsum);
5302 }
5303 
5304 /*****************************************************************************/
5305 /*                                                                           */
5306 /*  incircle()   Return a positive value if the point pd lies inside the     */
5307 /*               circle passing through pa, pb, and pc; a negative value if  */
5308 /*               it lies outside; and zero if the four points are cocircular.*/
5309 /*               The points pa, pb, and pc must be in counterclockwise       */
5310 /*               order, or the sign of the result will be reversed.          */
5311 /*                                                                           */
5312 /*  Uses exact arithmetic if necessary to ensure a correct answer.  The      */
5313 /*  result returned is the determinant of a matrix.  This determinant is     */
5314 /*  computed adaptively, in the sense that exact arithmetic is used only to  */
5315 /*  the degree it is needed to ensure that the returned value has the        */
5316 /*  correct sign.  Hence, this function is usually quite fast, but will run  */
5317 /*  more slowly when the input points are cocircular or nearly so.           */
5318 /*                                                                           */
5319 /*  See my Robust Predicates paper for details.                              */
5320 /*                                                                           */
5321 /*****************************************************************************/
5322 
5323 #ifdef ANSI_DECLARATORS
5324 static REAL incircleadapt(vertex pa, vertex pb, vertex pc, vertex pd, REAL permanent)
5325 #else /* not ANSI_DECLARATORS */
5326 static REAL incircleadapt(pa, pb, pc, pd, permanent)
5327 vertex pa;
5328 vertex pb;
5329 vertex pc;
5330 vertex pd;
5331 REAL permanent;
5332 #endif /* not ANSI_DECLARATORS */
5333 
5334 {
5335   INEXACT REAL adx, bdx, cdx, ady, bdy, cdy;
5336   REAL det, errbound;
5337 
5338   INEXACT REAL bdxcdy1, cdxbdy1, cdxady1, adxcdy1, adxbdy1, bdxady1;
5339   REAL bdxcdy0, cdxbdy0, cdxady0, adxcdy0, adxbdy0, bdxady0;
5340   REAL bc[4], ca[4], ab[4];
5341   INEXACT REAL bc3, ca3, ab3;
5342   REAL axbc[8], axxbc[16], aybc[8], ayybc[16], adet[32];
5343   int axbclen, axxbclen, aybclen, ayybclen, alen;
5344   REAL bxca[8], bxxca[16], byca[8], byyca[16], bdet[32];
5345   int bxcalen, bxxcalen, bycalen, byycalen, blen;
5346   REAL cxab[8], cxxab[16], cyab[8], cyyab[16], cdet[32];
5347   int cxablen, cxxablen, cyablen, cyyablen, clen;
5348   REAL abdet[64];
5349   int ablen;
5350   REAL fin1[1152], fin2[1152];
5351   REAL *finnow, *finother, *finswap;
5352   int finlength;
5353 
5354   REAL adxtail, bdxtail, cdxtail, adytail, bdytail, cdytail;
5355   INEXACT REAL adxadx1, adyady1, bdxbdx1, bdybdy1, cdxcdx1, cdycdy1;
5356   REAL adxadx0, adyady0, bdxbdx0, bdybdy0, cdxcdx0, cdycdy0;
5357   REAL aa[4], bb[4], cc[4];
5358   INEXACT REAL aa3, bb3, cc3;
5359   INEXACT REAL ti1, tj1;
5360   REAL ti0, tj0;
5361   REAL u[4], v[4];
5362   INEXACT REAL u3, v3;
5363   REAL temp8[8], temp16a[16], temp16b[16], temp16c[16];
5364   REAL temp32a[32], temp32b[32], temp48[48], temp64[64];
5365   int temp8len, temp16alen, temp16blen, temp16clen;
5366   int temp32alen, temp32blen, temp48len, temp64len;
5367   REAL axtbb[8], axtcc[8], aytbb[8], aytcc[8];
5368   int axtbblen, axtcclen, aytbblen, aytcclen;
5369   REAL bxtaa[8], bxtcc[8], bytaa[8], bytcc[8];
5370   int bxtaalen, bxtcclen, bytaalen, bytcclen;
5371   REAL cxtaa[8], cxtbb[8], cytaa[8], cytbb[8];
5372   int cxtaalen, cxtbblen, cytaalen, cytbblen;
5373   REAL axtbc[8], aytbc[8], bxtca[8], bytca[8], cxtab[8], cytab[8];
5374   int axtbclen = 0, aytbclen = 0, bxtcalen = 0, bytcalen = 0, cxtablen = 0, cytablen = 0;
5375   REAL axtbct[16], aytbct[16], bxtcat[16], bytcat[16], cxtabt[16], cytabt[16];
5376   int axtbctlen, aytbctlen, bxtcatlen, bytcatlen, cxtabtlen, cytabtlen;
5377   REAL axtbctt[8], aytbctt[8], bxtcatt[8];
5378   REAL bytcatt[8], cxtabtt[8], cytabtt[8];
5379   int axtbcttlen, aytbcttlen, bxtcattlen, bytcattlen, cxtabttlen, cytabttlen;
5380   REAL abt[8], bct[8], cat[8];
5381   int abtlen, bctlen, catlen;
5382   REAL abtt[4], bctt[4], catt[4];
5383   int abttlen, bcttlen, cattlen;
5384   INEXACT REAL abtt3, bctt3, catt3;
5385   REAL negate;
5386 
5387   INEXACT REAL bvirt;
5388   REAL avirt, bround, around;
5389   INEXACT REAL c;
5390   INEXACT REAL abig;
5391   REAL ahi, alo, bhi, blo;
5392   REAL err1, err2, err3;
5393   INEXACT REAL _i, _j;
5394   REAL _0;
5395 
5396   adx = (REAL) (pa[0] - pd[0]);
5397   bdx = (REAL) (pb[0] - pd[0]);
5398   cdx = (REAL) (pc[0] - pd[0]);
5399   ady = (REAL) (pa[1] - pd[1]);
5400   bdy = (REAL) (pb[1] - pd[1]);
5401   cdy = (REAL) (pc[1] - pd[1]);
5402 
5403   Two_Product(bdx, cdy, bdxcdy1, bdxcdy0);
5404   Two_Product(cdx, bdy, cdxbdy1, cdxbdy0);
5405   Two_Two_Diff(bdxcdy1, bdxcdy0, cdxbdy1, cdxbdy0, bc3, bc[2], bc[1], bc[0]);
5406   bc[3] = bc3;
5407   axbclen = scale_expansion_zeroelim(4, bc, adx, axbc);
5408   axxbclen = scale_expansion_zeroelim(axbclen, axbc, adx, axxbc);
5409   aybclen = scale_expansion_zeroelim(4, bc, ady, aybc);
5410   ayybclen = scale_expansion_zeroelim(aybclen, aybc, ady, ayybc);
5411   alen = fast_expansion_sum_zeroelim(axxbclen, axxbc, ayybclen, ayybc, adet);
5412 
5413   Two_Product(cdx, ady, cdxady1, cdxady0);
5414   Two_Product(adx, cdy, adxcdy1, adxcdy0);
5415   Two_Two_Diff(cdxady1, cdxady0, adxcdy1, adxcdy0, ca3, ca[2], ca[1], ca[0]);
5416   ca[3] = ca3;
5417   bxcalen = scale_expansion_zeroelim(4, ca, bdx, bxca);
5418   bxxcalen = scale_expansion_zeroelim(bxcalen, bxca, bdx, bxxca);
5419   bycalen = scale_expansion_zeroelim(4, ca, bdy, byca);
5420   byycalen = scale_expansion_zeroelim(bycalen, byca, bdy, byyca);
5421   blen = fast_expansion_sum_zeroelim(bxxcalen, bxxca, byycalen, byyca, bdet);
5422 
5423   Two_Product(adx, bdy, adxbdy1, adxbdy0);
5424   Two_Product(bdx, ady, bdxady1, bdxady0);
5425   Two_Two_Diff(adxbdy1, adxbdy0, bdxady1, bdxady0, ab3, ab[2], ab[1], ab[0]);
5426   ab[3] = ab3;
5427   cxablen = scale_expansion_zeroelim(4, ab, cdx, cxab);
5428   cxxablen = scale_expansion_zeroelim(cxablen, cxab, cdx, cxxab);
5429   cyablen = scale_expansion_zeroelim(4, ab, cdy, cyab);
5430   cyyablen = scale_expansion_zeroelim(cyablen, cyab, cdy, cyyab);
5431   clen = fast_expansion_sum_zeroelim(cxxablen, cxxab, cyyablen, cyyab, cdet);
5432 
5433   ablen = fast_expansion_sum_zeroelim(alen, adet, blen, bdet, abdet);
5434   finlength = fast_expansion_sum_zeroelim(ablen, abdet, clen, cdet, fin1);
5435 
5436   det = estimate(finlength, fin1);
5437   errbound = iccerrboundB * permanent;
5438   if ((det >= errbound) || (-det >= errbound)) {
5439     return det;
5440   }
5441 
5442   Two_Diff_Tail(pa[0], pd[0], adx, adxtail);
5443   Two_Diff_Tail(pa[1], pd[1], ady, adytail);
5444   Two_Diff_Tail(pb[0], pd[0], bdx, bdxtail);
5445   Two_Diff_Tail(pb[1], pd[1], bdy, bdytail);
5446   Two_Diff_Tail(pc[0], pd[0], cdx, cdxtail);
5447   Two_Diff_Tail(pc[1], pd[1], cdy, cdytail);
5448   if ((adxtail == 0.0) && (bdxtail == 0.0) && (cdxtail == 0.0)
5449       && (adytail == 0.0) && (bdytail == 0.0) && (cdytail == 0.0)) {
5450     return det;
5451   }
5452 
5453   errbound = iccerrboundC * permanent + resulterrbound * Absolute(det);
5454   det += ((adx * adx + ady * ady) * ((bdx * cdytail + cdy * bdxtail)
5455                                      - (bdy * cdxtail + cdx * bdytail))
5456           + 2.0 * (adx * adxtail + ady * adytail) * (bdx * cdy - bdy * cdx))
5457        + ((bdx * bdx + bdy * bdy) * ((cdx * adytail + ady * cdxtail)
5458                                      - (cdy * adxtail + adx * cdytail))
5459           + 2.0 * (bdx * bdxtail + bdy * bdytail) * (cdx * ady - cdy * adx))
5460        + ((cdx * cdx + cdy * cdy) * ((adx * bdytail + bdy * adxtail)
5461                                      - (ady * bdxtail + bdx * adytail))
5462           + 2.0 * (cdx * cdxtail + cdy * cdytail) * (adx * bdy - ady * bdx));
5463   if ((det >= errbound) || (-det >= errbound)) {
5464     return det;
5465   }
5466 
5467   finnow = fin1;
5468   finother = fin2;
5469 
5470   if ((bdxtail != 0.0) || (bdytail != 0.0)
5471       || (cdxtail != 0.0) || (cdytail != 0.0)) {
5472     Square(adx, adxadx1, adxadx0);
5473     Square(ady, adyady1, adyady0);
5474     Two_Two_Sum(adxadx1, adxadx0, adyady1, adyady0, aa3, aa[2], aa[1], aa[0]);
5475     aa[3] = aa3;
5476   }
5477   if ((cdxtail != 0.0) || (cdytail != 0.0)
5478       || (adxtail != 0.0) || (adytail != 0.0)) {
5479     Square(bdx, bdxbdx1, bdxbdx0);
5480     Square(bdy, bdybdy1, bdybdy0);
5481     Two_Two_Sum(bdxbdx1, bdxbdx0, bdybdy1, bdybdy0, bb3, bb[2], bb[1], bb[0]);
5482     bb[3] = bb3;
5483   }
5484   if ((adxtail != 0.0) || (adytail != 0.0)
5485       || (bdxtail != 0.0) || (bdytail != 0.0)) {
5486     Square(cdx, cdxcdx1, cdxcdx0);
5487     Square(cdy, cdycdy1, cdycdy0);
5488     Two_Two_Sum(cdxcdx1, cdxcdx0, cdycdy1, cdycdy0, cc3, cc[2], cc[1], cc[0]);
5489     cc[3] = cc3;
5490   }
5491 
5492   if (adxtail != 0.0) {
5493     axtbclen = scale_expansion_zeroelim(4, bc, adxtail, axtbc);
5494     temp16alen = scale_expansion_zeroelim(axtbclen, axtbc, 2.0 * adx,
5495                                           temp16a);
5496 
5497     axtcclen = scale_expansion_zeroelim(4, cc, adxtail, axtcc);
5498     temp16blen = scale_expansion_zeroelim(axtcclen, axtcc, bdy, temp16b);
5499 
5500     axtbblen = scale_expansion_zeroelim(4, bb, adxtail, axtbb);
5501     temp16clen = scale_expansion_zeroelim(axtbblen, axtbb, -cdy, temp16c);
5502 
5503     temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5504                                             temp16blen, temp16b, temp32a);
5505     temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
5506                                             temp32alen, temp32a, temp48);
5507     finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
5508                                             temp48, finother);
5509     finswap = finnow; finnow = finother; finother = finswap;
5510   }
5511   if (adytail != 0.0) {
5512     aytbclen = scale_expansion_zeroelim(4, bc, adytail, aytbc);
5513     temp16alen = scale_expansion_zeroelim(aytbclen, aytbc, 2.0 * ady,
5514                                           temp16a);
5515 
5516     aytbblen = scale_expansion_zeroelim(4, bb, adytail, aytbb);
5517     temp16blen = scale_expansion_zeroelim(aytbblen, aytbb, cdx, temp16b);
5518 
5519     aytcclen = scale_expansion_zeroelim(4, cc, adytail, aytcc);
5520     temp16clen = scale_expansion_zeroelim(aytcclen, aytcc, -bdx, temp16c);
5521 
5522     temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5523                                             temp16blen, temp16b, temp32a);
5524     temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
5525                                             temp32alen, temp32a, temp48);
5526     finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
5527                                             temp48, finother);
5528     finswap = finnow; finnow = finother; finother = finswap;
5529   }
5530   if (bdxtail != 0.0) {
5531     bxtcalen = scale_expansion_zeroelim(4, ca, bdxtail, bxtca);
5532     temp16alen = scale_expansion_zeroelim(bxtcalen, bxtca, 2.0 * bdx,
5533                                           temp16a);
5534 
5535     bxtaalen = scale_expansion_zeroelim(4, aa, bdxtail, bxtaa);
5536     temp16blen = scale_expansion_zeroelim(bxtaalen, bxtaa, cdy, temp16b);
5537 
5538     bxtcclen = scale_expansion_zeroelim(4, cc, bdxtail, bxtcc);
5539     temp16clen = scale_expansion_zeroelim(bxtcclen, bxtcc, -ady, temp16c);
5540 
5541     temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5542                                             temp16blen, temp16b, temp32a);
5543     temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
5544                                             temp32alen, temp32a, temp48);
5545     finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
5546                                             temp48, finother);
5547     finswap = finnow; finnow = finother; finother = finswap;
5548   }
5549   if (bdytail != 0.0) {
5550     bytcalen = scale_expansion_zeroelim(4, ca, bdytail, bytca);
5551     temp16alen = scale_expansion_zeroelim(bytcalen, bytca, 2.0 * bdy,
5552                                           temp16a);
5553 
5554     bytcclen = scale_expansion_zeroelim(4, cc, bdytail, bytcc);
5555     temp16blen = scale_expansion_zeroelim(bytcclen, bytcc, adx, temp16b);
5556 
5557     bytaalen = scale_expansion_zeroelim(4, aa, bdytail, bytaa);
5558     temp16clen = scale_expansion_zeroelim(bytaalen, bytaa, -cdx, temp16c);
5559 
5560     temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5561                                             temp16blen, temp16b, temp32a);
5562     temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
5563                                             temp32alen, temp32a, temp48);
5564     finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
5565                                             temp48, finother);
5566     finswap = finnow; finnow = finother; finother = finswap;
5567   }
5568   if (cdxtail != 0.0) {
5569     cxtablen = scale_expansion_zeroelim(4, ab, cdxtail, cxtab);
5570     temp16alen = scale_expansion_zeroelim(cxtablen, cxtab, 2.0 * cdx,
5571                                           temp16a);
5572 
5573     cxtbblen = scale_expansion_zeroelim(4, bb, cdxtail, cxtbb);
5574     temp16blen = scale_expansion_zeroelim(cxtbblen, cxtbb, ady, temp16b);
5575 
5576     cxtaalen = scale_expansion_zeroelim(4, aa, cdxtail, cxtaa);
5577     temp16clen = scale_expansion_zeroelim(cxtaalen, cxtaa, -bdy, temp16c);
5578 
5579     temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5580                                             temp16blen, temp16b, temp32a);
5581     temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
5582                                             temp32alen, temp32a, temp48);
5583     finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
5584                                             temp48, finother);
5585     finswap = finnow; finnow = finother; finother = finswap;
5586   }
5587   if (cdytail != 0.0) {
5588     cytablen = scale_expansion_zeroelim(4, ab, cdytail, cytab);
5589     temp16alen = scale_expansion_zeroelim(cytablen, cytab, 2.0 * cdy,
5590                                           temp16a);
5591 
5592     cytaalen = scale_expansion_zeroelim(4, aa, cdytail, cytaa);
5593     temp16blen = scale_expansion_zeroelim(cytaalen, cytaa, bdx, temp16b);
5594 
5595     cytbblen = scale_expansion_zeroelim(4, bb, cdytail, cytbb);
5596     temp16clen = scale_expansion_zeroelim(cytbblen, cytbb, -adx, temp16c);
5597 
5598     temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5599                                             temp16blen, temp16b, temp32a);
5600     temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
5601                                             temp32alen, temp32a, temp48);
5602     finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
5603                                             temp48, finother);
5604     finswap = finnow; finnow = finother; finother = finswap;
5605   }
5606 
5607   if ((adxtail != 0.0) || (adytail != 0.0)) {
5608     if ((bdxtail != 0.0) || (bdytail != 0.0)
5609         || (cdxtail != 0.0) || (cdytail != 0.0)) {
5610       Two_Product(bdxtail, cdy, ti1, ti0);
5611       Two_Product(bdx, cdytail, tj1, tj0);
5612       Two_Two_Sum(ti1, ti0, tj1, tj0, u3, u[2], u[1], u[0]);
5613       u[3] = u3;
5614       negate = -bdy;
5615       Two_Product(cdxtail, negate, ti1, ti0);
5616       negate = -bdytail;
5617       Two_Product(cdx, negate, tj1, tj0);
5618       Two_Two_Sum(ti1, ti0, tj1, tj0, v3, v[2], v[1], v[0]);
5619       v[3] = v3;
5620       bctlen = fast_expansion_sum_zeroelim(4, u, 4, v, bct);
5621 
5622       Two_Product(bdxtail, cdytail, ti1, ti0);
5623       Two_Product(cdxtail, bdytail, tj1, tj0);
5624       Two_Two_Diff(ti1, ti0, tj1, tj0, bctt3, bctt[2], bctt[1], bctt[0]);
5625       bctt[3] = bctt3;
5626       bcttlen = 4;
5627     } else {
5628       bct[0] = 0.0;
5629       bctlen = 1;
5630       bctt[0] = 0.0;
5631       bcttlen = 1;
5632     }
5633 
5634     if (adxtail != 0.0) {
5635       temp16alen = scale_expansion_zeroelim(axtbclen, axtbc, adxtail, temp16a);
5636       axtbctlen = scale_expansion_zeroelim(bctlen, bct, adxtail, axtbct);
5637       temp32alen = scale_expansion_zeroelim(axtbctlen, axtbct, 2.0 * adx,
5638                                             temp32a);
5639       temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5640                                               temp32alen, temp32a, temp48);
5641       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
5642                                               temp48, finother);
5643       finswap = finnow; finnow = finother; finother = finswap;
5644       if (bdytail != 0.0) {
5645         temp8len = scale_expansion_zeroelim(4, cc, adxtail, temp8);
5646         temp16alen = scale_expansion_zeroelim(temp8len, temp8, bdytail,
5647                                               temp16a);
5648         finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
5649                                                 temp16a, finother);
5650         finswap = finnow; finnow = finother; finother = finswap;
5651       }
5652       if (cdytail != 0.0) {
5653         temp8len = scale_expansion_zeroelim(4, bb, -adxtail, temp8);
5654         temp16alen = scale_expansion_zeroelim(temp8len, temp8, cdytail,
5655                                               temp16a);
5656         finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
5657                                                 temp16a, finother);
5658         finswap = finnow; finnow = finother; finother = finswap;
5659       }
5660 
5661       temp32alen = scale_expansion_zeroelim(axtbctlen, axtbct, adxtail,
5662                                             temp32a);
5663       axtbcttlen = scale_expansion_zeroelim(bcttlen, bctt, adxtail, axtbctt);
5664       temp16alen = scale_expansion_zeroelim(axtbcttlen, axtbctt, 2.0 * adx,
5665                                             temp16a);
5666       temp16blen = scale_expansion_zeroelim(axtbcttlen, axtbctt, adxtail,
5667                                             temp16b);
5668       temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5669                                               temp16blen, temp16b, temp32b);
5670       temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
5671                                               temp32blen, temp32b, temp64);
5672       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
5673                                               temp64, finother);
5674       finswap = finnow; finnow = finother; finother = finswap;
5675     }
5676     if (adytail != 0.0) {
5677       temp16alen = scale_expansion_zeroelim(aytbclen, aytbc, adytail, temp16a);
5678       aytbctlen = scale_expansion_zeroelim(bctlen, bct, adytail, aytbct);
5679       temp32alen = scale_expansion_zeroelim(aytbctlen, aytbct, 2.0 * ady,
5680                                             temp32a);
5681       temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5682                                               temp32alen, temp32a, temp48);
5683       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
5684                                               temp48, finother);
5685       finswap = finnow; finnow = finother; finother = finswap;
5686 
5687 
5688       temp32alen = scale_expansion_zeroelim(aytbctlen, aytbct, adytail,
5689                                             temp32a);
5690       aytbcttlen = scale_expansion_zeroelim(bcttlen, bctt, adytail, aytbctt);
5691       temp16alen = scale_expansion_zeroelim(aytbcttlen, aytbctt, 2.0 * ady,
5692                                             temp16a);
5693       temp16blen = scale_expansion_zeroelim(aytbcttlen, aytbctt, adytail,
5694                                             temp16b);
5695       temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5696                                               temp16blen, temp16b, temp32b);
5697       temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
5698                                               temp32blen, temp32b, temp64);
5699       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
5700                                               temp64, finother);
5701       finswap = finnow; finnow = finother; finother = finswap;
5702     }
5703   }
5704   if ((bdxtail != 0.0) || (bdytail != 0.0)) {
5705     if ((cdxtail != 0.0) || (cdytail != 0.0)
5706         || (adxtail != 0.0) || (adytail != 0.0)) {
5707       Two_Product(cdxtail, ady, ti1, ti0);
5708       Two_Product(cdx, adytail, tj1, tj0);
5709       Two_Two_Sum(ti1, ti0, tj1, tj0, u3, u[2], u[1], u[0]);
5710       u[3] = u3;
5711       negate = -cdy;
5712       Two_Product(adxtail, negate, ti1, ti0);
5713       negate = -cdytail;
5714       Two_Product(adx, negate, tj1, tj0);
5715       Two_Two_Sum(ti1, ti0, tj1, tj0, v3, v[2], v[1], v[0]);
5716       v[3] = v3;
5717       catlen = fast_expansion_sum_zeroelim(4, u, 4, v, cat);
5718 
5719       Two_Product(cdxtail, adytail, ti1, ti0);
5720       Two_Product(adxtail, cdytail, tj1, tj0);
5721       Two_Two_Diff(ti1, ti0, tj1, tj0, catt3, catt[2], catt[1], catt[0]);
5722       catt[3] = catt3;
5723       cattlen = 4;
5724     } else {
5725       cat[0] = 0.0;
5726       catlen = 1;
5727       catt[0] = 0.0;
5728       cattlen = 1;
5729     }
5730 
5731     if (bdxtail != 0.0) {
5732       temp16alen = scale_expansion_zeroelim(bxtcalen, bxtca, bdxtail, temp16a);
5733       bxtcatlen = scale_expansion_zeroelim(catlen, cat, bdxtail, bxtcat);
5734       temp32alen = scale_expansion_zeroelim(bxtcatlen, bxtcat, 2.0 * bdx,
5735                                             temp32a);
5736       temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5737                                               temp32alen, temp32a, temp48);
5738       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
5739                                               temp48, finother);
5740       finswap = finnow; finnow = finother; finother = finswap;
5741       if (cdytail != 0.0) {
5742         temp8len = scale_expansion_zeroelim(4, aa, bdxtail, temp8);
5743         temp16alen = scale_expansion_zeroelim(temp8len, temp8, cdytail,
5744                                               temp16a);
5745         finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
5746                                                 temp16a, finother);
5747         finswap = finnow; finnow = finother; finother = finswap;
5748       }
5749       if (adytail != 0.0) {
5750         temp8len = scale_expansion_zeroelim(4, cc, -bdxtail, temp8);
5751         temp16alen = scale_expansion_zeroelim(temp8len, temp8, adytail,
5752                                               temp16a);
5753         finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
5754                                                 temp16a, finother);
5755         finswap = finnow; finnow = finother; finother = finswap;
5756       }
5757 
5758       temp32alen = scale_expansion_zeroelim(bxtcatlen, bxtcat, bdxtail,
5759                                             temp32a);
5760       bxtcattlen = scale_expansion_zeroelim(cattlen, catt, bdxtail, bxtcatt);
5761       temp16alen = scale_expansion_zeroelim(bxtcattlen, bxtcatt, 2.0 * bdx,
5762                                             temp16a);
5763       temp16blen = scale_expansion_zeroelim(bxtcattlen, bxtcatt, bdxtail,
5764                                             temp16b);
5765       temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5766                                               temp16blen, temp16b, temp32b);
5767       temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
5768                                               temp32blen, temp32b, temp64);
5769       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
5770                                               temp64, finother);
5771       finswap = finnow; finnow = finother; finother = finswap;
5772     }
5773     if (bdytail != 0.0) {
5774       temp16alen = scale_expansion_zeroelim(bytcalen, bytca, bdytail, temp16a);
5775       bytcatlen = scale_expansion_zeroelim(catlen, cat, bdytail, bytcat);
5776       temp32alen = scale_expansion_zeroelim(bytcatlen, bytcat, 2.0 * bdy,
5777                                             temp32a);
5778       temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5779                                               temp32alen, temp32a, temp48);
5780       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
5781                                               temp48, finother);
5782       finswap = finnow; finnow = finother; finother = finswap;
5783 
5784 
5785       temp32alen = scale_expansion_zeroelim(bytcatlen, bytcat, bdytail,
5786                                             temp32a);
5787       bytcattlen = scale_expansion_zeroelim(cattlen, catt, bdytail, bytcatt);
5788       temp16alen = scale_expansion_zeroelim(bytcattlen, bytcatt, 2.0 * bdy,
5789                                             temp16a);
5790       temp16blen = scale_expansion_zeroelim(bytcattlen, bytcatt, bdytail,
5791                                             temp16b);
5792       temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5793                                               temp16blen, temp16b, temp32b);
5794       temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
5795                                               temp32blen, temp32b, temp64);
5796       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
5797                                               temp64, finother);
5798       finswap = finnow; finnow = finother; finother = finswap;
5799     }
5800   }
5801   if ((cdxtail != 0.0) || (cdytail != 0.0)) {
5802     if ((adxtail != 0.0) || (adytail != 0.0)
5803         || (bdxtail != 0.0) || (bdytail != 0.0)) {
5804       Two_Product(adxtail, bdy, ti1, ti0);
5805       Two_Product(adx, bdytail, tj1, tj0);
5806       Two_Two_Sum(ti1, ti0, tj1, tj0, u3, u[2], u[1], u[0]);
5807       u[3] = u3;
5808       negate = -ady;
5809       Two_Product(bdxtail, negate, ti1, ti0);
5810       negate = -adytail;
5811       Two_Product(bdx, negate, tj1, tj0);
5812       Two_Two_Sum(ti1, ti0, tj1, tj0, v3, v[2], v[1], v[0]);
5813       v[3] = v3;
5814       abtlen = fast_expansion_sum_zeroelim(4, u, 4, v, abt);
5815 
5816       Two_Product(adxtail, bdytail, ti1, ti0);
5817       Two_Product(bdxtail, adytail, tj1, tj0);
5818       Two_Two_Diff(ti1, ti0, tj1, tj0, abtt3, abtt[2], abtt[1], abtt[0]);
5819       abtt[3] = abtt3;
5820       abttlen = 4;
5821     } else {
5822       abt[0] = 0.0;
5823       abtlen = 1;
5824       abtt[0] = 0.0;
5825       abttlen = 1;
5826     }
5827 
5828     if (cdxtail != 0.0) {
5829       temp16alen = scale_expansion_zeroelim(cxtablen, cxtab, cdxtail, temp16a);
5830       cxtabtlen = scale_expansion_zeroelim(abtlen, abt, cdxtail, cxtabt);
5831       temp32alen = scale_expansion_zeroelim(cxtabtlen, cxtabt, 2.0 * cdx,
5832                                             temp32a);
5833       temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5834                                               temp32alen, temp32a, temp48);
5835       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
5836                                               temp48, finother);
5837       finswap = finnow; finnow = finother; finother = finswap;
5838       if (adytail != 0.0) {
5839         temp8len = scale_expansion_zeroelim(4, bb, cdxtail, temp8);
5840         temp16alen = scale_expansion_zeroelim(temp8len, temp8, adytail,
5841                                               temp16a);
5842         finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
5843                                                 temp16a, finother);
5844         finswap = finnow; finnow = finother; finother = finswap;
5845       }
5846       if (bdytail != 0.0) {
5847         temp8len = scale_expansion_zeroelim(4, aa, -cdxtail, temp8);
5848         temp16alen = scale_expansion_zeroelim(temp8len, temp8, bdytail,
5849                                               temp16a);
5850         finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
5851                                                 temp16a, finother);
5852         finswap = finnow; finnow = finother; finother = finswap;
5853       }
5854 
5855       temp32alen = scale_expansion_zeroelim(cxtabtlen, cxtabt, cdxtail,
5856                                             temp32a);
5857       cxtabttlen = scale_expansion_zeroelim(abttlen, abtt, cdxtail, cxtabtt);
5858       temp16alen = scale_expansion_zeroelim(cxtabttlen, cxtabtt, 2.0 * cdx,
5859                                             temp16a);
5860       temp16blen = scale_expansion_zeroelim(cxtabttlen, cxtabtt, cdxtail,
5861                                             temp16b);
5862       temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5863                                               temp16blen, temp16b, temp32b);
5864       temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
5865                                               temp32blen, temp32b, temp64);
5866       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
5867                                               temp64, finother);
5868       finswap = finnow; finnow = finother; finother = finswap;
5869     }
5870     if (cdytail != 0.0) {
5871       temp16alen = scale_expansion_zeroelim(cytablen, cytab, cdytail, temp16a);
5872       cytabtlen = scale_expansion_zeroelim(abtlen, abt, cdytail, cytabt);
5873       temp32alen = scale_expansion_zeroelim(cytabtlen, cytabt, 2.0 * cdy,
5874                                             temp32a);
5875       temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5876                                               temp32alen, temp32a, temp48);
5877       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
5878                                               temp48, finother);
5879       finswap = finnow; finnow = finother; finother = finswap;
5880 
5881 
5882       temp32alen = scale_expansion_zeroelim(cytabtlen, cytabt, cdytail,
5883                                             temp32a);
5884       cytabttlen = scale_expansion_zeroelim(abttlen, abtt, cdytail, cytabtt);
5885       temp16alen = scale_expansion_zeroelim(cytabttlen, cytabtt, 2.0 * cdy,
5886                                             temp16a);
5887       temp16blen = scale_expansion_zeroelim(cytabttlen, cytabtt, cdytail,
5888                                             temp16b);
5889       temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5890                                               temp16blen, temp16b, temp32b);
5891       temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
5892                                               temp32blen, temp32b, temp64);
5893       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
5894                                               temp64, finother);
5895       finswap = finnow; finnow = finother; finother = finswap;
5896     }
5897   }
5898 
5899   return finnow[finlength - 1];
5900 }
5901 
5902 #ifdef ANSI_DECLARATORS
5903 static REAL incircle(struct mesh *m, struct behavior *b,
5904               vertex pa, vertex pb, vertex pc, vertex pd)
5905 #else /* not ANSI_DECLARATORS */
5906 static REAL incircle(m, b, pa, pb, pc, pd)
5907 struct mesh *m;
5908 struct behavior *b;
5909 vertex pa;
5910 vertex pb;
5911 vertex pc;
5912 vertex pd;
5913 #endif /* not ANSI_DECLARATORS */
5914 
5915 {
5916   REAL adx, bdx, cdx, ady, bdy, cdy;
5917   REAL bdxcdy, cdxbdy, cdxady, adxcdy, adxbdy, bdxady;
5918   REAL alift, blift, clift;
5919   REAL det;
5920   REAL permanent, errbound;
5921 
5922   m->incirclecount++;
5923 
5924   adx = pa[0] - pd[0];
5925   bdx = pb[0] - pd[0];
5926   cdx = pc[0] - pd[0];
5927   ady = pa[1] - pd[1];
5928   bdy = pb[1] - pd[1];
5929   cdy = pc[1] - pd[1];
5930 
5931   bdxcdy = bdx * cdy;
5932   cdxbdy = cdx * bdy;
5933   alift = adx * adx + ady * ady;
5934 
5935   cdxady = cdx * ady;
5936   adxcdy = adx * cdy;
5937   blift = bdx * bdx + bdy * bdy;
5938 
5939   adxbdy = adx * bdy;
5940   bdxady = bdx * ady;
5941   clift = cdx * cdx + cdy * cdy;
5942 
5943   det = alift * (bdxcdy - cdxbdy)
5944       + blift * (cdxady - adxcdy)
5945       + clift * (adxbdy - bdxady);
5946 
5947   if (b->noexact) {
5948     return det;
5949   }
5950 
5951   permanent = (Absolute(bdxcdy) + Absolute(cdxbdy)) * alift
5952             + (Absolute(cdxady) + Absolute(adxcdy)) * blift
5953             + (Absolute(adxbdy) + Absolute(bdxady)) * clift;
5954   errbound = iccerrboundA * permanent;
5955   if ((det > errbound) || (-det > errbound)) {
5956     return det;
5957   }
5958 
5959   return incircleadapt(pa, pb, pc, pd, permanent);
5960 }
5961 
5962 /*****************************************************************************/
5963 /*                                                                           */
5964 /*  orient3d()   Return a positive value if the point pd lies below the      */
5965 /*               plane passing through pa, pb, and pc; "below" is defined so */
5966 /*               that pa, pb, and pc appear in counterclockwise order when   */
5967 /*               viewed from above the plane.  Returns a negative value if   */
5968 /*               pd lies above the plane.  Returns zero if the points are    */
5969 /*               coplanar.  The result is also a rough approximation of six  */
5970 /*               times the signed volume of the tetrahedron defined by the   */
5971 /*               four points.                                                */
5972 /*                                                                           */
5973 /*  Uses exact arithmetic if necessary to ensure a correct answer.  The      */
5974 /*  result returned is the determinant of a matrix.  This determinant is     */
5975 /*  computed adaptively, in the sense that exact arithmetic is used only to  */
5976 /*  the degree it is needed to ensure that the returned value has the        */
5977 /*  correct sign.  Hence, this function is usually quite fast, but will run  */
5978 /*  more slowly when the input points are coplanar or nearly so.             */
5979 /*                                                                           */
5980 /*  See my Robust Predicates paper for details.                              */
5981 /*                                                                           */
5982 /*****************************************************************************/
5983 
5984 #ifndef REDUCED
5985 
5986 #ifdef ANSI_DECLARATORS
5987 static REAL orient3dadapt(vertex pa, vertex pb, vertex pc, vertex pd,
5988                    REAL aheight, REAL bheight, REAL cheight, REAL dheight,
5989                    REAL permanent)
5990 #else /* not ANSI_DECLARATORS */
5991 static REAL orient3dadapt(pa, pb, pc, pd,
5992                    aheight, bheight, cheight, dheight, permanent)
5993 vertex pa;
5994 vertex pb;
5995 vertex pc;
5996 vertex pd;
5997 REAL aheight;
5998 REAL bheight;
5999 REAL cheight;
6000 REAL dheight;
6001 REAL permanent;
6002 #endif /* not ANSI_DECLARATORS */
6003 
6004 {
6005   INEXACT REAL adx, bdx, cdx, ady, bdy, cdy, adheight, bdheight, cdheight;
6006   REAL det, errbound;
6007 
6008   INEXACT REAL bdxcdy1, cdxbdy1, cdxady1, adxcdy1, adxbdy1, bdxady1;
6009   REAL bdxcdy0, cdxbdy0, cdxady0, adxcdy0, adxbdy0, bdxady0;
6010   REAL bc[4], ca[4], ab[4];
6011   INEXACT REAL bc3, ca3, ab3;
6012   REAL adet[8], bdet[8], cdet[8];
6013   int alen, blen, clen;
6014   REAL abdet[16];
6015   int ablen;
6016   REAL *finnow, *finother, *finswap;
6017   REAL fin1[192], fin2[192];
6018   int finlength;
6019 
6020   REAL adxtail, bdxtail, cdxtail;
6021   REAL adytail, bdytail, cdytail;
6022   REAL adheighttail, bdheighttail, cdheighttail;
6023   INEXACT REAL at_blarge, at_clarge;
6024   INEXACT REAL bt_clarge, bt_alarge;
6025   INEXACT REAL ct_alarge, ct_blarge;
6026   REAL at_b[4], at_c[4], bt_c[4], bt_a[4], ct_a[4], ct_b[4];
6027   int at_blen, at_clen, bt_clen, bt_alen, ct_alen, ct_blen;
6028   INEXACT REAL bdxt_cdy1, cdxt_bdy1, cdxt_ady1;
6029   INEXACT REAL adxt_cdy1, adxt_bdy1, bdxt_ady1;
6030   REAL bdxt_cdy0, cdxt_bdy0, cdxt_ady0;
6031   REAL adxt_cdy0, adxt_bdy0, bdxt_ady0;
6032   INEXACT REAL bdyt_cdx1, cdyt_bdx1, cdyt_adx1;
6033   INEXACT REAL adyt_cdx1, adyt_bdx1, bdyt_adx1;
6034   REAL bdyt_cdx0, cdyt_bdx0, cdyt_adx0;
6035   REAL adyt_cdx0, adyt_bdx0, bdyt_adx0;
6036   REAL bct[8], cat[8], abt[8];
6037   int bctlen, catlen, abtlen;
6038   INEXACT REAL bdxt_cdyt1, cdxt_bdyt1, cdxt_adyt1;
6039   INEXACT REAL adxt_cdyt1, adxt_bdyt1, bdxt_adyt1;
6040   REAL bdxt_cdyt0, cdxt_bdyt0, cdxt_adyt0;
6041   REAL adxt_cdyt0, adxt_bdyt0, bdxt_adyt0;
6042   REAL u[4], v[12], w[16];
6043   INEXACT REAL u3;
6044   int vlength, wlength;
6045   REAL negate;
6046 
6047   INEXACT REAL bvirt;
6048   REAL avirt, bround, around;
6049   INEXACT REAL c;
6050   INEXACT REAL abig;
6051   REAL ahi, alo, bhi, blo;
6052   REAL err1, err2, err3;
6053   INEXACT REAL _i, _j, _k;
6054   REAL _0;
6055 
6056   adx = (REAL) (pa[0] - pd[0]);
6057   bdx = (REAL) (pb[0] - pd[0]);
6058   cdx = (REAL) (pc[0] - pd[0]);
6059   ady = (REAL) (pa[1] - pd[1]);
6060   bdy = (REAL) (pb[1] - pd[1]);
6061   cdy = (REAL) (pc[1] - pd[1]);
6062   adheight = (REAL) (aheight - dheight);
6063   bdheight = (REAL) (bheight - dheight);
6064   cdheight = (REAL) (cheight - dheight);
6065 
6066   Two_Product(bdx, cdy, bdxcdy1, bdxcdy0);
6067   Two_Product(cdx, bdy, cdxbdy1, cdxbdy0);
6068   Two_Two_Diff(bdxcdy1, bdxcdy0, cdxbdy1, cdxbdy0, bc3, bc[2], bc[1], bc[0]);
6069   bc[3] = bc3;
6070   alen = scale_expansion_zeroelim(4, bc, adheight, adet);
6071 
6072   Two_Product(cdx, ady, cdxady1, cdxady0);
6073   Two_Product(adx, cdy, adxcdy1, adxcdy0);
6074   Two_Two_Diff(cdxady1, cdxady0, adxcdy1, adxcdy0, ca3, ca[2], ca[1], ca[0]);
6075   ca[3] = ca3;
6076   blen = scale_expansion_zeroelim(4, ca, bdheight, bdet);
6077 
6078   Two_Product(adx, bdy, adxbdy1, adxbdy0);
6079   Two_Product(bdx, ady, bdxady1, bdxady0);
6080   Two_Two_Diff(adxbdy1, adxbdy0, bdxady1, bdxady0, ab3, ab[2], ab[1], ab[0]);
6081   ab[3] = ab3;
6082   clen = scale_expansion_zeroelim(4, ab, cdheight, cdet);
6083 
6084   ablen = fast_expansion_sum_zeroelim(alen, adet, blen, bdet, abdet);
6085   finlength = fast_expansion_sum_zeroelim(ablen, abdet, clen, cdet, fin1);
6086 
6087   det = estimate(finlength, fin1);
6088   errbound = o3derrboundB * permanent;
6089   if ((det >= errbound) || (-det >= errbound)) {
6090     return det;
6091   }
6092 
6093   Two_Diff_Tail(pa[0], pd[0], adx, adxtail);
6094   Two_Diff_Tail(pb[0], pd[0], bdx, bdxtail);
6095   Two_Diff_Tail(pc[0], pd[0], cdx, cdxtail);
6096   Two_Diff_Tail(pa[1], pd[1], ady, adytail);
6097   Two_Diff_Tail(pb[1], pd[1], bdy, bdytail);
6098   Two_Diff_Tail(pc[1], pd[1], cdy, cdytail);
6099   Two_Diff_Tail(aheight, dheight, adheight, adheighttail);
6100   Two_Diff_Tail(bheight, dheight, bdheight, bdheighttail);
6101   Two_Diff_Tail(cheight, dheight, cdheight, cdheighttail);
6102 
6103   if ((adxtail == 0.0) && (bdxtail == 0.0) && (cdxtail == 0.0) &&
6104       (adytail == 0.0) && (bdytail == 0.0) && (cdytail == 0.0) &&
6105       (adheighttail == 0.0) &&
6106       (bdheighttail == 0.0) &&
6107       (cdheighttail == 0.0)) {
6108     return det;
6109   }
6110 
6111   errbound = o3derrboundC * permanent + resulterrbound * Absolute(det);
6112   det += (adheight * ((bdx * cdytail + cdy * bdxtail) -
6113                       (bdy * cdxtail + cdx * bdytail)) +
6114           adheighttail * (bdx * cdy - bdy * cdx)) +
6115          (bdheight * ((cdx * adytail + ady * cdxtail) -
6116                       (cdy * adxtail + adx * cdytail)) +
6117           bdheighttail * (cdx * ady - cdy * adx)) +
6118          (cdheight * ((adx * bdytail + bdy * adxtail) -
6119                       (ady * bdxtail + bdx * adytail)) +
6120           cdheighttail * (adx * bdy - ady * bdx));
6121   if ((det >= errbound) || (-det >= errbound)) {
6122     return det;
6123   }
6124 
6125   finnow = fin1;
6126   finother = fin2;
6127 
6128   if (adxtail == 0.0) {
6129     if (adytail == 0.0) {
6130       at_b[0] = 0.0;
6131       at_blen = 1;
6132       at_c[0] = 0.0;
6133       at_clen = 1;
6134     } else {
6135       negate = -adytail;
6136       Two_Product(negate, bdx, at_blarge, at_b[0]);
6137       at_b[1] = at_blarge;
6138       at_blen = 2;
6139       Two_Product(adytail, cdx, at_clarge, at_c[0]);
6140       at_c[1] = at_clarge;
6141       at_clen = 2;
6142     }
6143   } else {
6144     if (adytail == 0.0) {
6145       Two_Product(adxtail, bdy, at_blarge, at_b[0]);
6146       at_b[1] = at_blarge;
6147       at_blen = 2;
6148       negate = -adxtail;
6149       Two_Product(negate, cdy, at_clarge, at_c[0]);
6150       at_c[1] = at_clarge;
6151       at_clen = 2;
6152     } else {
6153       Two_Product(adxtail, bdy, adxt_bdy1, adxt_bdy0);
6154       Two_Product(adytail, bdx, adyt_bdx1, adyt_bdx0);
6155       Two_Two_Diff(adxt_bdy1, adxt_bdy0, adyt_bdx1, adyt_bdx0,
6156                    at_blarge, at_b[2], at_b[1], at_b[0]);
6157       at_b[3] = at_blarge;
6158       at_blen = 4;
6159       Two_Product(adytail, cdx, adyt_cdx1, adyt_cdx0);
6160       Two_Product(adxtail, cdy, adxt_cdy1, adxt_cdy0);
6161       Two_Two_Diff(adyt_cdx1, adyt_cdx0, adxt_cdy1, adxt_cdy0,
6162                    at_clarge, at_c[2], at_c[1], at_c[0]);
6163       at_c[3] = at_clarge;
6164       at_clen = 4;
6165     }
6166   }
6167   if (bdxtail == 0.0) {
6168     if (bdytail == 0.0) {
6169       bt_c[0] = 0.0;
6170       bt_clen = 1;
6171       bt_a[0] = 0.0;
6172       bt_alen = 1;
6173     } else {
6174       negate = -bdytail;
6175       Two_Product(negate, cdx, bt_clarge, bt_c[0]);
6176       bt_c[1] = bt_clarge;
6177       bt_clen = 2;
6178       Two_Product(bdytail, adx, bt_alarge, bt_a[0]);
6179       bt_a[1] = bt_alarge;
6180       bt_alen = 2;
6181     }
6182   } else {
6183     if (bdytail == 0.0) {
6184       Two_Product(bdxtail, cdy, bt_clarge, bt_c[0]);
6185       bt_c[1] = bt_clarge;
6186       bt_clen = 2;
6187       negate = -bdxtail;
6188       Two_Product(negate, ady, bt_alarge, bt_a[0]);
6189       bt_a[1] = bt_alarge;
6190       bt_alen = 2;
6191     } else {
6192       Two_Product(bdxtail, cdy, bdxt_cdy1, bdxt_cdy0);
6193       Two_Product(bdytail, cdx, bdyt_cdx1, bdyt_cdx0);
6194       Two_Two_Diff(bdxt_cdy1, bdxt_cdy0, bdyt_cdx1, bdyt_cdx0,
6195                    bt_clarge, bt_c[2], bt_c[1], bt_c[0]);
6196       bt_c[3] = bt_clarge;
6197       bt_clen = 4;
6198       Two_Product(bdytail, adx, bdyt_adx1, bdyt_adx0);
6199       Two_Product(bdxtail, ady, bdxt_ady1, bdxt_ady0);
6200       Two_Two_Diff(bdyt_adx1, bdyt_adx0, bdxt_ady1, bdxt_ady0,
6201                   bt_alarge, bt_a[2], bt_a[1], bt_a[0]);
6202       bt_a[3] = bt_alarge;
6203       bt_alen = 4;
6204     }
6205   }
6206   if (cdxtail == 0.0) {
6207     if (cdytail == 0.0) {
6208       ct_a[0] = 0.0;
6209       ct_alen = 1;
6210       ct_b[0] = 0.0;
6211       ct_blen = 1;
6212     } else {
6213       negate = -cdytail;
6214       Two_Product(negate, adx, ct_alarge, ct_a[0]);
6215       ct_a[1] = ct_alarge;
6216       ct_alen = 2;
6217       Two_Product(cdytail, bdx, ct_blarge, ct_b[0]);
6218       ct_b[1] = ct_blarge;
6219       ct_blen = 2;
6220     }
6221   } else {
6222     if (cdytail == 0.0) {
6223       Two_Product(cdxtail, ady, ct_alarge, ct_a[0]);
6224       ct_a[1] = ct_alarge;
6225       ct_alen = 2;
6226       negate = -cdxtail;
6227       Two_Product(negate, bdy, ct_blarge, ct_b[0]);
6228       ct_b[1] = ct_blarge;
6229       ct_blen = 2;
6230     } else {
6231       Two_Product(cdxtail, ady, cdxt_ady1, cdxt_ady0);
6232       Two_Product(cdytail, adx, cdyt_adx1, cdyt_adx0);
6233       Two_Two_Diff(cdxt_ady1, cdxt_ady0, cdyt_adx1, cdyt_adx0,
6234                    ct_alarge, ct_a[2], ct_a[1], ct_a[0]);
6235       ct_a[3] = ct_alarge;
6236       ct_alen = 4;
6237       Two_Product(cdytail, bdx, cdyt_bdx1, cdyt_bdx0);
6238       Two_Product(cdxtail, bdy, cdxt_bdy1, cdxt_bdy0);
6239       Two_Two_Diff(cdyt_bdx1, cdyt_bdx0, cdxt_bdy1, cdxt_bdy0,
6240                    ct_blarge, ct_b[2], ct_b[1], ct_b[0]);
6241       ct_b[3] = ct_blarge;
6242       ct_blen = 4;
6243     }
6244   }
6245 
6246   bctlen = fast_expansion_sum_zeroelim(bt_clen, bt_c, ct_blen, ct_b, bct);
6247   wlength = scale_expansion_zeroelim(bctlen, bct, adheight, w);
6248   finlength = fast_expansion_sum_zeroelim(finlength, finnow, wlength, w,
6249                                           finother);
6250   finswap = finnow; finnow = finother; finother = finswap;
6251 
6252   catlen = fast_expansion_sum_zeroelim(ct_alen, ct_a, at_clen, at_c, cat);
6253   wlength = scale_expansion_zeroelim(catlen, cat, bdheight, w);
6254   finlength = fast_expansion_sum_zeroelim(finlength, finnow, wlength, w,
6255                                           finother);
6256   finswap = finnow; finnow = finother; finother = finswap;
6257 
6258   abtlen = fast_expansion_sum_zeroelim(at_blen, at_b, bt_alen, bt_a, abt);
6259   wlength = scale_expansion_zeroelim(abtlen, abt, cdheight, w);
6260   finlength = fast_expansion_sum_zeroelim(finlength, finnow, wlength, w,
6261                                           finother);
6262   finswap = finnow; finnow = finother; finother = finswap;
6263 
6264   if (adheighttail != 0.0) {
6265     vlength = scale_expansion_zeroelim(4, bc, adheighttail, v);
6266     finlength = fast_expansion_sum_zeroelim(finlength, finnow, vlength, v,
6267                                             finother);
6268     finswap = finnow; finnow = finother; finother = finswap;
6269   }
6270   if (bdheighttail != 0.0) {
6271     vlength = scale_expansion_zeroelim(4, ca, bdheighttail, v);
6272     finlength = fast_expansion_sum_zeroelim(finlength, finnow, vlength, v,
6273                                             finother);
6274     finswap = finnow; finnow = finother; finother = finswap;
6275   }
6276   if (cdheighttail != 0.0) {
6277     vlength = scale_expansion_zeroelim(4, ab, cdheighttail, v);
6278     finlength = fast_expansion_sum_zeroelim(finlength, finnow, vlength, v,
6279                                             finother);
6280     finswap = finnow; finnow = finother; finother = finswap;
6281   }
6282 
6283   if (adxtail != 0.0) {
6284     if (bdytail != 0.0) {
6285       Two_Product(adxtail, bdytail, adxt_bdyt1, adxt_bdyt0);
6286       Two_One_Product(adxt_bdyt1, adxt_bdyt0, cdheight, u3, u[2], u[1], u[0]);
6287       u[3] = u3;
6288       finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
6289                                               finother);
6290       finswap = finnow; finnow = finother; finother = finswap;
6291       if (cdheighttail != 0.0) {
6292         Two_One_Product(adxt_bdyt1, adxt_bdyt0, cdheighttail,
6293                         u3, u[2], u[1], u[0]);
6294         u[3] = u3;
6295         finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
6296                                                 finother);
6297         finswap = finnow; finnow = finother; finother = finswap;
6298       }
6299     }
6300     if (cdytail != 0.0) {
6301       negate = -adxtail;
6302       Two_Product(negate, cdytail, adxt_cdyt1, adxt_cdyt0);
6303       Two_One_Product(adxt_cdyt1, adxt_cdyt0, bdheight, u3, u[2], u[1], u[0]);
6304       u[3] = u3;
6305       finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
6306                                               finother);
6307       finswap = finnow; finnow = finother; finother = finswap;
6308       if (bdheighttail != 0.0) {
6309         Two_One_Product(adxt_cdyt1, adxt_cdyt0, bdheighttail,
6310                         u3, u[2], u[1], u[0]);
6311         u[3] = u3;
6312         finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
6313                                                 finother);
6314         finswap = finnow; finnow = finother; finother = finswap;
6315       }
6316     }
6317   }
6318   if (bdxtail != 0.0) {
6319     if (cdytail != 0.0) {
6320       Two_Product(bdxtail, cdytail, bdxt_cdyt1, bdxt_cdyt0);
6321       Two_One_Product(bdxt_cdyt1, bdxt_cdyt0, adheight, u3, u[2], u[1], u[0]);
6322       u[3] = u3;
6323       finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
6324                                               finother);
6325       finswap = finnow; finnow = finother; finother = finswap;
6326       if (adheighttail != 0.0) {
6327         Two_One_Product(bdxt_cdyt1, bdxt_cdyt0, adheighttail,
6328                         u3, u[2], u[1], u[0]);
6329         u[3] = u3;
6330         finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
6331                                                 finother);
6332         finswap = finnow; finnow = finother; finother = finswap;
6333       }
6334     }
6335     if (adytail != 0.0) {
6336       negate = -bdxtail;
6337       Two_Product(negate, adytail, bdxt_adyt1, bdxt_adyt0);
6338       Two_One_Product(bdxt_adyt1, bdxt_adyt0, cdheight, u3, u[2], u[1], u[0]);
6339       u[3] = u3;
6340       finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
6341                                               finother);
6342       finswap = finnow; finnow = finother; finother = finswap;
6343       if (cdheighttail != 0.0) {
6344         Two_One_Product(bdxt_adyt1, bdxt_adyt0, cdheighttail,
6345                         u3, u[2], u[1], u[0]);
6346         u[3] = u3;
6347         finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
6348                                                 finother);
6349         finswap = finnow; finnow = finother; finother = finswap;
6350       }
6351     }
6352   }
6353   if (cdxtail != 0.0) {
6354     if (adytail != 0.0) {
6355       Two_Product(cdxtail, adytail, cdxt_adyt1, cdxt_adyt0);
6356       Two_One_Product(cdxt_adyt1, cdxt_adyt0, bdheight, u3, u[2], u[1], u[0]);
6357       u[3] = u3;
6358       finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
6359                                               finother);
6360       finswap = finnow; finnow = finother; finother = finswap;
6361       if (bdheighttail != 0.0) {
6362         Two_One_Product(cdxt_adyt1, cdxt_adyt0, bdheighttail,
6363                         u3, u[2], u[1], u[0]);
6364         u[3] = u3;
6365         finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
6366                                                 finother);
6367         finswap = finnow; finnow = finother; finother = finswap;
6368       }
6369     }
6370     if (bdytail != 0.0) {
6371       negate = -cdxtail;
6372       Two_Product(negate, bdytail, cdxt_bdyt1, cdxt_bdyt0);
6373       Two_One_Product(cdxt_bdyt1, cdxt_bdyt0, adheight, u3, u[2], u[1], u[0]);
6374       u[3] = u3;
6375       finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
6376                                               finother);
6377       finswap = finnow; finnow = finother; finother = finswap;
6378       if (adheighttail != 0.0) {
6379         Two_One_Product(cdxt_bdyt1, cdxt_bdyt0, adheighttail,
6380                         u3, u[2], u[1], u[0]);
6381         u[3] = u3;
6382         finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
6383                                                 finother);
6384         finswap = finnow; finnow = finother; finother = finswap;
6385       }
6386     }
6387   }
6388 
6389   if (adheighttail != 0.0) {
6390     wlength = scale_expansion_zeroelim(bctlen, bct, adheighttail, w);
6391     finlength = fast_expansion_sum_zeroelim(finlength, finnow, wlength, w,
6392                                             finother);
6393     finswap = finnow; finnow = finother; finother = finswap;
6394   }
6395   if (bdheighttail != 0.0) {
6396     wlength = scale_expansion_zeroelim(catlen, cat, bdheighttail, w);
6397     finlength = fast_expansion_sum_zeroelim(finlength, finnow, wlength, w,
6398                                             finother);
6399     finswap = finnow; finnow = finother; finother = finswap;
6400   }
6401   if (cdheighttail != 0.0) {
6402     wlength = scale_expansion_zeroelim(abtlen, abt, cdheighttail, w);
6403     finlength = fast_expansion_sum_zeroelim(finlength, finnow, wlength, w,
6404                                             finother);
6405     finswap = finnow; finnow = finother; finother = finswap;
6406   }
6407 
6408   return finnow[finlength - 1];
6409 }
6410 
6411 #ifdef ANSI_DECLARATORS
6412 static REAL orient3d(struct mesh *m, struct behavior *b,
6413               vertex pa, vertex pb, vertex pc, vertex pd,
6414               REAL aheight, REAL bheight, REAL cheight, REAL dheight)
6415 #else /* not ANSI_DECLARATORS */
6416 static REAL orient3d(m, b, pa, pb, pc, pd, aheight, bheight, cheight, dheight)
6417 struct mesh *m;
6418 struct behavior *b;
6419 vertex pa;
6420 vertex pb;
6421 vertex pc;
6422 vertex pd;
6423 REAL aheight;
6424 REAL bheight;
6425 REAL cheight;
6426 REAL dheight;
6427 #endif /* not ANSI_DECLARATORS */
6428 
6429 {
6430   REAL adx, bdx, cdx, ady, bdy, cdy, adheight, bdheight, cdheight;
6431   REAL bdxcdy, cdxbdy, cdxady, adxcdy, adxbdy, bdxady;
6432   REAL det;
6433   REAL permanent, errbound;
6434 
6435   m->orient3dcount++;
6436 
6437   adx = pa[0] - pd[0];
6438   bdx = pb[0] - pd[0];
6439   cdx = pc[0] - pd[0];
6440   ady = pa[1] - pd[1];
6441   bdy = pb[1] - pd[1];
6442   cdy = pc[1] - pd[1];
6443   adheight = aheight - dheight;
6444   bdheight = bheight - dheight;
6445   cdheight = cheight - dheight;
6446 
6447   bdxcdy = bdx * cdy;
6448   cdxbdy = cdx * bdy;
6449 
6450   cdxady = cdx * ady;
6451   adxcdy = adx * cdy;
6452 
6453   adxbdy = adx * bdy;
6454   bdxady = bdx * ady;
6455 
6456   det = adheight * (bdxcdy - cdxbdy)
6457       + bdheight * (cdxady - adxcdy)
6458       + cdheight * (adxbdy - bdxady);
6459 
6460   if (b->noexact) {
6461     return det;
6462   }
6463 
6464   permanent = (Absolute(bdxcdy) + Absolute(cdxbdy)) * Absolute(adheight)
6465             + (Absolute(cdxady) + Absolute(adxcdy)) * Absolute(bdheight)
6466             + (Absolute(adxbdy) + Absolute(bdxady)) * Absolute(cdheight);
6467   errbound = o3derrboundA * permanent;
6468   if ((det > errbound) || (-det > errbound)) {
6469     return det;
6470   }
6471 
6472   return orient3dadapt(pa, pb, pc, pd, aheight, bheight, cheight, dheight,
6473                        permanent);
6474 }
6475 
6476 #endif /* not REDUCED */
6477 
6478 /*****************************************************************************/
6479 /*                                                                           */
6480 /*  nonregular()   Return a positive value if the point pd is incompatible   */
6481 /*                 with the circle or plane passing through pa, pb, and pc   */
6482 /*                 (meaning that pd is inside the circle or below the        */
6483 /*                 plane); a negative value if it is compatible; and zero if */
6484 /*                 the four points are cocircular/coplanar.  The points pa,  */
6485 /*                 pb, and pc must be in counterclockwise order, or the sign */
6486 /*                 of the result will be reversed.                           */
6487 /*                                                                           */
6488 /*  If the -w switch is used, the points are lifted onto the parabolic       */
6489 /*  lifting map, then they are dropped according to their weights, then the  */
6490 /*  3D orientation test is applied.  If the -W switch is used, the points'   */
6491 /*  heights are already provided, so the 3D orientation test is applied      */
6492 /*  directly.  If neither switch is used, the incircle test is applied.      */
6493 /*                                                                           */
6494 /*****************************************************************************/
6495 
6496 #ifndef REDUCED
6497 
6498 #ifdef ANSI_DECLARATORS
6499 static REAL nonregular(struct mesh *m, struct behavior *b,
6500                 vertex pa, vertex pb, vertex pc, vertex pd)
6501 #else /* not ANSI_DECLARATORS */
6502 static REAL nonregular(m, b, pa, pb, pc, pd)
6503 struct mesh *m;
6504 struct behavior *b;
6505 vertex pa;
6506 vertex pb;
6507 vertex pc;
6508 vertex pd;
6509 #endif /* not ANSI_DECLARATORS */
6510 
6511 {
6512   if (b->weighted == 0) {
6513     return incircle(m, b, pa, pb, pc, pd);
6514   } else if (b->weighted == 1) {
6515     return orient3d(m, b, pa, pb, pc, pd,
6516                     pa[0] * pa[0] + pa[1] * pa[1] - pa[2],
6517                     pb[0] * pb[0] + pb[1] * pb[1] - pb[2],
6518                     pc[0] * pc[0] + pc[1] * pc[1] - pc[2],
6519                     pd[0] * pd[0] + pd[1] * pd[1] - pd[2]);
6520   } else {
6521     return orient3d(m, b, pa, pb, pc, pd, pa[2], pb[2], pc[2], pd[2]);
6522   }
6523 }
6524 
6525 #endif /* not REDUCED */
6526 
6527 /*****************************************************************************/
6528 /*                                                                           */
6529 /*  findcircumcenter()   Find the circumcenter of a triangle.                */
6530 /*                                                                           */
6531 /*  The result is returned both in terms of x-y coordinates and xi-eta       */
6532 /*  (barycentric) coordinates.  The xi-eta coordinate system is defined in   */
6533 /*  terms of the triangle:  the origin of the triangle is the origin of the  */
6534 /*  coordinate system; the destination of the triangle is one unit along the */
6535 /*  xi axis; and the apex of the triangle is one unit along the eta axis.    */
6536 /*  This procedure also returns the square of the length of the triangle's   */
6537 /*  shortest edge.                                                           */
6538 /*                                                                           */
6539 /*****************************************************************************/
6540 
6541 #ifdef ANSI_DECLARATORS
6542 static void findcircumcenter(struct mesh *m, struct behavior *b,
6543                       vertex torg, vertex tdest, vertex tapex,
6544                       vertex circumcenter, REAL *xi, REAL *eta, int offcenter)
6545 #else /* not ANSI_DECLARATORS */
6546 static void findcircumcenter(m, b, torg, tdest, tapex, circumcenter, xi, eta,
6547                       offcenter)
6548 struct mesh *m;
6549 struct behavior *b;
6550 vertex torg;
6551 vertex tdest;
6552 vertex tapex;
6553 vertex circumcenter;
6554 REAL *xi;
6555 REAL *eta;
6556 int offcenter;
6557 #endif /* not ANSI_DECLARATORS */
6558 
6559 {
6560   REAL xdo, ydo, xao, yao;
6561   REAL dodist, aodist, dadist;
6562   REAL denominator;
6563   REAL dx, dy, dxoff, dyoff;
6564 
6565   m->circumcentercount++;
6566 
6567   /* Compute the circumcenter of the triangle. */
6568   xdo = tdest[0] - torg[0];
6569   ydo = tdest[1] - torg[1];
6570   xao = tapex[0] - torg[0];
6571   yao = tapex[1] - torg[1];
6572   dodist = xdo * xdo + ydo * ydo;
6573   aodist = xao * xao + yao * yao;
6574   dadist = (tdest[0] - tapex[0]) * (tdest[0] - tapex[0]) +
6575            (tdest[1] - tapex[1]) * (tdest[1] - tapex[1]);
6576   if (b->noexact) {
6577     denominator = 0.5 / (xdo * yao - xao * ydo);
6578   } else {
6579     /* Use the counterclockwise() routine to ensure a positive (and */
6580     /*   reasonably accurate) result, avoiding any possibility of   */
6581     /*   division by zero.                                          */
6582     denominator = 0.5 / counterclockwise(m, b, tdest, tapex, torg);
6583     /* Don't count the above as an orientation test. */
6584     m->counterclockcount--;
6585   }
6586   dx = (yao * dodist - ydo * aodist) * denominator;
6587   dy = (xdo * aodist - xao * dodist) * denominator;
6588 
6589   /* Find the (squared) length of the triangle's shortest edge.  This   */
6590   /*   serves as a conservative estimate of the insertion radius of the */
6591   /*   circumcenter's parent.  The estimate is used to ensure that      */
6592   /*   the algorithm terminates even if very small angles appear in     */
6593   /*   the input PSLG.                                                  */
6594   if ((dodist < aodist) && (dodist < dadist)) {
6595     if (offcenter && (b->offconstant > 0.0)) {
6596       /* Find the position of the off-center, as described by Alper Ungor. */
6597       dxoff = 0.5 * xdo - b->offconstant * ydo;
6598       dyoff = 0.5 * ydo + b->offconstant * xdo;
6599       /* If the off-center is closer to the origin than the */
6600       /*   circumcenter, use the off-center instead.        */
6601       if (dxoff * dxoff + dyoff * dyoff < dx * dx + dy * dy) {
6602         dx = dxoff;
6603         dy = dyoff;
6604       }
6605     }
6606   } else if (aodist < dadist) {
6607     if (offcenter && (b->offconstant > 0.0)) {
6608       dxoff = 0.5 * xao + b->offconstant * yao;
6609       dyoff = 0.5 * yao - b->offconstant * xao;
6610       /* If the off-center is closer to the origin than the */
6611       /*   circumcenter, use the off-center instead.        */
6612       if (dxoff * dxoff + dyoff * dyoff < dx * dx + dy * dy) {
6613         dx = dxoff;
6614         dy = dyoff;
6615       }
6616     }
6617   } else {
6618     if (offcenter && (b->offconstant > 0.0)) {
6619       dxoff = 0.5 * (tapex[0] - tdest[0]) -
6620               b->offconstant * (tapex[1] - tdest[1]);
6621       dyoff = 0.5 * (tapex[1] - tdest[1]) +
6622               b->offconstant * (tapex[0] - tdest[0]);
6623       /* If the off-center is closer to the destination than the */
6624       /*   circumcenter, use the off-center instead.             */
6625       if (dxoff * dxoff + dyoff * dyoff <
6626           (dx - xdo) * (dx - xdo) + (dy - ydo) * (dy - ydo)) {
6627         dx = xdo + dxoff;
6628         dy = ydo + dyoff;
6629       }
6630     }
6631   }
6632 
6633   circumcenter[0] = torg[0] + dx;
6634   circumcenter[1] = torg[1] + dy;
6635 
6636   /* To interpolate vertex attributes for the new vertex inserted at */
6637   /*   the circumcenter, define a coordinate system with a xi-axis,  */
6638   /*   directed from the triangle's origin to its destination, and   */
6639   /*   an eta-axis, directed from its origin to its apex.            */
6640   /*   Calculate the xi and eta coordinates of the circumcenter.     */
6641   *xi = (yao * dx - xao * dy) * (2.0 * denominator);
6642   *eta = (xdo * dy - ydo * dx) * (2.0 * denominator);
6643 }
6644 
6645 /**                                                                         **/
6646 /**                                                                         **/
6647 /********* Geometric primitives end here                             *********/
6648 
6649 /*****************************************************************************/
6650 /*                                                                           */
6651 /*  triangleinit()   Initialize some variables.                              */
6652 /*                                                                           */
6653 /*****************************************************************************/
6654 
6655 #ifdef ANSI_DECLARATORS
6656 static void triangleinit(struct mesh *m)
6657 #else /* not ANSI_DECLARATORS */
6658 static void triangleinit(m)
6659 struct mesh *m;
6660 #endif /* not ANSI_DECLARATORS */
6661 
6662 {
6663   poolzero(&m->vertices);
6664   poolzero(&m->triangles);
6665   poolzero(&m->subsegs);
6666   poolzero(&m->viri);
6667   poolzero(&m->badsubsegs);
6668   poolzero(&m->badtriangles);
6669   poolzero(&m->flipstackers);
6670   poolzero(&m->splaynodes);
6671 
6672   m->recenttri.tri = (triangle *) NULL; /* No triangle has been visited yet. */
6673   m->undeads = 0;                       /* No eliminated input vertices yet. */
6674   m->samples = 1;         /* Point location should take at least one sample. */
6675   m->checksegments = 0;   /* There are no segments in the triangulation yet. */
6676   m->checkquality = 0;     /* The quality triangulation stage has not begun. */
6677   m->incirclecount = m->counterclockcount = m->orient3dcount = 0;
6678   m->hyperbolacount = m->circletopcount = m->circumcentercount = 0;
6679   randomseed = 1;
6680 
6681   exactinit();                     /* Initialize exact arithmetic constants. */
6682 }
6683 
6684 /*****************************************************************************/
6685 /*                                                                           */
6686 /*  randomnation()   Generate a random number between 0 and `choices' - 1.   */
6687 /*                                                                           */
6688 /*  This is a simple linear congruential random number generator.  Hence, it */
6689 /*  is a bad random number generator, but good enough for most randomized    */
6690 /*  geometric algorithms.                                                    */
6691 /*                                                                           */
6692 /*****************************************************************************/
6693 
6694 #ifdef ANSI_DECLARATORS
6695 static unsigned LONG randomnation(unsigned int choices)
6696 #else /* not ANSI_DECLARATORS */
6697 static unsigned LONG randomnation(choices)
6698 unsigned int choices;
6699 #endif /* not ANSI_DECLARATORS */
6700 
6701 {
6702   randomseed = (randomseed * 1366l + 150889l) % 714025l;
6703   return randomseed / (714025l / choices + 1);
6704 }
6705 
6706 /********* Mesh quality testing routines begin here                  *********/
6707 /**                                                                         **/
6708 /**                                                                         **/
6709 
6710 /*****************************************************************************/
6711 /*                                                                           */
6712 /*  checkmesh()   Test the mesh for topological consistency.                 */
6713 /*                                                                           */
6714 /*****************************************************************************/
6715 
6716 #ifndef REDUCED
6717 
6718 #ifdef ANSI_DECLARATORS
6719 static void checkmesh(struct mesh *m, struct behavior *b)
6720 #else /* not ANSI_DECLARATORS */
6721 static void checkmesh(m, b)
6722 struct mesh *m;
6723 struct behavior *b;
6724 #endif /* not ANSI_DECLARATORS */
6725 
6726 {
6727   struct otri triangleloop;
6728   struct otri oppotri, oppooppotri;
6729   vertex triorg, tridest, triapex;
6730   vertex oppoorg, oppodest;
6731   int horrors;
6732   int saveexact;
6733   triangle ptr;                         /* Temporary variable used by sym(). */
6734 
6735   /* Temporarily turn on exact arithmetic if it's off. */
6736   saveexact = b->noexact;
6737   b->noexact = 0;
6738   if (!b->quiet) {
6739     printf("  Checking consistency of mesh...\n");
6740   }
6741   horrors = 0;
6742   /* Run through the list of triangles, checking each one. */
6743   traversalinit(&m->triangles);
6744   triangleloop.tri = triangletraverse(m);
6745   while (triangleloop.tri != (triangle *) NULL) {
6746     /* Check all three edges of the triangle. */
6747     for (triangleloop.orient = 0; triangleloop.orient < 3;
6748          triangleloop.orient++) {
6749       org(triangleloop, triorg);
6750       dest(triangleloop, tridest);
6751       if (triangleloop.orient == 0) {       /* Only test for inversion once. */
6752         /* Test if the triangle is flat or inverted. */
6753         apex(triangleloop, triapex);
6754         if (counterclockwise(m, b, triorg, tridest, triapex) <= 0.0) {
6755           printf("  !! !! Inverted ");
6756           printtriangle(m, b, &triangleloop);
6757           horrors++;
6758         }
6759       }
6760       /* Find the neighboring triangle on this edge. */
6761       sym(triangleloop, oppotri);
6762       if (oppotri.tri != m->dummytri) {
6763         /* Check that the triangle's neighbor knows it's a neighbor. */
6764         sym(oppotri, oppooppotri);
6765         if ((triangleloop.tri != oppooppotri.tri)
6766             || (triangleloop.orient != oppooppotri.orient)) {
6767           printf("  !! !! Asymmetric triangle-triangle bond:\n");
6768           if (triangleloop.tri == oppooppotri.tri) {
6769             printf("   (Right triangle, wrong orientation)\n");
6770           }
6771           printf("    First ");
6772           printtriangle(m, b, &triangleloop);
6773           printf("    Second (nonreciprocating) ");
6774           printtriangle(m, b, &oppotri);
6775           horrors++;
6776         }
6777         /* Check that both triangles agree on the identities */
6778         /*   of their shared vertices.                       */
6779         org(oppotri, oppoorg);
6780         dest(oppotri, oppodest);
6781         if ((triorg != oppodest) || (tridest != oppoorg)) {
6782           printf("  !! !! Mismatched edge coordinates between two triangles:\n"
6783                  );
6784           printf("    First mismatched ");
6785           printtriangle(m, b, &triangleloop);
6786           printf("    Second mismatched ");
6787           printtriangle(m, b, &oppotri);
6788           horrors++;
6789         }
6790       }
6791     }
6792     triangleloop.tri = triangletraverse(m);
6793   }
6794   if (horrors == 0) {
6795     if (!b->quiet) {
6796       printf("  In my studied opinion, the mesh appears to be consistent.\n");
6797     }
6798   } else if (horrors == 1) {
6799     printf("  !! !! !! !! Precisely one festering wound discovered.\n");
6800   } else {
6801     printf("  !! !! !! !! %d abominations witnessed.\n", horrors);
6802   }
6803   /* Restore the status of exact arithmetic. */
6804   b->noexact = saveexact;
6805 }
6806 
6807 #endif /* not REDUCED */
6808 
6809 /*****************************************************************************/
6810 /*                                                                           */
6811 /*  checkdelaunay()   Ensure that the mesh is (constrained) Delaunay.        */
6812 /*                                                                           */
6813 /*****************************************************************************/
6814 
6815 #ifndef REDUCED
6816 
6817 #ifdef ANSI_DECLARATORS
6818 static void checkdelaunay(struct mesh *m, struct behavior *b)
6819 #else /* not ANSI_DECLARATORS */
6820 static void checkdelaunay(m, b)
6821 struct mesh *m;
6822 struct behavior *b;
6823 #endif /* not ANSI_DECLARATORS */
6824 
6825 {
6826   struct otri triangleloop;
6827   struct otri oppotri;
6828   struct osub opposubseg;
6829   vertex triorg, tridest, triapex;
6830   vertex oppoapex;
6831   int shouldbedelaunay;
6832   int horrors;
6833   int saveexact;
6834   triangle ptr;                         /* Temporary variable used by sym(). */
6835   subseg sptr;                      /* Temporary variable used by tspivot(). */
6836 
6837   /* Temporarily turn on exact arithmetic if it's off. */
6838   saveexact = b->noexact;
6839   b->noexact = 0;
6840   if (!b->quiet) {
6841     printf("  Checking Delaunay property of mesh...\n");
6842   }
6843   horrors = 0;
6844   /* Run through the list of triangles, checking each one. */
6845   traversalinit(&m->triangles);
6846   triangleloop.tri = triangletraverse(m);
6847   while (triangleloop.tri != (triangle *) NULL) {
6848     /* Check all three edges of the triangle. */
6849     for (triangleloop.orient = 0; triangleloop.orient < 3;
6850          triangleloop.orient++) {
6851       org(triangleloop, triorg);
6852       dest(triangleloop, tridest);
6853       apex(triangleloop, triapex);
6854       sym(triangleloop, oppotri);
6855       apex(oppotri, oppoapex);
6856       /* Only test that the edge is locally Delaunay if there is an   */
6857       /*   adjoining triangle whose pointer is larger (to ensure that */
6858       /*   each pair isn't tested twice).                             */
6859       shouldbedelaunay = (oppotri.tri != m->dummytri) &&
6860             !deadtri(oppotri.tri) && (triangleloop.tri < oppotri.tri) &&
6861             (triorg != m->infvertex1) && (triorg != m->infvertex2) &&
6862             (triorg != m->infvertex3) &&
6863             (tridest != m->infvertex1) && (tridest != m->infvertex2) &&
6864             (tridest != m->infvertex3) &&
6865             (triapex != m->infvertex1) && (triapex != m->infvertex2) &&
6866             (triapex != m->infvertex3) &&
6867             (oppoapex != m->infvertex1) && (oppoapex != m->infvertex2) &&
6868             (oppoapex != m->infvertex3);
6869       if (m->checksegments && shouldbedelaunay) {
6870         /* If a subsegment separates the triangles, then the edge is */
6871         /*   constrained, so no local Delaunay test should be done.  */
6872         tspivot(triangleloop, opposubseg);
6873         if (opposubseg.ss != m->dummysub){
6874           shouldbedelaunay = 0;
6875         }
6876       }
6877       if (shouldbedelaunay) {
6878         if (nonregular(m, b, triorg, tridest, triapex, oppoapex) > 0.0) {
6879           if (!b->weighted) {
6880             printf("  !! !! Non-Delaunay pair of triangles:\n");
6881             printf("    First non-Delaunay ");
6882             printtriangle(m, b, &triangleloop);
6883             printf("    Second non-Delaunay ");
6884           } else {
6885             printf("  !! !! Non-regular pair of triangles:\n");
6886             printf("    First non-regular ");
6887             printtriangle(m, b, &triangleloop);
6888             printf("    Second non-regular ");
6889           }
6890           printtriangle(m, b, &oppotri);
6891           horrors++;
6892         }
6893       }
6894     }
6895     triangleloop.tri = triangletraverse(m);
6896   }
6897   if (horrors == 0) {
6898     if (!b->quiet) {
6899       printf(
6900   "  By virtue of my perceptive intelligence, I declare the mesh Delaunay.\n");
6901     }
6902   } else if (horrors == 1) {
6903     printf(
6904          "  !! !! !! !! Precisely one terrifying transgression identified.\n");
6905   } else {
6906     printf("  !! !! !! !! %d obscenities viewed with horror.\n", horrors);
6907   }
6908   /* Restore the status of exact arithmetic. */
6909   b->noexact = saveexact;
6910 }
6911 
6912 #endif /* not REDUCED */
6913 
6914 /*****************************************************************************/
6915 /*                                                                           */
6916 /*  enqueuebadtriang()   Add a bad triangle data structure to the end of a   */
6917 /*                       queue.                                              */
6918 /*                                                                           */
6919 /*  The queue is actually a set of 4096 queues.  I use multiple queues to    */
6920 /*  give priority to smaller angles.  I originally implemented a heap, but   */
6921 /*  the queues are faster by a larger margin than I'd suspected.             */
6922 /*                                                                           */
6923 /*****************************************************************************/
6924 
6925 #ifndef CDT_ONLY
6926 
6927 #ifdef ANSI_DECLARATORS
6928 static void enqueuebadtriang(struct mesh *m, struct behavior *b,
6929                       struct badtriang *badtri)
6930 #else /* not ANSI_DECLARATORS */
6931 static void enqueuebadtriang(m, b, badtri)
6932 struct mesh *m;
6933 struct behavior *b;
6934 struct badtriang *badtri;
6935 #endif /* not ANSI_DECLARATORS */
6936 
6937 {
6938   REAL length, multiplier;
6939   int exponent, expincrement;
6940   int queuenumber;
6941   int posexponent;
6942   int i;
6943 
6944   if (b->verbose > 2) {
6945     printf("  Queueing bad triangle:\n");
6946     printf("    (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
6947            badtri->triangorg[0], badtri->triangorg[1],
6948            badtri->triangdest[0], badtri->triangdest[1],
6949            badtri->triangapex[0], badtri->triangapex[1]);
6950   }
6951 
6952   /* Determine the appropriate queue to put the bad triangle into.    */
6953   /*   Recall that the key is the square of its shortest edge length. */
6954   if (badtri->key >= 1.0) {
6955     length = badtri->key;
6956     posexponent = 1;
6957   } else {
6958     /* `badtri->key' is 2.0 to a negative exponent, so we'll record that */
6959     /*   fact and use the reciprocal of `badtri->key', which is > 1.0.   */
6960     length = 1.0 / badtri->key;
6961     posexponent = 0;
6962   }
6963   /* `length' is approximately 2.0 to what exponent?  The following code */
6964   /*   determines the answer in time logarithmic in the exponent.        */
6965   exponent = 0;
6966   while (length > 2.0) {
6967     /* Find an approximation by repeated squaring of two. */
6968     expincrement = 1;
6969     multiplier = 0.5;
6970     while (length * multiplier * multiplier > 1.0) {
6971       expincrement *= 2;
6972       multiplier *= multiplier;
6973     }
6974     /* Reduce the value of `length', then iterate if necessary. */
6975     exponent += expincrement;
6976     length *= multiplier;
6977   }
6978   /* `length' is approximately squareroot(2.0) to what exponent? */
6979   exponent = 2.0 * exponent + (length > SQUAREROOTTWO);
6980   /* `exponent' is now in the range 0...2047 for IEEE double precision.   */
6981   /*   Choose a queue in the range 0...4095.  The shortest edges have the */
6982   /*   highest priority (queue 4095).                                     */
6983   if (posexponent) {
6984     queuenumber = 2047 - exponent;
6985   } else {
6986     queuenumber = 2048 + exponent;
6987   }
6988 
6989   /* Are we inserting into an empty queue? */
6990   if (m->queuefront[queuenumber] == (struct badtriang *) NULL) {
6991     /* Yes, we are inserting into an empty queue.     */
6992     /*   Will this become the highest-priority queue? */
6993     if (queuenumber > m->firstnonemptyq) {
6994       /* Yes, this is the highest-priority queue. */
6995       m->nextnonemptyq[queuenumber] = m->firstnonemptyq;
6996       m->firstnonemptyq = queuenumber;
6997     } else {
6998       /* No, this is not the highest-priority queue. */
6999       /*   Find the queue with next higher priority. */
7000       i = queuenumber + 1;
7001       while (m->queuefront[i] == (struct badtriang *) NULL) {
7002         i++;
7003       }
7004       /* Mark the newly nonempty queue as following a higher-priority queue. */
7005       m->nextnonemptyq[queuenumber] = m->nextnonemptyq[i];
7006       m->nextnonemptyq[i] = queuenumber;
7007     }
7008     /* Put the bad triangle at the beginning of the (empty) queue. */
7009     m->queuefront[queuenumber] = badtri;
7010   } else {
7011     /* Add the bad triangle to the end of an already nonempty queue. */
7012     m->queuetail[queuenumber]->nexttriang = badtri;
7013   }
7014   /* Maintain a pointer to the last triangle of the queue. */
7015   m->queuetail[queuenumber] = badtri;
7016   /* Newly enqueued bad triangle has no successor in the queue. */
7017   badtri->nexttriang = (struct badtriang *) NULL;
7018 }
7019 
7020 #endif /* not CDT_ONLY */
7021 
7022 /*****************************************************************************/
7023 /*                                                                           */
7024 /*  enqueuebadtri()   Add a bad triangle to the end of a queue.              */
7025 /*                                                                           */
7026 /*  Allocates a badtriang data structure for the triangle, then passes it to */
7027 /*  enqueuebadtriang().                                                      */
7028 /*                                                                           */
7029 /*****************************************************************************/
7030 
7031 #ifndef CDT_ONLY
7032 
7033 #ifdef ANSI_DECLARATORS
7034 static void enqueuebadtri(struct mesh *m, struct behavior *b, struct otri *enqtri,
7035                    REAL minedge, vertex enqapex, vertex enqorg, vertex enqdest)
7036 #else /* not ANSI_DECLARATORS */
7037 static void enqueuebadtri(m, b, enqtri, minedge, enqapex, enqorg, enqdest)
7038 struct mesh *m;
7039 struct behavior *b;
7040 struct otri *enqtri;
7041 REAL minedge;
7042 vertex enqapex;
7043 vertex enqorg;
7044 vertex enqdest;
7045 #endif /* not ANSI_DECLARATORS */
7046 
7047 {
7048   struct badtriang *newbad;
7049 
7050   /* Allocate space for the bad triangle. */
7051   newbad = (struct badtriang *) poolalloc(&m->badtriangles);
7052   newbad->poortri = encode(*enqtri);
7053   newbad->key = minedge;
7054   newbad->triangapex = enqapex;
7055   newbad->triangorg = enqorg;
7056   newbad->triangdest = enqdest;
7057   enqueuebadtriang(m, b, newbad);
7058 }
7059 
7060 #endif /* not CDT_ONLY */
7061 
7062 /*****************************************************************************/
7063 /*                                                                           */
7064 /*  dequeuebadtriang()   Remove a triangle from the front of the queue.      */
7065 /*                                                                           */
7066 /*****************************************************************************/
7067 
7068 #ifndef CDT_ONLY
7069 
7070 #ifdef ANSI_DECLARATORS
7071 struct badtriang *dequeuebadtriang(struct mesh *m)
7072 #else /* not ANSI_DECLARATORS */
7073 struct badtriang *dequeuebadtriang(m)
7074 struct mesh *m;
7075 #endif /* not ANSI_DECLARATORS */
7076 
7077 {
7078   struct badtriang *result;
7079 
7080   /* If no queues are nonempty, return NULL. */
7081   if (m->firstnonemptyq < 0) {
7082     return (struct badtriang *) NULL;
7083   }
7084   /* Find the first triangle of the highest-priority queue. */
7085   result = m->queuefront[m->firstnonemptyq];
7086   /* Remove the triangle from the queue. */
7087   m->queuefront[m->firstnonemptyq] = result->nexttriang;
7088   /* If this queue is now empty, note the new highest-priority */
7089   /*   nonempty queue.                                         */
7090   if (result == m->queuetail[m->firstnonemptyq]) {
7091     m->firstnonemptyq = m->nextnonemptyq[m->firstnonemptyq];
7092   }
7093   return result;
7094 }
7095 
7096 #endif /* not CDT_ONLY */
7097 
7098 /*****************************************************************************/
7099 /*                                                                           */
7100 /*  checkseg4encroach()   Check a subsegment to see if it is encroached; add */
7101 /*                        it to the list if it is.                           */
7102 /*                                                                           */
7103 /*  A subsegment is encroached if there is a vertex in its diametral lens.   */
7104 /*  For Ruppert's algorithm (-D switch), the "diametral lens" is the         */
7105 /*  diametral circle.  For Chew's algorithm (default), the diametral lens is */
7106 /*  just big enough to enclose two isosceles triangles whose bases are the   */
7107 /*  subsegment.  Each of the two isosceles triangles has two angles equal    */
7108 /*  to `b->minangle'.                                                        */
7109 /*                                                                           */
7110 /*  Chew's algorithm does not require diametral lenses at all--but they save */
7111 /*  time.  Any vertex inside a subsegment's diametral lens implies that the  */
7112 /*  triangle adjoining the subsegment will be too skinny, so it's only a     */
7113 /*  matter of time before the encroaching vertex is deleted by Chew's        */
7114 /*  algorithm.  It's faster to simply not insert the doomed vertex in the    */
7115 /*  first place, which is why I use diametral lenses with Chew's algorithm.  */
7116 /*                                                                           */
7117 /*  Returns a nonzero value if the subsegment is encroached.                 */
7118 /*                                                                           */
7119 /*****************************************************************************/
7120 
7121 #ifndef CDT_ONLY
7122 
7123 #ifdef ANSI_DECLARATORS
7124 static int checkseg4encroach(struct mesh *m, struct behavior *b,
7125                       struct osub *testsubseg)
7126 #else /* not ANSI_DECLARATORS */
7127 static int checkseg4encroach(m, b, testsubseg)
7128 struct mesh *m;
7129 struct behavior *b;
7130 struct osub *testsubseg;
7131 #endif /* not ANSI_DECLARATORS */
7132 
7133 {
7134   struct otri neighbortri;
7135   struct osub testsym;
7136   struct badsubseg *encroachedseg;
7137   REAL dotproduct;
7138   int encroached;
7139   int sides;
7140   vertex eorg, edest, eapex;
7141   triangle ptr;                     /* Temporary variable used by stpivot(). */
7142 
7143   encroached = 0;
7144   sides = 0;
7145 
7146   sorg(*testsubseg, eorg);
7147   sdest(*testsubseg, edest);
7148   /* Check one neighbor of the subsegment. */
7149   stpivot(*testsubseg, neighbortri);
7150   /* Does the neighbor exist, or is this a boundary edge? */
7151   if (neighbortri.tri != m->dummytri) {
7152     sides++;
7153     /* Find a vertex opposite this subsegment. */
7154     apex(neighbortri, eapex);
7155     /* Check whether the apex is in the diametral lens of the subsegment */
7156     /*   (the diametral circle if `conformdel' is set).  A dot product   */
7157     /*   of two sides of the triangle is used to check whether the angle */
7158     /*   at the apex is greater than (180 - 2 `minangle') degrees (for   */
7159     /*   lenses; 90 degrees for diametral circles).                      */
7160     dotproduct = (eorg[0] - eapex[0]) * (edest[0] - eapex[0]) +
7161                  (eorg[1] - eapex[1]) * (edest[1] - eapex[1]);
7162     if (dotproduct < 0.0) {
7163       if (b->conformdel ||
7164           (dotproduct * dotproduct >=
7165            (2.0 * b->goodangle - 1.0) * (2.0 * b->goodangle - 1.0) *
7166            ((eorg[0] - eapex[0]) * (eorg[0] - eapex[0]) +
7167             (eorg[1] - eapex[1]) * (eorg[1] - eapex[1])) *
7168            ((edest[0] - eapex[0]) * (edest[0] - eapex[0]) +
7169             (edest[1] - eapex[1]) * (edest[1] - eapex[1])))) {
7170         encroached = 1;
7171       }
7172     }
7173   }
7174   /* Check the other neighbor of the subsegment. */
7175   ssym(*testsubseg, testsym);
7176   stpivot(testsym, neighbortri);
7177   /* Does the neighbor exist, or is this a boundary edge? */
7178   if (neighbortri.tri != m->dummytri) {
7179     sides++;
7180     /* Find the other vertex opposite this subsegment. */
7181     apex(neighbortri, eapex);
7182     /* Check whether the apex is in the diametral lens of the subsegment */
7183     /*   (or the diametral circle, if `conformdel' is set).              */
7184     dotproduct = (eorg[0] - eapex[0]) * (edest[0] - eapex[0]) +
7185                  (eorg[1] - eapex[1]) * (edest[1] - eapex[1]);
7186     if (dotproduct < 0.0) {
7187       if (b->conformdel ||
7188           (dotproduct * dotproduct >=
7189            (2.0 * b->goodangle - 1.0) * (2.0 * b->goodangle - 1.0) *
7190            ((eorg[0] - eapex[0]) * (eorg[0] - eapex[0]) +
7191             (eorg[1] - eapex[1]) * (eorg[1] - eapex[1])) *
7192            ((edest[0] - eapex[0]) * (edest[0] - eapex[0]) +
7193             (edest[1] - eapex[1]) * (edest[1] - eapex[1])))) {
7194         encroached += 2;
7195       }
7196     }
7197   }
7198 
7199   if (encroached && (!b->nobisect || ((b->nobisect == 1) && (sides == 2)))) {
7200     if (b->verbose > 2) {
7201       printf(
7202         "  Queueing encroached subsegment (%.12g, %.12g) (%.12g, %.12g).\n",
7203         eorg[0], eorg[1], edest[0], edest[1]);
7204     }
7205     /* Add the subsegment to the list of encroached subsegments. */
7206     /*   Be sure to get the orientation right.                   */
7207     encroachedseg = (struct badsubseg *) poolalloc(&m->badsubsegs);
7208     if (encroached == 1) {
7209       encroachedseg->encsubseg = sencode(*testsubseg);
7210       encroachedseg->subsegorg = eorg;
7211       encroachedseg->subsegdest = edest;
7212     } else {
7213       encroachedseg->encsubseg = sencode(testsym);
7214       encroachedseg->subsegorg = edest;
7215       encroachedseg->subsegdest = eorg;
7216     }
7217   }
7218 
7219   return encroached;
7220 }
7221 
7222 #endif /* not CDT_ONLY */
7223 
7224 /*****************************************************************************/
7225 /*                                                                           */
7226 /*  testtriangle()   Test a triangle for quality and size.                   */
7227 /*                                                                           */
7228 /*  Tests a triangle to see if it satisfies the minimum angle condition and  */
7229 /*  the maximum area condition.  Triangles that aren't up to spec are added  */
7230 /*  to the bad triangle queue.                                               */
7231 /*                                                                           */
7232 /*****************************************************************************/
7233 
7234 #ifndef CDT_ONLY
7235 
7236 #ifdef ANSI_DECLARATORS
7237 static void testtriangle(struct mesh *m, struct behavior *b, struct otri *testtri)
7238 #else /* not ANSI_DECLARATORS */
7239 static void testtriangle(m, b, testtri)
7240 struct mesh *m;
7241 struct behavior *b;
7242 struct otri *testtri;
7243 #endif /* not ANSI_DECLARATORS */
7244 
7245 {
7246   struct otri tri1, tri2;
7247   struct osub testsub;
7248   vertex torg, tdest, tapex;
7249   vertex base1, base2;
7250   vertex org1, dest1, org2, dest2;
7251   vertex joinvertex;
7252   REAL dxod, dyod, dxda, dyda, dxao, dyao;
7253   REAL dxod2, dyod2, dxda2, dyda2, dxao2, dyao2;
7254   REAL apexlen, orglen, destlen, minedge;
7255   REAL angle;
7256   REAL area;
7257   REAL dist1, dist2;
7258   subseg sptr;                      /* Temporary variable used by tspivot(). */
7259   triangle ptr;           /* Temporary variable used by oprev() and dnext(). */
7260 
7261   org(*testtri, torg);
7262   dest(*testtri, tdest);
7263   apex(*testtri, tapex);
7264   dxod = torg[0] - tdest[0];
7265   dyod = torg[1] - tdest[1];
7266   dxda = tdest[0] - tapex[0];
7267   dyda = tdest[1] - tapex[1];
7268   dxao = tapex[0] - torg[0];
7269   dyao = tapex[1] - torg[1];
7270   dxod2 = dxod * dxod;
7271   dyod2 = dyod * dyod;
7272   dxda2 = dxda * dxda;
7273   dyda2 = dyda * dyda;
7274   dxao2 = dxao * dxao;
7275   dyao2 = dyao * dyao;
7276   /* Find the lengths of the triangle's three edges. */
7277   apexlen = dxod2 + dyod2;
7278   orglen = dxda2 + dyda2;
7279   destlen = dxao2 + dyao2;
7280 
7281   if ((apexlen < orglen) && (apexlen < destlen)) {
7282     /* The edge opposite the apex is shortest. */
7283     minedge = apexlen;
7284     /* Find the square of the cosine of the angle at the apex. */
7285     angle = dxda * dxao + dyda * dyao;
7286     angle = angle * angle / (orglen * destlen);
7287     base1 = torg;
7288     base2 = tdest;
7289     otricopy(*testtri, tri1);
7290   } else if (orglen < destlen) {
7291     /* The edge opposite the origin is shortest. */
7292     minedge = orglen;
7293     /* Find the square of the cosine of the angle at the origin. */
7294     angle = dxod * dxao + dyod * dyao;
7295     angle = angle * angle / (apexlen * destlen);
7296     base1 = tdest;
7297     base2 = tapex;
7298     lnext(*testtri, tri1);
7299   } else {
7300     /* The edge opposite the destination is shortest. */
7301     minedge = destlen;
7302     /* Find the square of the cosine of the angle at the destination. */
7303     angle = dxod * dxda + dyod * dyda;
7304     angle = angle * angle / (apexlen * orglen);
7305     base1 = tapex;
7306     base2 = torg;
7307     lprev(*testtri, tri1);
7308   }
7309 
7310   if (b->vararea || b->fixedarea || b->usertest) {
7311     /* Check whether the area is larger than permitted. */
7312     area = 0.5 * (dxod * dyda - dyod * dxda);
7313     if (b->fixedarea && (area > b->maxarea)) {
7314       /* Add this triangle to the list of bad triangles. */
7315       enqueuebadtri(m, b, testtri, minedge, tapex, torg, tdest);
7316       return;
7317     }
7318 
7319     /* Nonpositive area constraints are treated as unconstrained. */
7320     if ((b->vararea) && (area > areabound(*testtri)) &&
7321         (areabound(*testtri) > 0.0)) {
7322       /* Add this triangle to the list of bad triangles. */
7323       enqueuebadtri(m, b, testtri, minedge, tapex, torg, tdest);
7324       return;
7325     }
7326 
7327     if (b->usertest) {
7328       /* Check whether the user thinks this triangle is too large. */
7329       if (triunsuitable(torg, tdest, tapex, area)) {
7330         enqueuebadtri(m, b, testtri, minedge, tapex, torg, tdest);
7331         return;
7332       }
7333     }
7334   }
7335 
7336   /* Check whether the angle is smaller than permitted. */
7337   if (angle > b->goodangle) {
7338     /* Use the rules of Miller, Pav, and Walkington to decide that certain */
7339     /*   triangles should not be split, even if they have bad angles.      */
7340     /*   A skinny triangle is not split if its shortest edge subtends a    */
7341     /*   small input angle, and both endpoints of the edge lie on a        */
7342     /*   concentric circular shell.  For convenience, I make a small       */
7343     /*   adjustment to that rule:  I check if the endpoints of the edge    */
7344     /*   both lie in segment interiors, equidistant from the apex where    */
7345     /*   the two segments meet.                                            */
7346     /* First, check if both points lie in segment interiors.               */
7347     if ((vertextype(base1) == SEGMENTVERTEX) &&
7348         (vertextype(base2) == SEGMENTVERTEX)) {
7349       /* Check if both points lie in a common segment.  If they do, the */
7350       /*   skinny triangle is enqueued to be split as usual.            */
7351       tspivot(tri1, testsub);
7352       if (testsub.ss == m->dummysub) {
7353         /* No common segment.  Find a subsegment that contains `torg'. */
7354         otricopy(tri1, tri2);
7355         do {
7356           oprevself(tri1);
7357           tspivot(tri1, testsub);
7358         } while (testsub.ss == m->dummysub);
7359         /* Find the endpoints of the containing segment. */
7360         segorg(testsub, org1);
7361         segdest(testsub, dest1);
7362         /* Find a subsegment that contains `tdest'. */
7363         do {
7364           dnextself(tri2);
7365           tspivot(tri2, testsub);
7366         } while (testsub.ss == m->dummysub);
7367         /* Find the endpoints of the containing segment. */
7368         segorg(testsub, org2);
7369         segdest(testsub, dest2);
7370         /* Check if the two containing segments have an endpoint in common. */
7371         joinvertex = (vertex) NULL;
7372         if ((dest1[0] == org2[0]) && (dest1[1] == org2[1])) {
7373           joinvertex = dest1;
7374         } else if ((org1[0] == dest2[0]) && (org1[1] == dest2[1])) {
7375           joinvertex = org1;
7376         }
7377         if (joinvertex != (vertex) NULL) {
7378           /* Compute the distance from the common endpoint (of the two  */
7379           /*   segments) to each of the endpoints of the shortest edge. */
7380           dist1 = ((base1[0] - joinvertex[0]) * (base1[0] - joinvertex[0]) +
7381                    (base1[1] - joinvertex[1]) * (base1[1] - joinvertex[1]));
7382           dist2 = ((base2[0] - joinvertex[0]) * (base2[0] - joinvertex[0]) +
7383                    (base2[1] - joinvertex[1]) * (base2[1] - joinvertex[1]));
7384           /* If the two distances are equal, don't split the triangle. */
7385           if ((dist1 < 1.001 * dist2) && (dist1 > 0.999 * dist2)) {
7386             /* Return now to avoid enqueueing the bad triangle. */
7387             return;
7388           }
7389         }
7390       }
7391     }
7392 
7393     /* Add this triangle to the list of bad triangles. */
7394     enqueuebadtri(m, b, testtri, minedge, tapex, torg, tdest);
7395   }
7396 }
7397 
7398 #endif /* not CDT_ONLY */
7399 
7400 /**                                                                         **/
7401 /**                                                                         **/
7402 /********* Mesh quality testing routines end here                    *********/
7403 
7404 /********* Point location routines begin here                        *********/
7405 /**                                                                         **/
7406 /**                                                                         **/
7407 
7408 /*****************************************************************************/
7409 /*                                                                           */
7410 /*  makevertexmap()   Construct a mapping from vertices to triangles to      */
7411 /*                    improve the speed of point location for segment        */
7412 /*                    insertion.                                             */
7413 /*                                                                           */
7414 /*  Traverses all the triangles, and provides each corner of each triangle   */
7415 /*  with a pointer to that triangle.  Of course, pointers will be            */
7416 /*  overwritten by other pointers because (almost) each vertex is a corner   */
7417 /*  of several triangles, but in the end every vertex will point to some     */
7418 /*  triangle that contains it.                                               */
7419 /*                                                                           */
7420 /*****************************************************************************/
7421 
7422 #ifdef ANSI_DECLARATORS
7423 static void makevertexmap(struct mesh *m, struct behavior *b)
7424 #else /* not ANSI_DECLARATORS */
7425 static void makevertexmap(m, b)
7426 struct mesh *m;
7427 struct behavior *b;
7428 #endif /* not ANSI_DECLARATORS */
7429 
7430 {
7431   struct otri triangleloop;
7432   vertex triorg;
7433 
7434   if (b->verbose) {
7435     printf("    Constructing mapping from vertices to triangles.\n");
7436   }
7437   traversalinit(&m->triangles);
7438   triangleloop.tri = triangletraverse(m);
7439   while (triangleloop.tri != (triangle *) NULL) {
7440     /* Check all three vertices of the triangle. */
7441     for (triangleloop.orient = 0; triangleloop.orient < 3;
7442          triangleloop.orient++) {
7443       org(triangleloop, triorg);
7444       setvertex2tri(triorg, encode(triangleloop));
7445     }
7446     triangleloop.tri = triangletraverse(m);
7447   }
7448 }
7449 
7450 /*****************************************************************************/
7451 /*                                                                           */
7452 /*  preciselocate()   Find a triangle or edge containing a given point.      */
7453 /*                                                                           */
7454 /*  Begins its search from `searchtri'.  It is important that `searchtri'    */
7455 /*  be a handle with the property that `searchpoint' is strictly to the left */
7456 /*  of the edge denoted by `searchtri', or is collinear with that edge and   */
7457 /*  does not intersect that edge.  (In particular, `searchpoint' should not  */
7458 /*  be the origin or destination of that edge.)                              */
7459 /*                                                                           */
7460 /*  These conditions are imposed because preciselocate() is normally used in */
7461 /*  one of two situations:                                                   */
7462 /*                                                                           */
7463 /*  (1)  To try to find the location to insert a new point.  Normally, we    */
7464 /*       know an edge that the point is strictly to the left of.  In the     */
7465 /*       incremental Delaunay algorithm, that edge is a bounding box edge.   */
7466 /*       In Ruppert's Delaunay refinement algorithm for quality meshing,     */
7467 /*       that edge is the shortest edge of the triangle whose circumcenter   */
7468 /*       is being inserted.                                                  */
7469 /*                                                                           */
7470 /*  (2)  To try to find an existing point.  In this case, any edge on the    */
7471 /*       convex hull is a good starting edge.  You must screen out the       */
7472 /*       possibility that the vertex sought is an endpoint of the starting   */
7473 /*       edge before you call preciselocate().                               */
7474 /*                                                                           */
7475 /*  On completion, `searchtri' is a triangle that contains `searchpoint'.    */
7476 /*                                                                           */
7477 /*  This implementation differs from that given by Guibas and Stolfi.  It    */
7478 /*  walks from triangle to triangle, crossing an edge only if `searchpoint'  */
7479 /*  is on the other side of the line containing that edge.  After entering   */
7480 /*  a triangle, there are two edges by which one can leave that triangle.    */
7481 /*  If both edges are valid (`searchpoint' is on the other side of both      */
7482 /*  edges), one of the two is chosen by drawing a line perpendicular to      */
7483 /*  the entry edge (whose endpoints are `forg' and `fdest') passing through  */
7484 /*  `fapex'.  Depending on which side of this perpendicular `searchpoint'    */
7485 /*  falls on, an exit edge is chosen.                                        */
7486 /*                                                                           */
7487 /*  This implementation is empirically faster than the Guibas and Stolfi     */
7488 /*  point location routine (which I originally used), which tends to spiral  */
7489 /*  in toward its target.                                                    */
7490 /*                                                                           */
7491 /*  Returns ONVERTEX if the point lies on an existing vertex.  `searchtri'   */
7492 /*  is a handle whose origin is the existing vertex.                         */
7493 /*                                                                           */
7494 /*  Returns ONEDGE if the point lies on a mesh edge.  `searchtri' is a       */
7495 /*  handle whose primary edge is the edge on which the point lies.           */
7496 /*                                                                           */
7497 /*  Returns INTRIANGLE if the point lies strictly within a triangle.         */
7498 /*  `searchtri' is a handle on the triangle that contains the point.         */
7499 /*                                                                           */
7500 /*  Returns OUTSIDE if the point lies outside the mesh.  `searchtri' is a    */
7501 /*  handle whose primary edge the point is to the right of.  This might      */
7502 /*  occur when the circumcenter of a triangle falls just slightly outside    */
7503 /*  the mesh due to floating-point roundoff error.  It also occurs when      */
7504 /*  seeking a hole or region point that a foolish user has placed outside    */
7505 /*  the mesh.                                                                */
7506 /*                                                                           */
7507 /*  If `stopatsubsegment' is nonzero, the search will stop if it tries to    */
7508 /*  walk through a subsegment, and will return OUTSIDE.                      */
7509 /*                                                                           */
7510 /*  WARNING:  This routine is designed for convex triangulations, and will   */
7511 /*  not generally work after the holes and concavities have been carved.     */
7512 /*  However, it can still be used to find the circumcenter of a triangle, as */
7513 /*  long as the search is begun from the triangle in question.               */
7514 /*                                                                           */
7515 /*****************************************************************************/
7516 
7517 #ifdef ANSI_DECLARATORS
7518 static enum locateresult preciselocate(struct mesh *m, struct behavior *b,
7519                                 vertex searchpoint, struct otri *searchtri,
7520                                 int stopatsubsegment)
7521 #else /* not ANSI_DECLARATORS */
7522 static enum locateresult preciselocate(m, b, searchpoint, searchtri, stopatsubsegment)
7523 struct mesh *m;
7524 struct behavior *b;
7525 vertex searchpoint;
7526 struct otri *searchtri;
7527 int stopatsubsegment;
7528 #endif /* not ANSI_DECLARATORS */
7529 
7530 {
7531   struct otri backtracktri;
7532   struct osub checkedge;
7533   vertex forg, fdest, fapex;
7534   REAL orgorient, destorient;
7535   int moveleft;
7536   triangle ptr;                         /* Temporary variable used by sym(). */
7537   subseg sptr;                      /* Temporary variable used by tspivot(). */
7538 
7539   if (b->verbose > 2) {
7540     printf("  Searching for point (%.12g, %.12g).\n",
7541            searchpoint[0], searchpoint[1]);
7542   }
7543   /* Where are we? */
7544   org(*searchtri, forg);
7545   dest(*searchtri, fdest);
7546   apex(*searchtri, fapex);
7547   while (1) {
7548     if (b->verbose > 2) {
7549       printf("    At (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
7550              forg[0], forg[1], fdest[0], fdest[1], fapex[0], fapex[1]);
7551     }
7552     /* Check whether the apex is the point we seek. */
7553     if ((fapex[0] == searchpoint[0]) && (fapex[1] == searchpoint[1])) {
7554       lprevself(*searchtri);
7555       return ONVERTEX;
7556     }
7557     /* Does the point lie on the other side of the line defined by the */
7558     /*   triangle edge opposite the triangle's destination?            */
7559     destorient = counterclockwise(m, b, forg, fapex, searchpoint);
7560     /* Does the point lie on the other side of the line defined by the */
7561     /*   triangle edge opposite the triangle's origin?                 */
7562     orgorient = counterclockwise(m, b, fapex, fdest, searchpoint);
7563     if (destorient > 0.0) {
7564       if (orgorient > 0.0) {
7565         /* Move left if the inner product of (fapex - searchpoint) and  */
7566         /*   (fdest - forg) is positive.  This is equivalent to drawing */
7567         /*   a line perpendicular to the line (forg, fdest) and passing */
7568         /*   through `fapex', and determining which side of this line   */
7569         /*   `searchpoint' falls on.                                    */
7570         moveleft = (fapex[0] - searchpoint[0]) * (fdest[0] - forg[0]) +
7571                    (fapex[1] - searchpoint[1]) * (fdest[1] - forg[1]) > 0.0;
7572       } else {
7573         moveleft = 1;
7574       }
7575     } else {
7576       if (orgorient > 0.0) {
7577         moveleft = 0;
7578       } else {
7579         /* The point we seek must be on the boundary of or inside this */
7580         /*   triangle.                                                 */
7581         if (destorient == 0.0) {
7582           lprevself(*searchtri);
7583           return ONEDGE;
7584         }
7585         if (orgorient == 0.0) {
7586           lnextself(*searchtri);
7587           return ONEDGE;
7588         }
7589         return INTRIANGLE;
7590       }
7591     }
7592 
7593     /* Move to another triangle.  Leave a trace `backtracktri' in case */
7594     /*   floating-point roundoff or some such bogey causes us to walk  */
7595     /*   off a boundary of the triangulation.                          */
7596     if (moveleft) {
7597       lprev(*searchtri, backtracktri);
7598       fdest = fapex;
7599     } else {
7600       lnext(*searchtri, backtracktri);
7601       forg = fapex;
7602     }
7603     sym(backtracktri, *searchtri);
7604 
7605     if (m->checksegments && stopatsubsegment) {
7606       /* Check for walking through a subsegment. */
7607       tspivot(backtracktri, checkedge);
7608       if (checkedge.ss != m->dummysub) {
7609         /* Go back to the last triangle. */
7610         otricopy(backtracktri, *searchtri);
7611         return OUTSIDE;
7612       }
7613     }
7614     /* Check for walking right out of the triangulation. */
7615     if (searchtri->tri == m->dummytri) {
7616       /* Go back to the last triangle. */
7617       otricopy(backtracktri, *searchtri);
7618       return OUTSIDE;
7619     }
7620 
7621     apex(*searchtri, fapex);
7622   }
7623 }
7624 
7625 /*****************************************************************************/
7626 /*                                                                           */
7627 /*  locate()   Find a triangle or edge containing a given point.             */
7628 /*                                                                           */
7629 /*  Searching begins from one of:  the input `searchtri', a recently         */
7630 /*  encountered triangle `recenttri', or from a triangle chosen from a       */
7631 /*  random sample.  The choice is made by determining which triangle's       */
7632 /*  origin is closest to the point we are searching for.  Normally,          */
7633 /*  `searchtri' should be a handle on the convex hull of the triangulation.  */
7634 /*                                                                           */
7635 /*  Details on the random sampling method can be found in the Mucke, Saias,  */
7636 /*  and Zhu paper cited in the header of this code.                          */
7637 /*                                                                           */
7638 /*  On completion, `searchtri' is a triangle that contains `searchpoint'.    */
7639 /*                                                                           */
7640 /*  Returns ONVERTEX if the point lies on an existing vertex.  `searchtri'   */
7641 /*  is a handle whose origin is the existing vertex.                         */
7642 /*                                                                           */
7643 /*  Returns ONEDGE if the point lies on a mesh edge.  `searchtri' is a       */
7644 /*  handle whose primary edge is the edge on which the point lies.           */
7645 /*                                                                           */
7646 /*  Returns INTRIANGLE if the point lies strictly within a triangle.         */
7647 /*  `searchtri' is a handle on the triangle that contains the point.         */
7648 /*                                                                           */
7649 /*  Returns OUTSIDE if the point lies outside the mesh.  `searchtri' is a    */
7650 /*  handle whose primary edge the point is to the right of.  This might      */
7651 /*  occur when the circumcenter of a triangle falls just slightly outside    */
7652 /*  the mesh due to floating-point roundoff error.  It also occurs when      */
7653 /*  seeking a hole or region point that a foolish user has placed outside    */
7654 /*  the mesh.                                                                */
7655 /*                                                                           */
7656 /*  WARNING:  This routine is designed for convex triangulations, and will   */
7657 /*  not generally work after the holes and concavities have been carved.     */
7658 /*                                                                           */
7659 /*****************************************************************************/
7660 
7661 #ifdef ANSI_DECLARATORS
7662 static enum locateresult locate(struct mesh *m, struct behavior *b,
7663                          vertex searchpoint, struct otri *searchtri)
7664 #else /* not ANSI_DECLARATORS */
7665 static enum locateresult locate(m, b, searchpoint, searchtri)
7666 struct mesh *m;
7667 struct behavior *b;
7668 vertex searchpoint;
7669 struct otri *searchtri;
7670 #endif /* not ANSI_DECLARATORS */
7671 
7672 {
7673   VOID **sampleblock;
7674   char *firsttri;
7675   struct otri sampletri;
7676   vertex torg, tdest;
7677   unsigned LONG alignptr;
7678   REAL searchdist, dist;
7679   REAL ahead;
7680   LONG samplesperblock, totalsamplesleft, samplesleft;
7681   LONG population, totalpopulation;
7682   triangle ptr;                         /* Temporary variable used by sym(). */
7683 
7684   if (b->verbose > 2) {
7685     printf("  Randomly sampling for a triangle near point (%.12g, %.12g).\n",
7686            searchpoint[0], searchpoint[1]);
7687   }
7688   /* Record the distance from the suggested starting triangle to the */
7689   /*   point we seek.                                                */
7690   org(*searchtri, torg);
7691   searchdist = (searchpoint[0] - torg[0]) * (searchpoint[0] - torg[0]) +
7692                (searchpoint[1] - torg[1]) * (searchpoint[1] - torg[1]);
7693   if (b->verbose > 2) {
7694     printf("    Boundary triangle has origin (%.12g, %.12g).\n",
7695            torg[0], torg[1]);
7696   }
7697 
7698   /* If a recently encountered triangle has been recorded and has not been */
7699   /*   deallocated, test it as a good starting point.                      */
7700   if (m->recenttri.tri != (triangle *) NULL) {
7701     if (!deadtri(m->recenttri.tri)) {
7702       org(m->recenttri, torg);
7703       if ((torg[0] == searchpoint[0]) && (torg[1] == searchpoint[1])) {
7704         otricopy(m->recenttri, *searchtri);
7705         return ONVERTEX;
7706       }
7707       dist = (searchpoint[0] - torg[0]) * (searchpoint[0] - torg[0]) +
7708              (searchpoint[1] - torg[1]) * (searchpoint[1] - torg[1]);
7709       if (dist < searchdist) {
7710         otricopy(m->recenttri, *searchtri);
7711         searchdist = dist;
7712         if (b->verbose > 2) {
7713           printf("    Choosing recent triangle with origin (%.12g, %.12g).\n",
7714                  torg[0], torg[1]);
7715         }
7716       }
7717     }
7718   }
7719 
7720   /* The number of random samples taken is proportional to the cube root of */
7721   /*   the number of triangles in the mesh.  The next bit of code assumes   */
7722   /*   that the number of triangles increases monotonically (or at least    */
7723   /*   doesn't decrease enough to matter).                                  */
7724   while (SAMPLEFACTOR * m->samples * m->samples * m->samples <
7725          m->triangles.items) {
7726     m->samples++;
7727   }
7728 
7729   /* We'll draw ceiling(samples * TRIPERBLOCK / maxitems) random samples  */
7730   /*   from each block of triangles (except the first)--until we meet the */
7731   /*   sample quota.  The ceiling means that blocks at the end might be   */
7732   /*   neglected, but I don't care.                                       */
7733   samplesperblock = (m->samples * TRIPERBLOCK - 1) / m->triangles.maxitems + 1;
7734   /* We'll draw ceiling(samples * itemsfirstblock / maxitems) random samples */
7735   /*   from the first block of triangles.                                    */
7736   samplesleft = (LONG)((m->samples * m->triangles.itemsfirstblock - 1) /
7737                 m->triangles.maxitems + 1);
7738   totalsamplesleft = m->samples;
7739   population = (LONG)m->triangles.itemsfirstblock;
7740   totalpopulation = m->triangles.maxitems;
7741   sampleblock = m->triangles.firstblock;
7742   sampletri.orient = 0;
7743   while (totalsamplesleft > 0) {
7744     /* If we're in the last block, `population' needs to be corrected. */
7745     if (population > totalpopulation) {
7746       population = totalpopulation;
7747     }
7748     /* Find a pointer to the first triangle in the block. */
7749     alignptr = (unsigned LONG) (sampleblock + 1);
7750     firsttri = (char *) (alignptr +
7751                          (unsigned LONG) m->triangles.alignbytes -
7752                          (alignptr %
7753                           (unsigned LONG) m->triangles.alignbytes));
7754 
7755     /* Choose `samplesleft' randomly sampled triangles in this block. */
7756     do {
7757       sampletri.tri = (triangle *) (firsttri +
7758                                     (randomnation((unsigned int) population) *
7759                                      m->triangles.itembytes));
7760       if (!deadtri(sampletri.tri)) {
7761         org(sampletri, torg);
7762         dist = (searchpoint[0] - torg[0]) * (searchpoint[0] - torg[0]) +
7763                (searchpoint[1] - torg[1]) * (searchpoint[1] - torg[1]);
7764         if (dist < searchdist) {
7765           otricopy(sampletri, *searchtri);
7766           searchdist = dist;
7767           if (b->verbose > 2) {
7768             printf("    Choosing triangle with origin (%.12g, %.12g).\n",
7769                    torg[0], torg[1]);
7770           }
7771         }
7772       }
7773 
7774       samplesleft--;
7775       totalsamplesleft--;
7776     } while ((samplesleft > 0) && (totalsamplesleft > 0));
7777 
7778     if (totalsamplesleft > 0) {
7779       sampleblock = (VOID **) *sampleblock;
7780       samplesleft = samplesperblock;
7781       totalpopulation -= population;
7782       population = TRIPERBLOCK;
7783     }
7784   }
7785 
7786   /* Where are we? */
7787   org(*searchtri, torg);
7788   dest(*searchtri, tdest);
7789   /* Check the starting triangle's vertices. */
7790   if ((torg[0] == searchpoint[0]) && (torg[1] == searchpoint[1])) {
7791     return ONVERTEX;
7792   }
7793   if ((tdest[0] == searchpoint[0]) && (tdest[1] == searchpoint[1])) {
7794     lnextself(*searchtri);
7795     return ONVERTEX;
7796   }
7797   /* Orient `searchtri' to fit the preconditions of calling preciselocate(). */
7798   ahead = counterclockwise(m, b, torg, tdest, searchpoint);
7799   if (ahead < 0.0) {
7800     /* Turn around so that `searchpoint' is to the left of the */
7801     /*   edge specified by `searchtri'.                        */
7802     symself(*searchtri);
7803   } else if (ahead == 0.0) {
7804     /* Check if `searchpoint' is between `torg' and `tdest'. */
7805     if (((torg[0] < searchpoint[0]) == (searchpoint[0] < tdest[0])) &&
7806         ((torg[1] < searchpoint[1]) == (searchpoint[1] < tdest[1]))) {
7807       return ONEDGE;
7808     }
7809   }
7810   return preciselocate(m, b, searchpoint, searchtri, 0);
7811 }
7812 
7813 /**                                                                         **/
7814 /**                                                                         **/
7815 /********* Point location routines end here                          *********/
7816 
7817 /********* Mesh transformation routines begin here                   *********/
7818 /**                                                                         **/
7819 /**                                                                         **/
7820 
7821 /*****************************************************************************/
7822 /*                                                                           */
7823 /*  insertsubseg()   Create a new subsegment and insert it between two       */
7824 /*                   triangles.                                              */
7825 /*                                                                           */
7826 /*  The new subsegment is inserted at the edge described by the handle       */
7827 /*  `tri'.  Its vertices are properly initialized.  The marker `subsegmark'  */
7828 /*  is applied to the subsegment and, if appropriate, its vertices.          */
7829 /*                                                                           */
7830 /*****************************************************************************/
7831 
7832 #ifdef ANSI_DECLARATORS
7833 static void insertsubseg(struct mesh *m, struct behavior *b, struct otri *tri,
7834                   int subsegmark)
7835 #else /* not ANSI_DECLARATORS */
7836 static void insertsubseg(m, b, tri, subsegmark)
7837 struct mesh *m;
7838 struct behavior *b;
7839 struct otri *tri;             /* Edge at which to insert the new subsegment. */
7840 int subsegmark;                            /* Marker for the new subsegment. */
7841 #endif /* not ANSI_DECLARATORS */
7842 
7843 {
7844   struct otri oppotri;
7845   struct osub newsubseg;
7846   vertex triorg, tridest;
7847   triangle ptr;                         /* Temporary variable used by sym(). */
7848   subseg sptr;                      /* Temporary variable used by tspivot(). */
7849 
7850   org(*tri, triorg);
7851   dest(*tri, tridest);
7852   /* Mark vertices if possible. */
7853   if (vertexmark(triorg) == 0) {
7854     setvertexmark(triorg, subsegmark);
7855   }
7856   if (vertexmark(tridest) == 0) {
7857     setvertexmark(tridest, subsegmark);
7858   }
7859   /* Check if there's already a subsegment here. */
7860   tspivot(*tri, newsubseg);
7861   if (newsubseg.ss == m->dummysub) {
7862     /* Make new subsegment and initialize its vertices. */
7863     makesubseg(m, &newsubseg);
7864     setsorg(newsubseg, tridest);
7865     setsdest(newsubseg, triorg);
7866     setsegorg(newsubseg, tridest);
7867     setsegdest(newsubseg, triorg);
7868     /* Bond new subsegment to the two triangles it is sandwiched between. */
7869     /*   Note that the facing triangle `oppotri' might be equal to        */
7870     /*   `dummytri' (outer space), but the new subsegment is bonded to it */
7871     /*   all the same.                                                    */
7872     tsbond(*tri, newsubseg);
7873     sym(*tri, oppotri);
7874     ssymself(newsubseg);
7875     tsbond(oppotri, newsubseg);
7876     setmark(newsubseg, subsegmark);
7877     if (b->verbose > 2) {
7878       printf("  Inserting new ");
7879       printsubseg(m, b, &newsubseg);
7880     }
7881   } else {
7882     if (mark(newsubseg) == 0) {
7883       setmark(newsubseg, subsegmark);
7884     }
7885   }
7886 }
7887 
7888 /*****************************************************************************/
7889 /*                                                                           */
7890 /*  Terminology                                                              */
7891 /*                                                                           */
7892 /*  A "local transformation" replaces a small set of triangles with another  */
7893 /*  set of triangles.  This may or may not involve inserting or deleting a   */
7894 /*  vertex.                                                                  */
7895 /*                                                                           */
7896 /*  The term "casing" is used to describe the set of triangles that are      */
7897 /*  attached to the triangles being transformed, but are not transformed     */
7898 /*  themselves.  Think of the casing as a fixed hollow structure inside      */
7899 /*  which all the action happens.  A "casing" is only defined relative to    */
7900 /*  a single transformation; each occurrence of a transformation will        */
7901 /*  involve a different casing.                                              */
7902 /*                                                                           */
7903 /*****************************************************************************/
7904 
7905 /*****************************************************************************/
7906 /*                                                                           */
7907 /*  flip()   Transform two triangles to two different triangles by flipping  */
7908 /*           an edge counterclockwise within a quadrilateral.                */
7909 /*                                                                           */
7910 /*  Imagine the original triangles, abc and bad, oriented so that the        */
7911 /*  shared edge ab lies in a horizontal plane, with the vertex b on the left */
7912 /*  and the vertex a on the right.  The vertex c lies below the edge, and    */
7913 /*  the vertex d lies above the edge.  The `flipedge' handle holds the edge  */
7914 /*  ab of triangle abc, and is directed left, from vertex a to vertex b.     */
7915 /*                                                                           */
7916 /*  The triangles abc and bad are deleted and replaced by the triangles cdb  */
7917 /*  and dca.  The triangles that represent abc and bad are NOT deallocated;  */
7918 /*  they are reused for dca and cdb, respectively.  Hence, any handles that  */
7919 /*  may have held the original triangles are still valid, although not       */
7920 /*  directed as they were before.                                            */
7921 /*                                                                           */
7922 /*  Upon completion of this routine, the `flipedge' handle holds the edge    */
7923 /*  dc of triangle dca, and is directed down, from vertex d to vertex c.     */
7924 /*  (Hence, the two triangles have rotated counterclockwise.)                */
7925 /*                                                                           */
7926 /*  WARNING:  This transformation is geometrically valid only if the         */
7927 /*  quadrilateral adbc is convex.  Furthermore, this transformation is       */
7928 /*  valid only if there is not a subsegment between the triangles abc and    */
7929 /*  bad.  This routine does not check either of these preconditions, and     */
7930 /*  it is the responsibility of the calling routine to ensure that they are  */
7931 /*  met.  If they are not, the streets shall be filled with wailing and      */
7932 /*  gnashing of teeth.                                                       */
7933 /*                                                                           */
7934 /*****************************************************************************/
7935 
7936 #ifdef ANSI_DECLARATORS
7937 static void flip(struct mesh *m, struct behavior *b, struct otri *flipedge)
7938 #else /* not ANSI_DECLARATORS */
7939 static void flip(m, b, flipedge)
7940 struct mesh *m;
7941 struct behavior *b;
7942 struct otri *flipedge;                    /* Handle for the triangle abc. */
7943 #endif /* not ANSI_DECLARATORS */
7944 
7945 {
7946   struct otri botleft, botright;
7947   struct otri topleft, topright;
7948   struct otri top;
7949   struct otri botlcasing, botrcasing;
7950   struct otri toplcasing, toprcasing;
7951   struct osub botlsubseg, botrsubseg;
7952   struct osub toplsubseg, toprsubseg;
7953   vertex leftvertex, rightvertex, botvertex;
7954   vertex farvertex;
7955   triangle ptr;                         /* Temporary variable used by sym(). */
7956   subseg sptr;                      /* Temporary variable used by tspivot(). */
7957 
7958   /* Identify the vertices of the quadrilateral. */
7959   org(*flipedge, rightvertex);
7960   dest(*flipedge, leftvertex);
7961   apex(*flipedge, botvertex);
7962   sym(*flipedge, top);
7963 #ifdef SELF_CHECK
7964   if (top.tri == m->dummytri) {
7965     printf("Internal error in flip():  Attempt to flip on boundary.\n");
7966     lnextself(*flipedge);
7967     return;
7968   }
7969   if (m->checksegments) {
7970     tspivot(*flipedge, toplsubseg);
7971     if (toplsubseg.ss != m->dummysub) {
7972       printf("Internal error in flip():  Attempt to flip a segment.\n");
7973       lnextself(*flipedge);
7974       return;
7975     }
7976   }
7977 #endif /* SELF_CHECK */
7978   apex(top, farvertex);
7979 
7980   /* Identify the casing of the quadrilateral. */
7981   lprev(top, topleft);
7982   sym(topleft, toplcasing);
7983   lnext(top, topright);
7984   sym(topright, toprcasing);
7985   lnext(*flipedge, botleft);
7986   sym(botleft, botlcasing);
7987   lprev(*flipedge, botright);
7988   sym(botright, botrcasing);
7989   /* Rotate the quadrilateral one-quarter turn counterclockwise. */
7990   bond(topleft, botlcasing);
7991   bond(botleft, botrcasing);
7992   bond(botright, toprcasing);
7993   bond(topright, toplcasing);
7994 
7995   if (m->checksegments) {
7996     /* Check for subsegments and rebond them to the quadrilateral. */
7997     tspivot(topleft, toplsubseg);
7998     tspivot(botleft, botlsubseg);
7999     tspivot(botright, botrsubseg);
8000     tspivot(topright, toprsubseg);
8001     if (toplsubseg.ss == m->dummysub) {
8002       tsdissolve(topright);
8003     } else {
8004       tsbond(topright, toplsubseg);
8005     }
8006     if (botlsubseg.ss == m->dummysub) {
8007       tsdissolve(topleft);
8008     } else {
8009       tsbond(topleft, botlsubseg);
8010     }
8011     if (botrsubseg.ss == m->dummysub) {
8012       tsdissolve(botleft);
8013     } else {
8014       tsbond(botleft, botrsubseg);
8015     }
8016     if (toprsubseg.ss == m->dummysub) {
8017       tsdissolve(botright);
8018     } else {
8019       tsbond(botright, toprsubseg);
8020     }
8021   }
8022 
8023   /* New vertex assignments for the rotated quadrilateral. */
8024   setorg(*flipedge, farvertex);
8025   setdest(*flipedge, botvertex);
8026   setapex(*flipedge, rightvertex);
8027   setorg(top, botvertex);
8028   setdest(top, farvertex);
8029   setapex(top, leftvertex);
8030   if (b->verbose > 2) {
8031     printf("  Edge flip results in left ");
8032     printtriangle(m, b, &top);
8033     printf("  and right ");
8034     printtriangle(m, b, flipedge);
8035   }
8036 }
8037 
8038 /*****************************************************************************/
8039 /*                                                                           */
8040 /*  unflip()   Transform two triangles to two different triangles by         */
8041 /*             flipping an edge clockwise within a quadrilateral.  Reverses  */
8042 /*             the flip() operation so that the data structures representing */
8043 /*             the triangles are back where they were before the flip().     */
8044 /*                                                                           */
8045 /*  Imagine the original triangles, abc and bad, oriented so that the        */
8046 /*  shared edge ab lies in a horizontal plane, with the vertex b on the left */
8047 /*  and the vertex a on the right.  The vertex c lies below the edge, and    */
8048 /*  the vertex d lies above the edge.  The `flipedge' handle holds the edge  */
8049 /*  ab of triangle abc, and is directed left, from vertex a to vertex b.     */
8050 /*                                                                           */
8051 /*  The triangles abc and bad are deleted and replaced by the triangles cdb  */
8052 /*  and dca.  The triangles that represent abc and bad are NOT deallocated;  */
8053 /*  they are reused for cdb and dca, respectively.  Hence, any handles that  */
8054 /*  may have held the original triangles are still valid, although not       */
8055 /*  directed as they were before.                                            */
8056 /*                                                                           */
8057 /*  Upon completion of this routine, the `flipedge' handle holds the edge    */
8058 /*  cd of triangle cdb, and is directed up, from vertex c to vertex d.       */
8059 /*  (Hence, the two triangles have rotated clockwise.)                       */
8060 /*                                                                           */
8061 /*  WARNING:  This transformation is geometrically valid only if the         */
8062 /*  quadrilateral adbc is convex.  Furthermore, this transformation is       */
8063 /*  valid only if there is not a subsegment between the triangles abc and    */
8064 /*  bad.  This routine does not check either of these preconditions, and     */
8065 /*  it is the responsibility of the calling routine to ensure that they are  */
8066 /*  met.  If they are not, the streets shall be filled with wailing and      */
8067 /*  gnashing of teeth.                                                       */
8068 /*                                                                           */
8069 /*****************************************************************************/
8070 
8071 #ifndef CDT_ONLY
8072 
8073 #ifdef ANSI_DECLARATORS
8074 static void unflip(struct mesh *m, struct behavior *b, struct otri *flipedge)
8075 #else /* not ANSI_DECLARATORS */
8076 static void unflip(m, b, flipedge)
8077 struct mesh *m;
8078 struct behavior *b;
8079 struct otri *flipedge;                    /* Handle for the triangle abc. */
8080 #endif /* not ANSI_DECLARATORS */
8081 
8082 {
8083   struct otri botleft, botright;
8084   struct otri topleft, topright;
8085   struct otri top;
8086   struct otri botlcasing, botrcasing;
8087   struct otri toplcasing, toprcasing;
8088   struct osub botlsubseg, botrsubseg;
8089   struct osub toplsubseg, toprsubseg;
8090   vertex leftvertex, rightvertex, botvertex;
8091   vertex farvertex;
8092   triangle ptr;                         /* Temporary variable used by sym(). */
8093   subseg sptr;                      /* Temporary variable used by tspivot(). */
8094 
8095   /* Identify the vertices of the quadrilateral. */
8096   org(*flipedge, rightvertex);
8097   dest(*flipedge, leftvertex);
8098   apex(*flipedge, botvertex);
8099   sym(*flipedge, top);
8100 #ifdef SELF_CHECK
8101   if (top.tri == m->dummytri) {
8102     printf("Internal error in unflip():  Attempt to flip on boundary.\n");
8103     lnextself(*flipedge);
8104     return;
8105   }
8106   if (m->checksegments) {
8107     tspivot(*flipedge, toplsubseg);
8108     if (toplsubseg.ss != m->dummysub) {
8109       printf("Internal error in unflip():  Attempt to flip a subsegment.\n");
8110       lnextself(*flipedge);
8111       return;
8112     }
8113   }
8114 #endif /* SELF_CHECK */
8115   apex(top, farvertex);
8116 
8117   /* Identify the casing of the quadrilateral. */
8118   lprev(top, topleft);
8119   sym(topleft, toplcasing);
8120   lnext(top, topright);
8121   sym(topright, toprcasing);
8122   lnext(*flipedge, botleft);
8123   sym(botleft, botlcasing);
8124   lprev(*flipedge, botright);
8125   sym(botright, botrcasing);
8126   /* Rotate the quadrilateral one-quarter turn clockwise. */
8127   bond(topleft, toprcasing);
8128   bond(botleft, toplcasing);
8129   bond(botright, botlcasing);
8130   bond(topright, botrcasing);
8131 
8132   if (m->checksegments) {
8133     /* Check for subsegments and rebond them to the quadrilateral. */
8134     tspivot(topleft, toplsubseg);
8135     tspivot(botleft, botlsubseg);
8136     tspivot(botright, botrsubseg);
8137     tspivot(topright, toprsubseg);
8138     if (toplsubseg.ss == m->dummysub) {
8139       tsdissolve(botleft);
8140     } else {
8141       tsbond(botleft, toplsubseg);
8142     }
8143     if (botlsubseg.ss == m->dummysub) {
8144       tsdissolve(botright);
8145     } else {
8146       tsbond(botright, botlsubseg);
8147     }
8148     if (botrsubseg.ss == m->dummysub) {
8149       tsdissolve(topright);
8150     } else {
8151       tsbond(topright, botrsubseg);
8152     }
8153     if (toprsubseg.ss == m->dummysub) {
8154       tsdissolve(topleft);
8155     } else {
8156       tsbond(topleft, toprsubseg);
8157     }
8158   }
8159 
8160   /* New vertex assignments for the rotated quadrilateral. */
8161   setorg(*flipedge, botvertex);
8162   setdest(*flipedge, farvertex);
8163   setapex(*flipedge, leftvertex);
8164   setorg(top, farvertex);
8165   setdest(top, botvertex);
8166   setapex(top, rightvertex);
8167   if (b->verbose > 2) {
8168     printf("  Edge unflip results in left ");
8169     printtriangle(m, b, flipedge);
8170     printf("  and right ");
8171     printtriangle(m, b, &top);
8172   }
8173 }
8174 
8175 #endif /* not CDT_ONLY */
8176 
8177 /*****************************************************************************/
8178 /*                                                                           */
8179 /*  insertvertex()   Insert a vertex into a Delaunay triangulation,          */
8180 /*                   performing flips as necessary to maintain the Delaunay  */
8181 /*                   property.                                               */
8182 /*                                                                           */
8183 /*  The point `insertvertex' is located.  If `searchtri.tri' is not NULL,    */
8184 /*  the search for the containing triangle begins from `searchtri'.  If      */
8185 /*  `searchtri.tri' is NULL, a full point location procedure is called.      */
8186 /*  If `insertvertex' is found inside a triangle, the triangle is split into */
8187 /*  three; if `insertvertex' lies on an edge, the edge is split in two,      */
8188 /*  thereby splitting the two adjacent triangles into four.  Edge flips are  */
8189 /*  used to restore the Delaunay property.  If `insertvertex' lies on an     */
8190 /*  existing vertex, no action is taken, and the value DUPLICATEVERTEX is    */
8191 /*  returned.  On return, `searchtri' is set to a handle whose origin is the */
8192 /*  existing vertex.                                                         */
8193 /*                                                                           */
8194 /*  Normally, the parameter `splitseg' is set to NULL, implying that no      */
8195 /*  subsegment should be split.  In this case, if `insertvertex' is found to */
8196 /*  lie on a segment, no action is taken, and the value VIOLATINGVERTEX is   */
8197 /*  returned.  On return, `searchtri' is set to a handle whose primary edge  */
8198 /*  is the violated subsegment.                                              */
8199 /*                                                                           */
8200 /*  If the calling routine wishes to split a subsegment by inserting a       */
8201 /*  vertex in it, the parameter `splitseg' should be that subsegment.  In    */
8202 /*  this case, `searchtri' MUST be the triangle handle reached by pivoting   */
8203 /*  from that subsegment; no point location is done.                         */
8204 /*                                                                           */
8205 /*  `segmentflaws' and `triflaws' are flags that indicate whether or not     */
8206 /*  there should be checks for the creation of encroached subsegments or bad */
8207 /*  quality triangles.  If a newly inserted vertex encroaches upon           */
8208 /*  subsegments, these subsegments are added to the list of subsegments to   */
8209 /*  be split if `segmentflaws' is set.  If bad triangles are created, these  */
8210 /*  are added to the queue if `triflaws' is set.                             */
8211 /*                                                                           */
8212 /*  If a duplicate vertex or violated segment does not prevent the vertex    */
8213 /*  from being inserted, the return value will be ENCROACHINGVERTEX if the   */
8214 /*  vertex encroaches upon a subsegment (and checking is enabled), or        */
8215 /*  SUCCESSFULVERTEX otherwise.  In either case, `searchtri' is set to a     */
8216 /*  handle whose origin is the newly inserted vertex.                        */
8217 /*                                                                           */
8218 /*  insertvertex() does not use flip() for reasons of speed; some            */
8219 /*  information can be reused from edge flip to edge flip, like the          */
8220 /*  locations of subsegments.                                                */
8221 /*                                                                           */
8222 /*****************************************************************************/
8223 
8224 #ifdef ANSI_DECLARATORS
8225 static enum insertvertexresult insertvertex(struct mesh *m, struct behavior *b,
8226                                      vertex newvertex, struct otri *searchtri,
8227                                      struct osub *splitseg,
8228                                      int segmentflaws, int triflaws)
8229 #else /* not ANSI_DECLARATORS */
8230 static enum insertvertexresult insertvertex(m, b, newvertex, searchtri, splitseg,
8231                                      segmentflaws, triflaws)
8232 struct mesh *m;
8233 struct behavior *b;
8234 vertex newvertex;
8235 struct otri *searchtri;
8236 struct osub *splitseg;
8237 int segmentflaws;
8238 int triflaws;
8239 #endif /* not ANSI_DECLARATORS */
8240 
8241 {
8242   struct otri horiz;
8243   struct otri top;
8244   struct otri botleft, botright;
8245   struct otri topleft, topright;
8246   struct otri newbotleft, newbotright;
8247   struct otri newtopright;
8248   struct otri botlcasing, botrcasing;
8249   struct otri toplcasing, toprcasing = {NULL, 0}; /* silence -Wuninitialized */
8250   struct otri testtri;
8251   struct osub botlsubseg, botrsubseg;
8252   struct osub toplsubseg, toprsubseg;
8253   struct osub brokensubseg;
8254   struct osub checksubseg;
8255   struct osub rightsubseg;
8256   struct osub newsubseg;
8257   struct badsubseg *encroached;
8258   struct flipstacker *newflip;
8259   vertex first;
8260   vertex leftvertex, rightvertex, botvertex, topvertex, farvertex;
8261   vertex segmentorg, segmentdest;
8262   REAL attrib;
8263   REAL area;
8264   enum insertvertexresult success;
8265   enum locateresult intersect;
8266   int doflip;
8267   int mirrorflag;
8268   int enq;
8269   int i;
8270   triangle ptr;                         /* Temporary variable used by sym(). */
8271   subseg sptr;         /* Temporary variable used by spivot() and tspivot(). */
8272   (void)(triflaws);
8273   if (b->verbose > 1) {
8274     printf("  Inserting (%.12g, %.12g).\n", newvertex[0], newvertex[1]);
8275   }
8276 
8277   if (splitseg == (struct osub *) NULL) {
8278     /* Find the location of the vertex to be inserted.  Check if a good */
8279     /*   starting triangle has already been provided by the caller.     */
8280     if (searchtri->tri == m->dummytri) {
8281       /* Find a boundary triangle. */
8282       horiz.tri = m->dummytri;
8283       horiz.orient = 0;
8284       symself(horiz);
8285       /* Search for a triangle containing `newvertex'. */
8286       intersect = locate(m, b, newvertex, &horiz);
8287     } else {
8288       /* Start searching from the triangle provided by the caller. */
8289       otricopy(*searchtri, horiz);
8290       intersect = preciselocate(m, b, newvertex, &horiz, 1);
8291     }
8292   } else {
8293     /* The calling routine provides the subsegment in which */
8294     /*   the vertex is inserted.                             */
8295     otricopy(*searchtri, horiz);
8296     intersect = ONEDGE;
8297   }
8298 
8299   if (intersect == ONVERTEX) {
8300     /* There's already a vertex there.  Return in `searchtri' a triangle */
8301     /*   whose origin is the existing vertex.                            */
8302     otricopy(horiz, *searchtri);
8303     otricopy(horiz, m->recenttri);
8304     return DUPLICATEVERTEX;
8305   }
8306   if ((intersect == ONEDGE) || (intersect == OUTSIDE)) {
8307     /* The vertex falls on an edge or boundary. */
8308     if (m->checksegments && (splitseg == (struct osub *) NULL)) {
8309       /* Check whether the vertex falls on a subsegment. */
8310       tspivot(horiz, brokensubseg);
8311       if (brokensubseg.ss != m->dummysub) {
8312         /* The vertex falls on a subsegment, and hence will not be inserted. */
8313         if (segmentflaws) {
8314           enq = b->nobisect != 2;
8315           if (enq && (b->nobisect == 1)) {
8316             /* This subsegment may be split only if it is an */
8317             /*   internal boundary.                          */
8318             sym(horiz, testtri);
8319             enq = testtri.tri != m->dummytri;
8320           }
8321           if (enq) {
8322             /* Add the subsegment to the list of encroached subsegments. */
8323             encroached = (struct badsubseg *) poolalloc(&m->badsubsegs);
8324             encroached->encsubseg = sencode(brokensubseg);
8325             sorg(brokensubseg, encroached->subsegorg);
8326             sdest(brokensubseg, encroached->subsegdest);
8327             if (b->verbose > 2) {
8328               printf(
8329           "  Queueing encroached subsegment (%.12g, %.12g) (%.12g, %.12g).\n",
8330                      encroached->subsegorg[0], encroached->subsegorg[1],
8331                      encroached->subsegdest[0], encroached->subsegdest[1]);
8332             }
8333           }
8334         }
8335         /* Return a handle whose primary edge contains the vertex, */
8336         /*   which has not been inserted.                          */
8337         otricopy(horiz, *searchtri);
8338         otricopy(horiz, m->recenttri);
8339         return VIOLATINGVERTEX;
8340       }
8341     }
8342 
8343     /* Insert the vertex on an edge, dividing one triangle into two (if */
8344     /*   the edge lies on a boundary) or two triangles into four.       */
8345     lprev(horiz, botright);
8346     sym(botright, botrcasing);
8347     sym(horiz, topright);
8348     /* Is there a second triangle?  (Or does this edge lie on a boundary?) */
8349     mirrorflag = topright.tri != m->dummytri;
8350     if (mirrorflag) {
8351       lnextself(topright);
8352       sym(topright, toprcasing);
8353       maketriangle(m, b, &newtopright);
8354     } else {
8355       /* Splitting a boundary edge increases the number of boundary edges. */
8356       m->hullsize++;
8357     }
8358     maketriangle(m, b, &newbotright);
8359 
8360     /* Set the vertices of changed and new triangles. */
8361     org(horiz, rightvertex);
8362     dest(horiz, leftvertex);
8363     apex(horiz, botvertex);
8364     setorg(newbotright, botvertex);
8365     setdest(newbotright, rightvertex);
8366     setapex(newbotright, newvertex);
8367     setorg(horiz, newvertex);
8368     for (i = 0; i < m->eextras; i++) {
8369       /* Set the element attributes of a new triangle. */
8370       setelemattribute(newbotright, i, elemattribute(botright, i));
8371     }
8372     if (b->vararea) {
8373       /* Set the area constraint of a new triangle. */
8374       setareabound(newbotright, areabound(botright));
8375     }
8376     if (mirrorflag) {
8377       dest(topright, topvertex);
8378       setorg(newtopright, rightvertex);
8379       setdest(newtopright, topvertex);
8380       setapex(newtopright, newvertex);
8381       setorg(topright, newvertex);
8382       for (i = 0; i < m->eextras; i++) {
8383         /* Set the element attributes of another new triangle. */
8384         setelemattribute(newtopright, i, elemattribute(topright, i));
8385       }
8386       if (b->vararea) {
8387         /* Set the area constraint of another new triangle. */
8388         setareabound(newtopright, areabound(topright));
8389       }
8390     }
8391 
8392     /* There may be subsegments that need to be bonded */
8393     /*   to the new triangle(s).                       */
8394     if (m->checksegments) {
8395       tspivot(botright, botrsubseg);
8396       if (botrsubseg.ss != m->dummysub) {
8397         tsdissolve(botright);
8398         tsbond(newbotright, botrsubseg);
8399       }
8400       if (mirrorflag) {
8401         tspivot(topright, toprsubseg);
8402         if (toprsubseg.ss != m->dummysub) {
8403           tsdissolve(topright);
8404           tsbond(newtopright, toprsubseg);
8405         }
8406       }
8407     }
8408 
8409     /* Bond the new triangle(s) to the surrounding triangles. */
8410     bond(newbotright, botrcasing);
8411     lprevself(newbotright);
8412     bond(newbotright, botright);
8413     lprevself(newbotright);
8414     if (mirrorflag) {
8415       bond(newtopright, toprcasing);
8416       lnextself(newtopright);
8417       bond(newtopright, topright);
8418       lnextself(newtopright);
8419       bond(newtopright, newbotright);
8420     }
8421 
8422     if (splitseg != (struct osub *) NULL) {
8423       /* Split the subsegment into two. */
8424       setsdest(*splitseg, newvertex);
8425       segorg(*splitseg, segmentorg);
8426       segdest(*splitseg, segmentdest);
8427       ssymself(*splitseg);
8428       spivot(*splitseg, rightsubseg);
8429       insertsubseg(m, b, &newbotright, mark(*splitseg));
8430       tspivot(newbotright, newsubseg);
8431       setsegorg(newsubseg, segmentorg);
8432       setsegdest(newsubseg, segmentdest);
8433       sbond(*splitseg, newsubseg);
8434       ssymself(newsubseg);
8435       sbond(newsubseg, rightsubseg);
8436       ssymself(*splitseg);
8437       /* Transfer the subsegment's boundary marker to the vertex */
8438       /*   if required.                                          */
8439       if (vertexmark(newvertex) == 0) {
8440         setvertexmark(newvertex, mark(*splitseg));
8441       }
8442     }
8443 
8444     if (m->checkquality) {
8445       poolrestart(&m->flipstackers);
8446       m->lastflip = (struct flipstacker *) poolalloc(&m->flipstackers);
8447       m->lastflip->flippedtri = encode(horiz);
8448       m->lastflip->prevflip = (struct flipstacker *) &insertvertex;
8449     }
8450 
8451 #ifdef SELF_CHECK
8452     if (counterclockwise(m, b, rightvertex, leftvertex, botvertex) < 0.0) {
8453       printf("Internal error in insertvertex():\n");
8454       printf(
8455             "  Clockwise triangle prior to edge vertex insertion (bottom).\n");
8456     }
8457     if (mirrorflag) {
8458       if (counterclockwise(m, b, leftvertex, rightvertex, topvertex) < 0.0) {
8459         printf("Internal error in insertvertex():\n");
8460         printf("  Clockwise triangle prior to edge vertex insertion (top).\n");
8461       }
8462       if (counterclockwise(m, b, rightvertex, topvertex, newvertex) < 0.0) {
8463         printf("Internal error in insertvertex():\n");
8464         printf(
8465             "  Clockwise triangle after edge vertex insertion (top right).\n");
8466       }
8467       if (counterclockwise(m, b, topvertex, leftvertex, newvertex) < 0.0) {
8468         printf("Internal error in insertvertex():\n");
8469         printf(
8470             "  Clockwise triangle after edge vertex insertion (top left).\n");
8471       }
8472     }
8473     if (counterclockwise(m, b, leftvertex, botvertex, newvertex) < 0.0) {
8474       printf("Internal error in insertvertex():\n");
8475       printf(
8476           "  Clockwise triangle after edge vertex insertion (bottom left).\n");
8477     }
8478     if (counterclockwise(m, b, botvertex, rightvertex, newvertex) < 0.0) {
8479       printf("Internal error in insertvertex():\n");
8480       printf(
8481         "  Clockwise triangle after edge vertex insertion (bottom right).\n");
8482     }
8483 #endif /* SELF_CHECK */
8484     if (b->verbose > 2) {
8485       printf("  Updating bottom left ");
8486       printtriangle(m, b, &botright);
8487       if (mirrorflag) {
8488         printf("  Updating top left ");
8489         printtriangle(m, b, &topright);
8490         printf("  Creating top right ");
8491         printtriangle(m, b, &newtopright);
8492       }
8493       printf("  Creating bottom right ");
8494       printtriangle(m, b, &newbotright);
8495     }
8496 
8497     /* Position `horiz' on the first edge to check for */
8498     /*   the Delaunay property.                        */
8499     lnextself(horiz);
8500   } else {
8501     /* Insert the vertex in a triangle, splitting it into three. */
8502     lnext(horiz, botleft);
8503     lprev(horiz, botright);
8504     sym(botleft, botlcasing);
8505     sym(botright, botrcasing);
8506     maketriangle(m, b, &newbotleft);
8507     maketriangle(m, b, &newbotright);
8508 
8509     /* Set the vertices of changed and new triangles. */
8510     org(horiz, rightvertex);
8511     dest(horiz, leftvertex);
8512     apex(horiz, botvertex);
8513     setorg(newbotleft, leftvertex);
8514     setdest(newbotleft, botvertex);
8515     setapex(newbotleft, newvertex);
8516     setorg(newbotright, botvertex);
8517     setdest(newbotright, rightvertex);
8518     setapex(newbotright, newvertex);
8519     setapex(horiz, newvertex);
8520     for (i = 0; i < m->eextras; i++) {
8521       /* Set the element attributes of the new triangles. */
8522       attrib = elemattribute(horiz, i);
8523       setelemattribute(newbotleft, i, attrib);
8524       setelemattribute(newbotright, i, attrib);
8525     }
8526     if (b->vararea) {
8527       /* Set the area constraint of the new triangles. */
8528       area = areabound(horiz);
8529       setareabound(newbotleft, area);
8530       setareabound(newbotright, area);
8531     }
8532 
8533     /* There may be subsegments that need to be bonded */
8534     /*   to the new triangles.                         */
8535     if (m->checksegments) {
8536       tspivot(botleft, botlsubseg);
8537       if (botlsubseg.ss != m->dummysub) {
8538         tsdissolve(botleft);
8539         tsbond(newbotleft, botlsubseg);
8540       }
8541       tspivot(botright, botrsubseg);
8542       if (botrsubseg.ss != m->dummysub) {
8543         tsdissolve(botright);
8544         tsbond(newbotright, botrsubseg);
8545       }
8546     }
8547 
8548     /* Bond the new triangles to the surrounding triangles. */
8549     bond(newbotleft, botlcasing);
8550     bond(newbotright, botrcasing);
8551     lnextself(newbotleft);
8552     lprevself(newbotright);
8553     bond(newbotleft, newbotright);
8554     lnextself(newbotleft);
8555     bond(botleft, newbotleft);
8556     lprevself(newbotright);
8557     bond(botright, newbotright);
8558 
8559     if (m->checkquality) {
8560       poolrestart(&m->flipstackers);
8561       m->lastflip = (struct flipstacker *) poolalloc(&m->flipstackers);
8562       m->lastflip->flippedtri = encode(horiz);
8563       m->lastflip->prevflip = (struct flipstacker *) NULL;
8564     }
8565 
8566 #ifdef SELF_CHECK
8567     if (counterclockwise(m, b, rightvertex, leftvertex, botvertex) < 0.0) {
8568       printf("Internal error in insertvertex():\n");
8569       printf("  Clockwise triangle prior to vertex insertion.\n");
8570     }
8571     if (counterclockwise(m, b, rightvertex, leftvertex, newvertex) < 0.0) {
8572       printf("Internal error in insertvertex():\n");
8573       printf("  Clockwise triangle after vertex insertion (top).\n");
8574     }
8575     if (counterclockwise(m, b, leftvertex, botvertex, newvertex) < 0.0) {
8576       printf("Internal error in insertvertex():\n");
8577       printf("  Clockwise triangle after vertex insertion (left).\n");
8578     }
8579     if (counterclockwise(m, b, botvertex, rightvertex, newvertex) < 0.0) {
8580       printf("Internal error in insertvertex():\n");
8581       printf("  Clockwise triangle after vertex insertion (right).\n");
8582     }
8583 #endif /* SELF_CHECK */
8584     if (b->verbose > 2) {
8585       printf("  Updating top ");
8586       printtriangle(m, b, &horiz);
8587       printf("  Creating left ");
8588       printtriangle(m, b, &newbotleft);
8589       printf("  Creating right ");
8590       printtriangle(m, b, &newbotright);
8591     }
8592   }
8593 
8594   /* The insertion is successful by default, unless an encroached */
8595   /*   subsegment is found.                                       */
8596   success = SUCCESSFULVERTEX;
8597   /* Circle around the newly inserted vertex, checking each edge opposite */
8598   /*   it for the Delaunay property.  Non-Delaunay edges are flipped.     */
8599   /*   `horiz' is always the edge being checked.  `first' marks where to  */
8600   /*   stop circling.                                                     */
8601   org(horiz, first);
8602   rightvertex = first;
8603   dest(horiz, leftvertex);
8604   /* Circle until finished. */
8605   while (1) {
8606     /* By default, the edge will be flipped. */
8607     doflip = 1;
8608 
8609     if (m->checksegments) {
8610       /* Check for a subsegment, which cannot be flipped. */
8611       tspivot(horiz, checksubseg);
8612       if (checksubseg.ss != m->dummysub) {
8613         /* The edge is a subsegment and cannot be flipped. */
8614         doflip = 0;
8615 #ifndef CDT_ONLY
8616         if (segmentflaws) {
8617           /* Does the new vertex encroach upon this subsegment? */
8618           if (checkseg4encroach(m, b, &checksubseg)) {
8619             success = ENCROACHINGVERTEX;
8620           }
8621         }
8622 #endif /* not CDT_ONLY */
8623       }
8624     }
8625 
8626     if (doflip) {
8627       /* Check if the edge is a boundary edge. */
8628       sym(horiz, top);
8629       if (top.tri == m->dummytri) {
8630         /* The edge is a boundary edge and cannot be flipped. */
8631         doflip = 0;
8632       } else {
8633         /* Find the vertex on the other side of the edge. */
8634         apex(top, farvertex);
8635         /* In the incremental Delaunay triangulation algorithm, any of      */
8636         /*   `leftvertex', `rightvertex', and `farvertex' could be vertices */
8637         /*   of the triangular bounding box.  These vertices must be        */
8638         /*   treated as if they are infinitely distant, even though their   */
8639         /*   "coordinates" are not.                                         */
8640         if ((leftvertex == m->infvertex1) || (leftvertex == m->infvertex2) ||
8641             (leftvertex == m->infvertex3)) {
8642           /* `leftvertex' is infinitely distant.  Check the convexity of  */
8643           /*   the boundary of the triangulation.  'farvertex' might be   */
8644           /*   infinite as well, but trust me, this same condition should */
8645           /*   be applied.                                                */
8646           doflip = counterclockwise(m, b, newvertex, rightvertex, farvertex)
8647                    > 0.0;
8648         } else if ((rightvertex == m->infvertex1) ||
8649                    (rightvertex == m->infvertex2) ||
8650                    (rightvertex == m->infvertex3)) {
8651           /* `rightvertex' is infinitely distant.  Check the convexity of */
8652           /*   the boundary of the triangulation.  'farvertex' might be   */
8653           /*   infinite as well, but trust me, this same condition should */
8654           /*   be applied.                                                */
8655           doflip = counterclockwise(m, b, farvertex, leftvertex, newvertex)
8656                    > 0.0;
8657         } else if ((farvertex == m->infvertex1) ||
8658                    (farvertex == m->infvertex2) ||
8659                    (farvertex == m->infvertex3)) {
8660           /* `farvertex' is infinitely distant and cannot be inside */
8661           /*   the circumcircle of the triangle `horiz'.            */
8662           doflip = 0;
8663         } else {
8664           /* Test whether the edge is locally Delaunay. */
8665           doflip = incircle(m, b, leftvertex, newvertex, rightvertex,
8666                             farvertex) > 0.0;
8667         }
8668         if (doflip) {
8669           /* We made it!  Flip the edge `horiz' by rotating its containing */
8670           /*   quadrilateral (the two triangles adjacent to `horiz').      */
8671           /* Identify the casing of the quadrilateral. */
8672           lprev(top, topleft);
8673           sym(topleft, toplcasing);
8674           lnext(top, topright);
8675           sym(topright, toprcasing);
8676           lnext(horiz, botleft);
8677           sym(botleft, botlcasing);
8678           lprev(horiz, botright);
8679           sym(botright, botrcasing);
8680           /* Rotate the quadrilateral one-quarter turn counterclockwise. */
8681           bond(topleft, botlcasing);
8682           bond(botleft, botrcasing);
8683           bond(botright, toprcasing);
8684           bond(topright, toplcasing);
8685           if (m->checksegments) {
8686             /* Check for subsegments and rebond them to the quadrilateral. */
8687             tspivot(topleft, toplsubseg);
8688             tspivot(botleft, botlsubseg);
8689             tspivot(botright, botrsubseg);
8690             tspivot(topright, toprsubseg);
8691             if (toplsubseg.ss == m->dummysub) {
8692               tsdissolve(topright);
8693             } else {
8694               tsbond(topright, toplsubseg);
8695             }
8696             if (botlsubseg.ss == m->dummysub) {
8697               tsdissolve(topleft);
8698             } else {
8699               tsbond(topleft, botlsubseg);
8700             }
8701             if (botrsubseg.ss == m->dummysub) {
8702               tsdissolve(botleft);
8703             } else {
8704               tsbond(botleft, botrsubseg);
8705             }
8706             if (toprsubseg.ss == m->dummysub) {
8707               tsdissolve(botright);
8708             } else {
8709               tsbond(botright, toprsubseg);
8710             }
8711           }
8712           /* New vertex assignments for the rotated quadrilateral. */
8713           setorg(horiz, farvertex);
8714           setdest(horiz, newvertex);
8715           setapex(horiz, rightvertex);
8716           setorg(top, newvertex);
8717           setdest(top, farvertex);
8718           setapex(top, leftvertex);
8719           for (i = 0; i < m->eextras; i++) {
8720             /* Take the average of the two triangles' attributes. */
8721             attrib = 0.5 * (elemattribute(top, i) + elemattribute(horiz, i));
8722             setelemattribute(top, i, attrib);
8723             setelemattribute(horiz, i, attrib);
8724           }
8725           if (b->vararea) {
8726             if ((areabound(top) <= 0.0) || (areabound(horiz) <= 0.0)) {
8727               area = -1.0;
8728             } else {
8729               /* Take the average of the two triangles' area constraints.    */
8730               /*   This prevents small area constraints from migrating a     */
8731               /*   long, long way from their original location due to flips. */
8732               area = 0.5 * (areabound(top) + areabound(horiz));
8733             }
8734             setareabound(top, area);
8735             setareabound(horiz, area);
8736           }
8737 
8738           if (m->checkquality) {
8739             newflip = (struct flipstacker *) poolalloc(&m->flipstackers);
8740             newflip->flippedtri = encode(horiz);
8741             newflip->prevflip = m->lastflip;
8742             m->lastflip = newflip;
8743           }
8744 
8745 #ifdef SELF_CHECK
8746           if (newvertex != (vertex) NULL) {
8747             if (counterclockwise(m, b, leftvertex, newvertex, rightvertex) <
8748                 0.0) {
8749               printf("Internal error in insertvertex():\n");
8750               printf("  Clockwise triangle prior to edge flip (bottom).\n");
8751             }
8752             /* The following test has been removed because constrainededge() */
8753             /*   sometimes generates inverted triangles that insertvertex()  */
8754             /*   removes.                                                    */
8755 /*
8756             if (counterclockwise(m, b, rightvertex, farvertex, leftvertex) <
8757                 0.0) {
8758               printf("Internal error in insertvertex():\n");
8759               printf("  Clockwise triangle prior to edge flip (top).\n");
8760             }
8761 */
8762             if (counterclockwise(m, b, farvertex, leftvertex, newvertex) <
8763                 0.0) {
8764               printf("Internal error in insertvertex():\n");
8765               printf("  Clockwise triangle after edge flip (left).\n");
8766             }
8767             if (counterclockwise(m, b, newvertex, rightvertex, farvertex) <
8768                 0.0) {
8769               printf("Internal error in insertvertex():\n");
8770               printf("  Clockwise triangle after edge flip (right).\n");
8771             }
8772           }
8773 #endif /* SELF_CHECK */
8774           if (b->verbose > 2) {
8775             printf("  Edge flip results in left ");
8776             lnextself(topleft);
8777             printtriangle(m, b, &topleft);
8778             printf("  and right ");
8779             printtriangle(m, b, &horiz);
8780           }
8781           /* On the next iterations, consider the two edges that were  */
8782           /*   exposed (this is, are now visible to the newly inserted */
8783           /*   vertex) by the edge flip.                               */
8784           lprevself(horiz);
8785           leftvertex = farvertex;
8786         }
8787       }
8788     }
8789     if (!doflip) {
8790       /* The handle `horiz' is accepted as locally Delaunay. */
8791 #ifndef CDT_ONLY
8792       if (triflaws) {
8793         /* Check the triangle `horiz' for quality. */
8794         testtriangle(m, b, &horiz);
8795       }
8796 #endif /* not CDT_ONLY */
8797       /* Look for the next edge around the newly inserted vertex. */
8798       lnextself(horiz);
8799       sym(horiz, testtri);
8800       /* Check for finishing a complete revolution about the new vertex, or */
8801       /*   falling outside  of the triangulation.  The latter will happen   */
8802       /*   when a vertex is inserted at a boundary.                         */
8803       if ((leftvertex == first) || (testtri.tri == m->dummytri)) {
8804         /* We're done.  Return a triangle whose origin is the new vertex. */
8805         lnext(horiz, *searchtri);
8806         lnext(horiz, m->recenttri);
8807         return success;
8808       }
8809       /* Finish finding the next edge around the newly inserted vertex. */
8810       lnext(testtri, horiz);
8811       rightvertex = leftvertex;
8812       dest(horiz, leftvertex);
8813     }
8814   }
8815 }
8816 
8817 /*****************************************************************************/
8818 /*                                                                           */
8819 /*  triangulatepolygon()   Find the Delaunay triangulation of a polygon that */
8820 /*                         has a certain "nice" shape.  This includes the    */
8821 /*                         polygons that result from deletion of a vertex or */
8822 /*                         insertion of a segment.                           */
8823 /*                                                                           */
8824 /*  This is a conceptually difficult routine.  The starting assumption is    */
8825 /*  that we have a polygon with n sides.  n - 1 of these sides are currently */
8826 /*  represented as edges in the mesh.  One side, called the "base", need not */
8827 /*  be.                                                                      */
8828 /*                                                                           */
8829 /*  Inside the polygon is a structure I call a "fan", consisting of n - 1    */
8830 /*  triangles that share a common origin.  For each of these triangles, the  */
8831 /*  edge opposite the origin is one of the sides of the polygon.  The        */
8832 /*  primary edge of each triangle is the edge directed from the origin to    */
8833 /*  the destination; note that this is not the same edge that is a side of   */
8834 /*  the polygon.  `firstedge' is the primary edge of the first triangle.     */
8835 /*  From there, the triangles follow in counterclockwise order about the     */
8836 /*  polygon, until `lastedge', the primary edge of the last triangle.        */
8837 /*  `firstedge' and `lastedge' are probably connected to other triangles     */
8838 /*  beyond the extremes of the fan, but their identity is not important, as  */
8839 /*  long as the fan remains connected to them.                               */
8840 /*                                                                           */
8841 /*  Imagine the polygon oriented so that its base is at the bottom.  This    */
8842 /*  puts `firstedge' on the far right, and `lastedge' on the far left.       */
8843 /*  The right vertex of the base is the destination of `firstedge', and the  */
8844 /*  left vertex of the base is the apex of `lastedge'.                       */
8845 /*                                                                           */
8846 /*  The challenge now is to find the right sequence of edge flips to         */
8847 /*  transform the fan into a Delaunay triangulation of the polygon.  Each    */
8848 /*  edge flip effectively removes one triangle from the fan, committing it   */
8849 /*  to the polygon.  The resulting polygon has one fewer edge.  If `doflip'  */
8850 /*  is set, the final flip will be performed, resulting in a fan of one      */
8851 /*  (useless?) triangle.  If `doflip' is not set, the final flip is not      */
8852 /*  performed, resulting in a fan of two triangles, and an unfinished        */
8853 /*  triangular polygon that is not yet filled out with a single triangle.    */
8854 /*  On completion of the routine, `lastedge' is the last remaining triangle, */
8855 /*  or the leftmost of the last two.                                         */
8856 /*                                                                           */
8857 /*  Although the flips are performed in the order described above, the       */
8858 /*  decisions about what flips to perform are made in precisely the reverse  */
8859 /*  order.  The recursive triangulatepolygon() procedure makes a decision,   */
8860 /*  uses up to two recursive calls to triangulate the "subproblems"          */
8861 /*  (polygons with fewer edges), and then performs an edge flip.             */
8862 /*                                                                           */
8863 /*  The "decision" it makes is which vertex of the polygon should be         */
8864 /*  connected to the base.  This decision is made by testing every possible  */
8865 /*  vertex.  Once the best vertex is found, the two edges that connect this  */
8866 /*  vertex to the base become the bases for two smaller polygons.  These     */
8867 /*  are triangulated recursively.  Unfortunately, this approach can take     */
8868 /*  O(n^2) time not only in the worst case, but in many common cases.  It's  */
8869 /*  rarely a big deal for vertex deletion, where n is rarely larger than     */
8870 /*  ten, but it could be a big deal for segment insertion, especially if     */
8871 /*  there's a lot of long segments that each cut many triangles.  I ought to */
8872 /*  code a faster algorithm some day.                                        */
8873 /*                                                                           */
8874 /*  The `edgecount' parameter is the number of sides of the polygon,         */
8875 /*  including its base.  `triflaws' is a flag that determines whether the    */
8876 /*  new triangles should be tested for quality, and enqueued if they are     */
8877 /*  bad.                                                                     */
8878 /*                                                                           */
8879 /*****************************************************************************/
8880 
8881 #ifndef CDT_ONLY
8882 
8883 #ifdef ANSI_DECLARATORS
8884 static void triangulatepolygon(struct mesh *m, struct behavior *b,
8885                         struct otri *firstedge, struct otri *lastedge,
8886                         int edgecount, int doflip, int triflaws)
8887 #else /* not ANSI_DECLARATORS */
8888 static void triangulatepolygon(m, b, firstedge, lastedge, edgecount, doflip, triflaws)
8889 struct mesh *m;
8890 struct behavior *b;
8891 struct otri *firstedge;
8892 struct otri *lastedge;
8893 int edgecount;
8894 int doflip;
8895 int triflaws;
8896 #endif /* not ANSI_DECLARATORS */
8897 
8898 {
8899   struct otri testtri;
8900   struct otri besttri;
8901   struct otri tempedge;
8902   vertex leftbasevertex, rightbasevertex;
8903   vertex testvertex;
8904   vertex bestvertex;
8905   int bestnumber;
8906   int i;
8907   triangle ptr;   /* Temporary variable used by sym(), onext(), and oprev(). */
8908 
8909   /* Identify the base vertices. */
8910   apex(*lastedge, leftbasevertex);
8911   dest(*firstedge, rightbasevertex);
8912   if (b->verbose > 2) {
8913     printf("  Triangulating interior polygon at edge\n");
8914     printf("    (%.12g, %.12g) (%.12g, %.12g)\n", leftbasevertex[0],
8915            leftbasevertex[1], rightbasevertex[0], rightbasevertex[1]);
8916   }
8917   /* Find the best vertex to connect the base to. */
8918   onext(*firstedge, besttri);
8919   dest(besttri, bestvertex);
8920   otricopy(besttri, testtri);
8921   bestnumber = 1;
8922   for (i = 2; i <= edgecount - 2; i++) {
8923     onextself(testtri);
8924     dest(testtri, testvertex);
8925     /* Is this a better vertex? */
8926     if (incircle(m, b, leftbasevertex, rightbasevertex, bestvertex,
8927                  testvertex) > 0.0) {
8928       otricopy(testtri, besttri);
8929       bestvertex = testvertex;
8930       bestnumber = i;
8931     }
8932   }
8933   if (b->verbose > 2) {
8934     printf("    Connecting edge to (%.12g, %.12g)\n", bestvertex[0],
8935            bestvertex[1]);
8936   }
8937   if (bestnumber > 1) {
8938     /* Recursively triangulate the smaller polygon on the right. */
8939     oprev(besttri, tempedge);
8940     triangulatepolygon(m, b, firstedge, &tempedge, bestnumber + 1, 1,
8941                        triflaws);
8942   }
8943   if (bestnumber < edgecount - 2) {
8944     /* Recursively triangulate the smaller polygon on the left. */
8945     sym(besttri, tempedge);
8946     triangulatepolygon(m, b, &besttri, lastedge, edgecount - bestnumber, 1,
8947                        triflaws);
8948     /* Find `besttri' again; it may have been lost to edge flips. */
8949     sym(tempedge, besttri);
8950   }
8951   if (doflip) {
8952     /* Do one final edge flip. */
8953     flip(m, b, &besttri);
8954 #ifndef CDT_ONLY
8955     if (triflaws) {
8956       /* Check the quality of the newly committed triangle. */
8957       sym(besttri, testtri);
8958       testtriangle(m, b, &testtri);
8959     }
8960 #endif /* not CDT_ONLY */
8961   }
8962   /* Return the base triangle. */
8963   otricopy(besttri, *lastedge);
8964 }
8965 
8966 #endif /* not CDT_ONLY */
8967 
8968 /*****************************************************************************/
8969 /*                                                                           */
8970 /*  deletevertex()   Delete a vertex from a Delaunay triangulation, ensuring */
8971 /*                   that the triangulation remains Delaunay.                */
8972 /*                                                                           */
8973 /*  The origin of `deltri' is deleted.  The union of the triangles adjacent  */
8974 /*  to this vertex is a polygon, for which the Delaunay triangulation is     */
8975 /*  found.  Two triangles are removed from the mesh.                         */
8976 /*                                                                           */
8977 /*  Only interior vertices that do not lie on segments or boundaries may be  */
8978 /*  deleted.                                                                 */
8979 /*                                                                           */
8980 /*****************************************************************************/
8981 
8982 #ifndef CDT_ONLY
8983 
8984 #ifdef ANSI_DECLARATORS
8985 static void deletevertex(struct mesh *m, struct behavior *b, struct otri *deltri)
8986 #else /* not ANSI_DECLARATORS */
8987 static void deletevertex(m, b, deltri)
8988 struct mesh *m;
8989 struct behavior *b;
8990 struct otri *deltri;
8991 #endif /* not ANSI_DECLARATORS */
8992 
8993 {
8994   struct otri countingtri;
8995   struct otri firstedge, lastedge;
8996   struct otri deltriright;
8997   struct otri lefttri, righttri;
8998   struct otri leftcasing, rightcasing;
8999   struct osub leftsubseg, rightsubseg;
9000   vertex delvertex;
9001   vertex neworg;
9002   int edgecount;
9003   triangle ptr;   /* Temporary variable used by sym(), onext(), and oprev(). */
9004   subseg sptr;                      /* Temporary variable used by tspivot(). */
9005 
9006   org(*deltri, delvertex);
9007   if (b->verbose > 1) {
9008     printf("  Deleting (%.12g, %.12g).\n", delvertex[0], delvertex[1]);
9009   }
9010   vertexdealloc(m, delvertex);
9011 
9012   /* Count the degree of the vertex being deleted. */
9013   onext(*deltri, countingtri);
9014   edgecount = 1;
9015   while (!otriequal(*deltri, countingtri)) {
9016 #ifdef SELF_CHECK
9017     if (countingtri.tri == m->dummytri) {
9018       printf("Internal error in deletevertex():\n");
9019       printf("  Attempt to delete boundary vertex.\n");
9020       internalerror();
9021     }
9022 #endif /* SELF_CHECK */
9023     edgecount++;
9024     onextself(countingtri);
9025   }
9026 
9027 #ifdef SELF_CHECK
9028   if (edgecount < 3) {
9029     printf("Internal error in deletevertex():\n  Vertex has degree %d.\n",
9030            edgecount);
9031     internalerror();
9032   }
9033 #endif /* SELF_CHECK */
9034   if (edgecount > 3) {
9035     /* Triangulate the polygon defined by the union of all triangles */
9036     /*   adjacent to the vertex being deleted.  Check the quality of */
9037     /*   the resulting triangles.                                    */
9038     onext(*deltri, firstedge);
9039     oprev(*deltri, lastedge);
9040     triangulatepolygon(m, b, &firstedge, &lastedge, edgecount, 0,
9041                        !b->nobisect);
9042   }
9043   /* Splice out two triangles. */
9044   lprev(*deltri, deltriright);
9045   dnext(*deltri, lefttri);
9046   sym(lefttri, leftcasing);
9047   oprev(deltriright, righttri);
9048   sym(righttri, rightcasing);
9049   bond(*deltri, leftcasing);
9050   bond(deltriright, rightcasing);
9051   tspivot(lefttri, leftsubseg);
9052   if (leftsubseg.ss != m->dummysub) {
9053     tsbond(*deltri, leftsubseg);
9054   }
9055   tspivot(righttri, rightsubseg);
9056   if (rightsubseg.ss != m->dummysub) {
9057     tsbond(deltriright, rightsubseg);
9058   }
9059 
9060   /* Set the new origin of `deltri' and check its quality. */
9061   org(lefttri, neworg);
9062   setorg(*deltri, neworg);
9063   if (!b->nobisect) {
9064     testtriangle(m, b, deltri);
9065   }
9066 
9067   /* Delete the two spliced-out triangles. */
9068   triangledealloc(m, lefttri.tri);
9069   triangledealloc(m, righttri.tri);
9070 }
9071 
9072 #endif /* not CDT_ONLY */
9073 
9074 /*****************************************************************************/
9075 /*                                                                           */
9076 /*  undovertex()   Undo the most recent vertex insertion.                    */
9077 /*                                                                           */
9078 /*  Walks through the list of transformations (flips and a vertex insertion) */
9079 /*  in the reverse of the order in which they were done, and undoes them.    */
9080 /*  The inserted vertex is removed from the triangulation and deallocated.   */
9081 /*  Two triangles (possibly just one) are also deallocated.                  */
9082 /*                                                                           */
9083 /*****************************************************************************/
9084 
9085 #ifndef CDT_ONLY
9086 
9087 #ifdef ANSI_DECLARATORS
9088 static void undovertex(struct mesh *m, struct behavior *b)
9089 #else /* not ANSI_DECLARATORS */
9090 static void undovertex(m, b)
9091 struct mesh *m;
9092 struct behavior *b;
9093 #endif /* not ANSI_DECLARATORS */
9094 
9095 {
9096   struct otri fliptri;
9097   struct otri botleft, botright, topright;
9098   struct otri botlcasing, botrcasing, toprcasing;
9099   struct otri gluetri;
9100   struct osub botlsubseg, botrsubseg, toprsubseg;
9101   vertex botvertex, rightvertex;
9102   triangle ptr;                         /* Temporary variable used by sym(). */
9103   subseg sptr;                      /* Temporary variable used by tspivot(). */
9104 
9105   /* Walk through the list of transformations (flips and a vertex insertion) */
9106   /*   in the reverse of the order in which they were done, and undo them.   */
9107   while (m->lastflip != (struct flipstacker *) NULL) {
9108     /* Find a triangle involved in the last unreversed transformation. */
9109     decode(m->lastflip->flippedtri, fliptri);
9110 
9111     /* We are reversing one of three transformations:  a trisection of one */
9112     /*   triangle into three (by inserting a vertex in the triangle), a    */
9113     /*   bisection of two triangles into four (by inserting a vertex in an */
9114     /*   edge), or an edge flip.                                           */
9115     if (m->lastflip->prevflip == (struct flipstacker *) NULL) {
9116       /* Restore a triangle that was split into three triangles, */
9117       /*   so it is again one triangle.                          */
9118       dprev(fliptri, botleft);
9119       lnextself(botleft);
9120       onext(fliptri, botright);
9121       lprevself(botright);
9122       sym(botleft, botlcasing);
9123       sym(botright, botrcasing);
9124       dest(botleft, botvertex);
9125 
9126       setapex(fliptri, botvertex);
9127       lnextself(fliptri);
9128       bond(fliptri, botlcasing);
9129       tspivot(botleft, botlsubseg);
9130       tsbond(fliptri, botlsubseg);
9131       lnextself(fliptri);
9132       bond(fliptri, botrcasing);
9133       tspivot(botright, botrsubseg);
9134       tsbond(fliptri, botrsubseg);
9135 
9136       /* Delete the two spliced-out triangles. */
9137       triangledealloc(m, botleft.tri);
9138       triangledealloc(m, botright.tri);
9139     } else if (m->lastflip->prevflip == (struct flipstacker *) &insertvertex) {
9140       /* Restore two triangles that were split into four triangles, */
9141       /*   so they are again two triangles.                         */
9142       lprev(fliptri, gluetri);
9143       sym(gluetri, botright);
9144       lnextself(botright);
9145       sym(botright, botrcasing);
9146       dest(botright, rightvertex);
9147 
9148       setorg(fliptri, rightvertex);
9149       bond(gluetri, botrcasing);
9150       tspivot(botright, botrsubseg);
9151       tsbond(gluetri, botrsubseg);
9152 
9153       /* Delete the spliced-out triangle. */
9154       triangledealloc(m, botright.tri);
9155 
9156       sym(fliptri, gluetri);
9157       if (gluetri.tri != m->dummytri) {
9158         lnextself(gluetri);
9159         dnext(gluetri, topright);
9160         sym(topright, toprcasing);
9161 
9162         setorg(gluetri, rightvertex);
9163         bond(gluetri, toprcasing);
9164         tspivot(topright, toprsubseg);
9165         tsbond(gluetri, toprsubseg);
9166 
9167         /* Delete the spliced-out triangle. */
9168         triangledealloc(m, topright.tri);
9169       }
9170 
9171       /* This is the end of the list, sneakily encoded. */
9172       m->lastflip->prevflip = (struct flipstacker *) NULL;
9173     } else {
9174       /* Undo an edge flip. */
9175       unflip(m, b, &fliptri);
9176     }
9177 
9178     /* Go on and process the next transformation. */
9179     m->lastflip = m->lastflip->prevflip;
9180   }
9181 }
9182 
9183 #endif /* not CDT_ONLY */
9184 
9185 /**                                                                         **/
9186 /**                                                                         **/
9187 /********* Mesh transformation routines end here                     *********/
9188 
9189 /********* Divide-and-conquer Delaunay triangulation begins here     *********/
9190 /**                                                                         **/
9191 /**                                                                         **/
9192 
9193 /*****************************************************************************/
9194 /*                                                                           */
9195 /*  The divide-and-conquer bounding box                                      */
9196 /*                                                                           */
9197 /*  I originally implemented the divide-and-conquer and incremental Delaunay */
9198 /*  triangulations using the edge-based data structure presented by Guibas   */
9199 /*  and Stolfi.  Switching to a triangle-based data structure doubled the    */
9200 /*  speed.  However, I had to think of a few extra tricks to maintain the    */
9201 /*  elegance of the original algorithms.                                     */
9202 /*                                                                           */
9203 /*  The "bounding box" used by my variant of the divide-and-conquer          */
9204 /*  algorithm uses one triangle for each edge of the convex hull of the      */
9205 /*  triangulation.  These bounding triangles all share a common apical       */
9206 /*  vertex, which is represented by NULL and which represents nothing.       */
9207 /*  The bounding triangles are linked in a circular fan about this NULL      */
9208 /*  vertex, and the edges on the convex hull of the triangulation appear     */
9209 /*  opposite the NULL vertex.  You might find it easiest to imagine that     */
9210 /*  the NULL vertex is a point in 3D space behind the center of the          */
9211 /*  triangulation, and that the bounding triangles form a sort of cone.      */
9212 /*                                                                           */
9213 /*  This bounding box makes it easy to represent degenerate cases.  For      */
9214 /*  instance, the triangulation of two vertices is a single edge.  This edge */
9215 /*  is represented by two bounding box triangles, one on each "side" of the  */
9216 /*  edge.  These triangles are also linked together in a fan about the NULL  */
9217 /*  vertex.                                                                  */
9218 /*                                                                           */
9219 /*  The bounding box also makes it easy to traverse the convex hull, as the  */
9220 /*  divide-and-conquer algorithm needs to do.                                */
9221 /*                                                                           */
9222 /*****************************************************************************/
9223 
9224 /*****************************************************************************/
9225 /*                                                                           */
9226 /*  vertexsort()   Sort an array of vertices by x-coordinate, using the      */
9227 /*                 y-coordinate as a secondary key.                          */
9228 /*                                                                           */
9229 /*  Uses quicksort.  Randomized O(n log n) time.  No, I did not make any of  */
9230 /*  the usual quicksort mistakes.                                            */
9231 /*                                                                           */
9232 /*****************************************************************************/
9233 
9234 #ifdef ANSI_DECLARATORS
9235 static void vertexsort(vertex *sortarray, int arraysize)
9236 #else /* not ANSI_DECLARATORS */
9237 static void vertexsort(sortarray, arraysize)
9238 vertex *sortarray;
9239 int arraysize;
9240 #endif /* not ANSI_DECLARATORS */
9241 
9242 {
9243   int left, right;
9244   int pivot;
9245   REAL pivotx, pivoty;
9246   vertex temp;
9247 
9248   if (arraysize == 2) {
9249     /* Recursive base case. */
9250     if ((sortarray[0][0] > sortarray[1][0]) ||
9251         ((sortarray[0][0] == sortarray[1][0]) &&
9252          (sortarray[0][1] > sortarray[1][1]))) {
9253       temp = sortarray[1];
9254       sortarray[1] = sortarray[0];
9255       sortarray[0] = temp;
9256     }
9257     return;
9258   }
9259   /* Choose a random pivot to split the array. */
9260   pivot = (int) randomnation((unsigned int) arraysize);
9261   pivotx = sortarray[pivot][0];
9262   pivoty = sortarray[pivot][1];
9263   /* Split the array. */
9264   left = -1;
9265   right = arraysize;
9266   while (left < right) {
9267     /* Search for a vertex whose x-coordinate is too large for the left. */
9268     do {
9269       left++;
9270     } while ((left <= right) && ((sortarray[left][0] < pivotx) ||
9271                                  ((sortarray[left][0] == pivotx) &&
9272                                   (sortarray[left][1] < pivoty))));
9273     /* Search for a vertex whose x-coordinate is too small for the right. */
9274     do {
9275       right--;
9276     } while ((left <= right) && ((sortarray[right][0] > pivotx) ||
9277                                  ((sortarray[right][0] == pivotx) &&
9278                                   (sortarray[right][1] > pivoty))));
9279     if (left < right) {
9280       /* Swap the left and right vertices. */
9281       temp = sortarray[left];
9282       sortarray[left] = sortarray[right];
9283       sortarray[right] = temp;
9284     }
9285   }
9286   if (left > 1) {
9287     /* Recursively sort the left subset. */
9288     vertexsort(sortarray, left);
9289   }
9290   if (right < arraysize - 2) {
9291     /* Recursively sort the right subset. */
9292     vertexsort(&sortarray[right + 1], arraysize - right - 1);
9293   }
9294 }
9295 
9296 /*****************************************************************************/
9297 /*                                                                           */
9298 /*  vertexmedian()   An order statistic algorithm, almost.  Shuffles an      */
9299 /*                   array of vertices so that the first `median' vertices   */
9300 /*                   occur lexicographically before the remaining vertices.  */
9301 /*                                                                           */
9302 /*  Uses the x-coordinate as the primary key if axis == 0; the y-coordinate  */
9303 /*  if axis == 1.  Very similar to the vertexsort() procedure, but runs in   */
9304 /*  randomized linear time.                                                  */
9305 /*                                                                           */
9306 /*****************************************************************************/
9307 
9308 #ifdef ANSI_DECLARATORS
9309 static void vertexmedian(vertex *sortarray, int arraysize, int median, int axis)
9310 #else /* not ANSI_DECLARATORS */
9311 static void vertexmedian(sortarray, arraysize, median, axis)
9312 vertex *sortarray;
9313 int arraysize;
9314 int median;
9315 int axis;
9316 #endif /* not ANSI_DECLARATORS */
9317 
9318 {
9319   int left, right;
9320   int pivot;
9321   REAL pivot1, pivot2;
9322   vertex temp;
9323 
9324   if (arraysize == 2) {
9325     /* Recursive base case. */
9326     if ((sortarray[0][axis] > sortarray[1][axis]) ||
9327         ((sortarray[0][axis] == sortarray[1][axis]) &&
9328          (sortarray[0][1 - axis] > sortarray[1][1 - axis]))) {
9329       temp = sortarray[1];
9330       sortarray[1] = sortarray[0];
9331       sortarray[0] = temp;
9332     }
9333     return;
9334   }
9335   /* Choose a random pivot to split the array. */
9336   pivot = (int) randomnation((unsigned int) arraysize);
9337   pivot1 = sortarray[pivot][axis];
9338   pivot2 = sortarray[pivot][1 - axis];
9339   /* Split the array. */
9340   left = -1;
9341   right = arraysize;
9342   while (left < right) {
9343     /* Search for a vertex whose x-coordinate is too large for the left. */
9344     do {
9345       left++;
9346     } while ((left <= right) && ((sortarray[left][axis] < pivot1) ||
9347                                  ((sortarray[left][axis] == pivot1) &&
9348                                   (sortarray[left][1 - axis] < pivot2))));
9349     /* Search for a vertex whose x-coordinate is too small for the right. */
9350     do {
9351       right--;
9352     } while ((left <= right) && ((sortarray[right][axis] > pivot1) ||
9353                                  ((sortarray[right][axis] == pivot1) &&
9354                                   (sortarray[right][1 - axis] > pivot2))));
9355     if (left < right) {
9356       /* Swap the left and right vertices. */
9357       temp = sortarray[left];
9358       sortarray[left] = sortarray[right];
9359       sortarray[right] = temp;
9360     }
9361   }
9362   /* Unlike in vertexsort(), at most one of the following */
9363   /*   conditionals is true.                             */
9364   if (left > median) {
9365     /* Recursively shuffle the left subset. */
9366     vertexmedian(sortarray, left, median, axis);
9367   }
9368   if (right < median - 1) {
9369     /* Recursively shuffle the right subset. */
9370     vertexmedian(&sortarray[right + 1], arraysize - right - 1,
9371                  median - right - 1, axis);
9372   }
9373 }
9374 
9375 /*****************************************************************************/
9376 /*                                                                           */
9377 /*  alternateaxes()   Sorts the vertices as appropriate for the divide-and-  */
9378 /*                    conquer algorithm with alternating cuts.               */
9379 /*                                                                           */
9380 /*  Partitions by x-coordinate if axis == 0; by y-coordinate if axis == 1.   */
9381 /*  For the base case, subsets containing only two or three vertices are     */
9382 /*  always sorted by x-coordinate.                                           */
9383 /*                                                                           */
9384 /*****************************************************************************/
9385 
9386 #ifdef ANSI_DECLARATORS
9387 static void alternateaxes(vertex *sortarray, int arraysize, int axis)
9388 #else /* not ANSI_DECLARATORS */
9389 static void alternateaxes(sortarray, arraysize, axis)
9390 vertex *sortarray;
9391 int arraysize;
9392 int axis;
9393 #endif /* not ANSI_DECLARATORS */
9394 
9395 {
9396   int divider;
9397 
9398   divider = arraysize >> 1;
9399   if (arraysize <= 3) {
9400     /* Recursive base case:  subsets of two or three vertices will be    */
9401     /*   handled specially, and should always be sorted by x-coordinate. */
9402     axis = 0;
9403   }
9404   /* Partition with a horizontal or vertical cut. */
9405   vertexmedian(sortarray, arraysize, divider, axis);
9406   /* Recursively partition the subsets with a cross cut. */
9407   if (arraysize - divider >= 2) {
9408     if (divider >= 2) {
9409       alternateaxes(sortarray, divider, 1 - axis);
9410     }
9411     alternateaxes(&sortarray[divider], arraysize - divider, 1 - axis);
9412   }
9413 }
9414 
9415 /*****************************************************************************/
9416 /*                                                                           */
9417 /*  mergehulls()   Merge two adjacent Delaunay triangulations into a         */
9418 /*                 single Delaunay triangulation.                            */
9419 /*                                                                           */
9420 /*  This is similar to the algorithm given by Guibas and Stolfi, but uses    */
9421 /*  a triangle-based, rather than edge-based, data structure.                */
9422 /*                                                                           */
9423 /*  The algorithm walks up the gap between the two triangulations, knitting  */
9424 /*  them together.  As they are merged, some of their bounding triangles     */
9425 /*  are converted into real triangles of the triangulation.  The procedure   */
9426 /*  pulls each hull's bounding triangles apart, then knits them together     */
9427 /*  like the teeth of two gears.  The Delaunay property determines, at each  */
9428 /*  step, whether the next "tooth" is a bounding triangle of the left hull   */
9429 /*  or the right.  When a bounding triangle becomes real, its apex is        */
9430 /*  changed from NULL to a real vertex.                                      */
9431 /*                                                                           */
9432 /*  Only two new triangles need to be allocated.  These become new bounding  */
9433 /*  triangles at the top and bottom of the seam.  They are used to connect   */
9434 /*  the remaining bounding triangles (those that have not been converted     */
9435 /*  into real triangles) into a single fan.                                  */
9436 /*                                                                           */
9437 /*  On entry, `farleft' and `innerleft' are bounding triangles of the left   */
9438 /*  triangulation.  The origin of `farleft' is the leftmost vertex, and      */
9439 /*  the destination of `innerleft' is the rightmost vertex of the            */
9440 /*  triangulation.  Similarly, `innerright' and `farright' are bounding      */
9441 /*  triangles of the right triangulation.  The origin of `innerright' and    */
9442 /*  destination of `farright' are the leftmost and rightmost vertices.       */
9443 /*                                                                           */
9444 /*  On completion, the origin of `farleft' is the leftmost vertex of the     */
9445 /*  merged triangulation, and the destination of `farright' is the rightmost */
9446 /*  vertex.                                                                  */
9447 /*                                                                           */
9448 /*****************************************************************************/
9449 
9450 #ifdef ANSI_DECLARATORS
9451 static void mergehulls(struct mesh *m, struct behavior *b, struct otri *farleft,
9452                 struct otri *innerleft, struct otri *innerright,
9453                 struct otri *farright, int axis)
9454 #else /* not ANSI_DECLARATORS */
9455 static void mergehulls(m, b, farleft, innerleft, innerright, farright, axis)
9456 struct mesh *m;
9457 struct behavior *b;
9458 struct otri *farleft;
9459 struct otri *innerleft;
9460 struct otri *innerright;
9461 struct otri *farright;
9462 int axis;
9463 #endif /* not ANSI_DECLARATORS */
9464 
9465 {
9466   struct otri leftcand, rightcand;
9467   struct otri baseedge;
9468   struct otri nextedge;
9469   struct otri sidecasing, topcasing, outercasing;
9470   struct otri checkedge;
9471   vertex innerleftdest;
9472   vertex innerrightorg;
9473   vertex innerleftapex, innerrightapex;
9474   vertex farleftpt, farrightpt;
9475   vertex farleftapex, farrightapex;
9476   vertex lowerleft, lowerright;
9477   vertex upperleft, upperright;
9478   vertex nextapex;
9479   vertex checkvertex;
9480   int changemade;
9481   int badedge;
9482   int leftfinished, rightfinished;
9483   triangle ptr;                         /* Temporary variable used by sym(). */
9484 
9485   dest(*innerleft, innerleftdest);
9486   apex(*innerleft, innerleftapex);
9487   org(*innerright, innerrightorg);
9488   apex(*innerright, innerrightapex);
9489   /* Special treatment for horizontal cuts. */
9490   if (b->dwyer && (axis == 1)) {
9491     org(*farleft, farleftpt);
9492     apex(*farleft, farleftapex);
9493     dest(*farright, farrightpt);
9494     apex(*farright, farrightapex);
9495     /* The pointers to the extremal vertices are shifted to point to the */
9496     /*   topmost and bottommost vertex of each hull, rather than the     */
9497     /*   leftmost and rightmost vertices.                                */
9498     while (farleftapex[1] < farleftpt[1]) {
9499       lnextself(*farleft);
9500       symself(*farleft);
9501       farleftpt = farleftapex;
9502       apex(*farleft, farleftapex);
9503     }
9504     sym(*innerleft, checkedge);
9505     apex(checkedge, checkvertex);
9506     while (checkvertex[1] > innerleftdest[1]) {
9507       lnext(checkedge, *innerleft);
9508       innerleftapex = innerleftdest;
9509       innerleftdest = checkvertex;
9510       sym(*innerleft, checkedge);
9511       apex(checkedge, checkvertex);
9512     }
9513     while (innerrightapex[1] < innerrightorg[1]) {
9514       lnextself(*innerright);
9515       symself(*innerright);
9516       innerrightorg = innerrightapex;
9517       apex(*innerright, innerrightapex);
9518     }
9519     sym(*farright, checkedge);
9520     apex(checkedge, checkvertex);
9521     while (checkvertex[1] > farrightpt[1]) {
9522       lnext(checkedge, *farright);
9523       farrightapex = farrightpt;
9524       farrightpt = checkvertex;
9525       sym(*farright, checkedge);
9526       apex(checkedge, checkvertex);
9527     }
9528   }
9529   /* Find a line tangent to and below both hulls. */
9530   do {
9531     changemade = 0;
9532     /* Make innerleftdest the "bottommost" vertex of the left hull. */
9533     if (counterclockwise(m, b, innerleftdest, innerleftapex, innerrightorg) >
9534         0.0) {
9535       lprevself(*innerleft);
9536       symself(*innerleft);
9537       innerleftdest = innerleftapex;
9538       apex(*innerleft, innerleftapex);
9539       changemade = 1;
9540     }
9541     /* Make innerrightorg the "bottommost" vertex of the right hull. */
9542     if (counterclockwise(m, b, innerrightapex, innerrightorg, innerleftdest) >
9543         0.0) {
9544       lnextself(*innerright);
9545       symself(*innerright);
9546       innerrightorg = innerrightapex;
9547       apex(*innerright, innerrightapex);
9548       changemade = 1;
9549     }
9550   } while (changemade);
9551   /* Find the two candidates to be the next "gear tooth." */
9552   sym(*innerleft, leftcand);
9553   sym(*innerright, rightcand);
9554   /* Create the bottom new bounding triangle. */
9555   maketriangle(m, b, &baseedge);
9556   /* Connect it to the bounding boxes of the left and right triangulations. */
9557   bond(baseedge, *innerleft);
9558   lnextself(baseedge);
9559   bond(baseedge, *innerright);
9560   lnextself(baseedge);
9561   setorg(baseedge, innerrightorg);
9562   setdest(baseedge, innerleftdest);
9563   /* Apex is intentionally left NULL. */
9564   if (b->verbose > 2) {
9565     printf("  Creating base bounding ");
9566     printtriangle(m, b, &baseedge);
9567   }
9568   /* Fix the extreme triangles if necessary. */
9569   org(*farleft, farleftpt);
9570   if (innerleftdest == farleftpt) {
9571     lnext(baseedge, *farleft);
9572   }
9573   dest(*farright, farrightpt);
9574   if (innerrightorg == farrightpt) {
9575     lprev(baseedge, *farright);
9576   }
9577   /* The vertices of the current knitting edge. */
9578   lowerleft = innerleftdest;
9579   lowerright = innerrightorg;
9580   /* The candidate vertices for knitting. */
9581   apex(leftcand, upperleft);
9582   apex(rightcand, upperright);
9583   /* Walk up the gap between the two triangulations, knitting them together. */
9584   while (1) {
9585     /* Have we reached the top?  (This isn't quite the right question,       */
9586     /*   because even though the left triangulation might seem finished now, */
9587     /*   moving up on the right triangulation might reveal a new vertex of   */
9588     /*   the left triangulation.  And vice-versa.)                           */
9589     leftfinished = counterclockwise(m, b, upperleft, lowerleft, lowerright) <=
9590                    0.0;
9591     rightfinished = counterclockwise(m, b, upperright, lowerleft, lowerright)
9592                  <= 0.0;
9593     if (leftfinished && rightfinished) {
9594       /* Create the top new bounding triangle. */
9595       maketriangle(m, b, &nextedge);
9596       setorg(nextedge, lowerleft);
9597       setdest(nextedge, lowerright);
9598       /* Apex is intentionally left NULL. */
9599       /* Connect it to the bounding boxes of the two triangulations. */
9600       bond(nextedge, baseedge);
9601       lnextself(nextedge);
9602       bond(nextedge, rightcand);
9603       lnextself(nextedge);
9604       bond(nextedge, leftcand);
9605       if (b->verbose > 2) {
9606         printf("  Creating top bounding ");
9607         printtriangle(m, b, &nextedge);
9608       }
9609       /* Special treatment for horizontal cuts. */
9610       if (b->dwyer && (axis == 1)) {
9611         org(*farleft, farleftpt);
9612         apex(*farleft, farleftapex);
9613         dest(*farright, farrightpt);
9614         apex(*farright, farrightapex);
9615         sym(*farleft, checkedge);
9616         apex(checkedge, checkvertex);
9617         /* The pointers to the extremal vertices are restored to the  */
9618         /*   leftmost and rightmost vertices (rather than topmost and */
9619         /*   bottommost).                                             */
9620         while (checkvertex[0] < farleftpt[0]) {
9621           lprev(checkedge, *farleft);
9622           farleftapex = farleftpt;
9623           farleftpt = checkvertex;
9624           sym(*farleft, checkedge);
9625           apex(checkedge, checkvertex);
9626         }
9627         while (farrightapex[0] > farrightpt[0]) {
9628           lprevself(*farright);
9629           symself(*farright);
9630           farrightpt = farrightapex;
9631           apex(*farright, farrightapex);
9632         }
9633       }
9634       return;
9635     }
9636     /* Consider eliminating edges from the left triangulation. */
9637     if (!leftfinished) {
9638       /* What vertex would be exposed if an edge were deleted? */
9639       lprev(leftcand, nextedge);
9640       symself(nextedge);
9641       apex(nextedge, nextapex);
9642       /* If nextapex is NULL, then no vertex would be exposed; the */
9643       /*   triangulation would have been eaten right through.      */
9644       if (nextapex != (vertex) NULL) {
9645         /* Check whether the edge is Delaunay. */
9646         badedge = incircle(m, b, lowerleft, lowerright, upperleft, nextapex) >
9647                   0.0;
9648         while (badedge) {
9649           /* Eliminate the edge with an edge flip.  As a result, the    */
9650           /*   left triangulation will have one more boundary triangle. */
9651           lnextself(nextedge);
9652           sym(nextedge, topcasing);
9653           lnextself(nextedge);
9654           sym(nextedge, sidecasing);
9655           bond(nextedge, topcasing);
9656           bond(leftcand, sidecasing);
9657           lnextself(leftcand);
9658           sym(leftcand, outercasing);
9659           lprevself(nextedge);
9660           bond(nextedge, outercasing);
9661           /* Correct the vertices to reflect the edge flip. */
9662           setorg(leftcand, lowerleft);
9663           setdest(leftcand, NULL);
9664           setapex(leftcand, nextapex);
9665           setorg(nextedge, NULL);
9666           setdest(nextedge, upperleft);
9667           setapex(nextedge, nextapex);
9668           /* Consider the newly exposed vertex. */
9669           upperleft = nextapex;
9670           /* What vertex would be exposed if another edge were deleted? */
9671           otricopy(sidecasing, nextedge);
9672           apex(nextedge, nextapex);
9673           if (nextapex != (vertex) NULL) {
9674             /* Check whether the edge is Delaunay. */
9675             badedge = incircle(m, b, lowerleft, lowerright, upperleft,
9676                                nextapex) > 0.0;
9677           } else {
9678             /* Avoid eating right through the triangulation. */
9679             badedge = 0;
9680           }
9681         }
9682       }
9683     }
9684     /* Consider eliminating edges from the right triangulation. */
9685     if (!rightfinished) {
9686       /* What vertex would be exposed if an edge were deleted? */
9687       lnext(rightcand, nextedge);
9688       symself(nextedge);
9689       apex(nextedge, nextapex);
9690       /* If nextapex is NULL, then no vertex would be exposed; the */
9691       /*   triangulation would have been eaten right through.      */
9692       if (nextapex != (vertex) NULL) {
9693         /* Check whether the edge is Delaunay. */
9694         badedge = incircle(m, b, lowerleft, lowerright, upperright, nextapex) >
9695                   0.0;
9696         while (badedge) {
9697           /* Eliminate the edge with an edge flip.  As a result, the     */
9698           /*   right triangulation will have one more boundary triangle. */
9699           lprevself(nextedge);
9700           sym(nextedge, topcasing);
9701           lprevself(nextedge);
9702           sym(nextedge, sidecasing);
9703           bond(nextedge, topcasing);
9704           bond(rightcand, sidecasing);
9705           lprevself(rightcand);
9706           sym(rightcand, outercasing);
9707           lnextself(nextedge);
9708           bond(nextedge, outercasing);
9709           /* Correct the vertices to reflect the edge flip. */
9710           setorg(rightcand, NULL);
9711           setdest(rightcand, lowerright);
9712           setapex(rightcand, nextapex);
9713           setorg(nextedge, upperright);
9714           setdest(nextedge, NULL);
9715           setapex(nextedge, nextapex);
9716           /* Consider the newly exposed vertex. */
9717           upperright = nextapex;
9718           /* What vertex would be exposed if another edge were deleted? */
9719           otricopy(sidecasing, nextedge);
9720           apex(nextedge, nextapex);
9721           if (nextapex != (vertex) NULL) {
9722             /* Check whether the edge is Delaunay. */
9723             badedge = incircle(m, b, lowerleft, lowerright, upperright,
9724                                nextapex) > 0.0;
9725           } else {
9726             /* Avoid eating right through the triangulation. */
9727             badedge = 0;
9728           }
9729         }
9730       }
9731     }
9732     if (leftfinished || (!rightfinished &&
9733            (incircle(m, b, upperleft, lowerleft, lowerright, upperright) >
9734             0.0))) {
9735       /* Knit the triangulations, adding an edge from `lowerleft' */
9736       /*   to `upperright'.                                       */
9737       bond(baseedge, rightcand);
9738       lprev(rightcand, baseedge);
9739       setdest(baseedge, lowerleft);
9740       lowerright = upperright;
9741       sym(baseedge, rightcand);
9742       apex(rightcand, upperright);
9743     } else {
9744       /* Knit the triangulations, adding an edge from `upperleft' */
9745       /*   to `lowerright'.                                       */
9746       bond(baseedge, leftcand);
9747       lnext(leftcand, baseedge);
9748       setorg(baseedge, lowerright);
9749       lowerleft = upperleft;
9750       sym(baseedge, leftcand);
9751       apex(leftcand, upperleft);
9752     }
9753     if (b->verbose > 2) {
9754       printf("  Connecting ");
9755       printtriangle(m, b, &baseedge);
9756     }
9757   }
9758 }
9759 
9760 /*****************************************************************************/
9761 /*                                                                           */
9762 /*  divconqrecurse()   Recursively form a Delaunay triangulation by the      */
9763 /*                     divide-and-conquer method.                            */
9764 /*                                                                           */
9765 /*  Recursively breaks down the problem into smaller pieces, which are       */
9766 /*  knitted together by mergehulls().  The base cases (problems of two or    */
9767 /*  three vertices) are handled specially here.                              */
9768 /*                                                                           */
9769 /*  On completion, `farleft' and `farright' are bounding triangles such that */
9770 /*  the origin of `farleft' is the leftmost vertex (breaking ties by         */
9771 /*  choosing the highest leftmost vertex), and the destination of            */
9772 /*  `farright' is the rightmost vertex (breaking ties by choosing the        */
9773 /*  lowest rightmost vertex).                                                */
9774 /*                                                                           */
9775 /*****************************************************************************/
9776 
9777 #ifdef ANSI_DECLARATORS
9778 static void divconqrecurse(struct mesh *m, struct behavior *b, vertex *sortarray,
9779                     int vertices, int axis,
9780                     struct otri *farleft, struct otri *farright)
9781 #else /* not ANSI_DECLARATORS */
9782 static void divconqrecurse(m, b, sortarray, vertices, axis, farleft, farright)
9783 struct mesh *m;
9784 struct behavior *b;
9785 vertex *sortarray;
9786 int vertices;
9787 int axis;
9788 struct otri *farleft;
9789 struct otri *farright;
9790 #endif /* not ANSI_DECLARATORS */
9791 
9792 {
9793   struct otri midtri, tri1, tri2, tri3;
9794   struct otri innerleft, innerright;
9795   REAL area;
9796   int divider;
9797 
9798   if (b->verbose > 2) {
9799     printf("  Triangulating %d vertices.\n", vertices);
9800   }
9801   if (vertices == 2) {
9802     /* The triangulation of two vertices is an edge.  An edge is */
9803     /*   represented by two bounding triangles.                  */
9804     maketriangle(m, b, farleft);
9805     setorg(*farleft, sortarray[0]);
9806     setdest(*farleft, sortarray[1]);
9807     /* The apex is intentionally left NULL. */
9808     maketriangle(m, b, farright);
9809     setorg(*farright, sortarray[1]);
9810     setdest(*farright, sortarray[0]);
9811     /* The apex is intentionally left NULL. */
9812     bond(*farleft, *farright);
9813     lprevself(*farleft);
9814     lnextself(*farright);
9815     bond(*farleft, *farright);
9816     lprevself(*farleft);
9817     lnextself(*farright);
9818     bond(*farleft, *farright);
9819     if (b->verbose > 2) {
9820       printf("  Creating ");
9821       printtriangle(m, b, farleft);
9822       printf("  Creating ");
9823       printtriangle(m, b, farright);
9824     }
9825     /* Ensure that the origin of `farleft' is sortarray[0]. */
9826     lprev(*farright, *farleft);
9827     return;
9828   } else if (vertices == 3) {
9829     /* The triangulation of three vertices is either a triangle (with */
9830     /*   three bounding triangles) or two edges (with four bounding   */
9831     /*   triangles).  In either case, four triangles are created.     */
9832     maketriangle(m, b, &midtri);
9833     maketriangle(m, b, &tri1);
9834     maketriangle(m, b, &tri2);
9835     maketriangle(m, b, &tri3);
9836     area = counterclockwise(m, b, sortarray[0], sortarray[1], sortarray[2]);
9837     if (area == 0.0) {
9838       /* Three collinear vertices; the triangulation is two edges. */
9839       setorg(midtri, sortarray[0]);
9840       setdest(midtri, sortarray[1]);
9841       setorg(tri1, sortarray[1]);
9842       setdest(tri1, sortarray[0]);
9843       setorg(tri2, sortarray[2]);
9844       setdest(tri2, sortarray[1]);
9845       setorg(tri3, sortarray[1]);
9846       setdest(tri3, sortarray[2]);
9847       /* All apices are intentionally left NULL. */
9848       bond(midtri, tri1);
9849       bond(tri2, tri3);
9850       lnextself(midtri);
9851       lprevself(tri1);
9852       lnextself(tri2);
9853       lprevself(tri3);
9854       bond(midtri, tri3);
9855       bond(tri1, tri2);
9856       lnextself(midtri);
9857       lprevself(tri1);
9858       lnextself(tri2);
9859       lprevself(tri3);
9860       bond(midtri, tri1);
9861       bond(tri2, tri3);
9862       /* Ensure that the origin of `farleft' is sortarray[0]. */
9863       otricopy(tri1, *farleft);
9864       /* Ensure that the destination of `farright' is sortarray[2]. */
9865       otricopy(tri2, *farright);
9866     } else {
9867       /* The three vertices are not collinear; the triangulation is one */
9868       /*   triangle, namely `midtri'.                                   */
9869       setorg(midtri, sortarray[0]);
9870       setdest(tri1, sortarray[0]);
9871       setorg(tri3, sortarray[0]);
9872       /* Apices of tri1, tri2, and tri3 are left NULL. */
9873       if (area > 0.0) {
9874         /* The vertices are in counterclockwise order. */
9875         setdest(midtri, sortarray[1]);
9876         setorg(tri1, sortarray[1]);
9877         setdest(tri2, sortarray[1]);
9878         setapex(midtri, sortarray[2]);
9879         setorg(tri2, sortarray[2]);
9880         setdest(tri3, sortarray[2]);
9881       } else {
9882         /* The vertices are in clockwise order. */
9883         setdest(midtri, sortarray[2]);
9884         setorg(tri1, sortarray[2]);
9885         setdest(tri2, sortarray[2]);
9886         setapex(midtri, sortarray[1]);
9887         setorg(tri2, sortarray[1]);
9888         setdest(tri3, sortarray[1]);
9889       }
9890       /* The topology does not depend on how the vertices are ordered. */
9891       bond(midtri, tri1);
9892       lnextself(midtri);
9893       bond(midtri, tri2);
9894       lnextself(midtri);
9895       bond(midtri, tri3);
9896       lprevself(tri1);
9897       lnextself(tri2);
9898       bond(tri1, tri2);
9899       lprevself(tri1);
9900       lprevself(tri3);
9901       bond(tri1, tri3);
9902       lnextself(tri2);
9903       lprevself(tri3);
9904       bond(tri2, tri3);
9905       /* Ensure that the origin of `farleft' is sortarray[0]. */
9906       otricopy(tri1, *farleft);
9907       /* Ensure that the destination of `farright' is sortarray[2]. */
9908       if (area > 0.0) {
9909         otricopy(tri2, *farright);
9910       } else {
9911         lnext(*farleft, *farright);
9912       }
9913     }
9914     if (b->verbose > 2) {
9915       printf("  Creating ");
9916       printtriangle(m, b, &midtri);
9917       printf("  Creating ");
9918       printtriangle(m, b, &tri1);
9919       printf("  Creating ");
9920       printtriangle(m, b, &tri2);
9921       printf("  Creating ");
9922       printtriangle(m, b, &tri3);
9923     }
9924     return;
9925   } else {
9926     /* Split the vertices in half. */
9927     divider = vertices >> 1;
9928     /* Recursively triangulate each half. */
9929     divconqrecurse(m, b, sortarray, divider, 1 - axis, farleft, &innerleft);
9930     divconqrecurse(m, b, &sortarray[divider], vertices - divider, 1 - axis,
9931                    &innerright, farright);
9932     if (b->verbose > 1) {
9933       printf("  Joining triangulations with %d and %d vertices.\n", divider,
9934              vertices - divider);
9935     }
9936     /* Merge the two triangulations into one. */
9937     mergehulls(m, b, farleft, &innerleft, &innerright, farright, axis);
9938   }
9939 }
9940 
9941 #ifdef ANSI_DECLARATORS
9942 static LONG removeghosts(struct mesh *m, struct behavior *b, struct otri *startghost)
9943 #else /* not ANSI_DECLARATORS */
9944 static LONG removeghosts(m, b, startghost)
9945 struct mesh *m;
9946 struct behavior *b;
9947 struct otri *startghost;
9948 #endif /* not ANSI_DECLARATORS */
9949 
9950 {
9951   struct otri searchedge;
9952   struct otri dissolveedge;
9953   struct otri deadtriangle;
9954   vertex markorg;
9955   LONG hullsize;
9956   triangle ptr;                         /* Temporary variable used by sym(). */
9957 
9958   if (b->verbose) {
9959     printf("  Removing ghost triangles.\n");
9960   }
9961   /* Find an edge on the convex hull to start point location from. */
9962   lprev(*startghost, searchedge);
9963   symself(searchedge);
9964   m->dummytri[0] = encode(searchedge);
9965   /* Remove the bounding box and count the convex hull edges. */
9966   otricopy(*startghost, dissolveedge);
9967   hullsize = 0;
9968   do {
9969     hullsize++;
9970     lnext(dissolveedge, deadtriangle);
9971     lprevself(dissolveedge);
9972     symself(dissolveedge);
9973     /* If no PSLG is involved, set the boundary markers of all the vertices */
9974     /*   on the convex hull.  If a PSLG is used, this step is done later.   */
9975     if (!b->poly) {
9976       /* Watch out for the case where all the input vertices are collinear. */
9977       if (dissolveedge.tri != m->dummytri) {
9978         org(dissolveedge, markorg);
9979         if (vertexmark(markorg) == 0) {
9980           setvertexmark(markorg, 1);
9981         }
9982       }
9983     }
9984     /* Remove a bounding triangle from a convex hull triangle. */
9985     dissolve(dissolveedge);
9986     /* Find the next bounding triangle. */
9987     sym(deadtriangle, dissolveedge);
9988     /* Delete the bounding triangle. */
9989     triangledealloc(m, deadtriangle.tri);
9990   } while (!otriequal(dissolveedge, *startghost));
9991   return hullsize;
9992 }
9993 
9994 /*****************************************************************************/
9995 /*                                                                           */
9996 /*  divconqdelaunay()   Form a Delaunay triangulation by the divide-and-     */
9997 /*                      conquer method.                                      */
9998 /*                                                                           */
9999 /*  Sorts the vertices, calls a recursive procedure to triangulate them, and */
10000 /*  removes the bounding box, setting boundary markers as appropriate.       */
10001 /*                                                                           */
10002 /*****************************************************************************/
10003 
10004 #ifdef ANSI_DECLARATORS
10005 static LONG divconqdelaunay(struct mesh *m, struct behavior *b)
10006 #else /* not ANSI_DECLARATORS */
10007 static LONG divconqdelaunay(m, b)
10008 struct mesh *m;
10009 struct behavior *b;
10010 #endif /* not ANSI_DECLARATORS */
10011 
10012 {
10013   vertex *sortarray;
10014   struct otri hullleft, hullright;
10015   int divider;
10016   int i, j;
10017 
10018   if (b->verbose) {
10019     printf("  Sorting vertices.\n");
10020   }
10021 
10022   /* Allocate an array of pointers to vertices for sorting. */
10023   sortarray = (vertex *) trimalloc(m->invertices * (int) sizeof(vertex));
10024   traversalinit(&m->vertices);
10025   for (i = 0; i < m->invertices; i++) {
10026     sortarray[i] = vertextraverse(m);
10027   }
10028   /* Sort the vertices. */
10029   vertexsort(sortarray, m->invertices);
10030   /* Discard duplicate vertices, which can really mess up the algorithm. */
10031   i = 0;
10032   for (j = 1; j < m->invertices; j++) {
10033     if ((sortarray[i][0] == sortarray[j][0])
10034         && (sortarray[i][1] == sortarray[j][1])) {
10035       if (!b->quiet) {
10036         printf(
10037 "Warning:  A duplicate vertex at (%.12g, %.12g) appeared and was ignored.\n",
10038                sortarray[j][0], sortarray[j][1]);
10039       }
10040       setvertextype(sortarray[j], UNDEADVERTEX);
10041       m->undeads++;
10042     } else {
10043       i++;
10044       sortarray[i] = sortarray[j];
10045     }
10046   }
10047   i++;
10048   if (b->dwyer) {
10049     /* Re-sort the array of vertices to accommodate alternating cuts. */
10050     divider = i >> 1;
10051     if (i - divider >= 2) {
10052       if (divider >= 2) {
10053         alternateaxes(sortarray, divider, 1);
10054       }
10055       alternateaxes(&sortarray[divider], i - divider, 1);
10056     }
10057   }
10058 
10059   if (b->verbose) {
10060     printf("  Forming triangulation.\n");
10061   }
10062 
10063   /* Form the Delaunay triangulation. */
10064   divconqrecurse(m, b, sortarray, i, 0, &hullleft, &hullright);
10065   trifree((VOID *) sortarray);
10066 
10067   return removeghosts(m, b, &hullleft);
10068 }
10069 
10070 /**                                                                         **/
10071 /**                                                                         **/
10072 /********* Divide-and-conquer Delaunay triangulation ends here       *********/
10073 
10074 /********* Incremental Delaunay triangulation begins here            *********/
10075 /**                                                                         **/
10076 /**                                                                         **/
10077 
10078 /*****************************************************************************/
10079 /*                                                                           */
10080 /*  boundingbox()   Form an "infinite" bounding triangle to insert vertices  */
10081 /*                  into.                                                    */
10082 /*                                                                           */
10083 /*  The vertices at "infinity" are assigned finite coordinates, which are    */
10084 /*  used by the point location routines, but (mostly) ignored by the         */
10085 /*  Delaunay edge flip routines.                                             */
10086 /*                                                                           */
10087 /*****************************************************************************/
10088 
10089 #ifndef REDUCED
10090 
10091 #ifdef ANSI_DECLARATORS
10092 static void boundingbox(struct mesh *m, struct behavior *b)
10093 #else /* not ANSI_DECLARATORS */
10094 static void boundingbox(m, b)
10095 struct mesh *m;
10096 struct behavior *b;
10097 #endif /* not ANSI_DECLARATORS */
10098 
10099 {
10100   struct otri inftri;          /* Handle for the triangular bounding box. */
10101   REAL width;
10102 
10103   if (b->verbose) {
10104     printf("  Creating triangular bounding box.\n");
10105   }
10106   /* Find the width (or height, whichever is larger) of the triangulation. */
10107   width = m->xmax - m->xmin;
10108   if (m->ymax - m->ymin > width) {
10109     width = m->ymax - m->ymin;
10110   }
10111   if (width == 0.0) {
10112     width = 1.0;
10113   }
10114   /* Create the vertices of the bounding box. */
10115   m->infvertex1 = (vertex) trimalloc(m->vertices.itembytes);
10116   m->infvertex2 = (vertex) trimalloc(m->vertices.itembytes);
10117   m->infvertex3 = (vertex) trimalloc(m->vertices.itembytes);
10118   m->infvertex1[0] = m->xmin - 50.0 * width;
10119   m->infvertex1[1] = m->ymin - 40.0 * width;
10120   m->infvertex2[0] = m->xmax + 50.0 * width;
10121   m->infvertex2[1] = m->ymin - 40.0 * width;
10122   m->infvertex3[0] = 0.5 * (m->xmin + m->xmax);
10123   m->infvertex3[1] = m->ymax + 60.0 * width;
10124 
10125   /* Create the bounding box. */
10126   maketriangle(m, b, &inftri);
10127   setorg(inftri, m->infvertex1);
10128   setdest(inftri, m->infvertex2);
10129   setapex(inftri, m->infvertex3);
10130   /* Link dummytri to the bounding box so we can always find an */
10131   /*   edge to begin searching (point location) from.           */
10132   m->dummytri[0] = (triangle) inftri.tri;
10133   if (b->verbose > 2) {
10134     printf("  Creating ");
10135     printtriangle(m, b, &inftri);
10136   }
10137 }
10138 
10139 #endif /* not REDUCED */
10140 
10141 /*****************************************************************************/
10142 /*                                                                           */
10143 /*  removebox()   Remove the "infinite" bounding triangle, setting boundary  */
10144 /*                markers as appropriate.                                    */
10145 /*                                                                           */
10146 /*  The triangular bounding box has three boundary triangles (one for each   */
10147 /*  side of the bounding box), and a bunch of triangles fanning out from     */
10148 /*  the three bounding box vertices (one triangle for each edge of the       */
10149 /*  convex hull of the inner mesh).  This routine removes these triangles.   */
10150 /*                                                                           */
10151 /*  Returns the number of edges on the convex hull of the triangulation.     */
10152 /*                                                                           */
10153 /*****************************************************************************/
10154 
10155 #ifndef REDUCED
10156 
10157 #ifdef ANSI_DECLARATORS
10158 static LONG removebox(struct mesh *m, struct behavior *b)
10159 #else /* not ANSI_DECLARATORS */
10160 static LONG removebox(m, b)
10161 struct mesh *m;
10162 struct behavior *b;
10163 #endif /* not ANSI_DECLARATORS */
10164 
10165 {
10166   struct otri deadtriangle;
10167   struct otri searchedge;
10168   struct otri checkedge;
10169   struct otri nextedge, finaledge, dissolveedge;
10170   vertex markorg;
10171   LONG hullsize;
10172   triangle ptr;                         /* Temporary variable used by sym(). */
10173 
10174   if (b->verbose) {
10175     printf("  Removing triangular bounding box.\n");
10176   }
10177   /* Find a boundary triangle. */
10178   nextedge.tri = m->dummytri;
10179   nextedge.orient = 0;
10180   symself(nextedge);
10181   /* Mark a place to stop. */
10182   lprev(nextedge, finaledge);
10183   lnextself(nextedge);
10184   symself(nextedge);
10185   /* Find a triangle (on the boundary of the vertex set) that isn't */
10186   /*   a bounding box triangle.                                     */
10187   lprev(nextedge, searchedge);
10188   symself(searchedge);
10189   /* Check whether nextedge is another boundary triangle */
10190   /*   adjacent to the first one.                        */
10191   lnext(nextedge, checkedge);
10192   symself(checkedge);
10193   if (checkedge.tri == m->dummytri) {
10194     /* Go on to the next triangle.  There are only three boundary   */
10195     /*   triangles, and this next triangle cannot be the third one, */
10196     /*   so it's safe to stop here.                                 */
10197     lprevself(searchedge);
10198     symself(searchedge);
10199   }
10200   /* Find a new boundary edge to search from, as the current search */
10201   /*   edge lies on a bounding box triangle and will be deleted.    */
10202   m->dummytri[0] = encode(searchedge);
10203   hullsize = -2l;
10204   while (!otriequal(nextedge, finaledge)) {
10205     hullsize++;
10206     lprev(nextedge, dissolveedge);
10207     symself(dissolveedge);
10208     /* If not using a PSLG, the vertices should be marked now. */
10209     /*   (If using a PSLG, markhull() will do the job.)        */
10210     if (!b->poly) {
10211       /* Be careful!  One must check for the case where all the input     */
10212       /*   vertices are collinear, and thus all the triangles are part of */
10213       /*   the bounding box.  Otherwise, the setvertexmark() call below   */
10214       /*   will cause a bad pointer reference.                            */
10215       if (dissolveedge.tri != m->dummytri) {
10216         org(dissolveedge, markorg);
10217         if (vertexmark(markorg) == 0) {
10218           setvertexmark(markorg, 1);
10219         }
10220       }
10221     }
10222     /* Disconnect the bounding box triangle from the mesh triangle. */
10223     dissolve(dissolveedge);
10224     lnext(nextedge, deadtriangle);
10225     sym(deadtriangle, nextedge);
10226     /* Get rid of the bounding box triangle. */
10227     triangledealloc(m, deadtriangle.tri);
10228     /* Do we need to turn the corner? */
10229     if (nextedge.tri == m->dummytri) {
10230       /* Turn the corner. */
10231       otricopy(dissolveedge, nextedge);
10232     }
10233   }
10234   triangledealloc(m, finaledge.tri);
10235 
10236   trifree((VOID *) m->infvertex1);  /* Deallocate the bounding box vertices. */
10237   trifree((VOID *) m->infvertex2);
10238   trifree((VOID *) m->infvertex3);
10239 
10240   return hullsize;
10241 }
10242 
10243 #endif /* not REDUCED */
10244 
10245 /*****************************************************************************/
10246 /*                                                                           */
10247 /*  incrementaldelaunay()   Form a Delaunay triangulation by incrementally   */
10248 /*                          inserting vertices.                              */
10249 /*                                                                           */
10250 /*  Returns the number of edges on the convex hull of the triangulation.     */
10251 /*                                                                           */
10252 /*****************************************************************************/
10253 
10254 #ifndef REDUCED
10255 
10256 #ifdef ANSI_DECLARATORS
10257 static LONG incrementaldelaunay(struct mesh *m, struct behavior *b)
10258 #else /* not ANSI_DECLARATORS */
10259 static LONG incrementaldelaunay(m, b)
10260 struct mesh *m;
10261 struct behavior *b;
10262 #endif /* not ANSI_DECLARATORS */
10263 
10264 {
10265   struct otri starttri;
10266   vertex vertexloop;
10267 
10268   /* Create a triangular bounding box. */
10269   boundingbox(m, b);
10270   if (b->verbose) {
10271     printf("  Incrementally inserting vertices.\n");
10272   }
10273   traversalinit(&m->vertices);
10274   vertexloop = vertextraverse(m);
10275   while (vertexloop != (vertex) NULL) {
10276     starttri.tri = m->dummytri;
10277     if (insertvertex(m, b, vertexloop, &starttri, (struct osub *) NULL, 0, 0)
10278         == DUPLICATEVERTEX) {
10279       if (!b->quiet) {
10280         printf(
10281 "Warning:  A duplicate vertex at (%.12g, %.12g) appeared and was ignored.\n",
10282                vertexloop[0], vertexloop[1]);
10283       }
10284       setvertextype(vertexloop, UNDEADVERTEX);
10285       m->undeads++;
10286     }
10287     vertexloop = vertextraverse(m);
10288   }
10289   /* Remove the bounding box. */
10290   return removebox(m, b);
10291 }
10292 
10293 #endif /* not REDUCED */
10294 
10295 /**                                                                         **/
10296 /**                                                                         **/
10297 /********* Incremental Delaunay triangulation ends here              *********/
10298 
10299 /********* Sweepline Delaunay triangulation begins here              *********/
10300 /**                                                                         **/
10301 /**                                                                         **/
10302 
10303 #ifndef REDUCED
10304 
10305 #ifdef ANSI_DECLARATORS
10306 static void eventheapinsert(struct event **heap, int heapsize, struct event *newevent)
10307 #else /* not ANSI_DECLARATORS */
10308 static void eventheapinsert(heap, heapsize, newevent)
10309 struct event **heap;
10310 int heapsize;
10311 struct event *newevent;
10312 #endif /* not ANSI_DECLARATORS */
10313 
10314 {
10315   REAL eventx, eventy;
10316   int eventnum;
10317   int parent;
10318   int notdone;
10319 
10320   eventx = newevent->xkey;
10321   eventy = newevent->ykey;
10322   eventnum = heapsize;
10323   notdone = eventnum > 0;
10324   while (notdone) {
10325     parent = (eventnum - 1) >> 1;
10326     if ((heap[parent]->ykey < eventy) ||
10327         ((heap[parent]->ykey == eventy)
10328          && (heap[parent]->xkey <= eventx))) {
10329       notdone = 0;
10330     } else {
10331       heap[eventnum] = heap[parent];
10332       heap[eventnum]->heapposition = eventnum;
10333 
10334       eventnum = parent;
10335       notdone = eventnum > 0;
10336     }
10337   }
10338   heap[eventnum] = newevent;
10339   newevent->heapposition = eventnum;
10340 }
10341 
10342 #endif /* not REDUCED */
10343 
10344 #ifndef REDUCED
10345 
10346 #ifdef ANSI_DECLARATORS
10347 static void eventheapify(struct event **heap, int heapsize, int eventnum)
10348 #else /* not ANSI_DECLARATORS */
10349 static void eventheapify(heap, heapsize, eventnum)
10350 struct event **heap;
10351 int heapsize;
10352 int eventnum;
10353 #endif /* not ANSI_DECLARATORS */
10354 
10355 {
10356   struct event *thisevent;
10357   REAL eventx, eventy;
10358   int leftchild, rightchild;
10359   int smallest;
10360   int notdone;
10361 
10362   thisevent = heap[eventnum];
10363   eventx = thisevent->xkey;
10364   eventy = thisevent->ykey;
10365   leftchild = 2 * eventnum + 1;
10366   notdone = leftchild < heapsize;
10367   while (notdone) {
10368     if ((heap[leftchild]->ykey < eventy) ||
10369         ((heap[leftchild]->ykey == eventy)
10370          && (heap[leftchild]->xkey < eventx))) {
10371       smallest = leftchild;
10372     } else {
10373       smallest = eventnum;
10374     }
10375     rightchild = leftchild + 1;
10376     if (rightchild < heapsize) {
10377       if ((heap[rightchild]->ykey < heap[smallest]->ykey) ||
10378           ((heap[rightchild]->ykey == heap[smallest]->ykey)
10379            && (heap[rightchild]->xkey < heap[smallest]->xkey))) {
10380         smallest = rightchild;
10381       }
10382     }
10383     if (smallest == eventnum) {
10384       notdone = 0;
10385     } else {
10386       heap[eventnum] = heap[smallest];
10387       heap[eventnum]->heapposition = eventnum;
10388       heap[smallest] = thisevent;
10389       thisevent->heapposition = smallest;
10390 
10391       eventnum = smallest;
10392       leftchild = 2 * eventnum + 1;
10393       notdone = leftchild < heapsize;
10394     }
10395   }
10396 }
10397 
10398 #endif /* not REDUCED */
10399 
10400 #ifndef REDUCED
10401 
10402 #ifdef ANSI_DECLARATORS
10403 static void eventheapdelete(struct event **heap, int heapsize, int eventnum)
10404 #else /* not ANSI_DECLARATORS */
10405 static void eventheapdelete(heap, heapsize, eventnum)
10406 struct event **heap;
10407 int heapsize;
10408 int eventnum;
10409 #endif /* not ANSI_DECLARATORS */
10410 
10411 {
10412   struct event *moveevent;
10413   REAL eventx, eventy;
10414   int parent;
10415   int notdone;
10416 
10417   moveevent = heap[heapsize - 1];
10418   if (eventnum > 0) {
10419     eventx = moveevent->xkey;
10420     eventy = moveevent->ykey;
10421     do {
10422       parent = (eventnum - 1) >> 1;
10423       if ((heap[parent]->ykey < eventy) ||
10424           ((heap[parent]->ykey == eventy)
10425            && (heap[parent]->xkey <= eventx))) {
10426         notdone = 0;
10427       } else {
10428         heap[eventnum] = heap[parent];
10429         heap[eventnum]->heapposition = eventnum;
10430 
10431         eventnum = parent;
10432         notdone = eventnum > 0;
10433       }
10434     } while (notdone);
10435   }
10436   heap[eventnum] = moveevent;
10437   moveevent->heapposition = eventnum;
10438   eventheapify(heap, heapsize - 1, eventnum);
10439 }
10440 
10441 #endif /* not REDUCED */
10442 
10443 #ifndef REDUCED
10444 
10445 #ifdef ANSI_DECLARATORS
10446 static void createeventheap(struct mesh *m, struct event ***eventheap,
10447                      struct event **events, struct event **freeevents)
10448 #else /* not ANSI_DECLARATORS */
10449 static void createeventheap(m, eventheap, events, freeevents)
10450 struct mesh *m;
10451 struct event ***eventheap;
10452 struct event **events;
10453 struct event **freeevents;
10454 #endif /* not ANSI_DECLARATORS */
10455 
10456 {
10457   vertex thisvertex;
10458   int maxevents;
10459   int i;
10460 
10461   maxevents = (3 * m->invertices) / 2;
10462   *eventheap = (struct event **) trimalloc(maxevents *
10463                                            (int) sizeof(struct event *));
10464   *events = (struct event *) trimalloc(maxevents * (int) sizeof(struct event));
10465   traversalinit(&m->vertices);
10466   for (i = 0; i < m->invertices; i++) {
10467     thisvertex = vertextraverse(m);
10468     (*events)[i].eventptr = (VOID *) thisvertex;
10469     (*events)[i].xkey = thisvertex[0];
10470     (*events)[i].ykey = thisvertex[1];
10471     eventheapinsert(*eventheap, i, *events + i);
10472   }
10473   *freeevents = (struct event *) NULL;
10474   for (i = maxevents - 1; i >= m->invertices; i--) {
10475     (*events)[i].eventptr = (VOID *) *freeevents;
10476     *freeevents = *events + i;
10477   }
10478 }
10479 
10480 #endif /* not REDUCED */
10481 
10482 #ifndef REDUCED
10483 
10484 #ifdef ANSI_DECLARATORS
10485 static int rightofhyperbola(struct mesh *m, struct otri *fronttri, vertex newsite)
10486 #else /* not ANSI_DECLARATORS */
10487 static int rightofhyperbola(m, fronttri, newsite)
10488 struct mesh *m;
10489 struct otri *fronttri;
10490 vertex newsite;
10491 #endif /* not ANSI_DECLARATORS */
10492 
10493 {
10494   vertex leftvertex, rightvertex;
10495   REAL dxa, dya, dxb, dyb;
10496 
10497   m->hyperbolacount++;
10498 
10499   dest(*fronttri, leftvertex);
10500   apex(*fronttri, rightvertex);
10501   if ((leftvertex[1] < rightvertex[1]) ||
10502       ((leftvertex[1] == rightvertex[1]) &&
10503        (leftvertex[0] < rightvertex[0]))) {
10504     if (newsite[0] >= rightvertex[0]) {
10505       return 1;
10506     }
10507   } else {
10508     if (newsite[0] <= leftvertex[0]) {
10509       return 0;
10510     }
10511   }
10512   dxa = leftvertex[0] - newsite[0];
10513   dya = leftvertex[1] - newsite[1];
10514   dxb = rightvertex[0] - newsite[0];
10515   dyb = rightvertex[1] - newsite[1];
10516   return dya * (dxb * dxb + dyb * dyb) > dyb * (dxa * dxa + dya * dya);
10517 }
10518 
10519 #endif /* not REDUCED */
10520 
10521 #ifndef REDUCED
10522 
10523 #ifdef ANSI_DECLARATORS
10524 static REAL circletop(struct mesh *m, vertex pa, vertex pb, vertex pc, REAL ccwabc)
10525 #else /* not ANSI_DECLARATORS */
10526 static REAL circletop(m, pa, pb, pc, ccwabc)
10527 struct mesh *m;
10528 vertex pa;
10529 vertex pb;
10530 vertex pc;
10531 REAL ccwabc;
10532 #endif /* not ANSI_DECLARATORS */
10533 
10534 {
10535   REAL xac, yac, xbc, ybc, xab, yab;
10536   REAL aclen2, bclen2, ablen2;
10537 
10538   m->circletopcount++;
10539 
10540   xac = pa[0] - pc[0];
10541   yac = pa[1] - pc[1];
10542   xbc = pb[0] - pc[0];
10543   ybc = pb[1] - pc[1];
10544   xab = pa[0] - pb[0];
10545   yab = pa[1] - pb[1];
10546   aclen2 = xac * xac + yac * yac;
10547   bclen2 = xbc * xbc + ybc * ybc;
10548   ablen2 = xab * xab + yab * yab;
10549   return pc[1] + (xac * bclen2 - xbc * aclen2 + sqrt(aclen2 * bclen2 * ablen2))
10550                / (2.0 * ccwabc);
10551 }
10552 
10553 #endif /* not REDUCED */
10554 
10555 #ifndef REDUCED
10556 
10557 #ifdef ANSI_DECLARATORS
10558 static void check4deadevent(struct otri *checktri, struct event **freeevents,
10559                      struct event **eventheap, int *heapsize)
10560 #else /* not ANSI_DECLARATORS */
10561 static void check4deadevent(checktri, freeevents, eventheap, heapsize)
10562 struct otri *checktri;
10563 struct event **freeevents;
10564 struct event **eventheap;
10565 int *heapsize;
10566 #endif /* not ANSI_DECLARATORS */
10567 
10568 {
10569   struct event *deadevent;
10570   vertex eventvertex;
10571   int eventnum;
10572 
10573   org(*checktri, eventvertex);
10574   if (eventvertex != (vertex) NULL) {
10575     deadevent = (struct event *) eventvertex;
10576     eventnum = deadevent->heapposition;
10577     deadevent->eventptr = (VOID *) *freeevents;
10578     *freeevents = deadevent;
10579     eventheapdelete(eventheap, *heapsize, eventnum);
10580     (*heapsize)--;
10581     setorg(*checktri, NULL);
10582   }
10583 }
10584 
10585 #endif /* not REDUCED */
10586 
10587 #ifndef REDUCED
10588 
10589 #ifdef ANSI_DECLARATORS
10590 struct splaynode *splay(struct mesh *m, struct splaynode *splaytree,
10591                         vertex searchpoint, struct otri *searchtri)
10592 #else /* not ANSI_DECLARATORS */
10593 struct splaynode *splay(m, splaytree, searchpoint, searchtri)
10594 struct mesh *m;
10595 struct splaynode *splaytree;
10596 vertex searchpoint;
10597 struct otri *searchtri;
10598 #endif /* not ANSI_DECLARATORS */
10599 
10600 {
10601   struct splaynode *child, *grandchild;
10602   struct splaynode *lefttree, *righttree;
10603   struct splaynode *leftright;
10604   vertex checkvertex;
10605   int rightofroot, rightofchild;
10606 
10607   if (splaytree == (struct splaynode *) NULL) {
10608     return (struct splaynode *) NULL;
10609   }
10610   dest(splaytree->keyedge, checkvertex);
10611   if (checkvertex == splaytree->keydest) {
10612     rightofroot = rightofhyperbola(m, &splaytree->keyedge, searchpoint);
10613     if (rightofroot) {
10614       otricopy(splaytree->keyedge, *searchtri);
10615       child = splaytree->rchild;
10616     } else {
10617       child = splaytree->lchild;
10618     }
10619     if (child == (struct splaynode *) NULL) {
10620       return splaytree;
10621     }
10622     dest(child->keyedge, checkvertex);
10623     if (checkvertex != child->keydest) {
10624       child = splay(m, child, searchpoint, searchtri);
10625       if (child == (struct splaynode *) NULL) {
10626         if (rightofroot) {
10627           splaytree->rchild = (struct splaynode *) NULL;
10628         } else {
10629           splaytree->lchild = (struct splaynode *) NULL;
10630         }
10631         return splaytree;
10632       }
10633     }
10634     rightofchild = rightofhyperbola(m, &child->keyedge, searchpoint);
10635     if (rightofchild) {
10636       otricopy(child->keyedge, *searchtri);
10637       grandchild = splay(m, child->rchild, searchpoint, searchtri);
10638       child->rchild = grandchild;
10639     } else {
10640       grandchild = splay(m, child->lchild, searchpoint, searchtri);
10641       child->lchild = grandchild;
10642     }
10643     if (grandchild == (struct splaynode *) NULL) {
10644       if (rightofroot) {
10645         splaytree->rchild = child->lchild;
10646         child->lchild = splaytree;
10647       } else {
10648         splaytree->lchild = child->rchild;
10649         child->rchild = splaytree;
10650       }
10651       return child;
10652     }
10653     if (rightofchild) {
10654       if (rightofroot) {
10655         splaytree->rchild = child->lchild;
10656         child->lchild = splaytree;
10657       } else {
10658         splaytree->lchild = grandchild->rchild;
10659         grandchild->rchild = splaytree;
10660       }
10661       child->rchild = grandchild->lchild;
10662       grandchild->lchild = child;
10663     } else {
10664       if (rightofroot) {
10665         splaytree->rchild = grandchild->lchild;
10666         grandchild->lchild = splaytree;
10667       } else {
10668         splaytree->lchild = child->rchild;
10669         child->rchild = splaytree;
10670       }
10671       child->lchild = grandchild->rchild;
10672       grandchild->rchild = child;
10673     }
10674     return grandchild;
10675   } else {
10676     lefttree = splay(m, splaytree->lchild, searchpoint, searchtri);
10677     righttree = splay(m, splaytree->rchild, searchpoint, searchtri);
10678 
10679     pooldealloc(&m->splaynodes, (VOID *) splaytree);
10680     if (lefttree == (struct splaynode *) NULL) {
10681       return righttree;
10682     } else if (righttree == (struct splaynode *) NULL) {
10683       return lefttree;
10684     } else if (lefttree->rchild == (struct splaynode *) NULL) {
10685       lefttree->rchild = righttree->lchild;
10686       righttree->lchild = lefttree;
10687       return righttree;
10688     } else if (righttree->lchild == (struct splaynode *) NULL) {
10689       righttree->lchild = lefttree->rchild;
10690       lefttree->rchild = righttree;
10691       return lefttree;
10692     } else {
10693 /*      printf("Holy Toledo!!!\n"); */
10694       leftright = lefttree->rchild;
10695       while (leftright->rchild != (struct splaynode *) NULL) {
10696         leftright = leftright->rchild;
10697       }
10698       leftright->rchild = righttree;
10699       return lefttree;
10700     }
10701   }
10702 }
10703 
10704 #endif /* not REDUCED */
10705 
10706 #ifndef REDUCED
10707 
10708 #ifdef ANSI_DECLARATORS
10709 struct splaynode *splayinsert(struct mesh *m, struct splaynode *splayroot,
10710                               struct otri *newkey, vertex searchpoint)
10711 #else /* not ANSI_DECLARATORS */
10712 struct splaynode *splayinsert(m, splayroot, newkey, searchpoint)
10713 struct mesh *m;
10714 struct splaynode *splayroot;
10715 struct otri *newkey;
10716 vertex searchpoint;
10717 #endif /* not ANSI_DECLARATORS */
10718 
10719 {
10720   struct splaynode *newsplaynode;
10721 
10722   newsplaynode = (struct splaynode *) poolalloc(&m->splaynodes);
10723   otricopy(*newkey, newsplaynode->keyedge);
10724   dest(*newkey, newsplaynode->keydest);
10725   if (splayroot == (struct splaynode *) NULL) {
10726     newsplaynode->lchild = (struct splaynode *) NULL;
10727     newsplaynode->rchild = (struct splaynode *) NULL;
10728   } else if (rightofhyperbola(m, &splayroot->keyedge, searchpoint)) {
10729     newsplaynode->lchild = splayroot;
10730     newsplaynode->rchild = splayroot->rchild;
10731     splayroot->rchild = (struct splaynode *) NULL;
10732   } else {
10733     newsplaynode->lchild = splayroot->lchild;
10734     newsplaynode->rchild = splayroot;
10735     splayroot->lchild = (struct splaynode *) NULL;
10736   }
10737   return newsplaynode;
10738 }
10739 
10740 #endif /* not REDUCED */
10741 
10742 #ifndef REDUCED
10743 
10744 #ifdef ANSI_DECLARATORS
10745 struct splaynode *circletopinsert(struct mesh *m, struct behavior *b,
10746                                   struct splaynode *splayroot,
10747                                   struct otri *newkey,
10748                                   vertex pa, vertex pb, vertex pc, REAL topy)
10749 #else /* not ANSI_DECLARATORS */
10750 struct splaynode *circletopinsert(m, b, splayroot, newkey, pa, pb, pc, topy)
10751 struct mesh *m;
10752 struct behavior *b;
10753 struct splaynode *splayroot;
10754 struct otri *newkey;
10755 vertex pa;
10756 vertex pb;
10757 vertex pc;
10758 REAL topy;
10759 #endif /* not ANSI_DECLARATORS */
10760 
10761 {
10762   REAL ccwabc;
10763   REAL xac, yac, xbc, ybc;
10764   REAL aclen2, bclen2;
10765   REAL searchpoint[2];
10766   struct otri dummytri;
10767 
10768   ccwabc = counterclockwise(m, b, pa, pb, pc);
10769   xac = pa[0] - pc[0];
10770   yac = pa[1] - pc[1];
10771   xbc = pb[0] - pc[0];
10772   ybc = pb[1] - pc[1];
10773   aclen2 = xac * xac + yac * yac;
10774   bclen2 = xbc * xbc + ybc * ybc;
10775   searchpoint[0] = pc[0] - (yac * bclen2 - ybc * aclen2) / (2.0 * ccwabc);
10776   searchpoint[1] = topy;
10777   return splayinsert(m, splay(m, splayroot, (vertex) searchpoint, &dummytri),
10778                      newkey, (vertex) searchpoint);
10779 }
10780 
10781 #endif /* not REDUCED */
10782 
10783 #ifndef REDUCED
10784 
10785 #ifdef ANSI_DECLARATORS
10786 struct splaynode *frontlocate(struct mesh *m, struct splaynode *splayroot,
10787                               struct otri *bottommost, vertex searchvertex,
10788                               struct otri *searchtri, int *farright)
10789 #else /* not ANSI_DECLARATORS */
10790 struct splaynode *frontlocate(m, splayroot, bottommost, searchvertex,
10791                               searchtri, farright)
10792 struct mesh *m;
10793 struct splaynode *splayroot;
10794 struct otri *bottommost;
10795 vertex searchvertex;
10796 struct otri *searchtri;
10797 int *farright;
10798 #endif /* not ANSI_DECLARATORS */
10799 
10800 {
10801   int farrightflag;
10802   triangle ptr;                       /* Temporary variable used by onext(). */
10803 
10804   otricopy(*bottommost, *searchtri);
10805   splayroot = splay(m, splayroot, searchvertex, searchtri);
10806 
10807   farrightflag = 0;
10808   while (!farrightflag && rightofhyperbola(m, searchtri, searchvertex)) {
10809     onextself(*searchtri);
10810     farrightflag = otriequal(*searchtri, *bottommost);
10811   }
10812   *farright = farrightflag;
10813   return splayroot;
10814 }
10815 
10816 #endif /* not REDUCED */
10817 
10818 #ifndef REDUCED
10819 
10820 #ifdef ANSI_DECLARATORS
10821 static LONG sweeplinedelaunay(struct mesh *m, struct behavior *b)
10822 #else /* not ANSI_DECLARATORS */
10823 static LONG sweeplinedelaunay(m, b)
10824 struct mesh *m;
10825 struct behavior *b;
10826 #endif /* not ANSI_DECLARATORS */
10827 
10828 {
10829   struct event **eventheap;
10830   struct event *events;
10831   struct event *freeevents;
10832   struct event *nextevent;
10833   struct event *newevent;
10834   struct splaynode *splayroot;
10835   struct otri bottommost;
10836   struct otri searchtri;
10837   struct otri fliptri;
10838   struct otri lefttri, righttri, farlefttri, farrighttri;
10839   struct otri inserttri;
10840   vertex firstvertex, secondvertex;
10841   vertex nextvertex, lastvertex;
10842   vertex connectvertex;
10843   vertex leftvertex, midvertex, rightvertex;
10844   REAL lefttest, righttest;
10845   int heapsize;
10846   int check4events, farrightflag;
10847   triangle ptr;   /* Temporary variable used by sym(), onext(), and oprev(). */
10848 
10849   poolinit(&m->splaynodes, sizeof(struct splaynode), SPLAYNODEPERBLOCK,
10850            SPLAYNODEPERBLOCK, 0);
10851   splayroot = (struct splaynode *) NULL;
10852 
10853   if (b->verbose) {
10854     printf("  Placing vertices in event heap.\n");
10855   }
10856   createeventheap(m, &eventheap, &events, &freeevents);
10857   heapsize = m->invertices;
10858 
10859   if (b->verbose) {
10860     printf("  Forming triangulation.\n");
10861   }
10862   maketriangle(m, b, &lefttri);
10863   maketriangle(m, b, &righttri);
10864   bond(lefttri, righttri);
10865   lnextself(lefttri);
10866   lprevself(righttri);
10867   bond(lefttri, righttri);
10868   lnextself(lefttri);
10869   lprevself(righttri);
10870   bond(lefttri, righttri);
10871   firstvertex = (vertex) eventheap[0]->eventptr;
10872   eventheap[0]->eventptr = (VOID *) freeevents;
10873   freeevents = eventheap[0];
10874   eventheapdelete(eventheap, heapsize, 0);
10875   heapsize--;
10876   do {
10877     if (heapsize == 0) {
10878       printf("Error:  Input vertices are all identical.\n");
10879       triexit(1);
10880     }
10881     secondvertex = (vertex) eventheap[0]->eventptr;
10882     eventheap[0]->eventptr = (VOID *) freeevents;
10883     freeevents = eventheap[0];
10884     eventheapdelete(eventheap, heapsize, 0);
10885     heapsize--;
10886     if ((firstvertex[0] == secondvertex[0]) &&
10887         (firstvertex[1] == secondvertex[1])) {
10888       if (!b->quiet) {
10889         printf(
10890 "Warning:  A duplicate vertex at (%.12g, %.12g) appeared and was ignored.\n",
10891                secondvertex[0], secondvertex[1]);
10892       }
10893       setvertextype(secondvertex, UNDEADVERTEX);
10894       m->undeads++;
10895     }
10896   } while ((firstvertex[0] == secondvertex[0]) &&
10897            (firstvertex[1] == secondvertex[1]));
10898   setorg(lefttri, firstvertex);
10899   setdest(lefttri, secondvertex);
10900   setorg(righttri, secondvertex);
10901   setdest(righttri, firstvertex);
10902   lprev(lefttri, bottommost);
10903   lastvertex = secondvertex;
10904   while (heapsize > 0) {
10905     nextevent = eventheap[0];
10906     eventheapdelete(eventheap, heapsize, 0);
10907     heapsize--;
10908     check4events = 1;
10909     if (nextevent->xkey < m->xmin) {
10910       decode(nextevent->eventptr, fliptri);
10911       oprev(fliptri, farlefttri);
10912       check4deadevent(&farlefttri, &freeevents, eventheap, &heapsize);
10913       onext(fliptri, farrighttri);
10914       check4deadevent(&farrighttri, &freeevents, eventheap, &heapsize);
10915 
10916       if (otriequal(farlefttri, bottommost)) {
10917         lprev(fliptri, bottommost);
10918       }
10919       flip(m, b, &fliptri);
10920       setapex(fliptri, NULL);
10921       lprev(fliptri, lefttri);
10922       lnext(fliptri, righttri);
10923       sym(lefttri, farlefttri);
10924 
10925       if (randomnation(SAMPLERATE) == 0) {
10926         symself(fliptri);
10927         dest(fliptri, leftvertex);
10928         apex(fliptri, midvertex);
10929         org(fliptri, rightvertex);
10930         splayroot = circletopinsert(m, b, splayroot, &lefttri, leftvertex,
10931                                     midvertex, rightvertex, nextevent->ykey);
10932       }
10933     } else {
10934       nextvertex = (vertex) nextevent->eventptr;
10935       if ((nextvertex[0] == lastvertex[0]) &&
10936           (nextvertex[1] == lastvertex[1])) {
10937         if (!b->quiet) {
10938           printf(
10939 "Warning:  A duplicate vertex at (%.12g, %.12g) appeared and was ignored.\n",
10940                  nextvertex[0], nextvertex[1]);
10941         }
10942         setvertextype(nextvertex, UNDEADVERTEX);
10943         m->undeads++;
10944         check4events = 0;
10945       } else {
10946         lastvertex = nextvertex;
10947 
10948         splayroot = frontlocate(m, splayroot, &bottommost, nextvertex,
10949                                 &searchtri, &farrightflag);
10950 /*
10951         otricopy(bottommost, searchtri);
10952         farrightflag = 0;
10953         while (!farrightflag && rightofhyperbola(m, &searchtri, nextvertex)) {
10954           onextself(searchtri);
10955           farrightflag = otriequal(searchtri, bottommost);
10956         }
10957 */
10958 
10959         check4deadevent(&searchtri, &freeevents, eventheap, &heapsize);
10960 
10961         otricopy(searchtri, farrighttri);
10962         sym(searchtri, farlefttri);
10963         maketriangle(m, b, &lefttri);
10964         maketriangle(m, b, &righttri);
10965         dest(farrighttri, connectvertex);
10966         setorg(lefttri, connectvertex);
10967         setdest(lefttri, nextvertex);
10968         setorg(righttri, nextvertex);
10969         setdest(righttri, connectvertex);
10970         bond(lefttri, righttri);
10971         lnextself(lefttri);
10972         lprevself(righttri);
10973         bond(lefttri, righttri);
10974         lnextself(lefttri);
10975         lprevself(righttri);
10976         bond(lefttri, farlefttri);
10977         bond(righttri, farrighttri);
10978         if (!farrightflag && otriequal(farrighttri, bottommost)) {
10979           otricopy(lefttri, bottommost);
10980         }
10981 
10982         if (randomnation(SAMPLERATE) == 0) {
10983           splayroot = splayinsert(m, splayroot, &lefttri, nextvertex);
10984         } else if (randomnation(SAMPLERATE) == 0) {
10985           lnext(righttri, inserttri);
10986           splayroot = splayinsert(m, splayroot, &inserttri, nextvertex);
10987         }
10988       }
10989     }
10990     nextevent->eventptr = (VOID *) freeevents;
10991     freeevents = nextevent;
10992 
10993     if (check4events) {
10994       apex(farlefttri, leftvertex);
10995       dest(lefttri, midvertex);
10996       apex(lefttri, rightvertex);
10997       lefttest = counterclockwise(m, b, leftvertex, midvertex, rightvertex);
10998       if (lefttest > 0.0) {
10999         newevent = freeevents;
11000         freeevents = (struct event *) freeevents->eventptr;
11001         newevent->xkey = m->xminextreme;
11002         newevent->ykey = circletop(m, leftvertex, midvertex, rightvertex,
11003                                    lefttest);
11004         newevent->eventptr = (VOID *) encode(lefttri);
11005         eventheapinsert(eventheap, heapsize, newevent);
11006         heapsize++;
11007         setorg(lefttri, newevent);
11008       }
11009       apex(righttri, leftvertex);
11010       org(righttri, midvertex);
11011       apex(farrighttri, rightvertex);
11012       righttest = counterclockwise(m, b, leftvertex, midvertex, rightvertex);
11013       if (righttest > 0.0) {
11014         newevent = freeevents;
11015         freeevents = (struct event *) freeevents->eventptr;
11016         newevent->xkey = m->xminextreme;
11017         newevent->ykey = circletop(m, leftvertex, midvertex, rightvertex,
11018                                    righttest);
11019         newevent->eventptr = (VOID *) encode(farrighttri);
11020         eventheapinsert(eventheap, heapsize, newevent);
11021         heapsize++;
11022         setorg(farrighttri, newevent);
11023       }
11024     }
11025   }
11026 
11027   pooldeinit(&m->splaynodes);
11028   lprevself(bottommost);
11029   return removeghosts(m, b, &bottommost);
11030 }
11031 
11032 #endif /* not REDUCED */
11033 
11034 /**                                                                         **/
11035 /**                                                                         **/
11036 /********* Sweepline Delaunay triangulation ends here                *********/
11037 
11038 /********* General mesh construction routines begin here             *********/
11039 /**                                                                         **/
11040 /**                                                                         **/
11041 
11042 /*****************************************************************************/
11043 /*                                                                           */
11044 /*  delaunay()   Form a Delaunay triangulation.                              */
11045 /*                                                                           */
11046 /*****************************************************************************/
11047 
11048 #ifdef ANSI_DECLARATORS
11049 static LONG delaunay(struct mesh *m, struct behavior *b)
11050 #else /* not ANSI_DECLARATORS */
11051 static LONG delaunay(m, b)
11052 struct mesh *m;
11053 struct behavior *b;
11054 #endif /* not ANSI_DECLARATORS */
11055 
11056 {
11057   LONG hulledges;
11058 
11059   m->eextras = 0;
11060   initializetrisubpools(m, b);
11061 
11062 #ifdef REDUCED
11063   if (!b->quiet) {
11064     printf(
11065       "Constructing Delaunay triangulation by divide-and-conquer method.\n");
11066   }
11067   hulledges = divconqdelaunay(m, b);
11068 #else /* not REDUCED */
11069   if (!b->quiet) {
11070     printf("Constructing Delaunay triangulation ");
11071     if (b->incremental) {
11072       printf("by incremental method.\n");
11073     } else if (b->sweepline) {
11074       printf("by sweepline method.\n");
11075     } else {
11076       printf("by divide-and-conquer method.\n");
11077     }
11078   }
11079   if (b->incremental) {
11080     hulledges = incrementaldelaunay(m, b);
11081   } else if (b->sweepline) {
11082     hulledges = sweeplinedelaunay(m, b);
11083   } else {
11084     hulledges = divconqdelaunay(m, b);
11085   }
11086 #endif /* not REDUCED */
11087 
11088   if (m->triangles.items == 0) {
11089     /* The input vertices were all collinear, so there are no triangles. */
11090     return 0l;
11091   } else {
11092     return hulledges;
11093   }
11094 }
11095 
11096 /*****************************************************************************/
11097 /*                                                                           */
11098 /*  reconstruct()   Reconstruct a triangulation from its .ele (and possibly  */
11099 /*                  .poly) file.  Used when the -r switch is used.           */
11100 /*                                                                           */
11101 /*  Reads an .ele file and reconstructs the original mesh.  If the -p switch */
11102 /*  is used, this procedure will also read a .poly file and reconstruct the  */
11103 /*  subsegments of the original mesh.  If the -a switch is used, this        */
11104 /*  procedure will also read an .area file and set a maximum area constraint */
11105 /*  on each triangle.                                                        */
11106 /*                                                                           */
11107 /*  Vertices that are not corners of triangles, such as nodes on edges of    */
11108 /*  subparametric elements, are discarded.                                   */
11109 /*                                                                           */
11110 /*  This routine finds the adjacencies between triangles (and subsegments)   */
11111 /*  by forming one stack of triangles for each vertex.  Each triangle is on  */
11112 /*  three different stacks simultaneously.  Each triangle's subsegment       */
11113 /*  pointers are used to link the items in each stack.  This memory-saving   */
11114 /*  feature makes the code harder to read.  The most important thing to keep */
11115 /*  in mind is that each triangle is removed from a stack precisely when     */
11116 /*  the corresponding pointer is adjusted to refer to a subsegment rather    */
11117 /*  than the next triangle of the stack.                                     */
11118 /*                                                                           */
11119 /*****************************************************************************/
11120 
11121 #ifndef CDT_ONLY
11122 
11123 #ifdef TRILIBRARY
11124 
11125 #ifdef ANSI_DECLARATORS
11126 static int reconstruct(struct mesh *m, struct behavior *b, int *trianglelist,
11127                 REAL *triangleattriblist, REAL *trianglearealist,
11128                 int elements, int corners, int attribs,
11129                 int *segmentlist,int *segmentmarkerlist, int numberofsegments)
11130 #else /* not ANSI_DECLARATORS */
11131 static int reconstruct(m, b, trianglelist, triangleattriblist, trianglearealist,
11132                 elements, corners, attribs, segmentlist, segmentmarkerlist,
11133                 numberofsegments)
11134 struct mesh *m;
11135 struct behavior *b;
11136 int *trianglelist;
11137 REAL *triangleattriblist;
11138 REAL *trianglearealist;
11139 int elements;
11140 int corners;
11141 int attribs;
11142 int *segmentlist;
11143 int *segmentmarkerlist;
11144 int numberofsegments;
11145 #endif /* not ANSI_DECLARATORS */
11146 
11147 #else /* not TRILIBRARY */
11148 
11149 #ifdef ANSI_DECLARATORS
11150 static LONG reconstruct(struct mesh *m, struct behavior *b, char *elefilename,
11151                  char *areafilename, char *polyfilename, FILE *polyfile)
11152 #else /* not ANSI_DECLARATORS */
11153 static LONG reconstruct(m, b, elefilename, areafilename, polyfilename, polyfile)
11154 struct mesh *m;
11155 struct behavior *b;
11156 char *elefilename;
11157 char *areafilename;
11158 char *polyfilename;
11159 FILE *polyfile;
11160 #endif /* not ANSI_DECLARATORS */
11161 
11162 #endif /* not TRILIBRARY */
11163 
11164 {
11165 #ifdef TRILIBRARY
11166   int vertexindex;
11167   int attribindex;
11168 #else /* not TRILIBRARY */
11169   FILE *elefile;
11170   FILE *areafile;
11171   char inputline[INPUTLINESIZE];
11172   char *stringptr;
11173   int areaelements;
11174 #endif /* not TRILIBRARY */
11175   struct otri triangleloop;
11176   struct otri triangleleft;
11177   struct otri checktri;
11178   struct otri checkleft;
11179   struct otri checkneighbor;
11180   struct osub subsegloop;
11181   triangle *vertexarray;
11182   triangle *prevlink;
11183   triangle nexttri;
11184   vertex tdest, tapex;
11185   vertex checkdest, checkapex;
11186   vertex shorg;
11187   vertex killvertex;
11188   vertex segmentorg, segmentdest;
11189   REAL area;
11190   int corner[3];
11191   int end[2];
11192   int killvertexindex;
11193   int incorners;
11194   int segmentmarkers;
11195   int boundmarker;
11196   int aroundvertex;
11197   LONG hullsize;
11198   int notfound;
11199   LONG elementnumber, segmentnumber;
11200   int i, j;
11201   triangle ptr;                         /* Temporary variable used by sym(). */
11202 
11203 #ifdef TRILIBRARY
11204   m->inelements = elements;
11205   incorners = corners;
11206   if (incorners < 3) {
11207     printf("Error:  Triangles must have at least 3 vertices.\n");
11208     triexit(1);
11209   }
11210   m->eextras = attribs;
11211 #else /* not TRILIBRARY */
11212   /* Read the triangles from an .ele file. */
11213   if (!b->quiet) {
11214     printf("Opening %s.\n", elefilename);
11215   }
11216   elefile = fopen(elefilename, "r");
11217   if (elefile == (FILE *) NULL) {
11218     printf("Error:  Cannot access file %s.\n", elefilename);
11219     triexit(1);
11220   }
11221   /* Read number of triangles, number of vertices per triangle, and */
11222   /*   number of triangle attributes from .ele file.                */
11223   stringptr = readline(inputline, elefile, elefilename);
11224   m->inelements = (int) strtol(stringptr, &stringptr, 0);
11225   stringptr = findfield(stringptr);
11226   if (*stringptr == '\0') {
11227     incorners = 3;
11228   } else {
11229     incorners = (int) strtol(stringptr, &stringptr, 0);
11230     if (incorners < 3) {
11231       printf("Error:  Triangles in %s must have at least 3 vertices.\n",
11232              elefilename);
11233       triexit(1);
11234     }
11235   }
11236   stringptr = findfield(stringptr);
11237   if (*stringptr == '\0') {
11238     m->eextras = 0;
11239   } else {
11240     m->eextras = (int) strtol(stringptr, &stringptr, 0);
11241   }
11242 #endif /* not TRILIBRARY */
11243 
11244   initializetrisubpools(m, b);
11245 
11246   /* Create the triangles. */
11247   for (elementnumber = 1; elementnumber <= m->inelements; elementnumber++) {
11248     maketriangle(m, b, &triangleloop);
11249     /* Mark the triangle as living. */
11250     triangleloop.tri[3] = (triangle) triangleloop.tri;
11251   }
11252 
11253   segmentmarkers = 0;
11254   if (b->poly) {
11255 #ifdef TRILIBRARY
11256     m->insegments = numberofsegments;
11257     segmentmarkers = segmentmarkerlist != (int *) NULL;
11258 #else /* not TRILIBRARY */
11259     /* Read number of segments and number of segment */
11260     /*   boundary markers from .poly file.           */
11261     stringptr = readline(inputline, polyfile, b->inpolyfilename);
11262     m->insegments = (int) strtol(stringptr, &stringptr, 0);
11263     stringptr = findfield(stringptr);
11264     if (*stringptr != '\0') {
11265       segmentmarkers = (int) strtol(stringptr, &stringptr, 0);
11266     }
11267 #endif /* not TRILIBRARY */
11268 
11269     /* Create the subsegments. */
11270     for (segmentnumber = 1; segmentnumber <= m->insegments; segmentnumber++) {
11271       makesubseg(m, &subsegloop);
11272       /* Mark the subsegment as living. */
11273       subsegloop.ss[2] = (subseg) subsegloop.ss;
11274     }
11275   }
11276 
11277 #ifdef TRILIBRARY
11278   vertexindex = 0;
11279   attribindex = 0;
11280 #else /* not TRILIBRARY */
11281   if (b->vararea) {
11282     /* Open an .area file, check for consistency with the .ele file. */
11283     if (!b->quiet) {
11284       printf("Opening %s.\n", areafilename);
11285     }
11286     areafile = fopen(areafilename, "r");
11287     if (areafile == (FILE *) NULL) {
11288       printf("Error:  Cannot access file %s.\n", areafilename);
11289       triexit(1);
11290     }
11291     stringptr = readline(inputline, areafile, areafilename);
11292     areaelements = (int) strtol(stringptr, &stringptr, 0);
11293     if (areaelements != m->inelements) {
11294       printf("Error:  %s and %s disagree on number of triangles.\n",
11295              elefilename, areafilename);
11296       triexit(1);
11297     }
11298   }
11299 #endif /* not TRILIBRARY */
11300 
11301   if (!b->quiet) {
11302     printf("Reconstructing mesh.\n");
11303   }
11304   /* Allocate a temporary array that maps each vertex to some adjacent */
11305   /*   triangle.  I took care to allocate all the permanent memory for */
11306   /*   triangles and subsegments first.                                */
11307   vertexarray = (triangle *) trimalloc(m->vertices.items *
11308                                        (int) sizeof(triangle));
11309   /* Each vertex is initially unrepresented. */
11310   for (i = 0; i < m->vertices.items; i++) {
11311     vertexarray[i] = (triangle) m->dummytri;
11312   }
11313 
11314   if (b->verbose) {
11315     printf("  Assembling triangles.\n");
11316   }
11317   /* Read the triangles from the .ele file, and link */
11318   /*   together those that share an edge.            */
11319   traversalinit(&m->triangles);
11320   triangleloop.tri = triangletraverse(m);
11321   elementnumber = b->firstnumber;
11322   while (triangleloop.tri != (triangle *) NULL) {
11323 #ifdef TRILIBRARY
11324     /* Copy the triangle's three corners. */
11325     for (j = 0; j < 3; j++) {
11326       corner[j] = trianglelist[vertexindex++];
11327       if ((corner[j] < b->firstnumber) ||
11328           (corner[j] >= b->firstnumber + m->invertices)) {
11329         printf("Error:  Triangle %ld has an invalid vertex index.\n",
11330                elementnumber);
11331         triexit(1);
11332       }
11333     }
11334 #else /* not TRILIBRARY */
11335     /* Read triangle number and the triangle's three corners. */
11336     stringptr = readline(inputline, elefile, elefilename);
11337     for (j = 0; j < 3; j++) {
11338       stringptr = findfield(stringptr);
11339       if (*stringptr == '\0') {
11340         printf("Error:  Triangle %ld is missing vertex %d in %s.\n",
11341                elementnumber, j + 1, elefilename);
11342         triexit(1);
11343       } else {
11344         corner[j] = (int) strtol(stringptr, &stringptr, 0);
11345         if ((corner[j] < b->firstnumber) ||
11346             (corner[j] >= b->firstnumber + m->invertices)) {
11347           printf("Error:  Triangle %ld has an invalid vertex index.\n",
11348                  elementnumber);
11349           triexit(1);
11350         }
11351       }
11352     }
11353 #endif /* not TRILIBRARY */
11354 
11355     /* Find out about (and throw away) extra nodes. */
11356     for (j = 3; j < incorners; j++) {
11357 #ifdef TRILIBRARY
11358       killvertexindex = trianglelist[vertexindex++];
11359 #else /* not TRILIBRARY */
11360       stringptr = findfield(stringptr);
11361       if (*stringptr != '\0') {
11362         killvertexindex = (int) strtol(stringptr, &stringptr, 0);
11363 #endif /* not TRILIBRARY */
11364         if ((killvertexindex >= b->firstnumber) &&
11365             (killvertexindex < b->firstnumber + m->invertices)) {
11366           /* Delete the non-corner vertex if it's not already deleted. */
11367           killvertex = getvertex(m, b, killvertexindex);
11368           if (vertextype(killvertex) != DEADVERTEX) {
11369             vertexdealloc(m, killvertex);
11370           }
11371         }
11372 #ifndef TRILIBRARY
11373       }
11374 #endif /* not TRILIBRARY */
11375     }
11376 
11377     /* Read the triangle's attributes. */
11378     for (j = 0; j < m->eextras; j++) {
11379 #ifdef TRILIBRARY
11380       setelemattribute(triangleloop, j, triangleattriblist[attribindex++]);
11381 #else /* not TRILIBRARY */
11382       stringptr = findfield(stringptr);
11383       if (*stringptr == '\0') {
11384         setelemattribute(triangleloop, j, 0);
11385       } else {
11386         setelemattribute(triangleloop, j,
11387                          (REAL) strtod(stringptr, &stringptr));
11388       }
11389 #endif /* not TRILIBRARY */
11390     }
11391 
11392     if (b->vararea) {
11393 #ifdef TRILIBRARY
11394       area = trianglearealist[elementnumber - b->firstnumber];
11395 #else /* not TRILIBRARY */
11396       /* Read an area constraint from the .area file. */
11397       stringptr = readline(inputline, areafile, areafilename);
11398       stringptr = findfield(stringptr);
11399       if (*stringptr == '\0') {
11400         area = -1.0;                      /* No constraint on this triangle. */
11401       } else {
11402         area = (REAL) strtod(stringptr, &stringptr);
11403       }
11404 #endif /* not TRILIBRARY */
11405       setareabound(triangleloop, area);
11406     }
11407 
11408     /* Set the triangle's vertices. */
11409     triangleloop.orient = 0;
11410     setorg(triangleloop, getvertex(m, b, corner[0]));
11411     setdest(triangleloop, getvertex(m, b, corner[1]));
11412     setapex(triangleloop, getvertex(m, b, corner[2]));
11413     /* Try linking the triangle to others that share these vertices. */
11414     for (triangleloop.orient = 0; triangleloop.orient < 3;
11415          triangleloop.orient++) {
11416       /* Take the number for the origin of triangleloop. */
11417       aroundvertex = corner[triangleloop.orient];
11418       /* Look for other triangles having this vertex. */
11419       nexttri = vertexarray[aroundvertex - b->firstnumber];
11420       /* Link the current triangle to the next one in the stack. */
11421       triangleloop.tri[6 + triangleloop.orient] = nexttri;
11422       /* Push the current triangle onto the stack. */
11423       vertexarray[aroundvertex - b->firstnumber] = encode(triangleloop);
11424       decode(nexttri, checktri);
11425       if (checktri.tri != m->dummytri) {
11426         dest(triangleloop, tdest);
11427         apex(triangleloop, tapex);
11428         /* Look for other triangles that share an edge. */
11429         do {
11430           dest(checktri, checkdest);
11431           apex(checktri, checkapex);
11432           if (tapex == checkdest) {
11433             /* The two triangles share an edge; bond them together. */
11434             lprev(triangleloop, triangleleft);
11435             bond(triangleleft, checktri);
11436           }
11437           if (tdest == checkapex) {
11438             /* The two triangles share an edge; bond them together. */
11439             lprev(checktri, checkleft);
11440             bond(triangleloop, checkleft);
11441           }
11442           /* Find the next triangle in the stack. */
11443           nexttri = checktri.tri[6 + checktri.orient];
11444           decode(nexttri, checktri);
11445         } while (checktri.tri != m->dummytri);
11446       }
11447     }
11448     triangleloop.tri = triangletraverse(m);
11449     elementnumber++;
11450   }
11451 
11452 #ifdef TRILIBRARY
11453   vertexindex = 0;
11454 #else /* not TRILIBRARY */
11455   fclose(elefile);
11456   if (b->vararea) {
11457     fclose(areafile);
11458   }
11459 #endif /* not TRILIBRARY */
11460 
11461   hullsize = 0;                      /* Prepare to count the boundary edges. */
11462   if (b->poly) {
11463     if (b->verbose) {
11464       printf("  Marking segments in triangulation.\n");
11465     }
11466     /* Read the segments from the .poly file, and link them */
11467     /*   to their neighboring triangles.                    */
11468     boundmarker = 0;
11469     traversalinit(&m->subsegs);
11470     subsegloop.ss = subsegtraverse(m);
11471     segmentnumber = b->firstnumber;
11472     while (subsegloop.ss != (subseg *) NULL) {
11473 #ifdef TRILIBRARY
11474       end[0] = segmentlist[vertexindex++];
11475       end[1] = segmentlist[vertexindex++];
11476       if (segmentmarkers) {
11477         boundmarker = segmentmarkerlist[segmentnumber - b->firstnumber];
11478       }
11479 #else /* not TRILIBRARY */
11480       /* Read the endpoints of each segment, and possibly a boundary marker. */
11481       stringptr = readline(inputline, polyfile, b->inpolyfilename);
11482       /* Skip the first (segment number) field. */
11483       stringptr = findfield(stringptr);
11484       if (*stringptr == '\0') {
11485         printf("Error:  Segment %ld has no endpoints in %s.\n", segmentnumber,
11486                polyfilename);
11487         triexit(1);
11488       } else {
11489         end[0] = (int) strtol(stringptr, &stringptr, 0);
11490       }
11491       stringptr = findfield(stringptr);
11492       if (*stringptr == '\0') {
11493         printf("Error:  Segment %ld is missing its second endpoint in %s.\n",
11494                segmentnumber, polyfilename);
11495         triexit(1);
11496       } else {
11497         end[1] = (int) strtol(stringptr, &stringptr, 0);
11498       }
11499       if (segmentmarkers) {
11500         stringptr = findfield(stringptr);
11501         if (*stringptr == '\0') {
11502           boundmarker = 0;
11503         } else {
11504           boundmarker = (int) strtol(stringptr, &stringptr, 0);
11505         }
11506       }
11507 #endif /* not TRILIBRARY */
11508       for (j = 0; j < 2; j++) {
11509         if ((end[j] < b->firstnumber) ||
11510             (end[j] >= b->firstnumber + m->invertices)) {
11511           printf("Error:  Segment %ld has an invalid vertex index.\n",
11512                  segmentnumber);
11513           triexit(1);
11514         }
11515       }
11516 
11517       /* set the subsegment's vertices. */
11518       subsegloop.ssorient = 0;
11519       segmentorg = getvertex(m, b, end[0]);
11520       segmentdest = getvertex(m, b, end[1]);
11521       setsorg(subsegloop, segmentorg);
11522       setsdest(subsegloop, segmentdest);
11523       setsegorg(subsegloop, segmentorg);
11524       setsegdest(subsegloop, segmentdest);
11525       setmark(subsegloop, boundmarker);
11526       /* Try linking the subsegment to triangles that share these vertices. */
11527       for (subsegloop.ssorient = 0; subsegloop.ssorient < 2;
11528            subsegloop.ssorient++) {
11529         /* Take the number for the destination of subsegloop. */
11530         aroundvertex = end[1 - subsegloop.ssorient];
11531         /* Look for triangles having this vertex. */
11532         prevlink = &vertexarray[aroundvertex - b->firstnumber];
11533         nexttri = vertexarray[aroundvertex - b->firstnumber];
11534         decode(nexttri, checktri);
11535         sorg(subsegloop, shorg);
11536         notfound = 1;
11537         /* Look for triangles having this edge.  Note that I'm only       */
11538         /*   comparing each triangle's destination with the subsegment;   */
11539         /*   each triangle's apex is handled through a different vertex.  */
11540         /*   Because each triangle appears on three vertices' lists, each */
11541         /*   occurrence of a triangle on a list can (and does) represent  */
11542         /*   an edge.  In this way, most edges are represented twice, and */
11543         /*   every triangle-subsegment bond is represented once.          */
11544         while (notfound && (checktri.tri != m->dummytri)) {
11545           dest(checktri, checkdest);
11546           if (shorg == checkdest) {
11547             /* We have a match.  Remove this triangle from the list. */
11548             *prevlink = checktri.tri[6 + checktri.orient];
11549             /* Bond the subsegment to the triangle. */
11550             tsbond(checktri, subsegloop);
11551             /* Check if this is a boundary edge. */
11552             sym(checktri, checkneighbor);
11553             if (checkneighbor.tri == m->dummytri) {
11554               /* The next line doesn't insert a subsegment (because there's */
11555               /*   already one there), but it sets the boundary markers of  */
11556               /*   the existing subsegment and its vertices.                */
11557               insertsubseg(m, b, &checktri, 1);
11558               hullsize++;
11559             }
11560             notfound = 0;
11561           }
11562           /* Find the next triangle in the stack. */
11563           prevlink = &checktri.tri[6 + checktri.orient];
11564           nexttri = checktri.tri[6 + checktri.orient];
11565           decode(nexttri, checktri);
11566         }
11567       }
11568       subsegloop.ss = subsegtraverse(m);
11569       segmentnumber++;
11570     }
11571   }
11572 
11573   /* Mark the remaining edges as not being attached to any subsegment. */
11574   /* Also, count the (yet uncounted) boundary edges.                   */
11575   for (i = 0; i < m->vertices.items; i++) {
11576     /* Search the stack of triangles adjacent to a vertex. */
11577     nexttri = vertexarray[i];
11578     decode(nexttri, checktri);
11579     while (checktri.tri != m->dummytri) {
11580       /* Find the next triangle in the stack before this */
11581       /*   information gets overwritten.                 */
11582       nexttri = checktri.tri[6 + checktri.orient];
11583       /* No adjacent subsegment.  (This overwrites the stack info.) */
11584       tsdissolve(checktri);
11585       sym(checktri, checkneighbor);
11586       if (checkneighbor.tri == m->dummytri) {
11587         insertsubseg(m, b, &checktri, 1);
11588         hullsize++;
11589       }
11590       decode(nexttri, checktri);
11591     }
11592   }
11593 
11594   trifree((VOID *) vertexarray);
11595   return hullsize;
11596 }
11597 
11598 #endif /* not CDT_ONLY */
11599 
11600 /**                                                                         **/
11601 /**                                                                         **/
11602 /********* General mesh construction routines end here               *********/
11603 
11604 /********* Segment insertion begins here                             *********/
11605 /**                                                                         **/
11606 /**                                                                         **/
11607 
11608 /*****************************************************************************/
11609 /*                                                                           */
11610 /*  finddirection()   Find the first triangle on the path from one point     */
11611 /*                    to another.                                            */
11612 /*                                                                           */
11613 /*  Finds the triangle that intersects a line segment drawn from the         */
11614 /*  origin of `searchtri' to the point `searchpoint', and returns the result */
11615 /*  in `searchtri'.  The origin of `searchtri' does not change, even though  */
11616 /*  the triangle returned may differ from the one passed in.  This routine   */
11617 /*  is used to find the direction to move in to get from one point to        */
11618 /*  another.                                                                 */
11619 /*                                                                           */
11620 /*  The return value notes whether the destination or apex of the found      */
11621 /*  triangle is collinear with the two points in question.                   */
11622 /*                                                                           */
11623 /*****************************************************************************/
11624 
11625 #ifdef ANSI_DECLARATORS
11626 static enum finddirectionresult finddirection(struct mesh *m, struct behavior *b,
11627                                        struct otri *searchtri,
11628                                        vertex searchpoint)
11629 #else /* not ANSI_DECLARATORS */
11630 static enum finddirectionresult finddirection(m, b, searchtri, searchpoint)
11631 struct mesh *m;
11632 struct behavior *b;
11633 struct otri *searchtri;
11634 vertex searchpoint;
11635 #endif /* not ANSI_DECLARATORS */
11636 
11637 {
11638   struct otri checktri;
11639   vertex startvertex;
11640   vertex leftvertex, rightvertex;
11641   REAL leftccw, rightccw;
11642   int leftflag, rightflag;
11643   triangle ptr;           /* Temporary variable used by onext() and oprev(). */
11644 
11645   org(*searchtri, startvertex);
11646   dest(*searchtri, rightvertex);
11647   apex(*searchtri, leftvertex);
11648   /* Is `searchpoint' to the left? */
11649   leftccw = counterclockwise(m, b, searchpoint, startvertex, leftvertex);
11650   leftflag = leftccw > 0.0;
11651   /* Is `searchpoint' to the right? */
11652   rightccw = counterclockwise(m, b, startvertex, searchpoint, rightvertex);
11653   rightflag = rightccw > 0.0;
11654   if (leftflag && rightflag) {
11655     /* `searchtri' faces directly away from `searchpoint'.  We could go left */
11656     /*   or right.  Ask whether it's a triangle or a boundary on the left.   */
11657     onext(*searchtri, checktri);
11658     if (checktri.tri == m->dummytri) {
11659       leftflag = 0;
11660     } else {
11661       rightflag = 0;
11662     }
11663   }
11664   while (leftflag) {
11665     /* Turn left until satisfied. */
11666     onextself(*searchtri);
11667     if (searchtri->tri == m->dummytri) {
11668       printf("Internal error in finddirection():  Unable to find a\n");
11669       printf("  triangle leading from (%.12g, %.12g) to", startvertex[0],
11670              startvertex[1]);
11671       printf("  (%.12g, %.12g).\n", searchpoint[0], searchpoint[1]);
11672       internalerror();
11673     }
11674     apex(*searchtri, leftvertex);
11675     rightccw = leftccw;
11676     leftccw = counterclockwise(m, b, searchpoint, startvertex, leftvertex);
11677     leftflag = leftccw > 0.0;
11678   }
11679   while (rightflag) {
11680     /* Turn right until satisfied. */
11681     oprevself(*searchtri);
11682     if (searchtri->tri == m->dummytri) {
11683       printf("Internal error in finddirection():  Unable to find a\n");
11684       printf("  triangle leading from (%.12g, %.12g) to", startvertex[0],
11685              startvertex[1]);
11686       printf("  (%.12g, %.12g).\n", searchpoint[0], searchpoint[1]);
11687       internalerror();
11688     }
11689     dest(*searchtri, rightvertex);
11690     leftccw = rightccw;
11691     rightccw = counterclockwise(m, b, startvertex, searchpoint, rightvertex);
11692     rightflag = rightccw > 0.0;
11693   }
11694   if (leftccw == 0.0) {
11695     return LEFTCOLLINEAR;
11696   } else if (rightccw == 0.0) {
11697     return RIGHTCOLLINEAR;
11698   } else {
11699     return WITHIN;
11700   }
11701 }
11702 
11703 /*****************************************************************************/
11704 /*                                                                           */
11705 /*  segmentintersection()   Find the intersection of an existing segment     */
11706 /*                          and a segment that is being inserted.  Insert    */
11707 /*                          a vertex at the intersection, splitting an       */
11708 /*                          existing subsegment.                             */
11709 /*                                                                           */
11710 /*  The segment being inserted connects the apex of splittri to endpoint2.   */
11711 /*  splitsubseg is the subsegment being split, and MUST adjoin splittri.     */
11712 /*  Hence, endpoints of the subsegment being split are the origin and        */
11713 /*  destination of splittri.                                                 */
11714 /*                                                                           */
11715 /*  On completion, splittri is a handle having the newly inserted            */
11716 /*  intersection point as its origin, and endpoint1 as its destination.      */
11717 /*                                                                           */
11718 /*****************************************************************************/
11719 
11720 #ifdef ANSI_DECLARATORS
11721 static void segmentintersection(struct mesh *m, struct behavior *b,
11722                          struct otri *splittri, struct osub *splitsubseg,
11723                          vertex endpoint2)
11724 #else /* not ANSI_DECLARATORS */
11725 static void segmentintersection(m, b, splittri, splitsubseg, endpoint2)
11726 struct mesh *m;
11727 struct behavior *b;
11728 struct otri *splittri;
11729 struct osub *splitsubseg;
11730 vertex endpoint2;
11731 #endif /* not ANSI_DECLARATORS */
11732 
11733 {
11734   struct osub opposubseg;
11735   vertex endpoint1;
11736   vertex torg, tdest;
11737   vertex leftvertex, rightvertex;
11738   vertex newvertex;
11739   enum insertvertexresult success;
11740   REAL ex, ey;
11741   REAL tx, ty;
11742   REAL etx, ety;
11743   REAL split, denom;
11744   int i;
11745   triangle ptr;                       /* Temporary variable used by onext(). */
11746   subseg sptr;                        /* Temporary variable used by snext(). */
11747 
11748   /* Find the other three segment endpoints. */
11749   apex(*splittri, endpoint1);
11750   org(*splittri, torg);
11751   dest(*splittri, tdest);
11752   /* Segment intersection formulae; see the Antonio reference. */
11753   tx = tdest[0] - torg[0];
11754   ty = tdest[1] - torg[1];
11755   ex = endpoint2[0] - endpoint1[0];
11756   ey = endpoint2[1] - endpoint1[1];
11757   etx = torg[0] - endpoint2[0];
11758   ety = torg[1] - endpoint2[1];
11759   denom = ty * ex - tx * ey;
11760   if (denom == 0.0) {
11761     printf("Internal error in segmentintersection():");
11762     printf("  Attempt to find intersection of parallel segments.\n");
11763     internalerror();
11764   }
11765   split = (ey * etx - ex * ety) / denom;
11766   /* Create the new vertex. */
11767   newvertex = (vertex) poolalloc(&m->vertices);
11768   /* Interpolate its coordinate and attributes. */
11769   for (i = 0; i < 2 + m->nextras; i++) {
11770     newvertex[i] = torg[i] + split * (tdest[i] - torg[i]);
11771   }
11772   setvertexmark(newvertex, mark(*splitsubseg));
11773   setvertextype(newvertex, INPUTVERTEX);
11774   if (b->verbose > 1) {
11775     printf(
11776   "  Splitting subsegment (%.12g, %.12g) (%.12g, %.12g) at (%.12g, %.12g).\n",
11777            torg[0], torg[1], tdest[0], tdest[1], newvertex[0], newvertex[1]);
11778   }
11779   /* Insert the intersection vertex.  This should always succeed. */
11780   success = insertvertex(m, b, newvertex, splittri, splitsubseg, 0, 0);
11781   if (success != SUCCESSFULVERTEX) {
11782     printf("Internal error in segmentintersection():\n");
11783     printf("  Failure to split a segment.\n");
11784     internalerror();
11785   }
11786   /* Record a triangle whose origin is the new vertex. */
11787   setvertex2tri(newvertex, encode(*splittri));
11788   if (m->steinerleft > 0) {
11789     m->steinerleft--;
11790   }
11791 
11792   /* Divide the segment into two, and correct the segment endpoints. */
11793   ssymself(*splitsubseg);
11794   spivot(*splitsubseg, opposubseg);
11795   sdissolve(*splitsubseg);
11796   sdissolve(opposubseg);
11797   do {
11798     setsegorg(*splitsubseg, newvertex);
11799     snextself(*splitsubseg);
11800   } while (splitsubseg->ss != m->dummysub);
11801   do {
11802     setsegorg(opposubseg, newvertex);
11803     snextself(opposubseg);
11804   } while (opposubseg.ss != m->dummysub);
11805 
11806   /* Inserting the vertex may have caused edge flips.  We wish to rediscover */
11807   /*   the edge connecting endpoint1 to the new intersection vertex.         */
11808   dest(*splittri, rightvertex);
11809   apex(*splittri, leftvertex);
11810   if ((leftvertex[0] == endpoint1[0]) && (leftvertex[1] == endpoint1[1])) {
11811     onextself(*splittri);
11812   } else if ((rightvertex[0] != endpoint1[0]) ||
11813              (rightvertex[1] != endpoint1[1])) {
11814     printf("Internal error in segmentintersection():\n");
11815     printf("  Topological inconsistency after splitting a segment.\n");
11816     internalerror();
11817   }
11818   /* `splittri' should have destination endpoint1. */
11819 }
11820 
11821 /*****************************************************************************/
11822 /*                                                                           */
11823 /*  scoutsegment()   Scout the first triangle on the path from one endpoint  */
11824 /*                   to another, and check for completion (reaching the      */
11825 /*                   second endpoint), a collinear vertex, or the            */
11826 /*                   intersection of two segments.                           */
11827 /*                                                                           */
11828 /*  Returns one if the entire segment is successfully inserted, and zero if  */
11829 /*  the job must be finished by conformingedge() or constrainededge().       */
11830 /*                                                                           */
11831 /*  If the first triangle on the path has the second endpoint as its         */
11832 /*  destination or apex, a subsegment is inserted and the job is done.       */
11833 /*                                                                           */
11834 /*  If the first triangle on the path has a destination or apex that lies on */
11835 /*  the segment, a subsegment is inserted connecting the first endpoint to   */
11836 /*  the collinear vertex, and the search is continued from the collinear     */
11837 /*  vertex.                                                                  */
11838 /*                                                                           */
11839 /*  If the first triangle on the path has a subsegment opposite its origin,  */
11840 /*  then there is a segment that intersects the segment being inserted.      */
11841 /*  Their intersection vertex is inserted, splitting the subsegment.         */
11842 /*                                                                           */
11843 /*****************************************************************************/
11844 
11845 #ifdef ANSI_DECLARATORS
11846 static int scoutsegment(struct mesh *m, struct behavior *b, struct otri *searchtri,
11847                  vertex endpoint2, int newmark)
11848 #else /* not ANSI_DECLARATORS */
11849 static int scoutsegment(m, b, searchtri, endpoint2, newmark)
11850 struct mesh *m;
11851 struct behavior *b;
11852 struct otri *searchtri;
11853 vertex endpoint2;
11854 int newmark;
11855 #endif /* not ANSI_DECLARATORS */
11856 
11857 {
11858   struct otri crosstri;
11859   struct osub crosssubseg;
11860   vertex leftvertex, rightvertex;
11861   enum finddirectionresult collinear;
11862   subseg sptr;                      /* Temporary variable used by tspivot(). */
11863 
11864   collinear = finddirection(m, b, searchtri, endpoint2);
11865   dest(*searchtri, rightvertex);
11866   apex(*searchtri, leftvertex);
11867   if (((leftvertex[0] == endpoint2[0]) && (leftvertex[1] == endpoint2[1])) ||
11868       ((rightvertex[0] == endpoint2[0]) && (rightvertex[1] == endpoint2[1]))) {
11869     /* The segment is already an edge in the mesh. */
11870     if ((leftvertex[0] == endpoint2[0]) && (leftvertex[1] == endpoint2[1])) {
11871       lprevself(*searchtri);
11872     }
11873     /* Insert a subsegment, if there isn't already one there. */
11874     insertsubseg(m, b, searchtri, newmark);
11875     return 1;
11876   } else if (collinear == LEFTCOLLINEAR) {
11877     /* We've collided with a vertex between the segment's endpoints. */
11878     /* Make the collinear vertex be the triangle's origin. */
11879     lprevself(*searchtri);
11880     insertsubseg(m, b, searchtri, newmark);
11881     /* Insert the remainder of the segment. */
11882     return scoutsegment(m, b, searchtri, endpoint2, newmark);
11883   } else if (collinear == RIGHTCOLLINEAR) {
11884     /* We've collided with a vertex between the segment's endpoints. */
11885     insertsubseg(m, b, searchtri, newmark);
11886     /* Make the collinear vertex be the triangle's origin. */
11887     lnextself(*searchtri);
11888     /* Insert the remainder of the segment. */
11889     return scoutsegment(m, b, searchtri, endpoint2, newmark);
11890   } else {
11891     lnext(*searchtri, crosstri);
11892     tspivot(crosstri, crosssubseg);
11893     /* Check for a crossing segment. */
11894     if (crosssubseg.ss == m->dummysub) {
11895       return 0;
11896     } else {
11897       /* Insert a vertex at the intersection. */
11898       segmentintersection(m, b, &crosstri, &crosssubseg, endpoint2);
11899       otricopy(crosstri, *searchtri);
11900       insertsubseg(m, b, searchtri, newmark);
11901       /* Insert the remainder of the segment. */
11902       return scoutsegment(m, b, searchtri, endpoint2, newmark);
11903     }
11904   }
11905 }
11906 
11907 /*****************************************************************************/
11908 /*                                                                           */
11909 /*  conformingedge()   Force a segment into a conforming Delaunay            */
11910 /*                     triangulation by inserting a vertex at its midpoint,  */
11911 /*                     and recursively forcing in the two half-segments if   */
11912 /*                     necessary.                                            */
11913 /*                                                                           */
11914 /*  Generates a sequence of subsegments connecting `endpoint1' to            */
11915 /*  `endpoint2'.  `newmark' is the boundary marker of the segment, assigned  */
11916 /*  to each new splitting vertex and subsegment.                             */
11917 /*                                                                           */
11918 /*  Note that conformingedge() does not always maintain the conforming       */
11919 /*  Delaunay property.  Once inserted, segments are locked into place;       */
11920 /*  vertices inserted later (to force other segments in) may render these    */
11921 /*  fixed segments non-Delaunay.  The conforming Delaunay property will be   */
11922 /*  restored by enforcequality() by splitting encroached subsegments.        */
11923 /*                                                                           */
11924 /*****************************************************************************/
11925 
11926 #ifndef REDUCED
11927 #ifndef CDT_ONLY
11928 
11929 #ifdef ANSI_DECLARATORS
11930 static void conformingedge(struct mesh *m, struct behavior *b,
11931                     vertex endpoint1, vertex endpoint2, int newmark)
11932 #else /* not ANSI_DECLARATORS */
11933 static void conformingedge(m, b, endpoint1, endpoint2, newmark)
11934 struct mesh *m;
11935 struct behavior *b;
11936 vertex endpoint1;
11937 vertex endpoint2;
11938 int newmark;
11939 #endif /* not ANSI_DECLARATORS */
11940 
11941 {
11942   struct otri searchtri1, searchtri2;
11943   struct osub brokensubseg;
11944   vertex newvertex;
11945   vertex midvertex1, midvertex2;
11946   enum insertvertexresult success;
11947   int i;
11948   subseg sptr;                      /* Temporary variable used by tspivot(). */
11949 
11950   if (b->verbose > 2) {
11951     printf("Forcing segment into triangulation by recursive splitting:\n");
11952     printf("  (%.12g, %.12g) (%.12g, %.12g)\n", endpoint1[0], endpoint1[1],
11953            endpoint2[0], endpoint2[1]);
11954   }
11955   /* Create a new vertex to insert in the middle of the segment. */
11956   newvertex = (vertex) poolalloc(&m->vertices);
11957   /* Interpolate coordinates and attributes. */
11958   for (i = 0; i < 2 + m->nextras; i++) {
11959     newvertex[i] = 0.5 * (endpoint1[i] + endpoint2[i]);
11960   }
11961   setvertexmark(newvertex, newmark);
11962   setvertextype(newvertex, SEGMENTVERTEX);
11963   /* No known triangle to search from. */
11964   searchtri1.tri = m->dummytri;
11965   /* Attempt to insert the new vertex. */
11966   success = insertvertex(m, b, newvertex, &searchtri1, (struct osub *) NULL,
11967                          0, 0);
11968   if (success == DUPLICATEVERTEX) {
11969     if (b->verbose > 2) {
11970       printf("  Segment intersects existing vertex (%.12g, %.12g).\n",
11971              newvertex[0], newvertex[1]);
11972     }
11973     /* Use the vertex that's already there. */
11974     vertexdealloc(m, newvertex);
11975     org(searchtri1, newvertex);
11976   } else {
11977     if (success == VIOLATINGVERTEX) {
11978       if (b->verbose > 2) {
11979         printf("  Two segments intersect at (%.12g, %.12g).\n",
11980                newvertex[0], newvertex[1]);
11981       }
11982       /* By fluke, we've landed right on another segment.  Split it. */
11983       tspivot(searchtri1, brokensubseg);
11984       success = insertvertex(m, b, newvertex, &searchtri1, &brokensubseg,
11985                              0, 0);
11986       if (success != SUCCESSFULVERTEX) {
11987         printf("Internal error in conformingedge():\n");
11988         printf("  Failure to split a segment.\n");
11989         internalerror();
11990       }
11991     }
11992     /* The vertex has been inserted successfully. */
11993     if (m->steinerleft > 0) {
11994       m->steinerleft--;
11995     }
11996   }
11997   otricopy(searchtri1, searchtri2);
11998   /* `searchtri1' and `searchtri2' are fastened at their origins to         */
11999   /*   `newvertex', and will be directed toward `endpoint1' and `endpoint2' */
12000   /*   respectively.  First, we must get `searchtri2' out of the way so it  */
12001   /*   won't be invalidated during the insertion of the first half of the   */
12002   /*   segment.                                                             */
12003   finddirection(m, b, &searchtri2, endpoint2);
12004   if (!scoutsegment(m, b, &searchtri1, endpoint1, newmark)) {
12005     /* The origin of searchtri1 may have changed if a collision with an */
12006     /*   intervening vertex on the segment occurred.                    */
12007     org(searchtri1, midvertex1);
12008     conformingedge(m, b, midvertex1, endpoint1, newmark);
12009   }
12010   if (!scoutsegment(m, b, &searchtri2, endpoint2, newmark)) {
12011     /* The origin of searchtri2 may have changed if a collision with an */
12012     /*   intervening vertex on the segment occurred.                    */
12013     org(searchtri2, midvertex2);
12014     conformingedge(m, b, midvertex2, endpoint2, newmark);
12015   }
12016 }
12017 
12018 #endif /* not CDT_ONLY */
12019 #endif /* not REDUCED */
12020 
12021 /*****************************************************************************/
12022 /*                                                                           */
12023 /*  delaunayfixup()   Enforce the Delaunay condition at an edge, fanning out */
12024 /*                    recursively from an existing vertex.  Pay special      */
12025 /*                    attention to stacking inverted triangles.              */
12026 /*                                                                           */
12027 /*  This is a support routine for inserting segments into a constrained      */
12028 /*  Delaunay triangulation.                                                  */
12029 /*                                                                           */
12030 /*  The origin of fixuptri is treated as if it has just been inserted, and   */
12031 /*  the local Delaunay condition needs to be enforced.  It is only enforced  */
12032 /*  in one sector, however, that being the angular range defined by          */
12033 /*  fixuptri.                                                                */
12034 /*                                                                           */
12035 /*  This routine also needs to make decisions regarding the "stacking" of    */
12036 /*  triangles.  (Read the description of constrainededge() below before      */
12037 /*  reading on here, so you understand the algorithm.)  If the position of   */
12038 /*  the new vertex (the origin of fixuptri) indicates that the vertex before */
12039 /*  it on the polygon is a reflex vertex, then "stack" the triangle by       */
12040 /*  doing nothing.  (fixuptri is an inverted triangle, which is how stacked  */
12041 /*  triangles are identified.)                                               */
12042 /*                                                                           */
12043 /*  Otherwise, check whether the vertex before that was a reflex vertex.     */
12044 /*  If so, perform an edge flip, thereby eliminating an inverted triangle    */
12045 /*  (popping it off the stack).  The edge flip may result in the creation    */
12046 /*  of a new inverted triangle, depending on whether or not the new vertex   */
12047 /*  is visible to the vertex three edges behind on the polygon.              */
12048 /*                                                                           */
12049 /*  If neither of the two vertices behind the new vertex are reflex          */
12050 /*  vertices, fixuptri and fartri, the triangle opposite it, are not         */
12051 /*  inverted; hence, ensure that the edge between them is locally Delaunay.  */
12052 /*                                                                           */
12053 /*  `leftside' indicates whether or not fixuptri is to the left of the       */
12054 /*  segment being inserted.  (Imagine that the segment is pointing up from   */
12055 /*  endpoint1 to endpoint2.)                                                 */
12056 /*                                                                           */
12057 /*****************************************************************************/
12058 
12059 #ifdef ANSI_DECLARATORS
12060 static void delaunayfixup(struct mesh *m, struct behavior *b,
12061                    struct otri *fixuptri, int leftside)
12062 #else /* not ANSI_DECLARATORS */
12063 static void delaunayfixup(m, b, fixuptri, leftside)
12064 struct mesh *m;
12065 struct behavior *b;
12066 struct otri *fixuptri;
12067 int leftside;
12068 #endif /* not ANSI_DECLARATORS */
12069 
12070 {
12071   struct otri neartri;
12072   struct otri fartri;
12073   struct osub faredge;
12074   vertex nearvertex, leftvertex, rightvertex, farvertex;
12075   triangle ptr;                         /* Temporary variable used by sym(). */
12076   subseg sptr;                      /* Temporary variable used by tspivot(). */
12077 
12078   lnext(*fixuptri, neartri);
12079   sym(neartri, fartri);
12080   /* Check if the edge opposite the origin of fixuptri can be flipped. */
12081   if (fartri.tri == m->dummytri) {
12082     return;
12083   }
12084   tspivot(neartri, faredge);
12085   if (faredge.ss != m->dummysub) {
12086     return;
12087   }
12088   /* Find all the relevant vertices. */
12089   apex(neartri, nearvertex);
12090   org(neartri, leftvertex);
12091   dest(neartri, rightvertex);
12092   apex(fartri, farvertex);
12093   /* Check whether the previous polygon vertex is a reflex vertex. */
12094   if (leftside) {
12095     if (counterclockwise(m, b, nearvertex, leftvertex, farvertex) <= 0.0) {
12096       /* leftvertex is a reflex vertex too.  Nothing can */
12097       /*   be done until a convex section is found.      */
12098       return;
12099     }
12100   } else {
12101     if (counterclockwise(m, b, farvertex, rightvertex, nearvertex) <= 0.0) {
12102       /* rightvertex is a reflex vertex too.  Nothing can */
12103       /*   be done until a convex section is found.       */
12104       return;
12105     }
12106   }
12107   if (counterclockwise(m, b, rightvertex, leftvertex, farvertex) > 0.0) {
12108     /* fartri is not an inverted triangle, and farvertex is not a reflex */
12109     /*   vertex.  As there are no reflex vertices, fixuptri isn't an     */
12110     /*   inverted triangle, either.  Hence, test the edge between the    */
12111     /*   triangles to ensure it is locally Delaunay.                     */
12112     if (incircle(m, b, leftvertex, farvertex, rightvertex, nearvertex) <=
12113         0.0) {
12114       return;
12115     }
12116     /* Not locally Delaunay; go on to an edge flip. */
12117   }        /* else fartri is inverted; remove it from the stack by flipping. */
12118   flip(m, b, &neartri);
12119   lprevself(*fixuptri);    /* Restore the origin of fixuptri after the flip. */
12120   /* Recursively process the two triangles that result from the flip. */
12121   delaunayfixup(m, b, fixuptri, leftside);
12122   delaunayfixup(m, b, &fartri, leftside);
12123 }
12124 
12125 /*****************************************************************************/
12126 /*                                                                           */
12127 /*  constrainededge()   Force a segment into a constrained Delaunay          */
12128 /*                      triangulation by deleting the triangles it           */
12129 /*                      intersects, and triangulating the polygons that      */
12130 /*                      form on each side of it.                             */
12131 /*                                                                           */
12132 /*  Generates a single subsegment connecting `endpoint1' to `endpoint2'.     */
12133 /*  The triangle `starttri' has `endpoint1' as its origin.  `newmark' is the */
12134 /*  boundary marker of the segment.                                          */
12135 /*                                                                           */
12136 /*  To insert a segment, every triangle whose interior intersects the        */
12137 /*  segment is deleted.  The union of these deleted triangles is a polygon   */
12138 /*  (which is not necessarily monotone, but is close enough), which is       */
12139 /*  divided into two polygons by the new segment.  This routine's task is    */
12140 /*  to generate the Delaunay triangulation of these two polygons.            */
12141 /*                                                                           */
12142 /*  You might think of this routine's behavior as a two-step process.  The   */
12143 /*  first step is to walk from endpoint1 to endpoint2, flipping each edge    */
12144 /*  encountered.  This step creates a fan of edges connected to endpoint1,   */
12145 /*  including the desired edge to endpoint2.  The second step enforces the   */
12146 /*  Delaunay condition on each side of the segment in an incremental manner: */
12147 /*  proceeding along the polygon from endpoint1 to endpoint2 (this is done   */
12148 /*  independently on each side of the segment), each vertex is "enforced"    */
12149 /*  as if it had just been inserted, but affecting only the previous         */
12150 /*  vertices.  The result is the same as if the vertices had been inserted   */
12151 /*  in the order they appear on the polygon, so the result is Delaunay.      */
12152 /*                                                                           */
12153 /*  In truth, constrainededge() interleaves these two steps.  The procedure  */
12154 /*  walks from endpoint1 to endpoint2, and each time an edge is encountered  */
12155 /*  and flipped, the newly exposed vertex (at the far end of the flipped     */
12156 /*  edge) is "enforced" upon the previously flipped edges, usually affecting */
12157 /*  only one side of the polygon (depending upon which side of the segment   */
12158 /*  the vertex falls on).                                                    */
12159 /*                                                                           */
12160 /*  The algorithm is complicated by the need to handle polygons that are not */
12161 /*  convex.  Although the polygon is not necessarily monotone, it can be     */
12162 /*  triangulated in a manner similar to the stack-based algorithms for       */
12163 /*  monotone polygons.  For each reflex vertex (local concavity) of the      */
12164 /*  polygon, there will be an inverted triangle formed by one of the edge    */
12165 /*  flips.  (An inverted triangle is one with negative area - that is, its   */
12166 /*  vertices are arranged in clockwise order - and is best thought of as a   */
12167 /*  wrinkle in the fabric of the mesh.)  Each inverted triangle can be       */
12168 /*  thought of as a reflex vertex pushed on the stack, waiting to be fixed   */
12169 /*  later.                                                                   */
12170 /*                                                                           */
12171 /*  A reflex vertex is popped from the stack when a vertex is inserted that  */
12172 /*  is visible to the reflex vertex.  (However, if the vertex behind the     */
12173 /*  reflex vertex is not visible to the reflex vertex, a new inverted        */
12174 /*  triangle will take its place on the stack.)  These details are handled   */
12175 /*  by the delaunayfixup() routine above.                                    */
12176 /*                                                                           */
12177 /*****************************************************************************/
12178 
12179 #ifdef ANSI_DECLARATORS
12180 static void constrainededge(struct mesh *m, struct behavior *b,
12181                      struct otri *starttri, vertex endpoint2, int newmark)
12182 #else /* not ANSI_DECLARATORS */
12183 static void constrainededge(m, b, starttri, endpoint2, newmark)
12184 struct mesh *m;
12185 struct behavior *b;
12186 struct otri *starttri;
12187 vertex endpoint2;
12188 int newmark;
12189 #endif /* not ANSI_DECLARATORS */
12190 
12191 {
12192   struct otri fixuptri, fixuptri2;
12193   struct osub crosssubseg;
12194   vertex endpoint1;
12195   vertex farvertex;
12196   REAL area;
12197   int collision;
12198   int done;
12199   triangle ptr;             /* Temporary variable used by sym() and oprev(). */
12200   subseg sptr;                      /* Temporary variable used by tspivot(). */
12201 
12202   org(*starttri, endpoint1);
12203   lnext(*starttri, fixuptri);
12204   flip(m, b, &fixuptri);
12205   /* `collision' indicates whether we have found a vertex directly */
12206   /*   between endpoint1 and endpoint2.                            */
12207   collision = 0;
12208   done = 0;
12209   do {
12210     org(fixuptri, farvertex);
12211     /* `farvertex' is the extreme point of the polygon we are "digging" */
12212     /*   to get from endpoint1 to endpoint2.                           */
12213     if ((farvertex[0] == endpoint2[0]) && (farvertex[1] == endpoint2[1])) {
12214       oprev(fixuptri, fixuptri2);
12215       /* Enforce the Delaunay condition around endpoint2. */
12216       delaunayfixup(m, b, &fixuptri, 0);
12217       delaunayfixup(m, b, &fixuptri2, 1);
12218       done = 1;
12219     } else {
12220       /* Check whether farvertex is to the left or right of the segment */
12221       /*   being inserted, to decide which edge of fixuptri to dig      */
12222       /*   through next.                                                */
12223       area = counterclockwise(m, b, endpoint1, endpoint2, farvertex);
12224       if (area == 0.0) {
12225         /* We've collided with a vertex between endpoint1 and endpoint2. */
12226         collision = 1;
12227         oprev(fixuptri, fixuptri2);
12228         /* Enforce the Delaunay condition around farvertex. */
12229         delaunayfixup(m, b, &fixuptri, 0);
12230         delaunayfixup(m, b, &fixuptri2, 1);
12231         done = 1;
12232       } else {
12233         if (area > 0.0) {        /* farvertex is to the left of the segment. */
12234           oprev(fixuptri, fixuptri2);
12235           /* Enforce the Delaunay condition around farvertex, on the */
12236           /*   left side of the segment only.                        */
12237           delaunayfixup(m, b, &fixuptri2, 1);
12238           /* Flip the edge that crosses the segment.  After the edge is */
12239           /*   flipped, one of its endpoints is the fan vertex, and the */
12240           /*   destination of fixuptri is the fan vertex.               */
12241           lprevself(fixuptri);
12242         } else {                /* farvertex is to the right of the segment. */
12243           delaunayfixup(m, b, &fixuptri, 0);
12244           /* Flip the edge that crosses the segment.  After the edge is */
12245           /*   flipped, one of its endpoints is the fan vertex, and the */
12246           /*   destination of fixuptri is the fan vertex.               */
12247           oprevself(fixuptri);
12248         }
12249         /* Check for two intersecting segments. */
12250         tspivot(fixuptri, crosssubseg);
12251         if (crosssubseg.ss == m->dummysub) {
12252           flip(m, b, &fixuptri);    /* May create inverted triangle at left. */
12253         } else {
12254           /* We've collided with a segment between endpoint1 and endpoint2. */
12255           collision = 1;
12256           /* Insert a vertex at the intersection. */
12257           segmentintersection(m, b, &fixuptri, &crosssubseg, endpoint2);
12258           done = 1;
12259         }
12260       }
12261     }
12262   } while (!done);
12263   /* Insert a subsegment to make the segment permanent. */
12264   insertsubseg(m, b, &fixuptri, newmark);
12265   /* If there was a collision with an interceding vertex, install another */
12266   /*   segment connecting that vertex with endpoint2.                     */
12267   if (collision) {
12268     /* Insert the remainder of the segment. */
12269     if (!scoutsegment(m, b, &fixuptri, endpoint2, newmark)) {
12270       constrainededge(m, b, &fixuptri, endpoint2, newmark);
12271     }
12272   }
12273 }
12274 
12275 /*****************************************************************************/
12276 /*                                                                           */
12277 /*  insertsegment()   Insert a PSLG segment into a triangulation.            */
12278 /*                                                                           */
12279 /*****************************************************************************/
12280 
12281 #ifdef ANSI_DECLARATORS
12282 static void insertsegment(struct mesh *m, struct behavior *b,
12283                    vertex endpoint1, vertex endpoint2, int newmark)
12284 #else /* not ANSI_DECLARATORS */
12285 static void insertsegment(m, b, endpoint1, endpoint2, newmark)
12286 struct mesh *m;
12287 struct behavior *b;
12288 vertex endpoint1;
12289 vertex endpoint2;
12290 int newmark;
12291 #endif /* not ANSI_DECLARATORS */
12292 
12293 {
12294   struct otri searchtri1, searchtri2;
12295   triangle encodedtri;
12296   vertex checkvertex;
12297   triangle ptr;                         /* Temporary variable used by sym(). */
12298 
12299   if (b->verbose > 1) {
12300     printf("  Connecting (%.12g, %.12g) to (%.12g, %.12g).\n",
12301            endpoint1[0], endpoint1[1], endpoint2[0], endpoint2[1]);
12302   }
12303 
12304   /* Find a triangle whose origin is the segment's first endpoint. */
12305   checkvertex = (vertex) NULL;
12306   encodedtri = vertex2tri(endpoint1);
12307   if (encodedtri != (triangle) NULL) {
12308     decode(encodedtri, searchtri1);
12309     org(searchtri1, checkvertex);
12310   }
12311   if (checkvertex != endpoint1) {
12312     /* Find a boundary triangle to search from. */
12313     searchtri1.tri = m->dummytri;
12314     searchtri1.orient = 0;
12315     symself(searchtri1);
12316     /* Search for the segment's first endpoint by point location. */
12317     if (locate(m, b, endpoint1, &searchtri1) != ONVERTEX) {
12318       printf(
12319         "Internal error in insertsegment():  Unable to locate PSLG vertex\n");
12320       printf("  (%.12g, %.12g) in triangulation.\n",
12321              endpoint1[0], endpoint1[1]);
12322       internalerror();
12323     }
12324   }
12325   /* Remember this triangle to improve subsequent point location. */
12326   otricopy(searchtri1, m->recenttri);
12327   /* Scout the beginnings of a path from the first endpoint */
12328   /*   toward the second.                                   */
12329   if (scoutsegment(m, b, &searchtri1, endpoint2, newmark)) {
12330     /* The segment was easily inserted. */
12331     return;
12332   }
12333   /* The first endpoint may have changed if a collision with an intervening */
12334   /*   vertex on the segment occurred.                                      */
12335   org(searchtri1, endpoint1);
12336 
12337   /* Find a triangle whose origin is the segment's second endpoint. */
12338   checkvertex = (vertex) NULL;
12339   encodedtri = vertex2tri(endpoint2);
12340   if (encodedtri != (triangle) NULL) {
12341     decode(encodedtri, searchtri2);
12342     org(searchtri2, checkvertex);
12343   }
12344   if (checkvertex != endpoint2) {
12345     /* Find a boundary triangle to search from. */
12346     searchtri2.tri = m->dummytri;
12347     searchtri2.orient = 0;
12348     symself(searchtri2);
12349     /* Search for the segment's second endpoint by point location. */
12350     if (locate(m, b, endpoint2, &searchtri2) != ONVERTEX) {
12351       printf(
12352         "Internal error in insertsegment():  Unable to locate PSLG vertex\n");
12353       printf("  (%.12g, %.12g) in triangulation.\n",
12354              endpoint2[0], endpoint2[1]);
12355       internalerror();
12356     }
12357   }
12358   /* Remember this triangle to improve subsequent point location. */
12359   otricopy(searchtri2, m->recenttri);
12360   /* Scout the beginnings of a path from the second endpoint */
12361   /*   toward the first.                                     */
12362   if (scoutsegment(m, b, &searchtri2, endpoint1, newmark)) {
12363     /* The segment was easily inserted. */
12364     return;
12365   }
12366   /* The second endpoint may have changed if a collision with an intervening */
12367   /*   vertex on the segment occurred.                                       */
12368   org(searchtri2, endpoint2);
12369 
12370 #ifndef REDUCED
12371 #ifndef CDT_ONLY
12372   if (b->splitseg) {
12373     /* Insert vertices to force the segment into the triangulation. */
12374     conformingedge(m, b, endpoint1, endpoint2, newmark);
12375   } else {
12376 #endif /* not CDT_ONLY */
12377 #endif /* not REDUCED */
12378     /* Insert the segment directly into the triangulation. */
12379     constrainededge(m, b, &searchtri1, endpoint2, newmark);
12380 #ifndef REDUCED
12381 #ifndef CDT_ONLY
12382   }
12383 #endif /* not CDT_ONLY */
12384 #endif /* not REDUCED */
12385 }
12386 
12387 /*****************************************************************************/
12388 /*                                                                           */
12389 /*  markhull()   Cover the convex hull of a triangulation with subsegments.  */
12390 /*                                                                           */
12391 /*****************************************************************************/
12392 
12393 #ifdef ANSI_DECLARATORS
12394 static void markhull(struct mesh *m, struct behavior *b)
12395 #else /* not ANSI_DECLARATORS */
12396 static void markhull(m, b)
12397 struct mesh *m;
12398 struct behavior *b;
12399 #endif /* not ANSI_DECLARATORS */
12400 
12401 {
12402   struct otri hulltri;
12403   struct otri nexttri;
12404   struct otri starttri;
12405   triangle ptr;             /* Temporary variable used by sym() and oprev(). */
12406 
12407   /* Find a triangle handle on the hull. */
12408   hulltri.tri = m->dummytri;
12409   hulltri.orient = 0;
12410   symself(hulltri);
12411   /* Remember where we started so we know when to stop. */
12412   otricopy(hulltri, starttri);
12413   /* Go once counterclockwise around the convex hull. */
12414   do {
12415     /* Create a subsegment if there isn't already one here. */
12416     insertsubseg(m, b, &hulltri, 1);
12417     /* To find the next hull edge, go clockwise around the next vertex. */
12418     lnextself(hulltri);
12419     oprev(hulltri, nexttri);
12420     while (nexttri.tri != m->dummytri) {
12421       otricopy(nexttri, hulltri);
12422       oprev(hulltri, nexttri);
12423     }
12424   } while (!otriequal(hulltri, starttri));
12425 }
12426 
12427 /*****************************************************************************/
12428 /*                                                                           */
12429 /*  formskeleton()   Create the segments of a triangulation, including PSLG  */
12430 /*                   segments and edges on the convex hull.                  */
12431 /*                                                                           */
12432 /*  The PSLG segments are read from a .poly file.  The return value is the   */
12433 /*  number of segments in the file.                                          */
12434 /*                                                                           */
12435 /*****************************************************************************/
12436 
12437 #ifdef TRILIBRARY
12438 
12439 #ifdef ANSI_DECLARATORS
12440 static void formskeleton(struct mesh *m, struct behavior *b, int *segmentlist,
12441                   int *segmentmarkerlist, int numberofsegments)
12442 #else /* not ANSI_DECLARATORS */
12443 static void formskeleton(m, b, segmentlist, segmentmarkerlist, numberofsegments)
12444 struct mesh *m;
12445 struct behavior *b;
12446 int *segmentlist;
12447 int *segmentmarkerlist;
12448 int numberofsegments;
12449 #endif /* not ANSI_DECLARATORS */
12450 
12451 #else /* not TRILIBRARY */
12452 
12453 #ifdef ANSI_DECLARATORS
12454 static void formskeleton(struct mesh *m, struct behavior *b,
12455                   FILE *polyfile, char *polyfilename)
12456 #else /* not ANSI_DECLARATORS */
12457 static void formskeleton(m, b, polyfile, polyfilename)
12458 struct mesh *m;
12459 struct behavior *b;
12460 FILE *polyfile;
12461 char *polyfilename;
12462 #endif /* not ANSI_DECLARATORS */
12463 
12464 #endif /* not TRILIBRARY */
12465 
12466 {
12467 #ifdef TRILIBRARY
12468   char polyfilename[6];
12469   int index;
12470 #else /* not TRILIBRARY */
12471   char inputline[INPUTLINESIZE];
12472   char *stringptr;
12473 #endif /* not TRILIBRARY */
12474   vertex endpoint1, endpoint2;
12475   int segmentmarkers;
12476   int end1, end2;
12477   int boundmarker;
12478   int i;
12479 
12480   if (b->poly) {
12481     if (!b->quiet) {
12482       printf("Recovering segments in Delaunay triangulation.\n");
12483     }
12484 #ifdef TRILIBRARY
12485     strcpy(polyfilename, "input");
12486     m->insegments = numberofsegments;
12487     segmentmarkers = segmentmarkerlist != (int *) NULL;
12488     index = 0;
12489 #else /* not TRILIBRARY */
12490     /* Read the segments from a .poly file. */
12491     /* Read number of segments and number of boundary markers. */
12492     stringptr = readline(inputline, polyfile, polyfilename);
12493     m->insegments = (int) strtol(stringptr, &stringptr, 0);
12494     stringptr = findfield(stringptr);
12495     if (*stringptr == '\0') {
12496       segmentmarkers = 0;
12497     } else {
12498       segmentmarkers = (int) strtol(stringptr, &stringptr, 0);
12499     }
12500 #endif /* not TRILIBRARY */
12501     /* If the input vertices are collinear, there is no triangulation, */
12502     /*   so don't try to insert segments.                              */
12503     if (m->triangles.items == 0) {
12504       return;
12505     }
12506 
12507     /* If segments are to be inserted, compute a mapping */
12508     /*   from vertices to triangles.                     */
12509     if (m->insegments > 0) {
12510       makevertexmap(m, b);
12511       if (b->verbose) {
12512         printf("  Recovering PSLG segments.\n");
12513       }
12514     }
12515 
12516     boundmarker = 0;
12517     /* Read and insert the segments. */
12518     for (i = 0; i < m->insegments; i++) {
12519 #ifdef TRILIBRARY
12520       end1 = segmentlist[index++];
12521       end2 = segmentlist[index++];
12522       if (segmentmarkers) {
12523         boundmarker = segmentmarkerlist[i];
12524       }
12525 #else /* not TRILIBRARY */
12526       stringptr = readline(inputline, polyfile, b->inpolyfilename);
12527       stringptr = findfield(stringptr);
12528       if (*stringptr == '\0') {
12529         printf("Error:  Segment %d has no endpoints in %s.\n",
12530                b->firstnumber + i, polyfilename);
12531         triexit(1);
12532       } else {
12533         end1 = (int) strtol(stringptr, &stringptr, 0);
12534       }
12535       stringptr = findfield(stringptr);
12536       if (*stringptr == '\0') {
12537         printf("Error:  Segment %d is missing its second endpoint in %s.\n",
12538                b->firstnumber + i, polyfilename);
12539         triexit(1);
12540       } else {
12541         end2 = (int) strtol(stringptr, &stringptr, 0);
12542       }
12543       if (segmentmarkers) {
12544         stringptr = findfield(stringptr);
12545         if (*stringptr == '\0') {
12546           boundmarker = 0;
12547         } else {
12548           boundmarker = (int) strtol(stringptr, &stringptr, 0);
12549         }
12550       }
12551 #endif /* not TRILIBRARY */
12552       if ((end1 < b->firstnumber) ||
12553           (end1 >= b->firstnumber + m->invertices)) {
12554         if (!b->quiet) {
12555           printf("Warning:  Invalid first endpoint of segment %d in %s.\n",
12556                  b->firstnumber + i, polyfilename);
12557         }
12558       } else if ((end2 < b->firstnumber) ||
12559                  (end2 >= b->firstnumber + m->invertices)) {
12560         if (!b->quiet) {
12561           printf("Warning:  Invalid second endpoint of segment %d in %s.\n",
12562                  b->firstnumber + i, polyfilename);
12563         }
12564       } else {
12565         /* Find the vertices numbered `end1' and `end2'. */
12566         endpoint1 = getvertex(m, b, end1);
12567         endpoint2 = getvertex(m, b, end2);
12568         if ((endpoint1[0] == endpoint2[0]) && (endpoint1[1] == endpoint2[1])) {
12569           if (!b->quiet) {
12570             printf("Warning:  Endpoints of segment %d are coincident in %s.\n",
12571                    b->firstnumber + i, polyfilename);
12572           }
12573         } else {
12574           insertsegment(m, b, endpoint1, endpoint2, boundmarker);
12575         }
12576       }
12577     }
12578   } else {
12579     m->insegments = 0;
12580   }
12581   if (b->convex || !b->poly) {
12582     /* Enclose the convex hull with subsegments. */
12583     if (b->verbose) {
12584       printf("  Enclosing convex hull with segments.\n");
12585     }
12586     markhull(m, b);
12587   }
12588 }
12589 
12590 /**                                                                         **/
12591 /**                                                                         **/
12592 /********* Segment insertion ends here                               *********/
12593 
12594 /********* Carving out holes and concavities begins here             *********/
12595 /**                                                                         **/
12596 /**                                                                         **/
12597 
12598 /*****************************************************************************/
12599 /*                                                                           */
12600 /*  infecthull()   Virally infect all of the triangles of the convex hull    */
12601 /*                 that are not protected by subsegments.  Where there are   */
12602 /*                 subsegments, set boundary markers as appropriate.         */
12603 /*                                                                           */
12604 /*****************************************************************************/
12605 
12606 #ifdef ANSI_DECLARATORS
12607 static void infecthull(struct mesh *m, struct behavior *b)
12608 #else /* not ANSI_DECLARATORS */
12609 static void infecthull(m, b)
12610 struct mesh *m;
12611 struct behavior *b;
12612 #endif /* not ANSI_DECLARATORS */
12613 
12614 {
12615   struct otri hulltri;
12616   struct otri nexttri;
12617   struct otri starttri;
12618   struct osub hullsubseg;
12619   triangle **deadtriangle;
12620   vertex horg, hdest;
12621   triangle ptr;                         /* Temporary variable used by sym(). */
12622   subseg sptr;                      /* Temporary variable used by tspivot(). */
12623 
12624   if (b->verbose) {
12625     printf("  Marking concavities (external triangles) for elimination.\n");
12626   }
12627   /* Find a triangle handle on the hull. */
12628   hulltri.tri = m->dummytri;
12629   hulltri.orient = 0;
12630   symself(hulltri);
12631   /* Remember where we started so we know when to stop. */
12632   otricopy(hulltri, starttri);
12633   /* Go once counterclockwise around the convex hull. */
12634   do {
12635     /* Ignore triangles that are already infected. */
12636     if (!infected(hulltri)) {
12637       /* Is the triangle protected by a subsegment? */
12638       tspivot(hulltri, hullsubseg);
12639       if (hullsubseg.ss == m->dummysub) {
12640         /* The triangle is not protected; infect it. */
12641         if (!infected(hulltri)) {
12642           infect(hulltri);
12643           deadtriangle = (triangle **) poolalloc(&m->viri);
12644           *deadtriangle = hulltri.tri;
12645         }
12646       } else {
12647         /* The triangle is protected; set boundary markers if appropriate. */
12648         if (mark(hullsubseg) == 0) {
12649           setmark(hullsubseg, 1);
12650           org(hulltri, horg);
12651           dest(hulltri, hdest);
12652           if (vertexmark(horg) == 0) {
12653             setvertexmark(horg, 1);
12654           }
12655           if (vertexmark(hdest) == 0) {
12656             setvertexmark(hdest, 1);
12657           }
12658         }
12659       }
12660     }
12661     /* To find the next hull edge, go clockwise around the next vertex. */
12662     lnextself(hulltri);
12663     oprev(hulltri, nexttri);
12664     while (nexttri.tri != m->dummytri) {
12665       otricopy(nexttri, hulltri);
12666       oprev(hulltri, nexttri);
12667     }
12668   } while (!otriequal(hulltri, starttri));
12669 }
12670 
12671 /*****************************************************************************/
12672 /*                                                                           */
12673 /*  plague()   Spread the virus from all infected triangles to any neighbors */
12674 /*             not protected by subsegments.  Delete all infected triangles. */
12675 /*                                                                           */
12676 /*  This is the procedure that actually creates holes and concavities.       */
12677 /*                                                                           */
12678 /*  This procedure operates in two phases.  The first phase identifies all   */
12679 /*  the triangles that will die, and marks them as infected.  They are       */
12680 /*  marked to ensure that each triangle is added to the virus pool only      */
12681 /*  once, so the procedure will terminate.                                   */
12682 /*                                                                           */
12683 /*  The second phase actually eliminates the infected triangles.  It also    */
12684 /*  eliminates orphaned vertices.                                            */
12685 /*                                                                           */
12686 /*****************************************************************************/
12687 
12688 #ifdef ANSI_DECLARATORS
12689 static void plague(struct mesh *m, struct behavior *b)
12690 #else /* not ANSI_DECLARATORS */
12691 static void plague(m, b)
12692 struct mesh *m;
12693 struct behavior *b;
12694 #endif /* not ANSI_DECLARATORS */
12695 
12696 {
12697   struct otri testtri;
12698   struct otri neighbor;
12699   triangle **virusloop;
12700   triangle **deadtriangle;
12701   struct osub neighborsubseg;
12702   vertex testvertex;
12703   vertex norg, ndest;
12704   vertex deadorg, deaddest, deadapex;
12705   int killorg;
12706   triangle ptr;             /* Temporary variable used by sym() and onext(). */
12707   subseg sptr;                      /* Temporary variable used by tspivot(). */
12708 
12709   if (b->verbose) {
12710     printf("  Marking neighbors of marked triangles.\n");
12711   }
12712   /* Loop through all the infected triangles, spreading the virus to */
12713   /*   their neighbors, then to their neighbors' neighbors.          */
12714   traversalinit(&m->viri);
12715   virusloop = (triangle **) traverse(&m->viri);
12716   while (virusloop != (triangle **) NULL) {
12717     testtri.tri = *virusloop;
12718     /* A triangle is marked as infected by messing with one of its pointers */
12719     /*   to subsegments, setting it to an illegal value.  Hence, we have to */
12720     /*   temporarily uninfect this triangle so that we can examine its      */
12721     /*   adjacent subsegments.                                              */
12722     uninfect(testtri);
12723     if (b->verbose > 2) {
12724       /* Assign the triangle an orientation for convenience in */
12725       /*   checking its vertices.                              */
12726       testtri.orient = 0;
12727       org(testtri, deadorg);
12728       dest(testtri, deaddest);
12729       apex(testtri, deadapex);
12730       printf("    Checking (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
12731              deadorg[0], deadorg[1], deaddest[0], deaddest[1],
12732              deadapex[0], deadapex[1]);
12733     }
12734     /* Check each of the triangle's three neighbors. */
12735     for (testtri.orient = 0; testtri.orient < 3; testtri.orient++) {
12736       /* Find the neighbor. */
12737       sym(testtri, neighbor);
12738       /* Check for a subsegment between the triangle and its neighbor. */
12739       tspivot(testtri, neighborsubseg);
12740       /* Check if the neighbor is nonexistent or already infected. */
12741       if ((neighbor.tri == m->dummytri) || infected(neighbor)) {
12742         if (neighborsubseg.ss != m->dummysub) {
12743           /* There is a subsegment separating the triangle from its      */
12744           /*   neighbor, but both triangles are dying, so the subsegment */
12745           /*   dies too.                                                 */
12746           subsegdealloc(m, neighborsubseg.ss);
12747           if (neighbor.tri != m->dummytri) {
12748             /* Make sure the subsegment doesn't get deallocated again */
12749             /*   later when the infected neighbor is visited.         */
12750             uninfect(neighbor);
12751             tsdissolve(neighbor);
12752             infect(neighbor);
12753           }
12754         }
12755       } else {                   /* The neighbor exists and is not infected. */
12756         if (neighborsubseg.ss == m->dummysub) {
12757           /* There is no subsegment protecting the neighbor, so */
12758           /*   the neighbor becomes infected.                   */
12759           if (b->verbose > 2) {
12760             org(neighbor, deadorg);
12761             dest(neighbor, deaddest);
12762             apex(neighbor, deadapex);
12763             printf(
12764               "    Marking (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
12765                    deadorg[0], deadorg[1], deaddest[0], deaddest[1],
12766                    deadapex[0], deadapex[1]);
12767           }
12768           infect(neighbor);
12769           /* Ensure that the neighbor's neighbors will be infected. */
12770           deadtriangle = (triangle **) poolalloc(&m->viri);
12771           *deadtriangle = neighbor.tri;
12772         } else {               /* The neighbor is protected by a subsegment. */
12773           /* Remove this triangle from the subsegment. */
12774           stdissolve(neighborsubseg);
12775           /* The subsegment becomes a boundary.  Set markers accordingly. */
12776           if (mark(neighborsubseg) == 0) {
12777             setmark(neighborsubseg, 1);
12778           }
12779           org(neighbor, norg);
12780           dest(neighbor, ndest);
12781           if (vertexmark(norg) == 0) {
12782             setvertexmark(norg, 1);
12783           }
12784           if (vertexmark(ndest) == 0) {
12785             setvertexmark(ndest, 1);
12786           }
12787         }
12788       }
12789     }
12790     /* Remark the triangle as infected, so it doesn't get added to the */
12791     /*   virus pool again.                                             */
12792     infect(testtri);
12793     virusloop = (triangle **) traverse(&m->viri);
12794   }
12795 
12796   if (b->verbose) {
12797     printf("  Deleting marked triangles.\n");
12798   }
12799 
12800   traversalinit(&m->viri);
12801   virusloop = (triangle **) traverse(&m->viri);
12802   while (virusloop != (triangle **) NULL) {
12803     testtri.tri = *virusloop;
12804 
12805     /* Check each of the three corners of the triangle for elimination. */
12806     /*   This is done by walking around each vertex, checking if it is  */
12807     /*   still connected to at least one live triangle.                 */
12808     for (testtri.orient = 0; testtri.orient < 3; testtri.orient++) {
12809       org(testtri, testvertex);
12810       /* Check if the vertex has already been tested. */
12811       if (testvertex != (vertex) NULL) {
12812         killorg = 1;
12813         /* Mark the corner of the triangle as having been tested. */
12814         setorg(testtri, NULL);
12815         /* Walk counterclockwise about the vertex. */
12816         onext(testtri, neighbor);
12817         /* Stop upon reaching a boundary or the starting triangle. */
12818         while ((neighbor.tri != m->dummytri) &&
12819                (!otriequal(neighbor, testtri))) {
12820           if (infected(neighbor)) {
12821             /* Mark the corner of this triangle as having been tested. */
12822             setorg(neighbor, NULL);
12823           } else {
12824             /* A live triangle.  The vertex survives. */
12825             killorg = 0;
12826           }
12827           /* Walk counterclockwise about the vertex. */
12828           onextself(neighbor);
12829         }
12830         /* If we reached a boundary, we must walk clockwise as well. */
12831         if (neighbor.tri == m->dummytri) {
12832           /* Walk clockwise about the vertex. */
12833           oprev(testtri, neighbor);
12834           /* Stop upon reaching a boundary. */
12835           while (neighbor.tri != m->dummytri) {
12836             if (infected(neighbor)) {
12837             /* Mark the corner of this triangle as having been tested. */
12838               setorg(neighbor, NULL);
12839             } else {
12840               /* A live triangle.  The vertex survives. */
12841               killorg = 0;
12842             }
12843             /* Walk clockwise about the vertex. */
12844             oprevself(neighbor);
12845           }
12846         }
12847         if (killorg) {
12848           if (b->verbose > 1) {
12849             printf("    Deleting vertex (%.12g, %.12g)\n",
12850                    testvertex[0], testvertex[1]);
12851           }
12852           setvertextype(testvertex, UNDEADVERTEX);
12853           m->undeads++;
12854         }
12855       }
12856     }
12857 
12858     /* Record changes in the number of boundary edges, and disconnect */
12859     /*   dead triangles from their neighbors.                         */
12860     for (testtri.orient = 0; testtri.orient < 3; testtri.orient++) {
12861       sym(testtri, neighbor);
12862       if (neighbor.tri == m->dummytri) {
12863         /* There is no neighboring triangle on this edge, so this edge    */
12864         /*   is a boundary edge.  This triangle is being deleted, so this */
12865         /*   boundary edge is deleted.                                    */
12866         m->hullsize--;
12867       } else {
12868         /* Disconnect the triangle from its neighbor. */
12869         dissolve(neighbor);
12870         /* There is a neighboring triangle on this edge, so this edge */
12871         /*   becomes a boundary edge when this triangle is deleted.   */
12872         m->hullsize++;
12873       }
12874     }
12875     /* Return the dead triangle to the pool of triangles. */
12876     triangledealloc(m, testtri.tri);
12877     virusloop = (triangle **) traverse(&m->viri);
12878   }
12879   /* Empty the virus pool. */
12880   poolrestart(&m->viri);
12881 }
12882 
12883 /*****************************************************************************/
12884 /*                                                                           */
12885 /*  regionplague()   Spread regional attributes and/or area constraints      */
12886 /*                   (from a .poly file) throughout the mesh.                */
12887 /*                                                                           */
12888 /*  This procedure operates in two phases.  The first phase spreads an       */
12889 /*  attribute and/or an area constraint through a (segment-bounded) region.  */
12890 /*  The triangles are marked to ensure that each triangle is added to the    */
12891 /*  virus pool only once, so the procedure will terminate.                   */
12892 /*                                                                           */
12893 /*  The second phase uninfects all infected triangles, returning them to     */
12894 /*  normal.                                                                  */
12895 /*                                                                           */
12896 /*****************************************************************************/
12897 
12898 #ifdef ANSI_DECLARATORS
12899 static void regionplague(struct mesh *m, struct behavior *b,
12900                   REAL attribute, REAL area)
12901 #else /* not ANSI_DECLARATORS */
12902 static void regionplague(m, b, attribute, area)
12903 struct mesh *m;
12904 struct behavior *b;
12905 REAL attribute;
12906 REAL area;
12907 #endif /* not ANSI_DECLARATORS */
12908 
12909 {
12910   struct otri testtri;
12911   struct otri neighbor;
12912   triangle **virusloop;
12913   triangle **regiontri;
12914   struct osub neighborsubseg;
12915   vertex regionorg, regiondest, regionapex;
12916   triangle ptr;             /* Temporary variable used by sym() and onext(). */
12917   subseg sptr;                      /* Temporary variable used by tspivot(). */
12918 
12919   if (b->verbose > 1) {
12920     printf("  Marking neighbors of marked triangles.\n");
12921   }
12922   /* Loop through all the infected triangles, spreading the attribute      */
12923   /*   and/or area constraint to their neighbors, then to their neighbors' */
12924   /*   neighbors.                                                          */
12925   traversalinit(&m->viri);
12926   virusloop = (triangle **) traverse(&m->viri);
12927   while (virusloop != (triangle **) NULL) {
12928     testtri.tri = *virusloop;
12929     /* A triangle is marked as infected by messing with one of its pointers */
12930     /*   to subsegments, setting it to an illegal value.  Hence, we have to */
12931     /*   temporarily uninfect this triangle so that we can examine its      */
12932     /*   adjacent subsegments.                                              */
12933     uninfect(testtri);
12934     if (b->regionattrib) {
12935       /* Set an attribute. */
12936       setelemattribute(testtri, m->eextras, attribute);
12937     }
12938     if (b->vararea) {
12939       /* Set an area constraint. */
12940       setareabound(testtri, area);
12941     }
12942     if (b->verbose > 2) {
12943       /* Assign the triangle an orientation for convenience in */
12944       /*   checking its vertices.                              */
12945       testtri.orient = 0;
12946       org(testtri, regionorg);
12947       dest(testtri, regiondest);
12948       apex(testtri, regionapex);
12949       printf("    Checking (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
12950              regionorg[0], regionorg[1], regiondest[0], regiondest[1],
12951              regionapex[0], regionapex[1]);
12952     }
12953     /* Check each of the triangle's three neighbors. */
12954     for (testtri.orient = 0; testtri.orient < 3; testtri.orient++) {
12955       /* Find the neighbor. */
12956       sym(testtri, neighbor);
12957       /* Check for a subsegment between the triangle and its neighbor. */
12958       tspivot(testtri, neighborsubseg);
12959       /* Make sure the neighbor exists, is not already infected, and */
12960       /*   isn't protected by a subsegment.                          */
12961       if ((neighbor.tri != m->dummytri) && !infected(neighbor)
12962           && (neighborsubseg.ss == m->dummysub)) {
12963         if (b->verbose > 2) {
12964           org(neighbor, regionorg);
12965           dest(neighbor, regiondest);
12966           apex(neighbor, regionapex);
12967           printf("    Marking (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
12968                  regionorg[0], regionorg[1], regiondest[0], regiondest[1],
12969                  regionapex[0], regionapex[1]);
12970         }
12971         /* Infect the neighbor. */
12972         infect(neighbor);
12973         /* Ensure that the neighbor's neighbors will be infected. */
12974         regiontri = (triangle **) poolalloc(&m->viri);
12975         *regiontri = neighbor.tri;
12976       }
12977     }
12978     /* Remark the triangle as infected, so it doesn't get added to the */
12979     /*   virus pool again.                                             */
12980     infect(testtri);
12981     virusloop = (triangle **) traverse(&m->viri);
12982   }
12983 
12984   /* Uninfect all triangles. */
12985   if (b->verbose > 1) {
12986     printf("  Unmarking marked triangles.\n");
12987   }
12988   traversalinit(&m->viri);
12989   virusloop = (triangle **) traverse(&m->viri);
12990   while (virusloop != (triangle **) NULL) {
12991     testtri.tri = *virusloop;
12992     uninfect(testtri);
12993     virusloop = (triangle **) traverse(&m->viri);
12994   }
12995   /* Empty the virus pool. */
12996   poolrestart(&m->viri);
12997 }
12998 
12999 /*****************************************************************************/
13000 /*                                                                           */
13001 /*  carveholes()   Find the holes and infect them.  Find the area            */
13002 /*                 constraints and infect them.  Infect the convex hull.     */
13003 /*                 Spread the infection and kill triangles.  Spread the      */
13004 /*                 area constraints.                                         */
13005 /*                                                                           */
13006 /*  This routine mainly calls other routines to carry out all these          */
13007 /*  functions.                                                               */
13008 /*                                                                           */
13009 /*****************************************************************************/
13010 
13011 #ifdef ANSI_DECLARATORS
13012 static void carveholes(struct mesh *m, struct behavior *b, REAL *holelist, int holes,
13013                 REAL *regionlist, int regions)
13014 #else /* not ANSI_DECLARATORS */
13015 static void carveholes(m, b, holelist, holes, regionlist, regions)
13016 struct mesh *m;
13017 struct behavior *b;
13018 REAL *holelist;
13019 int holes;
13020 REAL *regionlist;
13021 int regions;
13022 #endif /* not ANSI_DECLARATORS */
13023 
13024 {
13025   struct otri searchtri;
13026   struct otri triangleloop;
13027   struct otri *regiontris;
13028   triangle **holetri;
13029   triangle **regiontri;
13030   vertex searchorg, searchdest;
13031   enum locateresult intersect;
13032   int i;
13033   triangle ptr;                         /* Temporary variable used by sym(). */
13034 
13035   if (!(b->quiet || (b->noholes && b->convex))) {
13036     printf("Removing unwanted triangles.\n");
13037     if (b->verbose && (holes > 0)) {
13038       printf("  Marking holes for elimination.\n");
13039     }
13040   }
13041 
13042   if (regions > 0) {
13043     /* Allocate storage for the triangles in which region points fall. */
13044     regiontris = (struct otri *) trimalloc(regions *
13045                                            (int) sizeof(struct otri));
13046   } else {
13047     regiontris = (struct otri *) NULL;
13048   }
13049 
13050   if (((holes > 0) && !b->noholes) || !b->convex || (regions > 0)) {
13051     /* Initialize a pool of viri to be used for holes, concavities, */
13052     /*   regional attributes, and/or regional area constraints.     */
13053     poolinit(&m->viri, sizeof(triangle *), VIRUSPERBLOCK, VIRUSPERBLOCK, 0);
13054   }
13055 
13056   if (!b->convex) {
13057     /* Mark as infected any unprotected triangles on the boundary. */
13058     /*   This is one way by which concavities are created.         */
13059     infecthull(m, b);
13060   }
13061 
13062   if ((holes > 0) && !b->noholes) {
13063     /* Infect each triangle in which a hole lies. */
13064     for (i = 0; i < 2 * holes; i += 2) {
13065       /* Ignore holes that aren't within the bounds of the mesh. */
13066       if ((holelist[i] >= m->xmin) && (holelist[i] <= m->xmax)
13067           && (holelist[i + 1] >= m->ymin) && (holelist[i + 1] <= m->ymax)) {
13068         /* Start searching from some triangle on the outer boundary. */
13069         searchtri.tri = m->dummytri;
13070         searchtri.orient = 0;
13071         symself(searchtri);
13072         /* Ensure that the hole is to the left of this boundary edge; */
13073         /*   otherwise, locate() will falsely report that the hole    */
13074         /*   falls within the starting triangle.                      */
13075         org(searchtri, searchorg);
13076         dest(searchtri, searchdest);
13077         if (counterclockwise(m, b, searchorg, searchdest, &holelist[i]) >
13078             0.0) {
13079           /* Find a triangle that contains the hole. */
13080           intersect = locate(m, b, &holelist[i], &searchtri);
13081           if ((intersect != OUTSIDE) && (!infected(searchtri))) {
13082             /* Infect the triangle.  This is done by marking the triangle  */
13083             /*   as infected and including the triangle in the virus pool. */
13084             infect(searchtri);
13085             holetri = (triangle **) poolalloc(&m->viri);
13086             *holetri = searchtri.tri;
13087           }
13088         }
13089       }
13090     }
13091   }
13092 
13093   /* Now, we have to find all the regions BEFORE we carve the holes, because */
13094   /*   locate() won't work when the triangulation is no longer convex.       */
13095   /*   (Incidentally, this is the reason why regional attributes and area    */
13096   /*   constraints can't be used when refining a preexisting mesh, which     */
13097   /*   might not be convex; they can only be used with a freshly             */
13098   /*   triangulated PSLG.)                                                   */
13099   if (regions > 0) {
13100     /* Find the starting triangle for each region. */
13101     for (i = 0; i < regions; i++) {
13102       regiontris[i].tri = m->dummytri;
13103       /* Ignore region points that aren't within the bounds of the mesh. */
13104       if ((regionlist[4 * i] >= m->xmin) && (regionlist[4 * i] <= m->xmax) &&
13105           (regionlist[4 * i + 1] >= m->ymin) &&
13106           (regionlist[4 * i + 1] <= m->ymax)) {
13107         /* Start searching from some triangle on the outer boundary. */
13108         searchtri.tri = m->dummytri;
13109         searchtri.orient = 0;
13110         symself(searchtri);
13111         /* Ensure that the region point is to the left of this boundary */
13112         /*   edge; otherwise, locate() will falsely report that the     */
13113         /*   region point falls within the starting triangle.           */
13114         org(searchtri, searchorg);
13115         dest(searchtri, searchdest);
13116         if (counterclockwise(m, b, searchorg, searchdest, &regionlist[4 * i]) >
13117             0.0) {
13118           /* Find a triangle that contains the region point. */
13119           intersect = locate(m, b, &regionlist[4 * i], &searchtri);
13120           if ((intersect != OUTSIDE) && (!infected(searchtri))) {
13121             /* Record the triangle for processing after the */
13122             /*   holes have been carved.                    */
13123             otricopy(searchtri, regiontris[i]);
13124           }
13125         }
13126       }
13127     }
13128   }
13129 
13130   if (m->viri.items > 0) {
13131     /* Carve the holes and concavities. */
13132     plague(m, b);
13133   }
13134   /* The virus pool should be empty now. */
13135 
13136   if (regions > 0) {
13137     if (!b->quiet) {
13138       if (b->regionattrib) {
13139         if (b->vararea) {
13140           printf("Spreading regional attributes and area constraints.\n");
13141         } else {
13142           printf("Spreading regional attributes.\n");
13143         }
13144       } else {
13145         printf("Spreading regional area constraints.\n");
13146       }
13147     }
13148     if (b->regionattrib && !b->refine) {
13149       /* Assign every triangle a regional attribute of zero. */
13150       traversalinit(&m->triangles);
13151       triangleloop.orient = 0;
13152       triangleloop.tri = triangletraverse(m);
13153       while (triangleloop.tri != (triangle *) NULL) {
13154         setelemattribute(triangleloop, m->eextras, 0.0);
13155         triangleloop.tri = triangletraverse(m);
13156       }
13157     }
13158     for (i = 0; i < regions; i++) {
13159       if (regiontris[i].tri != m->dummytri) {
13160         /* Make sure the triangle under consideration still exists. */
13161         /*   It may have been eaten by the virus.                   */
13162         if (!deadtri(regiontris[i].tri)) {
13163           /* Put one triangle in the virus pool. */
13164           infect(regiontris[i]);
13165           regiontri = (triangle **) poolalloc(&m->viri);
13166           *regiontri = regiontris[i].tri;
13167           /* Apply one region's attribute and/or area constraint. */
13168           regionplague(m, b, regionlist[4 * i + 2], regionlist[4 * i + 3]);
13169           /* The virus pool should be empty now. */
13170         }
13171       }
13172     }
13173     if (b->regionattrib && !b->refine) {
13174       /* Note the fact that each triangle has an additional attribute. */
13175       m->eextras++;
13176     }
13177   }
13178 
13179   /* Free up memory. */
13180   if (((holes > 0) && !b->noholes) || !b->convex || (regions > 0)) {
13181     pooldeinit(&m->viri);
13182   }
13183   if (regions > 0) {
13184     trifree((VOID *) regiontris);
13185   }
13186 }
13187 
13188 /**                                                                         **/
13189 /**                                                                         **/
13190 /********* Carving out holes and concavities ends here               *********/
13191 
13192 /********* Mesh quality maintenance begins here                      *********/
13193 /**                                                                         **/
13194 /**                                                                         **/
13195 
13196 /*****************************************************************************/
13197 /*                                                                           */
13198 /*  tallyencs()   Traverse the entire list of subsegments, and check each    */
13199 /*                to see if it is encroached.  If so, add it to the list.    */
13200 /*                                                                           */
13201 /*****************************************************************************/
13202 
13203 #ifndef CDT_ONLY
13204 
13205 #ifdef ANSI_DECLARATORS
13206 static void tallyencs(struct mesh *m, struct behavior *b)
13207 #else /* not ANSI_DECLARATORS */
13208 static void tallyencs(m, b)
13209 struct mesh *m;
13210 struct behavior *b;
13211 #endif /* not ANSI_DECLARATORS */
13212 
13213 {
13214   struct osub subsegloop;
13215   int dummy;
13216 
13217   traversalinit(&m->subsegs);
13218   subsegloop.ssorient = 0;
13219   subsegloop.ss = subsegtraverse(m);
13220   while (subsegloop.ss != (subseg *) NULL) {
13221     /* If the segment is encroached, add it to the list. */
13222     dummy = checkseg4encroach(m, b, &subsegloop);
13223     subsegloop.ss = subsegtraverse(m);
13224   }
13225 }
13226 
13227 #endif /* not CDT_ONLY */
13228 
13229 /*****************************************************************************/
13230 /*                                                                           */
13231 /*  precisionerror()  Print an error message for precision problems.         */
13232 /*                                                                           */
13233 /*****************************************************************************/
13234 
13235 #ifndef CDT_ONLY
13236 
13237 static void precisionerror()
13238 {
13239   printf("Try increasing the area criterion and/or reducing the minimum\n");
13240   printf("  allowable angle so that tiny triangles are not created.\n");
13241 #ifdef SINGLE
13242   printf("Alternatively, try recompiling me with double precision\n");
13243   printf("  arithmetic (by removing \"#define SINGLE\" from the\n");
13244   printf("  source file or \"-DSINGLE\" from the makefile).\n");
13245 #endif /* SINGLE */
13246 }
13247 
13248 #endif /* not CDT_ONLY */
13249 
13250 /*****************************************************************************/
13251 /*                                                                           */
13252 /*  splitencsegs()   Split all the encroached subsegments.                   */
13253 /*                                                                           */
13254 /*  Each encroached subsegment is repaired by splitting it - inserting a     */
13255 /*  vertex at or near its midpoint.  Newly inserted vertices may encroach    */
13256 /*  upon other subsegments; these are also repaired.                         */
13257 /*                                                                           */
13258 /*  `triflaws' is a flag that specifies whether one should take note of new  */
13259 /*  bad triangles that result from inserting vertices to repair encroached   */
13260 /*  subsegments.                                                             */
13261 /*                                                                           */
13262 /*****************************************************************************/
13263 
13264 #ifndef CDT_ONLY
13265 
13266 #ifdef ANSI_DECLARATORS
13267 static void splitencsegs(struct mesh *m, struct behavior *b, int triflaws)
13268 #else /* not ANSI_DECLARATORS */
13269 static void splitencsegs(m, b, triflaws)
13270 struct mesh *m;
13271 struct behavior *b;
13272 int triflaws;
13273 #endif /* not ANSI_DECLARATORS */
13274 
13275 {
13276   struct otri enctri;
13277   struct otri testtri;
13278   struct osub testsh;
13279   struct osub currentenc;
13280   struct badsubseg *encloop;
13281   vertex eorg, edest, eapex;
13282   vertex newvertex;
13283   enum insertvertexresult success;
13284   REAL segmentlength, nearestpoweroftwo;
13285   REAL split;
13286   REAL multiplier, divisor;
13287   int acuteorg, acuteorg2, acutedest, acutedest2;
13288   int dummy;
13289   int i;
13290   triangle ptr;                     /* Temporary variable used by stpivot(). */
13291   subseg sptr;                        /* Temporary variable used by snext(). */
13292 
13293   /* Note that steinerleft == -1 if an unlimited number */
13294   /*   of Steiner points is allowed.                    */
13295   while ((m->badsubsegs.items > 0) && (m->steinerleft != 0)) {
13296     traversalinit(&m->badsubsegs);
13297     encloop = badsubsegtraverse(m);
13298     while ((encloop != (struct badsubseg *) NULL) && (m->steinerleft != 0)) {
13299       sdecode(encloop->encsubseg, currentenc);
13300       sorg(currentenc, eorg);
13301       sdest(currentenc, edest);
13302       /* Make sure that this segment is still the same segment it was   */
13303       /*   when it was determined to be encroached.  If the segment was */
13304       /*   enqueued multiple times (because several newly inserted      */
13305       /*   vertices encroached it), it may have already been split.     */
13306       if (!deadsubseg(currentenc.ss) &&
13307           (eorg == encloop->subsegorg) && (edest == encloop->subsegdest)) {
13308         /* To decide where to split a segment, we need to know if the   */
13309         /*   segment shares an endpoint with an adjacent segment.       */
13310         /*   The concern is that, if we simply split every encroached   */
13311         /*   segment in its center, two adjacent segments with a small  */
13312         /*   angle between them might lead to an infinite loop; each    */
13313         /*   vertex added to split one segment will encroach upon the   */
13314         /*   other segment, which must then be split with a vertex that */
13315         /*   will encroach upon the first segment, and so on forever.   */
13316         /* To avoid this, imagine a set of concentric circles, whose    */
13317         /*   radii are powers of two, about each segment endpoint.      */
13318         /*   These concentric circles determine where the segment is    */
13319         /*   split.  (If both endpoints are shared with adjacent        */
13320         /*   segments, split the segment in the middle, and apply the   */
13321         /*   concentric circles for later splittings.)                  */
13322 
13323         /* Is the origin shared with another segment? */
13324         stpivot(currentenc, enctri);
13325         lnext(enctri, testtri);
13326         tspivot(testtri, testsh);
13327         acuteorg = testsh.ss != m->dummysub;
13328         /* Is the destination shared with another segment? */
13329         lnextself(testtri);
13330         tspivot(testtri, testsh);
13331         acutedest = testsh.ss != m->dummysub;
13332 
13333         /* If we're using Chew's algorithm (rather than Ruppert's) */
13334         /*   to define encroachment, delete free vertices from the */
13335         /*   subsegment's diametral circle.                        */
13336         if (!b->conformdel && !acuteorg && !acutedest) {
13337           apex(enctri, eapex);
13338           while ((vertextype(eapex) == FREEVERTEX) &&
13339                  ((eorg[0] - eapex[0]) * (edest[0] - eapex[0]) +
13340                   (eorg[1] - eapex[1]) * (edest[1] - eapex[1]) < 0.0)) {
13341             deletevertex(m, b, &testtri);
13342             stpivot(currentenc, enctri);
13343             apex(enctri, eapex);
13344             lprev(enctri, testtri);
13345           }
13346         }
13347 
13348         /* Now, check the other side of the segment, if there's a triangle */
13349         /*   there.                                                        */
13350         sym(enctri, testtri);
13351         if (testtri.tri != m->dummytri) {
13352           /* Is the destination shared with another segment? */
13353           lnextself(testtri);
13354           tspivot(testtri, testsh);
13355           acutedest2 = testsh.ss != m->dummysub;
13356           acutedest = acutedest || acutedest2;
13357           /* Is the origin shared with another segment? */
13358           lnextself(testtri);
13359           tspivot(testtri, testsh);
13360           acuteorg2 = testsh.ss != m->dummysub;
13361           acuteorg = acuteorg || acuteorg2;
13362 
13363           /* Delete free vertices from the subsegment's diametral circle. */
13364           if (!b->conformdel && !acuteorg2 && !acutedest2) {
13365             org(testtri, eapex);
13366             while ((vertextype(eapex) == FREEVERTEX) &&
13367                    ((eorg[0] - eapex[0]) * (edest[0] - eapex[0]) +
13368                     (eorg[1] - eapex[1]) * (edest[1] - eapex[1]) < 0.0)) {
13369               deletevertex(m, b, &testtri);
13370               sym(enctri, testtri);
13371               apex(testtri, eapex);
13372               lprevself(testtri);
13373             }
13374           }
13375         }
13376 
13377         /* Use the concentric circles if exactly one endpoint is shared */
13378         /*   with another adjacent segment.                             */
13379         if (acuteorg || acutedest) {
13380           segmentlength = sqrt((edest[0] - eorg[0]) * (edest[0] - eorg[0]) +
13381                                (edest[1] - eorg[1]) * (edest[1] - eorg[1]));
13382           /* Find the power of two that most evenly splits the segment.  */
13383           /*   The worst case is a 2:1 ratio between subsegment lengths. */
13384           nearestpoweroftwo = 1.0;
13385           while (segmentlength > 3.0 * nearestpoweroftwo) {
13386             nearestpoweroftwo *= 2.0;
13387           }
13388           while (segmentlength < 1.5 * nearestpoweroftwo) {
13389             nearestpoweroftwo *= 0.5;
13390           }
13391           /* Where do we split the segment? */
13392           split = nearestpoweroftwo / segmentlength;
13393           if (acutedest) {
13394             split = 1.0 - split;
13395           }
13396         } else {
13397           /* If we're not worried about adjacent segments, split */
13398           /*   this segment in the middle.                       */
13399           split = 0.5;
13400         }
13401 
13402         /* Create the new vertex. */
13403         newvertex = (vertex) poolalloc(&m->vertices);
13404         /* Interpolate its coordinate and attributes. */
13405         for (i = 0; i < 2 + m->nextras; i++) {
13406           newvertex[i] = eorg[i] + split * (edest[i] - eorg[i]);
13407         }
13408 
13409         if (!b->noexact) {
13410           /* Roundoff in the above calculation may yield a `newvertex'   */
13411           /*   that is not precisely collinear with `eorg' and `edest'.  */
13412           /*   Improve collinearity by one step of iterative refinement. */
13413           multiplier = counterclockwise(m, b, eorg, edest, newvertex);
13414           divisor = ((eorg[0] - edest[0]) * (eorg[0] - edest[0]) +
13415                      (eorg[1] - edest[1]) * (eorg[1] - edest[1]));
13416           if ((multiplier != 0.0) && (divisor != 0.0)) {
13417             multiplier = multiplier / divisor;
13418             /* Watch out for NANs. */
13419             if (multiplier == multiplier) {
13420               newvertex[0] += multiplier * (edest[1] - eorg[1]);
13421               newvertex[1] += multiplier * (eorg[0] - edest[0]);
13422             }
13423           }
13424         }
13425 
13426         setvertexmark(newvertex, mark(currentenc));
13427         setvertextype(newvertex, SEGMENTVERTEX);
13428         if (b->verbose > 1) {
13429           printf(
13430   "  Splitting subsegment (%.12g, %.12g) (%.12g, %.12g) at (%.12g, %.12g).\n",
13431                  eorg[0], eorg[1], edest[0], edest[1],
13432                  newvertex[0], newvertex[1]);
13433         }
13434         /* Check whether the new vertex lies on an endpoint. */
13435         if (((newvertex[0] == eorg[0]) && (newvertex[1] == eorg[1])) ||
13436             ((newvertex[0] == edest[0]) && (newvertex[1] == edest[1]))) {
13437           printf("Error:  Ran out of precision at (%.12g, %.12g).\n",
13438                  newvertex[0], newvertex[1]);
13439           printf("I attempted to split a segment to a smaller size than\n");
13440           printf("  can be accommodated by the finite precision of\n");
13441           printf("  floating point arithmetic.\n");
13442           precisionerror();
13443           triexit(1);
13444         }
13445         /* Insert the splitting vertex.  This should always succeed. */
13446         success = insertvertex(m, b, newvertex, &enctri, &currentenc,
13447                                1, triflaws);
13448         if ((success != SUCCESSFULVERTEX) && (success != ENCROACHINGVERTEX)) {
13449           printf("Internal error in splitencsegs():\n");
13450           printf("  Failure to split a segment.\n");
13451           internalerror();
13452         }
13453         if (m->steinerleft > 0) {
13454           m->steinerleft--;
13455         }
13456         /* Check the two new subsegments to see if they're encroached. */
13457         dummy = checkseg4encroach(m, b, &currentenc);
13458         snextself(currentenc);
13459         dummy = checkseg4encroach(m, b, &currentenc);
13460       }
13461 
13462       badsubsegdealloc(m, encloop);
13463       encloop = badsubsegtraverse(m);
13464     }
13465   }
13466 }
13467 
13468 #endif /* not CDT_ONLY */
13469 
13470 /*****************************************************************************/
13471 /*                                                                           */
13472 /*  tallyfaces()   Test every triangle in the mesh for quality measures.     */
13473 /*                                                                           */
13474 /*****************************************************************************/
13475 
13476 #ifndef CDT_ONLY
13477 
13478 #ifdef ANSI_DECLARATORS
13479 static void tallyfaces(struct mesh *m, struct behavior *b)
13480 #else /* not ANSI_DECLARATORS */
13481 static void tallyfaces(m, b)
13482 struct mesh *m;
13483 struct behavior *b;
13484 #endif /* not ANSI_DECLARATORS */
13485 
13486 {
13487   struct otri triangleloop;
13488 
13489   if (b->verbose) {
13490     printf("  Making a list of bad triangles.\n");
13491   }
13492   traversalinit(&m->triangles);
13493   triangleloop.orient = 0;
13494   triangleloop.tri = triangletraverse(m);
13495   while (triangleloop.tri != (triangle *) NULL) {
13496     /* If the triangle is bad, enqueue it. */
13497     testtriangle(m, b, &triangleloop);
13498     triangleloop.tri = triangletraverse(m);
13499   }
13500 }
13501 
13502 #endif /* not CDT_ONLY */
13503 
13504 /*****************************************************************************/
13505 /*                                                                           */
13506 /*  splittriangle()   Inserts a vertex at the circumcenter of a triangle.    */
13507 /*                    Deletes the newly inserted vertex if it encroaches     */
13508 /*                    upon a segment.                                        */
13509 /*                                                                           */
13510 /*****************************************************************************/
13511 
13512 #ifndef CDT_ONLY
13513 
13514 #ifdef ANSI_DECLARATORS
13515 static void splittriangle(struct mesh *m, struct behavior *b,
13516                    struct badtriang *badtri)
13517 #else /* not ANSI_DECLARATORS */
13518 static void splittriangle(m, b, badtri)
13519 struct mesh *m;
13520 struct behavior *b;
13521 struct badtriang *badtri;
13522 #endif /* not ANSI_DECLARATORS */
13523 
13524 {
13525   struct otri badotri;
13526   vertex borg, bdest, bapex;
13527   vertex newvertex;
13528   REAL xi, eta;
13529   enum insertvertexresult success;
13530   int errorflag;
13531   int i;
13532 
13533   decode(badtri->poortri, badotri);
13534   org(badotri, borg);
13535   dest(badotri, bdest);
13536   apex(badotri, bapex);
13537   /* Make sure that this triangle is still the same triangle it was      */
13538   /*   when it was tested and determined to be of bad quality.           */
13539   /*   Subsequent transformations may have made it a different triangle. */
13540   if (!deadtri(badotri.tri) && (borg == badtri->triangorg) &&
13541       (bdest == badtri->triangdest) && (bapex == badtri->triangapex)) {
13542     if (b->verbose > 1) {
13543       printf("  Splitting this triangle at its circumcenter:\n");
13544       printf("    (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n", borg[0],
13545              borg[1], bdest[0], bdest[1], bapex[0], bapex[1]);
13546     }
13547 
13548     errorflag = 0;
13549     /* Create a new vertex at the triangle's circumcenter. */
13550     newvertex = (vertex) poolalloc(&m->vertices);
13551     findcircumcenter(m, b, borg, bdest, bapex, newvertex, &xi, &eta, 1);
13552 
13553     /* Check whether the new vertex lies on a triangle vertex. */
13554     if (((newvertex[0] == borg[0]) && (newvertex[1] == borg[1])) ||
13555         ((newvertex[0] == bdest[0]) && (newvertex[1] == bdest[1])) ||
13556         ((newvertex[0] == bapex[0]) && (newvertex[1] == bapex[1]))) {
13557       if (!b->quiet) {
13558         printf(
13559              "Warning:  New vertex (%.12g, %.12g) falls on existing vertex.\n",
13560                newvertex[0], newvertex[1]);
13561         errorflag = 1;
13562       }
13563       vertexdealloc(m, newvertex);
13564     } else {
13565       for (i = 2; i < 2 + m->nextras; i++) {
13566         /* Interpolate the vertex attributes at the circumcenter. */
13567         newvertex[i] = borg[i] + xi * (bdest[i] - borg[i])
13568                               + eta * (bapex[i] - borg[i]);
13569       }
13570       /* The new vertex must be in the interior, and therefore is a */
13571       /*   free vertex with a marker of zero.                       */
13572       setvertexmark(newvertex, 0);
13573       setvertextype(newvertex, FREEVERTEX);
13574 
13575       /* Ensure that the handle `badotri' does not represent the longest  */
13576       /*   edge of the triangle.  This ensures that the circumcenter must */
13577       /*   fall to the left of this edge, so point location will work.    */
13578       /*   (If the angle org-apex-dest exceeds 90 degrees, then the       */
13579       /*   circumcenter lies outside the org-dest edge, and eta is        */
13580       /*   negative.  Roundoff error might prevent eta from being         */
13581       /*   negative when it should be, so I test eta against xi.)         */
13582       if (eta < xi) {
13583         lprevself(badotri);
13584       }
13585 
13586       /* Insert the circumcenter, searching from the edge of the triangle, */
13587       /*   and maintain the Delaunay property of the triangulation.        */
13588       success = insertvertex(m, b, newvertex, &badotri, (struct osub *) NULL,
13589                              1, 1);
13590       if (success == SUCCESSFULVERTEX) {
13591         if (m->steinerleft > 0) {
13592           m->steinerleft--;
13593         }
13594       } else if (success == ENCROACHINGVERTEX) {
13595         /* If the newly inserted vertex encroaches upon a subsegment, */
13596         /*   delete the new vertex.                                   */
13597         undovertex(m, b);
13598         if (b->verbose > 1) {
13599           printf("  Rejecting (%.12g, %.12g).\n", newvertex[0], newvertex[1]);
13600         }
13601         vertexdealloc(m, newvertex);
13602       } else if (success == VIOLATINGVERTEX) {
13603         /* Failed to insert the new vertex, but some subsegment was */
13604         /*   marked as being encroached.                            */
13605         vertexdealloc(m, newvertex);
13606       } else {                                 /* success == DUPLICATEVERTEX */
13607         /* Couldn't insert the new vertex because a vertex is already there. */
13608         if (!b->quiet) {
13609           printf(
13610             "Warning:  New vertex (%.12g, %.12g) falls on existing vertex.\n",
13611                  newvertex[0], newvertex[1]);
13612           errorflag = 1;
13613         }
13614         vertexdealloc(m, newvertex);
13615       }
13616     }
13617     if (errorflag) {
13618       if (b->verbose) {
13619         printf("  The new vertex is at the circumcenter of triangle\n");
13620         printf("    (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
13621                borg[0], borg[1], bdest[0], bdest[1], bapex[0], bapex[1]);
13622       }
13623       printf("This probably means that I am trying to refine triangles\n");
13624       printf("  to a smaller size than can be accommodated by the finite\n");
13625       printf("  precision of floating point arithmetic.  (You can be\n");
13626       printf("  sure of this if I fail to terminate.)\n");
13627       precisionerror();
13628     }
13629   }
13630 }
13631 
13632 #endif /* not CDT_ONLY */
13633 
13634 /*****************************************************************************/
13635 /*                                                                           */
13636 /*  enforcequality()   Remove all the encroached subsegments and bad         */
13637 /*                     triangles from the triangulation.                     */
13638 /*                                                                           */
13639 /*****************************************************************************/
13640 
13641 #ifndef CDT_ONLY
13642 
13643 #ifdef ANSI_DECLARATORS
13644 static void enforcequality(struct mesh *m, struct behavior *b)
13645 #else /* not ANSI_DECLARATORS */
13646 static void enforcequality(m, b)
13647 struct mesh *m;
13648 struct behavior *b;
13649 #endif /* not ANSI_DECLARATORS */
13650 
13651 {
13652   struct badtriang *badtri;
13653   int i;
13654 
13655   if (!b->quiet) {
13656     printf("Adding Steiner points to enforce quality.\n");
13657   }
13658   /* Initialize the pool of encroached subsegments. */
13659   poolinit(&m->badsubsegs, sizeof(struct badsubseg), BADSUBSEGPERBLOCK,
13660            BADSUBSEGPERBLOCK, 0);
13661   if (b->verbose) {
13662     printf("  Looking for encroached subsegments.\n");
13663   }
13664   /* Test all segments to see if they're encroached. */
13665   tallyencs(m, b);
13666   if (b->verbose && (m->badsubsegs.items > 0)) {
13667     printf("  Splitting encroached subsegments.\n");
13668   }
13669   /* Fix encroached subsegments without noting bad triangles. */
13670   splitencsegs(m, b, 0);
13671   /* At this point, if we haven't run out of Steiner points, the */
13672   /*   triangulation should be (conforming) Delaunay.            */
13673 
13674   /* Next, we worry about enforcing triangle quality. */
13675   if ((b->minangle > 0.0) || b->vararea || b->fixedarea || b->usertest) {
13676     /* Initialize the pool of bad triangles. */
13677     poolinit(&m->badtriangles, sizeof(struct badtriang), BADTRIPERBLOCK,
13678              BADTRIPERBLOCK, 0);
13679     /* Initialize the queues of bad triangles. */
13680     for (i = 0; i < 4096; i++) {
13681       m->queuefront[i] = (struct badtriang *) NULL;
13682     }
13683     m->firstnonemptyq = -1;
13684     /* Test all triangles to see if they're bad. */
13685     tallyfaces(m, b);
13686     /* Initialize the pool of recently flipped triangles. */
13687     poolinit(&m->flipstackers, sizeof(struct flipstacker), FLIPSTACKERPERBLOCK,
13688              FLIPSTACKERPERBLOCK, 0);
13689     m->checkquality = 1;
13690     if (b->verbose) {
13691       printf("  Splitting bad triangles.\n");
13692     }
13693     while ((m->badtriangles.items > 0) && (m->steinerleft != 0)) {
13694       /* Fix one bad triangle by inserting a vertex at its circumcenter. */
13695       badtri = dequeuebadtriang(m);
13696       splittriangle(m, b, badtri);
13697       if (m->badsubsegs.items > 0) {
13698         /* Put bad triangle back in queue for another try later. */
13699         enqueuebadtriang(m, b, badtri);
13700         /* Fix any encroached subsegments that resulted. */
13701         /*   Record any new bad triangles that result.   */
13702         splitencsegs(m, b, 1);
13703       } else {
13704         /* Return the bad triangle to the pool. */
13705         pooldealloc(&m->badtriangles, (VOID *) badtri);
13706       }
13707     }
13708   }
13709   /* At this point, if the "-D" switch was selected and we haven't run out  */
13710   /*   of Steiner points, the triangulation should be (conforming) Delaunay */
13711   /*   and have no low-quality triangles.                                   */
13712 
13713   /* Might we have run out of Steiner points too soon? */
13714   if (!b->quiet && b->conformdel && (m->badsubsegs.items > 0) &&
13715       (m->steinerleft == 0)) {
13716     printf("\nWarning:  I ran out of Steiner points, but the mesh has\n");
13717     if (m->badsubsegs.items == 1) {
13718       printf("  one encroached subsegment, and therefore might not be truly\n"
13719              );
13720     } else {
13721       printf("  %ld encroached subsegments, and therefore might not be truly\n"
13722              , m->badsubsegs.items);
13723     }
13724     printf("  Delaunay.  If the Delaunay property is important to you,\n");
13725     printf("  try increasing the number of Steiner points (controlled by\n");
13726     printf("  the -S switch) slightly and try again.\n\n");
13727   }
13728 }
13729 
13730 #endif /* not CDT_ONLY */
13731 
13732 /**                                                                         **/
13733 /**                                                                         **/
13734 /********* Mesh quality maintenance ends here                        *********/
13735 
13736 /*****************************************************************************/
13737 /*                                                                           */
13738 /*  highorder()   Create extra nodes for quadratic subparametric elements.   */
13739 /*                                                                           */
13740 /*****************************************************************************/
13741 
13742 #ifdef ANSI_DECLARATORS
13743 static void highorder(struct mesh *m, struct behavior *b)
13744 #else /* not ANSI_DECLARATORS */
13745 static void highorder(m, b)
13746 struct mesh *m;
13747 struct behavior *b;
13748 #endif /* not ANSI_DECLARATORS */
13749 
13750 {
13751   struct otri triangleloop, trisym;
13752   struct osub checkmark;
13753   vertex newvertex;
13754   vertex torg, tdest;
13755   int i;
13756   triangle ptr;                         /* Temporary variable used by sym(). */
13757   subseg sptr;                      /* Temporary variable used by tspivot(). */
13758 
13759   if (!b->quiet) {
13760     printf("Adding vertices for second-order triangles.\n");
13761   }
13762   /* The following line ensures that dead items in the pool of nodes    */
13763   /*   cannot be allocated for the extra nodes associated with high     */
13764   /*   order elements.  This ensures that the primary nodes (at the     */
13765   /*   corners of elements) will occur earlier in the output files, and */
13766   /*   have lower indices, than the extra nodes.                        */
13767   m->vertices.deaditemstack = (VOID *) NULL;
13768 
13769   traversalinit(&m->triangles);
13770   triangleloop.tri = triangletraverse(m);
13771   /* To loop over the set of edges, loop over all triangles, and look at   */
13772   /*   the three edges of each triangle.  If there isn't another triangle  */
13773   /*   adjacent to the edge, operate on the edge.  If there is another     */
13774   /*   adjacent triangle, operate on the edge only if the current triangle */
13775   /*   has a smaller pointer than its neighbor.  This way, each edge is    */
13776   /*   considered only once.                                               */
13777   while (triangleloop.tri != (triangle *) NULL) {
13778     for (triangleloop.orient = 0; triangleloop.orient < 3;
13779          triangleloop.orient++) {
13780       sym(triangleloop, trisym);
13781       if ((triangleloop.tri < trisym.tri) || (trisym.tri == m->dummytri)) {
13782         org(triangleloop, torg);
13783         dest(triangleloop, tdest);
13784         /* Create a new node in the middle of the edge.  Interpolate */
13785         /*   its attributes.                                         */
13786         newvertex = (vertex) poolalloc(&m->vertices);
13787         for (i = 0; i < 2 + m->nextras; i++) {
13788           newvertex[i] = 0.5 * (torg[i] + tdest[i]);
13789         }
13790         /* Set the new node's marker to zero or one, depending on */
13791         /*   whether it lies on a boundary.                       */
13792         setvertexmark(newvertex, trisym.tri == m->dummytri);
13793         setvertextype(newvertex,
13794                       trisym.tri == m->dummytri ? FREEVERTEX : SEGMENTVERTEX);
13795         if (b->usesegments) {
13796           tspivot(triangleloop, checkmark);
13797           /* If this edge is a segment, transfer the marker to the new node. */
13798           if (checkmark.ss != m->dummysub) {
13799             setvertexmark(newvertex, mark(checkmark));
13800             setvertextype(newvertex, SEGMENTVERTEX);
13801           }
13802         }
13803         if (b->verbose > 1) {
13804           printf("  Creating (%.12g, %.12g).\n", newvertex[0], newvertex[1]);
13805         }
13806         /* Record the new node in the (one or two) adjacent elements. */
13807         triangleloop.tri[m->highorderindex + triangleloop.orient] =
13808                 (triangle) newvertex;
13809         if (trisym.tri != m->dummytri) {
13810           trisym.tri[m->highorderindex + trisym.orient] = (triangle) newvertex;
13811         }
13812       }
13813     }
13814     triangleloop.tri = triangletraverse(m);
13815   }
13816 }
13817 
13818 /********* File I/O routines begin here                              *********/
13819 /**                                                                         **/
13820 /**                                                                         **/
13821 
13822 /*****************************************************************************/
13823 /*                                                                           */
13824 /*  readline()   Read a nonempty line from a file.                           */
13825 /*                                                                           */
13826 /*  A line is considered "nonempty" if it contains something that looks like */
13827 /*  a number.  Comments (prefaced by `#') are ignored.                       */
13828 /*                                                                           */
13829 /*****************************************************************************/
13830 
13831 #ifndef TRILIBRARY
13832 
13833 #ifdef ANSI_DECLARATORS
13834 char *readline(char *string, FILE *infile, char *infilename)
13835 #else /* not ANSI_DECLARATORS */
13836 char *readline(string, infile, infilename)
13837 char *string;
13838 FILE *infile;
13839 char *infilename;
13840 #endif /* not ANSI_DECLARATORS */
13841 
13842 {
13843   char *result;
13844 
13845   /* Search for something that looks like a number. */
13846   do {
13847     result = fgets(string, INPUTLINESIZE, infile);
13848     if (result == (char *) NULL) {
13849       printf("Error:  Unexpected end of file in %s.\n", infilename);
13850       triexit(1);
13851     }
13852     /* Skip anything that doesn't look like a number, a comment, */
13853     /*   or the end of a line.                                   */
13854     while ((*result != '\0') && (*result != '#')
13855            && (*result != '.') && (*result != '+') && (*result != '-')
13856            && ((*result < '0') || (*result > '9'))) {
13857       result++;
13858     }
13859   /* If it's a comment or end of line, read another line and try again. */
13860   } while ((*result == '#') || (*result == '\0'));
13861   return result;
13862 }
13863 
13864 #endif /* not TRILIBRARY */
13865 
13866 /*****************************************************************************/
13867 /*                                                                           */
13868 /*  findfield()   Find the next field of a string.                           */
13869 /*                                                                           */
13870 /*  Jumps past the current field by searching for whitespace, then jumps     */
13871 /*  past the whitespace to find the next field.                              */
13872 /*                                                                           */
13873 /*****************************************************************************/
13874 
13875 #ifndef TRILIBRARY
13876 
13877 #ifdef ANSI_DECLARATORS
13878 char *findfield(char *string)
13879 #else /* not ANSI_DECLARATORS */
13880 char *findfield(string)
13881 char *string;
13882 #endif /* not ANSI_DECLARATORS */
13883 
13884 {
13885   char *result;
13886 
13887   result = string;
13888   /* Skip the current field.  Stop upon reaching whitespace. */
13889   while ((*result != '\0') && (*result != '#')
13890          && (*result != ' ') && (*result != '\t')) {
13891     result++;
13892   }
13893   /* Now skip the whitespace and anything else that doesn't look like a */
13894   /*   number, a comment, or the end of a line.                         */
13895   while ((*result != '\0') && (*result != '#')
13896          && (*result != '.') && (*result != '+') && (*result != '-')
13897          && ((*result < '0') || (*result > '9'))) {
13898     result++;
13899   }
13900   /* Check for a comment (prefixed with `#'). */
13901   if (*result == '#') {
13902     *result = '\0';
13903   }
13904   return result;
13905 }
13906 
13907 #endif /* not TRILIBRARY */
13908 
13909 /*****************************************************************************/
13910 /*                                                                           */
13911 /*  readnodes()   Read the vertices from a file, which may be a .node or     */
13912 /*                .poly file.                                                */
13913 /*                                                                           */
13914 /*****************************************************************************/
13915 
13916 #ifndef TRILIBRARY
13917 
13918 #ifdef ANSI_DECLARATORS
13919 static void readnodes(struct mesh *m, struct behavior *b, char *nodefilename,
13920                char *polyfilename, FILE **polyfile)
13921 #else /* not ANSI_DECLARATORS */
13922 static void readnodes(m, b, nodefilename, polyfilename, polyfile)
13923 struct mesh *m;
13924 struct behavior *b;
13925 char *nodefilename;
13926 char *polyfilename;
13927 FILE **polyfile;
13928 #endif /* not ANSI_DECLARATORS */
13929 
13930 {
13931   FILE *infile;
13932   vertex vertexloop;
13933   char inputline[INPUTLINESIZE];
13934   char *stringptr;
13935   char *infilename;
13936   REAL x, y;
13937   int firstnode;
13938   int nodemarkers;
13939   int currentmarker;
13940   int i, j;
13941 
13942   if (b->poly) {
13943     /* Read the vertices from a .poly file. */
13944     if (!b->quiet) {
13945       printf("Opening %s.\n", polyfilename);
13946     }
13947     *polyfile = fopen(polyfilename, "r");
13948     if (*polyfile == (FILE *) NULL) {
13949       printf("Error:  Cannot access file %s.\n", polyfilename);
13950       triexit(1);
13951     }
13952     /* Read number of vertices, number of dimensions, number of vertex */
13953     /*   attributes, and number of boundary markers.                   */
13954     stringptr = readline(inputline, *polyfile, polyfilename);
13955     m->invertices = (int) strtol(stringptr, &stringptr, 0);
13956     stringptr = findfield(stringptr);
13957     if (*stringptr == '\0') {
13958       m->mesh_dim = 2;
13959     } else {
13960       m->mesh_dim = (int) strtol(stringptr, &stringptr, 0);
13961     }
13962     stringptr = findfield(stringptr);
13963     if (*stringptr == '\0') {
13964       m->nextras = 0;
13965     } else {
13966       m->nextras = (int) strtol(stringptr, &stringptr, 0);
13967     }
13968     stringptr = findfield(stringptr);
13969     if (*stringptr == '\0') {
13970       nodemarkers = 0;
13971     } else {
13972       nodemarkers = (int) strtol(stringptr, &stringptr, 0);
13973     }
13974     if (m->invertices > 0) {
13975       infile = *polyfile;
13976       infilename = polyfilename;
13977       m->readnodefile = 0;
13978     } else {
13979       /* If the .poly file claims there are zero vertices, that means that */
13980       /*   the vertices should be read from a separate .node file.         */
13981       m->readnodefile = 1;
13982       infilename = nodefilename;
13983     }
13984   } else {
13985     m->readnodefile = 1;
13986     infilename = nodefilename;
13987     *polyfile = (FILE *) NULL;
13988   }
13989 
13990   if (m->readnodefile) {
13991     /* Read the vertices from a .node file. */
13992     if (!b->quiet) {
13993       printf("Opening %s.\n", nodefilename);
13994     }
13995     infile = fopen(nodefilename, "r");
13996     if (infile == (FILE *) NULL) {
13997       printf("Error:  Cannot access file %s.\n", nodefilename);
13998       triexit(1);
13999     }
14000     /* Read number of vertices, number of dimensions, number of vertex */
14001     /*   attributes, and number of boundary markers.                   */
14002     stringptr = readline(inputline, infile, nodefilename);
14003     m->invertices = (int) strtol(stringptr, &stringptr, 0);
14004     stringptr = findfield(stringptr);
14005     if (*stringptr == '\0') {
14006       m->mesh_dim = 2;
14007     } else {
14008       m->mesh_dim = (int) strtol(stringptr, &stringptr, 0);
14009     }
14010     stringptr = findfield(stringptr);
14011     if (*stringptr == '\0') {
14012       m->nextras = 0;
14013     } else {
14014       m->nextras = (int) strtol(stringptr, &stringptr, 0);
14015     }
14016     stringptr = findfield(stringptr);
14017     if (*stringptr == '\0') {
14018       nodemarkers = 0;
14019     } else {
14020       nodemarkers = (int) strtol(stringptr, &stringptr, 0);
14021     }
14022   }
14023 
14024   if (m->invertices < 3) {
14025     printf("Error:  Input must have at least three input vertices.\n");
14026     triexit(1);
14027   }
14028   if (m->mesh_dim != 2) {
14029     printf("Error:  Triangle only works with two-dimensional meshes.\n");
14030     triexit(1);
14031   }
14032   if (m->nextras == 0) {
14033     b->weighted = 0;
14034   }
14035 
14036   initializevertexpool(m, b);
14037 
14038   /* Read the vertices. */
14039   for (i = 0; i < m->invertices; i++) {
14040     vertexloop = (vertex) poolalloc(&m->vertices);
14041     stringptr = readline(inputline, infile, infilename);
14042     if (i == 0) {
14043       firstnode = (int) strtol(stringptr, &stringptr, 0);
14044       if ((firstnode == 0) || (firstnode == 1)) {
14045         b->firstnumber = firstnode;
14046       }
14047     }
14048     stringptr = findfield(stringptr);
14049     if (*stringptr == '\0') {
14050       printf("Error:  Vertex %d has no x coordinate.\n", b->firstnumber + i);
14051       triexit(1);
14052     }
14053     x = (REAL) strtod(stringptr, &stringptr);
14054     stringptr = findfield(stringptr);
14055     if (*stringptr == '\0') {
14056       printf("Error:  Vertex %d has no y coordinate.\n", b->firstnumber + i);
14057       triexit(1);
14058     }
14059     y = (REAL) strtod(stringptr, &stringptr);
14060     vertexloop[0] = x;
14061     vertexloop[1] = y;
14062     /* Read the vertex attributes. */
14063     for (j = 2; j < 2 + m->nextras; j++) {
14064       stringptr = findfield(stringptr);
14065       if (*stringptr == '\0') {
14066         vertexloop[j] = 0.0;
14067       } else {
14068         vertexloop[j] = (REAL) strtod(stringptr, &stringptr);
14069       }
14070     }
14071     if (nodemarkers) {
14072       /* Read a vertex marker. */
14073       stringptr = findfield(stringptr);
14074       if (*stringptr == '\0') {
14075         setvertexmark(vertexloop, 0);
14076       } else {
14077         currentmarker = (int) strtol(stringptr, &stringptr, 0);
14078         setvertexmark(vertexloop, currentmarker);
14079       }
14080     } else {
14081       /* If no markers are specified in the file, they default to zero. */
14082       setvertexmark(vertexloop, 0);
14083     }
14084     setvertextype(vertexloop, INPUTVERTEX);
14085     /* Determine the smallest and largest x and y coordinates. */
14086     if (i == 0) {
14087       m->xmin = m->xmax = x;
14088       m->ymin = m->ymax = y;
14089     } else {
14090       m->xmin = (x < m->xmin) ? x : m->xmin;
14091       m->xmax = (x > m->xmax) ? x : m->xmax;
14092       m->ymin = (y < m->ymin) ? y : m->ymin;
14093       m->ymax = (y > m->ymax) ? y : m->ymax;
14094     }
14095   }
14096   if (m->readnodefile) {
14097     fclose(infile);
14098   }
14099 
14100   /* Nonexistent x value used as a flag to mark circle events in sweepline */
14101   /*   Delaunay algorithm.                                                 */
14102   m->xminextreme = 10 * m->xmin - 9 * m->xmax;
14103 }
14104 
14105 #endif /* not TRILIBRARY */
14106 
14107 /*****************************************************************************/
14108 /*                                                                           */
14109 /*  transfernodes()   Read the vertices from memory.                         */
14110 /*                                                                           */
14111 /*****************************************************************************/
14112 
14113 #ifdef TRILIBRARY
14114 
14115 #ifdef ANSI_DECLARATORS
14116 static void transfernodes(struct mesh *m, struct behavior *b, REAL *pointlist,
14117                    REAL *pointattriblist, int *pointmarkerlist,
14118                    int numberofpoints, int numberofpointattribs)
14119 #else /* not ANSI_DECLARATORS */
14120 static void transfernodes(m, b, pointlist, pointattriblist, pointmarkerlist,
14121                    numberofpoints, numberofpointattribs)
14122 struct mesh *m;
14123 struct behavior *b;
14124 REAL *pointlist;
14125 REAL *pointattriblist;
14126 int *pointmarkerlist;
14127 int numberofpoints;
14128 int numberofpointattribs;
14129 #endif /* not ANSI_DECLARATORS */
14130 
14131 {
14132   vertex vertexloop;
14133   REAL x, y;
14134   int i, j;
14135   int coordindex;
14136   int attribindex;
14137 
14138   m->invertices = numberofpoints;
14139   m->mesh_dim = 2;
14140   m->nextras = numberofpointattribs;
14141   m->readnodefile = 0;
14142   if (m->invertices < 3) {
14143     printf("Error:  Input must have at least three input vertices.\n");
14144     triexit(1);
14145   }
14146   if (m->nextras == 0) {
14147     b->weighted = 0;
14148   }
14149 
14150   initializevertexpool(m, b);
14151 
14152   /* Read the vertices. */
14153   coordindex = 0;
14154   attribindex = 0;
14155   for (i = 0; i < m->invertices; i++) {
14156     vertexloop = (vertex) poolalloc(&m->vertices);
14157     /* Read the vertex coordinates. */
14158     x = vertexloop[0] = pointlist[coordindex++];
14159     y = vertexloop[1] = pointlist[coordindex++];
14160     /* Read the vertex attributes. */
14161     for (j = 0; j < numberofpointattribs; j++) {
14162       vertexloop[2 + j] = pointattriblist[attribindex++];
14163     }
14164     if (pointmarkerlist != (int *) NULL) {
14165       /* Read a vertex marker. */
14166       setvertexmark(vertexloop, pointmarkerlist[i]);
14167     } else {
14168       /* If no markers are specified, they default to zero. */
14169       setvertexmark(vertexloop, 0);
14170     }
14171     setvertextype(vertexloop, INPUTVERTEX);
14172     /* Determine the smallest and largest x and y coordinates. */
14173     if (i == 0) {
14174       m->xmin = m->xmax = x;
14175       m->ymin = m->ymax = y;
14176     } else {
14177       m->xmin = (x < m->xmin) ? x : m->xmin;
14178       m->xmax = (x > m->xmax) ? x : m->xmax;
14179       m->ymin = (y < m->ymin) ? y : m->ymin;
14180       m->ymax = (y > m->ymax) ? y : m->ymax;
14181     }
14182   }
14183 
14184   /* Nonexistent x value used as a flag to mark circle events in sweepline */
14185   /*   Delaunay algorithm.                                                 */
14186   m->xminextreme = 10 * m->xmin - 9 * m->xmax;
14187 }
14188 
14189 #endif /* TRILIBRARY */
14190 
14191 /*****************************************************************************/
14192 /*                                                                           */
14193 /*  readholes()   Read the holes, and possibly regional attributes and area  */
14194 /*                constraints, from a .poly file.                            */
14195 /*                                                                           */
14196 /*****************************************************************************/
14197 
14198 #ifndef TRILIBRARY
14199 
14200 #ifdef ANSI_DECLARATORS
14201 static void readholes(struct mesh *m, struct behavior *b,
14202                FILE *polyfile, char *polyfilename, REAL **hlist, int *holes,
14203                REAL **rlist, int *regions)
14204 #else /* not ANSI_DECLARATORS */
14205 static void readholes(m, b, polyfile, polyfilename, hlist, holes, rlist, regions)
14206 struct mesh *m;
14207 struct behavior *b;
14208 FILE *polyfile;
14209 char *polyfilename;
14210 REAL **hlist;
14211 int *holes;
14212 REAL **rlist;
14213 int *regions;
14214 #endif /* not ANSI_DECLARATORS */
14215 
14216 {
14217   REAL *holelist;
14218   REAL *regionlist;
14219   char inputline[INPUTLINESIZE];
14220   char *stringptr;
14221   int index;
14222   int i;
14223 
14224   /* Read the holes. */
14225   stringptr = readline(inputline, polyfile, polyfilename);
14226   *holes = (int) strtol(stringptr, &stringptr, 0);
14227   if (*holes > 0) {
14228     holelist = (REAL *) trimalloc(2 * *holes * (int) sizeof(REAL));
14229     *hlist = holelist;
14230     for (i = 0; i < 2 * *holes; i += 2) {
14231       stringptr = readline(inputline, polyfile, polyfilename);
14232       stringptr = findfield(stringptr);
14233       if (*stringptr == '\0') {
14234         printf("Error:  Hole %d has no x coordinate.\n",
14235                b->firstnumber + (i >> 1));
14236         triexit(1);
14237       } else {
14238         holelist[i] = (REAL) strtod(stringptr, &stringptr);
14239       }
14240       stringptr = findfield(stringptr);
14241       if (*stringptr == '\0') {
14242         printf("Error:  Hole %d has no y coordinate.\n",
14243                b->firstnumber + (i >> 1));
14244         triexit(1);
14245       } else {
14246         holelist[i + 1] = (REAL) strtod(stringptr, &stringptr);
14247       }
14248     }
14249   } else {
14250     *hlist = (REAL *) NULL;
14251   }
14252 
14253 #ifndef CDT_ONLY
14254   if ((b->regionattrib || b->vararea) && !b->refine) {
14255     /* Read the area constraints. */
14256     stringptr = readline(inputline, polyfile, polyfilename);
14257     *regions = (int) strtol(stringptr, &stringptr, 0);
14258     if (*regions > 0) {
14259       regionlist = (REAL *) trimalloc(4 * *regions * (int) sizeof(REAL));
14260       *rlist = regionlist;
14261       index = 0;
14262       for (i = 0; i < *regions; i++) {
14263         stringptr = readline(inputline, polyfile, polyfilename);
14264         stringptr = findfield(stringptr);
14265         if (*stringptr == '\0') {
14266           printf("Error:  Region %d has no x coordinate.\n",
14267                  b->firstnumber + i);
14268           triexit(1);
14269         } else {
14270           regionlist[index++] = (REAL) strtod(stringptr, &stringptr);
14271         }
14272         stringptr = findfield(stringptr);
14273         if (*stringptr == '\0') {
14274           printf("Error:  Region %d has no y coordinate.\n",
14275                  b->firstnumber + i);
14276           triexit(1);
14277         } else {
14278           regionlist[index++] = (REAL) strtod(stringptr, &stringptr);
14279         }
14280         stringptr = findfield(stringptr);
14281         if (*stringptr == '\0') {
14282           printf(
14283             "Error:  Region %d has no region attribute or area constraint.\n",
14284                  b->firstnumber + i);
14285           triexit(1);
14286         } else {
14287           regionlist[index++] = (REAL) strtod(stringptr, &stringptr);
14288         }
14289         stringptr = findfield(stringptr);
14290         if (*stringptr == '\0') {
14291           regionlist[index] = regionlist[index - 1];
14292         } else {
14293           regionlist[index] = (REAL) strtod(stringptr, &stringptr);
14294         }
14295         index++;
14296       }
14297     }
14298   } else {
14299     /* Set `*regions' to zero to avoid an accidental free() later. */
14300     *regions = 0;
14301     *rlist = (REAL *) NULL;
14302   }
14303 #endif /* not CDT_ONLY */
14304 
14305   fclose(polyfile);
14306 }
14307 
14308 #endif /* not TRILIBRARY */
14309 
14310 /*****************************************************************************/
14311 /*                                                                           */
14312 /*  finishfile()   Write the command line to the output file so the user     */
14313 /*                 can remember how the file was generated.  Close the file. */
14314 /*                                                                           */
14315 /*****************************************************************************/
14316 
14317 #ifndef TRILIBRARY
14318 
14319 #ifdef ANSI_DECLARATORS
14320 static void finishfile(FILE *outfile, int argc, char **argv)
14321 #else /* not ANSI_DECLARATORS */
14322 static void finishfile(outfile, argc, argv)
14323 FILE *outfile;
14324 int argc;
14325 char **argv;
14326 #endif /* not ANSI_DECLARATORS */
14327 
14328 {
14329   int i;
14330 
14331   fprintf(outfile, "# Generated by");
14332   for (i = 0; i < argc; i++) {
14333     fprintf(outfile, " ");
14334     fputs(argv[i], outfile);
14335   }
14336   fprintf(outfile, "\n");
14337   fclose(outfile);
14338 }
14339 
14340 #endif /* not TRILIBRARY */
14341 
14342 /*****************************************************************************/
14343 /*                                                                           */
14344 /*  writenodes()   Number the vertices and write them to a .node file.       */
14345 /*                                                                           */
14346 /*  To save memory, the vertex numbers are written over the boundary markers */
14347 /*  after the vertices are written to a file.                                */
14348 /*                                                                           */
14349 /*****************************************************************************/
14350 
14351 #ifdef TRILIBRARY
14352 
14353 #ifdef ANSI_DECLARATORS
14354 static void writenodes(struct mesh *m, struct behavior *b, REAL **pointlist,
14355                 REAL **pointattriblist, int **pointmarkerlist)
14356 #else /* not ANSI_DECLARATORS */
14357 static void writenodes(m, b, pointlist, pointattriblist, pointmarkerlist)
14358 struct mesh *m;
14359 struct behavior *b;
14360 REAL **pointlist;
14361 REAL **pointattriblist;
14362 int **pointmarkerlist;
14363 #endif /* not ANSI_DECLARATORS */
14364 
14365 #else /* not TRILIBRARY */
14366 
14367 #ifdef ANSI_DECLARATORS
14368 static void writenodes(struct mesh *m, struct behavior *b, char *nodefilename,
14369                 int argc, char **argv)
14370 #else /* not ANSI_DECLARATORS */
14371 static void writenodes(m, b, nodefilename, argc, argv)
14372 struct mesh *m;
14373 struct behavior *b;
14374 char *nodefilename;
14375 int argc;
14376 char **argv;
14377 #endif /* not ANSI_DECLARATORS */
14378 
14379 #endif /* not TRILIBRARY */
14380 
14381 {
14382 #ifdef TRILIBRARY
14383   REAL *plist;
14384   REAL *palist;
14385   int *pmlist;
14386   int coordindex;
14387   int attribindex;
14388 #else /* not TRILIBRARY */
14389   FILE *outfile;
14390 #endif /* not TRILIBRARY */
14391   vertex vertexloop;
14392   LONG outvertices;
14393   int vertexnumber;
14394   int i;
14395 
14396   if (b->jettison) {
14397     outvertices = m->vertices.items - m->undeads;
14398   } else {
14399     outvertices = m->vertices.items;
14400   }
14401 
14402 #ifdef TRILIBRARY
14403   if (!b->quiet) {
14404     printf("Writing vertices.\n");
14405   }
14406   /* Allocate memory for output vertices if necessary. */
14407   if (*pointlist == (REAL *) NULL) {
14408     *pointlist = (REAL *) trimalloc((int) (outvertices * 2 * sizeof(REAL)));
14409   }
14410   /* Allocate memory for output vertex attributes if necessary. */
14411   if ((m->nextras > 0) && (*pointattriblist == (REAL *) NULL)) {
14412     *pointattriblist = (REAL *) trimalloc((int) (outvertices * m->nextras *
14413                                                  sizeof(REAL)));
14414   }
14415   /* Allocate memory for output vertex markers if necessary. */
14416   if (!b->nobound && (*pointmarkerlist == (int *) NULL)) {
14417     *pointmarkerlist = (int *) trimalloc((int) (outvertices * sizeof(int)));
14418   }
14419   plist = *pointlist;
14420   palist = *pointattriblist;
14421   pmlist = *pointmarkerlist;
14422   coordindex = 0;
14423   attribindex = 0;
14424 #else /* not TRILIBRARY */
14425   if (!b->quiet) {
14426     printf("Writing %s.\n", nodefilename);
14427   }
14428   outfile = fopen(nodefilename, "w");
14429   if (outfile == (FILE *) NULL) {
14430     printf("Error:  Cannot create file %s.\n", nodefilename);
14431     triexit(1);
14432   }
14433   /* Number of vertices, number of dimensions, number of vertex attributes, */
14434   /*   and number of boundary markers (zero or one).                        */
14435   fprintf(outfile, "%ld  %d  %d  %d\n", outvertices, m->mesh_dim,
14436           m->nextras, 1 - b->nobound);
14437 #endif /* not TRILIBRARY */
14438 
14439   traversalinit(&m->vertices);
14440   vertexnumber = b->firstnumber;
14441   vertexloop = vertextraverse(m);
14442   while (vertexloop != (vertex) NULL) {
14443     if (!b->jettison || (vertextype(vertexloop) != UNDEADVERTEX)) {
14444 #ifdef TRILIBRARY
14445       /* X and y coordinates. */
14446       plist[coordindex++] = vertexloop[0];
14447       plist[coordindex++] = vertexloop[1];
14448       /* Vertex attributes. */
14449       for (i = 0; i < m->nextras; i++) {
14450         palist[attribindex++] = vertexloop[2 + i];
14451       }
14452       if (!b->nobound) {
14453         /* Copy the boundary marker. */
14454         pmlist[vertexnumber - b->firstnumber] = vertexmark(vertexloop);
14455       }
14456 #else /* not TRILIBRARY */
14457       /* Vertex number, x and y coordinates. */
14458       fprintf(outfile, "%4d    %.17g  %.17g", vertexnumber, vertexloop[0],
14459               vertexloop[1]);
14460       for (i = 0; i < m->nextras; i++) {
14461         /* Write an attribute. */
14462         fprintf(outfile, "  %.17g", vertexloop[i + 2]);
14463       }
14464       if (b->nobound) {
14465         fprintf(outfile, "\n");
14466       } else {
14467         /* Write the boundary marker. */
14468         fprintf(outfile, "    %d\n", vertexmark(vertexloop));
14469       }
14470 #endif /* not TRILIBRARY */
14471 
14472       setvertexmark(vertexloop, vertexnumber);
14473       vertexnumber++;
14474     }
14475     vertexloop = vertextraverse(m);
14476   }
14477 
14478 #ifndef TRILIBRARY
14479   finishfile(outfile, argc, argv);
14480 #endif /* not TRILIBRARY */
14481 }
14482 
14483 /*****************************************************************************/
14484 /*                                                                           */
14485 /*  numbernodes()   Number the vertices.                                     */
14486 /*                                                                           */
14487 /*  Each vertex is assigned a marker equal to its number.                    */
14488 /*                                                                           */
14489 /*  Used when writenodes() is not called because no .node file is written.   */
14490 /*                                                                           */
14491 /*****************************************************************************/
14492 
14493 #ifdef ANSI_DECLARATORS
14494 static void numbernodes(struct mesh *m, struct behavior *b)
14495 #else /* not ANSI_DECLARATORS */
14496 static void numbernodes(m, b)
14497 struct mesh *m;
14498 struct behavior *b;
14499 #endif /* not ANSI_DECLARATORS */
14500 
14501 {
14502   vertex vertexloop;
14503   int vertexnumber;
14504 
14505   traversalinit(&m->vertices);
14506   vertexnumber = b->firstnumber;
14507   vertexloop = vertextraverse(m);
14508   while (vertexloop != (vertex) NULL) {
14509     setvertexmark(vertexloop, vertexnumber);
14510     if (!b->jettison || (vertextype(vertexloop) != UNDEADVERTEX)) {
14511       vertexnumber++;
14512     }
14513     vertexloop = vertextraverse(m);
14514   }
14515 }
14516 
14517 /*****************************************************************************/
14518 /*                                                                           */
14519 /*  writeelements()   Write the triangles to an .ele file.                   */
14520 /*                                                                           */
14521 /*****************************************************************************/
14522 
14523 #ifdef TRILIBRARY
14524 
14525 #ifdef ANSI_DECLARATORS
14526 static void writeelements(struct mesh *m, struct behavior *b,
14527                    int **trianglelist, REAL **triangleattriblist)
14528 #else /* not ANSI_DECLARATORS */
14529 static void writeelements(m, b, trianglelist, triangleattriblist)
14530 struct mesh *m;
14531 struct behavior *b;
14532 int **trianglelist;
14533 REAL **triangleattriblist;
14534 #endif /* not ANSI_DECLARATORS */
14535 
14536 #else /* not TRILIBRARY */
14537 
14538 #ifdef ANSI_DECLARATORS
14539 static void writeelements(struct mesh *m, struct behavior *b, char *elefilename,
14540                    int argc, char **argv)
14541 #else /* not ANSI_DECLARATORS */
14542 static void writeelements(m, b, elefilename, argc, argv)
14543 struct mesh *m;
14544 struct behavior *b;
14545 char *elefilename;
14546 int argc;
14547 char **argv;
14548 #endif /* not ANSI_DECLARATORS */
14549 
14550 #endif /* not TRILIBRARY */
14551 
14552 {
14553 #ifdef TRILIBRARY
14554   int *tlist;
14555   REAL *talist;
14556   int vertexindex;
14557   int attribindex;
14558 #else /* not TRILIBRARY */
14559   FILE *outfile;
14560 #endif /* not TRILIBRARY */
14561   struct otri triangleloop;
14562   vertex p1, p2, p3;
14563   vertex mid1, mid2, mid3;
14564   LONG elementnumber;
14565   int i;
14566 
14567 #ifdef TRILIBRARY
14568   if (!b->quiet) {
14569     printf("Writing triangles.\n");
14570   }
14571   /* Allocate memory for output triangles if necessary. */
14572   if (*trianglelist == (int *) NULL) {
14573     *trianglelist = (int *) trimalloc((int) (m->triangles.items *
14574                                              ((b->order + 1) * (b->order + 2) /
14575                                               2) * sizeof(int)));
14576   }
14577   /* Allocate memory for output triangle attributes if necessary. */
14578   if ((m->eextras > 0) && (*triangleattriblist == (REAL *) NULL)) {
14579     *triangleattriblist = (REAL *) trimalloc((int) (m->triangles.items *
14580                                                     m->eextras *
14581                                                     sizeof(REAL)));
14582   }
14583   tlist = *trianglelist;
14584   talist = *triangleattriblist;
14585   vertexindex = 0;
14586   attribindex = 0;
14587 #else /* not TRILIBRARY */
14588   if (!b->quiet) {
14589     printf("Writing %s.\n", elefilename);
14590   }
14591   outfile = fopen(elefilename, "w");
14592   if (outfile == (FILE *) NULL) {
14593     printf("Error:  Cannot create file %s.\n", elefilename);
14594     triexit(1);
14595   }
14596   /* Number of triangles, vertices per triangle, attributes per triangle. */
14597   fprintf(outfile, "%ld  %d  %d\n", m->triangles.items,
14598           (b->order + 1) * (b->order + 2) / 2, m->eextras);
14599 #endif /* not TRILIBRARY */
14600 
14601   traversalinit(&m->triangles);
14602   triangleloop.tri = triangletraverse(m);
14603   triangleloop.orient = 0;
14604   elementnumber = b->firstnumber;
14605   while (triangleloop.tri != (triangle *) NULL) {
14606     org(triangleloop, p1);
14607     dest(triangleloop, p2);
14608     apex(triangleloop, p3);
14609     if (b->order == 1) {
14610 #ifdef TRILIBRARY
14611       tlist[vertexindex++] = vertexmark(p1);
14612       tlist[vertexindex++] = vertexmark(p2);
14613       tlist[vertexindex++] = vertexmark(p3);
14614 #else /* not TRILIBRARY */
14615       /* Triangle number, indices for three vertices. */
14616       fprintf(outfile, "%4ld    %4d  %4d  %4d", elementnumber,
14617               vertexmark(p1), vertexmark(p2), vertexmark(p3));
14618 #endif /* not TRILIBRARY */
14619     } else {
14620       mid1 = (vertex) triangleloop.tri[m->highorderindex + 1];
14621       mid2 = (vertex) triangleloop.tri[m->highorderindex + 2];
14622       mid3 = (vertex) triangleloop.tri[m->highorderindex];
14623 #ifdef TRILIBRARY
14624       tlist[vertexindex++] = vertexmark(p1);
14625       tlist[vertexindex++] = vertexmark(p2);
14626       tlist[vertexindex++] = vertexmark(p3);
14627       tlist[vertexindex++] = vertexmark(mid1);
14628       tlist[vertexindex++] = vertexmark(mid2);
14629       tlist[vertexindex++] = vertexmark(mid3);
14630 #else /* not TRILIBRARY */
14631       /* Triangle number, indices for six vertices. */
14632       fprintf(outfile, "%4ld    %4d  %4d  %4d  %4d  %4d  %4d", elementnumber,
14633               vertexmark(p1), vertexmark(p2), vertexmark(p3), vertexmark(mid1),
14634               vertexmark(mid2), vertexmark(mid3));
14635 #endif /* not TRILIBRARY */
14636     }
14637 
14638 #ifdef TRILIBRARY
14639     for (i = 0; i < m->eextras; i++) {
14640       talist[attribindex++] = elemattribute(triangleloop, i);
14641     }
14642 #else /* not TRILIBRARY */
14643     for (i = 0; i < m->eextras; i++) {
14644       fprintf(outfile, "  %.17g", elemattribute(triangleloop, i));
14645     }
14646     fprintf(outfile, "\n");
14647 #endif /* not TRILIBRARY */
14648 
14649     triangleloop.tri = triangletraverse(m);
14650     elementnumber++;
14651   }
14652 
14653 #ifndef TRILIBRARY
14654   finishfile(outfile, argc, argv);
14655 #endif /* not TRILIBRARY */
14656 }
14657 
14658 /*****************************************************************************/
14659 /*                                                                           */
14660 /*  writepoly()   Write the segments and holes to a .poly file.              */
14661 /*                                                                           */
14662 /*****************************************************************************/
14663 
14664 #ifdef TRILIBRARY
14665 
14666 #ifdef ANSI_DECLARATORS
14667 static void writepoly(struct mesh *m, struct behavior *b,
14668                int **segmentlist, int **segmentmarkerlist)
14669 #else /* not ANSI_DECLARATORS */
14670 static void writepoly(m, b, segmentlist, segmentmarkerlist)
14671 struct mesh *m;
14672 struct behavior *b;
14673 int **segmentlist;
14674 int **segmentmarkerlist;
14675 #endif /* not ANSI_DECLARATORS */
14676 
14677 #else /* not TRILIBRARY */
14678 
14679 #ifdef ANSI_DECLARATORS
14680 static void writepoly(struct mesh *m, struct behavior *b, char *polyfilename,
14681                REAL *holelist, int holes, REAL *regionlist, int regions,
14682                int argc, char **argv)
14683 #else /* not ANSI_DECLARATORS */
14684 static void writepoly(m, b, polyfilename, holelist, holes, regionlist, regions,
14685                argc, argv)
14686 struct mesh *m;
14687 struct behavior *b;
14688 char *polyfilename;
14689 REAL *holelist;
14690 int holes;
14691 REAL *regionlist;
14692 int regions;
14693 int argc;
14694 char **argv;
14695 #endif /* not ANSI_DECLARATORS */
14696 
14697 #endif /* not TRILIBRARY */
14698 
14699 {
14700 #ifdef TRILIBRARY
14701   int *slist;
14702   int *smlist;
14703   int index;
14704 #else /* not TRILIBRARY */
14705   FILE *outfile;
14706   LONG holenumber, regionnumber;
14707 #endif /* not TRILIBRARY */
14708   struct osub subsegloop;
14709   vertex endpoint1, endpoint2;
14710   LONG subsegnumber;
14711 
14712 #ifdef TRILIBRARY
14713   if (!b->quiet) {
14714     printf("Writing segments.\n");
14715   }
14716   /* Allocate memory for output segments if necessary. */
14717   if (*segmentlist == (int *) NULL) {
14718     *segmentlist = (int *) trimalloc((int) (m->subsegs.items * 2 *
14719                                             sizeof(int)));
14720   }
14721   /* Allocate memory for output segment markers if necessary. */
14722   if (!b->nobound && (*segmentmarkerlist == (int *) NULL)) {
14723     *segmentmarkerlist = (int *) trimalloc((int) (m->subsegs.items *
14724                                                   sizeof(int)));
14725   }
14726   slist = *segmentlist;
14727   smlist = *segmentmarkerlist;
14728   index = 0;
14729 #else /* not TRILIBRARY */
14730   if (!b->quiet) {
14731     printf("Writing %s.\n", polyfilename);
14732   }
14733   outfile = fopen(polyfilename, "w");
14734   if (outfile == (FILE *) NULL) {
14735     printf("Error:  Cannot create file %s.\n", polyfilename);
14736     triexit(1);
14737   }
14738   /* The zero indicates that the vertices are in a separate .node file. */
14739   /*   Followed by number of dimensions, number of vertex attributes,   */
14740   /*   and number of boundary markers (zero or one).                    */
14741   fprintf(outfile, "%d  %d  %d  %d\n", 0, m->mesh_dim, m->nextras,
14742           1 - b->nobound);
14743   /* Number of segments, number of boundary markers (zero or one). */
14744   fprintf(outfile, "%ld  %d\n", m->subsegs.items, 1 - b->nobound);
14745 #endif /* not TRILIBRARY */
14746 
14747   traversalinit(&m->subsegs);
14748   subsegloop.ss = subsegtraverse(m);
14749   subsegloop.ssorient = 0;
14750   subsegnumber = b->firstnumber;
14751   while (subsegloop.ss != (subseg *) NULL) {
14752     sorg(subsegloop, endpoint1);
14753     sdest(subsegloop, endpoint2);
14754 #ifdef TRILIBRARY
14755     /* Copy indices of the segment's two endpoints. */
14756     slist[index++] = vertexmark(endpoint1);
14757     slist[index++] = vertexmark(endpoint2);
14758     if (!b->nobound) {
14759       /* Copy the boundary marker. */
14760       smlist[subsegnumber - b->firstnumber] = mark(subsegloop);
14761     }
14762 #else /* not TRILIBRARY */
14763     /* Segment number, indices of its two endpoints, and possibly a marker. */
14764     if (b->nobound) {
14765       fprintf(outfile, "%4ld    %4d  %4d\n", subsegnumber,
14766               vertexmark(endpoint1), vertexmark(endpoint2));
14767     } else {
14768       fprintf(outfile, "%4ld    %4d  %4d    %4d\n", subsegnumber,
14769               vertexmark(endpoint1), vertexmark(endpoint2), mark(subsegloop));
14770     }
14771 #endif /* not TRILIBRARY */
14772 
14773     subsegloop.ss = subsegtraverse(m);
14774     subsegnumber++;
14775   }
14776 
14777 #ifndef TRILIBRARY
14778 #ifndef CDT_ONLY
14779   fprintf(outfile, "%d\n", holes);
14780   if (holes > 0) {
14781     for (holenumber = 0; holenumber < holes; holenumber++) {
14782       /* Hole number, x and y coordinates. */
14783       fprintf(outfile, "%4ld   %.17g  %.17g\n", b->firstnumber + holenumber,
14784               holelist[2 * holenumber], holelist[2 * holenumber + 1]);
14785     }
14786   }
14787   if (regions > 0) {
14788     fprintf(outfile, "%d\n", regions);
14789     for (regionnumber = 0; regionnumber < regions; regionnumber++) {
14790       /* Region number, x and y coordinates, attribute, maximum area. */
14791       fprintf(outfile, "%4ld   %.17g  %.17g  %.17g  %.17g\n",
14792               b->firstnumber + regionnumber,
14793               regionlist[4 * regionnumber], regionlist[4 * regionnumber + 1],
14794               regionlist[4 * regionnumber + 2],
14795               regionlist[4 * regionnumber + 3]);
14796     }
14797   }
14798 #endif /* not CDT_ONLY */
14799 
14800   finishfile(outfile, argc, argv);
14801 #endif /* not TRILIBRARY */
14802 }
14803 
14804 /*****************************************************************************/
14805 /*                                                                           */
14806 /*  writeedges()   Write the edges to an .edge file.                         */
14807 /*                                                                           */
14808 /*****************************************************************************/
14809 
14810 #ifdef TRILIBRARY
14811 
14812 #ifdef ANSI_DECLARATORS
14813 static void writeedges(struct mesh *m, struct behavior *b,
14814                 int **edgelist, int **edgemarkerlist)
14815 #else /* not ANSI_DECLARATORS */
14816 static void writeedges(m, b, edgelist, edgemarkerlist)
14817 struct mesh *m;
14818 struct behavior *b;
14819 int **edgelist;
14820 int **edgemarkerlist;
14821 #endif /* not ANSI_DECLARATORS */
14822 
14823 #else /* not TRILIBRARY */
14824 
14825 #ifdef ANSI_DECLARATORS
14826 static void writeedges(struct mesh *m, struct behavior *b, char *edgefilename,
14827                 int argc, char **argv)
14828 #else /* not ANSI_DECLARATORS */
14829 static void writeedges(m, b, edgefilename, argc, argv)
14830 struct mesh *m;
14831 struct behavior *b;
14832 char *edgefilename;
14833 int argc;
14834 char **argv;
14835 #endif /* not ANSI_DECLARATORS */
14836 
14837 #endif /* not TRILIBRARY */
14838 
14839 {
14840 #ifdef TRILIBRARY
14841   int *elist;
14842   int *emlist;
14843   int index;
14844 #else /* not TRILIBRARY */
14845   FILE *outfile;
14846 #endif /* not TRILIBRARY */
14847   struct otri triangleloop, trisym;
14848   struct osub checkmark;
14849   vertex p1, p2;
14850   LONG edgenumber;
14851   triangle ptr;                         /* Temporary variable used by sym(). */
14852   subseg sptr;                      /* Temporary variable used by tspivot(). */
14853 
14854 #ifdef TRILIBRARY
14855   if (!b->quiet) {
14856     printf("Writing edges.\n");
14857   }
14858   /* Allocate memory for edges if necessary. */
14859   if (*edgelist == (int *) NULL) {
14860     *edgelist = (int *) trimalloc((int) (m->edges * 2 * sizeof(int)));
14861   }
14862   /* Allocate memory for edge markers if necessary. */
14863   if (!b->nobound && (*edgemarkerlist == (int *) NULL)) {
14864     *edgemarkerlist = (int *) trimalloc((int) (m->edges * sizeof(int)));
14865   }
14866   elist = *edgelist;
14867   emlist = *edgemarkerlist;
14868   index = 0;
14869 #else /* not TRILIBRARY */
14870   if (!b->quiet) {
14871     printf("Writing %s.\n", edgefilename);
14872   }
14873   outfile = fopen(edgefilename, "w");
14874   if (outfile == (FILE *) NULL) {
14875     printf("Error:  Cannot create file %s.\n", edgefilename);
14876     triexit(1);
14877   }
14878   /* Number of edges, number of boundary markers (zero or one). */
14879   fprintf(outfile, "%ld  %d\n", m->edges, 1 - b->nobound);
14880 #endif /* not TRILIBRARY */
14881 
14882   traversalinit(&m->triangles);
14883   triangleloop.tri = triangletraverse(m);
14884   edgenumber = b->firstnumber;
14885   /* To loop over the set of edges, loop over all triangles, and look at   */
14886   /*   the three edges of each triangle.  If there isn't another triangle  */
14887   /*   adjacent to the edge, operate on the edge.  If there is another     */
14888   /*   adjacent triangle, operate on the edge only if the current triangle */
14889   /*   has a smaller pointer than its neighbor.  This way, each edge is    */
14890   /*   considered only once.                                               */
14891   while (triangleloop.tri != (triangle *) NULL) {
14892     for (triangleloop.orient = 0; triangleloop.orient < 3;
14893          triangleloop.orient++) {
14894       sym(triangleloop, trisym);
14895       if ((triangleloop.tri < trisym.tri) || (trisym.tri == m->dummytri)) {
14896         org(triangleloop, p1);
14897         dest(triangleloop, p2);
14898 #ifdef TRILIBRARY
14899         elist[index++] = vertexmark(p1);
14900         elist[index++] = vertexmark(p2);
14901 #endif /* TRILIBRARY */
14902         if (b->nobound) {
14903 #ifndef TRILIBRARY
14904           /* Edge number, indices of two endpoints. */
14905           fprintf(outfile, "%4ld   %d  %d\n", edgenumber,
14906                   vertexmark(p1), vertexmark(p2));
14907 #endif /* not TRILIBRARY */
14908         } else {
14909           /* Edge number, indices of two endpoints, and a boundary marker. */
14910           /*   If there's no subsegment, the boundary marker is zero.      */
14911           if (b->usesegments) {
14912             tspivot(triangleloop, checkmark);
14913             if (checkmark.ss == m->dummysub) {
14914 #ifdef TRILIBRARY
14915               emlist[edgenumber - b->firstnumber] = 0;
14916 #else /* not TRILIBRARY */
14917               fprintf(outfile, "%4ld   %d  %d  %d\n", edgenumber,
14918                       vertexmark(p1), vertexmark(p2), 0);
14919 #endif /* not TRILIBRARY */
14920             } else {
14921 #ifdef TRILIBRARY
14922               emlist[edgenumber - b->firstnumber] = mark(checkmark);
14923 #else /* not TRILIBRARY */
14924               fprintf(outfile, "%4ld   %d  %d  %d\n", edgenumber,
14925                       vertexmark(p1), vertexmark(p2), mark(checkmark));
14926 #endif /* not TRILIBRARY */
14927             }
14928           } else {
14929 #ifdef TRILIBRARY
14930             emlist[edgenumber - b->firstnumber] = trisym.tri == m->dummytri;
14931 #else /* not TRILIBRARY */
14932             fprintf(outfile, "%4ld   %d  %d  %d\n", edgenumber,
14933                     vertexmark(p1), vertexmark(p2), trisym.tri == m->dummytri);
14934 #endif /* not TRILIBRARY */
14935           }
14936         }
14937         edgenumber++;
14938       }
14939     }
14940     triangleloop.tri = triangletraverse(m);
14941   }
14942 
14943 #ifndef TRILIBRARY
14944   finishfile(outfile, argc, argv);
14945 #endif /* not TRILIBRARY */
14946 }
14947 
14948 /*****************************************************************************/
14949 /*                                                                           */
14950 /*  writevoronoi()   Write the Voronoi diagram to a .v.node and .v.edge      */
14951 /*                   file.                                                   */
14952 /*                                                                           */
14953 /*  The Voronoi diagram is the geometric dual of the Delaunay triangulation. */
14954 /*  Hence, the Voronoi vertices are listed by traversing the Delaunay        */
14955 /*  triangles, and the Voronoi edges are listed by traversing the Delaunay   */
14956 /*  edges.                                                                   */
14957 /*                                                                           */
14958 /*  WARNING:  In order to assign numbers to the Voronoi vertices, this       */
14959 /*  procedure messes up the subsegments or the extra nodes of every          */
14960 /*  element.  Hence, you should call this procedure last.                    */
14961 /*                                                                           */
14962 /*****************************************************************************/
14963 
14964 #ifdef TRILIBRARY
14965 
14966 #ifdef ANSI_DECLARATORS
14967 static void writevoronoi(struct mesh *m, struct behavior *b, REAL **vpointlist,
14968                   REAL **vpointattriblist, int **vpointmarkerlist,
14969                   int **vedgelist, int **vedgemarkerlist, REAL **vnormlist)
14970 #else /* not ANSI_DECLARATORS */
14971 static void writevoronoi(m, b, vpointlist, vpointattriblist, vpointmarkerlist,
14972                   vedgelist, vedgemarkerlist, vnormlist)
14973 struct mesh *m;
14974 struct behavior *b;
14975 REAL **vpointlist;
14976 REAL **vpointattriblist;
14977 int **vpointmarkerlist;
14978 int **vedgelist;
14979 int **vedgemarkerlist;
14980 REAL **vnormlist;
14981 #endif /* not ANSI_DECLARATORS */
14982 
14983 #else /* not TRILIBRARY */
14984 
14985 #ifdef ANSI_DECLARATORS
14986 static void writevoronoi(struct mesh *m, struct behavior *b, char *vnodefilename,
14987                   char *vedgefilename, int argc, char **argv)
14988 #else /* not ANSI_DECLARATORS */
14989 static void writevoronoi(m, b, vnodefilename, vedgefilename, argc, argv)
14990 struct mesh *m;
14991 struct behavior *b;
14992 char *vnodefilename;
14993 char *vedgefilename;
14994 int argc;
14995 char **argv;
14996 #endif /* not ANSI_DECLARATORS */
14997 
14998 #endif /* not TRILIBRARY */
14999 
15000 {
15001 #ifdef TRILIBRARY
15002   REAL *plist;
15003   REAL *palist;
15004   int *elist;
15005   REAL *normlist;
15006   int coordindex;
15007   int attribindex;
15008 #else /* not TRILIBRARY */
15009   FILE *outfile;
15010 #endif /* not TRILIBRARY */
15011   struct otri triangleloop, trisym;
15012   vertex torg, tdest, tapex;
15013   REAL circumcenter[2];
15014   REAL xi, eta;
15015   LONG vnodenumber, vedgenumber;
15016   int p1, p2;
15017   int i;
15018   triangle ptr;                         /* Temporary variable used by sym(). */
15019 
15020 #ifdef TRILIBRARY
15021   if (!b->quiet) {
15022     printf("Writing Voronoi vertices.\n");
15023   }
15024   /* Allocate memory for Voronoi vertices if necessary. */
15025   if (*vpointlist == (REAL *) NULL) {
15026     *vpointlist = (REAL *) trimalloc((int) (m->triangles.items * 2 *
15027                                             sizeof(REAL)));
15028   }
15029   /* Allocate memory for Voronoi vertex attributes if necessary. */
15030   if (*vpointattriblist == (REAL *) NULL) {
15031     *vpointattriblist = (REAL *) trimalloc((int) (m->triangles.items *
15032                                                   m->nextras * sizeof(REAL)));
15033   }
15034   *vpointmarkerlist = (int *) NULL;
15035   plist = *vpointlist;
15036   palist = *vpointattriblist;
15037   coordindex = 0;
15038   attribindex = 0;
15039 #else /* not TRILIBRARY */
15040   if (!b->quiet) {
15041     printf("Writing %s.\n", vnodefilename);
15042   }
15043   outfile = fopen(vnodefilename, "w");
15044   if (outfile == (FILE *) NULL) {
15045     printf("Error:  Cannot create file %s.\n", vnodefilename);
15046     triexit(1);
15047   }
15048   /* Number of triangles, two dimensions, number of vertex attributes, */
15049   /*   no markers.                                                     */
15050   fprintf(outfile, "%ld  %d  %d  %d\n", m->triangles.items, 2, m->nextras, 0);
15051 #endif /* not TRILIBRARY */
15052 
15053   traversalinit(&m->triangles);
15054   triangleloop.tri = triangletraverse(m);
15055   triangleloop.orient = 0;
15056   vnodenumber = b->firstnumber;
15057   while (triangleloop.tri != (triangle *) NULL) {
15058     org(triangleloop, torg);
15059     dest(triangleloop, tdest);
15060     apex(triangleloop, tapex);
15061     findcircumcenter(m, b, torg, tdest, tapex, circumcenter, &xi, &eta, 0);
15062 #ifdef TRILIBRARY
15063     /* X and y coordinates. */
15064     plist[coordindex++] = circumcenter[0];
15065     plist[coordindex++] = circumcenter[1];
15066     for (i = 2; i < 2 + m->nextras; i++) {
15067       /* Interpolate the vertex attributes at the circumcenter. */
15068       palist[attribindex++] = torg[i] + xi * (tdest[i] - torg[i])
15069                                      + eta * (tapex[i] - torg[i]);
15070     }
15071 #else /* not TRILIBRARY */
15072     /* Voronoi vertex number, x and y coordinates. */
15073     fprintf(outfile, "%4ld    %.17g  %.17g", vnodenumber, circumcenter[0],
15074             circumcenter[1]);
15075     for (i = 2; i < 2 + m->nextras; i++) {
15076       /* Interpolate the vertex attributes at the circumcenter. */
15077       fprintf(outfile, "  %.17g", torg[i] + xi * (tdest[i] - torg[i])
15078                                          + eta * (tapex[i] - torg[i]));
15079     }
15080     fprintf(outfile, "\n");
15081 #endif /* not TRILIBRARY */
15082 
15083     * (int *) (triangleloop.tri + 6) = (int) vnodenumber;
15084     triangleloop.tri = triangletraverse(m);
15085     vnodenumber++;
15086   }
15087 
15088 #ifndef TRILIBRARY
15089   finishfile(outfile, argc, argv);
15090 #endif /* not TRILIBRARY */
15091 
15092 #ifdef TRILIBRARY
15093   if (!b->quiet) {
15094     printf("Writing Voronoi edges.\n");
15095   }
15096   /* Allocate memory for output Voronoi edges if necessary. */
15097   if (*vedgelist == (int *) NULL) {
15098     *vedgelist = (int *) trimalloc((int) (m->edges * 2 * sizeof(int)));
15099   }
15100   *vedgemarkerlist = (int *) NULL;
15101   /* Allocate memory for output Voronoi norms if necessary. */
15102   if (*vnormlist == (REAL *) NULL) {
15103     *vnormlist = (REAL *) trimalloc((int) (m->edges * 2 * sizeof(REAL)));
15104   }
15105   elist = *vedgelist;
15106   normlist = *vnormlist;
15107   coordindex = 0;
15108 #else /* not TRILIBRARY */
15109   if (!b->quiet) {
15110     printf("Writing %s.\n", vedgefilename);
15111   }
15112   outfile = fopen(vedgefilename, "w");
15113   if (outfile == (FILE *) NULL) {
15114     printf("Error:  Cannot create file %s.\n", vedgefilename);
15115     triexit(1);
15116   }
15117   /* Number of edges, zero boundary markers. */
15118   fprintf(outfile, "%ld  %d\n", m->edges, 0);
15119 #endif /* not TRILIBRARY */
15120 
15121   traversalinit(&m->triangles);
15122   triangleloop.tri = triangletraverse(m);
15123   vedgenumber = b->firstnumber;
15124   /* To loop over the set of edges, loop over all triangles, and look at   */
15125   /*   the three edges of each triangle.  If there isn't another triangle  */
15126   /*   adjacent to the edge, operate on the edge.  If there is another     */
15127   /*   adjacent triangle, operate on the edge only if the current triangle */
15128   /*   has a smaller pointer than its neighbor.  This way, each edge is    */
15129   /*   considered only once.                                               */
15130   while (triangleloop.tri != (triangle *) NULL) {
15131     for (triangleloop.orient = 0; triangleloop.orient < 3;
15132          triangleloop.orient++) {
15133       sym(triangleloop, trisym);
15134       if ((triangleloop.tri < trisym.tri) || (trisym.tri == m->dummytri)) {
15135         /* Find the number of this triangle (and Voronoi vertex). */
15136         p1 = * (int *) (triangleloop.tri + 6);
15137         if (trisym.tri == m->dummytri) {
15138           org(triangleloop, torg);
15139           dest(triangleloop, tdest);
15140 #ifdef TRILIBRARY
15141           /* Copy an infinite ray.  Index of one endpoint, and -1. */
15142           elist[coordindex] = p1;
15143           normlist[coordindex++] = tdest[1] - torg[1];
15144           elist[coordindex] = -1;
15145           normlist[coordindex++] = torg[0] - tdest[0];
15146 #else /* not TRILIBRARY */
15147           /* Write an infinite ray.  Edge number, index of one endpoint, -1, */
15148           /*   and x and y coordinates of a vector representing the          */
15149           /*   direction of the ray.                                         */
15150           fprintf(outfile, "%4ld   %d  %d   %.17g  %.17g\n", vedgenumber,
15151                   p1, -1, tdest[1] - torg[1], torg[0] - tdest[0]);
15152 #endif /* not TRILIBRARY */
15153         } else {
15154           /* Find the number of the adjacent triangle (and Voronoi vertex). */
15155           p2 = * (int *) (trisym.tri + 6);
15156           /* Finite edge.  Write indices of two endpoints. */
15157 #ifdef TRILIBRARY
15158           elist[coordindex] = p1;
15159           normlist[coordindex++] = 0.0;
15160           elist[coordindex] = p2;
15161           normlist[coordindex++] = 0.0;
15162 #else /* not TRILIBRARY */
15163           fprintf(outfile, "%4ld   %d  %d\n", vedgenumber, p1, p2);
15164 #endif /* not TRILIBRARY */
15165         }
15166         vedgenumber++;
15167       }
15168     }
15169     triangleloop.tri = triangletraverse(m);
15170   }
15171 
15172 #ifndef TRILIBRARY
15173   finishfile(outfile, argc, argv);
15174 #endif /* not TRILIBRARY */
15175 }
15176 
15177 #ifdef TRILIBRARY
15178 
15179 #ifdef ANSI_DECLARATORS
15180 static void writeneighbors(struct mesh *m, struct behavior *b, int **neighborlist)
15181 #else /* not ANSI_DECLARATORS */
15182 static void writeneighbors(m, b, neighborlist)
15183 struct mesh *m;
15184 struct behavior *b;
15185 int **neighborlist;
15186 #endif /* not ANSI_DECLARATORS */
15187 
15188 #else /* not TRILIBRARY */
15189 
15190 #ifdef ANSI_DECLARATORS
15191 static void writeneighbors(struct mesh *m, struct behavior *b, char *neighborfilename,
15192                     int argc, char **argv)
15193 #else /* not ANSI_DECLARATORS */
15194 static void writeneighbors(m, b, neighborfilename, argc, argv)
15195 struct mesh *m;
15196 struct behavior *b;
15197 char *neighborfilename;
15198 int argc;
15199 char **argv;
15200 #endif /* not ANSI_DECLARATORS */
15201 
15202 #endif /* not TRILIBRARY */
15203 
15204 {
15205 #ifdef TRILIBRARY
15206   int *nlist;
15207   int index;
15208 #else /* not TRILIBRARY */
15209   FILE *outfile;
15210 #endif /* not TRILIBRARY */
15211   struct otri triangleloop, trisym;
15212   LONG elementnumber;
15213   int neighbor1, neighbor2, neighbor3;
15214   triangle ptr;                         /* Temporary variable used by sym(). */
15215 
15216 #ifdef TRILIBRARY
15217   if (!b->quiet) {
15218     printf("Writing neighbors.\n");
15219   }
15220   /* Allocate memory for neighbors if necessary. */
15221   if (*neighborlist == (int *) NULL) {
15222     *neighborlist = (int *) trimalloc((int) (m->triangles.items * 3 *
15223                                              sizeof(int)));
15224   }
15225   nlist = *neighborlist;
15226   index = 0;
15227 #else /* not TRILIBRARY */
15228   if (!b->quiet) {
15229     printf("Writing %s.\n", neighborfilename);
15230   }
15231   outfile = fopen(neighborfilename, "w");
15232   if (outfile == (FILE *) NULL) {
15233     printf("Error:  Cannot create file %s.\n", neighborfilename);
15234     triexit(1);
15235   }
15236   /* Number of triangles, three neighbors per triangle. */
15237   fprintf(outfile, "%ld  %d\n", m->triangles.items, 3);
15238 #endif /* not TRILIBRARY */
15239 
15240   traversalinit(&m->triangles);
15241   triangleloop.tri = triangletraverse(m);
15242   triangleloop.orient = 0;
15243   elementnumber = b->firstnumber;
15244   while (triangleloop.tri != (triangle *) NULL) {
15245     * (int *) (triangleloop.tri + 6) = (int) elementnumber;
15246     triangleloop.tri = triangletraverse(m);
15247     elementnumber++;
15248   }
15249   * (int *) (m->dummytri + 6) = -1;
15250 
15251   traversalinit(&m->triangles);
15252   triangleloop.tri = triangletraverse(m);
15253   elementnumber = b->firstnumber;
15254   while (triangleloop.tri != (triangle *) NULL) {
15255     triangleloop.orient = 1;
15256     sym(triangleloop, trisym);
15257     neighbor1 = * (int *) (trisym.tri + 6);
15258     triangleloop.orient = 2;
15259     sym(triangleloop, trisym);
15260     neighbor2 = * (int *) (trisym.tri + 6);
15261     triangleloop.orient = 0;
15262     sym(triangleloop, trisym);
15263     neighbor3 = * (int *) (trisym.tri + 6);
15264 #ifdef TRILIBRARY
15265     nlist[index++] = neighbor1;
15266     nlist[index++] = neighbor2;
15267     nlist[index++] = neighbor3;
15268 #else /* not TRILIBRARY */
15269     /* Triangle number, neighboring triangle numbers. */
15270     fprintf(outfile, "%4ld    %d  %d  %d\n", elementnumber,
15271             neighbor1, neighbor2, neighbor3);
15272 #endif /* not TRILIBRARY */
15273 
15274     triangleloop.tri = triangletraverse(m);
15275     elementnumber++;
15276   }
15277 
15278 #ifndef TRILIBRARY
15279   finishfile(outfile, argc, argv);
15280 #endif /* not TRILIBRARY */
15281 }
15282 
15283 /*****************************************************************************/
15284 /*                                                                           */
15285 /*  writeoff()   Write the triangulation to an .off file.                    */
15286 /*                                                                           */
15287 /*  OFF stands for the Object File Format, a format used by the Geometry     */
15288 /*  Center's Geomview package.                                               */
15289 /*                                                                           */
15290 /*****************************************************************************/
15291 
15292 #ifndef TRILIBRARY
15293 
15294 #ifdef ANSI_DECLARATORS
15295 static void writeoff(struct mesh *m, struct behavior *b, char *offfilename,
15296               int argc, char **argv)
15297 #else /* not ANSI_DECLARATORS */
15298 static void writeoff(m, b, offfilename, argc, argv)
15299 struct mesh *m;
15300 struct behavior *b;
15301 char *offfilename;
15302 int argc;
15303 char **argv;
15304 #endif /* not ANSI_DECLARATORS */
15305 
15306 {
15307   FILE *outfile;
15308   struct otri triangleloop;
15309   vertex vertexloop;
15310   vertex p1, p2, p3;
15311   LONG outvertices;
15312 
15313   if (!b->quiet) {
15314     printf("Writing %s.\n", offfilename);
15315   }
15316 
15317   if (b->jettison) {
15318     outvertices = m->vertices.items - m->undeads;
15319   } else {
15320     outvertices = m->vertices.items;
15321   }
15322 
15323   outfile = fopen(offfilename, "w");
15324   if (outfile == (FILE *) NULL) {
15325     printf("Error:  Cannot create file %s.\n", offfilename);
15326     triexit(1);
15327   }
15328   /* Number of vertices, triangles, and edges. */
15329   fprintf(outfile, "OFF\n%ld  %ld  %ld\n", outvertices, m->triangles.items,
15330           m->edges);
15331 
15332   /* Write the vertices. */
15333   traversalinit(&m->vertices);
15334   vertexloop = vertextraverse(m);
15335   while (vertexloop != (vertex) NULL) {
15336     if (!b->jettison || (vertextype(vertexloop) != UNDEADVERTEX)) {
15337       /* The "0.0" is here because the OFF format uses 3D coordinates. */
15338       fprintf(outfile, " %.17g  %.17g  %.17g\n", vertexloop[0], vertexloop[1],
15339               0.0);
15340     }
15341     vertexloop = vertextraverse(m);
15342   }
15343 
15344   /* Write the triangles. */
15345   traversalinit(&m->triangles);
15346   triangleloop.tri = triangletraverse(m);
15347   triangleloop.orient = 0;
15348   while (triangleloop.tri != (triangle *) NULL) {
15349     org(triangleloop, p1);
15350     dest(triangleloop, p2);
15351     apex(triangleloop, p3);
15352     /* The "3" means a three-vertex polygon. */
15353     fprintf(outfile, " 3   %4d  %4d  %4d\n", vertexmark(p1) - b->firstnumber,
15354             vertexmark(p2) - b->firstnumber, vertexmark(p3) - b->firstnumber);
15355     triangleloop.tri = triangletraverse(m);
15356   }
15357   finishfile(outfile, argc, argv);
15358 }
15359 
15360 #endif /* not TRILIBRARY */
15361 
15362 /**                                                                         **/
15363 /**                                                                         **/
15364 /********* File I/O routines end here                                *********/
15365 
15366 /*****************************************************************************/
15367 /*                                                                           */
15368 /*  quality_statistics()   Print statistics about the quality of the mesh.   */
15369 /*                                                                           */
15370 /*****************************************************************************/
15371 
15372 #ifdef ANSI_DECLARATORS
15373 static void quality_statistics(struct mesh *m, struct behavior *b)
15374 #else /* not ANSI_DECLARATORS */
15375 static void quality_statistics(m, b)
15376 struct mesh *m;
15377 struct behavior *b;
15378 #endif /* not ANSI_DECLARATORS */
15379 
15380 {
15381   struct otri triangleloop;
15382   vertex p[3];
15383   REAL cossquaretable[8];
15384   REAL ratiotable[16];
15385   REAL dx[3], dy[3];
15386   REAL edgelength[3];
15387   REAL dotproduct;
15388   REAL cossquare;
15389   REAL triarea;
15390   REAL shortest, longest;
15391   REAL trilongest2;
15392   REAL smallestarea, biggestarea;
15393   REAL triminaltitude2;
15394   REAL minaltitude;
15395   REAL triaspect2;
15396   REAL worstaspect;
15397   REAL smallestangle, biggestangle;
15398   REAL radconst, degconst;
15399   int angletable[18];
15400   int aspecttable[16];
15401   int aspectindex;
15402   int tendegree;
15403   int acutebiggest;
15404   int i, ii, j, k;
15405 
15406   printf("Mesh quality statistics:\n\n");
15407   radconst = PI / 18.0;
15408   degconst = 180.0 / PI;
15409   for (i = 0; i < 8; i++) {
15410     cossquaretable[i] = cos(radconst * (REAL) (i + 1));
15411     cossquaretable[i] = cossquaretable[i] * cossquaretable[i];
15412   }
15413   for (i = 0; i < 18; i++) {
15414     angletable[i] = 0;
15415   }
15416 
15417   ratiotable[0]  =      1.5;      ratiotable[1]  =     2.0;
15418   ratiotable[2]  =      2.5;      ratiotable[3]  =     3.0;
15419   ratiotable[4]  =      4.0;      ratiotable[5]  =     6.0;
15420   ratiotable[6]  =     10.0;      ratiotable[7]  =    15.0;
15421   ratiotable[8]  =     25.0;      ratiotable[9]  =    50.0;
15422   ratiotable[10] =    100.0;      ratiotable[11] =   300.0;
15423   ratiotable[12] =   1000.0;      ratiotable[13] = 10000.0;
15424   ratiotable[14] = 100000.0;      ratiotable[15] =     0.0;
15425   for (i = 0; i < 16; i++) {
15426     aspecttable[i] = 0;
15427   }
15428 
15429   worstaspect = 0.0;
15430   minaltitude = m->xmax - m->xmin + m->ymax - m->ymin;
15431   minaltitude = minaltitude * minaltitude;
15432   shortest = minaltitude;
15433   longest = 0.0;
15434   smallestarea = minaltitude;
15435   biggestarea = 0.0;
15436   worstaspect = 0.0;
15437   smallestangle = 0.0;
15438   biggestangle = 2.0;
15439   acutebiggest = 1;
15440 
15441   traversalinit(&m->triangles);
15442   triangleloop.tri = triangletraverse(m);
15443   triangleloop.orient = 0;
15444   while (triangleloop.tri != (triangle *) NULL) {
15445     org(triangleloop, p[0]);
15446     dest(triangleloop, p[1]);
15447     apex(triangleloop, p[2]);
15448     trilongest2 = 0.0;
15449 
15450     for (i = 0; i < 3; i++) {
15451       j = plus1mod3[i];
15452       k = minus1mod3[i];
15453       dx[i] = p[j][0] - p[k][0];
15454       dy[i] = p[j][1] - p[k][1];
15455       edgelength[i] = dx[i] * dx[i] + dy[i] * dy[i];
15456       if (edgelength[i] > trilongest2) {
15457         trilongest2 = edgelength[i];
15458       }
15459       if (edgelength[i] > longest) {
15460         longest = edgelength[i];
15461       }
15462       if (edgelength[i] < shortest) {
15463         shortest = edgelength[i];
15464       }
15465     }
15466 
15467     triarea = counterclockwise(m, b, p[0], p[1], p[2]);
15468     if (triarea < smallestarea) {
15469       smallestarea = triarea;
15470     }
15471     if (triarea > biggestarea) {
15472       biggestarea = triarea;
15473     }
15474     triminaltitude2 = triarea * triarea / trilongest2;
15475     if (triminaltitude2 < minaltitude) {
15476       minaltitude = triminaltitude2;
15477     }
15478     triaspect2 = trilongest2 / triminaltitude2;
15479     if (triaspect2 > worstaspect) {
15480       worstaspect = triaspect2;
15481     }
15482     aspectindex = 0;
15483     while ((triaspect2 > ratiotable[aspectindex] * ratiotable[aspectindex])
15484            && (aspectindex < 15)) {
15485       aspectindex++;
15486     }
15487     aspecttable[aspectindex]++;
15488 
15489     for (i = 0; i < 3; i++) {
15490       j = plus1mod3[i];
15491       k = minus1mod3[i];
15492       dotproduct = dx[j] * dx[k] + dy[j] * dy[k];
15493       cossquare = dotproduct * dotproduct / (edgelength[j] * edgelength[k]);
15494       tendegree = 8;
15495       for (ii = 7; ii >= 0; ii--) {
15496         if (cossquare > cossquaretable[ii]) {
15497           tendegree = ii;
15498         }
15499       }
15500       if (dotproduct <= 0.0) {
15501         angletable[tendegree]++;
15502         if (cossquare > smallestangle) {
15503           smallestangle = cossquare;
15504         }
15505         if (acutebiggest && (cossquare < biggestangle)) {
15506           biggestangle = cossquare;
15507         }
15508       } else {
15509         angletable[17 - tendegree]++;
15510         if (acutebiggest || (cossquare > biggestangle)) {
15511           biggestangle = cossquare;
15512           acutebiggest = 0;
15513         }
15514       }
15515     }
15516     triangleloop.tri = triangletraverse(m);
15517   }
15518 
15519   shortest = sqrt(shortest);
15520   longest = sqrt(longest);
15521   minaltitude = sqrt(minaltitude);
15522   worstaspect = sqrt(worstaspect);
15523   smallestarea *= 0.5;
15524   biggestarea *= 0.5;
15525   if (smallestangle >= 1.0) {
15526     smallestangle = 0.0;
15527   } else {
15528     smallestangle = degconst * acos(sqrt(smallestangle));
15529   }
15530   if (biggestangle >= 1.0) {
15531     biggestangle = 180.0;
15532   } else {
15533     if (acutebiggest) {
15534       biggestangle = degconst * acos(sqrt(biggestangle));
15535     } else {
15536       biggestangle = 180.0 - degconst * acos(sqrt(biggestangle));
15537     }
15538   }
15539 
15540   printf("  Smallest area: %16.5g   |  Largest area: %16.5g\n",
15541          smallestarea, biggestarea);
15542   printf("  Shortest edge: %16.5g   |  Longest edge: %16.5g\n",
15543          shortest, longest);
15544   printf("  Shortest altitude: %12.5g   |  Largest aspect ratio: %8.5g\n\n",
15545          minaltitude, worstaspect);
15546 
15547   printf("  Triangle aspect ratio histogram:\n");
15548   printf("  1.1547 - %-6.6g    :  %8d    | %6.6g - %-6.6g     :  %8d\n",
15549          ratiotable[0], aspecttable[0], ratiotable[7], ratiotable[8],
15550          aspecttable[8]);
15551   for (i = 1; i < 7; i++) {
15552     printf("  %6.6g - %-6.6g    :  %8d    | %6.6g - %-6.6g     :  %8d\n",
15553            ratiotable[i - 1], ratiotable[i], aspecttable[i],
15554            ratiotable[i + 7], ratiotable[i + 8], aspecttable[i + 8]);
15555   }
15556   printf("  %6.6g - %-6.6g    :  %8d    | %6.6g -            :  %8d\n",
15557          ratiotable[6], ratiotable[7], aspecttable[7], ratiotable[14],
15558          aspecttable[15]);
15559   printf("  (Aspect ratio is longest edge divided by shortest altitude)\n\n");
15560 
15561   printf("  Smallest angle: %15.5g   |  Largest angle: %15.5g\n\n",
15562          smallestangle, biggestangle);
15563 
15564   printf("  Angle histogram:\n");
15565   for (i = 0; i < 9; i++) {
15566     printf("    %3d - %3d degrees:  %8d    |    %3d - %3d degrees:  %8d\n",
15567            i * 10, i * 10 + 10, angletable[i],
15568            i * 10 + 90, i * 10 + 100, angletable[i + 9]);
15569   }
15570   printf("\n");
15571 }
15572 
15573 /*****************************************************************************/
15574 /*                                                                           */
15575 /*  statistics()   Print all sorts of cool facts.                            */
15576 /*                                                                           */
15577 /*****************************************************************************/
15578 
15579 #ifdef ANSI_DECLARATORS
15580 static void statistics(struct mesh *m, struct behavior *b)
15581 #else /* not ANSI_DECLARATORS */
15582 static void statistics(m, b)
15583 struct mesh *m;
15584 struct behavior *b;
15585 #endif /* not ANSI_DECLARATORS */
15586 
15587 {
15588   printf("\nStatistics:\n\n");
15589   printf("  Input vertices: %d\n", m->invertices);
15590   if (b->refine) {
15591     printf("  Input triangles: %d\n", m->inelements);
15592   }
15593   if (b->poly) {
15594     printf("  Input segments: %d\n", m->insegments);
15595     if (!b->refine) {
15596       printf("  Input holes: %d\n", m->holes);
15597     }
15598   }
15599 
15600   printf("\n  Mesh vertices: %" PRIu "\n", m->vertices.items - m->undeads);
15601   printf("  Mesh triangles: %" PRIu "\n", m->triangles.items);
15602   printf("  Mesh edges: %" PRIu "\n", m->edges);
15603   printf("  Mesh exterior boundary edges: %" PRIu "\n", m->hullsize); if (b->poly || b->refine) {
15604     printf("  Mesh interior boundary edges: %" PRIu "\n", m->subsegs.items - m->hullsize);
15605     printf("  Mesh subsegments (constrained edges): %" PRIu "\n", m->subsegs.items);
15606   }
15607   printf("\n");
15608 
15609   if (b->verbose) {
15610     quality_statistics(m, b);
15611     printf("Memory allocation statistics:\n\n");
15612     printf("  Maximum number of vertices: %" PRIu "\n", m->vertices.maxitems);
15613     printf("  Maximum number of triangles: %" PRIu "\n", m->triangles.maxitems);
15614     if (m->subsegs.maxitems > 0) {
15615       printf("  Maximum number of subsegments: %" PRIu "\n", m->subsegs.maxitems);
15616     }
15617     if (m->viri.maxitems > 0) {
15618       printf("  Maximum number of viri: %" PRIu "\n", m->viri.maxitems);
15619     }
15620     if (m->badsubsegs.maxitems > 0) {
15621       printf("  Maximum number of encroached subsegments: %" PRIu "\n", m->badsubsegs.maxitems);
15622     }
15623     if (m->badtriangles.maxitems > 0) {
15624       printf("  Maximum number of bad triangles: %" PRIu "\n", m->badtriangles.maxitems);
15625     }
15626     if (m->flipstackers.maxitems > 0) {
15627       printf("  Maximum number of stacked triangle flips: %" PRIu "\n", m->flipstackers.maxitems);
15628     }
15629     if (m->splaynodes.maxitems > 0) {
15630       printf("  Maximum number of splay tree nodes: %" PRIu "\n", m->splaynodes.maxitems);
15631     }
15632     printf("  Approximate heap memory use (bytes): %" PRIu "\n\n",
15633            m->vertices.maxitems * m->vertices.itembytes +
15634            m->triangles.maxitems * m->triangles.itembytes +
15635            m->subsegs.maxitems * m->subsegs.itembytes +
15636            m->viri.maxitems * m->viri.itembytes +
15637            m->badsubsegs.maxitems * m->badsubsegs.itembytes +
15638            m->badtriangles.maxitems * m->badtriangles.itembytes +
15639            m->flipstackers.maxitems * m->flipstackers.itembytes +
15640            m->splaynodes.maxitems * m->splaynodes.itembytes);
15641 
15642     printf("Algorithmic statistics:\n\n");
15643     if (!b->weighted) {
15644       printf("  Number of incircle tests: %" PRIu "\n", m->incirclecount);
15645     } else {
15646       printf("  Number of 3D orientation tests: %" PRIu "\n", m->orient3dcount);
15647     }
15648     printf("  Number of 2D orientation tests: %" PRIu "\n", m->counterclockcount);
15649     if (m->hyperbolacount > 0) {
15650       printf("  Number of right-of-hyperbola tests: %" PRIu "\n", m->hyperbolacount);
15651     }
15652     if (m->circletopcount > 0) {
15653       printf("  Number of circle top computations: %" PRIu "\n", m->circletopcount);
15654     }
15655     if (m->circumcentercount > 0) {
15656       printf("  Number of triangle circumcenter computations: %" PRIu "\n", m->circumcentercount);
15657     }
15658     printf("\n");
15659   }
15660 }
15661 
15662 /*****************************************************************************/
15663 /*                                                                           */
15664 /*  main() or triangulate()   Gosh, do everything.                           */
15665 /*                                                                           */
15666 /*  The sequence is roughly as follows.  Many of these steps can be skipped, */
15667 /*  depending on the command line switches.                                  */
15668 /*                                                                           */
15669 /*  - Initialize constants and parse the command line.                       */
15670 /*  - Read the vertices from a file and either                               */
15671 /*    - triangulate them (no -r), or                                         */
15672 /*    - read an old mesh from files and reconstruct it (-r).                 */
15673 /*  - Insert the PSLG segments (-p), and possibly segments on the convex     */
15674 /*      hull (-c).                                                           */
15675 /*  - Read the holes (-p), regional attributes (-pA), and regional area      */
15676 /*      constraints (-pa).  Carve the holes and concavities, and spread the  */
15677 /*      regional attributes and area constraints.                            */
15678 /*  - Enforce the constraints on minimum angle (-q) and maximum area (-a).   */
15679 /*      Also enforce the conforming Delaunay property (-q and -a).           */
15680 /*  - Compute the number of edges in the resulting mesh.                     */
15681 /*  - Promote the mesh's linear triangles to higher order elements (-o).     */
15682 /*  - Write the output files and print the statistics.                       */
15683 /*  - Check the consistency and Delaunay property of the mesh (-C).          */
15684 /*                                                                           */
15685 /*****************************************************************************/
15686 
15687 #ifdef TRILIBRARY
15688 
15689 #ifdef ANSI_DECLARATORS
15690 void triangulate(char *triswitches, struct triangulateio *in,
15691                  struct triangulateio *out, struct triangulateio *vorout)
15692 #else /* not ANSI_DECLARATORS */
15693 void triangulate(triswitches, in, out, vorout)
15694 char *triswitches;
15695 struct triangulateio *in;
15696 struct triangulateio *out;
15697 struct triangulateio *vorout;
15698 #endif /* not ANSI_DECLARATORS */
15699 
15700 #else /* not TRILIBRARY */
15701 
15702 #ifdef ANSI_DECLARATORS
15703 int main(int argc, char **argv)
15704 #else /* not ANSI_DECLARATORS */
15705 int main(argc, argv)
15706 int argc;
15707 char **argv;
15708 #endif /* not ANSI_DECLARATORS */
15709 
15710 #endif /* not TRILIBRARY */
15711 
15712 {
15713   struct mesh m;
15714   struct behavior b;
15715   REAL *holearray;                                        /* Array of holes. */
15716   REAL *regionarray;   /* Array of regional attributes and area constraints. */
15717 #ifndef TRILIBRARY
15718   FILE *polyfile;
15719 #endif /* not TRILIBRARY */
15720 #ifndef NO_TIMER
15721   /* Variables for timing the performance of Triangle.  The types are */
15722   /*   defined in sys/time.h.                                         */
15723   struct timeval tv0, tv1, tv2, tv3, tv4, tv5, tv6;
15724   struct timezone tz;
15725 #endif /* not NO_TIMER */
15726 
15727 #ifndef NO_TIMER
15728   gettimeofday(&tv0, &tz);
15729 #endif /* not NO_TIMER */
15730 
15731   triangleinit(&m);
15732 #ifdef TRILIBRARY
15733   parsecommandline(1, &triswitches, &b);
15734 #else /* not TRILIBRARY */
15735   parsecommandline(argc, argv, &b);
15736 #endif /* not TRILIBRARY */
15737   m.steinerleft = b.steiner;
15738 
15739 #ifdef TRILIBRARY
15740   transfernodes(&m, &b, in->pointlist, in->pointattributelist,
15741                 in->pointmarkerlist, in->numberofpoints,
15742                 in->numberofpointattributes);
15743 #else /* not TRILIBRARY */
15744   readnodes(&m, &b, b.innodefilename, b.inpolyfilename, &polyfile);
15745 #endif /* not TRILIBRARY */
15746 
15747 #ifndef NO_TIMER
15748   if (!b.quiet) {
15749     gettimeofday(&tv1, &tz);
15750   }
15751 #endif /* not NO_TIMER */
15752 
15753 #ifdef CDT_ONLY
15754   m.hullsize = delaunay(&m, &b);                /* Triangulate the vertices. */
15755 #else /* not CDT_ONLY */
15756   if (b.refine) {
15757     /* Read and reconstruct a mesh. */
15758 #ifdef TRILIBRARY
15759     m.hullsize = reconstruct(&m, &b, in->trianglelist,
15760                              in->triangleattributelist, in->trianglearealist,
15761                              in->numberoftriangles, in->numberofcorners,
15762                              in->numberoftriangleattributes,
15763                              in->segmentlist, in->segmentmarkerlist,
15764                              in->numberofsegments);
15765 #else /* not TRILIBRARY */
15766     m.hullsize = reconstruct(&m, &b, b.inelefilename, b.areafilename,
15767                              b.inpolyfilename, polyfile);
15768 #endif /* not TRILIBRARY */
15769   } else {
15770     m.hullsize = delaunay(&m, &b);              /* Triangulate the vertices. */
15771   }
15772 #endif /* not CDT_ONLY */
15773 
15774 #ifndef NO_TIMER
15775   if (!b.quiet) {
15776     gettimeofday(&tv2, &tz);
15777     if (b.refine) {
15778       printf("Mesh reconstruction");
15779     } else {
15780       printf("Delaunay");
15781     }
15782     printf(" milliseconds:  %ld\n", 1000l * (tv2.tv_sec - tv1.tv_sec) +
15783            (tv2.tv_usec - tv1.tv_usec) / 1000l);
15784   }
15785 #endif /* not NO_TIMER */
15786 
15787   /* Ensure that no vertex can be mistaken for a triangular bounding */
15788   /*   box vertex in insertvertex().                                 */
15789   m.infvertex1 = (vertex) NULL;
15790   m.infvertex2 = (vertex) NULL;
15791   m.infvertex3 = (vertex) NULL;
15792 
15793   if (b.usesegments) {
15794     m.checksegments = 1;                /* Segments will be introduced next. */
15795     if (!b.refine) {
15796       /* Insert PSLG segments and/or convex hull segments. */
15797 #ifdef TRILIBRARY
15798       formskeleton(&m, &b, in->segmentlist,
15799                    in->segmentmarkerlist, in->numberofsegments);
15800 #else /* not TRILIBRARY */
15801       formskeleton(&m, &b, polyfile, b.inpolyfilename);
15802 #endif /* not TRILIBRARY */
15803     }
15804   }
15805 
15806 #ifndef NO_TIMER
15807   if (!b.quiet) {
15808     gettimeofday(&tv3, &tz);
15809     if (b.usesegments && !b.refine) {
15810       printf("Segment milliseconds:  %ld\n",
15811              1000l * (tv3.tv_sec - tv2.tv_sec) +
15812              (tv3.tv_usec - tv2.tv_usec) / 1000l);
15813     }
15814   }
15815 #endif /* not NO_TIMER */
15816 
15817   if (b.poly && (m.triangles.items > 0)) {
15818 #ifdef TRILIBRARY
15819     holearray = in->holelist;
15820     m.holes = in->numberofholes;
15821     regionarray = in->regionlist;
15822     m.regions = in->numberofregions;
15823 #else /* not TRILIBRARY */
15824     readholes(&m, &b, polyfile, b.inpolyfilename, &holearray, &m.holes,
15825               &regionarray, &m.regions);
15826 #endif /* not TRILIBRARY */
15827     if (!b.refine) {
15828       /* Carve out holes and concavities. */
15829       carveholes(&m, &b, holearray, m.holes, regionarray, m.regions);
15830     }
15831   } else {
15832     /* Without a PSLG, there can be no holes or regional attributes   */
15833     /*   or area constraints.  The following are set to zero to avoid */
15834     /*   an accidental free() later.                                  */
15835     m.holes = 0;
15836     m.regions = 0;
15837   }
15838 
15839 #ifndef NO_TIMER
15840   if (!b.quiet) {
15841     gettimeofday(&tv4, &tz);
15842     if (b.poly && !b.refine) {
15843       printf("Hole milliseconds:  %ld\n", 1000l * (tv4.tv_sec - tv3.tv_sec) +
15844              (tv4.tv_usec - tv3.tv_usec) / 1000l);
15845     }
15846   }
15847 #endif /* not NO_TIMER */
15848 
15849 #ifndef CDT_ONLY
15850   if (b.quality && (m.triangles.items > 0)) {
15851     enforcequality(&m, &b);           /* Enforce angle and area constraints. */
15852   }
15853 #endif /* not CDT_ONLY */
15854 
15855 #ifndef NO_TIMER
15856   if (!b.quiet) {
15857     gettimeofday(&tv5, &tz);
15858 #ifndef CDT_ONLY
15859     if (b.quality) {
15860       printf("Quality milliseconds:  %ld\n",
15861              1000l * (tv5.tv_sec - tv4.tv_sec) +
15862              (tv5.tv_usec - tv4.tv_usec) / 1000l);
15863     }
15864 #endif /* not CDT_ONLY */
15865   }
15866 #endif /* not NO_TIMER */
15867 
15868   /* Calculate the number of edges. */
15869   m.edges = (3l * m.triangles.items + m.hullsize) / 2l;
15870 
15871   if (b.order > 1) {
15872     highorder(&m, &b);       /* Promote elements to higher polynomial order. */
15873   }
15874   if (!b.quiet) {
15875     printf("\n");
15876   }
15877 
15878 #ifdef TRILIBRARY
15879   if (b.jettison) {
15880     out->numberofpoints = m.vertices.items - m.undeads;
15881   } else {
15882     out->numberofpoints = m.vertices.items;
15883   }
15884   out->numberofpointattributes = m.nextras;
15885   out->numberoftriangles = m.triangles.items;
15886   out->numberofcorners = (b.order + 1) * (b.order + 2) / 2;
15887   out->numberoftriangleattributes = m.eextras;
15888   out->numberofedges = m.edges;
15889   if (b.usesegments) {
15890     out->numberofsegments = m.subsegs.items;
15891   } else {
15892     out->numberofsegments = m.hullsize;
15893   }
15894   if (vorout != (struct triangulateio *) NULL) {
15895     vorout->numberofpoints = m.triangles.items;
15896     vorout->numberofpointattributes = m.nextras;
15897     vorout->numberofedges = m.edges;
15898   }
15899 #endif /* TRILIBRARY */
15900   /* If not using iteration numbers, don't write a .node file if one was */
15901   /*   read, because the original one would be overwritten!              */
15902   if (b.nonodewritten || (b.noiterationnum && m.readnodefile)) {
15903     if (!b.quiet) {
15904 #ifdef TRILIBRARY
15905       printf("NOT writing vertices.\n");
15906 #else /* not TRILIBRARY */
15907       printf("NOT writing a .node file.\n");
15908 #endif /* not TRILIBRARY */
15909     }
15910     numbernodes(&m, &b);         /* We must remember to number the vertices. */
15911   } else {
15912     /* writenodes() numbers the vertices too. */
15913 #ifdef TRILIBRARY
15914     writenodes(&m, &b, &out->pointlist, &out->pointattributelist,
15915                &out->pointmarkerlist);
15916 #else /* not TRILIBRARY */
15917     writenodes(&m, &b, b.outnodefilename, argc, argv);
15918 #endif /* TRILIBRARY */
15919   }
15920   if (b.noelewritten) {
15921     if (!b.quiet) {
15922 #ifdef TRILIBRARY
15923       printf("NOT writing triangles.\n");
15924 #else /* not TRILIBRARY */
15925       printf("NOT writing an .ele file.\n");
15926 #endif /* not TRILIBRARY */
15927     }
15928   } else {
15929 #ifdef TRILIBRARY
15930     writeelements(&m, &b, &out->trianglelist, &out->triangleattributelist);
15931 #else /* not TRILIBRARY */
15932     writeelements(&m, &b, b.outelefilename, argc, argv);
15933 #endif /* not TRILIBRARY */
15934   }
15935   /* The -c switch (convex switch) causes a PSLG to be written */
15936   /*   even if none was read.                                  */
15937   if (b.poly || b.convex) {
15938     /* If not using iteration numbers, don't overwrite the .poly file. */
15939     if (b.nopolywritten || b.noiterationnum) {
15940       if (!b.quiet) {
15941 #ifdef TRILIBRARY
15942         printf("NOT writing segments.\n");
15943 #else /* not TRILIBRARY */
15944         printf("NOT writing a .poly file.\n");
15945 #endif /* not TRILIBRARY */
15946       }
15947     } else {
15948 #ifdef TRILIBRARY
15949       writepoly(&m, &b, &out->segmentlist, &out->segmentmarkerlist);
15950       out->numberofholes = m.holes;
15951       out->numberofregions = m.regions;
15952       if (b.poly) {
15953         out->holelist = in->holelist;
15954         out->regionlist = in->regionlist;
15955       } else {
15956         out->holelist = (REAL *) NULL;
15957         out->regionlist = (REAL *) NULL;
15958       }
15959 #else /* not TRILIBRARY */
15960       writepoly(&m, &b, b.outpolyfilename, holearray, m.holes, regionarray,
15961                 m.regions, argc, argv);
15962 #endif /* not TRILIBRARY */
15963     }
15964   }
15965 #ifndef TRILIBRARY
15966 #ifndef CDT_ONLY
15967   if (m.regions > 0) {
15968     trifree((VOID *) regionarray);
15969   }
15970 #endif /* not CDT_ONLY */
15971   if (m.holes > 0) {
15972     trifree((VOID *) holearray);
15973   }
15974   if (b.geomview) {
15975     writeoff(&m, &b, b.offfilename, argc, argv);
15976   }
15977 #endif /* not TRILIBRARY */
15978   if (b.edgesout) {
15979 #ifdef TRILIBRARY
15980     writeedges(&m, &b, &out->edgelist, &out->edgemarkerlist);
15981 #else /* not TRILIBRARY */
15982     writeedges(&m, &b, b.edgefilename, argc, argv);
15983 #endif /* not TRILIBRARY */
15984   }
15985   if (b.voronoi) {
15986 #ifdef TRILIBRARY
15987     writevoronoi(&m, &b, &vorout->pointlist, &vorout->pointattributelist,
15988                  &vorout->pointmarkerlist, &vorout->edgelist,
15989                  &vorout->edgemarkerlist, &vorout->normlist);
15990 #else /* not TRILIBRARY */
15991     writevoronoi(&m, &b, b.vnodefilename, b.vedgefilename, argc, argv);
15992 #endif /* not TRILIBRARY */
15993   }
15994   if (b.neighbors) {
15995 #ifdef TRILIBRARY
15996     writeneighbors(&m, &b, &out->neighborlist);
15997 #else /* not TRILIBRARY */
15998     writeneighbors(&m, &b, b.neighborfilename, argc, argv);
15999 #endif /* not TRILIBRARY */
16000   }
16001 
16002   if (!b.quiet) {
16003 #ifndef NO_TIMER
16004     gettimeofday(&tv6, &tz);
16005     printf("\nOutput milliseconds:  %ld\n",
16006            1000l * (tv6.tv_sec - tv5.tv_sec) +
16007            (tv6.tv_usec - tv5.tv_usec) / 1000l);
16008     printf("Total running milliseconds:  %ld\n",
16009            1000l * (tv6.tv_sec - tv0.tv_sec) +
16010            (tv6.tv_usec - tv0.tv_usec) / 1000l);
16011 #endif /* not NO_TIMER */
16012 
16013     statistics(&m, &b);
16014   }
16015 
16016 #ifndef REDUCED
16017   if (b.docheck) {
16018     checkmesh(&m, &b);
16019     checkdelaunay(&m, &b);
16020   }
16021 #endif /* not REDUCED */
16022 
16023   triangledeinit(&m, &b);
16024 #ifndef TRILIBRARY
16025   return 0;
16026 #endif /* not TRILIBRARY */
16027 }
16028