1 /*****************************************************************************/
2 /*                                                                           */
3 /*      888888888        ,o,                          / 888                  */
4 /*         888    88o88o  "    o8888o  88o8888o o88888o 888  o88888o         */
5 /*         888    888    888       88b 888  888 888 888 888 d888  88b        */
6 /*         888    888    888  o88^o888 888  888 "88888" 888 8888oo888        */
7 /*         888    888    888 C888  888 888  888  /      888 q888             */
8 /*         888    888    888  "88o^888 888  888 Cb      888  "88oooo"        */
9 /*                                              "8oo8D                       */
10 /*                                                                           */
11 /*  A Two-Dimensional Quality Mesh Generator and Delaunay Triangulator.      */
12 /*  (triangle.c)                                                             */
13 /*                                                                           */
14 /*  Version 1.6                                                              */
15 /*  July 28, 2005                                                            */
16 /*                                                                           */
17 /*  Copyright 1993, 1995, 1997, 1998, 2002, 2005                             */
18 /*  Jonathan Richard Shewchuk                                                */
19 /*  2360 Woolsey #H                                                          */
20 /*  Berkeley, California  94705-1927                                         */
21 /*  jrs@cs.berkeley.edu                                                      */
22 /*                                                                           */
23 /*  This program may be freely redistributed under the condition that the    */
24 /*    copyright notices (including this entire header and the copyright      */
25 /*    notice printed when the `-h' switch is selected) are not removed, and  */
26 /*    no compensation is received.  Private, research, and institutional     */
27 /*    use is free.  You may distribute modified versions of this code UNDER  */
28 /*    THE CONDITION THAT THIS CODE AND ANY MODIFICATIONS MADE TO IT IN THE   */
29 /*    SAME FILE REMAIN UNDER COPYRIGHT OF THE ORIGINAL AUTHOR, BOTH SOURCE   */
30 /*    AND OBJECT CODE ARE MADE FREELY AVAILABLE WITHOUT CHARGE, AND CLEAR    */
31 /*    NOTICE IS GIVEN OF THE MODIFICATIONS.  Distribution of this code as    */
32 /*    part of a commercial system is permissible ONLY BY DIRECT ARRANGEMENT  */
33 /*    WITH THE AUTHOR.  (If you are not directly supplying this code to a    */
34 /*    customer, and you are instead telling them how they can obtain it for  */
35 /*    free, then you are not required to make any arrangement with me.)      */
36 /*                                                                           */
37 /*  Hypertext instructions for Triangle are available on the Web at          */
38 /*                                                                           */
39 /*      http://www.cs.cmu.edu/~quake/triangle.html                           */
40 /*                                                                           */
41 /*  Disclaimer:  Neither I nor Carnegie Mellon warrant this code in any way  */
42 /*    whatsoever.  This code is provided "as-is".  Use at your own risk.     */
43 /*                                                                           */
44 /*  Some of the references listed below are marked with an asterisk.  [*]    */
45 /*    These references are available for downloading from the Web page       */
46 /*                                                                           */
47 /*      http://www.cs.cmu.edu/~quake/triangle.research.html                  */
48 /*                                                                           */
49 /*  Three papers discussing aspects of Triangle are available.  A short      */
50 /*    overview appears in "Triangle:  Engineering a 2D Quality Mesh          */
51 /*    Generator and Delaunay Triangulator," in Applied Computational         */
52 /*    Geometry:  Towards Geometric Engineering, Ming C. Lin and Dinesh       */
53 /*    Manocha, editors, Lecture Notes in Computer Science volume 1148,       */
54 /*    pages 203-222, Springer-Verlag, Berlin, May 1996 (from the First ACM   */
55 /*    Workshop on Applied Computational Geometry).  [*]                      */
56 /*                                                                           */
57 /*    The algorithms are discussed in the greatest detail in "Delaunay       */
58 /*    Refinement Algorithms for Triangular Mesh Generation," Computational   */
59 /*    Geometry:  Theory and Applications 22(1-3):21-74, May 2002.  [*]       */
60 /*                                                                           */
61 /*    More detail about the data structures may be found in my dissertation: */
62 /*    "Delaunay Refinement Mesh Generation," Ph.D. thesis, Technical Report  */
63 /*    CMU-CS-97-137, School of Computer Science, Carnegie Mellon University, */
64 /*    Pittsburgh, Pennsylvania, 18 May 1997.  [*]                            */
65 /*                                                                           */
66 /*  Triangle was created as part of the Quake Project in the School of       */
67 /*    Computer Science at Carnegie Mellon University.  For further           */
68 /*    information, see Hesheng Bao, Jacobo Bielak, Omar Ghattas, Loukas F.   */
69 /*    Kallivokas, David R. O'Hallaron, Jonathan R. Shewchuk, and Jifeng Xu,  */
70 /*    "Large-scale Simulation of Elastic Wave Propagation in Heterogeneous   */
71 /*    Media on Parallel Computers," Computer Methods in Applied Mechanics    */
72 /*    and Engineering 152(1-2):85-102, 22 January 1998.                      */
73 /*                                                                           */
74 /*  Triangle's Delaunay refinement algorithm for quality mesh generation is  */
75 /*    a hybrid of one due to Jim Ruppert, "A Delaunay Refinement Algorithm   */
76 /*    for Quality 2-Dimensional Mesh Generation," Journal of Algorithms      */
77 /*    18(3):548-585, May 1995 [*], and one due to L. Paul Chew, "Guaranteed- */
78 /*    Quality Mesh Generation for Curved Surfaces," Proceedings of the Ninth */
79 /*    Annual Symposium on Computational Geometry (San Diego, California),    */
80 /*    pages 274-280, Association for Computing Machinery, May 1993,          */
81 /*    http://portal.acm.org/citation.cfm?id=161150 .                         */
82 /*                                                                           */
83 /*  The Delaunay refinement algorithm has been modified so that it meshes    */
84 /*    domains with small input angles well, as described in Gary L. Miller,  */
85 /*    Steven E. Pav, and Noel J. Walkington, "When and Why Ruppert's         */
86 /*    Algorithm Works," Twelfth International Meshing Roundtable, pages      */
87 /*    91-102, Sandia National Laboratories, September 2003.  [*]             */
88 /*                                                                           */
89 /*  My implementation of the divide-and-conquer and incremental Delaunay     */
90 /*    triangulation algorithms follows closely the presentation of Guibas    */
91 /*    and Stolfi, even though I use a triangle-based data structure instead  */
92 /*    of their quad-edge data structure.  (In fact, I originally implemented */
93 /*    Triangle using the quad-edge data structure, but the switch to a       */
94 /*    triangle-based data structure sped Triangle by a factor of two.)  The  */
95 /*    mesh manipulation primitives and the two aforementioned Delaunay       */
96 /*    triangulation algorithms are described by Leonidas J. Guibas and Jorge */
97 /*    Stolfi, "Primitives for the Manipulation of General Subdivisions and   */
98 /*    the Computation of Voronoi Diagrams," ACM Transactions on Graphics     */
99 /*    4(2):74-123, April 1985, http://portal.acm.org/citation.cfm?id=282923 .*/
100 /*                                                                           */
101 /*  Their O(n log n) divide-and-conquer algorithm is adapted from Der-Tsai   */
102 /*    Lee and Bruce J. Schachter, "Two Algorithms for Constructing the       */
103 /*    Delaunay Triangulation," International Journal of Computer and         */
104 /*    Information Science 9(3):219-242, 1980.  Triangle's improvement of the */
105 /*    divide-and-conquer algorithm by alternating between vertical and       */
106 /*    horizontal cuts was introduced by Rex A. Dwyer, "A Faster Divide-and-  */
107 /*    Conquer Algorithm for Constructing Delaunay Triangulations,"           */
108 /*    Algorithmica 2(2):137-151, 1987.                                       */
109 /*                                                                           */
110 /*  The incremental insertion algorithm was first proposed by C. L. Lawson,  */
111 /*    "Software for C1 Surface Interpolation," in Mathematical Software III, */
112 /*    John R. Rice, editor, Academic Press, New York, pp. 161-194, 1977.     */
113 /*    For point location, I use the algorithm of Ernst P. Mucke, Isaac       */
114 /*    Saias, and Binhai Zhu, "Fast Randomized Point Location Without         */
115 /*    Preprocessing in Two- and Three-Dimensional Delaunay Triangulations,"  */
116 /*    Proceedings of the Twelfth Annual Symposium on Computational Geometry, */
117 /*    ACM, May 1996.  [*]  If I were to randomize the order of vertex        */
118 /*    insertion (I currently don't bother), their result combined with the   */
119 /*    result of Kenneth L. Clarkson and Peter W. Shor, "Applications of      */
120 /*    Random Sampling in Computational Geometry II," Discrete &              */
121 /*    Computational Geometry 4(1):387-421, 1989, would yield an expected     */
122 /*    O(n^{4/3}) bound on running time.                                      */
123 /*                                                                           */
124 /*  The O(n log n) sweepline Delaunay triangulation algorithm is taken from  */
125 /*    Steven Fortune, "A Sweepline Algorithm for Voronoi Diagrams",          */
126 /*    Algorithmica 2(2):153-174, 1987.  A random sample of edges on the      */
127 /*    boundary of the triangulation are maintained in a splay tree for the   */
128 /*    purpose of point location.  Splay trees are described by Daniel        */
129 /*    Dominic Sleator and Robert Endre Tarjan, "Self-Adjusting Binary Search */
130 /*    Trees," Journal of the ACM 32(3):652-686, July 1985,                   */
131 /*    http://portal.acm.org/citation.cfm?id=3835 .                           */
132 /*                                                                           */
133 /*  The algorithms for exact computation of the signs of determinants are    */
134 /*    described in Jonathan Richard Shewchuk, "Adaptive Precision Floating-  */
135 /*    Point Arithmetic and Fast Robust Geometric Predicates," Discrete &     */
136 /*    Computational Geometry 18(3):305-363, October 1997.  (Also available   */
137 /*    as Technical Report CMU-CS-96-140, School of Computer Science,         */
138 /*    Carnegie Mellon University, Pittsburgh, Pennsylvania, May 1996.)  [*]  */
139 /*    An abbreviated version appears as Jonathan Richard Shewchuk, "Robust   */
140 /*    Adaptive Floating-Point Geometric Predicates," Proceedings of the      */
141 /*    Twelfth Annual Symposium on Computational Geometry, ACM, May 1996. [*] */
142 /*    Many of the ideas for my exact arithmetic routines originate with      */
143 /*    Douglas M. Priest, "Algorithms for Arbitrary Precision Floating Point  */
144 /*    Arithmetic," Tenth Symposium on Computer Arithmetic, pp. 132-143, IEEE */
145 /*    Computer Society Press, 1991.  [*]  Many of the ideas for the correct  */
146 /*    evaluation of the signs of determinants are taken from Steven Fortune  */
147 /*    and Christopher J. Van Wyk, "Efficient Exact Arithmetic for Computa-   */
148 /*    tional Geometry," Proceedings of the Ninth Annual Symposium on         */
149 /*    Computational Geometry, ACM, pp. 163-172, May 1993, and from Steven    */
150 /*    Fortune, "Numerical Stability of Algorithms for 2D Delaunay Triangu-   */
151 /*    lations," International Journal of Computational Geometry & Applica-   */
152 /*    tions 5(1-2):193-213, March-June 1995.                                 */
153 /*                                                                           */
154 /*  The method of inserting new vertices off-center (not precisely at the    */
155 /*    circumcenter of every poor-quality triangle) is from Alper Ungor,      */
156 /*    "Off-centers:  A New Type of Steiner Points for Computing Size-Optimal */
157 /*    Quality-Guaranteed Delaunay Triangulations," Proceedings of LATIN      */
158 /*    2004 (Buenos Aires, Argentina), April 2004.                            */
159 /*                                                                           */
160 /*  For definitions of and results involving Delaunay triangulations,        */
161 /*    constrained and conforming versions thereof, and other aspects of      */
162 /*    triangular mesh generation, see the excellent survey by Marshall Bern  */
163 /*    and David Eppstein, "Mesh Generation and Optimal Triangulation," in    */
164 /*    Computing and Euclidean Geometry, Ding-Zhu Du and Frank Hwang,         */
165 /*    editors, World Scientific, Singapore, pp. 23-90, 1992.  [*]            */
166 /*                                                                           */
167 /*  The time for incrementally adding PSLG (planar straight line graph)      */
168 /*    segments to create a constrained Delaunay triangulation is probably    */
169 /*    O(t^2) per segment in the worst case and O(t) per segment in the       */
170 /*    common case, where t is the number of triangles that intersect the     */
171 /*    segment before it is inserted.  This doesn't count point location,     */
172 /*    which can be much more expensive.  I could improve this to O(d log d)  */
173 /*    time, but d is usually quite small, so it's not worth the bother.      */
174 /*    (This note does not apply when the -s switch is used, invoking a       */
175 /*    different method is used to insert segments.)                          */
176 /*                                                                           */
177 /*  The time for deleting a vertex from a Delaunay triangulation is O(d^2)   */
178 /*    in the worst case and O(d) in the common case, where d is the degree   */
179 /*    of the vertex being deleted.  I could improve this to O(d log d) time, */
180 /*    but d is usually quite small, so it's not worth the bother.            */
181 /*                                                                           */
182 /*  Ruppert's Delaunay refinement algorithm typically generates triangles    */
183 /*    at a linear rate (constant time per triangle) after the initial        */
184 /*    triangulation is formed.  There may be pathological cases where        */
185 /*    quadratic time is required, but these never arise in practice.         */
186 /*                                                                           */
187 /*  The geometric predicates (circumcenter calculations, segment             */
188 /*    intersection formulae, etc.) appear in my "Lecture Notes on Geometric  */
189 /*    Robustness" at http://www.cs.berkeley.edu/~jrs/mesh .                  */
190 /*                                                                           */
191 /*  If you make any improvements to this code, please please please let me   */
192 /*    know, so that I may obtain the improvements.  Even if you don't change */
193 /*    the code, I'd still love to hear what it's being used for.             */
194 /*                                                                           */
195 /*****************************************************************************/
196 
197 /* For single precision (which will save some memory and reduce paging),     */
198 /*   define the symbol SINGLE by using the -DSINGLE compiler switch or by    */
199 /*   writing "#define SINGLE" below.                                         */
200 /*                                                                           */
201 /* For double precision (which will allow you to refine meshes to a smaller  */
202 /*   edge length), leave SINGLE undefined.                                   */
203 /*                                                                           */
204 /* Double precision uses more memory, but improves the resolution of the     */
205 /*   meshes you can generate with Triangle.  It also reduces the likelihood  */
206 /*   of a floating exception due to overflow.  Finally, it is much faster    */
207 /*   than single precision on 64-bit architectures like the DEC Alpha.  I    */
208 /*   recommend double precision unless you want to generate a mesh for which */
209 /*   you do not have enough memory.                                          */
210 
211 /* #define SINGLE */
212 
213 #ifdef SINGLE
214 #define REAL float
215 #else /* not SINGLE */
216 #define REAL double
217 #endif /* not SINGLE */
218 
219 #define TRIANGLE_PTRINT size_t
220 
221 /* If yours is not a Unix system, define the NO_TIMER compiler switch to     */
222 /*   remove the Unix-specific timing code.                                   */
223 
224 #define NO_TIMER
225 
226 /* To insert lots of self-checks for internal errors, define the SELF_CHECK  */
227 /*   symbol.  This will slow down the program significantly.  It is best to  */
228 /*   define the symbol using the -DSELF_CHECK compiler switch, but you could */
229 /*   write "#define SELF_CHECK" below.  If you are modifying this code, I    */
230 /*   recommend you turn self-checks on until your work is debugged.          */
231 
232 /* #define SELF_CHECK */
233 
234 /* To compile Triangle as a callable object library (triangle.o), define the */
235 /*   TRILIBRARY symbol.  Read the file triangle.h for details on how to call */
236 /*   the procedure triangulate() that results.                               */
237 
238 #define TRILIBRARY
239 
240 /* It is possible to generate a smaller version of Triangle using one or     */
241 /*   both of the following symbols.  Define the REDUCED symbol to eliminate  */
242 /*   all features that are primarily of research interest; specifically, the */
243 /*   -i, -F, -s, and -C switches.  Define the CDT_ONLY symbol to eliminate   */
244 /*   all meshing algorithms above and beyond constrained Delaunay            */
245 /*   triangulation; specifically, the -r, -q, -a, -u, -D, -S, and -s         */
246 /*   switches.  These reductions are most likely to be useful when           */
247 /*   generating an object library (triangle.o) by defining the TRILIBRARY    */
248 /*   symbol.                                                                 */
249 
250 /* #define REDUCED */
251 /* #define CDT_ONLY */
252 
253 /* On some machines, my exact arithmetic routines might be defeated by the   */
254 /*   use of internal extended precision floating-point registers.  The best  */
255 /*   way to solve this problem is to set the floating-point registers to use */
256 /*   single or double precision internally.  On 80x86 processors, this may   */
257 /*   be accomplished by setting the CPU86 symbol for the Microsoft C         */
258 /*   compiler, or the LINUX symbol for the gcc compiler running on Linux.    */
259 /*                                                                           */
260 /* An inferior solution is to declare certain values as `volatile', thus     */
261 /*   forcing them to be stored to memory and rounded off.  Unfortunately,    */
262 /*   this solution might slow Triangle down quite a bit.  To use volatile    */
263 /*   values, write "#define INEXACT volatile" below.  Normally, however,     */
264 /*   INEXACT should be defined to be nothing.  ("#define INEXACT".)          */
265 /*                                                                           */
266 /* For more discussion, see http://www.cs.cmu.edu/~quake/robust.pc.html .    */
267 /*   For yet more discussion, see Section 5 of my paper, "Adaptive Precision */
268 /*   Floating-Point Arithmetic and Fast Robust Geometric Predicates" (also   */
269 /*   available as Section 6.6 of my dissertation).                           */
270 
271 /* #define CPU86 */
272 /* #define LINUX */
273 
274 #define INEXACT /* Nothing */
275 /* #define INEXACT volatile */
276 
277 /* Maximum number of characters in a file name (including the null).         */
278 
279 #define FILENAMESIZE 2048
280 
281 /* Maximum number of characters in a line read from a file (including the    */
282 /*   null).                                                                  */
283 
284 #define INPUTLINESIZE 4096
285 
286 /* For efficiency, a variety of data structures are allocated in bulk.  The  */
287 /*   following constants determine how many of each structure is allocated   */
288 /*   at once.                                                                */
289 
290 #define TRIPERBLOCK 4092           /* Number of triangles allocated at once. */
291 #define SUBSEGPERBLOCK 508       /* Number of subsegments allocated at once. */
292 #define VERTEXPERBLOCK 4092         /* Number of vertices allocated at once. */
293 #define VIRUSPERBLOCK 1020   /* Number of virus triangles allocated at once. */
294 /* Number of encroached subsegments allocated at once. */
295 #define BADSUBSEGPERBLOCK 252
296 /* Number of skinny triangles allocated at once. */
297 #define BADTRIPERBLOCK 4092
298 /* Number of flipped triangles allocated at once. */
299 #define FLIPSTACKERPERBLOCK 252
300 /* Number of splay tree nodes allocated at once. */
301 #define SPLAYNODEPERBLOCK 508
302 
303 /* The vertex types.   A DEADVERTEX has been deleted entirely.  An           */
304 /*   UNDEADVERTEX is not part of the mesh, but is written to the output      */
305 /*   .node file and affects the node indexing in the other output files.     */
306 
307 #define INPUTVERTEX 0
308 #define SEGMENTVERTEX 1
309 #define FREEVERTEX 2
310 #define DEADVERTEX -32768
311 #define UNDEADVERTEX -32767
312 
313 /* The next line is used to outsmart some very stupid compilers.  If your    */
314 /*   compiler is smarter, feel free to replace the "int" with "void".        */
315 /*   Not that it matters.                                                    */
316 
317 /*#define void int */
318 
319 /* Two constants for algorithms based on random sampling.  Both constants    */
320 /*   have been chosen empirically to optimize their respective algorithms.   */
321 
322 /* Used for the point location scheme of Mucke, Saias, and Zhu, to decide    */
323 /*   how large a random sample of triangles to inspect.                      */
324 
325 #define SAMPLEFACTOR 11
326 
327 /* Used in Fortune's sweepline Delaunay algorithm to determine what fraction */
328 /*   of boundary edges should be maintained in the splay tree for point      */
329 /*   location on the front.                                                  */
330 
331 #define SAMPLERATE 10
332 
333 /* A number that speaks for itself, every kissable digit.                    */
334 
335 #define PI 3.141592653589793238462643383279502884197169399375105820974944592308
336 
337 /* Another fave.                                                             */
338 
339 #define SQUAREROOTTWO 1.4142135623730950488016887242096980785696718753769480732
340 
341 /* And here's one for those of you who are intimidated by math.              */
342 
343 #define ONETHIRD 0.333333333333333333333333333333333333333333333333333333333333
344 
345 #include <stdio.h>
346 #include <stdlib.h>
347 #include <string.h>
348 #include <math.h>
349 #ifndef NO_TIMER
350 #include <sys/time.h>
351 #endif /* not NO_TIMER */
352 #ifdef CPU86
353 #include <float.h>
354 #endif /* CPU86 */
355 #ifdef LINUX
356 #include <fpu_control.h>
357 #endif /* LINUX */
358 #ifdef TRILIBRARY
359 #include "triangle.h"
360 #endif /* TRILIBRARY */
361 
362 /* A few forward declarations.                                               */
363 
364 #ifndef TRILIBRARY
365 char *readline();
366 char *findfield();
367 #endif /* not TRILIBRARY */
368 
369 /* Labels that signify the result of point location.  The result of a        */
370 /*   search indicates that the point falls in the interior of a triangle, on */
371 /*   an edge, on a vertex, or outside the mesh.                              */
372 
373 enum locateresult {INTRIANGLE, ONEDGE, ONVERTEX, OUTSIDE};
374 
375 /* Labels that signify the result of vertex insertion.  The result indicates */
376 /*   that the vertex was inserted with complete success, was inserted but    */
377 /*   encroaches upon a subsegment, was not inserted because it lies on a     */
378 /*   segment, or was not inserted because another vertex occupies the same   */
379 /*   location.                                                               */
380 
381 enum insertvertexresult {SUCCESSFULVERTEX, ENCROACHINGVERTEX, VIOLATINGVERTEX,
382                          DUPLICATEVERTEX};
383 
384 /* Labels that signify the result of direction finding.  The result          */
385 /*   indicates that a segment connecting the two query points falls within   */
386 /*   the direction triangle, along the left edge of the direction triangle,  */
387 /*   or along the right edge of the direction triangle.                      */
388 
389 enum finddirectionresult {WITHIN, LEFTCOLLINEAR, RIGHTCOLLINEAR};
390 
391 /* Labels that signify the result of the circumcenter computation routine.   */
392 /*   The return value indicates which edge of the triangle is shortest.      */
393 
394 enum circumcenterresult {OPPOSITEORG, OPPOSITEDEST, OPPOSITEAPEX};
395 
396 /*****************************************************************************/
397 /*                                                                           */
398 /*  The basic mesh data structures                                           */
399 /*                                                                           */
400 /*  There are three:  vertices, triangles, and subsegments (abbreviated      */
401 /*  `subseg').  These three data structures, linked by pointers, comprise    */
402 /*  the mesh.  A vertex simply represents a mesh vertex and its properties.  */
403 /*  A triangle is a triangle.  A subsegment is a special data structure used */
404 /*  to represent an impenetrable edge of the mesh (perhaps on the outer      */
405 /*  boundary, on the boundary of a hole, or part of an internal boundary     */
406 /*  separating two triangulated regions).  Subsegments represent boundaries, */
407 /*  defined by the user, that triangles may not lie across.                  */
408 /*                                                                           */
409 /*  A triangle consists of a list of three vertices, a list of three         */
410 /*  adjoining triangles, a list of three adjoining subsegments (when         */
411 /*  segments exist), an arbitrary number of optional user-defined            */
412 /*  floating-point attributes, and an optional area constraint.  The latter  */
413 /*  is an upper bound on the permissible area of each triangle in a region,  */
414 /*  used for mesh refinement.                                                */
415 /*                                                                           */
416 /*  For a triangle on a boundary of the mesh, some or all of the neighboring */
417 /*  triangles may not be present.  For a triangle in the interior of the     */
418 /*  mesh, often no neighboring subsegments are present.  Such absent         */
419 /*  triangles and subsegments are never represented by NULL pointers; they   */
420 /*  are represented by two special records:  `dummytri', the triangle that   */
421 /*  fills "outer space", and `dummysub', the omnipresent subsegment.         */
422 /*  `dummytri' and `dummysub' are used for several reasons; for instance,    */
423 /*  they can be dereferenced and their contents examined without violating   */
424 /*  protected memory.                                                        */
425 /*                                                                           */
426 /*  However, it is important to understand that a triangle includes other    */
427 /*  information as well.  The pointers to adjoining vertices, triangles, and */
428 /*  subsegments are ordered in a way that indicates their geometric relation */
429 /*  to each other.  Furthermore, each of these pointers contains orientation */
430 /*  information.  Each pointer to an adjoining triangle indicates which face */
431 /*  of that triangle is contacted.  Similarly, each pointer to an adjoining  */
432 /*  subsegment indicates which side of that subsegment is contacted, and how */
433 /*  the subsegment is oriented relative to the triangle.                     */
434 /*                                                                           */
435 /*  The data structure representing a subsegment may be thought to be        */
436 /*  abutting the edge of one or two triangle data structures:  either        */
437 /*  sandwiched between two triangles, or resting against one triangle on an  */
438 /*  exterior boundary or hole boundary.                                      */
439 /*                                                                           */
440 /*  A subsegment consists of a list of four vertices--the vertices of the    */
441 /*  subsegment, and the vertices of the segment it is a part of--a list of   */
442 /*  two adjoining subsegments, and a list of two adjoining triangles.  One   */
443 /*  of the two adjoining triangles may not be present (though there should   */
444 /*  always be one), and neighboring subsegments might not be present.        */
445 /*  Subsegments also store a user-defined integer "boundary marker".         */
446 /*  Typically, this integer is used to indicate what boundary conditions are */
447 /*  to be applied at that location in a finite element simulation.           */
448 /*                                                                           */
449 /*  Like triangles, subsegments maintain information about the relative      */
450 /*  orientation of neighboring objects.                                      */
451 /*                                                                           */
452 /*  Vertices are relatively simple.  A vertex is a list of floating-point    */
453 /*  numbers, starting with the x, and y coordinates, followed by an          */
454 /*  arbitrary number of optional user-defined floating-point attributes,     */
455 /*  followed by an integer boundary marker.  During the segment insertion    */
456 /*  phase, there is also a pointer from each vertex to a triangle that may   */
457 /*  contain it.  Each pointer is not always correct, but when one is, it     */
458 /*  speeds up segment insertion.  These pointers are assigned values once    */
459 /*  at the beginning of the segment insertion phase, and are not used or     */
460 /*  updated except during this phase.  Edge flipping during segment          */
461 /*  insertion will render some of them incorrect.  Hence, don't rely upon    */
462 /*  them for anything.                                                       */
463 /*                                                                           */
464 /*  Other than the exception mentioned above, vertices have no information   */
465 /*  about what triangles, subfacets, or subsegments they are linked to.      */
466 /*                                                                           */
467 /*****************************************************************************/
468 
469 /*****************************************************************************/
470 /*                                                                           */
471 /*  Handles                                                                  */
472 /*                                                                           */
473 /*  The oriented triangle (`otri') and oriented subsegment (`osub') data     */
474 /*  structures defined below do not themselves store any part of the mesh.   */
475 /*  The mesh itself is made of `triangle's, `subseg's, and `vertex's.        */
476 /*                                                                           */
477 /*  Oriented triangles and oriented subsegments will usually be referred to  */
478 /*  as "handles."  A handle is essentially a pointer into the mesh; it       */
479 /*  allows you to "hold" one particular part of the mesh.  Handles are used  */
480 /*  to specify the regions in which one is traversing and modifying the mesh.*/
481 /*  A single `triangle' may be held by many handles, or none at all.  (The   */
482 /*  latter case is not a memory leak, because the triangle is still          */
483 /*  connected to other triangles in the mesh.)                               */
484 /*                                                                           */
485 /*  An `otri' is a handle that holds a triangle.  It holds a specific edge   */
486 /*  of the triangle.  An `osub' is a handle that holds a subsegment.  It     */
487 /*  holds either the left or right side of the subsegment.                   */
488 /*                                                                           */
489 /*  Navigation about the mesh is accomplished through a set of mesh          */
490 /*  manipulation primitives, further below.  Many of these primitives take   */
491 /*  a handle and produce a new handle that holds the mesh near the first     */
492 /*  handle.  Other primitives take two handles and glue the corresponding    */
493 /*  parts of the mesh together.  The orientation of the handles is           */
494 /*  important.  For instance, when two triangles are glued together by the   */
495 /*  bond() primitive, they are glued at the edges on which the handles lie.  */
496 /*                                                                           */
497 /*  Because vertices have no information about which triangles they are      */
498 /*  attached to, I commonly represent a vertex by use of a handle whose      */
499 /*  origin is the vertex.  A single handle can simultaneously represent a    */
500 /*  triangle, an edge, and a vertex.                                         */
501 /*                                                                           */
502 /*****************************************************************************/
503 
504 /* The triangle data structure.  Each triangle contains three pointers to    */
505 /*   adjoining triangles, plus three pointers to vertices, plus three        */
506 /*   pointers to subsegments (declared below; these pointers are usually     */
507 /*   `dummysub').  It may or may not also contain user-defined attributes    */
508 /*   and/or a floating-point "area constraint."  It may also contain extra   */
509 /*   pointers for nodes, when the user asks for high-order elements.         */
510 /*   Because the size and structure of a `triangle' is not decided until     */
511 /*   runtime, I haven't simply declared the type `triangle' as a struct.     */
512 
513 typedef REAL **triangle;            /* Really:  typedef triangle *triangle   */
514 
515 /* An oriented triangle:  includes a pointer to a triangle and orientation.  */
516 /*   The orientation denotes an edge of the triangle.  Hence, there are      */
517 /*   three possible orientations.  By convention, each edge always points    */
518 /*   counterclockwise about the corresponding triangle.                      */
519 
520 struct otri {
521   triangle *tri;
522   int orient;                                         /* Ranges from 0 to 2. */
523 };
524 
525 /* The subsegment data structure.  Each subsegment contains two pointers to  */
526 /*   adjoining subsegments, plus four pointers to vertices, plus two         */
527 /*   pointers to adjoining triangles, plus one boundary marker, plus one     */
528 /*   segment number.                                                         */
529 
530 typedef REAL **subseg;                  /* Really:  typedef subseg *subseg   */
531 
532 /* An oriented subsegment:  includes a pointer to a subsegment and an        */
533 /*   orientation.  The orientation denotes a side of the edge.  Hence, there */
534 /*   are two possible orientations.  By convention, the edge is always       */
535 /*   directed so that the "side" denoted is the right side of the edge.      */
536 
537 struct osub {
538   subseg *ss;
539   int ssorient;                                       /* Ranges from 0 to 1. */
540 };
541 
542 /* The vertex data structure.  Each vertex is actually an array of REALs.    */
543 /*   The number of REALs is unknown until runtime.  An integer boundary      */
544 /*   marker, and sometimes a pointer to a triangle, is appended after the    */
545 /*   REALs.                                                                  */
546 
547 typedef REAL *vertex;
548 
549 /* A queue used to store encroached subsegments.  Each subsegment's vertices */
550 /*   are stored so that we can check whether a subsegment is still the same. */
551 
552 struct badsubseg {
553   subseg encsubseg;                             /* An encroached subsegment. */
554   vertex subsegorg, subsegdest;                         /* Its two vertices. */
555 };
556 
557 /* A queue used to store bad triangles.  The key is the square of the cosine */
558 /*   of the smallest angle of the triangle.  Each triangle's vertices are    */
559 /*   stored so that one can check whether a triangle is still the same.      */
560 
561 struct badtriang {
562   triangle poortri;                       /* A skinny or too-large triangle. */
563   REAL key;                             /* cos^2 of smallest (apical) angle. */
564   vertex triangorg, triangdest, triangapex;           /* Its three vertices. */
565   struct badtriang *nexttriang;             /* Pointer to next bad triangle. */
566 };
567 
568 /* A stack of triangles flipped during the most recent vertex insertion.     */
569 /*   The stack is used to undo the vertex insertion if the vertex encroaches */
570 /*   upon a subsegment.                                                      */
571 
572 struct flipstacker {
573   triangle flippedtri;                       /* A recently flipped triangle. */
574   struct flipstacker *prevflip;               /* Previous flip in the stack. */
575 };
576 
577 /* A node in a heap used to store events for the sweepline Delaunay          */
578 /*   algorithm.  Nodes do not point directly to their parents or children in */
579 /*   the heap.  Instead, each node knows its position in the heap, and can   */
580 /*   look up its parent and children in a separate array.  The `eventptr'    */
581 /*   points either to a `vertex' or to a triangle (in encoded format, so     */
582 /*   that an orientation is included).  In the latter case, the origin of    */
583 /*   the oriented triangle is the apex of a "circle event" of the sweepline  */
584 /*   algorithm.  To distinguish site events from circle events, all circle   */
585 /*   events are given an invalid (smaller than `xmin') x-coordinate `xkey'.  */
586 
587 struct event {
588   REAL xkey, ykey;                              /* Coordinates of the event. */
589   void *eventptr;      /* Can be a vertex or the location of a circle event. */
590   int heapposition;              /* Marks this event's position in the heap. */
591 };
592 
593 /* A node in the splay tree.  Each node holds an oriented ghost triangle     */
594 /*   that represents a boundary edge of the growing triangulation.  When a   */
595 /*   circle event covers two boundary edges with a triangle, so that they    */
596 /*   are no longer boundary edges, those edges are not immediately deleted   */
597 /*   from the tree; rather, they are lazily deleted when they are next       */
598 /*   encountered.  (Since only a random sample of boundary edges are kept    */
599 /*   in the tree, lazy deletion is faster.)  `keydest' is used to verify     */
600 /*   that a triangle is still the same as when it entered the splay tree; if */
601 /*   it has been rotated (due to a circle event), it no longer represents a  */
602 /*   boundary edge and should be deleted.                                    */
603 
604 struct splaynode {
605   struct otri keyedge;                     /* Lprev of an edge on the front. */
606   vertex keydest;           /* Used to verify that splay node is still live. */
607   struct splaynode *lchild, *rchild;              /* Children in splay tree. */
608 };
609 
610 /* A type used to allocate memory.  firstblock is the first block of items.  */
611 /*   nowblock is the block from which items are currently being allocated.   */
612 /*   nextitem points to the next slab of free memory for an item.            */
613 /*   deaditemstack is the head of a linked list (stack) of deallocated items */
614 /*   that can be recycled.  unallocateditems is the number of items that     */
615 /*   remain to be allocated from nowblock.                                   */
616 /*                                                                           */
617 /* Traversal is the process of walking through the entire list of items, and */
618 /*   is separate from allocation.  Note that a traversal will visit items on */
619 /*   the "deaditemstack" stack as well as live items.  pathblock points to   */
620 /*   the block currently being traversed.  pathitem points to the next item  */
621 /*   to be traversed.  pathitemsleft is the number of items that remain to   */
622 /*   be traversed in pathblock.                                              */
623 /*                                                                           */
624 /* alignbytes determines how new records should be aligned in memory.        */
625 /*   itembytes is the length of a record in bytes (after rounding up).       */
626 /*   itemsperblock is the number of items allocated at once in a single      */
627 /*   block.  itemsfirstblock is the number of items in the first block,      */
628 /*   which can vary from the others.  items is the number of currently       */
629 /*   allocated items.  maxitems is the maximum number of items that have     */
630 /*   been allocated at once; it is the current number of items plus the      */
631 /*   number of records kept on deaditemstack.                                */
632 
633 struct memorypool {
634   void **firstblock, **nowblock;
635   void *nextitem;
636   void *deaditemstack;
637   void **pathblock;
638   void *pathitem;
639   int alignbytes;
640   int itembytes;
641   int itemsperblock;
642   int itemsfirstblock;
643   long items, maxitems;
644   int unallocateditems;
645   int pathitemsleft;
646 };
647 
648 
649 /* Global constants.                                                         */
650 
651 REAL splitter;       /* Used to split REAL factors for exact multiplication. */
652 REAL epsilon;                             /* Floating-point machine epsilon. */
653 REAL resulterrbound;
654 REAL ccwerrboundA, ccwerrboundB, ccwerrboundC;
655 REAL iccerrboundA, iccerrboundB, iccerrboundC;
656 REAL o3derrboundA, o3derrboundB, o3derrboundC;
657 
658 /* Random number seed is not constant, but I've made it global anyway.       */
659 
660 TRIANGLE_PTRINT randomseed;                     /* Current random number seed. */
661 
662 
663 /* Mesh data structure.  Triangle operates on only one mesh, but the mesh    */
664 /*   structure is used (instead of global variables) to allow reentrancy.    */
665 
666 struct mesh {
667 
668 /* Variables used to allocate memory for triangles, subsegments, vertices,   */
669 /*   viri (triangles being eaten), encroached segments, bad (skinny or too   */
670 /*   large) triangles, and splay tree nodes.                                 */
671 
672   struct memorypool triangles;
673   struct memorypool subsegs;
674   struct memorypool vertices;
675   struct memorypool viri;
676   struct memorypool badsubsegs;
677   struct memorypool badtriangles;
678   struct memorypool flipstackers;
679   struct memorypool splaynodes;
680 
681 /* Variables that maintain the bad triangle queues.  The queues are          */
682 /*   ordered from 4095 (highest priority) to 0 (lowest priority).            */
683 
684   struct badtriang *queuefront[4096];
685   struct badtriang *queuetail[4096];
686   int nextnonemptyq[4096];
687   int firstnonemptyq;
688 
689 /* Variable that maintains the stack of recently flipped triangles.          */
690 
691   struct flipstacker *lastflip;
692 
693 /* Other variables. */
694 
695   REAL xmin, xmax, ymin, ymax;                            /* x and y bounds. */
696   REAL xminextreme;      /* Nonexistent x value used as a flag in sweepline. */
697   int invertices;                               /* Number of input vertices. */
698   int inelements;                              /* Number of input triangles. */
699   int insegments;                               /* Number of input segments. */
700   int holes;                                       /* Number of input holes. */
701   int regions;                                   /* Number of input regions. */
702   int undeads;    /* Number of input vertices that don't appear in the mesh. */
703   long edges;                                     /* Number of output edges. */
704   int mesh_dim;                                /* Dimension (ought to be 2). */
705   int nextras;                           /* Number of attributes per vertex. */
706   int eextras;                         /* Number of attributes per triangle. */
707   long hullsize;                          /* Number of edges in convex hull. */
708   int steinerleft;                 /* Number of Steiner points not yet used. */
709   int vertexmarkindex;         /* Index to find boundary marker of a vertex. */
710   int vertex2triindex;     /* Index to find a triangle adjacent to a vertex. */
711   int highorderindex;  /* Index to find extra nodes for high-order elements. */
712   int elemattribindex;            /* Index to find attributes of a triangle. */
713   int areaboundindex;             /* Index to find area bound of a triangle. */
714   int checksegments;         /* Are there segments in the triangulation yet? */
715   int checkquality;                  /* Has quality triangulation begun yet? */
716   int readnodefile;                           /* Has a .node file been read? */
717   long samples;              /* Number of random samples for point location. */
718 
719   long incirclecount;                 /* Number of incircle tests performed. */
720   long counterclockcount;     /* Number of counterclockwise tests performed. */
721   long orient3dcount;           /* Number of 3D orientation tests performed. */
722   long hyperbolacount;      /* Number of right-of-hyperbola tests performed. */
723   long circumcentercount;  /* Number of circumcenter calculations performed. */
724   long circletopcount;       /* Number of circle top calculations performed. */
725 
726 /* Triangular bounding box vertices.                                         */
727 
728   vertex infvertex1, infvertex2, infvertex3;
729 
730 /* Pointer to the `triangle' that occupies all of "outer space."             */
731 
732   triangle *dummytri;
733   triangle *dummytribase;    /* Keep base address so we can free() it later. */
734 
735 /* Pointer to the omnipresent subsegment.  Referenced by any triangle or     */
736 /*   subsegment that isn't really connected to a subsegment at that          */
737 /*   location.                                                               */
738 
739   subseg *dummysub;
740   subseg *dummysubbase;      /* Keep base address so we can free() it later. */
741 
742 /* Pointer to a recently visited triangle.  Improves point location if       */
743 /*   proximate vertices are inserted sequentially.                           */
744 
745   struct otri recenttri;
746 
747 };                                                  /* End of `struct mesh'. */
748 
749 
750 /* Data structure for command line switches and file names.  This structure  */
751 /*   is used (instead of global variables) to allow reentrancy.              */
752 
753 struct behavior {
754 
755 /* Switches for the triangulator.                                            */
756 /*   poly: -p switch.  refine: -r switch.                                    */
757 /*   quality: -q switch.                                                     */
758 /*     minangle: minimum angle bound, specified after -q switch.             */
759 /*     goodangle: cosine squared of minangle.                                */
760 /*     offconstant: constant used to place off-center Steiner points.        */
761 /*   vararea: -a switch without number.                                      */
762 /*   fixedarea: -a switch with number.                                       */
763 /*     maxarea: maximum area bound, specified after -a switch.               */
764 /*   usertest: -u switch.                                                    */
765 /*   regionattrib: -A switch.  convex: -c switch.                            */
766 /*   weighted: 1 for -w switch, 2 for -W switch.  jettison: -j switch        */
767 /*   firstnumber: inverse of -z switch.  All items are numbered starting     */
768 /*     from `firstnumber'.                                                   */
769 /*   edgesout: -e switch.  voronoi: -v switch.                               */
770 /*   neighbors: -n switch.  geomview: -g switch.                             */
771 /*   nobound: -B switch.  nopolywritten: -P switch.                          */
772 /*   nonodewritten: -N switch.  noelewritten: -E switch.                     */
773 /*   noiterationnum: -I switch.  noholes: -O switch.                         */
774 /*   noexact: -X switch.                                                     */
775 /*   order: element order, specified after -o switch.                        */
776 /*   nobisect: count of how often -Y switch is selected.                     */
777 /*   steiner: maximum number of Steiner points, specified after -S switch.   */
778 /*   incremental: -i switch.  sweepline: -F switch.                          */
779 /*   dwyer: inverse of -l switch.                                            */
780 /*   splitseg: -s switch.                                                    */
781 /*   conformdel: -D switch.  docheck: -C switch.                             */
782 /*   quiet: -Q switch.  verbose: count of how often -V switch is selected.   */
783 /*   usesegments: -p, -r, -q, or -c switch; determines whether segments are  */
784 /*     used at all.                                                          */
785 /*                                                                           */
786 /* Read the instructions to find out the meaning of these switches.          */
787 
788   int poly, refine, quality, vararea, fixedarea, usertest;
789   int regionattrib, convex, weighted, jettison;
790   int firstnumber;
791   int edgesout, voronoi, neighbors, geomview;
792   int nobound, nopolywritten, nonodewritten, noelewritten, noiterationnum;
793   int noholes, noexact, conformdel;
794   int incremental, sweepline, dwyer;
795   int splitseg;
796   int docheck;
797   int quiet, verbose;
798   int usesegments;
799   int order;
800   int nobisect;
801   int steiner;
802   REAL minangle, goodangle, offconstant;
803   REAL maxarea;
804 
805 /* Variables for file names.                                                 */
806 
807 #ifndef TRILIBRARY
808   char innodefilename[FILENAMESIZE];
809   char inelefilename[FILENAMESIZE];
810   char inpolyfilename[FILENAMESIZE];
811   char areafilename[FILENAMESIZE];
812   char outnodefilename[FILENAMESIZE];
813   char outelefilename[FILENAMESIZE];
814   char outpolyfilename[FILENAMESIZE];
815   char edgefilename[FILENAMESIZE];
816   char vnodefilename[FILENAMESIZE];
817   char vedgefilename[FILENAMESIZE];
818   char neighborfilename[FILENAMESIZE];
819   char offfilename[FILENAMESIZE];
820 #endif /* not TRILIBRARY */
821 
822 };                                              /* End of `struct behavior'. */
823 
824 
825 /*****************************************************************************/
826 /*                                                                           */
827 /*  Mesh manipulation primitives.  Each triangle contains three pointers to  */
828 /*  other triangles, with orientations.  Each pointer points not to the      */
829 /*  first byte of a triangle, but to one of the first three bytes of a       */
830 /*  triangle.  It is necessary to extract both the triangle itself and the   */
831 /*  orientation.  To save memory, I keep both pieces of information in one   */
832 /*  pointer.  To make this possible, I assume that all triangles are aligned */
833 /*  to four-byte boundaries.  The decode() routine below decodes a pointer,  */
834 /*  extracting an orientation (in the range 0 to 2) and a pointer to the     */
835 /*  beginning of a triangle.  The encode() routine compresses a pointer to a */
836 /*  triangle and an orientation into a single pointer.  My assumptions that  */
837 /*  triangles are four-byte-aligned and that the `TRIANGLE_PTRINT' type is     */
838 /*  long enough to hold a pointer are two of the few kludges in this program.*/
839 /*                                                                           */
840 /*  Subsegments are manipulated similarly.  A pointer to a subsegment        */
841 /*  carries both an address and an orientation in the range 0 to 1.          */
842 /*                                                                           */
843 /*  The other primitives take an oriented triangle or oriented subsegment,   */
844 /*  and return an oriented triangle or oriented subsegment or vertex; or     */
845 /*  they change the connections in the data structure.                       */
846 /*                                                                           */
847 /*  Below, triangles and subsegments are denoted by their vertices.  The     */
848 /*  triangle abc has origin (org) a, destination (dest) b, and apex (apex)   */
849 /*  c.  These vertices occur in counterclockwise order about the triangle.   */
850 /*  The handle abc may simultaneously denote vertex a, edge ab, and triangle */
851 /*  abc.                                                                     */
852 /*                                                                           */
853 /*  Similarly, the subsegment ab has origin (sorg) a and destination (sdest) */
854 /*  b.  If ab is thought to be directed upward (with b directly above a),    */
855 /*  then the handle ab is thought to grasp the right side of ab, and may     */
856 /*  simultaneously denote vertex a and edge ab.                              */
857 /*                                                                           */
858 /*  An asterisk (*) denotes a vertex whose identity is unknown.              */
859 /*                                                                           */
860 /*  Given this notation, a partial list of mesh manipulation primitives      */
861 /*  follows.                                                                 */
862 /*                                                                           */
863 /*                                                                           */
864 /*  For triangles:                                                           */
865 /*                                                                           */
866 /*  sym:  Find the abutting triangle; same edge.                             */
867 /*  sym(abc) -> ba*                                                          */
868 /*                                                                           */
869 /*  lnext:  Find the next edge (counterclockwise) of a triangle.             */
870 /*  lnext(abc) -> bca                                                        */
871 /*                                                                           */
872 /*  lprev:  Find the previous edge (clockwise) of a triangle.                */
873 /*  lprev(abc) -> cab                                                        */
874 /*                                                                           */
875 /*  onext:  Find the next edge counterclockwise with the same origin.        */
876 /*  onext(abc) -> ac*                                                        */
877 /*                                                                           */
878 /*  oprev:  Find the next edge clockwise with the same origin.               */
879 /*  oprev(abc) -> a*b                                                        */
880 /*                                                                           */
881 /*  dnext:  Find the next edge counterclockwise with the same destination.   */
882 /*  dnext(abc) -> *ba                                                        */
883 /*                                                                           */
884 /*  dprev:  Find the next edge clockwise with the same destination.          */
885 /*  dprev(abc) -> cb*                                                        */
886 /*                                                                           */
887 /*  rnext:  Find the next edge (counterclockwise) of the adjacent triangle.  */
888 /*  rnext(abc) -> *a*                                                        */
889 /*                                                                           */
890 /*  rprev:  Find the previous edge (clockwise) of the adjacent triangle.     */
891 /*  rprev(abc) -> b**                                                        */
892 /*                                                                           */
893 /*  org:  Origin          dest:  Destination          apex:  Apex            */
894 /*  org(abc) -> a         dest(abc) -> b              apex(abc) -> c         */
895 /*                                                                           */
896 /*  bond:  Bond two triangles together at the resepective handles.           */
897 /*  bond(abc, bad)                                                           */
898 /*                                                                           */
899 /*                                                                           */
900 /*  For subsegments:                                                         */
901 /*                                                                           */
902 /*  ssym:  Reverse the orientation of a subsegment.                          */
903 /*  ssym(ab) -> ba                                                           */
904 /*                                                                           */
905 /*  spivot:  Find adjoining subsegment with the same origin.                 */
906 /*  spivot(ab) -> a*                                                         */
907 /*                                                                           */
908 /*  snext:  Find next subsegment in sequence.                                */
909 /*  snext(ab) -> b*                                                          */
910 /*                                                                           */
911 /*  sorg:  Origin                      sdest:  Destination                   */
912 /*  sorg(ab) -> a                      sdest(ab) -> b                        */
913 /*                                                                           */
914 /*  sbond:  Bond two subsegments together at the respective origins.         */
915 /*  sbond(ab, ac)                                                            */
916 /*                                                                           */
917 /*                                                                           */
918 /*  For interacting tetrahedra and subfacets:                                */
919 /*                                                                           */
920 /*  tspivot:  Find a subsegment abutting a triangle.                         */
921 /*  tspivot(abc) -> ba                                                       */
922 /*                                                                           */
923 /*  stpivot:  Find a triangle abutting a subsegment.                         */
924 /*  stpivot(ab) -> ba*                                                       */
925 /*                                                                           */
926 /*  tsbond:  Bond a triangle to a subsegment.                                */
927 /*  tsbond(abc, ba)                                                          */
928 /*                                                                           */
929 /*****************************************************************************/
930 
931 /********* Mesh manipulation primitives begin here                   *********/
932 /**                                                                         **/
933 /**                                                                         **/
934 
935 /* Fast lookup arrays to speed some of the mesh manipulation primitives.     */
936 
937 int plus1mod3[3] = {1, 2, 0};
938 int minus1mod3[3] = {2, 0, 1};
939 
940 /********* Primitives for triangles                                  *********/
941 /*                                                                           */
942 /*                                                                           */
943 
944 /* decode() converts a pointer to an oriented triangle.  The orientation is  */
945 /*   extracted from the two least significant bits of the pointer.           */
946 
947 #define decode(ptr, otri)                                                     \
948   (otri).orient = (int) ((TRIANGLE_PTRINT) (ptr) & (TRIANGLE_PTRINT) 3l);         \
949   (otri).tri = (triangle *)                                                   \
950                   ((TRIANGLE_PTRINT) (ptr) ^ (TRIANGLE_PTRINT) (otri).orient)
951 
952 /* encode() compresses an oriented triangle into a single pointer.  It       */
953 /*   relies on the assumption that all triangles are aligned to four-byte    */
954 /*   boundaries, so the two least significant bits of (otri).tri are zero.   */
955 
956 #define encode(otri)                                                          \
957   (triangle) ((TRIANGLE_PTRINT) (otri).tri | (TRIANGLE_PTRINT) (otri).orient)
958 
959 /* The following handle manipulation primitives are all described by Guibas  */
960 /*   and Stolfi.  However, Guibas and Stolfi use an edge-based data          */
961 /*   structure, whereas I use a triangle-based data structure.               */
962 
963 /* sym() finds the abutting triangle, on the same edge.  Note that the edge  */
964 /*   direction is necessarily reversed, because the handle specified by an   */
965 /*   oriented triangle is directed counterclockwise around the triangle.     */
966 
967 #define sym(otri1, otri2)                                                     \
968   ptr = (otri1).tri[(otri1).orient];                                          \
969   decode(ptr, otri2);
970 
971 #define symself(otri)                                                         \
972   ptr = (otri).tri[(otri).orient];                                            \
973   decode(ptr, otri);
974 
975 /* lnext() finds the next edge (counterclockwise) of a triangle.             */
976 
977 #define lnext(otri1, otri2)                                                   \
978   (otri2).tri = (otri1).tri;                                                  \
979   (otri2).orient = plus1mod3[(otri1).orient]
980 
981 #define lnextself(otri)                                                       \
982   (otri).orient = plus1mod3[(otri).orient]
983 
984 /* lprev() finds the previous edge (clockwise) of a triangle.                */
985 
986 #define lprev(otri1, otri2)                                                   \
987   (otri2).tri = (otri1).tri;                                                  \
988   (otri2).orient = minus1mod3[(otri1).orient]
989 
990 #define lprevself(otri)                                                       \
991   (otri).orient = minus1mod3[(otri).orient]
992 
993 /* onext() spins counterclockwise around a vertex; that is, it finds the     */
994 /*   next edge with the same origin in the counterclockwise direction.  This */
995 /*   edge is part of a different triangle.                                   */
996 
997 #define onext(otri1, otri2)                                                   \
998   lprev(otri1, otri2);                                                        \
999   symself(otri2);
1000 
1001 #define onextself(otri)                                                       \
1002   lprevself(otri);                                                            \
1003   symself(otri);
1004 
1005 /* oprev() spins clockwise around a vertex; that is, it finds the next edge  */
1006 /*   with the same origin in the clockwise direction.  This edge is part of  */
1007 /*   a different triangle.                                                   */
1008 
1009 #define oprev(otri1, otri2)                                                   \
1010   sym(otri1, otri2);                                                          \
1011   lnextself(otri2);
1012 
1013 #define oprevself(otri)                                                       \
1014   symself(otri);                                                              \
1015   lnextself(otri);
1016 
1017 /* dnext() spins counterclockwise around a vertex; that is, it finds the     */
1018 /*   next edge with the same destination in the counterclockwise direction.  */
1019 /*   This edge is part of a different triangle.                              */
1020 
1021 #define dnext(otri1, otri2)                                                   \
1022   sym(otri1, otri2);                                                          \
1023   lprevself(otri2);
1024 
1025 #define dnextself(otri)                                                       \
1026   symself(otri);                                                              \
1027   lprevself(otri);
1028 
1029 /* dprev() spins clockwise around a vertex; that is, it finds the next edge  */
1030 /*   with the same destination in the clockwise direction.  This edge is     */
1031 /*   part of a different triangle.                                           */
1032 
1033 #define dprev(otri1, otri2)                                                   \
1034   lnext(otri1, otri2);                                                        \
1035   symself(otri2);
1036 
1037 #define dprevself(otri)                                                       \
1038   lnextself(otri);                                                            \
1039   symself(otri);
1040 
1041 /* rnext() moves one edge counterclockwise about the adjacent triangle.      */
1042 /*   (It's best understood by reading Guibas and Stolfi.  It involves        */
1043 /*   changing triangles twice.)                                              */
1044 
1045 #define rnext(otri1, otri2)                                                   \
1046   sym(otri1, otri2);                                                          \
1047   lnextself(otri2);                                                           \
1048   symself(otri2);
1049 
1050 #define rnextself(otri)                                                       \
1051   symself(otri);                                                              \
1052   lnextself(otri);                                                            \
1053   symself(otri);
1054 
1055 /* rprev() moves one edge clockwise about the adjacent triangle.             */
1056 /*   (It's best understood by reading Guibas and Stolfi.  It involves        */
1057 /*   changing triangles twice.)                                              */
1058 
1059 #define rprev(otri1, otri2)                                                   \
1060   sym(otri1, otri2);                                                          \
1061   lprevself(otri2);                                                           \
1062   symself(otri2);
1063 
1064 #define rprevself(otri)                                                       \
1065   symself(otri);                                                              \
1066   lprevself(otri);                                                            \
1067   symself(otri);
1068 
1069 /* These primitives determine or set the origin, destination, or apex of a   */
1070 /* triangle.                                                                 */
1071 
1072 #define org(otri, vertexptr)                                                  \
1073   vertexptr = (vertex) (otri).tri[plus1mod3[(otri).orient] + 3]
1074 
1075 #define dest(otri, vertexptr)                                                 \
1076   vertexptr = (vertex) (otri).tri[minus1mod3[(otri).orient] + 3]
1077 
1078 #define apex(otri, vertexptr)                                                 \
1079   vertexptr = (vertex) (otri).tri[(otri).orient + 3]
1080 
1081 #define setorg(otri, vertexptr)                                               \
1082   (otri).tri[plus1mod3[(otri).orient] + 3] = (triangle) vertexptr
1083 
1084 #define setdest(otri, vertexptr)                                              \
1085   (otri).tri[minus1mod3[(otri).orient] + 3] = (triangle) vertexptr
1086 
1087 #define setapex(otri, vertexptr)                                              \
1088   (otri).tri[(otri).orient + 3] = (triangle) vertexptr
1089 
1090 /* Bond two triangles together.                                              */
1091 
1092 #define bond(otri1, otri2)                                                    \
1093   (otri1).tri[(otri1).orient] = encode(otri2);                                \
1094   (otri2).tri[(otri2).orient] = encode(otri1)
1095 
1096 /* Dissolve a bond (from one side).  Note that the other triangle will still */
1097 /*   think it's connected to this triangle.  Usually, however, the other     */
1098 /*   triangle is being deleted entirely, or bonded to another triangle, so   */
1099 /*   it doesn't matter.                                                      */
1100 
1101 #define dissolve(otri)                                                        \
1102   (otri).tri[(otri).orient] = (triangle) m->dummytri
1103 
1104 /* Copy an oriented triangle.                                                */
1105 
1106 #define otricopy(otri1, otri2)                                                \
1107   (otri2).tri = (otri1).tri;                                                  \
1108   (otri2).orient = (otri1).orient
1109 
1110 /* Test for equality of oriented triangles.                                  */
1111 
1112 #define otriequal(otri1, otri2)                                               \
1113   (((otri1).tri == (otri2).tri) &&                                            \
1114    ((otri1).orient == (otri2).orient))
1115 
1116 /* Primitives to infect or cure a triangle with the virus.  These rely on    */
1117 /*   the assumption that all subsegments are aligned to four-byte boundaries.*/
1118 
1119 #define infect(otri)                                                          \
1120   (otri).tri[6] = (triangle)                                                  \
1121                     ((TRIANGLE_PTRINT) (otri).tri[6] | (TRIANGLE_PTRINT) 2l)
1122 
1123 #define uninfect(otri)                                                        \
1124   (otri).tri[6] = (triangle)                                                  \
1125                     ((TRIANGLE_PTRINT) (otri).tri[6] & ~ (TRIANGLE_PTRINT) 2l)
1126 
1127 /* Test a triangle for viral infection.                                      */
1128 
1129 #define infected(otri)                                                        \
1130   (((TRIANGLE_PTRINT) (otri).tri[6] & (TRIANGLE_PTRINT) 2l) != 0l)
1131 
1132 /* Check or set a triangle's attributes.                                     */
1133 
1134 #define elemattribute(otri, attnum)                                           \
1135   ((REAL *) (otri).tri)[m->elemattribindex + (attnum)]
1136 
1137 #define setelemattribute(otri, attnum, value)                                 \
1138   ((REAL *) (otri).tri)[m->elemattribindex + (attnum)] = value
1139 
1140 /* Check or set a triangle's maximum area bound.                             */
1141 
1142 #define areabound(otri)  ((REAL *) (otri).tri)[m->areaboundindex]
1143 
1144 #define setareabound(otri, value)                                             \
1145   ((REAL *) (otri).tri)[m->areaboundindex] = value
1146 
1147 /* Check or set a triangle's deallocation.  Its second pointer is set to     */
1148 /*   NULL to indicate that it is not allocated.  (Its first pointer is used  */
1149 /*   for the stack of dead items.)  Its fourth pointer (its first vertex)    */
1150 /*   is set to NULL in case a `badtriang' structure points to it.            */
1151 
1152 #define deadtri(tria)  ((tria)[1] == (triangle) NULL)
1153 
1154 #define killtri(tria)                                                         \
1155   (tria)[1] = (triangle) NULL;                                                \
1156   (tria)[3] = (triangle) NULL
1157 
1158 /********* Primitives for subsegments                                *********/
1159 /*                                                                           */
1160 /*                                                                           */
1161 
1162 /* sdecode() converts a pointer to an oriented subsegment.  The orientation  */
1163 /*   is extracted from the least significant bit of the pointer.  The two    */
1164 /*   least significant bits (one for orientation, one for viral infection)   */
1165 /*   are masked out to produce the real pointer.                             */
1166 
1167 #define sdecode(sptr, osub)                                                   \
1168   (osub).ssorient = (int) ((TRIANGLE_PTRINT) (sptr) & (TRIANGLE_PTRINT) 1l);      \
1169   (osub).ss = (subseg *)                                                      \
1170               ((TRIANGLE_PTRINT) (sptr) & ~ (TRIANGLE_PTRINT) 3l)
1171 
1172 /* sencode() compresses an oriented subsegment into a single pointer.  It    */
1173 /*   relies on the assumption that all subsegments are aligned to two-byte   */
1174 /*   boundaries, so the least significant bit of (osub).ss is zero.          */
1175 
1176 #define sencode(osub)                                                         \
1177   (subseg) ((TRIANGLE_PTRINT) (osub).ss | (TRIANGLE_PTRINT) (osub).ssorient)
1178 
1179 /* ssym() toggles the orientation of a subsegment.                           */
1180 
1181 #define ssym(osub1, osub2)                                                    \
1182   (osub2).ss = (osub1).ss;                                                    \
1183   (osub2).ssorient = 1 - (osub1).ssorient
1184 
1185 #define ssymself(osub)                                                        \
1186   (osub).ssorient = 1 - (osub).ssorient
1187 
1188 /* spivot() finds the other subsegment (from the same segment) that shares   */
1189 /*   the same origin.                                                        */
1190 
1191 #define spivot(osub1, osub2)                                                  \
1192   sptr = (osub1).ss[(osub1).ssorient];                                        \
1193   sdecode(sptr, osub2)
1194 
1195 #define spivotself(osub)                                                      \
1196   sptr = (osub).ss[(osub).ssorient];                                          \
1197   sdecode(sptr, osub)
1198 
1199 /* snext() finds the next subsegment (from the same segment) in sequence;    */
1200 /*   one whose origin is the input subsegment's destination.                 */
1201 
1202 #define snext(osub1, osub2)                                                   \
1203   sptr = (osub1).ss[1 - (osub1).ssorient];                                    \
1204   sdecode(sptr, osub2)
1205 
1206 #define snextself(osub)                                                       \
1207   sptr = (osub).ss[1 - (osub).ssorient];                                      \
1208   sdecode(sptr, osub)
1209 
1210 /* These primitives determine or set the origin or destination of a          */
1211 /*   subsegment or the segment that includes it.                             */
1212 
1213 #define sorg(osub, vertexptr)                                                 \
1214   vertexptr = (vertex) (osub).ss[2 + (osub).ssorient]
1215 
1216 #define sdest(osub, vertexptr)                                                \
1217   vertexptr = (vertex) (osub).ss[3 - (osub).ssorient]
1218 
1219 #define setsorg(osub, vertexptr)                                              \
1220   (osub).ss[2 + (osub).ssorient] = (subseg) vertexptr
1221 
1222 #define setsdest(osub, vertexptr)                                             \
1223   (osub).ss[3 - (osub).ssorient] = (subseg) vertexptr
1224 
1225 #define segorg(osub, vertexptr)                                               \
1226   vertexptr = (vertex) (osub).ss[4 + (osub).ssorient]
1227 
1228 #define segdest(osub, vertexptr)                                              \
1229   vertexptr = (vertex) (osub).ss[5 - (osub).ssorient]
1230 
1231 #define setsegorg(osub, vertexptr)                                            \
1232   (osub).ss[4 + (osub).ssorient] = (subseg) vertexptr
1233 
1234 #define setsegdest(osub, vertexptr)                                           \
1235   (osub).ss[5 - (osub).ssorient] = (subseg) vertexptr
1236 
1237 /* These primitives read or set a boundary marker.  Boundary markers are     */
1238 /*   used to hold user-defined tags for setting boundary conditions in       */
1239 /*   finite element solvers.                                                 */
1240 
1241 #define mark(osub)  (* (int *) ((osub).ss + 8))
1242 
1243 #define setmark(osub, value)                                                  \
1244   * (int *) ((osub).ss + 8) = value
1245 
1246 /* Bond two subsegments together.                                            */
1247 
1248 #define sbond(osub1, osub2)                                                   \
1249   (osub1).ss[(osub1).ssorient] = sencode(osub2);                              \
1250   (osub2).ss[(osub2).ssorient] = sencode(osub1)
1251 
1252 /* Dissolve a subsegment bond (from one side).  Note that the other          */
1253 /*   subsegment will still think it's connected to this subsegment.          */
1254 
1255 #define sdissolve(osub)                                                       \
1256   (osub).ss[(osub).ssorient] = (subseg) m->dummysub
1257 
1258 /* Copy a subsegment.                                                        */
1259 
1260 #define subsegcopy(osub1, osub2)                                              \
1261   (osub2).ss = (osub1).ss;                                                    \
1262   (osub2).ssorient = (osub1).ssorient
1263 
1264 /* Test for equality of subsegments.                                         */
1265 
1266 #define subsegequal(osub1, osub2)                                             \
1267   (((osub1).ss == (osub2).ss) &&                                              \
1268    ((osub1).ssorient == (osub2).ssorient))
1269 
1270 /* Check or set a subsegment's deallocation.  Its second pointer is set to   */
1271 /*   NULL to indicate that it is not allocated.  (Its first pointer is used  */
1272 /*   for the stack of dead items.)  Its third pointer (its first vertex)     */
1273 /*   is set to NULL in case a `badsubseg' structure points to it.            */
1274 
1275 #define deadsubseg(sub)  ((sub)[1] == (subseg) NULL)
1276 
1277 #define killsubseg(sub)                                                       \
1278   (sub)[1] = (subseg) NULL;                                                   \
1279   (sub)[2] = (subseg) NULL
1280 
1281 /********* Primitives for interacting triangles and subsegments      *********/
1282 /*                                                                           */
1283 /*                                                                           */
1284 
1285 /* tspivot() finds a subsegment abutting a triangle.                         */
1286 
1287 #define tspivot(otri, osub)                                                   \
1288   sptr = (subseg) (otri).tri[6 + (otri).orient];                              \
1289   sdecode(sptr, osub)
1290 
1291 /* stpivot() finds a triangle abutting a subsegment.  It requires that the   */
1292 /*   variable `ptr' of type `triangle' be defined.                           */
1293 
1294 #define stpivot(osub, otri)                                                   \
1295   ptr = (triangle) (osub).ss[6 + (osub).ssorient];                            \
1296   decode(ptr, otri)
1297 
1298 /* Bond a triangle to a subsegment.                                          */
1299 
1300 #define tsbond(otri, osub)                                                    \
1301   (otri).tri[6 + (otri).orient] = (triangle) sencode(osub);                   \
1302   (osub).ss[6 + (osub).ssorient] = (subseg) encode(otri)
1303 
1304 /* Dissolve a bond (from the triangle side).                                 */
1305 
1306 #define tsdissolve(otri)                                                      \
1307   (otri).tri[6 + (otri).orient] = (triangle) m->dummysub
1308 
1309 /* Dissolve a bond (from the subsegment side).                               */
1310 
1311 #define stdissolve(osub)                                                      \
1312   (osub).ss[6 + (osub).ssorient] = (subseg) m->dummytri
1313 
1314 /********* Primitives for vertices                                   *********/
1315 /*                                                                           */
1316 /*                                                                           */
1317 
1318 #define vertexmark(vx)  ((int *) (vx))[m->vertexmarkindex]
1319 
1320 #define setvertexmark(vx, value)                                              \
1321   ((int *) (vx))[m->vertexmarkindex] = value
1322 
1323 #define vertextype(vx)  ((int *) (vx))[m->vertexmarkindex + 1]
1324 
1325 #define setvertextype(vx, value)                                              \
1326   ((int *) (vx))[m->vertexmarkindex + 1] = value
1327 
1328 #define vertex2tri(vx)  ((triangle *) (vx))[m->vertex2triindex]
1329 
1330 #define setvertex2tri(vx, value)                                              \
1331   ((triangle *) (vx))[m->vertex2triindex] = value
1332 
1333 /**                                                                         **/
1334 /**                                                                         **/
1335 /********* Mesh manipulation primitives end here                     *********/
1336 
1337 /********* User-defined triangle evaluation routine begins here      *********/
1338 /**                                                                         **/
1339 /**                                                                         **/
1340 
1341 /*****************************************************************************/
1342 /*                                                                           */
1343 /*  triunsuitable()   Determine if a triangle is unsuitable, and thus must   */
1344 /*                    be further refined.                                    */
1345 /*                                                                           */
1346 /*  You may write your own procedure that decides whether or not a selected  */
1347 /*  triangle is too big (and needs to be refined).  There are two ways to do */
1348 /*  this.                                                                    */
1349 /*                                                                           */
1350 /*  (1)  Modify the procedure `triunsuitable' below, then recompile          */
1351 /*  Triangle.                                                                */
1352 /*                                                                           */
1353 /*  (2)  Define the symbol EXTERNAL_TEST (either by adding the definition    */
1354 /*  to this file, or by using the appropriate compiler switch).  This way,   */
1355 /*  you can compile triangle.c separately from your test.  Write your own    */
1356 /*  `triunsuitable' procedure in a separate C file (using the same prototype */
1357 /*  as below).  Compile it and link the object code with triangle.o.         */
1358 /*                                                                           */
1359 /*  This procedure returns 1 if the triangle is too large and should be      */
1360 /*  refined; 0 otherwise.                                                    */
1361 /*                                                                           */
1362 /*****************************************************************************/
1363 
1364 #ifdef EXTERNAL_TEST
1365 
1366 int triunsuitable();
1367 
1368 #else /* not EXTERNAL_TEST */
1369 
1370 #ifdef ANSI_DECLARATORS
1371 int triunsuitable(vertex triorg, vertex tridest, vertex triapex, REAL area)
1372 #else /* not ANSI_DECLARATORS */
1373 int triunsuitable(triorg, tridest, triapex, area)
1374 vertex triorg;                              /* The triangle's origin vertex. */
1375 vertex tridest;                        /* The triangle's destination vertex. */
1376 vertex triapex;                               /* The triangle's apex vertex. */
1377 REAL area;                                      /* The area of the triangle. */
1378 #endif /* not ANSI_DECLARATORS */
1379 
1380 {
1381   REAL dxoa, dxda, dxod;
1382   REAL dyoa, dyda, dyod;
1383   REAL oalen, dalen, odlen;
1384   REAL maxlen;
1385 
1386   dxoa = triorg[0] - triapex[0];
1387   dyoa = triorg[1] - triapex[1];
1388   dxda = tridest[0] - triapex[0];
1389   dyda = tridest[1] - triapex[1];
1390   dxod = triorg[0] - tridest[0];
1391   dyod = triorg[1] - tridest[1];
1392   /* Find the squares of the lengths of the triangle's three edges. */
1393   oalen = dxoa * dxoa + dyoa * dyoa;
1394   dalen = dxda * dxda + dyda * dyda;
1395   odlen = dxod * dxod + dyod * dyod;
1396   /* Find the square of the length of the longest edge. */
1397   maxlen = (dalen > oalen) ? dalen : oalen;
1398   maxlen = (odlen > maxlen) ? odlen : maxlen;
1399 
1400   if (maxlen > 0.05 * (triorg[0] * triorg[0] + triorg[1] * triorg[1]) + 0.02) {
1401     return 1;
1402   } else {
1403     return 0;
1404   }
1405 }
1406 
1407 #endif /* not EXTERNAL_TEST */
1408 
1409 /**                                                                         **/
1410 /**                                                                         **/
1411 /********* User-defined triangle evaluation routine ends here        *********/
1412 
1413 /********* Memory allocation and program exit wrappers begin here    *********/
1414 /**                                                                         **/
1415 /**                                                                         **/
1416 
1417 #ifdef ANSI_DECLARATORS
1418 void triexit(int status)
1419 #else /* not ANSI_DECLARATORS */
1420 void triexit(status)
1421 int status;
1422 #endif /* not ANSI_DECLARATORS */
1423 
1424 {
1425   exit(status);
1426 }
1427 
1428 #ifdef ANSI_DECLARATORS
1429 void *trimalloc(int size)
1430 #else /* not ANSI_DECLARATORS */
1431 void *trimalloc(size)
1432 int size;
1433 #endif /* not ANSI_DECLARATORS */
1434 
1435 {
1436   void *memptr;
1437 
1438   memptr = (void *) malloc((unsigned int) size);
1439   if (memptr == (void *) NULL) {
1440     printf("Error:  Out of memory.\n");
1441     triexit(1);
1442   }
1443   return(memptr);
1444 }
1445 
1446 #ifdef ANSI_DECLARATORS
1447 void trifree(void *memptr)
1448 #else /* not ANSI_DECLARATORS */
1449 void trifree(memptr)
1450 void *memptr;
1451 #endif /* not ANSI_DECLARATORS */
1452 
1453 {
1454   free(memptr);
1455 }
1456 
1457 /**                                                                         **/
1458 /**                                                                         **/
1459 /********* Memory allocation and program exit wrappers end here      *********/
1460 
1461 /********* User interaction routines begin here                      *********/
1462 /**                                                                         **/
1463 /**                                                                         **/
1464 
1465 /*****************************************************************************/
1466 /*                                                                           */
1467 /*  syntax()   Print list of command line switches.                          */
1468 /*                                                                           */
1469 /*****************************************************************************/
1470 
1471 #ifndef TRILIBRARY
1472 
syntax()1473 void syntax()
1474 {
1475 #ifdef CDT_ONLY
1476 #ifdef REDUCED
1477   printf("triangle [-pAcjevngBPNEIOXzo_lQVh] input_file\n");
1478 #else /* not REDUCED */
1479   printf("triangle [-pAcjevngBPNEIOXzo_iFlCQVh] input_file\n");
1480 #endif /* not REDUCED */
1481 #else /* not CDT_ONLY */
1482 #ifdef REDUCED
1483   printf("triangle [-prq__a__uAcDjevngBPNEIOXzo_YS__lQVh] input_file\n");
1484 #else /* not REDUCED */
1485   printf("triangle [-prq__a__uAcDjevngBPNEIOXzo_YS__iFlsCQVh] input_file\n");
1486 #endif /* not REDUCED */
1487 #endif /* not CDT_ONLY */
1488 
1489   printf("    -p  Triangulates a Planar Straight Line Graph (.poly file).\n");
1490 #ifndef CDT_ONLY
1491   printf("    -r  Refines a previously generated mesh.\n");
1492   printf(
1493     "    -q  Quality mesh generation.  A minimum angle may be specified.\n");
1494   printf("    -a  Applies a maximum triangle area constraint.\n");
1495   printf("    -u  Applies a user-defined triangle constraint.\n");
1496 #endif /* not CDT_ONLY */
1497   printf(
1498     "    -A  Applies attributes to identify triangles in certain regions.\n");
1499   printf("    -c  Encloses the convex hull with segments.\n");
1500 #ifndef CDT_ONLY
1501   printf("    -D  Conforming Delaunay:  all triangles are truly Delaunay.\n");
1502 #endif /* not CDT_ONLY */
1503 /*
1504   printf("    -w  Weighted Delaunay triangulation.\n");
1505   printf("    -W  Regular triangulation (lower hull of a height field).\n");
1506 */
1507   printf("    -j  Jettison unused vertices from output .node file.\n");
1508   printf("    -e  Generates an edge list.\n");
1509   printf("    -v  Generates a Voronoi diagram.\n");
1510   printf("    -n  Generates a list of triangle neighbors.\n");
1511   printf("    -g  Generates an .off file for Geomview.\n");
1512   printf("    -B  Suppresses output of boundary information.\n");
1513   printf("    -P  Suppresses output of .poly file.\n");
1514   printf("    -N  Suppresses output of .node file.\n");
1515   printf("    -E  Suppresses output of .ele file.\n");
1516   printf("    -I  Suppresses mesh iteration numbers.\n");
1517   printf("    -O  Ignores holes in .poly file.\n");
1518   printf("    -X  Suppresses use of exact arithmetic.\n");
1519   printf("    -z  Numbers all items starting from zero (rather than one).\n");
1520   printf("    -o2 Generates second-order subparametric elements.\n");
1521 #ifndef CDT_ONLY
1522   printf("    -Y  Suppresses boundary segment splitting.\n");
1523   printf("    -S  Specifies maximum number of added Steiner points.\n");
1524 #endif /* not CDT_ONLY */
1525 #ifndef REDUCED
1526   printf("    -i  Uses incremental method, rather than divide-and-conquer.\n");
1527   printf("    -F  Uses Fortune's sweepline algorithm, rather than d-and-c.\n");
1528 #endif /* not REDUCED */
1529   printf("    -l  Uses vertical cuts only, rather than alternating cuts.\n");
1530 #ifndef REDUCED
1531 #ifndef CDT_ONLY
1532   printf(
1533     "    -s  Force segments into mesh by splitting (instead of using CDT).\n");
1534 #endif /* not CDT_ONLY */
1535   printf("    -C  Check consistency of final mesh.\n");
1536 #endif /* not REDUCED */
1537   printf("    -Q  Quiet:  No terminal output except errors.\n");
1538   printf("    -V  Verbose:  Detailed information on what I'm doing.\n");
1539   printf("    -h  Help:  Detailed instructions for Triangle.\n");
1540   triexit(0);
1541 }
1542 
1543 #endif /* not TRILIBRARY */
1544 
1545 /*****************************************************************************/
1546 /*                                                                           */
1547 /*  info()   Print out complete instructions.                                */
1548 /*                                                                           */
1549 /*****************************************************************************/
1550 
1551 #ifndef TRILIBRARY
1552 
info()1553 void info()
1554 {
1555   printf("Triangle\n");
1556   printf(
1557 "A Two-Dimensional Quality Mesh Generator and Delaunay Triangulator.\n");
1558   printf("Version 1.6\n\n");
1559   printf(
1560 "Copyright 1993, 1995, 1997, 1998, 2002, 2005 Jonathan Richard Shewchuk\n");
1561   printf("2360 Woolsey #H / Berkeley, California 94705-1927\n");
1562   printf("Bugs/comments to jrs@cs.berkeley.edu\n");
1563   printf(
1564 "Created as part of the Quake project (tools for earthquake simulation).\n");
1565   printf(
1566 "Supported in part by NSF Grant CMS-9318163 and an NSERC 1967 Scholarship.\n");
1567   printf("There is no warranty whatsoever.  Use at your own risk.\n");
1568 #ifdef SINGLE
1569   printf("This executable is compiled for single precision arithmetic.\n\n\n");
1570 #else /* not SINGLE */
1571   printf("This executable is compiled for double precision arithmetic.\n\n\n");
1572 #endif /* not SINGLE */
1573   printf(
1574 "Triangle generates exact Delaunay triangulations, constrained Delaunay\n");
1575   printf(
1576 "triangulations, conforming Delaunay triangulations, Voronoi diagrams, and\n");
1577   printf(
1578 "high-quality triangular meshes.  The latter can be generated with no small\n"
1579 );
1580   printf(
1581 "or large angles, and are thus suitable for finite element analysis.  If no\n"
1582 );
1583   printf(
1584 "command line switch is specified, your .node input file is read, and the\n");
1585   printf(
1586 "Delaunay triangulation is returned in .node and .ele output files.  The\n");
1587   printf("command syntax is:\n\n");
1588   printf("triangle [-prq__a__uAcDjevngBPNEIOXzo_YS__iFlsCQVh] input_file\n\n");
1589   printf(
1590 "Underscores indicate that numbers may optionally follow certain switches.\n");
1591   printf(
1592 "Do not leave any space between a switch and its numeric parameter.\n");
1593   printf(
1594 "input_file must be a file with extension .node, or extension .poly if the\n");
1595   printf(
1596 "-p switch is used.  If -r is used, you must supply .node and .ele files,\n");
1597   printf(
1598 "and possibly a .poly file and an .area file as well.  The formats of these\n"
1599 );
1600   printf("files are described below.\n\n");
1601   printf("Command Line Switches:\n\n");
1602   printf(
1603 "    -p  Reads a Planar Straight Line Graph (.poly file), which can specify\n"
1604 );
1605   printf(
1606 "        vertices, segments, holes, regional attributes, and regional area\n");
1607   printf(
1608 "        constraints.  Generates a constrained Delaunay triangulation (CDT)\n"
1609 );
1610   printf(
1611 "        fitting the input; or, if -s, -q, -a, or -u is used, a conforming\n");
1612   printf(
1613 "        constrained Delaunay triangulation (CCDT).  If you want a truly\n");
1614   printf(
1615 "        Delaunay (not just constrained Delaunay) triangulation, use -D as\n");
1616   printf(
1617 "        well.  When -p is not used, Triangle reads a .node file by default.\n"
1618 );
1619   printf(
1620 "    -r  Refines a previously generated mesh.  The mesh is read from a .node\n"
1621 );
1622   printf(
1623 "        file and an .ele file.  If -p is also used, a .poly file is read\n");
1624   printf(
1625 "        and used to constrain segments in the mesh.  If -a is also used\n");
1626   printf(
1627 "        (with no number following), an .area file is read and used to\n");
1628   printf(
1629 "        impose area constraints on the mesh.  Further details on refinement\n"
1630 );
1631   printf("        appear below.\n");
1632   printf(
1633 "    -q  Quality mesh generation by Delaunay refinement (a hybrid of Paul\n");
1634   printf(
1635 "        Chew's and Jim Ruppert's algorithms).  Adds vertices to the mesh to\n"
1636 );
1637   printf(
1638 "        ensure that all angles are between 20 and 140 degrees.  An\n");
1639   printf(
1640 "        alternative bound on the minimum angle, replacing 20 degrees, may\n");
1641   printf(
1642 "        be specified after the `q'.  The specified angle may include a\n");
1643   printf(
1644 "        decimal point, but not exponential notation.  Note that a bound of\n"
1645 );
1646   printf(
1647 "        theta degrees on the smallest angle also implies a bound of\n");
1648   printf(
1649 "        (180 - 2 theta) on the largest angle.  If the minimum angle is 28.6\n"
1650 );
1651   printf(
1652 "        degrees or smaller, Triangle is mathematically guaranteed to\n");
1653   printf(
1654 "        terminate (assuming infinite precision arithmetic--Triangle may\n");
1655   printf(
1656 "        fail to terminate if you run out of precision).  In practice,\n");
1657   printf(
1658 "        Triangle often succeeds for minimum angles up to 34 degrees.  For\n");
1659   printf(
1660 "        some meshes, however, you might need to reduce the minimum angle to\n"
1661 );
1662   printf(
1663 "        avoid problems associated with insufficient floating-point\n");
1664   printf("        precision.\n");
1665   printf(
1666 "    -a  Imposes a maximum triangle area.  If a number follows the `a', no\n");
1667   printf(
1668 "        triangle is generated whose area is larger than that number.  If no\n"
1669 );
1670   printf(
1671 "        number is specified, an .area file (if -r is used) or .poly file\n");
1672   printf(
1673 "        (if -r is not used) specifies a set of maximum area constraints.\n");
1674   printf(
1675 "        An .area file contains a separate area constraint for each\n");
1676   printf(
1677 "        triangle, and is useful for refining a finite element mesh based on\n"
1678 );
1679   printf(
1680 "        a posteriori error estimates.  A .poly file can optionally contain\n"
1681 );
1682   printf(
1683 "        an area constraint for each segment-bounded region, thereby\n");
1684   printf(
1685 "        controlling triangle densities in a first triangulation of a PSLG.\n"
1686 );
1687   printf(
1688 "        You can impose both a fixed area constraint and a varying area\n");
1689   printf(
1690 "        constraint by invoking the -a switch twice, once with and once\n");
1691   printf(
1692 "        without a number following.  Each area specified may include a\n");
1693   printf("        decimal point.\n");
1694   printf(
1695 "    -u  Imposes a user-defined constraint on triangle size.  There are two\n"
1696 );
1697   printf(
1698 "        ways to use this feature.  One is to edit the triunsuitable()\n");
1699   printf(
1700 "        procedure in triangle.c to encode any constraint you like, then\n");
1701   printf(
1702 "        recompile Triangle.  The other is to compile triangle.c with the\n");
1703   printf(
1704 "        EXTERNAL_TEST symbol set (compiler switch -DEXTERNAL_TEST), then\n");
1705   printf(
1706 "        link Triangle with a separate object file that implements\n");
1707   printf(
1708 "        triunsuitable().  In either case, the -u switch causes the user-\n");
1709   printf("        defined test to be applied to every triangle.\n");
1710   printf(
1711 "    -A  Assigns an additional floating-point attribute to each triangle\n");
1712   printf(
1713 "        that identifies what segment-bounded region each triangle belongs\n");
1714   printf(
1715 "        to.  Attributes are assigned to regions by the .poly file.  If a\n");
1716   printf(
1717 "        region is not explicitly marked by the .poly file, triangles in\n");
1718   printf(
1719 "        that region are assigned an attribute of zero.  The -A switch has\n");
1720   printf(
1721 "        an effect only when the -p switch is used and the -r switch is not.\n"
1722 );
1723   printf(
1724 "    -c  Creates segments on the convex hull of the triangulation.  If you\n");
1725   printf(
1726 "        are triangulating a vertex set, this switch causes a .poly file to\n"
1727 );
1728   printf(
1729 "        be written, containing all edges of the convex hull.  If you are\n");
1730   printf(
1731 "        triangulating a PSLG, this switch specifies that the whole convex\n");
1732   printf(
1733 "        hull of the PSLG should be triangulated, regardless of what\n");
1734   printf(
1735 "        segments the PSLG has.  If you do not use this switch when\n");
1736   printf(
1737 "        triangulating a PSLG, Triangle assumes that you have identified the\n"
1738 );
1739   printf(
1740 "        region to be triangulated by surrounding it with segments of the\n");
1741   printf(
1742 "        input PSLG.  Beware:  if you are not careful, this switch can cause\n"
1743 );
1744   printf(
1745 "        the introduction of an extremely thin angle between a PSLG segment\n"
1746 );
1747   printf(
1748 "        and a convex hull segment, which can cause overrefinement (and\n");
1749   printf(
1750 "        possibly failure if Triangle runs out of precision).  If you are\n");
1751   printf(
1752 "        refining a mesh, the -c switch works differently:  it causes a\n");
1753   printf(
1754 "        .poly file to be written containing the boundary edges of the mesh\n"
1755 );
1756   printf("        (useful if no .poly file was read).\n");
1757   printf(
1758 "    -D  Conforming Delaunay triangulation:  use this switch if you want to\n"
1759 );
1760   printf(
1761 "        ensure that all the triangles in the mesh are Delaunay, and not\n");
1762   printf(
1763 "        merely constrained Delaunay; or if you want to ensure that all the\n"
1764 );
1765   printf(
1766 "        Voronoi vertices lie within the triangulation.  (Some finite volume\n"
1767 );
1768   printf(
1769 "        methods have this requirement.)  This switch invokes Ruppert's\n");
1770   printf(
1771 "        original algorithm, which splits every subsegment whose diametral\n");
1772   printf(
1773 "        circle is encroached.  It usually increases the number of vertices\n"
1774 );
1775   printf("        and triangles.\n");
1776   printf(
1777 "    -j  Jettisons vertices that are not part of the final triangulation\n");
1778   printf(
1779 "        from the output .node file.  By default, Triangle copies all\n");
1780   printf(
1781 "        vertices in the input .node file to the output .node file, in the\n");
1782   printf(
1783 "        same order, so their indices do not change.  The -j switch prevents\n"
1784 );
1785   printf(
1786 "        duplicated input vertices, or vertices `eaten' by holes, from\n");
1787   printf(
1788 "        appearing in the output .node file.  Thus, if two input vertices\n");
1789   printf(
1790 "        have exactly the same coordinates, only the first appears in the\n");
1791   printf(
1792 "        output.  If any vertices are jettisoned, the vertex numbering in\n");
1793   printf(
1794 "        the output .node file differs from that of the input .node file.\n");
1795   printf(
1796 "    -e  Outputs (to an .edge file) a list of edges of the triangulation.\n");
1797   printf(
1798 "    -v  Outputs the Voronoi diagram associated with the triangulation.\n");
1799   printf(
1800 "        Does not attempt to detect degeneracies, so some Voronoi vertices\n");
1801   printf(
1802 "        may be duplicated.  See the discussion of Voronoi diagrams below.\n");
1803   printf(
1804 "    -n  Outputs (to a .neigh file) a list of triangles neighboring each\n");
1805   printf("        triangle.\n");
1806   printf(
1807 "    -g  Outputs the mesh to an Object File Format (.off) file, suitable for\n"
1808 );
1809   printf("        viewing with the Geometry Center's Geomview package.\n");
1810   printf(
1811 "    -B  No boundary markers in the output .node, .poly, and .edge output\n");
1812   printf(
1813 "        files.  See the detailed discussion of boundary markers below.\n");
1814   printf(
1815 "    -P  No output .poly file.  Saves disk space, but you lose the ability\n");
1816   printf(
1817 "        to maintain constraining segments on later refinements of the mesh.\n"
1818 );
1819   printf("    -N  No output .node file.\n");
1820   printf("    -E  No output .ele file.\n");
1821   printf(
1822 "    -I  No iteration numbers.  Suppresses the output of .node and .poly\n");
1823   printf(
1824 "        files, so your input files won't be overwritten.  (If your input is\n"
1825 );
1826   printf(
1827 "        a .poly file only, a .node file is written.)  Cannot be used with\n");
1828   printf(
1829 "        the -r switch, because that would overwrite your input .ele file.\n");
1830   printf(
1831 "        Shouldn't be used with the -q, -a, -u, or -s switch if you are\n");
1832   printf(
1833 "        using a .node file for input, because no .node file is written, so\n"
1834 );
1835   printf("        there is no record of any added Steiner points.\n");
1836   printf("    -O  No holes.  Ignores the holes in the .poly file.\n");
1837   printf(
1838 "    -X  No exact arithmetic.  Normally, Triangle uses exact floating-point\n"
1839 );
1840   printf(
1841 "        arithmetic for certain tests if it thinks the inexact tests are not\n"
1842 );
1843   printf(
1844 "        accurate enough.  Exact arithmetic ensures the robustness of the\n");
1845   printf(
1846 "        triangulation algorithms, despite floating-point roundoff error.\n");
1847   printf(
1848 "        Disabling exact arithmetic with the -X switch causes a small\n");
1849   printf(
1850 "        improvement in speed and creates the possibility that Triangle will\n"
1851 );
1852   printf("        fail to produce a valid mesh.  Not recommended.\n");
1853   printf(
1854 "    -z  Numbers all items starting from zero (rather than one).  Note that\n"
1855 );
1856   printf(
1857 "        this switch is normally overridden by the value used to number the\n"
1858 );
1859   printf(
1860 "        first vertex of the input .node or .poly file.  However, this\n");
1861   printf(
1862 "        switch is useful when calling Triangle from another program.\n");
1863   printf(
1864 "    -o2 Generates second-order subparametric elements with six nodes each.\n"
1865 );
1866   printf(
1867 "    -Y  No new vertices on the boundary.  This switch is useful when the\n");
1868   printf(
1869 "        mesh boundary must be preserved so that it conforms to some\n");
1870   printf(
1871 "        adjacent mesh.  Be forewarned that you will probably sacrifice much\n"
1872 );
1873   printf(
1874 "        of the quality of the mesh; Triangle will try, but the resulting\n");
1875   printf(
1876 "        mesh may contain poorly shaped triangles.  Works well if all the\n");
1877   printf(
1878 "        boundary vertices are closely spaced.  Specify this switch twice\n");
1879   printf(
1880 "        (`-YY') to prevent all segment splitting, including internal\n");
1881   printf("        boundaries.\n");
1882   printf(
1883 "    -S  Specifies the maximum number of Steiner points (vertices that are\n");
1884   printf(
1885 "        not in the input, but are added to meet the constraints on minimum\n"
1886 );
1887   printf(
1888 "        angle and maximum area).  The default is to allow an unlimited\n");
1889   printf(
1890 "        number.  If you specify this switch with no number after it,\n");
1891   printf(
1892 "        the limit is set to zero.  Triangle always adds vertices at segment\n"
1893 );
1894   printf(
1895 "        intersections, even if it needs to use more vertices than the limit\n"
1896 );
1897   printf(
1898 "        you set.  When Triangle inserts segments by splitting (-s), it\n");
1899   printf(
1900 "        always adds enough vertices to ensure that all the segments of the\n"
1901 );
1902   printf("        PLSG are recovered, ignoring the limit if necessary.\n");
1903   printf(
1904 "    -i  Uses an incremental rather than a divide-and-conquer algorithm to\n");
1905   printf(
1906 "        construct a Delaunay triangulation.  Try it if the divide-and-\n");
1907   printf("        conquer algorithm fails.\n");
1908   printf(
1909 "    -F  Uses Steven Fortune's sweepline algorithm to construct a Delaunay\n");
1910   printf(
1911 "        triangulation.  Warning:  does not use exact arithmetic for all\n");
1912   printf("        calculations.  An exact result is not guaranteed.\n");
1913   printf(
1914 "    -l  Uses only vertical cuts in the divide-and-conquer algorithm.  By\n");
1915   printf(
1916 "        default, Triangle alternates between vertical and horizontal cuts,\n"
1917 );
1918   printf(
1919 "        which usually improve the speed except with vertex sets that are\n");
1920   printf(
1921 "        small or short and wide.  This switch is primarily of theoretical\n");
1922   printf("        interest.\n");
1923   printf(
1924 "    -s  Specifies that segments should be forced into the triangulation by\n"
1925 );
1926   printf(
1927 "        recursively splitting them at their midpoints, rather than by\n");
1928   printf(
1929 "        generating a constrained Delaunay triangulation.  Segment splitting\n"
1930 );
1931   printf(
1932 "        is true to Ruppert's original algorithm, but can create needlessly\n"
1933 );
1934   printf(
1935 "        small triangles.  This switch is primarily of theoretical interest.\n"
1936 );
1937   printf(
1938 "    -C  Check the consistency of the final mesh.  Uses exact arithmetic for\n"
1939 );
1940   printf(
1941 "        checking, even if the -X switch is used.  Useful if you suspect\n");
1942   printf("        Triangle is buggy.\n");
1943   printf(
1944 "    -Q  Quiet:  Suppresses all explanation of what Triangle is doing,\n");
1945   printf("        unless an error occurs.\n");
1946   printf(
1947 "    -V  Verbose:  Gives detailed information about what Triangle is doing.\n"
1948 );
1949   printf(
1950 "        Add more `V's for increasing amount of detail.  `-V' is most\n");
1951   printf(
1952 "        useful; itgives information on algorithmic progress and much more\n");
1953   printf(
1954 "        detailed statistics.  `-VV' gives vertex-by-vertex details, and\n");
1955   printf(
1956 "        prints so much that Triangle runs much more slowly.  `-VVVV' gives\n"
1957 );
1958   printf("        information only a debugger could love.\n");
1959   printf("    -h  Help:  Displays these instructions.\n");
1960   printf("\n");
1961   printf("Definitions:\n");
1962   printf("\n");
1963   printf(
1964 "  A Delaunay triangulation of a vertex set is a triangulation whose\n");
1965   printf(
1966 "  vertices are the vertex set, that covers the convex hull of the vertex\n");
1967   printf(
1968 "  set.  A Delaunay triangulation has the property that no vertex lies\n");
1969   printf(
1970 "  inside the circumscribing circle (circle that passes through all three\n");
1971   printf("  vertices) of any triangle in the triangulation.\n\n");
1972   printf(
1973 "  A Voronoi diagram of a vertex set is a subdivision of the plane into\n");
1974   printf(
1975 "  polygonal cells (some of which may be unbounded, meaning infinitely\n");
1976   printf(
1977 "  large), where each cell is the set of points in the plane that are closer\n"
1978 );
1979   printf(
1980 "  to some input vertex than to any other input vertex.  The Voronoi diagram\n"
1981 );
1982   printf("  is a geometric dual of the Delaunay triangulation.\n\n");
1983   printf(
1984 "  A Planar Straight Line Graph (PSLG) is a set of vertices and segments.\n");
1985   printf(
1986 "  Segments are simply edges, whose endpoints are all vertices in the PSLG.\n"
1987 );
1988   printf(
1989 "  Segments may intersect each other only at their endpoints.  The file\n");
1990   printf("  format for PSLGs (.poly files) is described below.\n\n");
1991   printf(
1992 "  A constrained Delaunay triangulation (CDT) of a PSLG is similar to a\n");
1993   printf(
1994 "  Delaunay triangulation, but each PSLG segment is present as a single edge\n"
1995 );
1996   printf(
1997 "  of the CDT.  (A constrained Delaunay triangulation is not truly a\n");
1998   printf(
1999 "  Delaunay triangulation, because some of its triangles might not be\n");
2000   printf(
2001 "  Delaunay.)  By definition, a CDT does not have any vertices other than\n");
2002   printf(
2003 "  those specified in the input PSLG.  Depending on context, a CDT might\n");
2004   printf(
2005 "  cover the convex hull of the PSLG, or it might cover only a segment-\n");
2006   printf("  bounded region (e.g. a polygon).\n\n");
2007   printf(
2008 "  A conforming Delaunay triangulation of a PSLG is a triangulation in which\n"
2009 );
2010   printf(
2011 "  each triangle is truly Delaunay, and each PSLG segment is represented by\n"
2012 );
2013   printf(
2014 "  a linear contiguous sequence of edges of the triangulation.  New vertices\n"
2015 );
2016   printf(
2017 "  (not part of the PSLG) may appear, and each input segment may have been\n");
2018   printf(
2019 "  subdivided into shorter edges (subsegments) by these additional vertices.\n"
2020 );
2021   printf(
2022 "  The new vertices are frequently necessary to maintain the Delaunay\n");
2023   printf("  property while ensuring that every segment is represented.\n\n");
2024   printf(
2025 "  A conforming constrained Delaunay triangulation (CCDT) of a PSLG is a\n");
2026   printf(
2027 "  triangulation of a PSLG whose triangles are constrained Delaunay.  New\n");
2028   printf("  vertices may appear, and input segments may be subdivided into\n");
2029   printf(
2030 "  subsegments, but not to guarantee that segments are respected; rather, to\n"
2031 );
2032   printf(
2033 "  improve the quality of the triangles.  The high-quality meshes produced\n");
2034   printf(
2035 "  by the -q switch are usually CCDTs, but can be made conforming Delaunay\n");
2036   printf("  with the -D switch.\n\n");
2037   printf("File Formats:\n\n");
2038   printf(
2039 "  All files may contain comments prefixed by the character '#'.  Vertices,\n"
2040 );
2041   printf(
2042 "  triangles, edges, holes, and maximum area constraints must be numbered\n");
2043   printf(
2044 "  consecutively, starting from either 1 or 0.  Whichever you choose, all\n");
2045   printf(
2046 "  input files must be consistent; if the vertices are numbered from 1, so\n");
2047   printf(
2048 "  must be all other objects.  Triangle automatically detects your choice\n");
2049   printf(
2050 "  while reading the .node (or .poly) file.  (When calling Triangle from\n");
2051   printf(
2052 "  another program, use the -z switch if you wish to number objects from\n");
2053   printf("  zero.)  Examples of these file formats are given below.\n\n");
2054   printf("  .node files:\n");
2055   printf(
2056 "    First line:  <# of vertices> <dimension (must be 2)> <# of attributes>\n"
2057 );
2058   printf(
2059 "                                           <# of boundary markers (0 or 1)>\n"
2060 );
2061   printf(
2062 "    Remaining lines:  <vertex #> <x> <y> [attributes] [boundary marker]\n");
2063   printf("\n");
2064   printf(
2065 "    The attributes, which are typically floating-point values of physical\n");
2066   printf(
2067 "    quantities (such as mass or conductivity) associated with the nodes of\n"
2068 );
2069   printf(
2070 "    a finite element mesh, are copied unchanged to the output mesh.  If -q,\n"
2071 );
2072   printf(
2073 "    -a, -u, -D, or -s is selected, each new Steiner point added to the mesh\n"
2074 );
2075   printf("    has attributes assigned to it by linear interpolation.\n\n");
2076   printf(
2077 "    If the fourth entry of the first line is `1', the last column of the\n");
2078   printf(
2079 "    remainder of the file is assumed to contain boundary markers.  Boundary\n"
2080 );
2081   printf(
2082 "    markers are used to identify boundary vertices and vertices resting on\n"
2083 );
2084   printf(
2085 "    PSLG segments; a complete description appears in a section below.  The\n"
2086 );
2087   printf(
2088 "    .node file produced by Triangle contains boundary markers in the last\n");
2089   printf("    column unless they are suppressed by the -B switch.\n\n");
2090   printf("  .ele files:\n");
2091   printf(
2092 "    First line:  <# of triangles> <nodes per triangle> <# of attributes>\n");
2093   printf(
2094 "    Remaining lines:  <triangle #> <node> <node> <node> ... [attributes]\n");
2095   printf("\n");
2096   printf(
2097 "    Nodes are indices into the corresponding .node file.  The first three\n");
2098   printf(
2099 "    nodes are the corner vertices, and are listed in counterclockwise order\n"
2100 );
2101   printf(
2102 "    around each triangle.  (The remaining nodes, if any, depend on the type\n"
2103 );
2104   printf("    of finite element used.)\n\n");
2105   printf(
2106 "    The attributes are just like those of .node files.  Because there is no\n"
2107 );
2108   printf(
2109 "    simple mapping from input to output triangles, Triangle attempts to\n");
2110   printf(
2111 "    interpolate attributes, and may cause a lot of diffusion of attributes\n"
2112 );
2113   printf(
2114 "    among nearby triangles as the triangulation is refined.  Attributes do\n"
2115 );
2116   printf("    not diffuse across segments, so attributes used to identify\n");
2117   printf("    segment-bounded regions remain intact.\n\n");
2118   printf(
2119 "    In .ele files produced by Triangle, each triangular element has three\n");
2120   printf(
2121 "    nodes (vertices) unless the -o2 switch is used, in which case\n");
2122   printf(
2123 "    subparametric quadratic elements with six nodes each are generated.\n");
2124   printf(
2125 "    The first three nodes are the corners in counterclockwise order, and\n");
2126   printf(
2127 "    the fourth, fifth, and sixth nodes lie on the midpoints of the edges\n");
2128   printf(
2129 "    opposite the first, second, and third vertices, respectively.\n");
2130   printf("\n");
2131   printf("  .poly files:\n");
2132   printf(
2133 "    First line:  <# of vertices> <dimension (must be 2)> <# of attributes>\n"
2134 );
2135   printf(
2136 "                                           <# of boundary markers (0 or 1)>\n"
2137 );
2138   printf(
2139 "    Following lines:  <vertex #> <x> <y> [attributes] [boundary marker]\n");
2140   printf("    One line:  <# of segments> <# of boundary markers (0 or 1)>\n");
2141   printf(
2142 "    Following lines:  <segment #> <endpoint> <endpoint> [boundary marker]\n");
2143   printf("    One line:  <# of holes>\n");
2144   printf("    Following lines:  <hole #> <x> <y>\n");
2145   printf(
2146 "    Optional line:  <# of regional attributes and/or area constraints>\n");
2147   printf(
2148 "    Optional following lines:  <region #> <x> <y> <attribute> <max area>\n");
2149   printf("\n");
2150   printf(
2151 "    A .poly file represents a PSLG, as well as some additional information.\n"
2152 );
2153   printf(
2154 "    The first section lists all the vertices, and is identical to the\n");
2155   printf(
2156 "    format of .node files.  <# of vertices> may be set to zero to indicate\n"
2157 );
2158   printf(
2159 "    that the vertices are listed in a separate .node file; .poly files\n");
2160   printf(
2161 "    produced by Triangle always have this format.  A vertex set represented\n"
2162 );
2163   printf(
2164 "    this way has the advantage that it may easily be triangulated with or\n");
2165   printf(
2166 "    without segments (depending on whether the -p switch is invoked).\n");
2167   printf("\n");
2168   printf(
2169 "    The second section lists the segments.  Segments are edges whose\n");
2170   printf(
2171 "    presence in the triangulation is enforced.  (Depending on the choice of\n"
2172 );
2173   printf(
2174 "    switches, segment might be subdivided into smaller edges).  Each\n");
2175   printf(
2176 "    segment is specified by listing the indices of its two endpoints.  This\n"
2177 );
2178   printf(
2179 "    means that you must include its endpoints in the vertex list.  Each\n");
2180   printf("    segment, like each point, may have a boundary marker.\n\n");
2181   printf(
2182 "    If -q, -a, -u, and -s are not selected, Triangle produces a constrained\n"
2183 );
2184   printf(
2185 "    Delaunay triangulation (CDT), in which each segment appears as a single\n"
2186 );
2187   printf(
2188 "    edge in the triangulation.  If -q, -a, -u, or -s is selected, Triangle\n"
2189 );
2190   printf(
2191 "    produces a conforming constrained Delaunay triangulation (CCDT), in\n");
2192   printf(
2193 "    which segments may be subdivided into smaller edges.  If -D is\n");
2194   printf(
2195 "    selected, Triangle produces a conforming Delaunay triangulation, so\n");
2196   printf(
2197 "    that every triangle is Delaunay, and not just constrained Delaunay.\n");
2198   printf("\n");
2199   printf(
2200 "    The third section lists holes (and concavities, if -c is selected) in\n");
2201   printf(
2202 "    the triangulation.  Holes are specified by identifying a point inside\n");
2203   printf(
2204 "    each hole.  After the triangulation is formed, Triangle creates holes\n");
2205   printf(
2206 "    by eating triangles, spreading out from each hole point until its\n");
2207   printf(
2208 "    progress is blocked by segments in the PSLG.  You must be careful to\n");
2209   printf(
2210 "    enclose each hole in segments, or your whole triangulation might be\n");
2211   printf(
2212 "    eaten away.  If the two triangles abutting a segment are eaten, the\n");
2213   printf(
2214 "    segment itself is also eaten.  Do not place a hole directly on a\n");
2215   printf("    segment; if you do, Triangle chooses one side of the segment\n");
2216   printf("    arbitrarily.\n\n");
2217   printf(
2218 "    The optional fourth section lists regional attributes (to be assigned\n");
2219   printf(
2220 "    to all triangles in a region) and regional constraints on the maximum\n");
2221   printf(
2222 "    triangle area.  Triangle reads this section only if the -A switch is\n");
2223   printf(
2224 "    used or the -a switch is used without a number following it, and the -r\n"
2225 );
2226   printf(
2227 "    switch is not used.  Regional attributes and area constraints are\n");
2228   printf(
2229 "    propagated in the same manner as holes:  you specify a point for each\n");
2230   printf(
2231 "    attribute and/or constraint, and the attribute and/or constraint\n");
2232   printf(
2233 "    affects the whole region (bounded by segments) containing the point.\n");
2234   printf(
2235 "    If two values are written on a line after the x and y coordinate, the\n");
2236   printf(
2237 "    first such value is assumed to be a regional attribute (but is only\n");
2238   printf(
2239 "    applied if the -A switch is selected), and the second value is assumed\n"
2240 );
2241   printf(
2242 "    to be a regional area constraint (but is only applied if the -a switch\n"
2243 );
2244   printf(
2245 "    is selected).  You may specify just one value after the coordinates,\n");
2246   printf(
2247 "    which can serve as both an attribute and an area constraint, depending\n"
2248 );
2249   printf(
2250 "    on the choice of switches.  If you are using the -A and -a switches\n");
2251   printf(
2252 "    simultaneously and wish to assign an attribute to some region without\n");
2253   printf("    imposing an area constraint, use a negative maximum area.\n\n");
2254   printf(
2255 "    When a triangulation is created from a .poly file, you must either\n");
2256   printf(
2257 "    enclose the entire region to be triangulated in PSLG segments, or\n");
2258   printf(
2259 "    use the -c switch, which automatically creates extra segments that\n");
2260   printf(
2261 "    enclose the convex hull of the PSLG.  If you do not use the -c switch,\n"
2262 );
2263   printf(
2264 "    Triangle eats all triangles that are not enclosed by segments; if you\n");
2265   printf(
2266 "    are not careful, your whole triangulation may be eaten away.  If you do\n"
2267 );
2268   printf(
2269 "    use the -c switch, you can still produce concavities by the appropriate\n"
2270 );
2271   printf(
2272 "    placement of holes just inside the boundary of the convex hull.\n");
2273   printf("\n");
2274   printf(
2275 "    An ideal PSLG has no intersecting segments, nor any vertices that lie\n");
2276   printf(
2277 "    upon segments (except, of course, the endpoints of each segment).  You\n"
2278 );
2279   printf(
2280 "    aren't required to make your .poly files ideal, but you should be aware\n"
2281 );
2282   printf(
2283 "    of what can go wrong.  Segment intersections are relatively safe--\n");
2284   printf(
2285 "    Triangle calculates the intersection points for you and adds them to\n");
2286   printf(
2287 "    the triangulation--as long as your machine's floating-point precision\n");
2288   printf(
2289 "    doesn't become a problem.  You are tempting the fates if you have three\n"
2290 );
2291   printf(
2292 "    segments that cross at the same location, and expect Triangle to figure\n"
2293 );
2294   printf(
2295 "    out where the intersection point is.  Thanks to floating-point roundoff\n"
2296 );
2297   printf(
2298 "    error, Triangle will probably decide that the three segments intersect\n"
2299 );
2300   printf(
2301 "    at three different points, and you will find a minuscule triangle in\n");
2302   printf(
2303 "    your output--unless Triangle tries to refine the tiny triangle, uses\n");
2304   printf(
2305 "    up the last bit of machine precision, and fails to terminate at all.\n");
2306   printf(
2307 "    You're better off putting the intersection point in the input files,\n");
2308   printf(
2309 "    and manually breaking up each segment into two.  Similarly, if you\n");
2310   printf(
2311 "    place a vertex at the middle of a segment, and hope that Triangle will\n"
2312 );
2313   printf(
2314 "    break up the segment at that vertex, you might get lucky.  On the other\n"
2315 );
2316   printf(
2317 "    hand, Triangle might decide that the vertex doesn't lie precisely on\n");
2318   printf(
2319 "    the segment, and you'll have a needle-sharp triangle in your output--or\n"
2320 );
2321   printf("    a lot of tiny triangles if you're generating a quality mesh.\n");
2322   printf("\n");
2323   printf(
2324 "    When Triangle reads a .poly file, it also writes a .poly file, which\n");
2325   printf(
2326 "    includes all the subsegments--the edges that are parts of input\n");
2327   printf(
2328 "    segments.  If the -c switch is used, the output .poly file also\n");
2329   printf(
2330 "    includes all of the edges on the convex hull.  Hence, the output .poly\n"
2331 );
2332   printf(
2333 "    file is useful for finding edges associated with input segments and for\n"
2334 );
2335   printf(
2336 "    setting boundary conditions in finite element simulations.  Moreover,\n");
2337   printf(
2338 "    you will need the output .poly file if you plan to refine the output\n");
2339   printf(
2340 "    mesh, and don't want segments to be missing in later triangulations.\n");
2341   printf("\n");
2342   printf("  .area files:\n");
2343   printf("    First line:  <# of triangles>\n");
2344   printf("    Following lines:  <triangle #> <maximum area>\n");
2345   printf("\n");
2346   printf(
2347 "    An .area file associates with each triangle a maximum area that is used\n"
2348 );
2349   printf(
2350 "    for mesh refinement.  As with other file formats, every triangle must\n");
2351   printf(
2352 "    be represented, and the triangles must be numbered consecutively.  A\n");
2353   printf(
2354 "    triangle may be left unconstrained by assigning it a negative maximum\n");
2355   printf("    area.\n\n");
2356   printf("  .edge files:\n");
2357   printf("    First line:  <# of edges> <# of boundary markers (0 or 1)>\n");
2358   printf(
2359 "    Following lines:  <edge #> <endpoint> <endpoint> [boundary marker]\n");
2360   printf("\n");
2361   printf(
2362 "    Endpoints are indices into the corresponding .node file.  Triangle can\n"
2363 );
2364   printf(
2365 "    produce .edge files (use the -e switch), but cannot read them.  The\n");
2366   printf(
2367 "    optional column of boundary markers is suppressed by the -B switch.\n");
2368   printf("\n");
2369   printf(
2370 "    In Voronoi diagrams, one also finds a special kind of edge that is an\n");
2371   printf(
2372 "    infinite ray with only one endpoint.  For these edges, a different\n");
2373   printf("    format is used:\n\n");
2374   printf("        <edge #> <endpoint> -1 <direction x> <direction y>\n\n");
2375   printf(
2376 "    The `direction' is a floating-point vector that indicates the direction\n"
2377 );
2378   printf("    of the infinite ray.\n\n");
2379   printf("  .neigh files:\n");
2380   printf(
2381 "    First line:  <# of triangles> <# of neighbors per triangle (always 3)>\n"
2382 );
2383   printf(
2384 "    Following lines:  <triangle #> <neighbor> <neighbor> <neighbor>\n");
2385   printf("\n");
2386   printf(
2387 "    Neighbors are indices into the corresponding .ele file.  An index of -1\n"
2388 );
2389   printf(
2390 "    indicates no neighbor (because the triangle is on an exterior\n");
2391   printf(
2392 "    boundary).  The first neighbor of triangle i is opposite the first\n");
2393   printf("    corner of triangle i, and so on.\n\n");
2394   printf(
2395 "    Triangle can produce .neigh files (use the -n switch), but cannot read\n"
2396 );
2397   printf("    them.\n\n");
2398   printf("Boundary Markers:\n\n");
2399   printf(
2400 "  Boundary markers are tags used mainly to identify which output vertices\n");
2401   printf(
2402 "  and edges are associated with which PSLG segment, and to identify which\n");
2403   printf(
2404 "  vertices and edges occur on a boundary of the triangulation.  A common\n");
2405   printf(
2406 "  use is to determine where boundary conditions should be applied to a\n");
2407   printf(
2408 "  finite element mesh.  You can prevent boundary markers from being written\n"
2409 );
2410   printf("  into files produced by Triangle by using the -B switch.\n\n");
2411   printf(
2412 "  The boundary marker associated with each segment in an output .poly file\n"
2413 );
2414   printf("  and each edge in an output .edge file is chosen as follows:\n");
2415   printf(
2416 "    - If an output edge is part or all of a PSLG segment with a nonzero\n");
2417   printf(
2418 "      boundary marker, then the edge is assigned the same marker.\n");
2419   printf(
2420 "    - Otherwise, if the edge lies on a boundary of the triangulation\n");
2421   printf(
2422 "      (even the boundary of a hole), then the edge is assigned the marker\n");
2423   printf("      one (1).\n");
2424   printf("    - Otherwise, the edge is assigned the marker zero (0).\n");
2425   printf(
2426 "  The boundary marker associated with each vertex in an output .node file\n");
2427   printf("  is chosen as follows:\n");
2428   printf(
2429 "    - If a vertex is assigned a nonzero boundary marker in the input file,\n"
2430 );
2431   printf(
2432 "      then it is assigned the same marker in the output .node file.\n");
2433   printf(
2434 "    - Otherwise, if the vertex lies on a PSLG segment (even if it is an\n");
2435   printf(
2436 "      endpoint of the segment) with a nonzero boundary marker, then the\n");
2437   printf(
2438 "      vertex is assigned the same marker.  If the vertex lies on several\n");
2439   printf("      such segments, one of the markers is chosen arbitrarily.\n");
2440   printf(
2441 "    - Otherwise, if the vertex occurs on a boundary of the triangulation,\n");
2442   printf("      then the vertex is assigned the marker one (1).\n");
2443   printf("    - Otherwise, the vertex is assigned the marker zero (0).\n");
2444   printf("\n");
2445   printf(
2446 "  If you want Triangle to determine for you which vertices and edges are on\n"
2447 );
2448   printf(
2449 "  the boundary, assign them the boundary marker zero (or use no markers at\n"
2450 );
2451   printf(
2452 "  all) in your input files.  In the output files, all boundary vertices,\n");
2453   printf("  edges, and segments will be assigned the value one.\n\n");
2454   printf("Triangulation Iteration Numbers:\n\n");
2455   printf(
2456 "  Because Triangle can read and refine its own triangulations, input\n");
2457   printf(
2458 "  and output files have iteration numbers.  For instance, Triangle might\n");
2459   printf(
2460 "  read the files mesh.3.node, mesh.3.ele, and mesh.3.poly, refine the\n");
2461   printf(
2462 "  triangulation, and output the files mesh.4.node, mesh.4.ele, and\n");
2463   printf("  mesh.4.poly.  Files with no iteration number are treated as if\n");
2464   printf(
2465 "  their iteration number is zero; hence, Triangle might read the file\n");
2466   printf(
2467 "  points.node, triangulate it, and produce the files points.1.node and\n");
2468   printf("  points.1.ele.\n\n");
2469   printf(
2470 "  Iteration numbers allow you to create a sequence of successively finer\n");
2471   printf(
2472 "  meshes suitable for multigrid methods.  They also allow you to produce a\n"
2473 );
2474   printf(
2475 "  sequence of meshes using error estimate-driven mesh refinement.\n");
2476   printf("\n");
2477   printf(
2478 "  If you're not using refinement or quality meshing, and you don't like\n");
2479   printf(
2480 "  iteration numbers, use the -I switch to disable them.  This switch also\n");
2481   printf(
2482 "  disables output of .node and .poly files to prevent your input files from\n"
2483 );
2484   printf(
2485 "  being overwritten.  (If the input is a .poly file that contains its own\n");
2486   printf(
2487 "  points, a .node file is written.  This can be quite convenient for\n");
2488   printf("  computing CDTs or quality meshes.)\n\n");
2489   printf("Examples of How to Use Triangle:\n\n");
2490   printf(
2491 "  `triangle dots' reads vertices from dots.node, and writes their Delaunay\n"
2492 );
2493   printf(
2494 "  triangulation to dots.1.node and dots.1.ele.  (dots.1.node is identical\n");
2495   printf(
2496 "  to dots.node.)  `triangle -I dots' writes the triangulation to dots.ele\n");
2497   printf(
2498 "  instead.  (No additional .node file is needed, so none is written.)\n");
2499   printf("\n");
2500   printf(
2501 "  `triangle -pe object.1' reads a PSLG from object.1.poly (and possibly\n");
2502   printf(
2503 "  object.1.node, if the vertices are omitted from object.1.poly) and writes\n"
2504 );
2505   printf(
2506 "  its constrained Delaunay triangulation to object.2.node and object.2.ele.\n"
2507 );
2508   printf(
2509 "  The segments are copied to object.2.poly, and all edges are written to\n");
2510   printf("  object.2.edge.\n\n");
2511   printf(
2512 "  `triangle -pq31.5a.1 object' reads a PSLG from object.poly (and possibly\n"
2513 );
2514   printf(
2515 "  object.node), generates a mesh whose angles are all between 31.5 and 117\n"
2516 );
2517   printf(
2518 "  degrees and whose triangles all have areas of 0.1 or less, and writes the\n"
2519 );
2520   printf(
2521 "  mesh to object.1.node and object.1.ele.  Each segment may be broken up\n");
2522   printf("  into multiple subsegments; these are written to object.1.poly.\n");
2523   printf("\n");
2524   printf(
2525 "  Here is a sample file `box.poly' describing a square with a square hole:\n"
2526 );
2527   printf("\n");
2528   printf(
2529 "    # A box with eight vertices in 2D, no attributes, one boundary marker.\n"
2530 );
2531   printf("    8 2 0 1\n");
2532   printf("     # Outer box has these vertices:\n");
2533   printf("     1   0 0   0\n");
2534   printf("     2   0 3   0\n");
2535   printf("     3   3 0   0\n");
2536   printf("     4   3 3   33     # A special marker for this vertex.\n");
2537   printf("     # Inner square has these vertices:\n");
2538   printf("     5   1 1   0\n");
2539   printf("     6   1 2   0\n");
2540   printf("     7   2 1   0\n");
2541   printf("     8   2 2   0\n");
2542   printf("    # Five segments with boundary markers.\n");
2543   printf("    5 1\n");
2544   printf("     1   1 2   5      # Left side of outer box.\n");
2545   printf("     # Square hole has these segments:\n");
2546   printf("     2   5 7   0\n");
2547   printf("     3   7 8   0\n");
2548   printf("     4   8 6   10\n");
2549   printf("     5   6 5   0\n");
2550   printf("    # One hole in the middle of the inner square.\n");
2551   printf("    1\n");
2552   printf("     1   1.5 1.5\n");
2553   printf("\n");
2554   printf(
2555 "  Note that some segments are missing from the outer square, so you must\n");
2556   printf(
2557 "  use the `-c' switch.  After `triangle -pqc box.poly', here is the output\n"
2558 );
2559   printf(
2560 "  file `box.1.node', with twelve vertices.  The last four vertices were\n");
2561   printf(
2562 "  added to meet the angle constraint.  Vertices 1, 2, and 9 have markers\n");
2563   printf(
2564 "  from segment 1.  Vertices 6 and 8 have markers from segment 4.  All the\n");
2565   printf(
2566 "  other vertices but 4 have been marked to indicate that they lie on a\n");
2567   printf("  boundary.\n\n");
2568   printf("    12  2  0  1\n");
2569   printf("       1    0   0      5\n");
2570   printf("       2    0   3      5\n");
2571   printf("       3    3   0      1\n");
2572   printf("       4    3   3     33\n");
2573   printf("       5    1   1      1\n");
2574   printf("       6    1   2     10\n");
2575   printf("       7    2   1      1\n");
2576   printf("       8    2   2     10\n");
2577   printf("       9    0   1.5    5\n");
2578   printf("      10    1.5   0    1\n");
2579   printf("      11    3   1.5    1\n");
2580   printf("      12    1.5   3    1\n");
2581   printf("    # Generated by triangle -pqc box.poly\n");
2582   printf("\n");
2583   printf("  Here is the output file `box.1.ele', with twelve triangles.\n");
2584   printf("\n");
2585   printf("    12  3  0\n");
2586   printf("       1     5   6   9\n");
2587   printf("       2    10   3   7\n");
2588   printf("       3     6   8  12\n");
2589   printf("       4     9   1   5\n");
2590   printf("       5     6   2   9\n");
2591   printf("       6     7   3  11\n");
2592   printf("       7    11   4   8\n");
2593   printf("       8     7   5  10\n");
2594   printf("       9    12   2   6\n");
2595   printf("      10     8   7  11\n");
2596   printf("      11     5   1  10\n");
2597   printf("      12     8   4  12\n");
2598   printf("    # Generated by triangle -pqc box.poly\n\n");
2599   printf(
2600 "  Here is the output file `box.1.poly'.  Note that segments have been added\n"
2601 );
2602   printf(
2603 "  to represent the convex hull, and some segments have been subdivided by\n");
2604   printf(
2605 "  newly added vertices.  Note also that <# of vertices> is set to zero to\n");
2606   printf("  indicate that the vertices should be read from the .node file.\n");
2607   printf("\n");
2608   printf("    0  2  0  1\n");
2609   printf("    12  1\n");
2610   printf("       1     1   9     5\n");
2611   printf("       2     5   7     1\n");
2612   printf("       3     8   7     1\n");
2613   printf("       4     6   8    10\n");
2614   printf("       5     5   6     1\n");
2615   printf("       6     3  10     1\n");
2616   printf("       7     4  11     1\n");
2617   printf("       8     2  12     1\n");
2618   printf("       9     9   2     5\n");
2619   printf("      10    10   1     1\n");
2620   printf("      11    11   3     1\n");
2621   printf("      12    12   4     1\n");
2622   printf("    1\n");
2623   printf("       1   1.5 1.5\n");
2624   printf("    # Generated by triangle -pqc box.poly\n");
2625   printf("\n");
2626   printf("Refinement and Area Constraints:\n");
2627   printf("\n");
2628   printf(
2629 "  The -r switch causes a mesh (.node and .ele files) to be read and\n");
2630   printf(
2631 "  refined.  If the -p switch is also used, a .poly file is read and used to\n"
2632 );
2633   printf(
2634 "  specify edges that are constrained and cannot be eliminated (although\n");
2635   printf(
2636 "  they can be subdivided into smaller edges) by the refinement process.\n");
2637   printf("\n");
2638   printf(
2639 "  When you refine a mesh, you generally want to impose tighter constraints.\n"
2640 );
2641   printf(
2642 "  One way to accomplish this is to use -q with a larger angle, or -a\n");
2643   printf(
2644 "  followed by a smaller area than you used to generate the mesh you are\n");
2645   printf(
2646 "  refining.  Another way to do this is to create an .area file, which\n");
2647   printf(
2648 "  specifies a maximum area for each triangle, and use the -a switch\n");
2649   printf(
2650 "  (without a number following).  Each triangle's area constraint is applied\n"
2651 );
2652   printf(
2653 "  to that triangle.  Area constraints tend to diffuse as the mesh is\n");
2654   printf(
2655 "  refined, so if there are large variations in area constraint between\n");
2656   printf(
2657 "  adjacent triangles, you may not get the results you want.  In that case,\n"
2658 );
2659   printf(
2660 "  consider instead using the -u switch and writing a C procedure that\n");
2661   printf("  determines which triangles are too large.\n\n");
2662   printf(
2663 "  If you are refining a mesh composed of linear (three-node) elements, the\n"
2664 );
2665   printf(
2666 "  output mesh contains all the nodes present in the input mesh, in the same\n"
2667 );
2668   printf(
2669 "  order, with new nodes added at the end of the .node file.  However, the\n");
2670   printf(
2671 "  refinement is not hierarchical: there is no guarantee that each output\n");
2672   printf(
2673 "  element is contained in a single input element.  Often, an output element\n"
2674 );
2675   printf(
2676 "  can overlap two or three input elements, and some input edges are not\n");
2677   printf(
2678 "  present in the output mesh.  Hence, a sequence of refined meshes forms a\n"
2679 );
2680   printf(
2681 "  hierarchy of nodes, but not a hierarchy of elements.  If you refine a\n");
2682   printf(
2683 "  mesh of higher-order elements, the hierarchical property applies only to\n"
2684 );
2685   printf(
2686 "  the nodes at the corners of an element; the midpoint nodes on each edge\n");
2687   printf("  are discarded before the mesh is refined.\n\n");
2688   printf(
2689 "  Maximum area constraints in .poly files operate differently from those in\n"
2690 );
2691   printf(
2692 "  .area files.  A maximum area in a .poly file applies to the whole\n");
2693   printf(
2694 "  (segment-bounded) region in which a point falls, whereas a maximum area\n");
2695   printf(
2696 "  in an .area file applies to only one triangle.  Area constraints in .poly\n"
2697 );
2698   printf(
2699 "  files are used only when a mesh is first generated, whereas area\n");
2700   printf(
2701 "  constraints in .area files are used only to refine an existing mesh, and\n"
2702 );
2703   printf(
2704 "  are typically based on a posteriori error estimates resulting from a\n");
2705   printf("  finite element simulation on that mesh.\n\n");
2706   printf(
2707 "  `triangle -rq25 object.1' reads object.1.node and object.1.ele, then\n");
2708   printf(
2709 "  refines the triangulation to enforce a 25 degree minimum angle, and then\n"
2710 );
2711   printf(
2712 "  writes the refined triangulation to object.2.node and object.2.ele.\n");
2713   printf("\n");
2714   printf(
2715 "  `triangle -rpaa6.2 z.3' reads z.3.node, z.3.ele, z.3.poly, and z.3.area.\n"
2716 );
2717   printf(
2718 "  After reconstructing the mesh and its subsegments, Triangle refines the\n");
2719   printf(
2720 "  mesh so that no triangle has area greater than 6.2, and furthermore the\n");
2721   printf(
2722 "  triangles satisfy the maximum area constraints in z.3.area.  No angle\n");
2723   printf(
2724 "  bound is imposed at all.  The output is written to z.4.node, z.4.ele, and\n"
2725 );
2726   printf("  z.4.poly.\n\n");
2727   printf(
2728 "  The sequence `triangle -qa1 x', `triangle -rqa.3 x.1', `triangle -rqa.1\n");
2729   printf(
2730 "  x.2' creates a sequence of successively finer meshes x.1, x.2, and x.3,\n");
2731   printf("  suitable for multigrid.\n\n");
2732   printf("Convex Hulls and Mesh Boundaries:\n\n");
2733   printf(
2734 "  If the input is a vertex set (not a PSLG), Triangle produces its convex\n");
2735   printf(
2736 "  hull as a by-product in the output .poly file if you use the -c switch.\n");
2737   printf(
2738 "  There are faster algorithms for finding a two-dimensional convex hull\n");
2739   printf("  than triangulation, of course, but this one comes for free.\n\n");
2740   printf(
2741 "  If the input is an unconstrained mesh (you are using the -r switch but\n");
2742   printf(
2743 "  not the -p switch), Triangle produces a list of its boundary edges\n");
2744   printf(
2745 "  (including hole boundaries) as a by-product when you use the -c switch.\n");
2746   printf(
2747 "  If you also use the -p switch, the output .poly file contains all the\n");
2748   printf("  segments from the input .poly file as well.\n\n");
2749   printf("Voronoi Diagrams:\n\n");
2750   printf(
2751 "  The -v switch produces a Voronoi diagram, in files suffixed .v.node and\n");
2752   printf(
2753 "  .v.edge.  For example, `triangle -v points' reads points.node, produces\n");
2754   printf(
2755 "  its Delaunay triangulation in points.1.node and points.1.ele, and\n");
2756   printf(
2757 "  produces its Voronoi diagram in points.1.v.node and points.1.v.edge.  The\n"
2758 );
2759   printf(
2760 "  .v.node file contains a list of all Voronoi vertices, and the .v.edge\n");
2761   printf(
2762 "  file contains a list of all Voronoi edges, some of which may be infinite\n"
2763 );
2764   printf(
2765 "  rays.  (The choice of filenames makes it easy to run the set of Voronoi\n");
2766   printf("  vertices through Triangle, if so desired.)\n\n");
2767   printf(
2768 "  This implementation does not use exact arithmetic to compute the Voronoi\n"
2769 );
2770   printf(
2771 "  vertices, and does not check whether neighboring vertices are identical.\n"
2772 );
2773   printf(
2774 "  Be forewarned that if the Delaunay triangulation is degenerate or\n");
2775   printf(
2776 "  near-degenerate, the Voronoi diagram may have duplicate vertices or\n");
2777   printf("  crossing edges.\n\n");
2778   printf(
2779 "  The result is a valid Voronoi diagram only if Triangle's output is a true\n"
2780 );
2781   printf(
2782 "  Delaunay triangulation.  The Voronoi output is usually meaningless (and\n");
2783   printf(
2784 "  may contain crossing edges and other pathology) if the output is a CDT or\n"
2785 );
2786   printf(
2787 "  CCDT, or if it has holes or concavities.  If the triangulated domain is\n");
2788   printf(
2789 "  convex and has no holes, you can use -D switch to force Triangle to\n");
2790   printf(
2791 "  construct a conforming Delaunay triangulation instead of a CCDT, so the\n");
2792   printf("  Voronoi diagram will be valid.\n\n");
2793   printf("Mesh Topology:\n\n");
2794   printf(
2795 "  You may wish to know which triangles are adjacent to a certain Delaunay\n");
2796   printf(
2797 "  edge in an .edge file, which Voronoi cells are adjacent to a certain\n");
2798   printf(
2799 "  Voronoi edge in a .v.edge file, or which Voronoi cells are adjacent to\n");
2800   printf(
2801 "  each other.  All of this information can be found by cross-referencing\n");
2802   printf(
2803 "  output files with the recollection that the Delaunay triangulation and\n");
2804   printf("  the Voronoi diagram are planar duals.\n\n");
2805   printf(
2806 "  Specifically, edge i of an .edge file is the dual of Voronoi edge i of\n");
2807   printf(
2808 "  the corresponding .v.edge file, and is rotated 90 degrees counterclock-\n");
2809   printf(
2810 "  wise from the Voronoi edge.  Triangle j of an .ele file is the dual of\n");
2811   printf(
2812 "  vertex j of the corresponding .v.node file.  Voronoi cell k is the dual\n");
2813   printf("  of vertex k of the corresponding .node file.\n\n");
2814   printf(
2815 "  Hence, to find the triangles adjacent to a Delaunay edge, look at the\n");
2816   printf(
2817 "  vertices of the corresponding Voronoi edge.  If the endpoints of a\n");
2818   printf(
2819 "  Voronoi edge are Voronoi vertices 2 and 6 respectively, then triangles 2\n"
2820 );
2821   printf(
2822 "  and 6 adjoin the left and right sides of the corresponding Delaunay edge,\n"
2823 );
2824   printf(
2825 "  respectively.  To find the Voronoi cells adjacent to a Voronoi edge, look\n"
2826 );
2827   printf(
2828 "  at the endpoints of the corresponding Delaunay edge.  If the endpoints of\n"
2829 );
2830   printf(
2831 "  a Delaunay edge are input vertices 7 and 12, then Voronoi cells 7 and 12\n"
2832 );
2833   printf(
2834 "  adjoin the right and left sides of the corresponding Voronoi edge,\n");
2835   printf(
2836 "  respectively.  To find which Voronoi cells are adjacent to each other,\n");
2837   printf("  just read the list of Delaunay edges.\n\n");
2838   printf(
2839 "  Triangle does not write a list of the edges adjoining each Voronoi cell,\n"
2840 );
2841   printf(
2842 "  but you can reconstructed it straightforwardly.  For instance, to find\n");
2843   printf(
2844 "  all the edges of Voronoi cell 1, search the output .edge file for every\n");
2845   printf(
2846 "  edge that has input vertex 1 as an endpoint.  The corresponding dual\n");
2847   printf(
2848 "  edges in the output .v.edge file form the boundary of Voronoi cell 1.\n");
2849   printf("\n");
2850   printf(
2851 "  For each Voronoi vertex, the .neigh file gives a list of the three\n");
2852   printf(
2853 "  Voronoi vertices attached to it.  You might find this more convenient\n");
2854   printf("  than the .v.edge file.\n\n");
2855   printf("Quadratic Elements:\n\n");
2856   printf(
2857 "  Triangle generates meshes with subparametric quadratic elements if the\n");
2858   printf(
2859 "  -o2 switch is specified.  Quadratic elements have six nodes per element,\n"
2860 );
2861   printf(
2862 "  rather than three.  `Subparametric' means that the edges of the triangles\n"
2863 );
2864   printf(
2865 "  are always straight, so that subparametric quadratic elements are\n");
2866   printf(
2867 "  geometrically identical to linear elements, even though they can be used\n"
2868 );
2869   printf(
2870 "  with quadratic interpolating functions.  The three extra nodes of an\n");
2871   printf(
2872 "  element fall at the midpoints of the three edges, with the fourth, fifth,\n"
2873 );
2874   printf(
2875 "  and sixth nodes appearing opposite the first, second, and third corners\n");
2876   printf("  respectively.\n\n");
2877   printf("Domains with Small Angles:\n\n");
2878   printf(
2879 "  If two input segments adjoin each other at a small angle, clearly the -q\n"
2880 );
2881   printf(
2882 "  switch cannot remove the small angle.  Moreover, Triangle may have no\n");
2883   printf(
2884 "  choice but to generate additional triangles whose smallest angles are\n");
2885   printf(
2886 "  smaller than the specified bound.  However, these triangles only appear\n");
2887   printf(
2888 "  between input segments separated by small angles.  Moreover, if you\n");
2889   printf(
2890 "  request a minimum angle of theta degrees, Triangle will generally produce\n"
2891 );
2892   printf(
2893 "  no angle larger than 180 - 2 theta, even if it is forced to compromise on\n"
2894 );
2895   printf("  the minimum angle.\n\n");
2896   printf("Statistics:\n\n");
2897   printf(
2898 "  After generating a mesh, Triangle prints a count of entities in the\n");
2899   printf(
2900 "  output mesh, including the number of vertices, triangles, edges, exterior\n"
2901 );
2902   printf(
2903 "  boundary edges (i.e. subsegments on the boundary of the triangulation,\n");
2904   printf(
2905 "  including hole boundaries), interior boundary edges (i.e. subsegments of\n"
2906 );
2907   printf(
2908 "  input segments not on the boundary), and total subsegments.  If you've\n");
2909   printf(
2910 "  forgotten the statistics for an existing mesh, run Triangle on that mesh\n"
2911 );
2912   printf(
2913 "  with the -rNEP switches to read the mesh and print the statistics without\n"
2914 );
2915   printf(
2916 "  writing any files.  Use -rpNEP if you've got a .poly file for the mesh.\n");
2917   printf("\n");
2918   printf(
2919 "  The -V switch produces extended statistics, including a rough estimate\n");
2920   printf(
2921 "  of memory use, the number of calls to geometric predicates, and\n");
2922   printf(
2923 "  histograms of the angles and the aspect ratios of the triangles in the\n");
2924   printf("  mesh.\n\n");
2925   printf("Exact Arithmetic:\n\n");
2926   printf(
2927 "  Triangle uses adaptive exact arithmetic to perform what computational\n");
2928   printf(
2929 "  geometers call the `orientation' and `incircle' tests.  If the floating-\n"
2930 );
2931   printf(
2932 "  point arithmetic of your machine conforms to the IEEE 754 standard (as\n");
2933   printf(
2934 "  most workstations do), and does not use extended precision internal\n");
2935   printf(
2936 "  floating-point registers, then your output is guaranteed to be an\n");
2937   printf(
2938 "  absolutely true Delaunay or constrained Delaunay triangulation, roundoff\n"
2939 );
2940   printf(
2941 "  error notwithstanding.  The word `adaptive' implies that these arithmetic\n"
2942 );
2943   printf(
2944 "  routines compute the result only to the precision necessary to guarantee\n"
2945 );
2946   printf(
2947 "  correctness, so they are usually nearly as fast as their approximate\n");
2948   printf("  counterparts.\n\n");
2949   printf(
2950 "  May CPUs, including Intel x86 processors, have extended precision\n");
2951   printf(
2952 "  floating-point registers.  These must be reconfigured so their precision\n"
2953 );
2954   printf(
2955 "  is reduced to memory precision.  Triangle does this if it is compiled\n");
2956   printf("  correctly.  See the makefile for details.\n\n");
2957   printf(
2958 "  The exact tests can be disabled with the -X switch.  On most inputs, this\n"
2959 );
2960   printf(
2961 "  switch reduces the computation time by about eight percent--it's not\n");
2962   printf(
2963 "  worth the risk.  There are rare difficult inputs (having many collinear\n");
2964   printf(
2965 "  and cocircular vertices), however, for which the difference in speed\n");
2966   printf(
2967 "  could be a factor of two.  Be forewarned that these are precisely the\n");
2968   printf(
2969 "  inputs most likely to cause errors if you use the -X switch.  Hence, the\n"
2970 );
2971   printf("  -X switch is not recommended.\n\n");
2972   printf(
2973 "  Unfortunately, the exact tests don't solve every numerical problem.\n");
2974   printf(
2975 "  Exact arithmetic is not used to compute the positions of new vertices,\n");
2976   printf(
2977 "  because the bit complexity of vertex coordinates would grow without\n");
2978   printf(
2979 "  bound.  Hence, segment intersections aren't computed exactly; in very\n");
2980   printf(
2981 "  unusual cases, roundoff error in computing an intersection point might\n");
2982   printf(
2983 "  actually lead to an inverted triangle and an invalid triangulation.\n");
2984   printf(
2985 "  (This is one reason to specify your own intersection points in your .poly\n"
2986 );
2987   printf(
2988 "  files.)  Similarly, exact arithmetic is not used to compute the vertices\n"
2989 );
2990   printf("  of the Voronoi diagram.\n\n");
2991   printf(
2992 "  Another pair of problems not solved by the exact arithmetic routines is\n");
2993   printf(
2994 "  underflow and overflow.  If Triangle is compiled for double precision\n");
2995   printf(
2996 "  arithmetic, I believe that Triangle's geometric predicates work correctly\n"
2997 );
2998   printf(
2999 "  if the exponent of every input coordinate falls in the range [-148, 201].\n"
3000 );
3001   printf(
3002 "  Underflow can silently prevent the orientation and incircle tests from\n");
3003   printf(
3004 "  being performed exactly, while overflow typically causes a floating\n");
3005   printf("  exception.\n\n");
3006   printf("Calling Triangle from Another Program:\n\n");
3007   printf("  Read the file triangle.h for details.\n\n");
3008   printf("Troubleshooting:\n\n");
3009   printf("  Please read this section before mailing me bugs.\n\n");
3010   printf("  `My output mesh has no triangles!'\n\n");
3011   printf(
3012 "    If you're using a PSLG, you've probably failed to specify a proper set\n"
3013 );
3014   printf(
3015 "    of bounding segments, or forgotten to use the -c switch.  Or you may\n");
3016   printf(
3017 "    have placed a hole badly, thereby eating all your triangles.  To test\n");
3018   printf("    these possibilities, try again with the -c and -O switches.\n");
3019   printf(
3020 "    Alternatively, all your input vertices may be collinear, in which case\n"
3021 );
3022   printf("    you can hardly expect to triangulate them.\n\n");
3023   printf("  `Triangle doesn't terminate, or just crashes.'\n\n");
3024   printf(
3025 "    Bad things can happen when triangles get so small that the distance\n");
3026   printf(
3027 "    between their vertices isn't much larger than the precision of your\n");
3028   printf(
3029 "    machine's arithmetic.  If you've compiled Triangle for single-precision\n"
3030 );
3031   printf(
3032 "    arithmetic, you might do better by recompiling it for double-precision.\n"
3033 );
3034   printf(
3035 "    Then again, you might just have to settle for more lenient constraints\n"
3036 );
3037   printf(
3038 "    on the minimum angle and the maximum area than you had planned.\n");
3039   printf("\n");
3040   printf(
3041 "    You can minimize precision problems by ensuring that the origin lies\n");
3042   printf(
3043 "    inside your vertex set, or even inside the densest part of your\n");
3044   printf(
3045 "    mesh.  If you're triangulating an object whose x-coordinates all fall\n");
3046   printf(
3047 "    between 6247133 and 6247134, you're not leaving much floating-point\n");
3048   printf("    precision for Triangle to work with.\n\n");
3049   printf(
3050 "    Precision problems can occur covertly if the input PSLG contains two\n");
3051   printf(
3052 "    segments that meet (or intersect) at an extremely small angle, or if\n");
3053   printf(
3054 "    such an angle is introduced by the -c switch.  If you don't realize\n");
3055   printf(
3056 "    that a tiny angle is being formed, you might never discover why\n");
3057   printf(
3058 "    Triangle is crashing.  To check for this possibility, use the -S switch\n"
3059 );
3060   printf(
3061 "    (with an appropriate limit on the number of Steiner points, found by\n");
3062   printf(
3063 "    trial-and-error) to stop Triangle early, and view the output .poly file\n"
3064 );
3065   printf(
3066 "    with Show Me (described below).  Look carefully for regions where dense\n"
3067 );
3068   printf(
3069 "    clusters of vertices are forming and for small angles between segments.\n"
3070 );
3071   printf(
3072 "    Zoom in closely, as such segments might look like a single segment from\n"
3073 );
3074   printf("    a distance.\n\n");
3075   printf(
3076 "    If some of the input values are too large, Triangle may suffer a\n");
3077   printf(
3078 "    floating exception due to overflow when attempting to perform an\n");
3079   printf(
3080 "    orientation or incircle test.  (Read the section on exact arithmetic\n");
3081   printf(
3082 "    above.)  Again, I recommend compiling Triangle for double (rather\n");
3083   printf("    than single) precision arithmetic.\n\n");
3084   printf(
3085 "    Unexpected problems can arise if you use quality meshing (-q, -a, or\n");
3086   printf(
3087 "    -u) with an input that is not segment-bounded--that is, if your input\n");
3088   printf(
3089 "    is a vertex set, or you're using the -c switch.  If the convex hull of\n"
3090 );
3091   printf(
3092 "    your input vertices has collinear vertices on its boundary, an input\n");
3093   printf(
3094 "    vertex that you think lies on the convex hull might actually lie just\n");
3095   printf(
3096 "    inside the convex hull.  If so, the vertex and the nearby convex hull\n");
3097   printf(
3098 "    edge form an extremely thin triangle.  When Triangle tries to refine\n");
3099   printf(
3100 "    the mesh to enforce angle and area constraints, Triangle might generate\n"
3101 );
3102   printf(
3103 "    extremely tiny triangles, or it might fail because of insufficient\n");
3104   printf("    floating-point precision.\n\n");
3105   printf(
3106 "  `The numbering of the output vertices doesn't match the input vertices.'\n"
3107 );
3108   printf("\n");
3109   printf(
3110 "    You may have had duplicate input vertices, or you may have eaten some\n");
3111   printf(
3112 "    of your input vertices with a hole, or by placing them outside the area\n"
3113 );
3114   printf(
3115 "    enclosed by segments.  In any case, you can solve the problem by not\n");
3116   printf("    using the -j switch.\n\n");
3117   printf(
3118 "  `Triangle executes without incident, but when I look at the resulting\n");
3119   printf(
3120 "  mesh, it has overlapping triangles or other geometric inconsistencies.'\n");
3121   printf("\n");
3122   printf(
3123 "    If you select the -X switch, Triangle occasionally makes mistakes due\n");
3124   printf(
3125 "    to floating-point roundoff error.  Although these errors are rare,\n");
3126   printf(
3127 "    don't use the -X switch.  If you still have problems, please report the\n"
3128 );
3129   printf("    bug.\n\n");
3130   printf(
3131 "  `Triangle executes without incident, but when I look at the resulting\n");
3132   printf("  Voronoi diagram, it has overlapping edges or other geometric\n");
3133   printf("  inconsistencies.'\n");
3134   printf("\n");
3135   printf(
3136 "    If your input is a PSLG (-p), you can only expect a meaningful Voronoi\n"
3137 );
3138   printf(
3139 "    diagram if the domain you are triangulating is convex and free of\n");
3140   printf(
3141 "    holes, and you use the -D switch to construct a conforming Delaunay\n");
3142   printf("    triangulation (instead of a CDT or CCDT).\n\n");
3143   printf(
3144 "  Strange things can happen if you've taken liberties with your PSLG.  Do\n");
3145   printf(
3146 "  you have a vertex lying in the middle of a segment?  Triangle sometimes\n");
3147   printf(
3148 "  copes poorly with that sort of thing.  Do you want to lay out a collinear\n"
3149 );
3150   printf(
3151 "  row of evenly spaced, segment-connected vertices?  Have you simply\n");
3152   printf(
3153 "  defined one long segment connecting the leftmost vertex to the rightmost\n"
3154 );
3155   printf(
3156 "  vertex, and a bunch of vertices lying along it?  This method occasionally\n"
3157 );
3158   printf(
3159 "  works, especially with horizontal and vertical lines, but often it\n");
3160   printf(
3161 "  doesn't, and you'll have to connect each adjacent pair of vertices with a\n"
3162 );
3163   printf("  separate segment.  If you don't like it, tough.\n\n");
3164   printf(
3165 "  Furthermore, if you have segments that intersect other than at their\n");
3166   printf(
3167 "  endpoints, try not to let the intersections fall extremely close to PSLG\n"
3168 );
3169   printf("  vertices or each other.\n\n");
3170   printf(
3171 "  If you have problems refining a triangulation not produced by Triangle:\n");
3172   printf(
3173 "  Are you sure the triangulation is geometrically valid?  Is it formatted\n");
3174   printf(
3175 "  correctly for Triangle?  Are the triangles all listed so the first three\n"
3176 );
3177   printf(
3178 "  vertices are their corners in counterclockwise order?  Are all of the\n");
3179   printf(
3180 "  triangles constrained Delaunay?  Triangle's Delaunay refinement algorithm\n"
3181 );
3182   printf("  assumes that it starts with a CDT.\n\n");
3183   printf("Show Me:\n\n");
3184   printf(
3185 "  Triangle comes with a separate program named `Show Me', whose primary\n");
3186   printf(
3187 "  purpose is to draw meshes on your screen or in PostScript.  Its secondary\n"
3188 );
3189   printf(
3190 "  purpose is to check the validity of your input files, and do so more\n");
3191   printf(
3192 "  thoroughly than Triangle does.  Unlike Triangle, Show Me requires that\n");
3193   printf(
3194 "  you have the X Windows system.  Sorry, Microsoft Windows users.\n");
3195   printf("\n");
3196   printf("Triangle on the Web:\n");
3197   printf("\n");
3198   printf("  To see an illustrated version of these instructions, check out\n");
3199   printf("\n");
3200   printf("    http://www.cs.cmu.edu/~quake/triangle.html\n");
3201   printf("\n");
3202   printf("A Brief Plea:\n");
3203   printf("\n");
3204   printf(
3205 "  If you use Triangle, and especially if you use it to accomplish real\n");
3206   printf(
3207 "  work, I would like very much to hear from you.  A short letter or email\n");
3208   printf(
3209 "  (to jrs@cs.berkeley.edu) describing how you use Triangle will mean a lot\n"
3210 );
3211   printf(
3212 "  to me.  The more people I know are using this program, the more easily I\n"
3213 );
3214   printf(
3215 "  can justify spending time on improvements, which in turn will benefit\n");
3216   printf(
3217 "  you.  Also, I can put you on a list to receive email whenever a new\n");
3218   printf("  version of Triangle is available.\n\n");
3219   printf(
3220 "  If you use a mesh generated by Triangle in a publication, please include\n"
3221 );
3222   printf(
3223 "  an acknowledgment as well.  And please spell Triangle with a capital `T'!\n"
3224 );
3225   printf(
3226 "  If you want to include a citation, use `Jonathan Richard Shewchuk,\n");
3227   printf(
3228 "  ``Triangle: Engineering a 2D Quality Mesh Generator and Delaunay\n");
3229   printf(
3230 "  Triangulator,'' in Applied Computational Geometry:  Towards Geometric\n");
3231   printf(
3232 "  Engineering (Ming C. Lin and Dinesh Manocha, editors), volume 1148 of\n");
3233   printf(
3234 "  Lecture Notes in Computer Science, pages 203-222, Springer-Verlag,\n");
3235   printf(
3236 "  Berlin, May 1996.  (From the First ACM Workshop on Applied Computational\n"
3237 );
3238   printf("  Geometry.)'\n\n");
3239   printf("Research credit:\n\n");
3240   printf(
3241 "  Of course, I can take credit for only a fraction of the ideas that made\n");
3242   printf(
3243 "  this mesh generator possible.  Triangle owes its existence to the efforts\n"
3244 );
3245   printf(
3246 "  of many fine computational geometers and other researchers, including\n");
3247   printf(
3248 "  Marshall Bern, L. Paul Chew, Kenneth L. Clarkson, Boris Delaunay, Rex A.\n"
3249 );
3250   printf(
3251 "  Dwyer, David Eppstein, Steven Fortune, Leonidas J. Guibas, Donald E.\n");
3252   printf(
3253 "  Knuth, Charles L. Lawson, Der-Tsai Lee, Gary L. Miller, Ernst P. Mucke,\n");
3254   printf(
3255 "  Steven E. Pav, Douglas M. Priest, Jim Ruppert, Isaac Saias, Bruce J.\n");
3256   printf(
3257 "  Schachter, Micha Sharir, Peter W. Shor, Daniel D. Sleator, Jorge Stolfi,\n"
3258 );
3259   printf("  Robert E. Tarjan, Alper Ungor, Christopher J. Van Wyk, Noel J.\n");
3260   printf(
3261 "  Walkington, and Binhai Zhu.  See the comments at the beginning of the\n");
3262   printf("  source code for references.\n\n");
3263   triexit(0);
3264 }
3265 
3266 #endif /* not TRILIBRARY */
3267 
3268 /*****************************************************************************/
3269 /*                                                                           */
3270 /*  internalerror()   Ask the user to send me the defective product.  Exit.  */
3271 /*                                                                           */
3272 /*****************************************************************************/
3273 
internalerror()3274 void internalerror()
3275 {
3276   printf("  Please report this bug to jrs@cs.berkeley.edu\n");
3277   printf("  Include the message above, your input data set, and the exact\n");
3278   printf("    command line you used to run Triangle.\n");
3279   triexit(1);
3280 }
3281 
3282 /*****************************************************************************/
3283 /*                                                                           */
3284 /*  parsecommandline()   Read the command line, identify switches, and set   */
3285 /*                       up options and file names.                          */
3286 /*                                                                           */
3287 /*****************************************************************************/
3288 
3289 #ifdef ANSI_DECLARATORS
3290 void parsecommandline(int argc, const char * const * const argv, struct behavior *b)
3291 #else /* not ANSI_DECLARATORS */
3292 void parsecommandline(argc, argv, b)
3293 int argc;
3294 const char * const * const argv;
3295 struct behavior *b;
3296 #endif /* not ANSI_DECLARATORS */
3297 
3298 {
3299 #ifdef TRILIBRARY
3300 #define STARTINDEX 0
3301 #else /* not TRILIBRARY */
3302 #define STARTINDEX 1
3303   int increment;
3304   int meshnumber;
3305 #endif /* not TRILIBRARY */
3306   int i, j, k;
3307   char workstring[FILENAMESIZE];
3308 
3309   b->poly = b->refine = b->quality = 0;
3310   b->vararea = b->fixedarea = b->usertest = 0;
3311   b->regionattrib = b->convex = b->weighted = b->jettison = 0;
3312   b->firstnumber = 1;
3313   b->edgesout = b->voronoi = b->neighbors = b->geomview = 0;
3314   b->nobound = b->nopolywritten = b->nonodewritten = b->noelewritten = 0;
3315   b->noiterationnum = 0;
3316   b->noholes = b->noexact = 0;
3317   b->incremental = b->sweepline = 0;
3318   b->dwyer = 1;
3319   b->splitseg = 0;
3320   b->docheck = 0;
3321   b->nobisect = 0;
3322   b->conformdel = 0;
3323   b->steiner = -1;
3324   b->order = 1;
3325   b->minangle = 0.0;
3326   b->maxarea = -1.0;
3327   b->quiet = b->verbose = 0;
3328 #ifndef TRILIBRARY
3329   b->innodefilename[0] = '\0';
3330 #endif /* not TRILIBRARY */
3331 
3332   for (i = STARTINDEX; i < argc; i++) {
3333 #ifndef TRILIBRARY
3334     if (argv[i][0] == '-') {
3335 #endif /* not TRILIBRARY */
3336       for (j = STARTINDEX; argv[i][j] != '\0'; j++) {
3337         if (argv[i][j] == 'p') {
3338           b->poly = 1;
3339         }
3340 #ifndef CDT_ONLY
3341         if (argv[i][j] == 'r') {
3342           b->refine = 1;
3343         }
3344         if (argv[i][j] == 'q') {
3345           b->quality = 1;
3346           if (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) ||
3347               (argv[i][j + 1] == '.')) {
3348             k = 0;
3349             while (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) ||
3350                    (argv[i][j + 1] == '.')) {
3351               j++;
3352               workstring[k] = argv[i][j];
3353               k++;
3354             }
3355             workstring[k] = '\0';
3356             b->minangle = (REAL) strtod(workstring, (char **) NULL);
3357           } else {
3358             b->minangle = 20.0;
3359           }
3360         }
3361         if (argv[i][j] == 'a') {
3362           b->quality = 1;
3363           if (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) ||
3364               (argv[i][j + 1] == '.')) {
3365             b->fixedarea = 1;
3366             k = 0;
3367             while (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) ||
3368                    (argv[i][j + 1] == '.')) {
3369               j++;
3370               workstring[k] = argv[i][j];
3371               k++;
3372             }
3373             workstring[k] = '\0';
3374             b->maxarea = (REAL) strtod(workstring, (char **) NULL);
3375             if (b->maxarea <= 0.0) {
3376               printf("Error:  Maximum area must be greater than zero.\n");
3377               triexit(1);
3378             }
3379           } else {
3380             b->vararea = 1;
3381           }
3382         }
3383         if (argv[i][j] == 'u') {
3384           b->quality = 1;
3385           b->usertest = 1;
3386         }
3387 #endif /* not CDT_ONLY */
3388         if (argv[i][j] == 'A') {
3389           b->regionattrib = 1;
3390         }
3391         if (argv[i][j] == 'c') {
3392           b->convex = 1;
3393         }
3394         if (argv[i][j] == 'w') {
3395           b->weighted = 1;
3396         }
3397         if (argv[i][j] == 'W') {
3398           b->weighted = 2;
3399         }
3400         if (argv[i][j] == 'j') {
3401           b->jettison = 1;
3402         }
3403         if (argv[i][j] == 'z') {
3404           b->firstnumber = 0;
3405         }
3406         if (argv[i][j] == 'e') {
3407           b->edgesout = 1;
3408         }
3409         if (argv[i][j] == 'v') {
3410           b->voronoi = 1;
3411         }
3412         if (argv[i][j] == 'n') {
3413           b->neighbors = 1;
3414         }
3415         if (argv[i][j] == 'g') {
3416           b->geomview = 1;
3417         }
3418         if (argv[i][j] == 'B') {
3419           b->nobound = 1;
3420         }
3421         if (argv[i][j] == 'P') {
3422           b->nopolywritten = 1;
3423         }
3424         if (argv[i][j] == 'N') {
3425           b->nonodewritten = 1;
3426         }
3427         if (argv[i][j] == 'E') {
3428           b->noelewritten = 1;
3429         }
3430 #ifndef TRILIBRARY
3431         if (argv[i][j] == 'I') {
3432           b->noiterationnum = 1;
3433         }
3434 #endif /* not TRILIBRARY */
3435         if (argv[i][j] == 'O') {
3436           b->noholes = 1;
3437         }
3438         if (argv[i][j] == 'X') {
3439           b->noexact = 1;
3440         }
3441         if (argv[i][j] == 'o') {
3442           if (argv[i][j + 1] == '2') {
3443             j++;
3444             b->order = 2;
3445           }
3446         }
3447 #ifndef CDT_ONLY
3448         if (argv[i][j] == 'Y') {
3449           b->nobisect++;
3450         }
3451         if (argv[i][j] == 'S') {
3452           b->steiner = 0;
3453           while ((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) {
3454             j++;
3455             b->steiner = b->steiner * 10 + (int) (argv[i][j] - '0');
3456           }
3457         }
3458 #endif /* not CDT_ONLY */
3459 #ifndef REDUCED
3460         if (argv[i][j] == 'i') {
3461           b->incremental = 1;
3462         }
3463         if (argv[i][j] == 'F') {
3464           b->sweepline = 1;
3465         }
3466 #endif /* not REDUCED */
3467         if (argv[i][j] == 'l') {
3468           b->dwyer = 0;
3469         }
3470 #ifndef REDUCED
3471 #ifndef CDT_ONLY
3472         if (argv[i][j] == 's') {
3473           b->splitseg = 1;
3474         }
3475         if ((argv[i][j] == 'D') || (argv[i][j] == 'L')) {
3476           b->quality = 1;
3477           b->conformdel = 1;
3478         }
3479 #endif /* not CDT_ONLY */
3480         if (argv[i][j] == 'C') {
3481           b->docheck = 1;
3482         }
3483 #endif /* not REDUCED */
3484         if (argv[i][j] == 'Q') {
3485           b->quiet = 1;
3486         }
3487         if (argv[i][j] == 'V') {
3488           b->verbose++;
3489         }
3490 #ifndef TRILIBRARY
3491         if ((argv[i][j] == 'h') || (argv[i][j] == 'H') ||
3492             (argv[i][j] == '?')) {
3493           info();
3494         }
3495 #endif /* not TRILIBRARY */
3496       }
3497 #ifndef TRILIBRARY
3498     } else {
3499       strncpy(b->innodefilename, argv[i], FILENAMESIZE - 1);
3500       b->innodefilename[FILENAMESIZE - 1] = '\0';
3501     }
3502 #endif /* not TRILIBRARY */
3503   }
3504 #ifndef TRILIBRARY
3505   if (b->innodefilename[0] == '\0') {
3506     syntax();
3507   }
3508   if (!strcmp(&b->innodefilename[strlen(b->innodefilename) - 5], ".node")) {
3509     b->innodefilename[strlen(b->innodefilename) - 5] = '\0';
3510   }
3511   if (!strcmp(&b->innodefilename[strlen(b->innodefilename) - 5], ".poly")) {
3512     b->innodefilename[strlen(b->innodefilename) - 5] = '\0';
3513     b->poly = 1;
3514   }
3515 #ifndef CDT_ONLY
3516   if (!strcmp(&b->innodefilename[strlen(b->innodefilename) - 4], ".ele")) {
3517     b->innodefilename[strlen(b->innodefilename) - 4] = '\0';
3518     b->refine = 1;
3519   }
3520   if (!strcmp(&b->innodefilename[strlen(b->innodefilename) - 5], ".area")) {
3521     b->innodefilename[strlen(b->innodefilename) - 5] = '\0';
3522     b->refine = 1;
3523     b->quality = 1;
3524     b->vararea = 1;
3525   }
3526 #endif /* not CDT_ONLY */
3527 #endif /* not TRILIBRARY */
3528   b->usesegments = b->poly || b->refine || b->quality || b->convex;
3529   b->goodangle = cos(b->minangle * PI / 180.0);
3530   if (b->goodangle == 1.0) {
3531     b->offconstant = 0.0;
3532   } else {
3533     b->offconstant = 0.475 * sqrt((1.0 + b->goodangle) / (1.0 - b->goodangle));
3534   }
3535   b->goodangle *= b->goodangle;
3536   if (b->refine && b->noiterationnum) {
3537     printf(
3538       "Error:  You cannot use the -I switch when refining a triangulation.\n");
3539     triexit(1);
3540   }
3541   /* Be careful not to allocate space for element area constraints that */
3542   /*   will never be assigned any value (other than the default -1.0).  */
3543   if (!b->refine && !b->poly) {
3544     b->vararea = 0;
3545   }
3546   /* Be careful not to add an extra attribute to each element unless the */
3547   /*   input supports it (PSLG in, but not refining a preexisting mesh). */
3548   if (b->refine || !b->poly) {
3549     b->regionattrib = 0;
3550   }
3551   /* Regular/weighted triangulations are incompatible with PSLGs */
3552   /*   and meshing.                                              */
3553   if (b->weighted && (b->poly || b->quality)) {
3554     b->weighted = 0;
3555     if (!b->quiet) {
3556       printf("Warning:  weighted triangulations (-w, -W) are incompatible\n");
3557       printf("  with PSLGs (-p) and meshing (-q, -a, -u).  Weights ignored.\n"
3558              );
3559     }
3560   }
3561   if (b->jettison && b->nonodewritten && !b->quiet) {
3562     printf("Warning:  -j and -N switches are somewhat incompatible.\n");
3563     printf("  If any vertices are jettisoned, you will need the output\n");
3564     printf("  .node file to reconstruct the new node indices.");
3565   }
3566 
3567 #ifndef TRILIBRARY
3568   strcpy(b->inpolyfilename, b->innodefilename);
3569   strcpy(b->inelefilename, b->innodefilename);
3570   strcpy(b->areafilename, b->innodefilename);
3571   increment = 0;
3572   strcpy(workstring, b->innodefilename);
3573   j = 1;
3574   while (workstring[j] != '\0') {
3575     if ((workstring[j] == '.') && (workstring[j + 1] != '\0')) {
3576       increment = j + 1;
3577     }
3578     j++;
3579   }
3580   meshnumber = 0;
3581   if (increment > 0) {
3582     j = increment;
3583     do {
3584       if ((workstring[j] >= '0') && (workstring[j] <= '9')) {
3585         meshnumber = meshnumber * 10 + (int) (workstring[j] - '0');
3586       } else {
3587         increment = 0;
3588       }
3589       j++;
3590     } while (workstring[j] != '\0');
3591   }
3592   if (b->noiterationnum) {
3593     strcpy(b->outnodefilename, b->innodefilename);
3594     strcpy(b->outelefilename, b->innodefilename);
3595     strcpy(b->edgefilename, b->innodefilename);
3596     strcpy(b->vnodefilename, b->innodefilename);
3597     strcpy(b->vedgefilename, b->innodefilename);
3598     strcpy(b->neighborfilename, b->innodefilename);
3599     strcpy(b->offfilename, b->innodefilename);
3600     strcat(b->outnodefilename, ".node");
3601     strcat(b->outelefilename, ".ele");
3602     strcat(b->edgefilename, ".edge");
3603     strcat(b->vnodefilename, ".v.node");
3604     strcat(b->vedgefilename, ".v.edge");
3605     strcat(b->neighborfilename, ".neigh");
3606     strcat(b->offfilename, ".off");
3607   } else if (increment == 0) {
3608     strcpy(b->outnodefilename, b->innodefilename);
3609     strcpy(b->outpolyfilename, b->innodefilename);
3610     strcpy(b->outelefilename, b->innodefilename);
3611     strcpy(b->edgefilename, b->innodefilename);
3612     strcpy(b->vnodefilename, b->innodefilename);
3613     strcpy(b->vedgefilename, b->innodefilename);
3614     strcpy(b->neighborfilename, b->innodefilename);
3615     strcpy(b->offfilename, b->innodefilename);
3616     strcat(b->outnodefilename, ".1.node");
3617     strcat(b->outpolyfilename, ".1.poly");
3618     strcat(b->outelefilename, ".1.ele");
3619     strcat(b->edgefilename, ".1.edge");
3620     strcat(b->vnodefilename, ".1.v.node");
3621     strcat(b->vedgefilename, ".1.v.edge");
3622     strcat(b->neighborfilename, ".1.neigh");
3623     strcat(b->offfilename, ".1.off");
3624   } else {
3625     workstring[increment] = '%';
3626     workstring[increment + 1] = 'd';
3627     workstring[increment + 2] = '\0';
3628     sprintf(b->outnodefilename, workstring, meshnumber + 1);
3629     strcpy(b->outpolyfilename, b->outnodefilename);
3630     strcpy(b->outelefilename, b->outnodefilename);
3631     strcpy(b->edgefilename, b->outnodefilename);
3632     strcpy(b->vnodefilename, b->outnodefilename);
3633     strcpy(b->vedgefilename, b->outnodefilename);
3634     strcpy(b->neighborfilename, b->outnodefilename);
3635     strcpy(b->offfilename, b->outnodefilename);
3636     strcat(b->outnodefilename, ".node");
3637     strcat(b->outpolyfilename, ".poly");
3638     strcat(b->outelefilename, ".ele");
3639     strcat(b->edgefilename, ".edge");
3640     strcat(b->vnodefilename, ".v.node");
3641     strcat(b->vedgefilename, ".v.edge");
3642     strcat(b->neighborfilename, ".neigh");
3643     strcat(b->offfilename, ".off");
3644   }
3645   strcat(b->innodefilename, ".node");
3646   strcat(b->inpolyfilename, ".poly");
3647   strcat(b->inelefilename, ".ele");
3648   strcat(b->areafilename, ".area");
3649 #endif /* not TRILIBRARY */
3650 }
3651 
3652 /**                                                                         **/
3653 /**                                                                         **/
3654 /********* User interaction routines begin here                      *********/
3655 
3656 /********* Debugging routines begin here                             *********/
3657 /**                                                                         **/
3658 /**                                                                         **/
3659 
3660 /*****************************************************************************/
3661 /*                                                                           */
3662 /*  printtriangle()   Print out the details of an oriented triangle.         */
3663 /*                                                                           */
3664 /*  I originally wrote this procedure to simplify debugging; it can be       */
3665 /*  called directly from the debugger, and presents information about an     */
3666 /*  oriented triangle in digestible form.  It's also used when the           */
3667 /*  highest level of verbosity (`-VVV') is specified.                        */
3668 /*                                                                           */
3669 /*****************************************************************************/
3670 
3671 #ifdef ANSI_DECLARATORS
3672 void printtriangle(struct mesh *m, struct behavior *b, struct otri *t)
3673 #else /* not ANSI_DECLARATORS */
3674 void printtriangle(m, b, t)
3675 struct mesh *m;
3676 struct behavior *b;
3677 struct otri *t;
3678 #endif /* not ANSI_DECLARATORS */
3679 
3680 {
3681   struct otri printtri;
3682   struct osub printsh;
3683   vertex printvertex;
3684 
3685   printf("triangle x%lx with orientation %d:\n", (TRIANGLE_PTRINT) t->tri,
3686          t->orient);
3687   decode(t->tri[0], printtri);
3688   if (printtri.tri == m->dummytri) {
3689     printf("    [0] = Outer space\n");
3690   } else {
3691     printf("    [0] = x%lx  %d\n", (TRIANGLE_PTRINT) printtri.tri,
3692            printtri.orient);
3693   }
3694   decode(t->tri[1], printtri);
3695   if (printtri.tri == m->dummytri) {
3696     printf("    [1] = Outer space\n");
3697   } else {
3698     printf("    [1] = x%lx  %d\n", (TRIANGLE_PTRINT) printtri.tri,
3699            printtri.orient);
3700   }
3701   decode(t->tri[2], printtri);
3702   if (printtri.tri == m->dummytri) {
3703     printf("    [2] = Outer space\n");
3704   } else {
3705     printf("    [2] = x%lx  %d\n", (TRIANGLE_PTRINT) printtri.tri,
3706            printtri.orient);
3707   }
3708 
3709   org(*t, printvertex);
3710   if (printvertex == (vertex) NULL)
3711     printf("    Origin[%d] = NULL\n", (t->orient + 1) % 3 + 3);
3712   else
3713     printf("    Origin[%d] = x%lx  (%.12g, %.12g)\n",
3714            (t->orient + 1) % 3 + 3, (TRIANGLE_PTRINT) printvertex,
3715            printvertex[0], printvertex[1]);
3716   dest(*t, printvertex);
3717   if (printvertex == (vertex) NULL)
3718     printf("    Dest  [%d] = NULL\n", (t->orient + 2) % 3 + 3);
3719   else
3720     printf("    Dest  [%d] = x%lx  (%.12g, %.12g)\n",
3721            (t->orient + 2) % 3 + 3, (TRIANGLE_PTRINT) printvertex,
3722            printvertex[0], printvertex[1]);
3723   apex(*t, printvertex);
3724   if (printvertex == (vertex) NULL)
3725     printf("    Apex  [%d] = NULL\n", t->orient + 3);
3726   else
3727     printf("    Apex  [%d] = x%lx  (%.12g, %.12g)\n",
3728            t->orient + 3, (TRIANGLE_PTRINT) printvertex,
3729            printvertex[0], printvertex[1]);
3730 
3731   if (b->usesegments) {
3732     sdecode(t->tri[6], printsh);
3733     if (printsh.ss != m->dummysub) {
3734       printf("    [6] = x%lx  %d\n", (TRIANGLE_PTRINT) printsh.ss,
3735              printsh.ssorient);
3736     }
3737     sdecode(t->tri[7], printsh);
3738     if (printsh.ss != m->dummysub) {
3739       printf("    [7] = x%lx  %d\n", (TRIANGLE_PTRINT) printsh.ss,
3740              printsh.ssorient);
3741     }
3742     sdecode(t->tri[8], printsh);
3743     if (printsh.ss != m->dummysub) {
3744       printf("    [8] = x%lx  %d\n", (TRIANGLE_PTRINT) printsh.ss,
3745              printsh.ssorient);
3746     }
3747   }
3748 
3749   if (b->vararea) {
3750     printf("    Area constraint:  %.4g\n", areabound(*t));
3751   }
3752 }
3753 
3754 /*****************************************************************************/
3755 /*                                                                           */
3756 /*  printsubseg()   Print out the details of an oriented subsegment.         */
3757 /*                                                                           */
3758 /*  I originally wrote this procedure to simplify debugging; it can be       */
3759 /*  called directly from the debugger, and presents information about an     */
3760 /*  oriented subsegment in digestible form.  It's also used when the highest */
3761 /*  level of verbosity (`-VVV') is specified.                                */
3762 /*                                                                           */
3763 /*****************************************************************************/
3764 
3765 #ifdef ANSI_DECLARATORS
3766 void printsubseg(struct mesh *m, struct behavior *b, struct osub *s)
3767 #else /* not ANSI_DECLARATORS */
3768 void printsubseg(m, b, s)
3769 struct mesh *m;
3770 struct behavior *b;
3771 struct osub *s;
3772 #endif /* not ANSI_DECLARATORS */
3773 
3774 {
3775   struct osub printsh;
3776   struct otri printtri;
3777   vertex printvertex;
3778 
3779   printf("subsegment x%lx with orientation %d and mark %d:\n",
3780          (TRIANGLE_PTRINT) s->ss, s->ssorient, mark(*s));
3781   sdecode(s->ss[0], printsh);
3782   if (printsh.ss == m->dummysub) {
3783     printf("    [0] = No subsegment\n");
3784   } else {
3785     printf("    [0] = x%lx  %d\n", (TRIANGLE_PTRINT) printsh.ss,
3786            printsh.ssorient);
3787   }
3788   sdecode(s->ss[1], printsh);
3789   if (printsh.ss == m->dummysub) {
3790     printf("    [1] = No subsegment\n");
3791   } else {
3792     printf("    [1] = x%lx  %d\n", (TRIANGLE_PTRINT) printsh.ss,
3793            printsh.ssorient);
3794   }
3795 
3796   sorg(*s, printvertex);
3797   if (printvertex == (vertex) NULL)
3798     printf("    Origin[%d] = NULL\n", 2 + s->ssorient);
3799   else
3800     printf("    Origin[%d] = x%lx  (%.12g, %.12g)\n",
3801            2 + s->ssorient, (TRIANGLE_PTRINT) printvertex,
3802            printvertex[0], printvertex[1]);
3803   sdest(*s, printvertex);
3804   if (printvertex == (vertex) NULL)
3805     printf("    Dest  [%d] = NULL\n", 3 - s->ssorient);
3806   else
3807     printf("    Dest  [%d] = x%lx  (%.12g, %.12g)\n",
3808            3 - s->ssorient, (TRIANGLE_PTRINT) printvertex,
3809            printvertex[0], printvertex[1]);
3810 
3811   decode(s->ss[6], printtri);
3812   if (printtri.tri == m->dummytri) {
3813     printf("    [6] = Outer space\n");
3814   } else {
3815     printf("    [6] = x%lx  %d\n", (TRIANGLE_PTRINT) printtri.tri,
3816            printtri.orient);
3817   }
3818   decode(s->ss[7], printtri);
3819   if (printtri.tri == m->dummytri) {
3820     printf("    [7] = Outer space\n");
3821   } else {
3822     printf("    [7] = x%lx  %d\n", (TRIANGLE_PTRINT) printtri.tri,
3823            printtri.orient);
3824   }
3825 
3826   segorg(*s, printvertex);
3827   if (printvertex == (vertex) NULL)
3828     printf("    Segment origin[%d] = NULL\n", 4 + s->ssorient);
3829   else
3830     printf("    Segment origin[%d] = x%lx  (%.12g, %.12g)\n",
3831            4 + s->ssorient, (TRIANGLE_PTRINT) printvertex,
3832            printvertex[0], printvertex[1]);
3833   segdest(*s, printvertex);
3834   if (printvertex == (vertex) NULL)
3835     printf("    Segment dest  [%d] = NULL\n", 5 - s->ssorient);
3836   else
3837     printf("    Segment dest  [%d] = x%lx  (%.12g, %.12g)\n",
3838            5 - s->ssorient, (TRIANGLE_PTRINT) printvertex,
3839            printvertex[0], printvertex[1]);
3840 }
3841 
3842 /**                                                                         **/
3843 /**                                                                         **/
3844 /********* Debugging routines end here                               *********/
3845 
3846 /********* Memory management routines begin here                     *********/
3847 /**                                                                         **/
3848 /**                                                                         **/
3849 
3850 /*****************************************************************************/
3851 /*                                                                           */
3852 /*  poolzero()   Set all of a pool's fields to zero.                         */
3853 /*                                                                           */
3854 /*  This procedure should never be called on a pool that has any memory      */
3855 /*  allocated to it, as that memory would leak.                              */
3856 /*                                                                           */
3857 /*****************************************************************************/
3858 
3859 #ifdef ANSI_DECLARATORS
3860 void poolzero(struct memorypool *pool)
3861 #else /* not ANSI_DECLARATORS */
3862 void poolzero(pool)
3863 struct memorypool *pool;
3864 #endif /* not ANSI_DECLARATORS */
3865 
3866 {
3867   pool->firstblock = (void **) NULL;
3868   pool->nowblock = (void **) NULL;
3869   pool->nextitem = (void *) NULL;
3870   pool->deaditemstack = (void *) NULL;
3871   pool->pathblock = (void **) NULL;
3872   pool->pathitem = (void *) NULL;
3873   pool->alignbytes = 0;
3874   pool->itembytes = 0;
3875   pool->itemsperblock = 0;
3876   pool->itemsfirstblock = 0;
3877   pool->items = 0;
3878   pool->maxitems = 0;
3879   pool->unallocateditems = 0;
3880   pool->pathitemsleft = 0;
3881 }
3882 
3883 /*****************************************************************************/
3884 /*                                                                           */
3885 /*  poolrestart()   Deallocate all items in a pool.                          */
3886 /*                                                                           */
3887 /*  The pool is returned to its starting state, except that no memory is     */
3888 /*  freed to the operating system.  Rather, the previously allocated blocks  */
3889 /*  are ready to be reused.                                                  */
3890 /*                                                                           */
3891 /*****************************************************************************/
3892 
3893 #ifdef ANSI_DECLARATORS
3894 void poolrestart(struct memorypool *pool)
3895 #else /* not ANSI_DECLARATORS */
3896 void poolrestart(pool)
3897 struct memorypool *pool;
3898 #endif /* not ANSI_DECLARATORS */
3899 
3900 {
3901   TRIANGLE_PTRINT alignptr;
3902 
3903   pool->items = 0;
3904   pool->maxitems = 0;
3905 
3906   /* Set the currently active block. */
3907   pool->nowblock = pool->firstblock;
3908   /* Find the first item in the pool.  Increment by the size of (void *). */
3909   alignptr = (TRIANGLE_PTRINT) (pool->nowblock + 1);
3910   /* Align the item on an `alignbytes'-byte boundary. */
3911   pool->nextitem = (void *)
3912     (alignptr + (TRIANGLE_PTRINT) pool->alignbytes -
3913      (alignptr % (TRIANGLE_PTRINT) pool->alignbytes));
3914   /* There are lots of unallocated items left in this block. */
3915   pool->unallocateditems = pool->itemsfirstblock;
3916   /* The stack of deallocated items is empty. */
3917   pool->deaditemstack = (void *) NULL;
3918 }
3919 
3920 /*****************************************************************************/
3921 /*                                                                           */
3922 /*  poolinit()   Initialize a pool of memory for allocation of items.        */
3923 /*                                                                           */
3924 /*  This routine initializes the machinery for allocating items.  A `pool'   */
3925 /*  is created whose records have size at least `bytecount'.  Items will be  */
3926 /*  allocated in `itemcount'-item blocks.  Each item is assumed to be a      */
3927 /*  collection of words, and either pointers or floating-point values are    */
3928 /*  assumed to be the "primary" word type.  (The "primary" word type is used */
3929 /*  to determine alignment of items.)  If `alignment' isn't zero, all items  */
3930 /*  will be `alignment'-byte aligned in memory.  `alignment' must be either  */
3931 /*  a multiple or a factor of the primary word size; powers of two are safe. */
3932 /*  `alignment' is normally used to create a few unused bits at the bottom   */
3933 /*  of each item's pointer, in which information may be stored.              */
3934 /*                                                                           */
3935 /*  Don't change this routine unless you understand it.                      */
3936 /*                                                                           */
3937 /*****************************************************************************/
3938 
3939 #ifdef ANSI_DECLARATORS
3940 void poolinit(struct memorypool *pool, int bytecount, int itemcount,
3941               int firstitemcount, int alignment)
3942 #else /* not ANSI_DECLARATORS */
3943 void poolinit(pool, bytecount, itemcount, firstitemcount, alignment)
3944 struct memorypool *pool;
3945 int bytecount;
3946 int itemcount;
3947 int firstitemcount;
3948 int alignment;
3949 #endif /* not ANSI_DECLARATORS */
3950 
3951 {
3952   /* Find the proper alignment, which must be at least as large as:   */
3953   /*   - The parameter `alignment'.                                   */
3954   /*   - sizeof(void *), so the stack of dead items can be maintained */
3955   /*       without unaligned accesses.                                */
3956   if (alignment > sizeof(void *)) {
3957     pool->alignbytes = alignment;
3958   } else {
3959     pool->alignbytes = sizeof(void *);
3960   }
3961   pool->itembytes = ((bytecount - 1) / pool->alignbytes + 1) *
3962                     pool->alignbytes;
3963   pool->itemsperblock = itemcount;
3964   if (firstitemcount == 0) {
3965     pool->itemsfirstblock = itemcount;
3966   } else {
3967     pool->itemsfirstblock = firstitemcount;
3968   }
3969 
3970   /* Allocate a block of items.  Space for `itemsfirstblock' items and one  */
3971   /*   pointer (to point to the next block) are allocated, as well as space */
3972   /*   to ensure alignment of the items.                                    */
3973   pool->firstblock = (void **)
3974     trimalloc(pool->itemsfirstblock * pool->itembytes + (int) sizeof(void *) +
3975               pool->alignbytes);
3976   /* Set the next block pointer to NULL. */
3977   *(pool->firstblock) = (void *) NULL;
3978   poolrestart(pool);
3979 }
3980 
3981 /*****************************************************************************/
3982 /*                                                                           */
3983 /*  pooldeinit()   Free to the operating system all memory taken by a pool.  */
3984 /*                                                                           */
3985 /*****************************************************************************/
3986 
3987 #ifdef ANSI_DECLARATORS
3988 void pooldeinit(struct memorypool *pool)
3989 #else /* not ANSI_DECLARATORS */
3990 void pooldeinit(pool)
3991 struct memorypool *pool;
3992 #endif /* not ANSI_DECLARATORS */
3993 
3994 {
3995   while (pool->firstblock != (void **) NULL) {
3996     pool->nowblock = (void **) *(pool->firstblock);
3997     trifree((void *) pool->firstblock);
3998     pool->firstblock = pool->nowblock;
3999   }
4000 }
4001 
4002 /*****************************************************************************/
4003 /*                                                                           */
4004 /*  poolalloc()   Allocate space for an item.                                */
4005 /*                                                                           */
4006 /*****************************************************************************/
4007 
4008 #ifdef ANSI_DECLARATORS
4009 void *poolalloc(struct memorypool *pool)
4010 #else /* not ANSI_DECLARATORS */
4011 void *poolalloc(pool)
4012 struct memorypool *pool;
4013 #endif /* not ANSI_DECLARATORS */
4014 
4015 {
4016   void *newitem;
4017   void **newblock;
4018   TRIANGLE_PTRINT alignptr;
4019 
4020   /* First check the linked list of dead items.  If the list is not   */
4021   /*   empty, allocate an item from the list rather than a fresh one. */
4022   if (pool->deaditemstack != (void *) NULL) {
4023     newitem = pool->deaditemstack;               /* Take first item in list. */
4024     pool->deaditemstack = * (void **) pool->deaditemstack;
4025   } else {
4026     /* Check if there are any free items left in the current block. */
4027     if (pool->unallocateditems == 0) {
4028       /* Check if another block must be allocated. */
4029       if (*(pool->nowblock) == (void *) NULL) {
4030         /* Allocate a new block of items, pointed to by the previous block. */
4031         newblock = (void **) trimalloc(pool->itemsperblock * pool->itembytes +
4032                                        (int) sizeof(void *) +
4033                                        pool->alignbytes);
4034         *(pool->nowblock) = (void *) newblock;
4035         /* The next block pointer is NULL. */
4036         *newblock = (void *) NULL;
4037       }
4038 
4039       /* Move to the new block. */
4040       pool->nowblock = (void **) *(pool->nowblock);
4041       /* Find the first item in the block.    */
4042       /*   Increment by the size of (void *). */
4043       alignptr = (TRIANGLE_PTRINT) (pool->nowblock + 1);
4044       /* Align the item on an `alignbytes'-byte boundary. */
4045       pool->nextitem = (void *)
4046         (alignptr + (TRIANGLE_PTRINT) pool->alignbytes -
4047          (alignptr % (TRIANGLE_PTRINT) pool->alignbytes));
4048       /* There are lots of unallocated items left in this block. */
4049       pool->unallocateditems = pool->itemsperblock;
4050     }
4051 
4052     /* Allocate a new item. */
4053     newitem = pool->nextitem;
4054     /* Advance `nextitem' pointer to next free item in block. */
4055     pool->nextitem = (void *) ((char *) pool->nextitem + pool->itembytes);
4056     pool->unallocateditems--;
4057     pool->maxitems++;
4058   }
4059   pool->items++;
4060   return newitem;
4061 }
4062 
4063 /*****************************************************************************/
4064 /*                                                                           */
4065 /*  pooldealloc()   Deallocate space for an item.                            */
4066 /*                                                                           */
4067 /*  The deallocated space is stored in a queue for later reuse.              */
4068 /*                                                                           */
4069 /*****************************************************************************/
4070 
4071 #ifdef ANSI_DECLARATORS
4072 void pooldealloc(struct memorypool *pool, void *dyingitem)
4073 #else /* not ANSI_DECLARATORS */
4074 void pooldealloc(pool, dyingitem)
4075 struct memorypool *pool;
4076 void *dyingitem;
4077 #endif /* not ANSI_DECLARATORS */
4078 
4079 {
4080   /* Push freshly killed item onto stack. */
4081   *((void **) dyingitem) = pool->deaditemstack;
4082   pool->deaditemstack = dyingitem;
4083   pool->items--;
4084 }
4085 
4086 /*****************************************************************************/
4087 /*                                                                           */
4088 /*  traversalinit()   Prepare to traverse the entire list of items.          */
4089 /*                                                                           */
4090 /*  This routine is used in conjunction with traverse().                     */
4091 /*                                                                           */
4092 /*****************************************************************************/
4093 
4094 #ifdef ANSI_DECLARATORS
4095 void traversalinit(struct memorypool *pool)
4096 #else /* not ANSI_DECLARATORS */
4097 void traversalinit(pool)
4098 struct memorypool *pool;
4099 #endif /* not ANSI_DECLARATORS */
4100 
4101 {
4102   TRIANGLE_PTRINT alignptr;
4103 
4104   /* Begin the traversal in the first block. */
4105   pool->pathblock = pool->firstblock;
4106   /* Find the first item in the block.  Increment by the size of (void *). */
4107   alignptr = (TRIANGLE_PTRINT) (pool->pathblock + 1);
4108   /* Align with item on an `alignbytes'-byte boundary. */
4109   pool->pathitem = (void *)
4110     (alignptr + (TRIANGLE_PTRINT) pool->alignbytes -
4111      (alignptr % (TRIANGLE_PTRINT) pool->alignbytes));
4112   /* Set the number of items left in the current block. */
4113   pool->pathitemsleft = pool->itemsfirstblock;
4114 }
4115 
4116 /*****************************************************************************/
4117 /*                                                                           */
4118 /*  traverse()   Find the next item in the list.                             */
4119 /*                                                                           */
4120 /*  This routine is used in conjunction with traversalinit().  Be forewarned */
4121 /*  that this routine successively returns all items in the list, including  */
4122 /*  deallocated ones on the deaditemqueue.  It's up to you to figure out     */
4123 /*  which ones are actually dead.  Why?  I don't want to allocate extra      */
4124 /*  space just to demarcate dead items.  It can usually be done more         */
4125 /*  space-efficiently by a routine that knows something about the structure  */
4126 /*  of the item.                                                             */
4127 /*                                                                           */
4128 /*****************************************************************************/
4129 
4130 #ifdef ANSI_DECLARATORS
4131 void *traverse(struct memorypool *pool)
4132 #else /* not ANSI_DECLARATORS */
4133 void *traverse(pool)
4134 struct memorypool *pool;
4135 #endif /* not ANSI_DECLARATORS */
4136 
4137 {
4138   void *newitem;
4139   TRIANGLE_PTRINT alignptr;
4140 
4141   /* Stop upon exhausting the list of items. */
4142   if (pool->pathitem == pool->nextitem) {
4143     return (void *) NULL;
4144   }
4145 
4146   /* Check whether any untraversed items remain in the current block. */
4147   if (pool->pathitemsleft == 0) {
4148     /* Find the next block. */
4149     pool->pathblock = (void **) *(pool->pathblock);
4150     /* Find the first item in the block.  Increment by the size of (void *). */
4151     alignptr = (TRIANGLE_PTRINT) (pool->pathblock + 1);
4152     /* Align with item on an `alignbytes'-byte boundary. */
4153     pool->pathitem = (void *)
4154       (alignptr + (TRIANGLE_PTRINT) pool->alignbytes -
4155        (alignptr % (TRIANGLE_PTRINT) pool->alignbytes));
4156     /* Set the number of items left in the current block. */
4157     pool->pathitemsleft = pool->itemsperblock;
4158   }
4159 
4160   newitem = pool->pathitem;
4161   /* Find the next item in the block. */
4162   pool->pathitem = (void *) ((char *) pool->pathitem + pool->itembytes);
4163   pool->pathitemsleft--;
4164   return newitem;
4165 }
4166 
4167 /*****************************************************************************/
4168 /*                                                                           */
4169 /*  dummyinit()   Initialize the triangle that fills "outer space" and the   */
4170 /*                omnipresent subsegment.                                    */
4171 /*                                                                           */
4172 /*  The triangle that fills "outer space," called `dummytri', is pointed to  */
4173 /*  by every triangle and subsegment on a boundary (be it outer or inner) of */
4174 /*  the triangulation.  Also, `dummytri' points to one of the triangles on   */
4175 /*  the convex hull (until the holes and concavities are carved), making it  */
4176 /*  possible to find a starting triangle for point location.                 */
4177 /*                                                                           */
4178 /*  The omnipresent subsegment, `dummysub', is pointed to by every triangle  */
4179 /*  or subsegment that doesn't have a full complement of real subsegments    */
4180 /*  to point to.                                                             */
4181 /*                                                                           */
4182 /*  `dummytri' and `dummysub' are generally required to fulfill only a few   */
4183 /*  invariants:  their vertices must remain NULL and `dummytri' must always  */
4184 /*  be bonded (at offset zero) to some triangle on the convex hull of the    */
4185 /*  mesh, via a boundary edge.  Otherwise, the connections of `dummytri' and */
4186 /*  `dummysub' may change willy-nilly.  This makes it possible to avoid      */
4187 /*  writing a good deal of special-case code (in the edge flip, for example) */
4188 /*  for dealing with the boundary of the mesh, places where no subsegment is */
4189 /*  present, and so forth.  Other entities are frequently bonded to          */
4190 /*  `dummytri' and `dummysub' as if they were real mesh entities, with no    */
4191 /*  harm done.                                                               */
4192 /*                                                                           */
4193 /*****************************************************************************/
4194 
4195 #ifdef ANSI_DECLARATORS
4196 void dummyinit(struct mesh *m, struct behavior *b, int trianglebytes,
4197                int subsegbytes)
4198 #else /* not ANSI_DECLARATORS */
4199 void dummyinit(m, b, trianglebytes, subsegbytes)
4200 struct mesh *m;
4201 struct behavior *b;
4202 int trianglebytes;
4203 int subsegbytes;
4204 #endif /* not ANSI_DECLARATORS */
4205 
4206 {
4207   TRIANGLE_PTRINT alignptr;
4208 
4209   /* Set up `dummytri', the `triangle' that occupies "outer space." */
4210   m->dummytribase = (triangle *) trimalloc(trianglebytes +
4211                                            m->triangles.alignbytes);
4212   /* Align `dummytri' on a `triangles.alignbytes'-byte boundary. */
4213   alignptr = (TRIANGLE_PTRINT) m->dummytribase;
4214   m->dummytri = (triangle *)
4215     (alignptr + (TRIANGLE_PTRINT) m->triangles.alignbytes -
4216      (alignptr % (TRIANGLE_PTRINT) m->triangles.alignbytes));
4217   /* Initialize the three adjoining triangles to be "outer space."  These  */
4218   /*   will eventually be changed by various bonding operations, but their */
4219   /*   values don't really matter, as long as they can legally be          */
4220   /*   dereferenced.                                                       */
4221   m->dummytri[0] = (triangle) m->dummytri;
4222   m->dummytri[1] = (triangle) m->dummytri;
4223   m->dummytri[2] = (triangle) m->dummytri;
4224   /* Three NULL vertices. */
4225   m->dummytri[3] = (triangle) NULL;
4226   m->dummytri[4] = (triangle) NULL;
4227   m->dummytri[5] = (triangle) NULL;
4228 
4229   if (b->usesegments) {
4230     /* Set up `dummysub', the omnipresent subsegment pointed to by any */
4231     /*   triangle side or subsegment end that isn't attached to a real */
4232     /*   subsegment.                                                   */
4233     m->dummysubbase = (subseg *) trimalloc(subsegbytes +
4234                                            m->subsegs.alignbytes);
4235     /* Align `dummysub' on a `subsegs.alignbytes'-byte boundary. */
4236     alignptr = (TRIANGLE_PTRINT) m->dummysubbase;
4237     m->dummysub = (subseg *)
4238       (alignptr + (TRIANGLE_PTRINT) m->subsegs.alignbytes -
4239        (alignptr % (TRIANGLE_PTRINT) m->subsegs.alignbytes));
4240     /* Initialize the two adjoining subsegments to be the omnipresent      */
4241     /*   subsegment.  These will eventually be changed by various bonding  */
4242     /*   operations, but their values don't really matter, as long as they */
4243     /*   can legally be dereferenced.                                      */
4244     m->dummysub[0] = (subseg) m->dummysub;
4245     m->dummysub[1] = (subseg) m->dummysub;
4246     /* Four NULL vertices. */
4247     m->dummysub[2] = (subseg) NULL;
4248     m->dummysub[3] = (subseg) NULL;
4249     m->dummysub[4] = (subseg) NULL;
4250     m->dummysub[5] = (subseg) NULL;
4251     /* Initialize the two adjoining triangles to be "outer space." */
4252     m->dummysub[6] = (subseg) m->dummytri;
4253     m->dummysub[7] = (subseg) m->dummytri;
4254     /* Set the boundary marker to zero. */
4255     * (int *) (m->dummysub + 8) = 0;
4256 
4257     /* Initialize the three adjoining subsegments of `dummytri' to be */
4258     /*   the omnipresent subsegment.                                  */
4259     m->dummytri[6] = (triangle) m->dummysub;
4260     m->dummytri[7] = (triangle) m->dummysub;
4261     m->dummytri[8] = (triangle) m->dummysub;
4262   }
4263 }
4264 
4265 /*****************************************************************************/
4266 /*                                                                           */
4267 /*  initializevertexpool()   Calculate the size of the vertex data structure */
4268 /*                           and initialize its memory pool.                 */
4269 /*                                                                           */
4270 /*  This routine also computes the `vertexmarkindex' and `vertex2triindex'   */
4271 /*  indices used to find values within each vertex.                          */
4272 /*                                                                           */
4273 /*****************************************************************************/
4274 
4275 #ifdef ANSI_DECLARATORS
4276 void initializevertexpool(struct mesh *m, struct behavior *b)
4277 #else /* not ANSI_DECLARATORS */
4278 void initializevertexpool(m, b)
4279 struct mesh *m;
4280 struct behavior *b;
4281 #endif /* not ANSI_DECLARATORS */
4282 
4283 {
4284   int vertexsize;
4285 
4286   /* The index within each vertex at which the boundary marker is found,    */
4287   /*   followed by the vertex type.  Ensure the vertex marker is aligned to */
4288   /*   a sizeof(int)-byte address.                                          */
4289   m->vertexmarkindex = ((m->mesh_dim + m->nextras) * sizeof(REAL) +
4290                         sizeof(int) - 1) /
4291                        sizeof(int);
4292   vertexsize = (m->vertexmarkindex + 2) * sizeof(int);
4293   if (b->poly) {
4294     /* The index within each vertex at which a triangle pointer is found.  */
4295     /*   Ensure the pointer is aligned to a sizeof(triangle)-byte address. */
4296     m->vertex2triindex = (vertexsize + sizeof(triangle) - 1) /
4297                          sizeof(triangle);
4298     vertexsize = (m->vertex2triindex + 1) * sizeof(triangle);
4299   }
4300 
4301   /* Initialize the pool of vertices. */
4302   poolinit(&m->vertices, vertexsize, VERTEXPERBLOCK,
4303            m->invertices > VERTEXPERBLOCK ? m->invertices : VERTEXPERBLOCK,
4304            sizeof(REAL));
4305 }
4306 
4307 /*****************************************************************************/
4308 /*                                                                           */
4309 /*  initializetrisubpools()   Calculate the sizes of the triangle and        */
4310 /*                            subsegment data structures and initialize      */
4311 /*                            their memory pools.                            */
4312 /*                                                                           */
4313 /*  This routine also computes the `highorderindex', `elemattribindex', and  */
4314 /*  `areaboundindex' indices used to find values within each triangle.       */
4315 /*                                                                           */
4316 /*****************************************************************************/
4317 
4318 #ifdef ANSI_DECLARATORS
4319 void initializetrisubpools(struct mesh *m, struct behavior *b)
4320 #else /* not ANSI_DECLARATORS */
4321 void initializetrisubpools(m, b)
4322 struct mesh *m;
4323 struct behavior *b;
4324 #endif /* not ANSI_DECLARATORS */
4325 
4326 {
4327   int trisize;
4328 
4329   /* The index within each triangle at which the extra nodes (above three)  */
4330   /*   associated with high order elements are found.  There are three      */
4331   /*   pointers to other triangles, three pointers to corners, and possibly */
4332   /*   three pointers to subsegments before the extra nodes.                */
4333   m->highorderindex = 6 + (b->usesegments * 3);
4334   /* The number of bytes occupied by a triangle. */
4335   trisize = ((b->order + 1) * (b->order + 2) / 2 + (m->highorderindex - 3)) *
4336             sizeof(triangle);
4337   /* The index within each triangle at which its attributes are found, */
4338   /*   where the index is measured in REALs.                           */
4339   m->elemattribindex = (trisize + sizeof(REAL) - 1) / sizeof(REAL);
4340   /* The index within each triangle at which the maximum area constraint  */
4341   /*   is found, where the index is measured in REALs.  Note that if the  */
4342   /*   `regionattrib' flag is set, an additional attribute will be added. */
4343   m->areaboundindex = m->elemattribindex + m->eextras + b->regionattrib;
4344   /* If triangle attributes or an area bound are needed, increase the number */
4345   /*   of bytes occupied by a triangle.                                      */
4346   if (b->vararea) {
4347     trisize = (m->areaboundindex + 1) * sizeof(REAL);
4348   } else if (m->eextras + b->regionattrib > 0) {
4349     trisize = m->areaboundindex * sizeof(REAL);
4350   }
4351   /* If a Voronoi diagram or triangle neighbor graph is requested, make    */
4352   /*   sure there's room to store an integer index in each triangle.  This */
4353   /*   integer index can occupy the same space as the subsegment pointers  */
4354   /*   or attributes or area constraint or extra nodes.                    */
4355   if ((b->voronoi || b->neighbors) &&
4356       (trisize < 6 * sizeof(triangle) + sizeof(int))) {
4357     trisize = 6 * sizeof(triangle) + sizeof(int);
4358   }
4359 
4360   /* Having determined the memory size of a triangle, initialize the pool. */
4361   poolinit(&m->triangles, trisize, TRIPERBLOCK,
4362            (2 * m->invertices - 2) > TRIPERBLOCK ? (2 * m->invertices - 2) :
4363            TRIPERBLOCK, 4);
4364 
4365   if (b->usesegments) {
4366     /* Initialize the pool of subsegments.  Take into account all eight */
4367     /*   pointers and one boundary marker.                              */
4368     poolinit(&m->subsegs, 8 * sizeof(triangle) + sizeof(int),
4369              SUBSEGPERBLOCK, SUBSEGPERBLOCK, 4);
4370 
4371     /* Initialize the "outer space" triangle and omnipresent subsegment. */
4372     dummyinit(m, b, m->triangles.itembytes, m->subsegs.itembytes);
4373   } else {
4374     /* Initialize the "outer space" triangle. */
4375     dummyinit(m, b, m->triangles.itembytes, 0);
4376   }
4377 }
4378 
4379 /*****************************************************************************/
4380 /*                                                                           */
4381 /*  triangledealloc()   Deallocate space for a triangle, marking it dead.    */
4382 /*                                                                           */
4383 /*****************************************************************************/
4384 
4385 #ifdef ANSI_DECLARATORS
4386 void triangledealloc(struct mesh *m, triangle *dyingtriangle)
4387 #else /* not ANSI_DECLARATORS */
4388 void triangledealloc(m, dyingtriangle)
4389 struct mesh *m;
4390 triangle *dyingtriangle;
4391 #endif /* not ANSI_DECLARATORS */
4392 
4393 {
4394   /* Mark the triangle as dead.  This makes it possible to detect dead */
4395   /*   triangles when traversing the list of all triangles.            */
4396   killtri(dyingtriangle);
4397   pooldealloc(&m->triangles, (void *) dyingtriangle);
4398 }
4399 
4400 /*****************************************************************************/
4401 /*                                                                           */
4402 /*  triangletraverse()   Traverse the triangles, skipping dead ones.         */
4403 /*                                                                           */
4404 /*****************************************************************************/
4405 
4406 #ifdef ANSI_DECLARATORS
4407 triangle *triangletraverse(struct mesh *m)
4408 #else /* not ANSI_DECLARATORS */
4409 triangle *triangletraverse(m)
4410 struct mesh *m;
4411 #endif /* not ANSI_DECLARATORS */
4412 
4413 {
4414   triangle *newtriangle;
4415 
4416   do {
4417     newtriangle = (triangle *) traverse(&m->triangles);
4418     if (newtriangle == (triangle *) NULL) {
4419       return (triangle *) NULL;
4420     }
4421   } while (deadtri(newtriangle));                         /* Skip dead ones. */
4422   return newtriangle;
4423 }
4424 
4425 /*****************************************************************************/
4426 /*                                                                           */
4427 /*  subsegdealloc()   Deallocate space for a subsegment, marking it dead.    */
4428 /*                                                                           */
4429 /*****************************************************************************/
4430 
4431 #ifdef ANSI_DECLARATORS
4432 void subsegdealloc(struct mesh *m, subseg *dyingsubseg)
4433 #else /* not ANSI_DECLARATORS */
4434 void subsegdealloc(m, dyingsubseg)
4435 struct mesh *m;
4436 subseg *dyingsubseg;
4437 #endif /* not ANSI_DECLARATORS */
4438 
4439 {
4440   /* Mark the subsegment as dead.  This makes it possible to detect dead */
4441   /*   subsegments when traversing the list of all subsegments.          */
4442   killsubseg(dyingsubseg);
4443   pooldealloc(&m->subsegs, (void *) dyingsubseg);
4444 }
4445 
4446 /*****************************************************************************/
4447 /*                                                                           */
4448 /*  subsegtraverse()   Traverse the subsegments, skipping dead ones.         */
4449 /*                                                                           */
4450 /*****************************************************************************/
4451 
4452 #ifdef ANSI_DECLARATORS
4453 subseg *subsegtraverse(struct mesh *m)
4454 #else /* not ANSI_DECLARATORS */
4455 subseg *subsegtraverse(m)
4456 struct mesh *m;
4457 #endif /* not ANSI_DECLARATORS */
4458 
4459 {
4460   subseg *newsubseg;
4461 
4462   do {
4463     newsubseg = (subseg *) traverse(&m->subsegs);
4464     if (newsubseg == (subseg *) NULL) {
4465       return (subseg *) NULL;
4466     }
4467   } while (deadsubseg(newsubseg));                        /* Skip dead ones. */
4468   return newsubseg;
4469 }
4470 
4471 /*****************************************************************************/
4472 /*                                                                           */
4473 /*  vertexdealloc()   Deallocate space for a vertex, marking it dead.        */
4474 /*                                                                           */
4475 /*****************************************************************************/
4476 
4477 #ifdef ANSI_DECLARATORS
4478 void vertexdealloc(struct mesh *m, vertex dyingvertex)
4479 #else /* not ANSI_DECLARATORS */
4480 void vertexdealloc(m, dyingvertex)
4481 struct mesh *m;
4482 vertex dyingvertex;
4483 #endif /* not ANSI_DECLARATORS */
4484 
4485 {
4486   /* Mark the vertex as dead.  This makes it possible to detect dead */
4487   /*   vertices when traversing the list of all vertices.            */
4488   setvertextype(dyingvertex, DEADVERTEX);
4489   pooldealloc(&m->vertices, (void *) dyingvertex);
4490 }
4491 
4492 /*****************************************************************************/
4493 /*                                                                           */
4494 /*  vertextraverse()   Traverse the vertices, skipping dead ones.            */
4495 /*                                                                           */
4496 /*****************************************************************************/
4497 
4498 #ifdef ANSI_DECLARATORS
4499 vertex vertextraverse(struct mesh *m)
4500 #else /* not ANSI_DECLARATORS */
4501 vertex vertextraverse(m)
4502 struct mesh *m;
4503 #endif /* not ANSI_DECLARATORS */
4504 
4505 {
4506   vertex newvertex;
4507 
4508   do {
4509     newvertex = (vertex) traverse(&m->vertices);
4510     if (newvertex == (vertex) NULL) {
4511       return (vertex) NULL;
4512     }
4513   } while (vertextype(newvertex) == DEADVERTEX);          /* Skip dead ones. */
4514   return newvertex;
4515 }
4516 
4517 /*****************************************************************************/
4518 /*                                                                           */
4519 /*  badsubsegdealloc()   Deallocate space for a bad subsegment, marking it   */
4520 /*                       dead.                                               */
4521 /*                                                                           */
4522 /*****************************************************************************/
4523 
4524 #ifndef CDT_ONLY
4525 
4526 #ifdef ANSI_DECLARATORS
4527 void badsubsegdealloc(struct mesh *m, struct badsubseg *dyingseg)
4528 #else /* not ANSI_DECLARATORS */
4529 void badsubsegdealloc(m, dyingseg)
4530 struct mesh *m;
4531 struct badsubseg *dyingseg;
4532 #endif /* not ANSI_DECLARATORS */
4533 
4534 {
4535   /* Set subsegment's origin to NULL.  This makes it possible to detect dead */
4536   /*   badsubsegs when traversing the list of all badsubsegs             .   */
4537   dyingseg->subsegorg = (vertex) NULL;
4538   pooldealloc(&m->badsubsegs, (void *) dyingseg);
4539 }
4540 
4541 #endif /* not CDT_ONLY */
4542 
4543 /*****************************************************************************/
4544 /*                                                                           */
4545 /*  badsubsegtraverse()   Traverse the bad subsegments, skipping dead ones.  */
4546 /*                                                                           */
4547 /*****************************************************************************/
4548 
4549 #ifndef CDT_ONLY
4550 
4551 #ifdef ANSI_DECLARATORS
4552 struct badsubseg *badsubsegtraverse(struct mesh *m)
4553 #else /* not ANSI_DECLARATORS */
4554 struct badsubseg *badsubsegtraverse(m)
4555 struct mesh *m;
4556 #endif /* not ANSI_DECLARATORS */
4557 
4558 {
4559   struct badsubseg *newseg;
4560 
4561   do {
4562     newseg = (struct badsubseg *) traverse(&m->badsubsegs);
4563     if (newseg == (struct badsubseg *) NULL) {
4564       return (struct badsubseg *) NULL;
4565     }
4566   } while (newseg->subsegorg == (vertex) NULL);           /* Skip dead ones. */
4567   return newseg;
4568 }
4569 
4570 #endif /* not CDT_ONLY */
4571 
4572 /*****************************************************************************/
4573 /*                                                                           */
4574 /*  getvertex()   Get a specific vertex, by number, from the list.           */
4575 /*                                                                           */
4576 /*  The first vertex is number 'firstnumber'.                                */
4577 /*                                                                           */
4578 /*  Note that this takes O(n) time (with a small constant, if VERTEXPERBLOCK */
4579 /*  is large).  I don't care to take the trouble to make it work in constant */
4580 /*  time.                                                                    */
4581 /*                                                                           */
4582 /*****************************************************************************/
4583 
4584 #ifdef ANSI_DECLARATORS
4585 vertex getvertex(struct mesh *m, struct behavior *b, int number)
4586 #else /* not ANSI_DECLARATORS */
4587 vertex getvertex(m, b, number)
4588 struct mesh *m;
4589 struct behavior *b;
4590 int number;
4591 #endif /* not ANSI_DECLARATORS */
4592 
4593 {
4594   void **getblock;
4595   char *foundvertex;
4596   TRIANGLE_PTRINT alignptr;
4597   int current;
4598 
4599   getblock = m->vertices.firstblock;
4600   current = b->firstnumber;
4601 
4602   /* Find the right block. */
4603   if (current + m->vertices.itemsfirstblock <= number) {
4604     getblock = (void **) *getblock;
4605     current += m->vertices.itemsfirstblock;
4606     while (current + m->vertices.itemsperblock <= number) {
4607       getblock = (void **) *getblock;
4608       current += m->vertices.itemsperblock;
4609     }
4610   }
4611 
4612   /* Now find the right vertex. */
4613   alignptr = (TRIANGLE_PTRINT) (getblock + 1);
4614   foundvertex = (char *) (alignptr + (TRIANGLE_PTRINT) m->vertices.alignbytes -
4615                           (alignptr % (TRIANGLE_PTRINT) m->vertices.alignbytes));
4616   return (vertex) (foundvertex + m->vertices.itembytes * (number - current));
4617 }
4618 
4619 /*****************************************************************************/
4620 /*                                                                           */
4621 /*  triangledeinit()   Free all remaining allocated memory.                  */
4622 /*                                                                           */
4623 /*****************************************************************************/
4624 
4625 #ifdef ANSI_DECLARATORS
4626 void triangledeinit(struct mesh *m, struct behavior *b)
4627 #else /* not ANSI_DECLARATORS */
4628 void triangledeinit(m, b)
4629 struct mesh *m;
4630 struct behavior *b;
4631 #endif /* not ANSI_DECLARATORS */
4632 
4633 {
4634   pooldeinit(&m->triangles);
4635   trifree((void *) m->dummytribase);
4636   if (b->usesegments) {
4637     pooldeinit(&m->subsegs);
4638     trifree((void *) m->dummysubbase);
4639   }
4640   pooldeinit(&m->vertices);
4641 #ifndef CDT_ONLY
4642   if (b->quality) {
4643     pooldeinit(&m->badsubsegs);
4644     if ((b->minangle > 0.0) || b->vararea || b->fixedarea || b->usertest) {
4645       pooldeinit(&m->badtriangles);
4646       pooldeinit(&m->flipstackers);
4647     }
4648   }
4649 #endif /* not CDT_ONLY */
4650 }
4651 
4652 /**                                                                         **/
4653 /**                                                                         **/
4654 /********* Memory management routines end here                       *********/
4655 
4656 /********* Constructors begin here                                   *********/
4657 /**                                                                         **/
4658 /**                                                                         **/
4659 
4660 /*****************************************************************************/
4661 /*                                                                           */
4662 /*  maketriangle()   Create a new triangle with orientation zero.            */
4663 /*                                                                           */
4664 /*****************************************************************************/
4665 
4666 #ifdef ANSI_DECLARATORS
4667 void maketriangle(struct mesh *m, struct behavior *b, struct otri *newotri)
4668 #else /* not ANSI_DECLARATORS */
4669 void maketriangle(m, b, newotri)
4670 struct mesh *m;
4671 struct behavior *b;
4672 struct otri *newotri;
4673 #endif /* not ANSI_DECLARATORS */
4674 
4675 {
4676   int i;
4677 
4678   newotri->tri = (triangle *) poolalloc(&m->triangles);
4679   /* Initialize the three adjoining triangles to be "outer space". */
4680   newotri->tri[0] = (triangle) m->dummytri;
4681   newotri->tri[1] = (triangle) m->dummytri;
4682   newotri->tri[2] = (triangle) m->dummytri;
4683   /* Three NULL vertices. */
4684   newotri->tri[3] = (triangle) NULL;
4685   newotri->tri[4] = (triangle) NULL;
4686   newotri->tri[5] = (triangle) NULL;
4687   if (b->usesegments) {
4688     /* Initialize the three adjoining subsegments to be the omnipresent */
4689     /*   subsegment.                                                    */
4690     newotri->tri[6] = (triangle) m->dummysub;
4691     newotri->tri[7] = (triangle) m->dummysub;
4692     newotri->tri[8] = (triangle) m->dummysub;
4693   }
4694   for (i = 0; i < m->eextras; i++) {
4695     setelemattribute(*newotri, i, 0.0);
4696   }
4697   if (b->vararea) {
4698     setareabound(*newotri, -1.0);
4699   }
4700 
4701   newotri->orient = 0;
4702 }
4703 
4704 /*****************************************************************************/
4705 /*                                                                           */
4706 /*  makesubseg()   Create a new subsegment with orientation zero.            */
4707 /*                                                                           */
4708 /*****************************************************************************/
4709 
4710 #ifdef ANSI_DECLARATORS
4711 void makesubseg(struct mesh *m, struct osub *newsubseg)
4712 #else /* not ANSI_DECLARATORS */
4713 void makesubseg(m, newsubseg)
4714 struct mesh *m;
4715 struct osub *newsubseg;
4716 #endif /* not ANSI_DECLARATORS */
4717 
4718 {
4719   newsubseg->ss = (subseg *) poolalloc(&m->subsegs);
4720   /* Initialize the two adjoining subsegments to be the omnipresent */
4721   /*   subsegment.                                                  */
4722   newsubseg->ss[0] = (subseg) m->dummysub;
4723   newsubseg->ss[1] = (subseg) m->dummysub;
4724   /* Four NULL vertices. */
4725   newsubseg->ss[2] = (subseg) NULL;
4726   newsubseg->ss[3] = (subseg) NULL;
4727   newsubseg->ss[4] = (subseg) NULL;
4728   newsubseg->ss[5] = (subseg) NULL;
4729   /* Initialize the two adjoining triangles to be "outer space." */
4730   newsubseg->ss[6] = (subseg) m->dummytri;
4731   newsubseg->ss[7] = (subseg) m->dummytri;
4732   /* Set the boundary marker to zero. */
4733   setmark(*newsubseg, 0);
4734 
4735   newsubseg->ssorient = 0;
4736 }
4737 
4738 /**                                                                         **/
4739 /**                                                                         **/
4740 /********* Constructors end here                                     *********/
4741 
4742 /********* Geometric primitives begin here                           *********/
4743 /**                                                                         **/
4744 /**                                                                         **/
4745 
4746 /* The adaptive exact arithmetic geometric predicates implemented herein are */
4747 /*   described in detail in my paper, "Adaptive Precision Floating-Point     */
4748 /*   Arithmetic and Fast Robust Geometric Predicates."  See the header for a */
4749 /*   full citation.                                                          */
4750 
4751 /* Which of the following two methods of finding the absolute values is      */
4752 /*   fastest is compiler-dependent.  A few compilers can inline and optimize */
4753 /*   the fabs() call; but most will incur the overhead of a function call,   */
4754 /*   which is disastrously slow.  A faster way on IEEE machines might be to  */
4755 /*   mask the appropriate bit, but that's difficult to do in C without       */
4756 /*   forcing the value to be stored to memory (rather than be kept in the    */
4757 /*   register to which the optimizer assigned it).                           */
4758 
4759 #define Absolute(a)  ((a) >= 0.0 ? (a) : -(a))
4760 /* #define Absolute(a)  fabs(a) */
4761 
4762 /* Many of the operations are broken up into two pieces, a main part that    */
4763 /*   performs an approximate operation, and a "tail" that computes the       */
4764 /*   roundoff error of that operation.                                       */
4765 /*                                                                           */
4766 /* The operations Fast_Two_Sum(), Fast_Two_Diff(), Two_Sum(), Two_Diff(),    */
4767 /*   Split(), and Two_Product() are all implemented as described in the      */
4768 /*   reference.  Each of these macros requires certain variables to be       */
4769 /*   defined in the calling routine.  The variables `bvirt', `c', `abig',    */
4770 /*   `_i', `_j', `_k', `_l', `_m', and `_n' are declared `INEXACT' because   */
4771 /*   they store the result of an operation that may incur roundoff error.    */
4772 /*   The input parameter `x' (or the highest numbered `x_' parameter) must   */
4773 /*   also be declared `INEXACT'.                                             */
4774 
4775 #define Fast_Two_Sum_Tail(a, b, x, y) \
4776   bvirt = x - a; \
4777   y = b - bvirt
4778 
4779 #define Fast_Two_Sum(a, b, x, y) \
4780   x = (REAL) (a + b); \
4781   Fast_Two_Sum_Tail(a, b, x, y)
4782 
4783 #define Two_Sum_Tail(a, b, x, y) \
4784   bvirt = (REAL) (x - a); \
4785   avirt = x - bvirt; \
4786   bround = b - bvirt; \
4787   around = a - avirt; \
4788   y = around + bround
4789 
4790 #define Two_Sum(a, b, x, y) \
4791   x = (REAL) (a + b); \
4792   Two_Sum_Tail(a, b, x, y)
4793 
4794 #define Two_Diff_Tail(a, b, x, y) \
4795   bvirt = (REAL) (a - x); \
4796   avirt = x + bvirt; \
4797   bround = bvirt - b; \
4798   around = a - avirt; \
4799   y = around + bround
4800 
4801 #define Two_Diff(a, b, x, y) \
4802   x = (REAL) (a - b); \
4803   Two_Diff_Tail(a, b, x, y)
4804 
4805 #define Split(a, ahi, alo) \
4806   c = (REAL) (splitter * a); \
4807   abig = (REAL) (c - a); \
4808   ahi = c - abig; \
4809   alo = a - ahi
4810 
4811 #define Two_Product_Tail(a, b, x, y) \
4812   Split(a, ahi, alo); \
4813   Split(b, bhi, blo); \
4814   err1 = x - (ahi * bhi); \
4815   err2 = err1 - (alo * bhi); \
4816   err3 = err2 - (ahi * blo); \
4817   y = (alo * blo) - err3
4818 
4819 #define Two_Product(a, b, x, y) \
4820   x = (REAL) (a * b); \
4821   Two_Product_Tail(a, b, x, y)
4822 
4823 /* Two_Product_Presplit() is Two_Product() where one of the inputs has       */
4824 /*   already been split.  Avoids redundant splitting.                        */
4825 
4826 #define Two_Product_Presplit(a, b, bhi, blo, x, y) \
4827   x = (REAL) (a * b); \
4828   Split(a, ahi, alo); \
4829   err1 = x - (ahi * bhi); \
4830   err2 = err1 - (alo * bhi); \
4831   err3 = err2 - (ahi * blo); \
4832   y = (alo * blo) - err3
4833 
4834 /* Square() can be done more quickly than Two_Product().                     */
4835 
4836 #define Square_Tail(a, x, y) \
4837   Split(a, ahi, alo); \
4838   err1 = x - (ahi * ahi); \
4839   err3 = err1 - ((ahi + ahi) * alo); \
4840   y = (alo * alo) - err3
4841 
4842 #define Square(a, x, y) \
4843   x = (REAL) (a * a); \
4844   Square_Tail(a, x, y)
4845 
4846 /* Macros for summing expansions of various fixed lengths.  These are all    */
4847 /*   unrolled versions of Expansion_Sum().                                   */
4848 
4849 #define Two_One_Sum(a1, a0, b, x2, x1, x0) \
4850   Two_Sum(a0, b , _i, x0); \
4851   Two_Sum(a1, _i, x2, x1)
4852 
4853 #define Two_One_Diff(a1, a0, b, x2, x1, x0) \
4854   Two_Diff(a0, b , _i, x0); \
4855   Two_Sum( a1, _i, x2, x1)
4856 
4857 #define Two_Two_Sum(a1, a0, b1, b0, x3, x2, x1, x0) \
4858   Two_One_Sum(a1, a0, b0, _j, _0, x0); \
4859   Two_One_Sum(_j, _0, b1, x3, x2, x1)
4860 
4861 #define Two_Two_Diff(a1, a0, b1, b0, x3, x2, x1, x0) \
4862   Two_One_Diff(a1, a0, b0, _j, _0, x0); \
4863   Two_One_Diff(_j, _0, b1, x3, x2, x1)
4864 
4865 /* Macro for multiplying a two-component expansion by a single component.    */
4866 
4867 #define Two_One_Product(a1, a0, b, x3, x2, x1, x0) \
4868   Split(b, bhi, blo); \
4869   Two_Product_Presplit(a0, b, bhi, blo, _i, x0); \
4870   Two_Product_Presplit(a1, b, bhi, blo, _j, _0); \
4871   Two_Sum(_i, _0, _k, x1); \
4872   Fast_Two_Sum(_j, _k, x3, x2)
4873 
4874 /*****************************************************************************/
4875 /*                                                                           */
4876 /*  exactinit()   Initialize the variables used for exact arithmetic.        */
4877 /*                                                                           */
4878 /*  `epsilon' is the largest power of two such that 1.0 + epsilon = 1.0 in   */
4879 /*  floating-point arithmetic.  `epsilon' bounds the relative roundoff       */
4880 /*  error.  It is used for floating-point error analysis.                    */
4881 /*                                                                           */
4882 /*  `splitter' is used to split floating-point numbers into two half-        */
4883 /*  length significands for exact multiplication.                            */
4884 /*                                                                           */
4885 /*  I imagine that a highly optimizing compiler might be too smart for its   */
4886 /*  own good, and somehow cause this routine to fail, if it pretends that    */
4887 /*  floating-point arithmetic is too much like real arithmetic.              */
4888 /*                                                                           */
4889 /*  Don't change this routine unless you fully understand it.                */
4890 /*                                                                           */
4891 /*****************************************************************************/
4892 
exactinit()4893 void exactinit()
4894 {
4895   REAL half;
4896   REAL check, lastcheck;
4897   int every_other;
4898 #ifdef LINUX
4899   int cword;
4900 #endif /* LINUX */
4901 
4902 #ifdef CPU86
4903 #ifdef SINGLE
4904   _control87(_PC_24, _MCW_PC); /* Set FPU control word for single precision. */
4905 #else /* not SINGLE */
4906   _control87(_PC_53, _MCW_PC); /* Set FPU control word for double precision. */
4907 #endif /* not SINGLE */
4908 #endif /* CPU86 */
4909 #ifdef LINUX
4910 #ifdef SINGLE
4911   /*  cword = 4223; */
4912   cword = 4210;                 /* set FPU control word for single precision */
4913 #else /* not SINGLE */
4914   /*  cword = 4735; */
4915   cword = 4722;                 /* set FPU control word for double precision */
4916 #endif /* not SINGLE */
4917   _FPU_SETCW(cword);
4918 #endif /* LINUX */
4919 
4920   every_other = 1;
4921   half = 0.5;
4922   epsilon = 1.0;
4923   splitter = 1.0;
4924   check = 1.0;
4925   /* Repeatedly divide `epsilon' by two until it is too small to add to      */
4926   /*   one without causing roundoff.  (Also check if the sum is equal to     */
4927   /*   the previous sum, for machines that round up instead of using exact   */
4928   /*   rounding.  Not that these routines will work on such machines.)       */
4929   do {
4930     lastcheck = check;
4931     epsilon *= half;
4932     if (every_other) {
4933       splitter *= 2.0;
4934     }
4935     every_other = !every_other;
4936     check = 1.0 + epsilon;
4937   } while ((check != 1.0) && (check != lastcheck));
4938   splitter += 1.0;
4939   /* Error bounds for orientation and incircle tests. */
4940   resulterrbound = (3.0 + 8.0 * epsilon) * epsilon;
4941   ccwerrboundA = (3.0 + 16.0 * epsilon) * epsilon;
4942   ccwerrboundB = (2.0 + 12.0 * epsilon) * epsilon;
4943   ccwerrboundC = (9.0 + 64.0 * epsilon) * epsilon * epsilon;
4944   iccerrboundA = (10.0 + 96.0 * epsilon) * epsilon;
4945   iccerrboundB = (4.0 + 48.0 * epsilon) * epsilon;
4946   iccerrboundC = (44.0 + 576.0 * epsilon) * epsilon * epsilon;
4947   o3derrboundA = (7.0 + 56.0 * epsilon) * epsilon;
4948   o3derrboundB = (3.0 + 28.0 * epsilon) * epsilon;
4949   o3derrboundC = (26.0 + 288.0 * epsilon) * epsilon * epsilon;
4950 }
4951 
4952 /*****************************************************************************/
4953 /*                                                                           */
4954 /*  fast_expansion_sum_zeroelim()   Sum two expansions, eliminating zero     */
4955 /*                                  components from the output expansion.    */
4956 /*                                                                           */
4957 /*  Sets h = e + f.  See my Robust Predicates paper for details.             */
4958 /*                                                                           */
4959 /*  If round-to-even is used (as with IEEE 754), maintains the strongly      */
4960 /*  nonoverlapping property.  (That is, if e is strongly nonoverlapping, h   */
4961 /*  will be also.)  Does NOT maintain the nonoverlapping or nonadjacent      */
4962 /*  properties.                                                              */
4963 /*                                                                           */
4964 /*****************************************************************************/
4965 
4966 #ifdef ANSI_DECLARATORS
4967 static int fast_expansion_sum_zeroelim(int elen, REAL *e, int flen, REAL *f, REAL *h)
4968 #else /* not ANSI_DECLARATORS */
4969 int fast_expansion_sum_zeroelim(elen, e, flen, f, h)  /* h cannot be e or f. */
4970 int elen;
4971 REAL *e;
4972 int flen;
4973 REAL *f;
4974 REAL *h;
4975 #endif /* not ANSI_DECLARATORS */
4976 
4977 {
4978   REAL Q;
4979   INEXACT REAL Qnew;
4980   INEXACT REAL hh;
4981   INEXACT REAL bvirt;
4982   REAL avirt, bround, around;
4983   int eindex, findex, hindex;
4984   REAL enow, fnow;
4985 
4986   enow = e[0];
4987   fnow = f[0];
4988   eindex = findex = 0;
4989   if ( (fnow > enow) == (fnow > -enow) ) {
4990     Q = enow;
4991     enow = e[++eindex];
4992   } else {
4993     Q = fnow;
4994     fnow = f[++findex];
4995   }
4996   hindex = 0;
4997   if ((eindex < elen) && (findex < flen)) {
4998     if ((fnow > enow) == (fnow > -enow)) {
4999       Fast_Two_Sum(enow, Q, Qnew, hh);
5000       enow = e[++eindex];
5001     } else {
5002       Fast_Two_Sum(fnow, Q, Qnew, hh);
5003       fnow = f[++findex];
5004     }
5005     Q = Qnew;
5006     if (hh != 0.0) {
5007       h[hindex++] = hh;
5008     }
5009     while ((eindex < elen) && (findex < flen)) {
5010       if ((fnow > enow) == (fnow > -enow)) {
5011         Two_Sum(Q, enow, Qnew, hh);
5012         enow = e[++eindex];
5013       } else {
5014         Two_Sum(Q, fnow, Qnew, hh);
5015         fnow = f[++findex];
5016       }
5017       Q = Qnew;
5018       if (hh != 0.0) {
5019         h[hindex++] = hh;
5020       }
5021     }
5022   }
5023   while (eindex < elen) {
5024     Two_Sum(Q, enow, Qnew, hh);
5025     enow = e[++eindex];
5026     Q = Qnew;
5027     if (hh != 0.0) {
5028       h[hindex++] = hh;
5029     }
5030   }
5031   while (findex < flen) {
5032     Two_Sum(Q, fnow, Qnew, hh);
5033     fnow = f[++findex];
5034     Q = Qnew;
5035     if (hh != 0.0) {
5036       h[hindex++] = hh;
5037     }
5038   }
5039   if ((Q != 0.0) || (hindex == 0)) {
5040     h[hindex++] = Q;
5041   }
5042   return hindex;
5043 }
5044 
5045 /*****************************************************************************/
5046 /*                                                                           */
5047 /*  scale_expansion_zeroelim()   Multiply an expansion by a scalar,          */
5048 /*                               eliminating zero components from the        */
5049 /*                               output expansion.                           */
5050 /*                                                                           */
5051 /*  Sets h = be.  See my Robust Predicates paper for details.                */
5052 /*                                                                           */
5053 /*  Maintains the nonoverlapping property.  If round-to-even is used (as     */
5054 /*  with IEEE 754), maintains the strongly nonoverlapping and nonadjacent    */
5055 /*  properties as well.  (That is, if e has one of these properties, so      */
5056 /*  will h.)                                                                 */
5057 /*                                                                           */
5058 /*****************************************************************************/
5059 
5060 #ifdef ANSI_DECLARATORS
5061 int scale_expansion_zeroelim(int elen, REAL *e, REAL b, REAL *h)
5062 #else /* not ANSI_DECLARATORS */
5063 int scale_expansion_zeroelim(elen, e, b, h)   /* e and h cannot be the same. */
5064 int elen;
5065 REAL *e;
5066 REAL b;
5067 REAL *h;
5068 #endif /* not ANSI_DECLARATORS */
5069 
5070 {
5071   INEXACT REAL Q, sum;
5072   REAL hh;
5073   INEXACT REAL product1;
5074   REAL product0;
5075   int eindex, hindex;
5076   REAL enow;
5077   INEXACT REAL bvirt;
5078   REAL avirt, bround, around;
5079   INEXACT REAL c;
5080   INEXACT REAL abig;
5081   REAL ahi, alo, bhi, blo;
5082   REAL err1, err2, err3;
5083 
5084   Split(b, bhi, blo);
5085   Two_Product_Presplit(e[0], b, bhi, blo, Q, hh);
5086   hindex = 0;
5087   if (hh != 0) {
5088     h[hindex++] = hh;
5089   }
5090   for (eindex = 1; eindex < elen; eindex++) {
5091     enow = e[eindex];
5092     Two_Product_Presplit(enow, b, bhi, blo, product1, product0);
5093     Two_Sum(Q, product0, sum, hh);
5094     if (hh != 0) {
5095       h[hindex++] = hh;
5096     }
5097     Fast_Two_Sum(product1, sum, Q, hh);
5098     if (hh != 0) {
5099       h[hindex++] = hh;
5100     }
5101   }
5102   if ((Q != 0.0) || (hindex == 0)) {
5103     h[hindex++] = Q;
5104   }
5105   return hindex;
5106 }
5107 
5108 /*****************************************************************************/
5109 /*                                                                           */
5110 /*  estimate()   Produce a one-word estimate of an expansion's value.        */
5111 /*                                                                           */
5112 /*  See my Robust Predicates paper for details.                              */
5113 /*                                                                           */
5114 /*****************************************************************************/
5115 
5116 #ifdef ANSI_DECLARATORS
5117 REAL estimate(int elen, REAL *e)
5118 #else /* not ANSI_DECLARATORS */
5119 REAL estimate(elen, e)
5120 int elen;
5121 REAL *e;
5122 #endif /* not ANSI_DECLARATORS */
5123 
5124 {
5125   REAL Q;
5126   int eindex;
5127 
5128   Q = e[0];
5129   for (eindex = 1; eindex < elen; eindex++) {
5130     Q += e[eindex];
5131   }
5132   return Q;
5133 }
5134 
5135 /*****************************************************************************/
5136 /*                                                                           */
5137 /*  counterclockwise()   Return a positive value if the points pa, pb, and   */
5138 /*                       pc occur in counterclockwise order; a negative      */
5139 /*                       value if they occur in clockwise order; and zero    */
5140 /*                       if they are collinear.  The result is also a rough  */
5141 /*                       approximation of twice the signed area of the       */
5142 /*                       triangle defined by the three points.               */
5143 /*                                                                           */
5144 /*  Uses exact arithmetic if necessary to ensure a correct answer.  The      */
5145 /*  result returned is the determinant of a matrix.  This determinant is     */
5146 /*  computed adaptively, in the sense that exact arithmetic is used only to  */
5147 /*  the degree it is needed to ensure that the returned value has the        */
5148 /*  correct sign.  Hence, this function is usually quite fast, but will run  */
5149 /*  more slowly when the input points are collinear or nearly so.            */
5150 /*                                                                           */
5151 /*  See my Robust Predicates paper for details.                              */
5152 /*                                                                           */
5153 /*****************************************************************************/
5154 
5155 #ifdef ANSI_DECLARATORS
5156 REAL counterclockwiseadapt(vertex pa, vertex pb, vertex pc, REAL detsum)
5157 #else /* not ANSI_DECLARATORS */
5158 REAL counterclockwiseadapt(pa, pb, pc, detsum)
5159 vertex pa;
5160 vertex pb;
5161 vertex pc;
5162 REAL detsum;
5163 #endif /* not ANSI_DECLARATORS */
5164 
5165 {
5166   INEXACT REAL acx, acy, bcx, bcy;
5167   REAL acxtail, acytail, bcxtail, bcytail;
5168   INEXACT REAL detleft, detright;
5169   REAL detlefttail, detrighttail;
5170   REAL det, errbound;
5171   REAL B[4] = {0.}, C1[8] = {0.}, C2[12] = {0.}, D[16] = {0.};
5172   INEXACT REAL B3;
5173   int C1length, C2length, Dlength;
5174   REAL u[4] = {0.};
5175   INEXACT REAL u3;
5176   INEXACT REAL s1, t1;
5177   REAL s0, t0;
5178 
5179   INEXACT REAL bvirt;
5180   REAL avirt, bround, around;
5181   INEXACT REAL c;
5182   INEXACT REAL abig;
5183   REAL ahi, alo, bhi, blo;
5184   REAL err1, err2, err3;
5185   INEXACT REAL _i, _j;
5186   REAL _0;
5187 
5188   acx = (REAL) (pa[0] - pc[0]);
5189   bcx = (REAL) (pb[0] - pc[0]);
5190   acy = (REAL) (pa[1] - pc[1]);
5191   bcy = (REAL) (pb[1] - pc[1]);
5192 
5193   Two_Product(acx, bcy, detleft, detlefttail);
5194   Two_Product(acy, bcx, detright, detrighttail);
5195 
5196   Two_Two_Diff(detleft, detlefttail, detright, detrighttail,
5197                B3, B[2], B[1], B[0]);
5198   B[3] = B3;
5199 
5200   det = estimate(4, B);
5201   errbound = ccwerrboundB * detsum;
5202   if ((det >= errbound) || (-det >= errbound)) {
5203     return det;
5204   }
5205 
5206   Two_Diff_Tail(pa[0], pc[0], acx, acxtail);
5207   Two_Diff_Tail(pb[0], pc[0], bcx, bcxtail);
5208   Two_Diff_Tail(pa[1], pc[1], acy, acytail);
5209   Two_Diff_Tail(pb[1], pc[1], bcy, bcytail);
5210 
5211   if ((acxtail == 0.0) && (acytail == 0.0)
5212       && (bcxtail == 0.0) && (bcytail == 0.0)) {
5213     return det;
5214   }
5215 
5216   errbound = ccwerrboundC * detsum + resulterrbound * Absolute(det);
5217   det += (acx * bcytail + bcy * acxtail)
5218        - (acy * bcxtail + bcx * acytail);
5219   if ((det >= errbound) || (-det >= errbound)) {
5220     return det;
5221   }
5222 
5223   Two_Product(acxtail, bcy, s1, s0);
5224   Two_Product(acytail, bcx, t1, t0);
5225   Two_Two_Diff(s1, s0, t1, t0, u3, u[2], u[1], u[0]);
5226   u[3] = u3;
5227   C1length = fast_expansion_sum_zeroelim(4, B, 4, u, C1);
5228 
5229   Two_Product(acx, bcytail, s1, s0);
5230   Two_Product(acy, bcxtail, t1, t0);
5231   Two_Two_Diff(s1, s0, t1, t0, u3, u[2], u[1], u[0]);
5232   u[3] = u3;
5233   C2length = fast_expansion_sum_zeroelim(C1length, C1, 4, u, C2);
5234 
5235   Two_Product(acxtail, bcytail, s1, s0);
5236   Two_Product(acytail, bcxtail, t1, t0);
5237   Two_Two_Diff(s1, s0, t1, t0, u3, u[2], u[1], u[0]);
5238   u[3] = u3;
5239   Dlength = fast_expansion_sum_zeroelim(C2length, C2, 4, u, D);
5240 
5241   return(D[Dlength - 1]);
5242 }
5243 
5244 #ifdef ANSI_DECLARATORS
5245 REAL counterclockwise(struct mesh *m, struct behavior *b,
5246                       vertex pa, vertex pb, vertex pc)
5247 #else /* not ANSI_DECLARATORS */
5248 REAL counterclockwise(m, b, pa, pb, pc)
5249 struct mesh *m;
5250 struct behavior *b;
5251 vertex pa;
5252 vertex pb;
5253 vertex pc;
5254 #endif /* not ANSI_DECLARATORS */
5255 
5256 {
5257   REAL detleft, detright, det;
5258   REAL detsum, errbound;
5259 
5260   m->counterclockcount++;
5261 
5262   detleft = (pa[0] - pc[0]) * (pb[1] - pc[1]);
5263   detright = (pa[1] - pc[1]) * (pb[0] - pc[0]);
5264   det = detleft - detright;
5265 
5266   if (b->noexact) {
5267     return det;
5268   }
5269 
5270   if (detleft > 0.0) {
5271     if (detright <= 0.0) {
5272       return det;
5273     } else {
5274       detsum = detleft + detright;
5275     }
5276   } else if (detleft < 0.0) {
5277     if (detright >= 0.0) {
5278       return det;
5279     } else {
5280       detsum = -detleft - detright;
5281     }
5282   } else {
5283     return det;
5284   }
5285 
5286   errbound = ccwerrboundA * detsum;
5287   if ((det >= errbound) || (-det >= errbound)) {
5288     return det;
5289   }
5290 
5291   return counterclockwiseadapt(pa, pb, pc, detsum);
5292 }
5293 
5294 /*****************************************************************************/
5295 /*                                                                           */
5296 /*  incircle()   Return a positive value if the point pd lies inside the     */
5297 /*               circle passing through pa, pb, and pc; a negative value if  */
5298 /*               it lies outside; and zero if the four points are cocircular.*/
5299 /*               The points pa, pb, and pc must be in counterclockwise       */
5300 /*               order, or the sign of the result will be reversed.          */
5301 /*                                                                           */
5302 /*  Uses exact arithmetic if necessary to ensure a correct answer.  The      */
5303 /*  result returned is the determinant of a matrix.  This determinant is     */
5304 /*  computed adaptively, in the sense that exact arithmetic is used only to  */
5305 /*  the degree it is needed to ensure that the returned value has the        */
5306 /*  correct sign.  Hence, this function is usually quite fast, but will run  */
5307 /*  more slowly when the input points are cocircular or nearly so.           */
5308 /*                                                                           */
5309 /*  See my Robust Predicates paper for details.                              */
5310 /*                                                                           */
5311 /*****************************************************************************/
5312 
5313 #ifdef ANSI_DECLARATORS
5314 REAL incircleadapt(vertex pa, vertex pb, vertex pc, vertex pd, REAL permanent)
5315 #else /* not ANSI_DECLARATORS */
5316 REAL incircleadapt(pa, pb, pc, pd, permanent)
5317 vertex pa;
5318 vertex pb;
5319 vertex pc;
5320 vertex pd;
5321 REAL permanent;
5322 #endif /* not ANSI_DECLARATORS */
5323 
5324 {
5325   INEXACT REAL adx, bdx, cdx, ady, bdy, cdy;
5326   REAL det, errbound;
5327 
5328   INEXACT REAL bdxcdy1, cdxbdy1, cdxady1, adxcdy1, adxbdy1, bdxady1;
5329   REAL bdxcdy0, cdxbdy0, cdxady0, adxcdy0, adxbdy0, bdxady0;
5330   REAL bc[4], ca[4], ab[4];
5331   INEXACT REAL bc3, ca3, ab3;
5332   REAL axbc[8], axxbc[16] ={0.}, aybc[8], ayybc[16] = {0.}, adet[32] = {0.};
5333   int axbclen, axxbclen, aybclen, ayybclen, alen;
5334   REAL bxca[8], bxxca[16] = {0.}, byca[8], byyca[16] = {0.}, bdet[32] = {0.};
5335   int bxcalen, bxxcalen, bycalen, byycalen, blen;
5336   REAL cxab[8], cxxab[16] = {0.}, cyab[8], cyyab[16] = {0.}, cdet[32] = {0.};
5337   int cxablen, cxxablen, cyablen, cyyablen, clen;
5338   REAL abdet[64] = {0,};
5339   int ablen;
5340   REAL fin1[1152] = {0.}, fin2[1152] = {0.};
5341   REAL *finnow, *finother, *finswap;
5342   int finlength;
5343 
5344   REAL adxtail, bdxtail, cdxtail, adytail, bdytail, cdytail;
5345   INEXACT REAL adxadx1, adyady1, bdxbdx1, bdybdy1, cdxcdx1, cdycdy1;
5346   REAL adxadx0, adyady0, bdxbdx0, bdybdy0, cdxcdx0, cdycdy0;
5347   REAL aa[4], bb[4], cc[4];
5348   INEXACT REAL aa3, bb3, cc3;
5349   INEXACT REAL ti1, tj1;
5350   REAL ti0, tj0;
5351   REAL u[4] = {0.}, v[4] = {0.};
5352   INEXACT REAL u3, v3;
5353   REAL temp8[8], temp16a[16] = {0.}, temp16b[16] = {0.}, temp16c[16] = {0.};
5354   REAL temp32a[32] = {0.}, temp32b[32] = {0.}, temp48[48] = {0.}, temp64[64] = {0.};
5355   int temp8len, temp16alen, temp16blen, temp16clen;
5356   int temp32alen, temp32blen, temp48len, temp64len;
5357   REAL axtbb[8], axtcc[8], aytbb[8], aytcc[8];
5358   int axtbblen, axtcclen, aytbblen, aytcclen;
5359   REAL bxtaa[8], bxtcc[8], bytaa[8], bytcc[8];
5360   int bxtaalen, bxtcclen, bytaalen, bytcclen;
5361   REAL cxtaa[8], cxtbb[8], cytaa[8], cytbb[8];
5362   int cxtaalen, cxtbblen, cytaalen, cytbblen;
5363   REAL axtbc[8], aytbc[8], bxtca[8], bytca[8], cxtab[8], cytab[8];
5364   int axtbclen = 8, aytbclen = 8, bxtcalen = 8, bytcalen = 8, cxtablen = 8, cytablen = 8;
5365   REAL axtbct[16], aytbct[16], bxtcat[16], bytcat[16], cxtabt[16], cytabt[16];
5366   int axtbctlen, aytbctlen, bxtcatlen, bytcatlen, cxtabtlen, cytabtlen;
5367   REAL axtbctt[8], aytbctt[8], bxtcatt[8];
5368   REAL bytcatt[8], cxtabtt[8], cytabtt[8];
5369   int axtbcttlen, aytbcttlen, bxtcattlen, bytcattlen, cxtabttlen, cytabttlen;
5370   REAL abt[8], bct[8], cat[8];
5371   int abtlen, bctlen, catlen;
5372   REAL abtt[4], bctt[4], catt[4];
5373   int abttlen, bcttlen, cattlen;
5374   INEXACT REAL abtt3, bctt3, catt3;
5375   REAL negate;
5376 
5377   INEXACT REAL bvirt;
5378   REAL avirt, bround, around;
5379   INEXACT REAL c;
5380   INEXACT REAL abig;
5381   REAL ahi, alo, bhi, blo;
5382   REAL err1, err2, err3;
5383   INEXACT REAL _i, _j;
5384   REAL _0;
5385 
5386   adx = (REAL) (pa[0] - pd[0]);
5387   bdx = (REAL) (pb[0] - pd[0]);
5388   cdx = (REAL) (pc[0] - pd[0]);
5389   ady = (REAL) (pa[1] - pd[1]);
5390   bdy = (REAL) (pb[1] - pd[1]);
5391   cdy = (REAL) (pc[1] - pd[1]);
5392 
5393   Two_Product(bdx, cdy, bdxcdy1, bdxcdy0);
5394   Two_Product(cdx, bdy, cdxbdy1, cdxbdy0);
5395   Two_Two_Diff(bdxcdy1, bdxcdy0, cdxbdy1, cdxbdy0, bc3, bc[2], bc[1], bc[0]);
5396   bc[3] = bc3;
5397   axbclen = scale_expansion_zeroelim(4, bc, adx, axbc);
5398   axxbclen = scale_expansion_zeroelim(axbclen, axbc, adx, axxbc);
5399   aybclen = scale_expansion_zeroelim(4, bc, ady, aybc);
5400   ayybclen = scale_expansion_zeroelim(aybclen, aybc, ady, ayybc);
5401   alen = fast_expansion_sum_zeroelim(axxbclen, axxbc, ayybclen, ayybc, adet);
5402 
5403   Two_Product(cdx, ady, cdxady1, cdxady0);
5404   Two_Product(adx, cdy, adxcdy1, adxcdy0);
5405   Two_Two_Diff(cdxady1, cdxady0, adxcdy1, adxcdy0, ca3, ca[2], ca[1], ca[0]);
5406   ca[3] = ca3;
5407   bxcalen = scale_expansion_zeroelim(4, ca, bdx, bxca);
5408   bxxcalen = scale_expansion_zeroelim(bxcalen, bxca, bdx, bxxca);
5409   bycalen = scale_expansion_zeroelim(4, ca, bdy, byca);
5410   byycalen = scale_expansion_zeroelim(bycalen, byca, bdy, byyca);
5411   blen = fast_expansion_sum_zeroelim(bxxcalen, bxxca, byycalen, byyca, bdet);
5412 
5413   Two_Product(adx, bdy, adxbdy1, adxbdy0);
5414   Two_Product(bdx, ady, bdxady1, bdxady0);
5415   Two_Two_Diff(adxbdy1, adxbdy0, bdxady1, bdxady0, ab3, ab[2], ab[1], ab[0]);
5416   ab[3] = ab3;
5417   cxablen = scale_expansion_zeroelim(4, ab, cdx, cxab);
5418   cxxablen = scale_expansion_zeroelim(cxablen, cxab, cdx, cxxab);
5419   cyablen = scale_expansion_zeroelim(4, ab, cdy, cyab);
5420   cyyablen = scale_expansion_zeroelim(cyablen, cyab, cdy, cyyab);
5421   clen = fast_expansion_sum_zeroelim(cxxablen, cxxab, cyyablen, cyyab, cdet);
5422 
5423   ablen = fast_expansion_sum_zeroelim(alen, adet, blen, bdet, abdet);
5424   finlength = fast_expansion_sum_zeroelim(ablen, abdet, clen, cdet, fin1);
5425 
5426   det = estimate(finlength, fin1);
5427   errbound = iccerrboundB * permanent;
5428   if ((det >= errbound) || (-det >= errbound)) {
5429     return det;
5430   }
5431 
5432   Two_Diff_Tail(pa[0], pd[0], adx, adxtail);
5433   Two_Diff_Tail(pa[1], pd[1], ady, adytail);
5434   Two_Diff_Tail(pb[0], pd[0], bdx, bdxtail);
5435   Two_Diff_Tail(pb[1], pd[1], bdy, bdytail);
5436   Two_Diff_Tail(pc[0], pd[0], cdx, cdxtail);
5437   Two_Diff_Tail(pc[1], pd[1], cdy, cdytail);
5438   if ((adxtail == 0.0) && (bdxtail == 0.0) && (cdxtail == 0.0)
5439       && (adytail == 0.0) && (bdytail == 0.0) && (cdytail == 0.0)) {
5440     return det;
5441   }
5442 
5443   errbound = iccerrboundC * permanent + resulterrbound * Absolute(det);
5444   det += ((adx * adx + ady * ady) * ((bdx * cdytail + cdy * bdxtail)
5445                                      - (bdy * cdxtail + cdx * bdytail))
5446           + 2.0 * (adx * adxtail + ady * adytail) * (bdx * cdy - bdy * cdx))
5447        + ((bdx * bdx + bdy * bdy) * ((cdx * adytail + ady * cdxtail)
5448                                      - (cdy * adxtail + adx * cdytail))
5449           + 2.0 * (bdx * bdxtail + bdy * bdytail) * (cdx * ady - cdy * adx))
5450        + ((cdx * cdx + cdy * cdy) * ((adx * bdytail + bdy * adxtail)
5451                                      - (ady * bdxtail + bdx * adytail))
5452           + 2.0 * (cdx * cdxtail + cdy * cdytail) * (adx * bdy - ady * bdx));
5453   if ((det >= errbound) || (-det >= errbound)) {
5454     return det;
5455   }
5456 
5457   finnow = fin1;
5458   finother = fin2;
5459 
5460   if ((bdxtail != 0.0) || (bdytail != 0.0)
5461       || (cdxtail != 0.0) || (cdytail != 0.0)) {
5462     Square(adx, adxadx1, adxadx0);
5463     Square(ady, adyady1, adyady0);
5464     Two_Two_Sum(adxadx1, adxadx0, adyady1, adyady0, aa3, aa[2], aa[1], aa[0]);
5465     aa[3] = aa3;
5466   }
5467   if ((cdxtail != 0.0) || (cdytail != 0.0)
5468       || (adxtail != 0.0) || (adytail != 0.0)) {
5469     Square(bdx, bdxbdx1, bdxbdx0);
5470     Square(bdy, bdybdy1, bdybdy0);
5471     Two_Two_Sum(bdxbdx1, bdxbdx0, bdybdy1, bdybdy0, bb3, bb[2], bb[1], bb[0]);
5472     bb[3] = bb3;
5473   }
5474   if ((adxtail != 0.0) || (adytail != 0.0)
5475       || (bdxtail != 0.0) || (bdytail != 0.0)) {
5476     Square(cdx, cdxcdx1, cdxcdx0);
5477     Square(cdy, cdycdy1, cdycdy0);
5478     Two_Two_Sum(cdxcdx1, cdxcdx0, cdycdy1, cdycdy0, cc3, cc[2], cc[1], cc[0]);
5479     cc[3] = cc3;
5480   }
5481 
5482   if (adxtail != 0.0) {
5483     axtbclen = scale_expansion_zeroelim(4, bc, adxtail, axtbc);
5484     temp16alen = scale_expansion_zeroelim(axtbclen, axtbc, 2.0 * adx,
5485                                           temp16a);
5486 
5487     axtcclen = scale_expansion_zeroelim(4, cc, adxtail, axtcc);
5488     temp16blen = scale_expansion_zeroelim(axtcclen, axtcc, bdy, temp16b);
5489 
5490     axtbblen = scale_expansion_zeroelim(4, bb, adxtail, axtbb);
5491     temp16clen = scale_expansion_zeroelim(axtbblen, axtbb, -cdy, temp16c);
5492 
5493     temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5494                                             temp16blen, temp16b, temp32a);
5495     temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
5496                                             temp32alen, temp32a, temp48);
5497     finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
5498                                             temp48, finother);
5499     finswap = finnow; finnow = finother; finother = finswap;
5500   }
5501   if (adytail != 0.0) {
5502     aytbclen = scale_expansion_zeroelim(4, bc, adytail, aytbc);
5503     temp16alen = scale_expansion_zeroelim(aytbclen, aytbc, 2.0 * ady,
5504                                           temp16a);
5505 
5506     aytbblen = scale_expansion_zeroelim(4, bb, adytail, aytbb);
5507     temp16blen = scale_expansion_zeroelim(aytbblen, aytbb, cdx, temp16b);
5508 
5509     aytcclen = scale_expansion_zeroelim(4, cc, adytail, aytcc);
5510     temp16clen = scale_expansion_zeroelim(aytcclen, aytcc, -bdx, temp16c);
5511 
5512     temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5513                                             temp16blen, temp16b, temp32a);
5514     temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
5515                                             temp32alen, temp32a, temp48);
5516     finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
5517                                             temp48, finother);
5518     finswap = finnow; finnow = finother; finother = finswap;
5519   }
5520   if (bdxtail != 0.0) {
5521     bxtcalen = scale_expansion_zeroelim(4, ca, bdxtail, bxtca);
5522     temp16alen = scale_expansion_zeroelim(bxtcalen, bxtca, 2.0 * bdx,
5523                                           temp16a);
5524 
5525     bxtaalen = scale_expansion_zeroelim(4, aa, bdxtail, bxtaa);
5526     temp16blen = scale_expansion_zeroelim(bxtaalen, bxtaa, cdy, temp16b);
5527 
5528     bxtcclen = scale_expansion_zeroelim(4, cc, bdxtail, bxtcc);
5529     temp16clen = scale_expansion_zeroelim(bxtcclen, bxtcc, -ady, temp16c);
5530 
5531     temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5532                                             temp16blen, temp16b, temp32a);
5533     temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
5534                                             temp32alen, temp32a, temp48);
5535     finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
5536                                             temp48, finother);
5537     finswap = finnow; finnow = finother; finother = finswap;
5538   }
5539   if (bdytail != 0.0) {
5540     bytcalen = scale_expansion_zeroelim(4, ca, bdytail, bytca);
5541     temp16alen = scale_expansion_zeroelim(bytcalen, bytca, 2.0 * bdy,
5542                                           temp16a);
5543 
5544     bytcclen = scale_expansion_zeroelim(4, cc, bdytail, bytcc);
5545     temp16blen = scale_expansion_zeroelim(bytcclen, bytcc, adx, temp16b);
5546 
5547     bytaalen = scale_expansion_zeroelim(4, aa, bdytail, bytaa);
5548     temp16clen = scale_expansion_zeroelim(bytaalen, bytaa, -cdx, temp16c);
5549 
5550     temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5551                                             temp16blen, temp16b, temp32a);
5552     temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
5553                                             temp32alen, temp32a, temp48);
5554     finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
5555                                             temp48, finother);
5556     finswap = finnow; finnow = finother; finother = finswap;
5557   }
5558   if (cdxtail != 0.0) {
5559     cxtablen = scale_expansion_zeroelim(4, ab, cdxtail, cxtab);
5560     temp16alen = scale_expansion_zeroelim(cxtablen, cxtab, 2.0 * cdx,
5561                                           temp16a);
5562 
5563     cxtbblen = scale_expansion_zeroelim(4, bb, cdxtail, cxtbb);
5564     temp16blen = scale_expansion_zeroelim(cxtbblen, cxtbb, ady, temp16b);
5565 
5566     cxtaalen = scale_expansion_zeroelim(4, aa, cdxtail, cxtaa);
5567     temp16clen = scale_expansion_zeroelim(cxtaalen, cxtaa, -bdy, temp16c);
5568 
5569     temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5570                                             temp16blen, temp16b, temp32a);
5571     temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
5572                                             temp32alen, temp32a, temp48);
5573     finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
5574                                             temp48, finother);
5575     finswap = finnow; finnow = finother; finother = finswap;
5576   }
5577   if (cdytail != 0.0) {
5578     cytablen = scale_expansion_zeroelim(4, ab, cdytail, cytab);
5579     temp16alen = scale_expansion_zeroelim(cytablen, cytab, 2.0 * cdy,
5580                                           temp16a);
5581 
5582     cytaalen = scale_expansion_zeroelim(4, aa, cdytail, cytaa);
5583     temp16blen = scale_expansion_zeroelim(cytaalen, cytaa, bdx, temp16b);
5584 
5585     cytbblen = scale_expansion_zeroelim(4, bb, cdytail, cytbb);
5586     temp16clen = scale_expansion_zeroelim(cytbblen, cytbb, -adx, temp16c);
5587 
5588     temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5589                                             temp16blen, temp16b, temp32a);
5590     temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
5591                                             temp32alen, temp32a, temp48);
5592     finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
5593                                             temp48, finother);
5594     finswap = finnow; finnow = finother; finother = finswap;
5595   }
5596 
5597   if ((adxtail != 0.0) || (adytail != 0.0)) {
5598     if ((bdxtail != 0.0) || (bdytail != 0.0)
5599         || (cdxtail != 0.0) || (cdytail != 0.0)) {
5600       Two_Product(bdxtail, cdy, ti1, ti0);
5601       Two_Product(bdx, cdytail, tj1, tj0);
5602       Two_Two_Sum(ti1, ti0, tj1, tj0, u3, u[2], u[1], u[0]);
5603       u[3] = u3;
5604       negate = -bdy;
5605       Two_Product(cdxtail, negate, ti1, ti0);
5606       negate = -bdytail;
5607       Two_Product(cdx, negate, tj1, tj0);
5608       Two_Two_Sum(ti1, ti0, tj1, tj0, v3, v[2], v[1], v[0]);
5609       v[3] = v3;
5610       bctlen = fast_expansion_sum_zeroelim(4, u, 4, v, bct);
5611 
5612       Two_Product(bdxtail, cdytail, ti1, ti0);
5613       Two_Product(cdxtail, bdytail, tj1, tj0);
5614       Two_Two_Diff(ti1, ti0, tj1, tj0, bctt3, bctt[2], bctt[1], bctt[0]);
5615       bctt[3] = bctt3;
5616       bcttlen = 4;
5617     } else {
5618       bct[0] = 0.0;
5619       bctlen = 1;
5620       bctt[0] = 0.0;
5621       bcttlen = 1;
5622     }
5623 
5624     if (adxtail != 0.0) {
5625       temp16alen = scale_expansion_zeroelim(axtbclen, axtbc, adxtail, temp16a);
5626       axtbctlen = scale_expansion_zeroelim(bctlen, bct, adxtail, axtbct);
5627       temp32alen = scale_expansion_zeroelim(axtbctlen, axtbct, 2.0 * adx,
5628                                             temp32a);
5629       temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5630                                               temp32alen, temp32a, temp48);
5631       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
5632                                               temp48, finother);
5633       finswap = finnow; finnow = finother; finother = finswap;
5634       if (bdytail != 0.0) {
5635         temp8len = scale_expansion_zeroelim(4, cc, adxtail, temp8);
5636         temp16alen = scale_expansion_zeroelim(temp8len, temp8, bdytail,
5637                                               temp16a);
5638         finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
5639                                                 temp16a, finother);
5640         finswap = finnow; finnow = finother; finother = finswap;
5641       }
5642       if (cdytail != 0.0) {
5643         temp8len = scale_expansion_zeroelim(4, bb, -adxtail, temp8);
5644         temp16alen = scale_expansion_zeroelim(temp8len, temp8, cdytail,
5645                                               temp16a);
5646         finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
5647                                                 temp16a, finother);
5648         finswap = finnow; finnow = finother; finother = finswap;
5649       }
5650 
5651       temp32alen = scale_expansion_zeroelim(axtbctlen, axtbct, adxtail,
5652                                             temp32a);
5653       axtbcttlen = scale_expansion_zeroelim(bcttlen, bctt, adxtail, axtbctt);
5654       temp16alen = scale_expansion_zeroelim(axtbcttlen, axtbctt, 2.0 * adx,
5655                                             temp16a);
5656       temp16blen = scale_expansion_zeroelim(axtbcttlen, axtbctt, adxtail,
5657                                             temp16b);
5658       temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5659                                               temp16blen, temp16b, temp32b);
5660       temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
5661                                               temp32blen, temp32b, temp64);
5662       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
5663                                               temp64, finother);
5664       finswap = finnow; finnow = finother; finother = finswap;
5665     }
5666     if (adytail != 0.0) {
5667       temp16alen = scale_expansion_zeroelim(aytbclen, aytbc, adytail, temp16a);
5668       aytbctlen = scale_expansion_zeroelim(bctlen, bct, adytail, aytbct);
5669       temp32alen = scale_expansion_zeroelim(aytbctlen, aytbct, 2.0 * ady,
5670                                             temp32a);
5671       temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5672                                               temp32alen, temp32a, temp48);
5673       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
5674                                               temp48, finother);
5675       finswap = finnow; finnow = finother; finother = finswap;
5676 
5677 
5678       temp32alen = scale_expansion_zeroelim(aytbctlen, aytbct, adytail,
5679                                             temp32a);
5680       aytbcttlen = scale_expansion_zeroelim(bcttlen, bctt, adytail, aytbctt);
5681       temp16alen = scale_expansion_zeroelim(aytbcttlen, aytbctt, 2.0 * ady,
5682                                             temp16a);
5683       temp16blen = scale_expansion_zeroelim(aytbcttlen, aytbctt, adytail,
5684                                             temp16b);
5685       temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5686                                               temp16blen, temp16b, temp32b);
5687       temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
5688                                               temp32blen, temp32b, temp64);
5689       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
5690                                               temp64, finother);
5691       finswap = finnow; finnow = finother; finother = finswap;
5692     }
5693   }
5694   if ((bdxtail != 0.0) || (bdytail != 0.0)) {
5695     if ((cdxtail != 0.0) || (cdytail != 0.0)
5696         || (adxtail != 0.0) || (adytail != 0.0)) {
5697       Two_Product(cdxtail, ady, ti1, ti0);
5698       Two_Product(cdx, adytail, tj1, tj0);
5699       Two_Two_Sum(ti1, ti0, tj1, tj0, u3, u[2], u[1], u[0]);
5700       u[3] = u3;
5701       negate = -cdy;
5702       Two_Product(adxtail, negate, ti1, ti0);
5703       negate = -cdytail;
5704       Two_Product(adx, negate, tj1, tj0);
5705       Two_Two_Sum(ti1, ti0, tj1, tj0, v3, v[2], v[1], v[0]);
5706       v[3] = v3;
5707       catlen = fast_expansion_sum_zeroelim(4, u, 4, v, cat);
5708 
5709       Two_Product(cdxtail, adytail, ti1, ti0);
5710       Two_Product(adxtail, cdytail, tj1, tj0);
5711       Two_Two_Diff(ti1, ti0, tj1, tj0, catt3, catt[2], catt[1], catt[0]);
5712       catt[3] = catt3;
5713       cattlen = 4;
5714     } else {
5715       cat[0] = 0.0;
5716       catlen = 1;
5717       catt[0] = 0.0;
5718       cattlen = 1;
5719     }
5720 
5721     if (bdxtail != 0.0) {
5722       temp16alen = scale_expansion_zeroelim(bxtcalen, bxtca, bdxtail, temp16a);
5723       bxtcatlen = scale_expansion_zeroelim(catlen, cat, bdxtail, bxtcat);
5724       temp32alen = scale_expansion_zeroelim(bxtcatlen, bxtcat, 2.0 * bdx,
5725                                             temp32a);
5726       temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5727                                               temp32alen, temp32a, temp48);
5728       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
5729                                               temp48, finother);
5730       finswap = finnow; finnow = finother; finother = finswap;
5731       if (cdytail != 0.0) {
5732         temp8len = scale_expansion_zeroelim(4, aa, bdxtail, temp8);
5733         temp16alen = scale_expansion_zeroelim(temp8len, temp8, cdytail,
5734                                               temp16a);
5735         finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
5736                                                 temp16a, finother);
5737         finswap = finnow; finnow = finother; finother = finswap;
5738       }
5739       if (adytail != 0.0) {
5740         temp8len = scale_expansion_zeroelim(4, cc, -bdxtail, temp8);
5741         temp16alen = scale_expansion_zeroelim(temp8len, temp8, adytail,
5742                                               temp16a);
5743         finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
5744                                                 temp16a, finother);
5745         finswap = finnow; finnow = finother; finother = finswap;
5746       }
5747 
5748       temp32alen = scale_expansion_zeroelim(bxtcatlen, bxtcat, bdxtail,
5749                                             temp32a);
5750       bxtcattlen = scale_expansion_zeroelim(cattlen, catt, bdxtail, bxtcatt);
5751       temp16alen = scale_expansion_zeroelim(bxtcattlen, bxtcatt, 2.0 * bdx,
5752                                             temp16a);
5753       temp16blen = scale_expansion_zeroelim(bxtcattlen, bxtcatt, bdxtail,
5754                                             temp16b);
5755       temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5756                                               temp16blen, temp16b, temp32b);
5757       temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
5758                                               temp32blen, temp32b, temp64);
5759       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
5760                                               temp64, finother);
5761       finswap = finnow; finnow = finother; finother = finswap;
5762     }
5763     if (bdytail != 0.0) {
5764       temp16alen = scale_expansion_zeroelim(bytcalen, bytca, bdytail, temp16a);
5765       bytcatlen = scale_expansion_zeroelim(catlen, cat, bdytail, bytcat);
5766       temp32alen = scale_expansion_zeroelim(bytcatlen, bytcat, 2.0 * bdy,
5767                                             temp32a);
5768       temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5769                                               temp32alen, temp32a, temp48);
5770       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
5771                                               temp48, finother);
5772       finswap = finnow; finnow = finother; finother = finswap;
5773 
5774 
5775       temp32alen = scale_expansion_zeroelim(bytcatlen, bytcat, bdytail,
5776                                             temp32a);
5777       bytcattlen = scale_expansion_zeroelim(cattlen, catt, bdytail, bytcatt);
5778       temp16alen = scale_expansion_zeroelim(bytcattlen, bytcatt, 2.0 * bdy,
5779                                             temp16a);
5780       temp16blen = scale_expansion_zeroelim(bytcattlen, bytcatt, bdytail,
5781                                             temp16b);
5782       temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5783                                               temp16blen, temp16b, temp32b);
5784       temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
5785                                               temp32blen, temp32b, temp64);
5786       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
5787                                               temp64, finother);
5788       finswap = finnow; finnow = finother; finother = finswap;
5789     }
5790   }
5791   if ((cdxtail != 0.0) || (cdytail != 0.0)) {
5792     if ((adxtail != 0.0) || (adytail != 0.0)
5793         || (bdxtail != 0.0) || (bdytail != 0.0)) {
5794       Two_Product(adxtail, bdy, ti1, ti0);
5795       Two_Product(adx, bdytail, tj1, tj0);
5796       Two_Two_Sum(ti1, ti0, tj1, tj0, u3, u[2], u[1], u[0]);
5797       u[3] = u3;
5798       negate = -ady;
5799       Two_Product(bdxtail, negate, ti1, ti0);
5800       negate = -adytail;
5801       Two_Product(bdx, negate, tj1, tj0);
5802       Two_Two_Sum(ti1, ti0, tj1, tj0, v3, v[2], v[1], v[0]);
5803       v[3] = v3;
5804       abtlen = fast_expansion_sum_zeroelim(4, u, 4, v, abt);
5805 
5806       Two_Product(adxtail, bdytail, ti1, ti0);
5807       Two_Product(bdxtail, adytail, tj1, tj0);
5808       Two_Two_Diff(ti1, ti0, tj1, tj0, abtt3, abtt[2], abtt[1], abtt[0]);
5809       abtt[3] = abtt3;
5810       abttlen = 4;
5811     } else {
5812       abt[0] = 0.0;
5813       abtlen = 1;
5814       abtt[0] = 0.0;
5815       abttlen = 1;
5816     }
5817 
5818     if (cdxtail != 0.0) {
5819       temp16alen = scale_expansion_zeroelim(cxtablen, cxtab, cdxtail, temp16a);
5820       cxtabtlen = scale_expansion_zeroelim(abtlen, abt, cdxtail, cxtabt);
5821       temp32alen = scale_expansion_zeroelim(cxtabtlen, cxtabt, 2.0 * cdx,
5822                                             temp32a);
5823       temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5824                                               temp32alen, temp32a, temp48);
5825       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
5826                                               temp48, finother);
5827       finswap = finnow; finnow = finother; finother = finswap;
5828       if (adytail != 0.0) {
5829         temp8len = scale_expansion_zeroelim(4, bb, cdxtail, temp8);
5830         temp16alen = scale_expansion_zeroelim(temp8len, temp8, adytail,
5831                                               temp16a);
5832         finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
5833                                                 temp16a, finother);
5834         finswap = finnow; finnow = finother; finother = finswap;
5835       }
5836       if (bdytail != 0.0) {
5837         temp8len = scale_expansion_zeroelim(4, aa, -cdxtail, temp8);
5838         temp16alen = scale_expansion_zeroelim(temp8len, temp8, bdytail,
5839                                               temp16a);
5840         finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
5841                                                 temp16a, finother);
5842         finswap = finnow; finnow = finother; finother = finswap;
5843       }
5844 
5845       temp32alen = scale_expansion_zeroelim(cxtabtlen, cxtabt, cdxtail,
5846                                             temp32a);
5847       cxtabttlen = scale_expansion_zeroelim(abttlen, abtt, cdxtail, cxtabtt);
5848       temp16alen = scale_expansion_zeroelim(cxtabttlen, cxtabtt, 2.0 * cdx,
5849                                             temp16a);
5850       temp16blen = scale_expansion_zeroelim(cxtabttlen, cxtabtt, cdxtail,
5851                                             temp16b);
5852       temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5853                                               temp16blen, temp16b, temp32b);
5854       temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
5855                                               temp32blen, temp32b, temp64);
5856       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
5857                                               temp64, finother);
5858       finswap = finnow; finnow = finother; finother = finswap;
5859     }
5860     if (cdytail != 0.0) {
5861       temp16alen = scale_expansion_zeroelim(cytablen, cytab, cdytail, temp16a);
5862       cytabtlen = scale_expansion_zeroelim(abtlen, abt, cdytail, cytabt);
5863       temp32alen = scale_expansion_zeroelim(cytabtlen, cytabt, 2.0 * cdy,
5864                                             temp32a);
5865       temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5866                                               temp32alen, temp32a, temp48);
5867       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
5868                                               temp48, finother);
5869       finswap = finnow; finnow = finother; finother = finswap;
5870 
5871 
5872       temp32alen = scale_expansion_zeroelim(cytabtlen, cytabt, cdytail,
5873                                             temp32a);
5874       cytabttlen = scale_expansion_zeroelim(abttlen, abtt, cdytail, cytabtt);
5875       temp16alen = scale_expansion_zeroelim(cytabttlen, cytabtt, 2.0 * cdy,
5876                                             temp16a);
5877       temp16blen = scale_expansion_zeroelim(cytabttlen, cytabtt, cdytail,
5878                                             temp16b);
5879       temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5880                                               temp16blen, temp16b, temp32b);
5881       temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
5882                                               temp32blen, temp32b, temp64);
5883       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
5884                                               temp64, finother);
5885       finnow = finother;
5886     }
5887   }
5888 
5889   return finnow[finlength - 1];
5890 }
5891 
5892 #ifdef ANSI_DECLARATORS
5893 REAL incircle(struct mesh *m, struct behavior *b,
5894               vertex pa, vertex pb, vertex pc, vertex pd)
5895 #else /* not ANSI_DECLARATORS */
5896 REAL incircle(m, b, pa, pb, pc, pd)
5897 struct mesh *m;
5898 struct behavior *b;
5899 vertex pa;
5900 vertex pb;
5901 vertex pc;
5902 vertex pd;
5903 #endif /* not ANSI_DECLARATORS */
5904 
5905 {
5906   REAL adx, bdx, cdx, ady, bdy, cdy;
5907   REAL bdxcdy, cdxbdy, cdxady, adxcdy, adxbdy, bdxady;
5908   REAL alift, blift, clift;
5909   REAL det;
5910   REAL permanent, errbound;
5911 
5912   m->incirclecount++;
5913 
5914   adx = pa[0] - pd[0];
5915   bdx = pb[0] - pd[0];
5916   cdx = pc[0] - pd[0];
5917   ady = pa[1] - pd[1];
5918   bdy = pb[1] - pd[1];
5919   cdy = pc[1] - pd[1];
5920 
5921   bdxcdy = bdx * cdy;
5922   cdxbdy = cdx * bdy;
5923   alift = adx * adx + ady * ady;
5924 
5925   cdxady = cdx * ady;
5926   adxcdy = adx * cdy;
5927   blift = bdx * bdx + bdy * bdy;
5928 
5929   adxbdy = adx * bdy;
5930   bdxady = bdx * ady;
5931   clift = cdx * cdx + cdy * cdy;
5932 
5933   det = alift * (bdxcdy - cdxbdy)
5934       + blift * (cdxady - adxcdy)
5935       + clift * (adxbdy - bdxady);
5936 
5937   if (b->noexact) {
5938     return det;
5939   }
5940 
5941   permanent = (Absolute(bdxcdy) + Absolute(cdxbdy)) * alift
5942             + (Absolute(cdxady) + Absolute(adxcdy)) * blift
5943             + (Absolute(adxbdy) + Absolute(bdxady)) * clift;
5944   errbound = iccerrboundA * permanent;
5945   if ((det > errbound) || (-det > errbound)) {
5946     return det;
5947   }
5948 
5949   return incircleadapt(pa, pb, pc, pd, permanent);
5950 }
5951 
5952 /*****************************************************************************/
5953 /*                                                                           */
5954 /*  orient3d()   Return a positive value if the point pd lies below the      */
5955 /*               plane passing through pa, pb, and pc; "below" is defined so */
5956 /*               that pa, pb, and pc appear in counterclockwise order when   */
5957 /*               viewed from above the plane.  Returns a negative value if   */
5958 /*               pd lies above the plane.  Returns zero if the points are    */
5959 /*               coplanar.  The result is also a rough approximation of six  */
5960 /*               times the signed volume of the tetrahedron defined by the   */
5961 /*               four points.                                                */
5962 /*                                                                           */
5963 /*  Uses exact arithmetic if necessary to ensure a correct answer.  The      */
5964 /*  result returned is the determinant of a matrix.  This determinant is     */
5965 /*  computed adaptively, in the sense that exact arithmetic is used only to  */
5966 /*  the degree it is needed to ensure that the returned value has the        */
5967 /*  correct sign.  Hence, this function is usually quite fast, but will run  */
5968 /*  more slowly when the input points are coplanar or nearly so.             */
5969 /*                                                                           */
5970 /*  See my Robust Predicates paper for details.                              */
5971 /*                                                                           */
5972 /*****************************************************************************/
5973 
5974 #ifdef ANSI_DECLARATORS
5975 REAL orient3dadapt(vertex pa, vertex pb, vertex pc, vertex pd,
5976                    REAL aheight, REAL bheight, REAL cheight, REAL dheight,
5977                    REAL permanent)
5978 #else /* not ANSI_DECLARATORS */
5979 REAL orient3dadapt(pa, pb, pc, pd,
5980                    aheight, bheight, cheight, dheight, permanent)
5981 vertex pa;
5982 vertex pb;
5983 vertex pc;
5984 vertex pd;
5985 REAL aheight;
5986 REAL bheight;
5987 REAL cheight;
5988 REAL dheight;
5989 REAL permanent;
5990 #endif /* not ANSI_DECLARATORS */
5991 
5992 {
5993   INEXACT REAL adx, bdx, cdx, ady, bdy, cdy, adheight, bdheight, cdheight;
5994   REAL det, errbound;
5995 
5996   INEXACT REAL bdxcdy1, cdxbdy1, cdxady1, adxcdy1, adxbdy1, bdxady1;
5997   REAL bdxcdy0, cdxbdy0, cdxady0, adxcdy0, adxbdy0, bdxady0;
5998   REAL bc[4], ca[4], ab[4];
5999   INEXACT REAL bc3, ca3, ab3;
6000   REAL adet[8]={0.}, bdet[8]={0.}, cdet[8]={0.};
6001   int alen, blen, clen;
6002   REAL abdet[16]={0.};
6003   int ablen;
6004   REAL *finnow, *finother, *finswap;
6005   REAL fin1[192], fin2[192];
6006   int finlength;
6007 
6008   REAL adxtail, bdxtail, cdxtail;
6009   REAL adytail, bdytail, cdytail;
6010   REAL adheighttail, bdheighttail, cdheighttail;
6011   INEXACT REAL at_blarge, at_clarge;
6012   INEXACT REAL bt_clarge, bt_alarge;
6013   INEXACT REAL ct_alarge, ct_blarge;
6014   REAL at_b[4]={0.}, at_c[4]={0.}, bt_c[4]={0.}, bt_a[4]={0.}, ct_a[4]={0.}, ct_b[4]={0.};
6015   int at_blen, at_clen, bt_clen, bt_alen, ct_alen, ct_blen;
6016   INEXACT REAL bdxt_cdy1, cdxt_bdy1, cdxt_ady1;
6017   INEXACT REAL adxt_cdy1, adxt_bdy1, bdxt_ady1;
6018   REAL bdxt_cdy0, cdxt_bdy0, cdxt_ady0;
6019   REAL adxt_cdy0, adxt_bdy0, bdxt_ady0;
6020   INEXACT REAL bdyt_cdx1, cdyt_bdx1, cdyt_adx1;
6021   INEXACT REAL adyt_cdx1, adyt_bdx1, bdyt_adx1;
6022   REAL bdyt_cdx0, cdyt_bdx0, cdyt_adx0;
6023   REAL adyt_cdx0, adyt_bdx0, bdyt_adx0;
6024   REAL bct[8], cat[8], abt[8];
6025   int bctlen, catlen, abtlen;
6026   INEXACT REAL bdxt_cdyt1, cdxt_bdyt1, cdxt_adyt1;
6027   INEXACT REAL adxt_cdyt1, adxt_bdyt1, bdxt_adyt1;
6028   REAL bdxt_cdyt0, cdxt_bdyt0, cdxt_adyt0;
6029   REAL adxt_cdyt0, adxt_bdyt0, bdxt_adyt0;
6030   REAL u[4]={0.}, v[12]={0.}, w[16]={0.};
6031   INEXACT REAL u3;
6032   int vlength, wlength;
6033   REAL negate;
6034 
6035   INEXACT REAL bvirt;
6036   REAL avirt, bround, around;
6037   INEXACT REAL c;
6038   INEXACT REAL abig;
6039   REAL ahi, alo, bhi, blo;
6040   REAL err1, err2, err3;
6041   INEXACT REAL _i, _j, _k;
6042   REAL _0;
6043 
6044   adx = (REAL) (pa[0] - pd[0]);
6045   bdx = (REAL) (pb[0] - pd[0]);
6046   cdx = (REAL) (pc[0] - pd[0]);
6047   ady = (REAL) (pa[1] - pd[1]);
6048   bdy = (REAL) (pb[1] - pd[1]);
6049   cdy = (REAL) (pc[1] - pd[1]);
6050   adheight = (REAL) (aheight - dheight);
6051   bdheight = (REAL) (bheight - dheight);
6052   cdheight = (REAL) (cheight - dheight);
6053 
6054   Two_Product(bdx, cdy, bdxcdy1, bdxcdy0);
6055   Two_Product(cdx, bdy, cdxbdy1, cdxbdy0);
6056   Two_Two_Diff(bdxcdy1, bdxcdy0, cdxbdy1, cdxbdy0, bc3, bc[2], bc[1], bc[0]);
6057   bc[3] = bc3;
6058   alen = scale_expansion_zeroelim(4, bc, adheight, adet);
6059 
6060   Two_Product(cdx, ady, cdxady1, cdxady0);
6061   Two_Product(adx, cdy, adxcdy1, adxcdy0);
6062   Two_Two_Diff(cdxady1, cdxady0, adxcdy1, adxcdy0, ca3, ca[2], ca[1], ca[0]);
6063   ca[3] = ca3;
6064   blen = scale_expansion_zeroelim(4, ca, bdheight, bdet);
6065 
6066   Two_Product(adx, bdy, adxbdy1, adxbdy0);
6067   Two_Product(bdx, ady, bdxady1, bdxady0);
6068   Two_Two_Diff(adxbdy1, adxbdy0, bdxady1, bdxady0, ab3, ab[2], ab[1], ab[0]);
6069   ab[3] = ab3;
6070   clen = scale_expansion_zeroelim(4, ab, cdheight, cdet);
6071 
6072   ablen = fast_expansion_sum_zeroelim(alen, adet, blen, bdet, abdet);
6073   finlength = fast_expansion_sum_zeroelim(ablen, abdet, clen, cdet, fin1);
6074 
6075   det = estimate(finlength, fin1);
6076   errbound = o3derrboundB * permanent;
6077   if ((det >= errbound) || (-det >= errbound)) {
6078     return det;
6079   }
6080 
6081   Two_Diff_Tail(pa[0], pd[0], adx, adxtail);
6082   Two_Diff_Tail(pb[0], pd[0], bdx, bdxtail);
6083   Two_Diff_Tail(pc[0], pd[0], cdx, cdxtail);
6084   Two_Diff_Tail(pa[1], pd[1], ady, adytail);
6085   Two_Diff_Tail(pb[1], pd[1], bdy, bdytail);
6086   Two_Diff_Tail(pc[1], pd[1], cdy, cdytail);
6087   Two_Diff_Tail(aheight, dheight, adheight, adheighttail);
6088   Two_Diff_Tail(bheight, dheight, bdheight, bdheighttail);
6089   Two_Diff_Tail(cheight, dheight, cdheight, cdheighttail);
6090 
6091   if ((adxtail == 0.0) && (bdxtail == 0.0) && (cdxtail == 0.0) &&
6092       (adytail == 0.0) && (bdytail == 0.0) && (cdytail == 0.0) &&
6093       (adheighttail == 0.0) &&
6094       (bdheighttail == 0.0) &&
6095       (cdheighttail == 0.0)) {
6096     return det;
6097   }
6098 
6099   errbound = o3derrboundC * permanent + resulterrbound * Absolute(det);
6100   det += (adheight * ((bdx * cdytail + cdy * bdxtail) -
6101                       (bdy * cdxtail + cdx * bdytail)) +
6102           adheighttail * (bdx * cdy - bdy * cdx)) +
6103          (bdheight * ((cdx * adytail + ady * cdxtail) -
6104                       (cdy * adxtail + adx * cdytail)) +
6105           bdheighttail * (cdx * ady - cdy * adx)) +
6106          (cdheight * ((adx * bdytail + bdy * adxtail) -
6107                       (ady * bdxtail + bdx * adytail)) +
6108           cdheighttail * (adx * bdy - ady * bdx));
6109   if ((det >= errbound) || (-det >= errbound)) {
6110     return det;
6111   }
6112 
6113   finnow = fin1;
6114   finother = fin2;
6115 
6116   if (adxtail == 0.0) {
6117     if (adytail == 0.0) {
6118       at_b[0] = 0.0;
6119       at_blen = 1;
6120       at_c[0] = 0.0;
6121       at_clen = 1;
6122     } else {
6123       negate = -adytail;
6124       Two_Product(negate, bdx, at_blarge, at_b[0]);
6125       at_b[1] = at_blarge;
6126       at_blen = 2;
6127       Two_Product(adytail, cdx, at_clarge, at_c[0]);
6128       at_c[1] = at_clarge;
6129       at_clen = 2;
6130     }
6131   } else {
6132     if (adytail == 0.0) {
6133       Two_Product(adxtail, bdy, at_blarge, at_b[0]);
6134       at_b[1] = at_blarge;
6135       at_blen = 2;
6136       negate = -adxtail;
6137       Two_Product(negate, cdy, at_clarge, at_c[0]);
6138       at_c[1] = at_clarge;
6139       at_clen = 2;
6140     } else {
6141       Two_Product(adxtail, bdy, adxt_bdy1, adxt_bdy0);
6142       Two_Product(adytail, bdx, adyt_bdx1, adyt_bdx0);
6143       Two_Two_Diff(adxt_bdy1, adxt_bdy0, adyt_bdx1, adyt_bdx0,
6144                    at_blarge, at_b[2], at_b[1], at_b[0]);
6145       at_b[3] = at_blarge;
6146       at_blen = 4;
6147       Two_Product(adytail, cdx, adyt_cdx1, adyt_cdx0);
6148       Two_Product(adxtail, cdy, adxt_cdy1, adxt_cdy0);
6149       Two_Two_Diff(adyt_cdx1, adyt_cdx0, adxt_cdy1, adxt_cdy0,
6150                    at_clarge, at_c[2], at_c[1], at_c[0]);
6151       at_c[3] = at_clarge;
6152       at_clen = 4;
6153     }
6154   }
6155   if (bdxtail == 0.0) {
6156     if (bdytail == 0.0) {
6157       bt_c[0] = 0.0;
6158       bt_clen = 1;
6159       bt_a[0] = 0.0;
6160       bt_alen = 1;
6161     } else {
6162       negate = -bdytail;
6163       Two_Product(negate, cdx, bt_clarge, bt_c[0]);
6164       bt_c[1] = bt_clarge;
6165       bt_clen = 2;
6166       Two_Product(bdytail, adx, bt_alarge, bt_a[0]);
6167       bt_a[1] = bt_alarge;
6168       bt_alen = 2;
6169     }
6170   } else {
6171     if (bdytail == 0.0) {
6172       Two_Product(bdxtail, cdy, bt_clarge, bt_c[0]);
6173       bt_c[1] = bt_clarge;
6174       bt_clen = 2;
6175       negate = -bdxtail;
6176       Two_Product(negate, ady, bt_alarge, bt_a[0]);
6177       bt_a[1] = bt_alarge;
6178       bt_alen = 2;
6179     } else {
6180       Two_Product(bdxtail, cdy, bdxt_cdy1, bdxt_cdy0);
6181       Two_Product(bdytail, cdx, bdyt_cdx1, bdyt_cdx0);
6182       Two_Two_Diff(bdxt_cdy1, bdxt_cdy0, bdyt_cdx1, bdyt_cdx0,
6183                    bt_clarge, bt_c[2], bt_c[1], bt_c[0]);
6184       bt_c[3] = bt_clarge;
6185       bt_clen = 4;
6186       Two_Product(bdytail, adx, bdyt_adx1, bdyt_adx0);
6187       Two_Product(bdxtail, ady, bdxt_ady1, bdxt_ady0);
6188       Two_Two_Diff(bdyt_adx1, bdyt_adx0, bdxt_ady1, bdxt_ady0,
6189                   bt_alarge, bt_a[2], bt_a[1], bt_a[0]);
6190       bt_a[3] = bt_alarge;
6191       bt_alen = 4;
6192     }
6193   }
6194   if (cdxtail == 0.0) {
6195     if (cdytail == 0.0) {
6196       ct_a[0] = 0.0;
6197       ct_alen = 1;
6198       ct_b[0] = 0.0;
6199       ct_blen = 1;
6200     } else {
6201       negate = -cdytail;
6202       Two_Product(negate, adx, ct_alarge, ct_a[0]);
6203       ct_a[1] = ct_alarge;
6204       ct_alen = 2;
6205       Two_Product(cdytail, bdx, ct_blarge, ct_b[0]);
6206       ct_b[1] = ct_blarge;
6207       ct_blen = 2;
6208     }
6209   } else {
6210     if (cdytail == 0.0) {
6211       Two_Product(cdxtail, ady, ct_alarge, ct_a[0]);
6212       ct_a[1] = ct_alarge;
6213       ct_alen = 2;
6214       negate = -cdxtail;
6215       Two_Product(negate, bdy, ct_blarge, ct_b[0]);
6216       ct_b[1] = ct_blarge;
6217       ct_blen = 2;
6218     } else {
6219       Two_Product(cdxtail, ady, cdxt_ady1, cdxt_ady0);
6220       Two_Product(cdytail, adx, cdyt_adx1, cdyt_adx0);
6221       Two_Two_Diff(cdxt_ady1, cdxt_ady0, cdyt_adx1, cdyt_adx0,
6222                    ct_alarge, ct_a[2], ct_a[1], ct_a[0]);
6223       ct_a[3] = ct_alarge;
6224       ct_alen = 4;
6225       Two_Product(cdytail, bdx, cdyt_bdx1, cdyt_bdx0);
6226       Two_Product(cdxtail, bdy, cdxt_bdy1, cdxt_bdy0);
6227       Two_Two_Diff(cdyt_bdx1, cdyt_bdx0, cdxt_bdy1, cdxt_bdy0,
6228                    ct_blarge, ct_b[2], ct_b[1], ct_b[0]);
6229       ct_b[3] = ct_blarge;
6230       ct_blen = 4;
6231     }
6232   }
6233 
6234   bctlen = fast_expansion_sum_zeroelim(bt_clen, bt_c, ct_blen, ct_b, bct);
6235   wlength = scale_expansion_zeroelim(bctlen, bct, adheight, w);
6236   finlength = fast_expansion_sum_zeroelim(finlength, finnow, wlength, w,
6237                                           finother);
6238   finswap = finnow; finnow = finother; finother = finswap;
6239 
6240   catlen = fast_expansion_sum_zeroelim(ct_alen, ct_a, at_clen, at_c, cat);
6241   wlength = scale_expansion_zeroelim(catlen, cat, bdheight, w);
6242   finlength = fast_expansion_sum_zeroelim(finlength, finnow, wlength, w,
6243                                           finother);
6244   finswap = finnow; finnow = finother; finother = finswap;
6245 
6246   abtlen = fast_expansion_sum_zeroelim(at_blen, at_b, bt_alen, bt_a, abt);
6247   wlength = scale_expansion_zeroelim(abtlen, abt, cdheight, w);
6248   finlength = fast_expansion_sum_zeroelim(finlength, finnow, wlength, w,
6249                                           finother);
6250   finswap = finnow; finnow = finother; finother = finswap;
6251 
6252   if (adheighttail != 0.0) {
6253     vlength = scale_expansion_zeroelim(4, bc, adheighttail, v);
6254     finlength = fast_expansion_sum_zeroelim(finlength, finnow, vlength, v,
6255                                             finother);
6256     finswap = finnow; finnow = finother; finother = finswap;
6257   }
6258   if (bdheighttail != 0.0) {
6259     vlength = scale_expansion_zeroelim(4, ca, bdheighttail, v);
6260     finlength = fast_expansion_sum_zeroelim(finlength, finnow, vlength, v,
6261                                             finother);
6262     finswap = finnow; finnow = finother; finother = finswap;
6263   }
6264   if (cdheighttail != 0.0) {
6265     vlength = scale_expansion_zeroelim(4, ab, cdheighttail, v);
6266     finlength = fast_expansion_sum_zeroelim(finlength, finnow, vlength, v,
6267                                             finother);
6268     finswap = finnow; finnow = finother; finother = finswap;
6269   }
6270 
6271   if (adxtail != 0.0) {
6272     if (bdytail != 0.0) {
6273       Two_Product(adxtail, bdytail, adxt_bdyt1, adxt_bdyt0);
6274       Two_One_Product(adxt_bdyt1, adxt_bdyt0, cdheight, u3, u[2], u[1], u[0]);
6275       u[3] = u3;
6276       finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
6277                                               finother);
6278       finswap = finnow; finnow = finother; finother = finswap;
6279       if (cdheighttail != 0.0) {
6280         Two_One_Product(adxt_bdyt1, adxt_bdyt0, cdheighttail,
6281                         u3, u[2], u[1], u[0]);
6282         u[3] = u3;
6283         finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
6284                                                 finother);
6285         finswap = finnow; finnow = finother; finother = finswap;
6286       }
6287     }
6288     if (cdytail != 0.0) {
6289       negate = -adxtail;
6290       Two_Product(negate, cdytail, adxt_cdyt1, adxt_cdyt0);
6291       Two_One_Product(adxt_cdyt1, adxt_cdyt0, bdheight, u3, u[2], u[1], u[0]);
6292       u[3] = u3;
6293       finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
6294                                               finother);
6295       finswap = finnow; finnow = finother; finother = finswap;
6296       if (bdheighttail != 0.0) {
6297         Two_One_Product(adxt_cdyt1, adxt_cdyt0, bdheighttail,
6298                         u3, u[2], u[1], u[0]);
6299         u[3] = u3;
6300         finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
6301                                                 finother);
6302         finswap = finnow; finnow = finother; finother = finswap;
6303       }
6304     }
6305   }
6306   if (bdxtail != 0.0) {
6307     if (cdytail != 0.0) {
6308       Two_Product(bdxtail, cdytail, bdxt_cdyt1, bdxt_cdyt0);
6309       Two_One_Product(bdxt_cdyt1, bdxt_cdyt0, adheight, u3, u[2], u[1], u[0]);
6310       u[3] = u3;
6311       finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
6312                                               finother);
6313       finswap = finnow; finnow = finother; finother = finswap;
6314       if (adheighttail != 0.0) {
6315         Two_One_Product(bdxt_cdyt1, bdxt_cdyt0, adheighttail,
6316                         u3, u[2], u[1], u[0]);
6317         u[3] = u3;
6318         finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
6319                                                 finother);
6320         finswap = finnow; finnow = finother; finother = finswap;
6321       }
6322     }
6323     if (adytail != 0.0) {
6324       negate = -bdxtail;
6325       Two_Product(negate, adytail, bdxt_adyt1, bdxt_adyt0);
6326       Two_One_Product(bdxt_adyt1, bdxt_adyt0, cdheight, u3, u[2], u[1], u[0]);
6327       u[3] = u3;
6328       finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
6329                                               finother);
6330       finswap = finnow; finnow = finother; finother = finswap;
6331       if (cdheighttail != 0.0) {
6332         Two_One_Product(bdxt_adyt1, bdxt_adyt0, cdheighttail,
6333                         u3, u[2], u[1], u[0]);
6334         u[3] = u3;
6335         finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
6336                                                 finother);
6337         finswap = finnow; finnow = finother; finother = finswap;
6338       }
6339     }
6340   }
6341   if (cdxtail != 0.0) {
6342     if (adytail != 0.0) {
6343       Two_Product(cdxtail, adytail, cdxt_adyt1, cdxt_adyt0);
6344       Two_One_Product(cdxt_adyt1, cdxt_adyt0, bdheight, u3, u[2], u[1], u[0]);
6345       u[3] = u3;
6346       finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
6347                                               finother);
6348       finswap = finnow; finnow = finother; finother = finswap;
6349       if (bdheighttail != 0.0) {
6350         Two_One_Product(cdxt_adyt1, cdxt_adyt0, bdheighttail,
6351                         u3, u[2], u[1], u[0]);
6352         u[3] = u3;
6353         finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
6354                                                 finother);
6355         finswap = finnow; finnow = finother; finother = finswap;
6356       }
6357     }
6358     if (bdytail != 0.0) {
6359       negate = -cdxtail;
6360       Two_Product(negate, bdytail, cdxt_bdyt1, cdxt_bdyt0);
6361       Two_One_Product(cdxt_bdyt1, cdxt_bdyt0, adheight, u3, u[2], u[1], u[0]);
6362       u[3] = u3;
6363       finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
6364                                               finother);
6365       finswap = finnow; finnow = finother; finother = finswap;
6366       if (adheighttail != 0.0) {
6367         Two_One_Product(cdxt_bdyt1, cdxt_bdyt0, adheighttail,
6368                         u3, u[2], u[1], u[0]);
6369         u[3] = u3;
6370         finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
6371                                                 finother);
6372         finswap = finnow; finnow = finother; finother = finswap;
6373       }
6374     }
6375   }
6376 
6377   if (adheighttail != 0.0) {
6378     wlength = scale_expansion_zeroelim(bctlen, bct, adheighttail, w);
6379     finlength = fast_expansion_sum_zeroelim(finlength, finnow, wlength, w,
6380                                             finother);
6381     finswap = finnow; finnow = finother; finother = finswap;
6382   }
6383   if (bdheighttail != 0.0) {
6384     wlength = scale_expansion_zeroelim(catlen, cat, bdheighttail, w);
6385     finlength = fast_expansion_sum_zeroelim(finlength, finnow, wlength, w,
6386                                             finother);
6387     finswap = finnow; finnow = finother; finother = finswap;
6388   }
6389   if (cdheighttail != 0.0) {
6390     wlength = scale_expansion_zeroelim(abtlen, abt, cdheighttail, w);
6391     finlength = fast_expansion_sum_zeroelim(finlength, finnow, wlength, w,
6392                                             finother);
6393     finnow = finother;
6394   }
6395 
6396   return finnow[finlength - 1];
6397 }
6398 
6399 #ifdef ANSI_DECLARATORS
6400 REAL orient3d(struct mesh *m, struct behavior *b,
6401               vertex pa, vertex pb, vertex pc, vertex pd,
6402               REAL aheight, REAL bheight, REAL cheight, REAL dheight)
6403 #else /* not ANSI_DECLARATORS */
6404 REAL orient3d(m, b, pa, pb, pc, pd, aheight, bheight, cheight, dheight)
6405 struct mesh *m;
6406 struct behavior *b;
6407 vertex pa;
6408 vertex pb;
6409 vertex pc;
6410 vertex pd;
6411 REAL aheight;
6412 REAL bheight;
6413 REAL cheight;
6414 REAL dheight;
6415 #endif /* not ANSI_DECLARATORS */
6416 
6417 {
6418   REAL adx, bdx, cdx, ady, bdy, cdy, adheight, bdheight, cdheight;
6419   REAL bdxcdy, cdxbdy, cdxady, adxcdy, adxbdy, bdxady;
6420   REAL det;
6421   REAL permanent, errbound;
6422 
6423   m->orient3dcount++;
6424 
6425   adx = pa[0] - pd[0];
6426   bdx = pb[0] - pd[0];
6427   cdx = pc[0] - pd[0];
6428   ady = pa[1] - pd[1];
6429   bdy = pb[1] - pd[1];
6430   cdy = pc[1] - pd[1];
6431   adheight = aheight - dheight;
6432   bdheight = bheight - dheight;
6433   cdheight = cheight - dheight;
6434 
6435   bdxcdy = bdx * cdy;
6436   cdxbdy = cdx * bdy;
6437 
6438   cdxady = cdx * ady;
6439   adxcdy = adx * cdy;
6440 
6441   adxbdy = adx * bdy;
6442   bdxady = bdx * ady;
6443 
6444   det = adheight * (bdxcdy - cdxbdy)
6445       + bdheight * (cdxady - adxcdy)
6446       + cdheight * (adxbdy - bdxady);
6447 
6448   if (b->noexact) {
6449     return det;
6450   }
6451 
6452   permanent = (Absolute(bdxcdy) + Absolute(cdxbdy)) * Absolute(adheight)
6453             + (Absolute(cdxady) + Absolute(adxcdy)) * Absolute(bdheight)
6454             + (Absolute(adxbdy) + Absolute(bdxady)) * Absolute(cdheight);
6455   errbound = o3derrboundA * permanent;
6456   if ((det > errbound) || (-det > errbound)) {
6457     return det;
6458   }
6459 
6460   return orient3dadapt(pa, pb, pc, pd, aheight, bheight, cheight, dheight,
6461                        permanent);
6462 }
6463 
6464 /*****************************************************************************/
6465 /*                                                                           */
6466 /*  nonregular()   Return a positive value if the point pd is incompatible   */
6467 /*                 with the circle or plane passing through pa, pb, and pc   */
6468 /*                 (meaning that pd is inside the circle or below the        */
6469 /*                 plane); a negative value if it is compatible; and zero if */
6470 /*                 the four points are cocircular/coplanar.  The points pa,  */
6471 /*                 pb, and pc must be in counterclockwise order, or the sign */
6472 /*                 of the result will be reversed.                           */
6473 /*                                                                           */
6474 /*  If the -w switch is used, the points are lifted onto the parabolic       */
6475 /*  lifting map, then they are dropped according to their weights, then the  */
6476 /*  3D orientation test is applied.  If the -W switch is used, the points'   */
6477 /*  heights are already provided, so the 3D orientation test is applied      */
6478 /*  directly.  If neither switch is used, the incircle test is applied.      */
6479 /*                                                                           */
6480 /*****************************************************************************/
6481 
6482 #ifdef ANSI_DECLARATORS
6483 REAL nonregular(struct mesh *m, struct behavior *b,
6484                 vertex pa, vertex pb, vertex pc, vertex pd)
6485 #else /* not ANSI_DECLARATORS */
6486 REAL nonregular(m, b, pa, pb, pc, pd)
6487 struct mesh *m;
6488 struct behavior *b;
6489 vertex pa;
6490 vertex pb;
6491 vertex pc;
6492 vertex pd;
6493 #endif /* not ANSI_DECLARATORS */
6494 
6495 {
6496   if (b->weighted == 0) {
6497     return incircle(m, b, pa, pb, pc, pd);
6498   } else if (b->weighted == 1) {
6499     return orient3d(m, b, pa, pb, pc, pd,
6500                     pa[0] * pa[0] + pa[1] * pa[1] - pa[2],
6501                     pb[0] * pb[0] + pb[1] * pb[1] - pb[2],
6502                     pc[0] * pc[0] + pc[1] * pc[1] - pc[2],
6503                     pd[0] * pd[0] + pd[1] * pd[1] - pd[2]);
6504   } else {
6505     return orient3d(m, b, pa, pb, pc, pd, pa[2], pb[2], pc[2], pd[2]);
6506   }
6507 }
6508 
6509 /*****************************************************************************/
6510 /*                                                                           */
6511 /*  findcircumcenter()   Find the circumcenter of a triangle.                */
6512 /*                                                                           */
6513 /*  The result is returned both in terms of x-y coordinates and xi-eta       */
6514 /*  (barycentric) coordinates.  The xi-eta coordinate system is defined in   */
6515 /*  terms of the triangle:  the origin of the triangle is the origin of the  */
6516 /*  coordinate system; the destination of the triangle is one unit along the */
6517 /*  xi axis; and the apex of the triangle is one unit along the eta axis.    */
6518 /*  This procedure also returns the square of the length of the triangle's   */
6519 /*  shortest edge.                                                           */
6520 /*                                                                           */
6521 /*****************************************************************************/
6522 
6523 #ifdef ANSI_DECLARATORS
6524 void findcircumcenter(struct mesh *m, struct behavior *b,
6525                       vertex torg, vertex tdest, vertex tapex,
6526                       vertex circumcenter, REAL *xi, REAL *eta, int offcenter)
6527 #else /* not ANSI_DECLARATORS */
6528 void findcircumcenter(m, b, torg, tdest, tapex, circumcenter, xi, eta,
6529                       offcenter)
6530 struct mesh *m;
6531 struct behavior *b;
6532 vertex torg;
6533 vertex tdest;
6534 vertex tapex;
6535 vertex circumcenter;
6536 REAL *xi;
6537 REAL *eta;
6538 int offcenter;
6539 #endif /* not ANSI_DECLARATORS */
6540 
6541 {
6542   REAL xdo, ydo, xao, yao;
6543   REAL dodist, aodist, dadist;
6544   REAL denominator;
6545   REAL dx, dy, dxoff, dyoff;
6546 
6547   m->circumcentercount++;
6548 
6549   /* Compute the circumcenter of the triangle. */
6550   xdo = tdest[0] - torg[0];
6551   ydo = tdest[1] - torg[1];
6552   xao = tapex[0] - torg[0];
6553   yao = tapex[1] - torg[1];
6554   dodist = xdo * xdo + ydo * ydo;
6555   aodist = xao * xao + yao * yao;
6556   dadist = (tdest[0] - tapex[0]) * (tdest[0] - tapex[0]) +
6557            (tdest[1] - tapex[1]) * (tdest[1] - tapex[1]);
6558   if (b->noexact) {
6559     denominator = 0.5 / (xdo * yao - xao * ydo);
6560   } else {
6561     /* Use the counterclockwise() routine to ensure a positive (and */
6562     /*   reasonably accurate) result, avoiding any possibility of   */
6563     /*   division by zero.                                          */
6564     denominator = 0.5 / counterclockwise(m, b, tdest, tapex, torg);
6565     /* Don't count the above as an orientation test. */
6566     m->counterclockcount--;
6567   }
6568   dx = (yao * dodist - ydo * aodist) * denominator;
6569   dy = (xdo * aodist - xao * dodist) * denominator;
6570 
6571   /* Find the (squared) length of the triangle's shortest edge.  This   */
6572   /*   serves as a conservative estimate of the insertion radius of the */
6573   /*   circumcenter's parent.  The estimate is used to ensure that      */
6574   /*   the algorithm terminates even if very small angles appear in     */
6575   /*   the input PSLG.                                                  */
6576   if ((dodist < aodist) && (dodist < dadist)) {
6577     if (offcenter && (b->offconstant > 0.0)) {
6578       /* Find the position of the off-center, as described by Alper Ungor. */
6579       dxoff = 0.5 * xdo - b->offconstant * ydo;
6580       dyoff = 0.5 * ydo + b->offconstant * xdo;
6581       /* If the off-center is closer to the origin than the */
6582       /*   circumcenter, use the off-center instead.        */
6583       if (dxoff * dxoff + dyoff * dyoff < dx * dx + dy * dy) {
6584         dx = dxoff;
6585         dy = dyoff;
6586       }
6587     }
6588   } else if (aodist < dadist) {
6589     if (offcenter && (b->offconstant > 0.0)) {
6590       dxoff = 0.5 * xao + b->offconstant * yao;
6591       dyoff = 0.5 * yao - b->offconstant * xao;
6592       /* If the off-center is closer to the origin than the */
6593       /*   circumcenter, use the off-center instead.        */
6594       if (dxoff * dxoff + dyoff * dyoff < dx * dx + dy * dy) {
6595         dx = dxoff;
6596         dy = dyoff;
6597       }
6598     }
6599   } else {
6600     if (offcenter && (b->offconstant > 0.0)) {
6601       dxoff = 0.5 * (tapex[0] - tdest[0]) -
6602               b->offconstant * (tapex[1] - tdest[1]);
6603       dyoff = 0.5 * (tapex[1] - tdest[1]) +
6604               b->offconstant * (tapex[0] - tdest[0]);
6605       /* If the off-center is closer to the destination than the */
6606       /*   circumcenter, use the off-center instead.             */
6607       if (dxoff * dxoff + dyoff * dyoff <
6608           (dx - xdo) * (dx - xdo) + (dy - ydo) * (dy - ydo)) {
6609         dx = xdo + dxoff;
6610         dy = ydo + dyoff;
6611       }
6612     }
6613   }
6614 
6615   circumcenter[0] = torg[0] + dx;
6616   circumcenter[1] = torg[1] + dy;
6617 
6618   /* To interpolate vertex attributes for the new vertex inserted at */
6619   /*   the circumcenter, define a coordinate system with a xi-axis,  */
6620   /*   directed from the triangle's origin to its destination, and   */
6621   /*   an eta-axis, directed from its origin to its apex.            */
6622   /*   Calculate the xi and eta coordinates of the circumcenter.     */
6623   *xi = (yao * dx - xao * dy) * (2.0 * denominator);
6624   *eta = (xdo * dy - ydo * dx) * (2.0 * denominator);
6625 }
6626 
6627 /**                                                                         **/
6628 /**                                                                         **/
6629 /********* Geometric primitives end here                             *********/
6630 
6631 /*****************************************************************************/
6632 /*                                                                           */
6633 /*  triangleinit()   Initialize some variables.                              */
6634 /*                                                                           */
6635 /*****************************************************************************/
6636 
6637 #ifdef ANSI_DECLARATORS
6638 void triangleinit(struct mesh *m)
6639 #else /* not ANSI_DECLARATORS */
6640 void triangleinit(m)
6641 struct mesh *m;
6642 #endif /* not ANSI_DECLARATORS */
6643 
6644 {
6645   poolzero(&m->vertices);
6646   poolzero(&m->triangles);
6647   poolzero(&m->subsegs);
6648   poolzero(&m->viri);
6649   poolzero(&m->badsubsegs);
6650   poolzero(&m->badtriangles);
6651   poolzero(&m->flipstackers);
6652   poolzero(&m->splaynodes);
6653 
6654   m->recenttri.tri = (triangle *) NULL; /* No triangle has been visited yet. */
6655   m->undeads = 0;                       /* No eliminated input vertices yet. */
6656   m->samples = 1;         /* Point location should take at least one sample. */
6657   m->checksegments = 0;   /* There are no segments in the triangulation yet. */
6658   m->checkquality = 0;     /* The quality triangulation stage has not begun. */
6659   m->incirclecount = m->counterclockcount = m->orient3dcount = 0;
6660   m->hyperbolacount = m->circletopcount = m->circumcentercount = 0;
6661   randomseed = 1;
6662 
6663   exactinit();                     /* Initialize exact arithmetic constants. */
6664 }
6665 
6666 /*****************************************************************************/
6667 /*                                                                           */
6668 /*  randomnation()   Generate a random number between 0 and `choices' - 1.   */
6669 /*                                                                           */
6670 /*  This is a simple linear congruential random number generator.  Hence, it */
6671 /*  is a bad random number generator, but good enough for most randomized    */
6672 /*  geometric algorithms.                                                    */
6673 /*                                                                           */
6674 /*****************************************************************************/
6675 
6676 #ifdef ANSI_DECLARATORS
6677 TRIANGLE_PTRINT randomnation(unsigned int choices)
6678 #else /* not ANSI_DECLARATORS */
6679 TRIANGLE_PTRINT randomnation(choices)
6680 unsigned int choices;
6681 #endif /* not ANSI_DECLARATORS */
6682 
6683 {
6684   randomseed = (randomseed * 1366l + 150889l) % 714025l;
6685   return ( randomseed * (choices + 1 ) )/ 714025l;
6686 }
6687 
6688 /********* Mesh quality testing routines begin here                  *********/
6689 /**                                                                         **/
6690 /**                                                                         **/
6691 
6692 /*****************************************************************************/
6693 /*                                                                           */
6694 /*  checkmesh()   Test the mesh for topological consistency.                 */
6695 /*                                                                           */
6696 /*****************************************************************************/
6697 
6698 #ifndef REDUCED
6699 
6700 #ifdef ANSI_DECLARATORS
6701 void checkmesh(struct mesh *m, struct behavior *b)
6702 #else /* not ANSI_DECLARATORS */
6703 void checkmesh(m, b)
6704 struct mesh *m;
6705 struct behavior *b;
6706 #endif /* not ANSI_DECLARATORS */
6707 
6708 {
6709   struct otri triangleloop;
6710   struct otri oppotri, oppooppotri;
6711   vertex triorg, tridest, triapex;
6712   vertex oppoorg, oppodest;
6713   int horrors;
6714   int saveexact;
6715   triangle ptr;                         /* Temporary variable used by sym(). */
6716 
6717   /* Temporarily turn on exact arithmetic if it's off. */
6718   saveexact = b->noexact;
6719   b->noexact = 0;
6720   if (!b->quiet) {
6721     printf("  Checking consistency of mesh...\n");
6722   }
6723   horrors = 0;
6724   /* Run through the list of triangles, checking each one. */
6725   traversalinit(&m->triangles);
6726   triangleloop.tri = triangletraverse(m);
6727   while (triangleloop.tri != (triangle *) NULL) {
6728     /* Check all three edges of the triangle. */
6729     for (triangleloop.orient = 0; triangleloop.orient < 3;
6730          triangleloop.orient++) {
6731       org(triangleloop, triorg);
6732       dest(triangleloop, tridest);
6733       if (triangleloop.orient == 0) {       /* Only test for inversion once. */
6734         /* Test if the triangle is flat or inverted. */
6735         apex(triangleloop, triapex);
6736         if (counterclockwise(m, b, triorg, tridest, triapex) <= 0.0) {
6737           printf("  !! !! Inverted ");
6738           printtriangle(m, b, &triangleloop);
6739           horrors++;
6740         }
6741       }
6742       /* Find the neighboring triangle on this edge. */
6743       sym(triangleloop, oppotri);
6744       if (oppotri.tri != m->dummytri) {
6745         /* Check that the triangle's neighbor knows it's a neighbor. */
6746         sym(oppotri, oppooppotri);
6747         if ((triangleloop.tri != oppooppotri.tri)
6748             || (triangleloop.orient != oppooppotri.orient)) {
6749           printf("  !! !! Asymmetric triangle-triangle bond:\n");
6750           if (triangleloop.tri == oppooppotri.tri) {
6751             printf("   (Right triangle, wrong orientation)\n");
6752           }
6753           printf("    First ");
6754           printtriangle(m, b, &triangleloop);
6755           printf("    Second (nonreciprocating) ");
6756           printtriangle(m, b, &oppotri);
6757           horrors++;
6758         }
6759         /* Check that both triangles agree on the identities */
6760         /*   of their shared vertices.                       */
6761         org(oppotri, oppoorg);
6762         dest(oppotri, oppodest);
6763         if ((triorg != oppodest) || (tridest != oppoorg)) {
6764           printf("  !! !! Mismatched edge coordinates between two triangles:\n"
6765                  );
6766           printf("    First mismatched ");
6767           printtriangle(m, b, &triangleloop);
6768           printf("    Second mismatched ");
6769           printtriangle(m, b, &oppotri);
6770           horrors++;
6771         }
6772       }
6773     }
6774     triangleloop.tri = triangletraverse(m);
6775   }
6776   if (horrors == 0) {
6777     if (!b->quiet) {
6778       printf("  In my studied opinion, the mesh appears to be consistent.\n");
6779     }
6780   } else if (horrors == 1) {
6781     printf("  !! !! !! !! Precisely one festering wound discovered.\n");
6782   } else {
6783     printf("  !! !! !! !! %d abominations witnessed.\n", horrors);
6784   }
6785   /* Restore the status of exact arithmetic. */
6786   b->noexact = saveexact;
6787 }
6788 
6789 #endif /* not REDUCED */
6790 
6791 /*****************************************************************************/
6792 /*                                                                           */
6793 /*  checkdelaunay()   Ensure that the mesh is (constrained) Delaunay.        */
6794 /*                                                                           */
6795 /*****************************************************************************/
6796 
6797 #ifndef REDUCED
6798 
6799 #ifdef ANSI_DECLARATORS
6800 void checkdelaunay(struct mesh *m, struct behavior *b)
6801 #else /* not ANSI_DECLARATORS */
6802 void checkdelaunay(m, b)
6803 struct mesh *m;
6804 struct behavior *b;
6805 #endif /* not ANSI_DECLARATORS */
6806 
6807 {
6808   struct otri triangleloop;
6809   struct otri oppotri;
6810   struct osub opposubseg;
6811   vertex triorg, tridest, triapex;
6812   vertex oppoapex;
6813   int shouldbedelaunay;
6814   int horrors;
6815   int saveexact;
6816   triangle ptr;                         /* Temporary variable used by sym(). */
6817   subseg sptr;                      /* Temporary variable used by tspivot(). */
6818 
6819   /* Temporarily turn on exact arithmetic if it's off. */
6820   saveexact = b->noexact;
6821   b->noexact = 0;
6822   if (!b->quiet) {
6823     printf("  Checking Delaunay property of mesh...\n");
6824   }
6825   horrors = 0;
6826   /* Run through the list of triangles, checking each one. */
6827   traversalinit(&m->triangles);
6828   triangleloop.tri = triangletraverse(m);
6829   while (triangleloop.tri != (triangle *) NULL) {
6830     /* Check all three edges of the triangle. */
6831     for (triangleloop.orient = 0; triangleloop.orient < 3;
6832          triangleloop.orient++) {
6833       org(triangleloop, triorg);
6834       dest(triangleloop, tridest);
6835       apex(triangleloop, triapex);
6836       sym(triangleloop, oppotri);
6837       apex(oppotri, oppoapex);
6838       /* Only test that the edge is locally Delaunay if there is an   */
6839       /*   adjoining triangle whose pointer is larger (to ensure that */
6840       /*   each pair isn't tested twice).                             */
6841       shouldbedelaunay = (oppotri.tri != m->dummytri) &&
6842             !deadtri(oppotri.tri) && (triangleloop.tri < oppotri.tri) &&
6843             (triorg != m->infvertex1) && (triorg != m->infvertex2) &&
6844             (triorg != m->infvertex3) &&
6845             (tridest != m->infvertex1) && (tridest != m->infvertex2) &&
6846             (tridest != m->infvertex3) &&
6847             (triapex != m->infvertex1) && (triapex != m->infvertex2) &&
6848             (triapex != m->infvertex3) &&
6849             (oppoapex != m->infvertex1) && (oppoapex != m->infvertex2) &&
6850             (oppoapex != m->infvertex3);
6851       if (m->checksegments && shouldbedelaunay) {
6852         /* If a subsegment separates the triangles, then the edge is */
6853         /*   constrained, so no local Delaunay test should be done.  */
6854         tspivot(triangleloop, opposubseg);
6855         if (opposubseg.ss != m->dummysub){
6856           shouldbedelaunay = 0;
6857         }
6858       }
6859       if (shouldbedelaunay) {
6860         if (nonregular(m, b, triorg, tridest, triapex, oppoapex) > 0.0) {
6861           if (!b->weighted) {
6862             printf("  !! !! Non-Delaunay pair of triangles:\n");
6863             printf("    First non-Delaunay ");
6864             printtriangle(m, b, &triangleloop);
6865             printf("    Second non-Delaunay ");
6866           } else {
6867             printf("  !! !! Non-regular pair of triangles:\n");
6868             printf("    First non-regular ");
6869             printtriangle(m, b, &triangleloop);
6870             printf("    Second non-regular ");
6871           }
6872           printtriangle(m, b, &oppotri);
6873           horrors++;
6874         }
6875       }
6876     }
6877     triangleloop.tri = triangletraverse(m);
6878   }
6879   if (horrors == 0) {
6880     if (!b->quiet) {
6881       printf(
6882   "  By virtue of my perceptive intelligence, I declare the mesh Delaunay.\n");
6883     }
6884   } else if (horrors == 1) {
6885     printf(
6886          "  !! !! !! !! Precisely one terrifying transgression identified.\n");
6887   } else {
6888     printf("  !! !! !! !! %d obscenities viewed with horror.\n", horrors);
6889   }
6890   /* Restore the status of exact arithmetic. */
6891   b->noexact = saveexact;
6892 }
6893 
6894 #endif /* not REDUCED */
6895 
6896 /*****************************************************************************/
6897 /*                                                                           */
6898 /*  enqueuebadtriang()   Add a bad triangle data structure to the end of a   */
6899 /*                       queue.                                              */
6900 /*                                                                           */
6901 /*  The queue is actually a set of 4096 queues.  I use multiple queues to    */
6902 /*  give priority to smaller angles.  I originally implemented a heap, but   */
6903 /*  the queues are faster by a larger margin than I'd suspected.             */
6904 /*                                                                           */
6905 /*****************************************************************************/
6906 
6907 #ifndef CDT_ONLY
6908 
6909 #ifdef ANSI_DECLARATORS
6910 void enqueuebadtriang(struct mesh *m, struct behavior *b,
6911                       struct badtriang *badtri)
6912 #else /* not ANSI_DECLARATORS */
6913 void enqueuebadtriang(m, b, badtri)
6914 struct mesh *m;
6915 struct behavior *b;
6916 struct badtriang *badtri;
6917 #endif /* not ANSI_DECLARATORS */
6918 
6919 {
6920   REAL length, multiplier;
6921   int exponent, expincrement;
6922   int queuenumber;
6923   int posexponent;
6924   int i;
6925 
6926   if (b->verbose > 2) {
6927     printf("  Queueing bad triangle:\n");
6928     printf("    (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
6929            badtri->triangorg[0], badtri->triangorg[1],
6930            badtri->triangdest[0], badtri->triangdest[1],
6931            badtri->triangapex[0], badtri->triangapex[1]);
6932   }
6933 
6934   /* Determine the appropriate queue to put the bad triangle into.    */
6935   /*   Recall that the key is the square of its shortest edge length. */
6936   if (badtri->key >= 1.0) {
6937     length = badtri->key;
6938     posexponent = 1;
6939   } else {
6940     /* `badtri->key' is 2.0 to a negative exponent, so we'll record that */
6941     /*   fact and use the reciprocal of `badtri->key', which is > 1.0.   */
6942     length = 1.0 / badtri->key;
6943     posexponent = 0;
6944   }
6945   /* `length' is approximately 2.0 to what exponent?  The following code */
6946   /*   determines the answer in time logarithmic in the exponent.        */
6947   exponent = 0;
6948   while (length > 2.0) {
6949     /* Find an approximation by repeated squaring of two. */
6950     expincrement = 1;
6951     multiplier = 0.5;
6952     while (length * multiplier * multiplier > 1.0) {
6953       expincrement *= 2;
6954       multiplier *= multiplier;
6955     }
6956     /* Reduce the value of `length', then iterate if necessary. */
6957     exponent += expincrement;
6958     length *= multiplier;
6959   }
6960   /* `length' is approximately squareroot(2.0) to what exponent? */
6961   exponent = (int) ( 2.0 * exponent + (length > SQUAREROOTTWO) );
6962   /* `exponent' is now in the range 0...2047 for IEEE double precision.   */
6963   /*   Choose a queue in the range 0...4095.  The shortest edges have the */
6964   /*   highest priority (queue 4095).                                     */
6965   if (posexponent) {
6966     queuenumber = 2047 - exponent;
6967   } else {
6968     queuenumber = 2048 + exponent;
6969   }
6970 
6971   /* Are we inserting into an empty queue? */
6972   if (m->queuefront[queuenumber] == (struct badtriang *) NULL) {
6973     /* Yes, we are inserting into an empty queue.     */
6974     /*   Will this become the highest-priority queue? */
6975     if (queuenumber > m->firstnonemptyq) {
6976       /* Yes, this is the highest-priority queue. */
6977       m->nextnonemptyq[queuenumber] = m->firstnonemptyq;
6978       m->firstnonemptyq = queuenumber;
6979     } else {
6980       /* No, this is not the highest-priority queue. */
6981       /*   Find the queue with next higher priority. */
6982       i = queuenumber + 1;
6983       while (m->queuefront[i] == (struct badtriang *) NULL) {
6984         i++;
6985       }
6986       /* Mark the newly nonempty queue as following a higher-priority queue. */
6987       m->nextnonemptyq[queuenumber] = m->nextnonemptyq[i];
6988       m->nextnonemptyq[i] = queuenumber;
6989     }
6990     /* Put the bad triangle at the beginning of the (empty) queue. */
6991     m->queuefront[queuenumber] = badtri;
6992   } else {
6993     /* Add the bad triangle to the end of an already nonempty queue. */
6994     m->queuetail[queuenumber]->nexttriang = badtri;
6995   }
6996   /* Maintain a pointer to the last triangle of the queue. */
6997   m->queuetail[queuenumber] = badtri;
6998   /* Newly enqueued bad triangle has no successor in the queue. */
6999   badtri->nexttriang = (struct badtriang *) NULL;
7000 }
7001 
7002 #endif /* not CDT_ONLY */
7003 
7004 /*****************************************************************************/
7005 /*                                                                           */
7006 /*  enqueuebadtri()   Add a bad triangle to the end of a queue.              */
7007 /*                                                                           */
7008 /*  Allocates a badtriang data structure for the triangle, then passes it to */
7009 /*  enqueuebadtriang().                                                      */
7010 /*                                                                           */
7011 /*****************************************************************************/
7012 
7013 #ifndef CDT_ONLY
7014 
7015 #ifdef ANSI_DECLARATORS
7016 void enqueuebadtri(struct mesh *m, struct behavior *b, struct otri *enqtri,
7017                    REAL minedge, vertex enqapex, vertex enqorg, vertex enqdest)
7018 #else /* not ANSI_DECLARATORS */
7019 void enqueuebadtri(m, b, enqtri, minedge, enqapex, enqorg, enqdest)
7020 struct mesh *m;
7021 struct behavior *b;
7022 struct otri *enqtri;
7023 REAL minedge;
7024 vertex enqapex;
7025 vertex enqorg;
7026 vertex enqdest;
7027 #endif /* not ANSI_DECLARATORS */
7028 
7029 {
7030   struct badtriang *newbad;
7031 
7032   /* Allocate space for the bad triangle. */
7033   newbad = (struct badtriang *) poolalloc(&m->badtriangles);
7034   newbad->poortri = encode(*enqtri);
7035   newbad->key = minedge;
7036   newbad->triangapex = enqapex;
7037   newbad->triangorg = enqorg;
7038   newbad->triangdest = enqdest;
7039   enqueuebadtriang(m, b, newbad);
7040 }
7041 
7042 #endif /* not CDT_ONLY */
7043 
7044 /*****************************************************************************/
7045 /*                                                                           */
7046 /*  dequeuebadtriang()   Remove a triangle from the front of the queue.      */
7047 /*                                                                           */
7048 /*****************************************************************************/
7049 
7050 #ifndef CDT_ONLY
7051 
7052 #ifdef ANSI_DECLARATORS
7053 struct badtriang *dequeuebadtriang(struct mesh *m)
7054 #else /* not ANSI_DECLARATORS */
7055 struct badtriang *dequeuebadtriang(m)
7056 struct mesh *m;
7057 #endif /* not ANSI_DECLARATORS */
7058 
7059 {
7060   struct badtriang *result;
7061 
7062   /* If no queues are nonempty, return NULL. */
7063   if (m->firstnonemptyq < 0) {
7064     return (struct badtriang *) NULL;
7065   }
7066   /* Find the first triangle of the highest-priority queue. */
7067   result = m->queuefront[m->firstnonemptyq];
7068   /* Remove the triangle from the queue. */
7069   m->queuefront[m->firstnonemptyq] = result->nexttriang;
7070   /* If this queue is now empty, note the new highest-priority */
7071   /*   nonempty queue.                                         */
7072   if (result == m->queuetail[m->firstnonemptyq]) {
7073     m->firstnonemptyq = m->nextnonemptyq[m->firstnonemptyq];
7074   }
7075   return result;
7076 }
7077 
7078 #endif /* not CDT_ONLY */
7079 
7080 /*****************************************************************************/
7081 /*                                                                           */
7082 /*  checkseg4encroach()   Check a subsegment to see if it is encroached; add */
7083 /*                        it to the list if it is.                           */
7084 /*                                                                           */
7085 /*  A subsegment is encroached if there is a vertex in its diametral lens.   */
7086 /*  For Ruppert's algorithm (-D switch), the "diametral lens" is the         */
7087 /*  diametral circle.  For Chew's algorithm (default), the diametral lens is */
7088 /*  just big enough to enclose two isosceles triangles whose bases are the   */
7089 /*  subsegment.  Each of the two isosceles triangles has two angles equal    */
7090 /*  to `b->minangle'.                                                        */
7091 /*                                                                           */
7092 /*  Chew's algorithm does not require diametral lenses at all--but they save */
7093 /*  time.  Any vertex inside a subsegment's diametral lens implies that the  */
7094 /*  triangle adjoining the subsegment will be too skinny, so it's only a     */
7095 /*  matter of time before the encroaching vertex is deleted by Chew's        */
7096 /*  algorithm.  It's faster to simply not insert the doomed vertex in the    */
7097 /*  first place, which is why I use diametral lenses with Chew's algorithm.  */
7098 /*                                                                           */
7099 /*  Returns a nonzero value if the subsegment is encroached.                 */
7100 /*                                                                           */
7101 /*****************************************************************************/
7102 
7103 #ifndef CDT_ONLY
7104 
7105 #ifdef ANSI_DECLARATORS
7106 int checkseg4encroach(struct mesh *m, struct behavior *b,
7107                       struct osub *testsubseg)
7108 #else /* not ANSI_DECLARATORS */
7109 int checkseg4encroach(m, b, testsubseg)
7110 struct mesh *m;
7111 struct behavior *b;
7112 struct osub *testsubseg;
7113 #endif /* not ANSI_DECLARATORS */
7114 
7115 {
7116   struct otri neighbortri;
7117   struct osub testsym;
7118   struct badsubseg *encroachedseg;
7119   REAL dotproduct;
7120   int encroached;
7121   int sides;
7122   vertex eorg, edest, eapex;
7123   triangle ptr;                     /* Temporary variable used by stpivot(). */
7124 
7125   encroached = 0;
7126   sides = 0;
7127 
7128   sorg(*testsubseg, eorg);
7129   sdest(*testsubseg, edest);
7130   /* Check one neighbor of the subsegment. */
7131   stpivot(*testsubseg, neighbortri);
7132   /* Does the neighbor exist, or is this a boundary edge? */
7133   if (neighbortri.tri != m->dummytri) {
7134     sides++;
7135     /* Find a vertex opposite this subsegment. */
7136     apex(neighbortri, eapex);
7137     /* Check whether the apex is in the diametral lens of the subsegment */
7138     /*   (the diametral circle if `conformdel' is set).  A dot product   */
7139     /*   of two sides of the triangle is used to check whether the angle */
7140     /*   at the apex is greater than (180 - 2 `minangle') degrees (for   */
7141     /*   lenses; 90 degrees for diametral circles).                      */
7142     dotproduct = (eorg[0] - eapex[0]) * (edest[0] - eapex[0]) +
7143                  (eorg[1] - eapex[1]) * (edest[1] - eapex[1]);
7144     if (dotproduct < 0.0) {
7145       if (b->conformdel ||
7146           (dotproduct * dotproduct >=
7147            (2.0 * b->goodangle - 1.0) * (2.0 * b->goodangle - 1.0) *
7148            ((eorg[0] - eapex[0]) * (eorg[0] - eapex[0]) +
7149             (eorg[1] - eapex[1]) * (eorg[1] - eapex[1])) *
7150            ((edest[0] - eapex[0]) * (edest[0] - eapex[0]) +
7151             (edest[1] - eapex[1]) * (edest[1] - eapex[1])))) {
7152         encroached = 1;
7153       }
7154     }
7155   }
7156   /* Check the other neighbor of the subsegment. */
7157   ssym(*testsubseg, testsym);
7158   stpivot(testsym, neighbortri);
7159   /* Does the neighbor exist, or is this a boundary edge? */
7160   if (neighbortri.tri != m->dummytri) {
7161     sides++;
7162     /* Find the other vertex opposite this subsegment. */
7163     apex(neighbortri, eapex);
7164     /* Check whether the apex is in the diametral lens of the subsegment */
7165     /*   (or the diametral circle, if `conformdel' is set).              */
7166     dotproduct = (eorg[0] - eapex[0]) * (edest[0] - eapex[0]) +
7167                  (eorg[1] - eapex[1]) * (edest[1] - eapex[1]);
7168     if (dotproduct < 0.0) {
7169       if (b->conformdel ||
7170           (dotproduct * dotproduct >=
7171            (2.0 * b->goodangle - 1.0) * (2.0 * b->goodangle - 1.0) *
7172            ((eorg[0] - eapex[0]) * (eorg[0] - eapex[0]) +
7173             (eorg[1] - eapex[1]) * (eorg[1] - eapex[1])) *
7174            ((edest[0] - eapex[0]) * (edest[0] - eapex[0]) +
7175             (edest[1] - eapex[1]) * (edest[1] - eapex[1])))) {
7176         encroached += 2;
7177       }
7178     }
7179   }
7180 
7181   if (encroached && (!b->nobisect || ((b->nobisect == 1) && (sides == 2)))) {
7182     if (b->verbose > 2) {
7183       printf(
7184         "  Queueing encroached subsegment (%.12g, %.12g) (%.12g, %.12g).\n",
7185         eorg[0], eorg[1], edest[0], edest[1]);
7186     }
7187     /* Add the subsegment to the list of encroached subsegments. */
7188     /*   Be sure to get the orientation right.                   */
7189     encroachedseg = (struct badsubseg *) poolalloc(&m->badsubsegs);
7190     if (encroached == 1) {
7191       encroachedseg->encsubseg = sencode(*testsubseg);
7192       encroachedseg->subsegorg = eorg;
7193       encroachedseg->subsegdest = edest;
7194     } else {
7195       encroachedseg->encsubseg = sencode(testsym);
7196       encroachedseg->subsegorg = edest;
7197       encroachedseg->subsegdest = eorg;
7198     }
7199   }
7200 
7201   return encroached;
7202 }
7203 
7204 #endif /* not CDT_ONLY */
7205 
7206 /*****************************************************************************/
7207 /*                                                                           */
7208 /*  testtriangle()   Test a triangle for quality and size.                   */
7209 /*                                                                           */
7210 /*  Tests a triangle to see if it satisfies the minimum angle condition and  */
7211 /*  the maximum area condition.  Triangles that aren't up to spec are added  */
7212 /*  to the bad triangle queue.                                               */
7213 /*                                                                           */
7214 /*****************************************************************************/
7215 
7216 #ifndef CDT_ONLY
7217 
7218 #ifdef ANSI_DECLARATORS
7219 void testtriangle(struct mesh *m, struct behavior *b, struct otri *testtri)
7220 #else /* not ANSI_DECLARATORS */
7221 void testtriangle(m, b, testtri)
7222 struct mesh *m;
7223 struct behavior *b;
7224 struct otri *testtri;
7225 #endif /* not ANSI_DECLARATORS */
7226 
7227 {
7228   struct otri tri1, tri2;
7229   struct osub testsub;
7230   vertex torg, tdest, tapex;
7231   vertex base1, base2;
7232   vertex org1, dest1, org2, dest2;
7233   vertex joinvertex;
7234   REAL dxod, dyod, dxda, dyda, dxao, dyao;
7235   REAL dxod2, dyod2, dxda2, dyda2, dxao2, dyao2;
7236   REAL apexlen, orglen, destlen, minedge;
7237   REAL angle;
7238   REAL area;
7239   REAL dist1, dist2;
7240   subseg sptr;                      /* Temporary variable used by tspivot(). */
7241   triangle ptr;           /* Temporary variable used by oprev() and dnext(). */
7242 
7243   org(*testtri, torg);
7244   dest(*testtri, tdest);
7245   apex(*testtri, tapex);
7246   dxod = torg[0] - tdest[0];
7247   dyod = torg[1] - tdest[1];
7248   dxda = tdest[0] - tapex[0];
7249   dyda = tdest[1] - tapex[1];
7250   dxao = tapex[0] - torg[0];
7251   dyao = tapex[1] - torg[1];
7252   dxod2 = dxod * dxod;
7253   dyod2 = dyod * dyod;
7254   dxda2 = dxda * dxda;
7255   dyda2 = dyda * dyda;
7256   dxao2 = dxao * dxao;
7257   dyao2 = dyao * dyao;
7258   /* Find the lengths of the triangle's three edges. */
7259   apexlen = dxod2 + dyod2;
7260   orglen = dxda2 + dyda2;
7261   destlen = dxao2 + dyao2;
7262 
7263   if ((apexlen < orglen) && (apexlen < destlen)) {
7264     /* The edge opposite the apex is shortest. */
7265     minedge = apexlen;
7266     /* Find the square of the cosine of the angle at the apex. */
7267     angle = dxda * dxao + dyda * dyao;
7268     angle = angle * angle / (orglen * destlen);
7269     base1 = torg;
7270     base2 = tdest;
7271     otricopy(*testtri, tri1);
7272   } else if (orglen < destlen) {
7273     /* The edge opposite the origin is shortest. */
7274     minedge = orglen;
7275     /* Find the square of the cosine of the angle at the origin. */
7276     angle = dxod * dxao + dyod * dyao;
7277     angle = angle * angle / (apexlen * destlen);
7278     base1 = tdest;
7279     base2 = tapex;
7280     lnext(*testtri, tri1);
7281   } else {
7282     /* The edge opposite the destination is shortest. */
7283     minedge = destlen;
7284     /* Find the square of the cosine of the angle at the destination. */
7285     angle = dxod * dxda + dyod * dyda;
7286     angle = angle * angle / (apexlen * orglen);
7287     base1 = tapex;
7288     base2 = torg;
7289     lprev(*testtri, tri1);
7290   }
7291 
7292   if (b->vararea || b->fixedarea || b->usertest) {
7293     /* Check whether the area is larger than permitted. */
7294     area = 0.5 * (dxod * dyda - dyod * dxda);
7295     if (b->fixedarea && (area > b->maxarea)) {
7296       /* Add this triangle to the list of bad triangles. */
7297       enqueuebadtri(m, b, testtri, minedge, tapex, torg, tdest);
7298       return;
7299     }
7300 
7301     /* Nonpositive area constraints are treated as unconstrained. */
7302     if ((b->vararea) && (area > areabound(*testtri)) &&
7303         (areabound(*testtri) > 0.0)) {
7304       /* Add this triangle to the list of bad triangles. */
7305       enqueuebadtri(m, b, testtri, minedge, tapex, torg, tdest);
7306       return;
7307     }
7308 
7309     if (b->usertest) {
7310       /* Check whether the user thinks this triangle is too large. */
7311       if (triunsuitable(torg, tdest, tapex, area)) {
7312         enqueuebadtri(m, b, testtri, minedge, tapex, torg, tdest);
7313         return;
7314       }
7315     }
7316   }
7317 
7318   /* Check whether the angle is smaller than permitted. */
7319   if (angle > b->goodangle) {
7320     /* Use the rules of Miller, Pav, and Walkington to decide that certain */
7321     /*   triangles should not be split, even if they have bad angles.      */
7322     /*   A skinny triangle is not split if its shortest edge subtends a    */
7323     /*   small input angle, and both endpoints of the edge lie on a        */
7324     /*   concentric circular shell.  For convenience, I make a small       */
7325     /*   adjustment to that rule:  I check if the endpoints of the edge    */
7326     /*   both lie in segment interiors, equidistant from the apex where    */
7327     /*   the two segments meet.                                            */
7328     /* First, check if both points lie in segment interiors.               */
7329     if ((vertextype(base1) == SEGMENTVERTEX) &&
7330         (vertextype(base2) == SEGMENTVERTEX)) {
7331       /* Check if both points lie in a common segment.  If they do, the */
7332       /*   skinny triangle is enqueued to be split as usual.            */
7333       tspivot(tri1, testsub);
7334       if (testsub.ss == m->dummysub) {
7335         /* No common segment.  Find a subsegment that contains `torg'. */
7336         otricopy(tri1, tri2);
7337         do {
7338           oprevself(tri1);
7339           tspivot(tri1, testsub);
7340         } while (testsub.ss == m->dummysub);
7341         /* Find the endpoints of the containing segment. */
7342         segorg(testsub, org1);
7343         segdest(testsub, dest1);
7344         /* Find a subsegment that contains `tdest'. */
7345         do {
7346           dnextself(tri2);
7347           tspivot(tri2, testsub);
7348         } while (testsub.ss == m->dummysub);
7349         /* Find the endpoints of the containing segment. */
7350         segorg(testsub, org2);
7351         segdest(testsub, dest2);
7352         /* Check if the two containing segments have an endpoint in common. */
7353         joinvertex = (vertex) NULL;
7354         if ((dest1[0] == org2[0]) && (dest1[1] == org2[1])) {
7355           joinvertex = dest1;
7356         } else if ((org1[0] == dest2[0]) && (org1[1] == dest2[1])) {
7357           joinvertex = org1;
7358         }
7359         if (joinvertex != (vertex) NULL) {
7360           /* Compute the distance from the common endpoint (of the two  */
7361           /*   segments) to each of the endpoints of the shortest edge. */
7362           dist1 = ((base1[0] - joinvertex[0]) * (base1[0] - joinvertex[0]) +
7363                    (base1[1] - joinvertex[1]) * (base1[1] - joinvertex[1]));
7364           dist2 = ((base2[0] - joinvertex[0]) * (base2[0] - joinvertex[0]) +
7365                    (base2[1] - joinvertex[1]) * (base2[1] - joinvertex[1]));
7366           /* If the two distances are equal, don't split the triangle. */
7367           if ((dist1 < 1.001 * dist2) && (dist1 > 0.999 * dist2)) {
7368             /* Return now to avoid enqueueing the bad triangle. */
7369             return;
7370           }
7371         }
7372       }
7373     }
7374 
7375     /* Add this triangle to the list of bad triangles. */
7376     enqueuebadtri(m, b, testtri, minedge, tapex, torg, tdest);
7377   }
7378 }
7379 
7380 #endif /* not CDT_ONLY */
7381 
7382 /**                                                                         **/
7383 /**                                                                         **/
7384 /********* Mesh quality testing routines end here                    *********/
7385 
7386 /********* Point location routines begin here                        *********/
7387 /**                                                                         **/
7388 /**                                                                         **/
7389 
7390 /*****************************************************************************/
7391 /*                                                                           */
7392 /*  makevertexmap()   Construct a mapping from vertices to triangles to      */
7393 /*                    improve the speed of point location for segment        */
7394 /*                    insertion.                                             */
7395 /*                                                                           */
7396 /*  Traverses all the triangles, and provides each corner of each triangle   */
7397 /*  with a pointer to that triangle.  Of course, pointers will be            */
7398 /*  overwritten by other pointers because (almost) each vertex is a corner   */
7399 /*  of several triangles, but in the end every vertex will point to some     */
7400 /*  triangle that contains it.                                               */
7401 /*                                                                           */
7402 /*****************************************************************************/
7403 
7404 #ifdef ANSI_DECLARATORS
7405 void makevertexmap(struct mesh *m, struct behavior *b)
7406 #else /* not ANSI_DECLARATORS */
7407 void makevertexmap(m, b)
7408 struct mesh *m;
7409 struct behavior *b;
7410 #endif /* not ANSI_DECLARATORS */
7411 
7412 {
7413   struct otri triangleloop;
7414   vertex triorg;
7415 
7416   if (b->verbose) {
7417     printf("    Constructing mapping from vertices to triangles.\n");
7418   }
7419   traversalinit(&m->triangles);
7420   triangleloop.tri = triangletraverse(m);
7421   while (triangleloop.tri != (triangle *) NULL) {
7422     /* Check all three vertices of the triangle. */
7423     for (triangleloop.orient = 0; triangleloop.orient < 3;
7424          triangleloop.orient++) {
7425       org(triangleloop, triorg);
7426       setvertex2tri(triorg, encode(triangleloop));
7427     }
7428     triangleloop.tri = triangletraverse(m);
7429   }
7430 }
7431 
7432 /*****************************************************************************/
7433 /*                                                                           */
7434 /*  preciselocate()   Find a triangle or edge containing a given point.      */
7435 /*                                                                           */
7436 /*  Begins its search from `searchtri'.  It is important that `searchtri'    */
7437 /*  be a handle with the property that `searchpoint' is strictly to the left */
7438 /*  of the edge denoted by `searchtri', or is collinear with that edge and   */
7439 /*  does not intersect that edge.  (In particular, `searchpoint' should not  */
7440 /*  be the origin or destination of that edge.)                              */
7441 /*                                                                           */
7442 /*  These conditions are imposed because preciselocate() is normally used in */
7443 /*  one of two situations:                                                   */
7444 /*                                                                           */
7445 /*  (1)  To try to find the location to insert a new point.  Normally, we    */
7446 /*       know an edge that the point is strictly to the left of.  In the     */
7447 /*       incremental Delaunay algorithm, that edge is a bounding box edge.   */
7448 /*       In Ruppert's Delaunay refinement algorithm for quality meshing,     */
7449 /*       that edge is the shortest edge of the triangle whose circumcenter   */
7450 /*       is being inserted.                                                  */
7451 /*                                                                           */
7452 /*  (2)  To try to find an existing point.  In this case, any edge on the    */
7453 /*       convex hull is a good starting edge.  You must screen out the       */
7454 /*       possibility that the vertex sought is an endpoint of the starting   */
7455 /*       edge before you call preciselocate().                               */
7456 /*                                                                           */
7457 /*  On completion, `searchtri' is a triangle that contains `searchpoint'.    */
7458 /*                                                                           */
7459 /*  This implementation differs from that given by Guibas and Stolfi.  It    */
7460 /*  walks from triangle to triangle, crossing an edge only if `searchpoint'  */
7461 /*  is on the other side of the line containing that edge.  After entering   */
7462 /*  a triangle, there are two edges by which one can leave that triangle.    */
7463 /*  If both edges are valid (`searchpoint' is on the other side of both      */
7464 /*  edges), one of the two is chosen by drawing a line perpendicular to      */
7465 /*  the entry edge (whose endpoints are `forg' and `fdest') passing through  */
7466 /*  `fapex'.  Depending on which side of this perpendicular `searchpoint'    */
7467 /*  falls on, an exit edge is chosen.                                        */
7468 /*                                                                           */
7469 /*  This implementation is empirically faster than the Guibas and Stolfi     */
7470 /*  point location routine (which I originally used), which tends to spiral  */
7471 /*  in toward its target.                                                    */
7472 /*                                                                           */
7473 /*  Returns ONVERTEX if the point lies on an existing vertex.  `searchtri'   */
7474 /*  is a handle whose origin is the existing vertex.                         */
7475 /*                                                                           */
7476 /*  Returns ONEDGE if the point lies on a mesh edge.  `searchtri' is a       */
7477 /*  handle whose primary edge is the edge on which the point lies.           */
7478 /*                                                                           */
7479 /*  Returns INTRIANGLE if the point lies strictly within a triangle.         */
7480 /*  `searchtri' is a handle on the triangle that contains the point.         */
7481 /*                                                                           */
7482 /*  Returns OUTSIDE if the point lies outside the mesh.  `searchtri' is a    */
7483 /*  handle whose primary edge the point is to the right of.  This might      */
7484 /*  occur when the circumcenter of a triangle falls just slightly outside    */
7485 /*  the mesh due to floating-point roundoff error.  It also occurs when      */
7486 /*  seeking a hole or region point that a foolish user has placed outside    */
7487 /*  the mesh.                                                                */
7488 /*                                                                           */
7489 /*  If `stopatsubsegment' is nonzero, the search will stop if it tries to    */
7490 /*  walk through a subsegment, and will return OUTSIDE.                      */
7491 /*                                                                           */
7492 /*  WARNING:  This routine is designed for convex triangulations, and will   */
7493 /*  not generally work after the holes and concavities have been carved.     */
7494 /*  However, it can still be used to find the circumcenter of a triangle, as */
7495 /*  long as the search is begun from the triangle in question.               */
7496 /*                                                                           */
7497 /*****************************************************************************/
7498 
7499 #ifdef ANSI_DECLARATORS
7500 enum locateresult preciselocate(struct mesh *m, struct behavior *b,
7501                                 vertex searchpoint, struct otri *searchtri,
7502                                 int stopatsubsegment)
7503 #else /* not ANSI_DECLARATORS */
7504 enum locateresult preciselocate(m, b, searchpoint, searchtri, stopatsubsegment)
7505 struct mesh *m;
7506 struct behavior *b;
7507 vertex searchpoint;
7508 struct otri *searchtri;
7509 int stopatsubsegment;
7510 #endif /* not ANSI_DECLARATORS */
7511 
7512 {
7513   struct otri backtracktri;
7514   struct osub checkedge;
7515   vertex forg, fdest, fapex;
7516   REAL orgorient, destorient;
7517   int moveleft;
7518   triangle ptr;                         /* Temporary variable used by sym(). */
7519   subseg sptr;                      /* Temporary variable used by tspivot(). */
7520 
7521   if (b->verbose > 2) {
7522     printf("  Searching for point (%.12g, %.12g).\n",
7523            searchpoint[0], searchpoint[1]);
7524   }
7525   /* Where are we? */
7526   org(*searchtri, forg);
7527   dest(*searchtri, fdest);
7528   apex(*searchtri, fapex);
7529   while (1) {
7530     if (b->verbose > 2) {
7531       printf("    At (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
7532              forg[0], forg[1], fdest[0], fdest[1], fapex[0], fapex[1]);
7533     }
7534     /* Check whether the apex is the point we seek. */
7535     if ((fapex[0] == searchpoint[0]) && (fapex[1] == searchpoint[1])) {
7536       lprevself(*searchtri);
7537       return ONVERTEX;
7538     }
7539     /* Does the point lie on the other side of the line defined by the */
7540     /*   triangle edge opposite the triangle's destination?            */
7541     destorient = counterclockwise(m, b, forg, fapex, searchpoint);
7542     /* Does the point lie on the other side of the line defined by the */
7543     /*   triangle edge opposite the triangle's origin?                 */
7544     orgorient = counterclockwise(m, b, fapex, fdest, searchpoint);
7545     if (destorient > 0.0) {
7546       if (orgorient > 0.0) {
7547         /* Move left if the inner product of (fapex - searchpoint) and  */
7548         /*   (fdest - forg) is positive.  This is equivalent to drawing */
7549         /*   a line perpendicular to the line (forg, fdest) and passing */
7550         /*   through `fapex', and determining which side of this line   */
7551         /*   `searchpoint' falls on.                                    */
7552         moveleft = (fapex[0] - searchpoint[0]) * (fdest[0] - forg[0]) +
7553                    (fapex[1] - searchpoint[1]) * (fdest[1] - forg[1]) > 0.0;
7554       } else {
7555         moveleft = 1;
7556       }
7557     } else {
7558       if (orgorient > 0.0) {
7559         moveleft = 0;
7560       } else {
7561         /* The point we seek must be on the boundary of or inside this */
7562         /*   triangle.                                                 */
7563         if (destorient == 0.0) {
7564           lprevself(*searchtri);
7565           return ONEDGE;
7566         }
7567         if (orgorient == 0.0) {
7568           lnextself(*searchtri);
7569           return ONEDGE;
7570         }
7571         return INTRIANGLE;
7572       }
7573     }
7574 
7575     /* Move to another triangle.  Leave a trace `backtracktri' in case */
7576     /*   floating-point roundoff or some such bogey causes us to walk  */
7577     /*   off a boundary of the triangulation.                          */
7578     if (moveleft) {
7579       lprev(*searchtri, backtracktri);
7580       fdest = fapex;
7581     } else {
7582       lnext(*searchtri, backtracktri);
7583       forg = fapex;
7584     }
7585     sym(backtracktri, *searchtri);
7586 
7587     if (m->checksegments && stopatsubsegment) {
7588       /* Check for walking through a subsegment. */
7589       tspivot(backtracktri, checkedge);
7590       if (checkedge.ss != m->dummysub) {
7591         /* Go back to the last triangle. */
7592         otricopy(backtracktri, *searchtri);
7593         return OUTSIDE;
7594       }
7595     }
7596     /* Check for walking right out of the triangulation. */
7597     if (searchtri->tri == m->dummytri) {
7598       /* Go back to the last triangle. */
7599       otricopy(backtracktri, *searchtri);
7600       return OUTSIDE;
7601     }
7602 
7603     apex(*searchtri, fapex);
7604   }
7605 }
7606 
7607 /*****************************************************************************/
7608 /*                                                                           */
7609 /*  locate()   Find a triangle or edge containing a given point.             */
7610 /*                                                                           */
7611 /*  Searching begins from one of:  the input `searchtri', a recently         */
7612 /*  encountered triangle `recenttri', or from a triangle chosen from a       */
7613 /*  random sample.  The choice is made by determining which triangle's       */
7614 /*  origin is closest to the point we are searching for.  Normally,          */
7615 /*  `searchtri' should be a handle on the convex hull of the triangulation.  */
7616 /*                                                                           */
7617 /*  Details on the random sampling method can be found in the Mucke, Saias,  */
7618 /*  and Zhu paper cited in the header of this code.                          */
7619 /*                                                                           */
7620 /*  On completion, `searchtri' is a triangle that contains `searchpoint'.    */
7621 /*                                                                           */
7622 /*  Returns ONVERTEX if the point lies on an existing vertex.  `searchtri'   */
7623 /*  is a handle whose origin is the existing vertex.                         */
7624 /*                                                                           */
7625 /*  Returns ONEDGE if the point lies on a mesh edge.  `searchtri' is a       */
7626 /*  handle whose primary edge is the edge on which the point lies.           */
7627 /*                                                                           */
7628 /*  Returns INTRIANGLE if the point lies strictly within a triangle.         */
7629 /*  `searchtri' is a handle on the triangle that contains the point.         */
7630 /*                                                                           */
7631 /*  Returns OUTSIDE if the point lies outside the mesh.  `searchtri' is a    */
7632 /*  handle whose primary edge the point is to the right of.  This might      */
7633 /*  occur when the circumcenter of a triangle falls just slightly outside    */
7634 /*  the mesh due to floating-point roundoff error.  It also occurs when      */
7635 /*  seeking a hole or region point that a foolish user has placed outside    */
7636 /*  the mesh.                                                                */
7637 /*                                                                           */
7638 /*  WARNING:  This routine is designed for convex triangulations, and will   */
7639 /*  not generally work after the holes and concavities have been carved.     */
7640 /*                                                                           */
7641 /*****************************************************************************/
7642 
7643 #ifdef ANSI_DECLARATORS
7644 enum locateresult locate(struct mesh *m, struct behavior *b,
7645                          vertex searchpoint, struct otri *searchtri)
7646 #else /* not ANSI_DECLARATORS */
7647 enum locateresult locate(m, b, searchpoint, searchtri)
7648 struct mesh *m;
7649 struct behavior *b;
7650 vertex searchpoint;
7651 struct otri *searchtri;
7652 #endif /* not ANSI_DECLARATORS */
7653 
7654 {
7655   void **sampleblock;
7656   char *firsttri;
7657   struct otri sampletri;
7658   vertex torg, tdest;
7659   TRIANGLE_PTRINT alignptr;
7660   REAL searchdist, dist;
7661   REAL ahead;
7662   long samplesperblock, totalsamplesleft, samplesleft;
7663   long population, totalpopulation;
7664   triangle ptr;                         /* Temporary variable used by sym(). */
7665 
7666   if (b->verbose > 2) {
7667     printf("  Randomly sampling for a triangle near point (%.12g, %.12g).\n",
7668            searchpoint[0], searchpoint[1]);
7669   }
7670   /* Record the distance from the suggested starting triangle to the */
7671   /*   point we seek.                                                */
7672   org(*searchtri, torg);
7673   searchdist = (searchpoint[0] - torg[0]) * (searchpoint[0] - torg[0]) +
7674                (searchpoint[1] - torg[1]) * (searchpoint[1] - torg[1]);
7675   if (b->verbose > 2) {
7676     printf("    Boundary triangle has origin (%.12g, %.12g).\n",
7677            torg[0], torg[1]);
7678   }
7679 
7680   /* If a recently encountered triangle has been recorded and has not been */
7681   /*   deallocated, test it as a good starting point.                      */
7682   if (m->recenttri.tri != (triangle *) NULL) {
7683     if (!deadtri(m->recenttri.tri)) {
7684       org(m->recenttri, torg);
7685       if ((torg[0] == searchpoint[0]) && (torg[1] == searchpoint[1])) {
7686         otricopy(m->recenttri, *searchtri);
7687         return ONVERTEX;
7688       }
7689       dist = (searchpoint[0] - torg[0]) * (searchpoint[0] - torg[0]) +
7690              (searchpoint[1] - torg[1]) * (searchpoint[1] - torg[1]);
7691       if (dist < searchdist) {
7692         otricopy(m->recenttri, *searchtri);
7693         searchdist = dist;
7694         if (b->verbose > 2) {
7695           printf("    Choosing recent triangle with origin (%.12g, %.12g).\n",
7696                  torg[0], torg[1]);
7697         }
7698       }
7699     }
7700   }
7701 
7702   /* The number of random samples taken is proportional to the cube root of */
7703   /*   the number of triangles in the mesh.  The next bit of code assumes   */
7704   /*   that the number of triangles increases monotonically (or at least    */
7705   /*   doesn't decrease enough to matter).                                  */
7706   while (SAMPLEFACTOR * m->samples * m->samples * m->samples <
7707          m->triangles.items) {
7708     m->samples++;
7709   }
7710 
7711   /* We'll draw ceiling(samples * TRIPERBLOCK / maxitems) random samples  */
7712   /*   from each block of triangles (except the first)--until we meet the */
7713   /*   sample quota.  The ceiling means that blocks at the end might be   */
7714   /*   neglected, but I don't care.                                       */
7715   samplesperblock = (m->samples * TRIPERBLOCK - 1) / m->triangles.maxitems + 1;
7716   /* We'll draw ceiling(samples * itemsfirstblock / maxitems) random samples */
7717   /*   from the first block of triangles.                                    */
7718   samplesleft = (m->samples * m->triangles.itemsfirstblock - 1) /
7719                 m->triangles.maxitems + 1;
7720   totalsamplesleft = m->samples;
7721   population = m->triangles.itemsfirstblock;
7722   totalpopulation = m->triangles.maxitems;
7723   sampleblock = m->triangles.firstblock;
7724   sampletri.orient = 0;
7725   while (totalsamplesleft > 0) {
7726     /* If we're in the last block, `population' needs to be corrected. */
7727     if (population > totalpopulation) {
7728       population = totalpopulation;
7729     }
7730     /* Find a pointer to the first triangle in the block. */
7731     alignptr = (TRIANGLE_PTRINT) (sampleblock + 1);
7732     firsttri = (char *) (alignptr +
7733                          (TRIANGLE_PTRINT) m->triangles.alignbytes -
7734                          (alignptr %
7735                           (TRIANGLE_PTRINT) m->triangles.alignbytes));
7736 
7737     /* Choose `samplesleft' randomly sampled triangles in this block. */
7738     do {
7739       sampletri.tri = (triangle *) (firsttri +
7740                                     (randomnation((unsigned int) population) *
7741                                      m->triangles.itembytes));
7742       if (!deadtri(sampletri.tri)) {
7743         org(sampletri, torg);
7744         dist = (searchpoint[0] - torg[0]) * (searchpoint[0] - torg[0]) +
7745                (searchpoint[1] - torg[1]) * (searchpoint[1] - torg[1]);
7746         if (dist < searchdist) {
7747           otricopy(sampletri, *searchtri);
7748           searchdist = dist;
7749           if (b->verbose > 2) {
7750             printf("    Choosing triangle with origin (%.12g, %.12g).\n",
7751                    torg[0], torg[1]);
7752           }
7753         }
7754       }
7755 
7756       samplesleft--;
7757       totalsamplesleft--;
7758     } while ((samplesleft > 0) && (totalsamplesleft > 0));
7759 
7760     if (totalsamplesleft > 0) {
7761       sampleblock = (void **) *sampleblock;
7762       samplesleft = samplesperblock;
7763       totalpopulation -= population;
7764       population = TRIPERBLOCK;
7765     }
7766   }
7767 
7768   /* Where are we? */
7769   org(*searchtri, torg);
7770   dest(*searchtri, tdest);
7771   /* Check the starting triangle's vertices. */
7772   if ((torg[0] == searchpoint[0]) && (torg[1] == searchpoint[1])) {
7773     return ONVERTEX;
7774   }
7775   if ((tdest[0] == searchpoint[0]) && (tdest[1] == searchpoint[1])) {
7776     lnextself(*searchtri);
7777     return ONVERTEX;
7778   }
7779   /* Orient `searchtri' to fit the preconditions of calling preciselocate(). */
7780   ahead = counterclockwise(m, b, torg, tdest, searchpoint);
7781   if (ahead < 0.0) {
7782     /* Turn around so that `searchpoint' is to the left of the */
7783     /*   edge specified by `searchtri'.                        */
7784     symself(*searchtri);
7785   } else if (ahead == 0.0) {
7786     /* Check if `searchpoint' is between `torg' and `tdest'. */
7787     if (((torg[0] < searchpoint[0]) == (searchpoint[0] < tdest[0])) &&
7788         ((torg[1] < searchpoint[1]) == (searchpoint[1] < tdest[1]))) {
7789       return ONEDGE;
7790     }
7791   }
7792   return preciselocate(m, b, searchpoint, searchtri, 0);
7793 }
7794 
7795 /**                                                                         **/
7796 /**                                                                         **/
7797 /********* Point location routines end here                          *********/
7798 
7799 /********* Mesh transformation routines begin here                   *********/
7800 /**                                                                         **/
7801 /**                                                                         **/
7802 
7803 /*****************************************************************************/
7804 /*                                                                           */
7805 /*  insertsubseg()   Create a new subsegment and insert it between two       */
7806 /*                   triangles.                                              */
7807 /*                                                                           */
7808 /*  The new subsegment is inserted at the edge described by the handle       */
7809 /*  `tri'.  Its vertices are properly initialized.  The marker `subsegmark'  */
7810 /*  is applied to the subsegment and, if appropriate, its vertices.          */
7811 /*                                                                           */
7812 /*****************************************************************************/
7813 
7814 #ifdef ANSI_DECLARATORS
7815 void insertsubseg(struct mesh *m, struct behavior *b, struct otri *tri,
7816                   int subsegmark)
7817 #else /* not ANSI_DECLARATORS */
7818 void insertsubseg(m, b, tri, subsegmark)
7819 struct mesh *m;
7820 struct behavior *b;
7821 struct otri *tri;             /* Edge at which to insert the new subsegment. */
7822 int subsegmark;                            /* Marker for the new subsegment. */
7823 #endif /* not ANSI_DECLARATORS */
7824 
7825 {
7826   struct otri oppotri;
7827   struct osub newsubseg;
7828   vertex triorg, tridest;
7829   triangle ptr;                         /* Temporary variable used by sym(). */
7830   subseg sptr;                      /* Temporary variable used by tspivot(). */
7831 
7832   org(*tri, triorg);
7833   dest(*tri, tridest);
7834   /* Mark vertices if possible. */
7835   if (vertexmark(triorg) == 0) {
7836     setvertexmark(triorg, subsegmark);
7837   }
7838   if (vertexmark(tridest) == 0) {
7839     setvertexmark(tridest, subsegmark);
7840   }
7841   /* Check if there's already a subsegment here. */
7842   tspivot(*tri, newsubseg);
7843   if (newsubseg.ss == m->dummysub) {
7844     /* Make new subsegment and initialize its vertices. */
7845     makesubseg(m, &newsubseg);
7846     setsorg(newsubseg, tridest);
7847     setsdest(newsubseg, triorg);
7848     setsegorg(newsubseg, tridest);
7849     setsegdest(newsubseg, triorg);
7850     /* Bond new subsegment to the two triangles it is sandwiched between. */
7851     /*   Note that the facing triangle `oppotri' might be equal to        */
7852     /*   `dummytri' (outer space), but the new subsegment is bonded to it */
7853     /*   all the same.                                                    */
7854     tsbond(*tri, newsubseg);
7855     sym(*tri, oppotri);
7856     ssymself(newsubseg);
7857     tsbond(oppotri, newsubseg);
7858     setmark(newsubseg, subsegmark);
7859     if (b->verbose > 2) {
7860       printf("  Inserting new ");
7861       printsubseg(m, b, &newsubseg);
7862     }
7863   } else {
7864     if (mark(newsubseg) == 0) {
7865       setmark(newsubseg, subsegmark);
7866     }
7867   }
7868 }
7869 
7870 /*****************************************************************************/
7871 /*                                                                           */
7872 /*  Terminology                                                              */
7873 /*                                                                           */
7874 /*  A "local transformation" replaces a small set of triangles with another  */
7875 /*  set of triangles.  This may or may not involve inserting or deleting a   */
7876 /*  vertex.                                                                  */
7877 /*                                                                           */
7878 /*  The term "casing" is used to describe the set of triangles that are      */
7879 /*  attached to the triangles being transformed, but are not transformed     */
7880 /*  themselves.  Think of the casing as a fixed hollow structure inside      */
7881 /*  which all the action happens.  A "casing" is only defined relative to    */
7882 /*  a single transformation; each occurrence of a transformation will        */
7883 /*  involve a different casing.                                              */
7884 /*                                                                           */
7885 /*****************************************************************************/
7886 
7887 /*****************************************************************************/
7888 /*                                                                           */
7889 /*  flip()   Transform two triangles to two different triangles by flipping  */
7890 /*           an edge counterclockwise within a quadrilateral.                */
7891 /*                                                                           */
7892 /*  Imagine the original triangles, abc and bad, oriented so that the        */
7893 /*  shared edge ab lies in a horizontal plane, with the vertex b on the left */
7894 /*  and the vertex a on the right.  The vertex c lies below the edge, and    */
7895 /*  the vertex d lies above the edge.  The `flipedge' handle holds the edge  */
7896 /*  ab of triangle abc, and is directed left, from vertex a to vertex b.     */
7897 /*                                                                           */
7898 /*  The triangles abc and bad are deleted and replaced by the triangles cdb  */
7899 /*  and dca.  The triangles that represent abc and bad are NOT deallocated;  */
7900 /*  they are reused for dca and cdb, respectively.  Hence, any handles that  */
7901 /*  may have held the original triangles are still valid, although not       */
7902 /*  directed as they were before.                                            */
7903 /*                                                                           */
7904 /*  Upon completion of this routine, the `flipedge' handle holds the edge    */
7905 /*  dc of triangle dca, and is directed down, from vertex d to vertex c.     */
7906 /*  (Hence, the two triangles have rotated counterclockwise.)                */
7907 /*                                                                           */
7908 /*  WARNING:  This transformation is geometrically valid only if the         */
7909 /*  quadrilateral adbc is convex.  Furthermore, this transformation is       */
7910 /*  valid only if there is not a subsegment between the triangles abc and    */
7911 /*  bad.  This routine does not check either of these preconditions, and     */
7912 /*  it is the responsibility of the calling routine to ensure that they are  */
7913 /*  met.  If they are not, the streets shall be filled with wailing and      */
7914 /*  gnashing of teeth.                                                       */
7915 /*                                                                           */
7916 /*****************************************************************************/
7917 
7918 #ifdef ANSI_DECLARATORS
7919 void flip(struct mesh *m, struct behavior *b, struct otri *flipedge)
7920 #else /* not ANSI_DECLARATORS */
7921 void flip(m, b, flipedge)
7922 struct mesh *m;
7923 struct behavior *b;
7924 struct otri *flipedge;                    /* Handle for the triangle abc. */
7925 #endif /* not ANSI_DECLARATORS */
7926 
7927 {
7928   struct otri botleft, botright;
7929   struct otri topleft, topright;
7930   struct otri top;
7931   struct otri botlcasing, botrcasing;
7932   struct otri toplcasing, toprcasing;
7933   struct osub botlsubseg, botrsubseg;
7934   struct osub toplsubseg, toprsubseg;
7935   vertex leftvertex, rightvertex, botvertex;
7936   vertex farvertex;
7937   triangle ptr;                         /* Temporary variable used by sym(). */
7938   subseg sptr;                      /* Temporary variable used by tspivot(). */
7939 
7940   /* Identify the vertices of the quadrilateral. */
7941   org(*flipedge, rightvertex);
7942   dest(*flipedge, leftvertex);
7943   apex(*flipedge, botvertex);
7944   sym(*flipedge, top);
7945 #ifdef SELF_CHECK
7946   if (top.tri == m->dummytri) {
7947     printf("Internal error in flip():  Attempt to flip on boundary.\n");
7948     lnextself(*flipedge);
7949     return;
7950   }
7951   if (m->checksegments) {
7952     tspivot(*flipedge, toplsubseg);
7953     if (toplsubseg.ss != m->dummysub) {
7954       printf("Internal error in flip():  Attempt to flip a segment.\n");
7955       lnextself(*flipedge);
7956       return;
7957     }
7958   }
7959 #endif /* SELF_CHECK */
7960   apex(top, farvertex);
7961 
7962   /* Identify the casing of the quadrilateral. */
7963   lprev(top, topleft);
7964   sym(topleft, toplcasing);
7965   lnext(top, topright);
7966   sym(topright, toprcasing);
7967   lnext(*flipedge, botleft);
7968   sym(botleft, botlcasing);
7969   lprev(*flipedge, botright);
7970   sym(botright, botrcasing);
7971   /* Rotate the quadrilateral one-quarter turn counterclockwise. */
7972   bond(topleft, botlcasing);
7973   bond(botleft, botrcasing);
7974   bond(botright, toprcasing);
7975   bond(topright, toplcasing);
7976 
7977   if (m->checksegments) {
7978     /* Check for subsegments and rebond them to the quadrilateral. */
7979     tspivot(topleft, toplsubseg);
7980     tspivot(botleft, botlsubseg);
7981     tspivot(botright, botrsubseg);
7982     tspivot(topright, toprsubseg);
7983     if (toplsubseg.ss == m->dummysub) {
7984       tsdissolve(topright);
7985     } else {
7986       tsbond(topright, toplsubseg);
7987     }
7988     if (botlsubseg.ss == m->dummysub) {
7989       tsdissolve(topleft);
7990     } else {
7991       tsbond(topleft, botlsubseg);
7992     }
7993     if (botrsubseg.ss == m->dummysub) {
7994       tsdissolve(botleft);
7995     } else {
7996       tsbond(botleft, botrsubseg);
7997     }
7998     if (toprsubseg.ss == m->dummysub) {
7999       tsdissolve(botright);
8000     } else {
8001       tsbond(botright, toprsubseg);
8002     }
8003   }
8004 
8005   /* New vertex assignments for the rotated quadrilateral. */
8006   setorg(*flipedge, farvertex);
8007   setdest(*flipedge, botvertex);
8008   setapex(*flipedge, rightvertex);
8009   setorg(top, botvertex);
8010   setdest(top, farvertex);
8011   setapex(top, leftvertex);
8012   if (b->verbose > 2) {
8013     printf("  Edge flip results in left ");
8014     printtriangle(m, b, &top);
8015     printf("  and right ");
8016     printtriangle(m, b, flipedge);
8017   }
8018 }
8019 
8020 /*****************************************************************************/
8021 /*                                                                           */
8022 /*  unflip()   Transform two triangles to two different triangles by         */
8023 /*             flipping an edge clockwise within a quadrilateral.  Reverses  */
8024 /*             the flip() operation so that the data structures representing */
8025 /*             the triangles are back where they were before the flip().     */
8026 /*                                                                           */
8027 /*  Imagine the original triangles, abc and bad, oriented so that the        */
8028 /*  shared edge ab lies in a horizontal plane, with the vertex b on the left */
8029 /*  and the vertex a on the right.  The vertex c lies below the edge, and    */
8030 /*  the vertex d lies above the edge.  The `flipedge' handle holds the edge  */
8031 /*  ab of triangle abc, and is directed left, from vertex a to vertex b.     */
8032 /*                                                                           */
8033 /*  The triangles abc and bad are deleted and replaced by the triangles cdb  */
8034 /*  and dca.  The triangles that represent abc and bad are NOT deallocated;  */
8035 /*  they are reused for cdb and dca, respectively.  Hence, any handles that  */
8036 /*  may have held the original triangles are still valid, although not       */
8037 /*  directed as they were before.                                            */
8038 /*                                                                           */
8039 /*  Upon completion of this routine, the `flipedge' handle holds the edge    */
8040 /*  cd of triangle cdb, and is directed up, from vertex c to vertex d.       */
8041 /*  (Hence, the two triangles have rotated clockwise.)                       */
8042 /*                                                                           */
8043 /*  WARNING:  This transformation is geometrically valid only if the         */
8044 /*  quadrilateral adbc is convex.  Furthermore, this transformation is       */
8045 /*  valid only if there is not a subsegment between the triangles abc and    */
8046 /*  bad.  This routine does not check either of these preconditions, and     */
8047 /*  it is the responsibility of the calling routine to ensure that they are  */
8048 /*  met.  If they are not, the streets shall be filled with wailing and      */
8049 /*  gnashing of teeth.                                                       */
8050 /*                                                                           */
8051 /*****************************************************************************/
8052 
8053 #ifdef ANSI_DECLARATORS
8054 void unflip(struct mesh *m, struct behavior *b, struct otri *flipedge)
8055 #else /* not ANSI_DECLARATORS */
8056 void unflip(m, b, flipedge)
8057 struct mesh *m;
8058 struct behavior *b;
8059 struct otri *flipedge;                    /* Handle for the triangle abc. */
8060 #endif /* not ANSI_DECLARATORS */
8061 
8062 {
8063   struct otri botleft, botright;
8064   struct otri topleft, topright;
8065   struct otri top;
8066   struct otri botlcasing, botrcasing;
8067   struct otri toplcasing, toprcasing;
8068   struct osub botlsubseg, botrsubseg;
8069   struct osub toplsubseg, toprsubseg;
8070   vertex leftvertex, rightvertex, botvertex;
8071   vertex farvertex;
8072   triangle ptr;                         /* Temporary variable used by sym(). */
8073   subseg sptr;                      /* Temporary variable used by tspivot(). */
8074 
8075   /* Identify the vertices of the quadrilateral. */
8076   org(*flipedge, rightvertex);
8077   dest(*flipedge, leftvertex);
8078   apex(*flipedge, botvertex);
8079   sym(*flipedge, top);
8080 #ifdef SELF_CHECK
8081   if (top.tri == m->dummytri) {
8082     printf("Internal error in unflip():  Attempt to flip on boundary.\n");
8083     lnextself(*flipedge);
8084     return;
8085   }
8086   if (m->checksegments) {
8087     tspivot(*flipedge, toplsubseg);
8088     if (toplsubseg.ss != m->dummysub) {
8089       printf("Internal error in unflip():  Attempt to flip a subsegment.\n");
8090       lnextself(*flipedge);
8091       return;
8092     }
8093   }
8094 #endif /* SELF_CHECK */
8095   apex(top, farvertex);
8096 
8097   /* Identify the casing of the quadrilateral. */
8098   lprev(top, topleft);
8099   sym(topleft, toplcasing);
8100   lnext(top, topright);
8101   sym(topright, toprcasing);
8102   lnext(*flipedge, botleft);
8103   sym(botleft, botlcasing);
8104   lprev(*flipedge, botright);
8105   sym(botright, botrcasing);
8106   /* Rotate the quadrilateral one-quarter turn clockwise. */
8107   bond(topleft, toprcasing);
8108   bond(botleft, toplcasing);
8109   bond(botright, botlcasing);
8110   bond(topright, botrcasing);
8111 
8112   if (m->checksegments) {
8113     /* Check for subsegments and rebond them to the quadrilateral. */
8114     tspivot(topleft, toplsubseg);
8115     tspivot(botleft, botlsubseg);
8116     tspivot(botright, botrsubseg);
8117     tspivot(topright, toprsubseg);
8118     if (toplsubseg.ss == m->dummysub) {
8119       tsdissolve(botleft);
8120     } else {
8121       tsbond(botleft, toplsubseg);
8122     }
8123     if (botlsubseg.ss == m->dummysub) {
8124       tsdissolve(botright);
8125     } else {
8126       tsbond(botright, botlsubseg);
8127     }
8128     if (botrsubseg.ss == m->dummysub) {
8129       tsdissolve(topright);
8130     } else {
8131       tsbond(topright, botrsubseg);
8132     }
8133     if (toprsubseg.ss == m->dummysub) {
8134       tsdissolve(topleft);
8135     } else {
8136       tsbond(topleft, toprsubseg);
8137     }
8138   }
8139 
8140   /* New vertex assignments for the rotated quadrilateral. */
8141   setorg(*flipedge, botvertex);
8142   setdest(*flipedge, farvertex);
8143   setapex(*flipedge, leftvertex);
8144   setorg(top, farvertex);
8145   setdest(top, botvertex);
8146   setapex(top, rightvertex);
8147   if (b->verbose > 2) {
8148     printf("  Edge unflip results in left ");
8149     printtriangle(m, b, flipedge);
8150     printf("  and right ");
8151     printtriangle(m, b, &top);
8152   }
8153 }
8154 
8155 /*****************************************************************************/
8156 /*                                                                           */
8157 /*  insertvertex()   Insert a vertex into a Delaunay triangulation,          */
8158 /*                   performing flips as necessary to maintain the Delaunay  */
8159 /*                   property.                                               */
8160 /*                                                                           */
8161 /*  The point `insertvertex' is located.  If `searchtri.tri' is not NULL,    */
8162 /*  the search for the containing triangle begins from `searchtri'.  If      */
8163 /*  `searchtri.tri' is NULL, a full point location procedure is called.      */
8164 /*  If `insertvertex' is found inside a triangle, the triangle is split into */
8165 /*  three; if `insertvertex' lies on an edge, the edge is split in two,      */
8166 /*  thereby splitting the two adjacent triangles into four.  Edge flips are  */
8167 /*  used to restore the Delaunay property.  If `insertvertex' lies on an     */
8168 /*  existing vertex, no action is taken, and the value DUPLICATEVERTEX is    */
8169 /*  returned.  On return, `searchtri' is set to a handle whose origin is the */
8170 /*  existing vertex.                                                         */
8171 /*                                                                           */
8172 /*  Normally, the parameter `splitseg' is set to NULL, implying that no      */
8173 /*  subsegment should be split.  In this case, if `insertvertex' is found to */
8174 /*  lie on a segment, no action is taken, and the value VIOLATINGVERTEX is   */
8175 /*  returned.  On return, `searchtri' is set to a handle whose primary edge  */
8176 /*  is the violated subsegment.                                              */
8177 /*                                                                           */
8178 /*  If the calling routine wishes to split a subsegment by inserting a       */
8179 /*  vertex in it, the parameter `splitseg' should be that subsegment.  In    */
8180 /*  this case, `searchtri' MUST be the triangle handle reached by pivoting   */
8181 /*  from that subsegment; no point location is done.                         */
8182 /*                                                                           */
8183 /*  `segmentflaws' and `triflaws' are flags that indicate whether or not     */
8184 /*  there should be checks for the creation of encroached subsegments or bad */
8185 /*  quality triangles.  If a newly inserted vertex encroaches upon           */
8186 /*  subsegments, these subsegments are added to the list of subsegments to   */
8187 /*  be split if `segmentflaws' is set.  If bad triangles are created, these  */
8188 /*  are added to the queue if `triflaws' is set.                             */
8189 /*                                                                           */
8190 /*  If a duplicate vertex or violated segment does not prevent the vertex    */
8191 /*  from being inserted, the return value will be ENCROACHINGVERTEX if the   */
8192 /*  vertex encroaches upon a subsegment (and checking is enabled), or        */
8193 /*  SUCCESSFULVERTEX otherwise.  In either case, `searchtri' is set to a     */
8194 /*  handle whose origin is the newly inserted vertex.                        */
8195 /*                                                                           */
8196 /*  insertvertex() does not use flip() for reasons of speed; some            */
8197 /*  information can be reused from edge flip to edge flip, like the          */
8198 /*  locations of subsegments.                                                */
8199 /*                                                                           */
8200 /*****************************************************************************/
8201 
8202 #ifdef ANSI_DECLARATORS
8203 enum insertvertexresult insertvertex(struct mesh *m, struct behavior *b,
8204                                      vertex newvertex, struct otri *searchtri,
8205                                      struct osub *splitseg,
8206                                      int segmentflaws, int triflaws)
8207 #else /* not ANSI_DECLARATORS */
8208 enum insertvertexresult insertvertex(m, b, newvertex, searchtri, splitseg,
8209                                      segmentflaws, triflaws)
8210 struct mesh *m;
8211 struct behavior *b;
8212 vertex newvertex;
8213 struct otri *searchtri;
8214 struct osub *splitseg;
8215 int segmentflaws;
8216 int triflaws;
8217 #endif /* not ANSI_DECLARATORS */
8218 
8219 {
8220   struct otri horiz;
8221   struct otri top;
8222   struct otri botleft, botright;
8223   struct otri topleft, topright;
8224   struct otri newbotleft, newbotright;
8225   struct otri newtopright;
8226   struct otri botlcasing, botrcasing;
8227   struct otri toplcasing, toprcasing;
8228   struct otri testtri;
8229   struct osub botlsubseg, botrsubseg;
8230   struct osub toplsubseg, toprsubseg;
8231   struct osub brokensubseg;
8232   struct osub checksubseg;
8233   struct osub rightsubseg;
8234   struct osub newsubseg;
8235   struct badsubseg *encroached;
8236   struct flipstacker *newflip;
8237   vertex first;
8238   vertex leftvertex, rightvertex, botvertex, topvertex, farvertex;
8239   vertex segmentorg, segmentdest;
8240   REAL attrib;
8241   REAL area;
8242   enum insertvertexresult success;
8243   enum locateresult intersect;
8244   int doflip;
8245   int mirrorflag;
8246   int enq;
8247   int i;
8248   triangle ptr;                         /* Temporary variable used by sym(). */
8249   subseg sptr;         /* Temporary variable used by spivot() and tspivot(). */
8250 
8251   if (b->verbose > 1) {
8252     printf("  Inserting (%.12g, %.12g).\n", newvertex[0], newvertex[1]);
8253   }
8254 
8255   if (splitseg == (struct osub *) NULL) {
8256     /* Find the location of the vertex to be inserted.  Check if a good */
8257     /*   starting triangle has already been provided by the caller.     */
8258     if (searchtri->tri == m->dummytri) {
8259       /* Find a boundary triangle. */
8260       horiz.tri = m->dummytri;
8261       horiz.orient = 0;
8262       symself(horiz);
8263       /* Search for a triangle containing `newvertex'. */
8264       intersect = locate(m, b, newvertex, &horiz);
8265     } else {
8266       /* Start searching from the triangle provided by the caller. */
8267       otricopy(*searchtri, horiz);
8268       intersect = preciselocate(m, b, newvertex, &horiz, 1);
8269     }
8270   } else {
8271     /* The calling routine provides the subsegment in which */
8272     /*   the vertex is inserted.                             */
8273     otricopy(*searchtri, horiz);
8274     intersect = ONEDGE;
8275   }
8276 
8277   if (intersect == ONVERTEX) {
8278     /* There's already a vertex there.  Return in `searchtri' a triangle */
8279     /*   whose origin is the existing vertex.                            */
8280     otricopy(horiz, *searchtri);
8281     otricopy(horiz, m->recenttri);
8282     return DUPLICATEVERTEX;
8283   }
8284   if ((intersect == ONEDGE) || (intersect == OUTSIDE)) {
8285     /* The vertex falls on an edge or boundary. */
8286     if (m->checksegments && (splitseg == (struct osub *) NULL)) {
8287       /* Check whether the vertex falls on a subsegment. */
8288       tspivot(horiz, brokensubseg);
8289       if (brokensubseg.ss != m->dummysub) {
8290         /* The vertex falls on a subsegment, and hence will not be inserted. */
8291         if (segmentflaws) {
8292           enq = b->nobisect != 2;
8293           if (enq && (b->nobisect == 1)) {
8294             /* This subsegment may be split only if it is an */
8295             /*   internal boundary.                          */
8296             sym(horiz, testtri);
8297             enq = testtri.tri != m->dummytri;
8298           }
8299           if (enq) {
8300             /* Add the subsegment to the list of encroached subsegments. */
8301             encroached = (struct badsubseg *) poolalloc(&m->badsubsegs);
8302             encroached->encsubseg = sencode(brokensubseg);
8303             sorg(brokensubseg, encroached->subsegorg);
8304             sdest(brokensubseg, encroached->subsegdest);
8305             if (b->verbose > 2) {
8306               printf(
8307           "  Queueing encroached subsegment (%.12g, %.12g) (%.12g, %.12g).\n",
8308                      encroached->subsegorg[0], encroached->subsegorg[1],
8309                      encroached->subsegdest[0], encroached->subsegdest[1]);
8310             }
8311           }
8312         }
8313         /* Return a handle whose primary edge contains the vertex, */
8314         /*   which has not been inserted.                          */
8315         otricopy(horiz, *searchtri);
8316         otricopy(horiz, m->recenttri);
8317         return VIOLATINGVERTEX;
8318       }
8319     }
8320 
8321     /* Insert the vertex on an edge, dividing one triangle into two (if */
8322     /*   the edge lies on a boundary) or two triangles into four.       */
8323     lprev(horiz, botright);
8324     sym(botright, botrcasing);
8325     sym(horiz, topright);
8326     /* Is there a second triangle?  (Or does this edge lie on a boundary?) */
8327     mirrorflag = topright.tri != m->dummytri;
8328     if (mirrorflag) {
8329       lnextself(topright);
8330       sym(topright, toprcasing);
8331       maketriangle(m, b, &newtopright);
8332     } else {
8333       /* Splitting a boundary edge increases the number of boundary edges. */
8334       m->hullsize++;
8335     }
8336     maketriangle(m, b, &newbotright);
8337 
8338     /* Set the vertices of changed and new triangles. */
8339     org(horiz, rightvertex);
8340     dest(horiz, leftvertex);
8341     apex(horiz, botvertex);
8342     setorg(newbotright, botvertex);
8343     setdest(newbotright, rightvertex);
8344     setapex(newbotright, newvertex);
8345     setorg(horiz, newvertex);
8346     for (i = 0; i < m->eextras; i++) {
8347       /* Set the element attributes of a new triangle. */
8348       setelemattribute(newbotright, i, elemattribute(botright, i));
8349     }
8350     if (b->vararea) {
8351       /* Set the area constraint of a new triangle. */
8352       setareabound(newbotright, areabound(botright));
8353     }
8354     if (mirrorflag) {
8355       dest(topright, topvertex);
8356       setorg(newtopright, rightvertex);
8357       setdest(newtopright, topvertex);
8358       setapex(newtopright, newvertex);
8359       setorg(topright, newvertex);
8360       for (i = 0; i < m->eextras; i++) {
8361         /* Set the element attributes of another new triangle. */
8362         setelemattribute(newtopright, i, elemattribute(topright, i));
8363       }
8364       if (b->vararea) {
8365         /* Set the area constraint of another new triangle. */
8366         setareabound(newtopright, areabound(topright));
8367       }
8368     }
8369 
8370     /* There may be subsegments that need to be bonded */
8371     /*   to the new triangle(s).                       */
8372     if (m->checksegments) {
8373       tspivot(botright, botrsubseg);
8374       if (botrsubseg.ss != m->dummysub) {
8375         tsdissolve(botright);
8376         tsbond(newbotright, botrsubseg);
8377       }
8378       if (mirrorflag) {
8379         tspivot(topright, toprsubseg);
8380         if (toprsubseg.ss != m->dummysub) {
8381           tsdissolve(topright);
8382           tsbond(newtopright, toprsubseg);
8383         }
8384       }
8385     }
8386 
8387     /* Bond the new triangle(s) to the surrounding triangles. */
8388     bond(newbotright, botrcasing);
8389     lprevself(newbotright);
8390     bond(newbotright, botright);
8391     lprevself(newbotright);
8392     if (mirrorflag) {
8393       bond(newtopright, toprcasing);
8394       lnextself(newtopright);
8395       bond(newtopright, topright);
8396       lnextself(newtopright);
8397       bond(newtopright, newbotright);
8398     }
8399 
8400     if (splitseg != (struct osub *) NULL) {
8401       /* Split the subsegment into two. */
8402       setsdest(*splitseg, newvertex);
8403       segorg(*splitseg, segmentorg);
8404       segdest(*splitseg, segmentdest);
8405       ssymself(*splitseg);
8406       spivot(*splitseg, rightsubseg);
8407       insertsubseg(m, b, &newbotright, mark(*splitseg));
8408       tspivot(newbotright, newsubseg);
8409       setsegorg(newsubseg, segmentorg);
8410       setsegdest(newsubseg, segmentdest);
8411       sbond(*splitseg, newsubseg);
8412       ssymself(newsubseg);
8413       sbond(newsubseg, rightsubseg);
8414       ssymself(*splitseg);
8415       /* Transfer the subsegment's boundary marker to the vertex */
8416       /*   if required.                                          */
8417       if (vertexmark(newvertex) == 0) {
8418         setvertexmark(newvertex, mark(*splitseg));
8419       }
8420     }
8421 
8422     if (m->checkquality) {
8423       poolrestart(&m->flipstackers);
8424       m->lastflip = (struct flipstacker *) poolalloc(&m->flipstackers);
8425       m->lastflip->flippedtri = encode(horiz);
8426       m->lastflip->prevflip = (struct flipstacker *) &insertvertex;
8427     }
8428 
8429 #ifdef SELF_CHECK
8430     if (counterclockwise(m, b, rightvertex, leftvertex, botvertex) < 0.0) {
8431       printf("Internal error in insertvertex():\n");
8432       printf(
8433             "  Clockwise triangle prior to edge vertex insertion (bottom).\n");
8434     }
8435     if (mirrorflag) {
8436       if (counterclockwise(m, b, leftvertex, rightvertex, topvertex) < 0.0) {
8437         printf("Internal error in insertvertex():\n");
8438         printf("  Clockwise triangle prior to edge vertex insertion (top).\n");
8439       }
8440       if (counterclockwise(m, b, rightvertex, topvertex, newvertex) < 0.0) {
8441         printf("Internal error in insertvertex():\n");
8442         printf(
8443             "  Clockwise triangle after edge vertex insertion (top right).\n");
8444       }
8445       if (counterclockwise(m, b, topvertex, leftvertex, newvertex) < 0.0) {
8446         printf("Internal error in insertvertex():\n");
8447         printf(
8448             "  Clockwise triangle after edge vertex insertion (top left).\n");
8449       }
8450     }
8451     if (counterclockwise(m, b, leftvertex, botvertex, newvertex) < 0.0) {
8452       printf("Internal error in insertvertex():\n");
8453       printf(
8454           "  Clockwise triangle after edge vertex insertion (bottom left).\n");
8455     }
8456     if (counterclockwise(m, b, botvertex, rightvertex, newvertex) < 0.0) {
8457       printf("Internal error in insertvertex():\n");
8458       printf(
8459         "  Clockwise triangle after edge vertex insertion (bottom right).\n");
8460     }
8461 #endif /* SELF_CHECK */
8462     if (b->verbose > 2) {
8463       printf("  Updating bottom left ");
8464       printtriangle(m, b, &botright);
8465       if (mirrorflag) {
8466         printf("  Updating top left ");
8467         printtriangle(m, b, &topright);
8468         printf("  Creating top right ");
8469         printtriangle(m, b, &newtopright);
8470       }
8471       printf("  Creating bottom right ");
8472       printtriangle(m, b, &newbotright);
8473     }
8474 
8475     /* Position `horiz' on the first edge to check for */
8476     /*   the Delaunay property.                        */
8477     lnextself(horiz);
8478   } else {
8479     /* Insert the vertex in a triangle, splitting it into three. */
8480     lnext(horiz, botleft);
8481     lprev(horiz, botright);
8482     sym(botleft, botlcasing);
8483     sym(botright, botrcasing);
8484     maketriangle(m, b, &newbotleft);
8485     maketriangle(m, b, &newbotright);
8486 
8487     /* Set the vertices of changed and new triangles. */
8488     org(horiz, rightvertex);
8489     dest(horiz, leftvertex);
8490     apex(horiz, botvertex);
8491     setorg(newbotleft, leftvertex);
8492     setdest(newbotleft, botvertex);
8493     setapex(newbotleft, newvertex);
8494     setorg(newbotright, botvertex);
8495     setdest(newbotright, rightvertex);
8496     setapex(newbotright, newvertex);
8497     setapex(horiz, newvertex);
8498     for (i = 0; i < m->eextras; i++) {
8499       /* Set the element attributes of the new triangles. */
8500       attrib = elemattribute(horiz, i);
8501       setelemattribute(newbotleft, i, attrib);
8502       setelemattribute(newbotright, i, attrib);
8503     }
8504     if (b->vararea) {
8505       /* Set the area constraint of the new triangles. */
8506       area = areabound(horiz);
8507       setareabound(newbotleft, area);
8508       setareabound(newbotright, area);
8509     }
8510 
8511     /* There may be subsegments that need to be bonded */
8512     /*   to the new triangles.                         */
8513     if (m->checksegments) {
8514       tspivot(botleft, botlsubseg);
8515       if (botlsubseg.ss != m->dummysub) {
8516         tsdissolve(botleft);
8517         tsbond(newbotleft, botlsubseg);
8518       }
8519       tspivot(botright, botrsubseg);
8520       if (botrsubseg.ss != m->dummysub) {
8521         tsdissolve(botright);
8522         tsbond(newbotright, botrsubseg);
8523       }
8524     }
8525 
8526     /* Bond the new triangles to the surrounding triangles. */
8527     bond(newbotleft, botlcasing);
8528     bond(newbotright, botrcasing);
8529     lnextself(newbotleft);
8530     lprevself(newbotright);
8531     bond(newbotleft, newbotright);
8532     lnextself(newbotleft);
8533     bond(botleft, newbotleft);
8534     lprevself(newbotright);
8535     bond(botright, newbotright);
8536 
8537     if (m->checkquality) {
8538       poolrestart(&m->flipstackers);
8539       m->lastflip = (struct flipstacker *) poolalloc(&m->flipstackers);
8540       m->lastflip->flippedtri = encode(horiz);
8541       m->lastflip->prevflip = (struct flipstacker *) NULL;
8542     }
8543 
8544 #ifdef SELF_CHECK
8545     if (counterclockwise(m, b, rightvertex, leftvertex, botvertex) < 0.0) {
8546       printf("Internal error in insertvertex():\n");
8547       printf("  Clockwise triangle prior to vertex insertion.\n");
8548     }
8549     if (counterclockwise(m, b, rightvertex, leftvertex, newvertex) < 0.0) {
8550       printf("Internal error in insertvertex():\n");
8551       printf("  Clockwise triangle after vertex insertion (top).\n");
8552     }
8553     if (counterclockwise(m, b, leftvertex, botvertex, newvertex) < 0.0) {
8554       printf("Internal error in insertvertex():\n");
8555       printf("  Clockwise triangle after vertex insertion (left).\n");
8556     }
8557     if (counterclockwise(m, b, botvertex, rightvertex, newvertex) < 0.0) {
8558       printf("Internal error in insertvertex():\n");
8559       printf("  Clockwise triangle after vertex insertion (right).\n");
8560     }
8561 #endif /* SELF_CHECK */
8562     if (b->verbose > 2) {
8563       printf("  Updating top ");
8564       printtriangle(m, b, &horiz);
8565       printf("  Creating left ");
8566       printtriangle(m, b, &newbotleft);
8567       printf("  Creating right ");
8568       printtriangle(m, b, &newbotright);
8569     }
8570   }
8571 
8572   /* The insertion is successful by default, unless an encroached */
8573   /*   subsegment is found.                                       */
8574   success = SUCCESSFULVERTEX;
8575   /* Circle around the newly inserted vertex, checking each edge opposite */
8576   /*   it for the Delaunay property.  Non-Delaunay edges are flipped.     */
8577   /*   `horiz' is always the edge being checked.  `first' marks where to  */
8578   /*   stop circling.                                                     */
8579   org(horiz, first);
8580   rightvertex = first;
8581   dest(horiz, leftvertex);
8582   /* Circle until finished. */
8583   while (1) {
8584     /* By default, the edge will be flipped. */
8585     doflip = 1;
8586 
8587     if (m->checksegments) {
8588       /* Check for a subsegment, which cannot be flipped. */
8589       tspivot(horiz, checksubseg);
8590       if (checksubseg.ss != m->dummysub) {
8591         /* The edge is a subsegment and cannot be flipped. */
8592         doflip = 0;
8593 #ifndef CDT_ONLY
8594         if (segmentflaws) {
8595           /* Does the new vertex encroach upon this subsegment? */
8596           if (checkseg4encroach(m, b, &checksubseg)) {
8597             success = ENCROACHINGVERTEX;
8598           }
8599         }
8600 #endif /* not CDT_ONLY */
8601       }
8602     }
8603 
8604     if (doflip) {
8605       /* Check if the edge is a boundary edge. */
8606       sym(horiz, top);
8607       if (top.tri == m->dummytri) {
8608         /* The edge is a boundary edge and cannot be flipped. */
8609         doflip = 0;
8610       } else {
8611         /* Find the vertex on the other side of the edge. */
8612         apex(top, farvertex);
8613         /* In the incremental Delaunay triangulation algorithm, any of      */
8614         /*   `leftvertex', `rightvertex', and `farvertex' could be vertices */
8615         /*   of the triangular bounding box.  These vertices must be        */
8616         /*   treated as if they are infinitely distant, even though their   */
8617         /*   "coordinates" are not.                                         */
8618         if ((leftvertex == m->infvertex1) || (leftvertex == m->infvertex2) ||
8619             (leftvertex == m->infvertex3)) {
8620           /* `leftvertex' is infinitely distant.  Check the convexity of  */
8621           /*   the boundary of the triangulation.  'farvertex' might be   */
8622           /*   infinite as well, but trust me, this same condition should */
8623           /*   be applied.                                                */
8624           doflip = counterclockwise(m, b, newvertex, rightvertex, farvertex)
8625                    > 0.0;
8626         } else if ((rightvertex == m->infvertex1) ||
8627                    (rightvertex == m->infvertex2) ||
8628                    (rightvertex == m->infvertex3)) {
8629           /* `rightvertex' is infinitely distant.  Check the convexity of */
8630           /*   the boundary of the triangulation.  'farvertex' might be   */
8631           /*   infinite as well, but trust me, this same condition should */
8632           /*   be applied.                                                */
8633           doflip = counterclockwise(m, b, farvertex, leftvertex, newvertex)
8634                    > 0.0;
8635         } else if ((farvertex == m->infvertex1) ||
8636                    (farvertex == m->infvertex2) ||
8637                    (farvertex == m->infvertex3)) {
8638           /* `farvertex' is infinitely distant and cannot be inside */
8639           /*   the circumcircle of the triangle `horiz'.            */
8640           doflip = 0;
8641         } else {
8642           /* Test whether the edge is locally Delaunay. */
8643           doflip = incircle(m, b, leftvertex, newvertex, rightvertex,
8644                             farvertex) > 0.0;
8645         }
8646         if (doflip) {
8647           /* We made it!  Flip the edge `horiz' by rotating its containing */
8648           /*   quadrilateral (the two triangles adjacent to `horiz').      */
8649           /* Identify the casing of the quadrilateral. */
8650           lprev(top, topleft);
8651           sym(topleft, toplcasing);
8652           lnext(top, topright);
8653           sym(topright, toprcasing);
8654           lnext(horiz, botleft);
8655           sym(botleft, botlcasing);
8656           lprev(horiz, botright);
8657           sym(botright, botrcasing);
8658           /* Rotate the quadrilateral one-quarter turn counterclockwise. */
8659           bond(topleft, botlcasing);
8660           bond(botleft, botrcasing);
8661           bond(botright, toprcasing);
8662           bond(topright, toplcasing);
8663           if (m->checksegments) {
8664             /* Check for subsegments and rebond them to the quadrilateral. */
8665             tspivot(topleft, toplsubseg);
8666             tspivot(botleft, botlsubseg);
8667             tspivot(botright, botrsubseg);
8668             tspivot(topright, toprsubseg);
8669             if (toplsubseg.ss == m->dummysub) {
8670               tsdissolve(topright);
8671             } else {
8672               tsbond(topright, toplsubseg);
8673             }
8674             if (botlsubseg.ss == m->dummysub) {
8675               tsdissolve(topleft);
8676             } else {
8677               tsbond(topleft, botlsubseg);
8678             }
8679             if (botrsubseg.ss == m->dummysub) {
8680               tsdissolve(botleft);
8681             } else {
8682               tsbond(botleft, botrsubseg);
8683             }
8684             if (toprsubseg.ss == m->dummysub) {
8685               tsdissolve(botright);
8686             } else {
8687               tsbond(botright, toprsubseg);
8688             }
8689           }
8690           /* New vertex assignments for the rotated quadrilateral. */
8691           setorg(horiz, farvertex);
8692           setdest(horiz, newvertex);
8693           setapex(horiz, rightvertex);
8694           setorg(top, newvertex);
8695           setdest(top, farvertex);
8696           setapex(top, leftvertex);
8697           for (i = 0; i < m->eextras; i++) {
8698             /* Take the average of the two triangles' attributes. */
8699             attrib = 0.5 * (elemattribute(top, i) + elemattribute(horiz, i));
8700             setelemattribute(top, i, attrib);
8701             setelemattribute(horiz, i, attrib);
8702           }
8703           if (b->vararea) {
8704             if ((areabound(top) <= 0.0) || (areabound(horiz) <= 0.0)) {
8705               area = -1.0;
8706             } else {
8707               /* Take the average of the two triangles' area constraints.    */
8708               /*   This prevents small area constraints from migrating a     */
8709               /*   long, long way from their original location due to flips. */
8710               area = 0.5 * (areabound(top) + areabound(horiz));
8711             }
8712             setareabound(top, area);
8713             setareabound(horiz, area);
8714           }
8715 
8716           if (m->checkquality) {
8717             newflip = (struct flipstacker *) poolalloc(&m->flipstackers);
8718             newflip->flippedtri = encode(horiz);
8719             newflip->prevflip = m->lastflip;
8720             m->lastflip = newflip;
8721           }
8722 
8723 #ifdef SELF_CHECK
8724           if (newvertex != (vertex) NULL) {
8725             if (counterclockwise(m, b, leftvertex, newvertex, rightvertex) <
8726                 0.0) {
8727               printf("Internal error in insertvertex():\n");
8728               printf("  Clockwise triangle prior to edge flip (bottom).\n");
8729             }
8730             /* The following test has been removed because constrainededge() */
8731             /*   sometimes generates inverted triangles that insertvertex()  */
8732             /*   removes.                                                    */
8733 /*
8734             if (counterclockwise(m, b, rightvertex, farvertex, leftvertex) <
8735                 0.0) {
8736               printf("Internal error in insertvertex():\n");
8737               printf("  Clockwise triangle prior to edge flip (top).\n");
8738             }
8739 */
8740             if (counterclockwise(m, b, farvertex, leftvertex, newvertex) <
8741                 0.0) {
8742               printf("Internal error in insertvertex():\n");
8743               printf("  Clockwise triangle after edge flip (left).\n");
8744             }
8745             if (counterclockwise(m, b, newvertex, rightvertex, farvertex) <
8746                 0.0) {
8747               printf("Internal error in insertvertex():\n");
8748               printf("  Clockwise triangle after edge flip (right).\n");
8749             }
8750           }
8751 #endif /* SELF_CHECK */
8752           if (b->verbose > 2) {
8753             printf("  Edge flip results in left ");
8754             lnextself(topleft);
8755             printtriangle(m, b, &topleft);
8756             printf("  and right ");
8757             printtriangle(m, b, &horiz);
8758           }
8759           /* On the next iterations, consider the two edges that were  */
8760           /*   exposed (this is, are now visible to the newly inserted */
8761           /*   vertex) by the edge flip.                               */
8762           lprevself(horiz);
8763           leftvertex = farvertex;
8764         }
8765       }
8766     }
8767     if (!doflip) {
8768       /* The handle `horiz' is accepted as locally Delaunay. */
8769 #ifndef CDT_ONLY
8770       if (triflaws) {
8771         /* Check the triangle `horiz' for quality. */
8772         testtriangle(m, b, &horiz);
8773       }
8774 #endif /* not CDT_ONLY */
8775       /* Look for the next edge around the newly inserted vertex. */
8776       lnextself(horiz);
8777       sym(horiz, testtri);
8778       /* Check for finishing a complete revolution about the new vertex, or */
8779       /*   falling outside  of the triangulation.  The latter will happen   */
8780       /*   when a vertex is inserted at a boundary.                         */
8781       if ((leftvertex == first) || (testtri.tri == m->dummytri)) {
8782         /* We're done.  Return a triangle whose origin is the new vertex. */
8783         lnext(horiz, *searchtri);
8784         lnext(horiz, m->recenttri);
8785         return success;
8786       }
8787       /* Finish finding the next edge around the newly inserted vertex. */
8788       lnext(testtri, horiz);
8789       rightvertex = leftvertex;
8790       dest(horiz, leftvertex);
8791     }
8792   }
8793 }
8794 
8795 /*****************************************************************************/
8796 /*                                                                           */
8797 /*  triangulatepolygon()   Find the Delaunay triangulation of a polygon that */
8798 /*                         has a certain "nice" shape.  This includes the    */
8799 /*                         polygons that result from deletion of a vertex or */
8800 /*                         insertion of a segment.                           */
8801 /*                                                                           */
8802 /*  This is a conceptually difficult routine.  The starting assumption is    */
8803 /*  that we have a polygon with n sides.  n - 1 of these sides are currently */
8804 /*  represented as edges in the mesh.  One side, called the "base", need not */
8805 /*  be.                                                                      */
8806 /*                                                                           */
8807 /*  Inside the polygon is a structure I call a "fan", consisting of n - 1    */
8808 /*  triangles that share a common origin.  For each of these triangles, the  */
8809 /*  edge opposite the origin is one of the sides of the polygon.  The        */
8810 /*  primary edge of each triangle is the edge directed from the origin to    */
8811 /*  the destination; note that this is not the same edge that is a side of   */
8812 /*  the polygon.  `firstedge' is the primary edge of the first triangle.     */
8813 /*  From there, the triangles follow in counterclockwise order about the     */
8814 /*  polygon, until `lastedge', the primary edge of the last triangle.        */
8815 /*  `firstedge' and `lastedge' are probably connected to other triangles     */
8816 /*  beyond the extremes of the fan, but their identity is not important, as  */
8817 /*  long as the fan remains connected to them.                               */
8818 /*                                                                           */
8819 /*  Imagine the polygon oriented so that its base is at the bottom.  This    */
8820 /*  puts `firstedge' on the far right, and `lastedge' on the far left.       */
8821 /*  The right vertex of the base is the destination of `firstedge', and the  */
8822 /*  left vertex of the base is the apex of `lastedge'.                       */
8823 /*                                                                           */
8824 /*  The challenge now is to find the right sequence of edge flips to         */
8825 /*  transform the fan into a Delaunay triangulation of the polygon.  Each    */
8826 /*  edge flip effectively removes one triangle from the fan, committing it   */
8827 /*  to the polygon.  The resulting polygon has one fewer edge.  If `doflip'  */
8828 /*  is set, the final flip will be performed, resulting in a fan of one      */
8829 /*  (useless?) triangle.  If `doflip' is not set, the final flip is not      */
8830 /*  performed, resulting in a fan of two triangles, and an unfinished        */
8831 /*  triangular polygon that is not yet filled out with a single triangle.    */
8832 /*  On completion of the routine, `lastedge' is the last remaining triangle, */
8833 /*  or the leftmost of the last two.                                         */
8834 /*                                                                           */
8835 /*  Although the flips are performed in the order described above, the       */
8836 /*  decisions about what flips to perform are made in precisely the reverse  */
8837 /*  order.  The recursive triangulatepolygon() procedure makes a decision,   */
8838 /*  uses up to two recursive calls to triangulate the "subproblems"          */
8839 /*  (polygons with fewer edges), and then performs an edge flip.             */
8840 /*                                                                           */
8841 /*  The "decision" it makes is which vertex of the polygon should be         */
8842 /*  connected to the base.  This decision is made by testing every possible  */
8843 /*  vertex.  Once the best vertex is found, the two edges that connect this  */
8844 /*  vertex to the base become the bases for two smaller polygons.  These     */
8845 /*  are triangulated recursively.  Unfortunately, this approach can take     */
8846 /*  O(n^2) time not only in the worst case, but in many common cases.  It's  */
8847 /*  rarely a big deal for vertex deletion, where n is rarely larger than     */
8848 /*  ten, but it could be a big deal for segment insertion, especially if     */
8849 /*  there's a lot of long segments that each cut many triangles.  I ought to */
8850 /*  code a faster algorithm some day.                                        */
8851 /*                                                                           */
8852 /*  The `edgecount' parameter is the number of sides of the polygon,         */
8853 /*  including its base.  `triflaws' is a flag that determines whether the    */
8854 /*  new triangles should be tested for quality, and enqueued if they are     */
8855 /*  bad.                                                                     */
8856 /*                                                                           */
8857 /*****************************************************************************/
8858 
8859 #ifdef ANSI_DECLARATORS
8860 void triangulatepolygon(struct mesh *m, struct behavior *b,
8861                         struct otri *firstedge, struct otri *lastedge,
8862                         int edgecount, int doflip, int triflaws)
8863 #else /* not ANSI_DECLARATORS */
8864 void triangulatepolygon(m, b, firstedge, lastedge, edgecount, doflip, triflaws)
8865 struct mesh *m;
8866 struct behavior *b;
8867 struct otri *firstedge;
8868 struct otri *lastedge;
8869 int edgecount;
8870 int doflip;
8871 int triflaws;
8872 #endif /* not ANSI_DECLARATORS */
8873 
8874 {
8875   struct otri testtri;
8876   struct otri besttri;
8877   struct otri tempedge;
8878   vertex leftbasevertex, rightbasevertex;
8879   vertex testvertex;
8880   vertex bestvertex;
8881   int bestnumber;
8882   int i;
8883   triangle ptr;   /* Temporary variable used by sym(), onext(), and oprev(). */
8884 
8885   /* Identify the base vertices. */
8886   apex(*lastedge, leftbasevertex);
8887   dest(*firstedge, rightbasevertex);
8888   if (b->verbose > 2) {
8889     printf("  Triangulating interior polygon at edge\n");
8890     printf("    (%.12g, %.12g) (%.12g, %.12g)\n", leftbasevertex[0],
8891            leftbasevertex[1], rightbasevertex[0], rightbasevertex[1]);
8892   }
8893   /* Find the best vertex to connect the base to. */
8894   onext(*firstedge, besttri);
8895   dest(besttri, bestvertex);
8896   otricopy(besttri, testtri);
8897   bestnumber = 1;
8898   for (i = 2; i <= edgecount - 2; i++) {
8899     onextself(testtri);
8900     dest(testtri, testvertex);
8901     /* Is this a better vertex? */
8902     if (incircle(m, b, leftbasevertex, rightbasevertex, bestvertex,
8903                  testvertex) > 0.0) {
8904       otricopy(testtri, besttri);
8905       bestvertex = testvertex;
8906       bestnumber = i;
8907     }
8908   }
8909   if (b->verbose > 2) {
8910     printf("    Connecting edge to (%.12g, %.12g)\n", bestvertex[0],
8911            bestvertex[1]);
8912   }
8913   if (bestnumber > 1) {
8914     /* Recursively triangulate the smaller polygon on the right. */
8915     oprev(besttri, tempedge);
8916     triangulatepolygon(m, b, firstedge, &tempedge, bestnumber + 1, 1,
8917                        triflaws);
8918   }
8919   if (bestnumber < edgecount - 2) {
8920     /* Recursively triangulate the smaller polygon on the left. */
8921     sym(besttri, tempedge);
8922     triangulatepolygon(m, b, &besttri, lastedge, edgecount - bestnumber, 1,
8923                        triflaws);
8924     /* Find `besttri' again; it may have been lost to edge flips. */
8925     sym(tempedge, besttri);
8926   }
8927   if (doflip) {
8928     /* Do one final edge flip. */
8929     flip(m, b, &besttri);
8930 #ifndef CDT_ONLY
8931     if (triflaws) {
8932       /* Check the quality of the newly committed triangle. */
8933       sym(besttri, testtri);
8934       testtriangle(m, b, &testtri);
8935     }
8936 #endif /* not CDT_ONLY */
8937   }
8938   /* Return the base triangle. */
8939   otricopy(besttri, *lastedge);
8940 }
8941 
8942 /*****************************************************************************/
8943 /*                                                                           */
8944 /*  deletevertex()   Delete a vertex from a Delaunay triangulation, ensuring */
8945 /*                   that the triangulation remains Delaunay.                */
8946 /*                                                                           */
8947 /*  The origin of `deltri' is deleted.  The union of the triangles adjacent  */
8948 /*  to this vertex is a polygon, for which the Delaunay triangulation is     */
8949 /*  found.  Two triangles are removed from the mesh.                         */
8950 /*                                                                           */
8951 /*  Only interior vertices that do not lie on segments or boundaries may be  */
8952 /*  deleted.                                                                 */
8953 /*                                                                           */
8954 /*****************************************************************************/
8955 
8956 #ifndef CDT_ONLY
8957 
8958 #ifdef ANSI_DECLARATORS
8959 void deletevertex(struct mesh *m, struct behavior *b, struct otri *deltri)
8960 #else /* not ANSI_DECLARATORS */
8961 void deletevertex(m, b, deltri)
8962 struct mesh *m;
8963 struct behavior *b;
8964 struct otri *deltri;
8965 #endif /* not ANSI_DECLARATORS */
8966 
8967 {
8968   struct otri countingtri;
8969   struct otri firstedge, lastedge;
8970   struct otri deltriright;
8971   struct otri lefttri, righttri;
8972   struct otri leftcasing, rightcasing;
8973   struct osub leftsubseg, rightsubseg;
8974   vertex delvertex;
8975   vertex neworg;
8976   int edgecount;
8977   triangle ptr;   /* Temporary variable used by sym(), onext(), and oprev(). */
8978   subseg sptr;                      /* Temporary variable used by tspivot(). */
8979 
8980   org(*deltri, delvertex);
8981   if (b->verbose > 1) {
8982     printf("  Deleting (%.12g, %.12g).\n", delvertex[0], delvertex[1]);
8983   }
8984   vertexdealloc(m, delvertex);
8985 
8986   /* Count the degree of the vertex being deleted. */
8987   onext(*deltri, countingtri);
8988   edgecount = 1;
8989   while (!otriequal(*deltri, countingtri)) {
8990 #ifdef SELF_CHECK
8991     if (countingtri.tri == m->dummytri) {
8992       printf("Internal error in deletevertex():\n");
8993       printf("  Attempt to delete boundary vertex.\n");
8994       internalerror();
8995     }
8996 #endif /* SELF_CHECK */
8997     edgecount++;
8998     onextself(countingtri);
8999   }
9000 
9001 #ifdef SELF_CHECK
9002   if (edgecount < 3) {
9003     printf("Internal error in deletevertex():\n  Vertex has degree %d.\n",
9004            edgecount);
9005     internalerror();
9006   }
9007 #endif /* SELF_CHECK */
9008   if (edgecount > 3) {
9009     /* Triangulate the polygon defined by the union of all triangles */
9010     /*   adjacent to the vertex being deleted.  Check the quality of */
9011     /*   the resulting triangles.                                    */
9012     onext(*deltri, firstedge);
9013     oprev(*deltri, lastedge);
9014     triangulatepolygon(m, b, &firstedge, &lastedge, edgecount, 0,
9015                        !b->nobisect);
9016   }
9017   /* Splice out two triangles. */
9018   lprev(*deltri, deltriright);
9019   dnext(*deltri, lefttri);
9020   sym(lefttri, leftcasing);
9021   oprev(deltriright, righttri);
9022   sym(righttri, rightcasing);
9023   bond(*deltri, leftcasing);
9024   bond(deltriright, rightcasing);
9025   tspivot(lefttri, leftsubseg);
9026   if (leftsubseg.ss != m->dummysub) {
9027     tsbond(*deltri, leftsubseg);
9028   }
9029   tspivot(righttri, rightsubseg);
9030   if (rightsubseg.ss != m->dummysub) {
9031     tsbond(deltriright, rightsubseg);
9032   }
9033 
9034   /* Set the new origin of `deltri' and check its quality. */
9035   org(lefttri, neworg);
9036   setorg(*deltri, neworg);
9037   if (!b->nobisect) {
9038     testtriangle(m, b, deltri);
9039   }
9040 
9041   /* Delete the two spliced-out triangles. */
9042   triangledealloc(m, lefttri.tri);
9043   triangledealloc(m, righttri.tri);
9044 }
9045 
9046 #endif /* not CDT_ONLY */
9047 
9048 /*****************************************************************************/
9049 /*                                                                           */
9050 /*  undovertex()   Undo the most recent vertex insertion.                    */
9051 /*                                                                           */
9052 /*  Walks through the list of transformations (flips and a vertex insertion) */
9053 /*  in the reverse of the order in which they were done, and undoes them.    */
9054 /*  The inserted vertex is removed from the triangulation and deallocated.   */
9055 /*  Two triangles (possibly just one) are also deallocated.                  */
9056 /*                                                                           */
9057 /*****************************************************************************/
9058 
9059 #ifndef CDT_ONLY
9060 
9061 #ifdef ANSI_DECLARATORS
9062 void undovertex(struct mesh *m, struct behavior *b)
9063 #else /* not ANSI_DECLARATORS */
9064 void undovertex(m, b)
9065 struct mesh *m;
9066 struct behavior *b;
9067 #endif /* not ANSI_DECLARATORS */
9068 
9069 {
9070   struct otri fliptri;
9071   struct otri botleft, botright, topright;
9072   struct otri botlcasing, botrcasing, toprcasing;
9073   struct otri gluetri;
9074   struct osub botlsubseg, botrsubseg, toprsubseg;
9075   vertex botvertex, rightvertex;
9076   triangle ptr;                         /* Temporary variable used by sym(). */
9077   subseg sptr;                      /* Temporary variable used by tspivot(). */
9078 
9079   /* Walk through the list of transformations (flips and a vertex insertion) */
9080   /*   in the reverse of the order in which they were done, and undo them.   */
9081   while (m->lastflip != (struct flipstacker *) NULL) {
9082     /* Find a triangle involved in the last unreversed transformation. */
9083     decode(m->lastflip->flippedtri, fliptri);
9084 
9085     /* We are reversing one of three transformations:  a trisection of one */
9086     /*   triangle into three (by inserting a vertex in the triangle), a    */
9087     /*   bisection of two triangles into four (by inserting a vertex in an */
9088     /*   edge), or an edge flip.                                           */
9089     if (m->lastflip->prevflip == (struct flipstacker *) NULL) {
9090       /* Restore a triangle that was split into three triangles, */
9091       /*   so it is again one triangle.                          */
9092       dprev(fliptri, botleft);
9093       lnextself(botleft);
9094       onext(fliptri, botright);
9095       lprevself(botright);
9096       sym(botleft, botlcasing);
9097       sym(botright, botrcasing);
9098       dest(botleft, botvertex);
9099 
9100       setapex(fliptri, botvertex);
9101       lnextself(fliptri);
9102       bond(fliptri, botlcasing);
9103       tspivot(botleft, botlsubseg);
9104       tsbond(fliptri, botlsubseg);
9105       lnextself(fliptri);
9106       bond(fliptri, botrcasing);
9107       tspivot(botright, botrsubseg);
9108       tsbond(fliptri, botrsubseg);
9109 
9110       /* Delete the two spliced-out triangles. */
9111       triangledealloc(m, botleft.tri);
9112       triangledealloc(m, botright.tri);
9113     } else if (m->lastflip->prevflip == (struct flipstacker *) &insertvertex) {
9114       /* Restore two triangles that were split into four triangles, */
9115       /*   so they are again two triangles.                         */
9116       lprev(fliptri, gluetri);
9117       sym(gluetri, botright);
9118       lnextself(botright);
9119       sym(botright, botrcasing);
9120       dest(botright, rightvertex);
9121 
9122       setorg(fliptri, rightvertex);
9123       bond(gluetri, botrcasing);
9124       tspivot(botright, botrsubseg);
9125       tsbond(gluetri, botrsubseg);
9126 
9127       /* Delete the spliced-out triangle. */
9128       triangledealloc(m, botright.tri);
9129 
9130       sym(fliptri, gluetri);
9131       if (gluetri.tri != m->dummytri) {
9132         lnextself(gluetri);
9133         dnext(gluetri, topright);
9134         sym(topright, toprcasing);
9135 
9136         setorg(gluetri, rightvertex);
9137         bond(gluetri, toprcasing);
9138         tspivot(topright, toprsubseg);
9139         tsbond(gluetri, toprsubseg);
9140 
9141         /* Delete the spliced-out triangle. */
9142         triangledealloc(m, topright.tri);
9143       }
9144 
9145       /* This is the end of the list, sneakily encoded. */
9146       m->lastflip->prevflip = (struct flipstacker *) NULL;
9147     } else {
9148       /* Undo an edge flip. */
9149       unflip(m, b, &fliptri);
9150     }
9151 
9152     /* Go on and process the next transformation. */
9153     m->lastflip = m->lastflip->prevflip;
9154   }
9155 }
9156 
9157 #endif /* not CDT_ONLY */
9158 
9159 /**                                                                         **/
9160 /**                                                                         **/
9161 /********* Mesh transformation routines end here                     *********/
9162 
9163 /********* Divide-and-conquer Delaunay triangulation begins here     *********/
9164 /**                                                                         **/
9165 /**                                                                         **/
9166 
9167 /*****************************************************************************/
9168 /*                                                                           */
9169 /*  The divide-and-conquer bounding box                                      */
9170 /*                                                                           */
9171 /*  I originally implemented the divide-and-conquer and incremental Delaunay */
9172 /*  triangulations using the edge-based data structure presented by Guibas   */
9173 /*  and Stolfi.  Switching to a triangle-based data structure doubled the    */
9174 /*  speed.  However, I had to think of a few extra tricks to maintain the    */
9175 /*  elegance of the original algorithms.                                     */
9176 /*                                                                           */
9177 /*  The "bounding box" used by my variant of the divide-and-conquer          */
9178 /*  algorithm uses one triangle for each edge of the convex hull of the      */
9179 /*  triangulation.  These bounding triangles all share a common apical       */
9180 /*  vertex, which is represented by NULL and which represents nothing.       */
9181 /*  The bounding triangles are linked in a circular fan about this NULL      */
9182 /*  vertex, and the edges on the convex hull of the triangulation appear     */
9183 /*  opposite the NULL vertex.  You might find it easiest to imagine that     */
9184 /*  the NULL vertex is a point in 3D space behind the center of the          */
9185 /*  triangulation, and that the bounding triangles form a sort of cone.      */
9186 /*                                                                           */
9187 /*  This bounding box makes it easy to represent degenerate cases.  For      */
9188 /*  instance, the triangulation of two vertices is a single edge.  This edge */
9189 /*  is represented by two bounding box triangles, one on each "side" of the  */
9190 /*  edge.  These triangles are also linked together in a fan about the NULL  */
9191 /*  vertex.                                                                  */
9192 /*                                                                           */
9193 /*  The bounding box also makes it easy to traverse the convex hull, as the  */
9194 /*  divide-and-conquer algorithm needs to do.                                */
9195 /*                                                                           */
9196 /*****************************************************************************/
9197 
9198 /*****************************************************************************/
9199 /*                                                                           */
9200 /*  vertexsort()   Sort an array of vertices by x-coordinate, using the      */
9201 /*                 y-coordinate as a secondary key.                          */
9202 /*                                                                           */
9203 /*  Uses quicksort.  Randomized O(n log n) time.  No, I did not make any of  */
9204 /*  the usual quicksort mistakes.                                            */
9205 /*                                                                           */
9206 /*****************************************************************************/
9207 
9208 #ifdef ANSI_DECLARATORS
9209 void vertexsort(vertex *sortarray, int arraysize)
9210 #else /* not ANSI_DECLARATORS */
9211 void vertexsort(sortarray, arraysize)
9212 vertex *sortarray;
9213 int arraysize;
9214 #endif /* not ANSI_DECLARATORS */
9215 
9216 {
9217   int left, right;
9218   int pivot;
9219   REAL pivotx, pivoty;
9220   vertex temp;
9221 
9222   if (arraysize == 2) {
9223     /* Recursive base case. */
9224     if ((sortarray[0][0] > sortarray[1][0]) ||
9225         ((sortarray[0][0] == sortarray[1][0]) &&
9226          (sortarray[0][1] > sortarray[1][1]))) {
9227       temp = sortarray[1];
9228       sortarray[1] = sortarray[0];
9229       sortarray[0] = temp;
9230     }
9231     return;
9232   }
9233   /* Choose a random pivot to split the array. */
9234   pivot = (int) randomnation((unsigned int) arraysize);
9235   if (pivot == arraysize)//JLM without this test, pivot can equal arraysize and segfault
9236 	  pivot--;
9237   pivotx = sortarray[pivot][0];
9238   pivoty = sortarray[pivot][1];
9239   /* Split the array. */
9240   left = -1;
9241   right = arraysize;
9242   while (left < right) {
9243     /* Search for a vertex whose x-coordinate is too large for the left. */
9244     do {
9245       left++;
9246     } while ((left <= right) && ((sortarray[left][0] < pivotx) ||
9247                                  ((sortarray[left][0] == pivotx) &&
9248                                   (sortarray[left][1] < pivoty))));
9249     /* Search for a vertex whose x-coordinate is too small for the right. */
9250     do {
9251       right--;
9252     } while ((left <= right) && ((sortarray[right][0] > pivotx) ||
9253                                  ((sortarray[right][0] == pivotx) &&
9254                                   (sortarray[right][1] > pivoty))));
9255     if (left < right) {
9256       /* Swap the left and right vertices. */
9257       temp = sortarray[left];
9258       sortarray[left] = sortarray[right];
9259       sortarray[right] = temp;
9260     }
9261   }
9262   if (left > 1) {
9263     /* Recursively sort the left subset. */
9264     vertexsort(sortarray, left);
9265   }
9266   if (right < arraysize - 2) {
9267     /* Recursively sort the right subset. */
9268     vertexsort(&sortarray[right + 1], arraysize - right - 1);
9269   }
9270 }
9271 
9272 /*****************************************************************************/
9273 /*                                                                           */
9274 /*  vertexmedian()   An order statistic algorithm, almost.  Shuffles an      */
9275 /*                   array of vertices so that the first `median' vertices   */
9276 /*                   occur lexicographically before the remaining vertices.  */
9277 /*                                                                           */
9278 /*  Uses the x-coordinate as the primary key if axis == 0; the y-coordinate  */
9279 /*  if axis == 1.  Very similar to the vertexsort() procedure, but runs in   */
9280 /*  randomized linear time.                                                  */
9281 /*                                                                           */
9282 /*****************************************************************************/
9283 
9284 #ifdef ANSI_DECLARATORS
9285 void vertexmedian(vertex *sortarray, int arraysize, int median, int axis)
9286 #else /* not ANSI_DECLARATORS */
9287 void vertexmedian(sortarray, arraysize, median, axis)
9288 vertex *sortarray;
9289 int arraysize;
9290 int median;
9291 int axis;
9292 #endif /* not ANSI_DECLARATORS */
9293 
9294 {
9295   int left, right;
9296   int pivot;
9297   REAL pivot1, pivot2;
9298   vertex temp;
9299 
9300   if (arraysize == 2) {
9301     /* Recursive base case. */
9302     if ((sortarray[0][axis] > sortarray[1][axis]) ||
9303         ((sortarray[0][axis] == sortarray[1][axis]) &&
9304          (sortarray[0][1 - axis] > sortarray[1][1 - axis]))) {
9305       temp = sortarray[1];
9306       sortarray[1] = sortarray[0];
9307       sortarray[0] = temp;
9308     }
9309     return;
9310   }
9311   /* Choose a random pivot to split the array. */
9312   pivot = (int) randomnation((unsigned int) arraysize);
9313   if (pivot == arraysize)//JLM/SES without this test, pivot can equal arraysize and segfault
9314 	  pivot--;
9315   pivot1 = sortarray[pivot][axis];
9316   pivot2 = sortarray[pivot][1 - axis];
9317   /* Split the array. */
9318   left = -1;
9319   right = arraysize;
9320   while (left < right) {
9321     /* Search for a vertex whose x-coordinate is too large for the left. */
9322     do {
9323       left++;
9324     } while ((left <= right) && ((sortarray[left][axis] < pivot1) ||
9325                                  ((sortarray[left][axis] == pivot1) &&
9326                                   (sortarray[left][1 - axis] < pivot2))));
9327     /* Search for a vertex whose x-coordinate is too small for the right. */
9328     do {
9329       right--;
9330     } while ((left <= right) && ((sortarray[right][axis] > pivot1) ||
9331                                  ((sortarray[right][axis] == pivot1) &&
9332                                   (sortarray[right][1 - axis] > pivot2))));
9333     if (left < right) {
9334       /* Swap the left and right vertices. */
9335       temp = sortarray[left];
9336       sortarray[left] = sortarray[right];
9337       sortarray[right] = temp;
9338     }
9339   }
9340   /* Unlike in vertexsort(), at most one of the following */
9341   /*   conditionals is true.                             */
9342   if (left > median) {
9343     /* Recursively shuffle the left subset. */
9344     vertexmedian(sortarray, left, median, axis);
9345   }
9346   if (right < median - 1) {
9347     /* Recursively shuffle the right subset. */
9348     vertexmedian(&sortarray[right + 1], arraysize - right - 1,
9349                  median - right - 1, axis);
9350   }
9351 }
9352 
9353 /*****************************************************************************/
9354 /*                                                                           */
9355 /*  alternateaxes()   Sorts the vertices as appropriate for the divide-and-  */
9356 /*                    conquer algorithm with alternating cuts.               */
9357 /*                                                                           */
9358 /*  Partitions by x-coordinate if axis == 0; by y-coordinate if axis == 1.   */
9359 /*  For the base case, subsets containing only two or three vertices are     */
9360 /*  always sorted by x-coordinate.                                           */
9361 /*                                                                           */
9362 /*****************************************************************************/
9363 
9364 #ifdef ANSI_DECLARATORS
9365 void alternateaxes(vertex *sortarray, int arraysize, int axis)
9366 #else /* not ANSI_DECLARATORS */
9367 void alternateaxes(sortarray, arraysize, axis)
9368 vertex *sortarray;
9369 int arraysize;
9370 int axis;
9371 #endif /* not ANSI_DECLARATORS */
9372 
9373 {
9374   int divider;
9375 
9376   divider = arraysize >> 1;
9377   if (arraysize <= 3) {
9378     /* Recursive base case:  subsets of two or three vertices will be    */
9379     /*   handled specially, and should always be sorted by x-coordinate. */
9380     axis = 0;
9381   }
9382   /* Partition with a horizontal or vertical cut. */
9383   vertexmedian(sortarray, arraysize, divider, axis);
9384   /* Recursively partition the subsets with a cross cut. */
9385   if (arraysize - divider >= 2) {
9386     if (divider >= 2) {
9387       alternateaxes(sortarray, divider, 1 - axis);
9388     }
9389     alternateaxes(&sortarray[divider], arraysize - divider, 1 - axis);
9390   }
9391 }
9392 
9393 /*****************************************************************************/
9394 /*                                                                           */
9395 /*  mergehulls()   Merge two adjacent Delaunay triangulations into a         */
9396 /*                 single Delaunay triangulation.                            */
9397 /*                                                                           */
9398 /*  This is similar to the algorithm given by Guibas and Stolfi, but uses    */
9399 /*  a triangle-based, rather than edge-based, data structure.                */
9400 /*                                                                           */
9401 /*  The algorithm walks up the gap between the two triangulations, knitting  */
9402 /*  them together.  As they are merged, some of their bounding triangles     */
9403 /*  are converted into real triangles of the triangulation.  The procedure   */
9404 /*  pulls each hull's bounding triangles apart, then knits them together     */
9405 /*  like the teeth of two gears.  The Delaunay property determines, at each  */
9406 /*  step, whether the next "tooth" is a bounding triangle of the left hull   */
9407 /*  or the right.  When a bounding triangle becomes real, its apex is        */
9408 /*  changed from NULL to a real vertex.                                      */
9409 /*                                                                           */
9410 /*  Only two new triangles need to be allocated.  These become new bounding  */
9411 /*  triangles at the top and bottom of the seam.  They are used to connect   */
9412 /*  the remaining bounding triangles (those that have not been converted     */
9413 /*  into real triangles) into a single fan.                                  */
9414 /*                                                                           */
9415 /*  On entry, `farleft' and `innerleft' are bounding triangles of the left   */
9416 /*  triangulation.  The origin of `farleft' is the leftmost vertex, and      */
9417 /*  the destination of `innerleft' is the rightmost vertex of the            */
9418 /*  triangulation.  Similarly, `innerright' and `farright' are bounding      */
9419 /*  triangles of the right triangulation.  The origin of `innerright' and    */
9420 /*  destination of `farright' are the leftmost and rightmost vertices.       */
9421 /*                                                                           */
9422 /*  On completion, the origin of `farleft' is the leftmost vertex of the     */
9423 /*  merged triangulation, and the destination of `farright' is the rightmost */
9424 /*  vertex.                                                                  */
9425 /*                                                                           */
9426 /*****************************************************************************/
9427 
9428 #ifdef ANSI_DECLARATORS
9429 void mergehulls(struct mesh *m, struct behavior *b, struct otri *farleft,
9430                 struct otri *innerleft, struct otri *innerright,
9431                 struct otri *farright, int axis)
9432 #else /* not ANSI_DECLARATORS */
9433 void mergehulls(m, b, farleft, innerleft, innerright, farright, axis)
9434 struct mesh *m;
9435 struct behavior *b;
9436 struct otri *farleft;
9437 struct otri *innerleft;
9438 struct otri *innerright;
9439 struct otri *farright;
9440 int axis;
9441 #endif /* not ANSI_DECLARATORS */
9442 
9443 {
9444   struct otri leftcand, rightcand;
9445   struct otri baseedge;
9446   struct otri nextedge;
9447   struct otri sidecasing, topcasing, outercasing;
9448   struct otri checkedge;
9449   vertex innerleftdest;
9450   vertex innerrightorg;
9451   vertex innerleftapex, innerrightapex;
9452   vertex farleftpt, farrightpt;
9453   vertex farleftapex, farrightapex;
9454   vertex lowerleft, lowerright;
9455   vertex upperleft, upperright;
9456   vertex nextapex;
9457   vertex checkvertex;
9458   int changemade;
9459   int badedge;
9460   int leftfinished, rightfinished;
9461   triangle ptr;                         /* Temporary variable used by sym(). */
9462 
9463   dest(*innerleft, innerleftdest);
9464   apex(*innerleft, innerleftapex);
9465   org(*innerright, innerrightorg);
9466   apex(*innerright, innerrightapex);
9467   /* Special treatment for horizontal cuts. */
9468   if (b->dwyer && (axis == 1)) {
9469     org(*farleft, farleftpt);
9470     apex(*farleft, farleftapex);
9471     dest(*farright, farrightpt);
9472     apex(*farright, farrightapex);
9473     /* The pointers to the extremal vertices are shifted to point to the */
9474     /*   topmost and bottommost vertex of each hull, rather than the     */
9475     /*   leftmost and rightmost vertices.                                */
9476     while (farleftapex[1] < farleftpt[1]) {
9477       lnextself(*farleft);
9478       symself(*farleft);
9479       farleftpt = farleftapex;
9480       apex(*farleft, farleftapex);
9481     }
9482     sym(*innerleft, checkedge);
9483     apex(checkedge, checkvertex);
9484     while (checkvertex[1] > innerleftdest[1]) {
9485       lnext(checkedge, *innerleft);
9486       innerleftapex = innerleftdest;
9487       innerleftdest = checkvertex;
9488       sym(*innerleft, checkedge);
9489       apex(checkedge, checkvertex);
9490     }
9491     while (innerrightapex[1] < innerrightorg[1]) {
9492       lnextself(*innerright);
9493       symself(*innerright);
9494       innerrightorg = innerrightapex;
9495       apex(*innerright, innerrightapex);
9496     }
9497     sym(*farright, checkedge);
9498     apex(checkedge, checkvertex);
9499     while (checkvertex[1] > farrightpt[1]) {
9500       lnext(checkedge, *farright);
9501       farrightpt = checkvertex;
9502       sym(*farright, checkedge);
9503       apex(checkedge, checkvertex);
9504     }
9505   }
9506   /* Find a line tangent to and below both hulls. */
9507   do {
9508     changemade = 0;
9509     /* Make innerleftdest the "bottommost" vertex of the left hull. */
9510     if (counterclockwise(m, b, innerleftdest, innerleftapex, innerrightorg) >
9511         0.0) {
9512       lprevself(*innerleft);
9513       symself(*innerleft);
9514       innerleftdest = innerleftapex;
9515       apex(*innerleft, innerleftapex);
9516       changemade = 1;
9517     }
9518     /* Make innerrightorg the "bottommost" vertex of the right hull. */
9519     if (counterclockwise(m, b, innerrightapex, innerrightorg, innerleftdest) >
9520         0.0) {
9521       lnextself(*innerright);
9522       symself(*innerright);
9523       innerrightorg = innerrightapex;
9524       apex(*innerright, innerrightapex);
9525       changemade = 1;
9526     }
9527   } while (changemade);
9528   /* Find the two candidates to be the next "gear tooth." */
9529   sym(*innerleft, leftcand);
9530   sym(*innerright, rightcand);
9531   /* Create the bottom new bounding triangle. */
9532   maketriangle(m, b, &baseedge);
9533   /* Connect it to the bounding boxes of the left and right triangulations. */
9534   bond(baseedge, *innerleft);
9535   lnextself(baseedge);
9536   bond(baseedge, *innerright);
9537   lnextself(baseedge);
9538   setorg(baseedge, innerrightorg);
9539   setdest(baseedge, innerleftdest);
9540   /* Apex is intentionally left NULL. */
9541   if (b->verbose > 2) {
9542     printf("  Creating base bounding ");
9543     printtriangle(m, b, &baseedge);
9544   }
9545   /* Fix the extreme triangles if necessary. */
9546   org(*farleft, farleftpt);
9547   if (innerleftdest == farleftpt) {
9548     lnext(baseedge, *farleft);
9549   }
9550   dest(*farright, farrightpt);
9551   if (innerrightorg == farrightpt) {
9552     lprev(baseedge, *farright);
9553   }
9554   /* The vertices of the current knitting edge. */
9555   lowerleft = innerleftdest;
9556   lowerright = innerrightorg;
9557   /* The candidate vertices for knitting. */
9558   apex(leftcand, upperleft);
9559   apex(rightcand, upperright);
9560   /* Walk up the gap between the two triangulations, knitting them together. */
9561   while (1) {
9562     /* Have we reached the top?  (This isn't quite the right question,       */
9563     /*   because even though the left triangulation might seem finished now, */
9564     /*   moving up on the right triangulation might reveal a new vertex of   */
9565     /*   the left triangulation.  And vice-versa.)                           */
9566     leftfinished = counterclockwise(m, b, upperleft, lowerleft, lowerright) <=
9567                    0.0;
9568     rightfinished = counterclockwise(m, b, upperright, lowerleft, lowerright)
9569                  <= 0.0;
9570     if (leftfinished && rightfinished) {
9571       /* Create the top new bounding triangle. */
9572       maketriangle(m, b, &nextedge);
9573       setorg(nextedge, lowerleft);
9574       setdest(nextedge, lowerright);
9575       /* Apex is intentionally left NULL. */
9576       /* Connect it to the bounding boxes of the two triangulations. */
9577       bond(nextedge, baseedge);
9578       lnextself(nextedge);
9579       bond(nextedge, rightcand);
9580       lnextself(nextedge);
9581       bond(nextedge, leftcand);
9582       if (b->verbose > 2) {
9583         printf("  Creating top bounding ");
9584         printtriangle(m, b, &nextedge);
9585       }
9586       /* Special treatment for horizontal cuts. */
9587       if (b->dwyer && (axis == 1)) {
9588         org(*farleft, farleftpt);
9589         apex(*farleft, farleftapex);
9590         dest(*farright, farrightpt);
9591         apex(*farright, farrightapex);
9592         sym(*farleft, checkedge);
9593         apex(checkedge, checkvertex);
9594         /* The pointers to the extremal vertices are restored to the  */
9595         /*   leftmost and rightmost vertices (rather than topmost and */
9596         /*   bottommost).                                             */
9597         while (checkvertex[0] < farleftpt[0]) {
9598           lprev(checkedge, *farleft);
9599           farleftpt = checkvertex;
9600           sym(*farleft, checkedge);
9601           apex(checkedge, checkvertex);
9602         }
9603         while (farrightapex[0] > farrightpt[0]) {
9604           lprevself(*farright);
9605           symself(*farright);
9606           farrightpt = farrightapex;
9607           apex(*farright, farrightapex);
9608         }
9609       }
9610       return;
9611     }
9612     /* Consider eliminating edges from the left triangulation. */
9613     if (!leftfinished) {
9614       /* What vertex would be exposed if an edge were deleted? */
9615       lprev(leftcand, nextedge);
9616       symself(nextedge);
9617       apex(nextedge, nextapex);
9618       /* If nextapex is NULL, then no vertex would be exposed; the */
9619       /*   triangulation would have been eaten right through.      */
9620       if (nextapex != (vertex) NULL) {
9621         /* Check whether the edge is Delaunay. */
9622         badedge = incircle(m, b, lowerleft, lowerright, upperleft, nextapex) >
9623                   0.0;
9624         while (badedge) {
9625           /* Eliminate the edge with an edge flip.  As a result, the    */
9626           /*   left triangulation will have one more boundary triangle. */
9627           lnextself(nextedge);
9628           sym(nextedge, topcasing);
9629           lnextself(nextedge);
9630           sym(nextedge, sidecasing);
9631           bond(nextedge, topcasing);
9632           bond(leftcand, sidecasing);
9633           lnextself(leftcand);
9634           sym(leftcand, outercasing);
9635           lprevself(nextedge);
9636           bond(nextedge, outercasing);
9637           /* Correct the vertices to reflect the edge flip. */
9638           setorg(leftcand, lowerleft);
9639           setdest(leftcand, NULL);
9640           setapex(leftcand, nextapex);
9641           setorg(nextedge, NULL);
9642           setdest(nextedge, upperleft);
9643           setapex(nextedge, nextapex);
9644           /* Consider the newly exposed vertex. */
9645           upperleft = nextapex;
9646           /* What vertex would be exposed if another edge were deleted? */
9647           otricopy(sidecasing, nextedge);
9648           apex(nextedge, nextapex);
9649           if (nextapex != (vertex) NULL) {
9650             /* Check whether the edge is Delaunay. */
9651             badedge = incircle(m, b, lowerleft, lowerright, upperleft,
9652                                nextapex) > 0.0;
9653           } else {
9654             /* Avoid eating right through the triangulation. */
9655             badedge = 0;
9656           }
9657         }
9658       }
9659     }
9660     /* Consider eliminating edges from the right triangulation. */
9661     if (!rightfinished) {
9662       /* What vertex would be exposed if an edge were deleted? */
9663       lnext(rightcand, nextedge);
9664       symself(nextedge);
9665       apex(nextedge, nextapex);
9666       /* If nextapex is NULL, then no vertex would be exposed; the */
9667       /*   triangulation would have been eaten right through.      */
9668       if (nextapex != (vertex) NULL) {
9669         /* Check whether the edge is Delaunay. */
9670         badedge = incircle(m, b, lowerleft, lowerright, upperright, nextapex) >
9671                   0.0;
9672         while (badedge) {
9673           /* Eliminate the edge with an edge flip.  As a result, the     */
9674           /*   right triangulation will have one more boundary triangle. */
9675           lprevself(nextedge);
9676           sym(nextedge, topcasing);
9677           lprevself(nextedge);
9678           sym(nextedge, sidecasing);
9679           bond(nextedge, topcasing);
9680           bond(rightcand, sidecasing);
9681           lprevself(rightcand);
9682           sym(rightcand, outercasing);
9683           lnextself(nextedge);
9684           bond(nextedge, outercasing);
9685           /* Correct the vertices to reflect the edge flip. */
9686           setorg(rightcand, NULL);
9687           setdest(rightcand, lowerright);
9688           setapex(rightcand, nextapex);
9689           setorg(nextedge, upperright);
9690           setdest(nextedge, NULL);
9691           setapex(nextedge, nextapex);
9692           /* Consider the newly exposed vertex. */
9693           upperright = nextapex;
9694           /* What vertex would be exposed if another edge were deleted? */
9695           otricopy(sidecasing, nextedge);
9696           apex(nextedge, nextapex);
9697           if (nextapex != (vertex) NULL) {
9698             /* Check whether the edge is Delaunay. */
9699             badedge = incircle(m, b, lowerleft, lowerright, upperright,
9700                                nextapex) > 0.0;
9701           } else {
9702             /* Avoid eating right through the triangulation. */
9703             badedge = 0;
9704           }
9705         }
9706       }
9707     }
9708     if (leftfinished || (!rightfinished &&
9709            (incircle(m, b, upperleft, lowerleft, lowerright, upperright) >
9710             0.0))) {
9711       /* Knit the triangulations, adding an edge from `lowerleft' */
9712       /*   to `upperright'.                                       */
9713       bond(baseedge, rightcand);
9714       lprev(rightcand, baseedge);
9715       setdest(baseedge, lowerleft);
9716       lowerright = upperright;
9717       sym(baseedge, rightcand);
9718       apex(rightcand, upperright);
9719     } else {
9720       /* Knit the triangulations, adding an edge from `upperleft' */
9721       /*   to `lowerright'.                                       */
9722       bond(baseedge, leftcand);
9723       lnext(leftcand, baseedge);
9724       setorg(baseedge, lowerright);
9725       lowerleft = upperleft;
9726       sym(baseedge, leftcand);
9727       apex(leftcand, upperleft);
9728     }
9729     if (b->verbose > 2) {
9730       printf("  Connecting ");
9731       printtriangle(m, b, &baseedge);
9732     }
9733   }
9734 }
9735 
9736 /*****************************************************************************/
9737 /*                                                                           */
9738 /*  divconqrecurse()   Recursively form a Delaunay triangulation by the      */
9739 /*                     divide-and-conquer method.                            */
9740 /*                                                                           */
9741 /*  Recursively breaks down the problem into smaller pieces, which are       */
9742 /*  knitted together by mergehulls().  The base cases (problems of two or    */
9743 /*  three vertices) are handled specially here.                              */
9744 /*                                                                           */
9745 /*  On completion, `farleft' and `farright' are bounding triangles such that */
9746 /*  the origin of `farleft' is the leftmost vertex (breaking ties by         */
9747 /*  choosing the highest leftmost vertex), and the destination of            */
9748 /*  `farright' is the rightmost vertex (breaking ties by choosing the        */
9749 /*  lowest rightmost vertex).                                                */
9750 /*                                                                           */
9751 /*****************************************************************************/
9752 
9753 #ifdef ANSI_DECLARATORS
9754 void divconqrecurse(struct mesh *m, struct behavior *b, vertex *sortarray,
9755                     int vertices, int axis,
9756                     struct otri *farleft, struct otri *farright)
9757 #else /* not ANSI_DECLARATORS */
9758 void divconqrecurse(m, b, sortarray, vertices, axis, farleft, farright)
9759 struct mesh *m;
9760 struct behavior *b;
9761 vertex *sortarray;
9762 int vertices;
9763 int axis;
9764 struct otri *farleft;
9765 struct otri *farright;
9766 #endif /* not ANSI_DECLARATORS */
9767 
9768 {
9769   struct otri midtri, tri1, tri2, tri3;
9770   struct otri innerleft, innerright;
9771   REAL area;
9772   int divider;
9773 
9774   if (b->verbose > 2) {
9775     printf("  Triangulating %d vertices.\n", vertices);
9776   }
9777   if (vertices == 2) {
9778     /* The triangulation of two vertices is an edge.  An edge is */
9779     /*   represented by two bounding triangles.                  */
9780     maketriangle(m, b, farleft);
9781     setorg(*farleft, sortarray[0]);
9782     setdest(*farleft, sortarray[1]);
9783     /* The apex is intentionally left NULL. */
9784     maketriangle(m, b, farright);
9785     setorg(*farright, sortarray[1]);
9786     setdest(*farright, sortarray[0]);
9787     /* The apex is intentionally left NULL. */
9788     bond(*farleft, *farright);
9789     lprevself(*farleft);
9790     lnextself(*farright);
9791     bond(*farleft, *farright);
9792     lprevself(*farleft);
9793     lnextself(*farright);
9794     bond(*farleft, *farright);
9795     if (b->verbose > 2) {
9796       printf("  Creating ");
9797       printtriangle(m, b, farleft);
9798       printf("  Creating ");
9799       printtriangle(m, b, farright);
9800     }
9801     /* Ensure that the origin of `farleft' is sortarray[0]. */
9802     lprev(*farright, *farleft);
9803     return;
9804   } else if (vertices == 3) {
9805     /* The triangulation of three vertices is either a triangle (with */
9806     /*   three bounding triangles) or two edges (with four bounding   */
9807     /*   triangles).  In either case, four triangles are created.     */
9808     maketriangle(m, b, &midtri);
9809     maketriangle(m, b, &tri1);
9810     maketriangle(m, b, &tri2);
9811     maketriangle(m, b, &tri3);
9812     area = counterclockwise(m, b, sortarray[0], sortarray[1], sortarray[2]);
9813     if (area == 0.0) {
9814       /* Three collinear vertices; the triangulation is two edges. */
9815       setorg(midtri, sortarray[0]);
9816       setdest(midtri, sortarray[1]);
9817       setorg(tri1, sortarray[1]);
9818       setdest(tri1, sortarray[0]);
9819       setorg(tri2, sortarray[2]);
9820       setdest(tri2, sortarray[1]);
9821       setorg(tri3, sortarray[1]);
9822       setdest(tri3, sortarray[2]);
9823       /* All apices are intentionally left NULL. */
9824       bond(midtri, tri1);
9825       bond(tri2, tri3);
9826       lnextself(midtri);
9827       lprevself(tri1);
9828       lnextself(tri2);
9829       lprevself(tri3);
9830       bond(midtri, tri3);
9831       bond(tri1, tri2);
9832       lnextself(midtri);
9833       lprevself(tri1);
9834       lnextself(tri2);
9835       lprevself(tri3);
9836       bond(midtri, tri1);
9837       bond(tri2, tri3);
9838       /* Ensure that the origin of `farleft' is sortarray[0]. */
9839       otricopy(tri1, *farleft);
9840       /* Ensure that the destination of `farright' is sortarray[2]. */
9841       otricopy(tri2, *farright);
9842     } else {
9843       /* The three vertices are not collinear; the triangulation is one */
9844       /*   triangle, namely `midtri'.                                   */
9845       setorg(midtri, sortarray[0]);
9846       setdest(tri1, sortarray[0]);
9847       setorg(tri3, sortarray[0]);
9848       /* Apices of tri1, tri2, and tri3 are left NULL. */
9849       if (area > 0.0) {
9850         /* The vertices are in counterclockwise order. */
9851         setdest(midtri, sortarray[1]);
9852         setorg(tri1, sortarray[1]);
9853         setdest(tri2, sortarray[1]);
9854         setapex(midtri, sortarray[2]);
9855         setorg(tri2, sortarray[2]);
9856         setdest(tri3, sortarray[2]);
9857       } else {
9858         /* The vertices are in clockwise order. */
9859         setdest(midtri, sortarray[2]);
9860         setorg(tri1, sortarray[2]);
9861         setdest(tri2, sortarray[2]);
9862         setapex(midtri, sortarray[1]);
9863         setorg(tri2, sortarray[1]);
9864         setdest(tri3, sortarray[1]);
9865       }
9866       /* The topology does not depend on how the vertices are ordered. */
9867       bond(midtri, tri1);
9868       lnextself(midtri);
9869       bond(midtri, tri2);
9870       lnextself(midtri);
9871       bond(midtri, tri3);
9872       lprevself(tri1);
9873       lnextself(tri2);
9874       bond(tri1, tri2);
9875       lprevself(tri1);
9876       lprevself(tri3);
9877       bond(tri1, tri3);
9878       lnextself(tri2);
9879       lprevself(tri3);
9880       bond(tri2, tri3);
9881       /* Ensure that the origin of `farleft' is sortarray[0]. */
9882       otricopy(tri1, *farleft);
9883       /* Ensure that the destination of `farright' is sortarray[2]. */
9884       if (area > 0.0) {
9885         otricopy(tri2, *farright);
9886       } else {
9887         lnext(*farleft, *farright);
9888       }
9889     }
9890     if (b->verbose > 2) {
9891       printf("  Creating ");
9892       printtriangle(m, b, &midtri);
9893       printf("  Creating ");
9894       printtriangle(m, b, &tri1);
9895       printf("  Creating ");
9896       printtriangle(m, b, &tri2);
9897       printf("  Creating ");
9898       printtriangle(m, b, &tri3);
9899     }
9900     return;
9901   } else {
9902     /* Split the vertices in half. */
9903     divider = vertices >> 1;
9904     /* Recursively triangulate each half. */
9905     divconqrecurse(m, b, sortarray, divider, 1 - axis, farleft, &innerleft);
9906     divconqrecurse(m, b, &sortarray[divider], vertices - divider, 1 - axis,
9907                    &innerright, farright);
9908     if (b->verbose > 1) {
9909       printf("  Joining triangulations with %d and %d vertices.\n", divider,
9910              vertices - divider);
9911     }
9912     /* Merge the two triangulations into one. */
9913     mergehulls(m, b, farleft, &innerleft, &innerright, farright, axis);
9914   }
9915 }
9916 
9917 #ifdef ANSI_DECLARATORS
9918 long removeghosts(struct mesh *m, struct behavior *b, struct otri *startghost)
9919 #else /* not ANSI_DECLARATORS */
9920 long removeghosts(m, b, startghost)
9921 struct mesh *m;
9922 struct behavior *b;
9923 struct otri *startghost;
9924 #endif /* not ANSI_DECLARATORS */
9925 
9926 {
9927   struct otri searchedge;
9928   struct otri dissolveedge;
9929   struct otri deadtriangle;
9930   vertex markorg;
9931   long hullsize;
9932   triangle ptr;                         /* Temporary variable used by sym(). */
9933 
9934   if (b->verbose) {
9935     printf("  Removing ghost triangles.\n");
9936   }
9937   /* Find an edge on the convex hull to start point location from. */
9938   lprev(*startghost, searchedge);
9939   symself(searchedge);
9940   m->dummytri[0] = encode(searchedge);
9941   /* Remove the bounding box and count the convex hull edges. */
9942   otricopy(*startghost, dissolveedge);
9943   hullsize = 0;
9944   do {
9945     hullsize++;
9946     lnext(dissolveedge, deadtriangle);
9947     lprevself(dissolveedge);
9948     symself(dissolveedge);
9949     /* If no PSLG is involved, set the boundary markers of all the vertices */
9950     /*   on the convex hull.  If a PSLG is used, this step is done later.   */
9951     if (!b->poly) {
9952       /* Watch out for the case where all the input vertices are collinear. */
9953       if (dissolveedge.tri != m->dummytri) {
9954         org(dissolveedge, markorg);
9955         if (vertexmark(markorg) == 0) {
9956           setvertexmark(markorg, 1);
9957         }
9958       }
9959     }
9960     /* Remove a bounding triangle from a convex hull triangle. */
9961     dissolve(dissolveedge);
9962     /* Find the next bounding triangle. */
9963     sym(deadtriangle, dissolveedge);
9964     /* Delete the bounding triangle. */
9965     triangledealloc(m, deadtriangle.tri);
9966   } while (!otriequal(dissolveedge, *startghost));
9967   return hullsize;
9968 }
9969 
9970 /*****************************************************************************/
9971 /*                                                                           */
9972 /*  divconqdelaunay()   Form a Delaunay triangulation by the divide-and-     */
9973 /*                      conquer method.                                      */
9974 /*                                                                           */
9975 /*  Sorts the vertices, calls a recursive procedure to triangulate them, and */
9976 /*  removes the bounding box, setting boundary markers as appropriate.       */
9977 /*                                                                           */
9978 /*****************************************************************************/
9979 
9980 #ifdef ANSI_DECLARATORS
9981 long divconqdelaunay(struct mesh *m, struct behavior *b)
9982 #else /* not ANSI_DECLARATORS */
9983 long divconqdelaunay(m, b)
9984 struct mesh *m;
9985 struct behavior *b;
9986 #endif /* not ANSI_DECLARATORS */
9987 
9988 {
9989   vertex *sortarray;
9990   struct otri hullleft, hullright;
9991   int divider;
9992   int i, j;
9993 
9994   if (b->verbose) {
9995     printf("  Sorting vertices.\n");
9996   }
9997 
9998   /* Allocate an array of pointers to vertices for sorting. */
9999   sortarray = (vertex *) trimalloc(m->invertices * (int) sizeof(vertex));
10000   traversalinit(&m->vertices);
10001   for (i = 0; i < m->invertices; i++) {
10002     sortarray[i] = vertextraverse(m);
10003   }
10004   /* Sort the vertices. */
10005   vertexsort(sortarray, m->invertices);
10006   /* Discard duplicate vertices, which can really mess up the algorithm. */
10007   i = 0;
10008   for (j = 1; j < m->invertices; j++) {
10009     if ((sortarray[i][0] == sortarray[j][0])
10010         && (sortarray[i][1] == sortarray[j][1])) {
10011       if (!b->quiet) {
10012         printf(
10013 "Warning:  A duplicate vertex at (%.12g, %.12g) appeared and was ignored.\n",
10014                sortarray[j][0], sortarray[j][1]);
10015       }
10016       setvertextype(sortarray[j], UNDEADVERTEX);
10017       m->undeads++;
10018     } else {
10019       i++;
10020       sortarray[i] = sortarray[j];
10021     }
10022   }
10023   i++;
10024   if (b->dwyer) {
10025     /* Re-sort the array of vertices to accommodate alternating cuts. */
10026     divider = i >> 1;
10027     if (i - divider >= 2) {
10028       if (divider >= 2) {
10029         alternateaxes(sortarray, divider, 1);
10030       }
10031       alternateaxes(&sortarray[divider], i - divider, 1);
10032     }
10033   }
10034 
10035   if (b->verbose) {
10036     printf("  Forming triangulation.\n");
10037   }
10038 
10039   /* Form the Delaunay triangulation. */
10040   divconqrecurse(m, b, sortarray, i, 0, &hullleft, &hullright);
10041   trifree((void *) sortarray);
10042 
10043   return removeghosts(m, b, &hullleft);
10044 }
10045 
10046 /**                                                                         **/
10047 /**                                                                         **/
10048 /********* Divide-and-conquer Delaunay triangulation ends here       *********/
10049 
10050 /********* Incremental Delaunay triangulation begins here            *********/
10051 /**                                                                         **/
10052 /**                                                                         **/
10053 
10054 /*****************************************************************************/
10055 /*                                                                           */
10056 /*  boundingbox()   Form an "infinite" bounding triangle to insert vertices  */
10057 /*                  into.                                                    */
10058 /*                                                                           */
10059 /*  The vertices at "infinity" are assigned finite coordinates, which are    */
10060 /*  used by the point location routines, but (mostly) ignored by the         */
10061 /*  Delaunay edge flip routines.                                             */
10062 /*                                                                           */
10063 /*****************************************************************************/
10064 
10065 #ifndef REDUCED
10066 
10067 #ifdef ANSI_DECLARATORS
10068 void boundingbox(struct mesh *m, struct behavior *b)
10069 #else /* not ANSI_DECLARATORS */
10070 void boundingbox(m, b)
10071 struct mesh *m;
10072 struct behavior *b;
10073 #endif /* not ANSI_DECLARATORS */
10074 
10075 {
10076   struct otri inftri;          /* Handle for the triangular bounding box. */
10077   REAL width;
10078 
10079   if (b->verbose) {
10080     printf("  Creating triangular bounding box.\n");
10081   }
10082   /* Find the width (or height, whichever is larger) of the triangulation. */
10083   width = m->xmax - m->xmin;
10084   if (m->ymax - m->ymin > width) {
10085     width = m->ymax - m->ymin;
10086   }
10087   if (width == 0.0) {
10088     width = 1.0;
10089   }
10090   /* Create the vertices of the bounding box. */
10091   m->infvertex1 = (vertex) trimalloc(m->vertices.itembytes);
10092   m->infvertex2 = (vertex) trimalloc(m->vertices.itembytes);
10093   m->infvertex3 = (vertex) trimalloc(m->vertices.itembytes);
10094   m->infvertex1[0] = m->xmin - 50.0 * width;
10095   m->infvertex1[1] = m->ymin - 40.0 * width;
10096   m->infvertex2[0] = m->xmax + 50.0 * width;
10097   m->infvertex2[1] = m->ymin - 40.0 * width;
10098   m->infvertex3[0] = 0.5 * (m->xmin + m->xmax);
10099   m->infvertex3[1] = m->ymax + 60.0 * width;
10100 
10101   /* Create the bounding box. */
10102   maketriangle(m, b, &inftri);
10103   setorg(inftri, m->infvertex1);
10104   setdest(inftri, m->infvertex2);
10105   setapex(inftri, m->infvertex3);
10106   /* Link dummytri to the bounding box so we can always find an */
10107   /*   edge to begin searching (point location) from.           */
10108   m->dummytri[0] = (triangle) inftri.tri;
10109   if (b->verbose > 2) {
10110     printf("  Creating ");
10111     printtriangle(m, b, &inftri);
10112   }
10113 }
10114 
10115 #endif /* not REDUCED */
10116 
10117 /*****************************************************************************/
10118 /*                                                                           */
10119 /*  removebox()   Remove the "infinite" bounding triangle, setting boundary  */
10120 /*                markers as appropriate.                                    */
10121 /*                                                                           */
10122 /*  The triangular bounding box has three boundary triangles (one for each   */
10123 /*  side of the bounding box), and a bunch of triangles fanning out from     */
10124 /*  the three bounding box vertices (one triangle for each edge of the       */
10125 /*  convex hull of the inner mesh).  This routine removes these triangles.   */
10126 /*                                                                           */
10127 /*  Returns the number of edges on the convex hull of the triangulation.     */
10128 /*                                                                           */
10129 /*****************************************************************************/
10130 
10131 #ifndef REDUCED
10132 
10133 #ifdef ANSI_DECLARATORS
10134 long removebox(struct mesh *m, struct behavior *b)
10135 #else /* not ANSI_DECLARATORS */
10136 long removebox(m, b)
10137 struct mesh *m;
10138 struct behavior *b;
10139 #endif /* not ANSI_DECLARATORS */
10140 
10141 {
10142   struct otri deadtriangle;
10143   struct otri searchedge;
10144   struct otri checkedge;
10145   struct otri nextedge, finaledge, dissolveedge;
10146   vertex markorg;
10147   long hullsize;
10148   triangle ptr;                         /* Temporary variable used by sym(). */
10149 
10150   if (b->verbose) {
10151     printf("  Removing triangular bounding box.\n");
10152   }
10153   /* Find a boundary triangle. */
10154   nextedge.tri = m->dummytri;
10155   nextedge.orient = 0;
10156   symself(nextedge);
10157   /* Mark a place to stop. */
10158   lprev(nextedge, finaledge);
10159   lnextself(nextedge);
10160   symself(nextedge);
10161   /* Find a triangle (on the boundary of the vertex set) that isn't */
10162   /*   a bounding box triangle.                                     */
10163   lprev(nextedge, searchedge);
10164   symself(searchedge);
10165   /* Check whether nextedge is another boundary triangle */
10166   /*   adjacent to the first one.                        */
10167   lnext(nextedge, checkedge);
10168   symself(checkedge);
10169   if (checkedge.tri == m->dummytri) {
10170     /* Go on to the next triangle.  There are only three boundary   */
10171     /*   triangles, and this next triangle cannot be the third one, */
10172     /*   so it's safe to stop here.                                 */
10173     lprevself(searchedge);
10174     symself(searchedge);
10175   }
10176   /* Find a new boundary edge to search from, as the current search */
10177   /*   edge lies on a bounding box triangle and will be deleted.    */
10178   m->dummytri[0] = encode(searchedge);
10179   hullsize = -2l;
10180   while (!otriequal(nextedge, finaledge)) {
10181     hullsize++;
10182     lprev(nextedge, dissolveedge);
10183     symself(dissolveedge);
10184     /* If not using a PSLG, the vertices should be marked now. */
10185     /*   (If using a PSLG, markhull() will do the job.)        */
10186     if (!b->poly) {
10187       /* Be careful!  One must check for the case where all the input     */
10188       /*   vertices are collinear, and thus all the triangles are part of */
10189       /*   the bounding box.  Otherwise, the setvertexmark() call below   */
10190       /*   will cause a bad pointer reference.                            */
10191       if (dissolveedge.tri != m->dummytri) {
10192         org(dissolveedge, markorg);
10193         if (vertexmark(markorg) == 0) {
10194           setvertexmark(markorg, 1);
10195         }
10196       }
10197     }
10198     /* Disconnect the bounding box triangle from the mesh triangle. */
10199     dissolve(dissolveedge);
10200     lnext(nextedge, deadtriangle);
10201     sym(deadtriangle, nextedge);
10202     /* Get rid of the bounding box triangle. */
10203     triangledealloc(m, deadtriangle.tri);
10204     /* Do we need to turn the corner? */
10205     if (nextedge.tri == m->dummytri) {
10206       /* Turn the corner. */
10207       otricopy(dissolveedge, nextedge);
10208     }
10209   }
10210   triangledealloc(m, finaledge.tri);
10211 
10212   trifree((void *) m->infvertex1);  /* Deallocate the bounding box vertices. */
10213   trifree((void *) m->infvertex2);
10214   trifree((void *) m->infvertex3);
10215 
10216   return hullsize;
10217 }
10218 
10219 #endif /* not REDUCED */
10220 
10221 /*****************************************************************************/
10222 /*                                                                           */
10223 /*  incrementaldelaunay()   Form a Delaunay triangulation by incrementally   */
10224 /*                          inserting vertices.                              */
10225 /*                                                                           */
10226 /*  Returns the number of edges on the convex hull of the triangulation.     */
10227 /*                                                                           */
10228 /*****************************************************************************/
10229 
10230 #ifndef REDUCED
10231 
10232 #ifdef ANSI_DECLARATORS
10233 long incrementaldelaunay(struct mesh *m, struct behavior *b)
10234 #else /* not ANSI_DECLARATORS */
10235 long incrementaldelaunay(m, b)
10236 struct mesh *m;
10237 struct behavior *b;
10238 #endif /* not ANSI_DECLARATORS */
10239 
10240 {
10241   struct otri starttri;
10242   vertex vertexloop;
10243 
10244   /* Create a triangular bounding box. */
10245   boundingbox(m, b);
10246   if (b->verbose) {
10247     printf("  Incrementally inserting vertices.\n");
10248   }
10249   traversalinit(&m->vertices);
10250   vertexloop = vertextraverse(m);
10251   while (vertexloop != (vertex) NULL) {
10252     starttri.tri = m->dummytri;
10253     if (insertvertex(m, b, vertexloop, &starttri, (struct osub *) NULL, 0, 0)
10254         == DUPLICATEVERTEX) {
10255       if (!b->quiet) {
10256         printf(
10257 "Warning:  A duplicate vertex at (%.12g, %.12g) appeared and was ignored.\n",
10258                vertexloop[0], vertexloop[1]);
10259       }
10260       setvertextype(vertexloop, UNDEADVERTEX);
10261       m->undeads++;
10262     }
10263     vertexloop = vertextraverse(m);
10264   }
10265   /* Remove the bounding box. */
10266   return removebox(m, b);
10267 }
10268 
10269 #endif /* not REDUCED */
10270 
10271 /**                                                                         **/
10272 /**                                                                         **/
10273 /********* Incremental Delaunay triangulation ends here              *********/
10274 
10275 /********* Sweepline Delaunay triangulation begins here              *********/
10276 /**                                                                         **/
10277 /**                                                                         **/
10278 
10279 #ifndef REDUCED
10280 
10281 #ifdef ANSI_DECLARATORS
10282 void eventheapinsert(struct event **heap, int heapsize, struct event *newevent)
10283 #else /* not ANSI_DECLARATORS */
10284 void eventheapinsert(heap, heapsize, newevent)
10285 struct event **heap;
10286 int heapsize;
10287 struct event *newevent;
10288 #endif /* not ANSI_DECLARATORS */
10289 
10290 {
10291   REAL eventx, eventy;
10292   int eventnum;
10293   int parent;
10294   int notdone;
10295 
10296   eventx = newevent->xkey;
10297   eventy = newevent->ykey;
10298   eventnum = heapsize;
10299   notdone = eventnum > 0;
10300   while (notdone) {
10301     parent = (eventnum - 1) >> 1;
10302     if ((heap[parent]->ykey < eventy) ||
10303         ((heap[parent]->ykey == eventy)
10304          && (heap[parent]->xkey <= eventx))) {
10305       notdone = 0;
10306     } else {
10307       heap[eventnum] = heap[parent];
10308       heap[eventnum]->heapposition = eventnum;
10309 
10310       eventnum = parent;
10311       notdone = eventnum > 0;
10312     }
10313   }
10314   heap[eventnum] = newevent;
10315   newevent->heapposition = eventnum;
10316 }
10317 
10318 #endif /* not REDUCED */
10319 
10320 #ifndef REDUCED
10321 
10322 #ifdef ANSI_DECLARATORS
10323 void eventheapify(struct event **heap, int heapsize, int eventnum)
10324 #else /* not ANSI_DECLARATORS */
10325 void eventheapify(heap, heapsize, eventnum)
10326 struct event **heap;
10327 int heapsize;
10328 int eventnum;
10329 #endif /* not ANSI_DECLARATORS */
10330 
10331 {
10332   struct event *thisevent;
10333   REAL eventx, eventy;
10334   int leftchild, rightchild;
10335   int smallest;
10336   int notdone;
10337 
10338   thisevent = heap[eventnum];
10339   eventx = thisevent->xkey;
10340   eventy = thisevent->ykey;
10341   leftchild = 2 * eventnum + 1;
10342   notdone = leftchild < heapsize;
10343   while (notdone) {
10344     if ((heap[leftchild]->ykey < eventy) ||
10345         ((heap[leftchild]->ykey == eventy)
10346          && (heap[leftchild]->xkey < eventx))) {
10347       smallest = leftchild;
10348     } else {
10349       smallest = eventnum;
10350     }
10351     rightchild = leftchild + 1;
10352     if (rightchild < heapsize) {
10353       if ((heap[rightchild]->ykey < heap[smallest]->ykey) ||
10354           ((heap[rightchild]->ykey == heap[smallest]->ykey)
10355            && (heap[rightchild]->xkey < heap[smallest]->xkey))) {
10356         smallest = rightchild;
10357       }
10358     }
10359     if (smallest == eventnum) {
10360       notdone = 0;
10361     } else {
10362       heap[eventnum] = heap[smallest];
10363       heap[eventnum]->heapposition = eventnum;
10364       heap[smallest] = thisevent;
10365       thisevent->heapposition = smallest;
10366 
10367       eventnum = smallest;
10368       leftchild = 2 * eventnum + 1;
10369       notdone = leftchild < heapsize;
10370     }
10371   }
10372 }
10373 
10374 #endif /* not REDUCED */
10375 
10376 #ifndef REDUCED
10377 
10378 #ifdef ANSI_DECLARATORS
10379 void eventheapdelete(struct event **heap, int heapsize, int eventnum)
10380 #else /* not ANSI_DECLARATORS */
10381 void eventheapdelete(heap, heapsize, eventnum)
10382 struct event **heap;
10383 int heapsize;
10384 int eventnum;
10385 #endif /* not ANSI_DECLARATORS */
10386 
10387 {
10388   struct event *moveevent;
10389   REAL eventx, eventy;
10390   int parent;
10391   int notdone;
10392 
10393   moveevent = heap[heapsize - 1];
10394   if (eventnum > 0) {
10395     eventx = moveevent->xkey;
10396     eventy = moveevent->ykey;
10397     do {
10398       parent = (eventnum - 1) >> 1;
10399       if ((heap[parent]->ykey < eventy) ||
10400           ((heap[parent]->ykey == eventy)
10401            && (heap[parent]->xkey <= eventx))) {
10402         notdone = 0;
10403       } else {
10404         heap[eventnum] = heap[parent];
10405         heap[eventnum]->heapposition = eventnum;
10406 
10407         eventnum = parent;
10408         notdone = eventnum > 0;
10409       }
10410     } while (notdone);
10411   }
10412   heap[eventnum] = moveevent;
10413   moveevent->heapposition = eventnum;
10414   eventheapify(heap, heapsize - 1, eventnum);
10415 }
10416 
10417 #endif /* not REDUCED */
10418 
10419 #ifndef REDUCED
10420 
10421 #ifdef ANSI_DECLARATORS
10422 void createeventheap(struct mesh *m, struct event ***eventheap,
10423                      struct event **events, struct event **freeevents)
10424 #else /* not ANSI_DECLARATORS */
10425 void createeventheap(m, eventheap, events, freeevents)
10426 struct mesh *m;
10427 struct event ***eventheap;
10428 struct event **events;
10429 struct event **freeevents;
10430 #endif /* not ANSI_DECLARATORS */
10431 
10432 {
10433   vertex thisvertex;
10434   int maxevents;
10435   int i;
10436 
10437   maxevents = (3 * m->invertices) / 2;
10438   *eventheap = (struct event **) trimalloc(maxevents *
10439                                            (int) sizeof(struct event *));
10440   *events = (struct event *) trimalloc(maxevents * (int) sizeof(struct event));
10441   traversalinit(&m->vertices);
10442   for (i = 0; i < m->invertices; i++) {
10443     thisvertex = vertextraverse(m);
10444     (*events)[i].eventptr = (void *) thisvertex;
10445     (*events)[i].xkey = thisvertex[0];
10446     (*events)[i].ykey = thisvertex[1];
10447     eventheapinsert(*eventheap, i, *events + i);
10448   }
10449   *freeevents = (struct event *) NULL;
10450   for (i = maxevents - 1; i >= m->invertices; i--) {
10451     (*events)[i].eventptr = (void *) *freeevents;
10452     *freeevents = *events + i;
10453   }
10454 }
10455 
10456 #endif /* not REDUCED */
10457 
10458 #ifndef REDUCED
10459 
10460 #ifdef ANSI_DECLARATORS
10461 int rightofhyperbola(struct mesh *m, struct otri *fronttri, vertex newsite)
10462 #else /* not ANSI_DECLARATORS */
10463 int rightofhyperbola(m, fronttri, newsite)
10464 struct mesh *m;
10465 struct otri *fronttri;
10466 vertex newsite;
10467 #endif /* not ANSI_DECLARATORS */
10468 
10469 {
10470   vertex leftvertex, rightvertex;
10471   REAL dxa, dya, dxb, dyb;
10472 
10473   m->hyperbolacount++;
10474 
10475   dest(*fronttri, leftvertex);
10476   apex(*fronttri, rightvertex);
10477   if ((leftvertex[1] < rightvertex[1]) ||
10478       ((leftvertex[1] == rightvertex[1]) &&
10479        (leftvertex[0] < rightvertex[0]))) {
10480     if (newsite[0] >= rightvertex[0]) {
10481       return 1;
10482     }
10483   } else {
10484     if (newsite[0] <= leftvertex[0]) {
10485       return 0;
10486     }
10487   }
10488   dxa = leftvertex[0] - newsite[0];
10489   dya = leftvertex[1] - newsite[1];
10490   dxb = rightvertex[0] - newsite[0];
10491   dyb = rightvertex[1] - newsite[1];
10492   return dya * (dxb * dxb + dyb * dyb) > dyb * (dxa * dxa + dya * dya);
10493 }
10494 
10495 #endif /* not REDUCED */
10496 
10497 #ifndef REDUCED
10498 
10499 #ifdef ANSI_DECLARATORS
10500 REAL circletop(struct mesh *m, vertex pa, vertex pb, vertex pc, REAL ccwabc)
10501 #else /* not ANSI_DECLARATORS */
10502 REAL circletop(m, pa, pb, pc, ccwabc)
10503 struct mesh *m;
10504 vertex pa;
10505 vertex pb;
10506 vertex pc;
10507 REAL ccwabc;
10508 #endif /* not ANSI_DECLARATORS */
10509 
10510 {
10511   REAL xac, yac, xbc, ybc, xab, yab;
10512   REAL aclen2, bclen2, ablen2;
10513 
10514   m->circletopcount++;
10515 
10516   xac = pa[0] - pc[0];
10517   yac = pa[1] - pc[1];
10518   xbc = pb[0] - pc[0];
10519   ybc = pb[1] - pc[1];
10520   xab = pa[0] - pb[0];
10521   yab = pa[1] - pb[1];
10522   aclen2 = xac * xac + yac * yac;
10523   bclen2 = xbc * xbc + ybc * ybc;
10524   ablen2 = xab * xab + yab * yab;
10525   return pc[1] + (xac * bclen2 - xbc * aclen2 + sqrt(aclen2 * bclen2 * ablen2))
10526                / (2.0 * ccwabc);
10527 }
10528 
10529 #endif /* not REDUCED */
10530 
10531 #ifndef REDUCED
10532 
10533 #ifdef ANSI_DECLARATORS
10534 void check4deadevent(struct otri *checktri, struct event **freeevents,
10535                      struct event **eventheap, int *heapsize)
10536 #else /* not ANSI_DECLARATORS */
10537 void check4deadevent(checktri, freeevents, eventheap, heapsize)
10538 struct otri *checktri;
10539 struct event **freeevents;
10540 struct event **eventheap;
10541 int *heapsize;
10542 #endif /* not ANSI_DECLARATORS */
10543 
10544 {
10545   struct event *deadevent;
10546   vertex eventvertex;
10547   int eventnum;
10548 
10549   org(*checktri, eventvertex);
10550   if (eventvertex != (vertex) NULL) {
10551     deadevent = (struct event *) eventvertex;
10552     eventnum = deadevent->heapposition;
10553     deadevent->eventptr = (void *) *freeevents;
10554     *freeevents = deadevent;
10555     eventheapdelete(eventheap, *heapsize, eventnum);
10556     (*heapsize)--;
10557     setorg(*checktri, NULL);
10558   }
10559 }
10560 
10561 #endif /* not REDUCED */
10562 
10563 #ifndef REDUCED
10564 
10565 #ifdef ANSI_DECLARATORS
10566 struct splaynode *splay(struct mesh *m, struct splaynode *splaytree,
10567                         vertex searchpoint, struct otri *searchtri)
10568 #else /* not ANSI_DECLARATORS */
10569 struct splaynode *splay(m, splaytree, searchpoint, searchtri)
10570 struct mesh *m;
10571 struct splaynode *splaytree;
10572 vertex searchpoint;
10573 struct otri *searchtri;
10574 #endif /* not ANSI_DECLARATORS */
10575 
10576 {
10577   struct splaynode *child, *grandchild;
10578   struct splaynode *lefttree, *righttree;
10579   struct splaynode *leftright;
10580   vertex checkvertex;
10581   int rightofroot, rightofchild;
10582 
10583   if (splaytree == (struct splaynode *) NULL) {
10584     return (struct splaynode *) NULL;
10585   }
10586   dest(splaytree->keyedge, checkvertex);
10587   if (checkvertex == splaytree->keydest) {
10588     rightofroot = rightofhyperbola(m, &splaytree->keyedge, searchpoint);
10589     if (rightofroot) {
10590       otricopy(splaytree->keyedge, *searchtri);
10591       child = splaytree->rchild;
10592     } else {
10593       child = splaytree->lchild;
10594     }
10595     if (child == (struct splaynode *) NULL) {
10596       return splaytree;
10597     }
10598     dest(child->keyedge, checkvertex);
10599     if (checkvertex != child->keydest) {
10600       child = splay(m, child, searchpoint, searchtri);
10601       if (child == (struct splaynode *) NULL) {
10602         if (rightofroot) {
10603           splaytree->rchild = (struct splaynode *) NULL;
10604         } else {
10605           splaytree->lchild = (struct splaynode *) NULL;
10606         }
10607         return splaytree;
10608       }
10609     }
10610     rightofchild = rightofhyperbola(m, &child->keyedge, searchpoint);
10611     if (rightofchild) {
10612       otricopy(child->keyedge, *searchtri);
10613       grandchild = splay(m, child->rchild, searchpoint, searchtri);
10614       child->rchild = grandchild;
10615     } else {
10616       grandchild = splay(m, child->lchild, searchpoint, searchtri);
10617       child->lchild = grandchild;
10618     }
10619     if (grandchild == (struct splaynode *) NULL) {
10620       if (rightofroot) {
10621         splaytree->rchild = child->lchild;
10622         child->lchild = splaytree;
10623       } else {
10624         splaytree->lchild = child->rchild;
10625         child->rchild = splaytree;
10626       }
10627       return child;
10628     }
10629     if (rightofchild) {
10630       if (rightofroot) {
10631         splaytree->rchild = child->lchild;
10632         child->lchild = splaytree;
10633       } else {
10634         splaytree->lchild = grandchild->rchild;
10635         grandchild->rchild = splaytree;
10636       }
10637       child->rchild = grandchild->lchild;
10638       grandchild->lchild = child;
10639     } else {
10640       if (rightofroot) {
10641         splaytree->rchild = grandchild->lchild;
10642         grandchild->lchild = splaytree;
10643       } else {
10644         splaytree->lchild = child->rchild;
10645         child->rchild = splaytree;
10646       }
10647       child->lchild = grandchild->rchild;
10648       grandchild->rchild = child;
10649     }
10650     return grandchild;
10651   } else {
10652     lefttree = splay(m, splaytree->lchild, searchpoint, searchtri);
10653     righttree = splay(m, splaytree->rchild, searchpoint, searchtri);
10654 
10655     pooldealloc(&m->splaynodes, (void *) splaytree);
10656     if (lefttree == (struct splaynode *) NULL) {
10657       return righttree;
10658     } else if (righttree == (struct splaynode *) NULL) {
10659       return lefttree;
10660     } else if (lefttree->rchild == (struct splaynode *) NULL) {
10661       lefttree->rchild = righttree->lchild;
10662       righttree->lchild = lefttree;
10663       return righttree;
10664     } else if (righttree->lchild == (struct splaynode *) NULL) {
10665       righttree->lchild = lefttree->rchild;
10666       lefttree->rchild = righttree;
10667       return lefttree;
10668     } else {
10669 /*      printf("Holy Toledo!!!\n"); */
10670       leftright = lefttree->rchild;
10671       while (leftright->rchild != (struct splaynode *) NULL) {
10672         leftright = leftright->rchild;
10673       }
10674       leftright->rchild = righttree;
10675       return lefttree;
10676     }
10677   }
10678 }
10679 
10680 #endif /* not REDUCED */
10681 
10682 #ifndef REDUCED
10683 
10684 #ifdef ANSI_DECLARATORS
10685 struct splaynode *splayinsert(struct mesh *m, struct splaynode *splayroot,
10686                               struct otri *newkey, vertex searchpoint)
10687 #else /* not ANSI_DECLARATORS */
10688 struct splaynode *splayinsert(m, splayroot, newkey, searchpoint)
10689 struct mesh *m;
10690 struct splaynode *splayroot;
10691 struct otri *newkey;
10692 vertex searchpoint;
10693 #endif /* not ANSI_DECLARATORS */
10694 
10695 {
10696   struct splaynode *newsplaynode;
10697 
10698   newsplaynode = (struct splaynode *) poolalloc(&m->splaynodes);
10699   otricopy(*newkey, newsplaynode->keyedge);
10700   dest(*newkey, newsplaynode->keydest);
10701   if (splayroot == (struct splaynode *) NULL) {
10702     newsplaynode->lchild = (struct splaynode *) NULL;
10703     newsplaynode->rchild = (struct splaynode *) NULL;
10704   } else if (rightofhyperbola(m, &splayroot->keyedge, searchpoint)) {
10705     newsplaynode->lchild = splayroot;
10706     newsplaynode->rchild = splayroot->rchild;
10707     splayroot->rchild = (struct splaynode *) NULL;
10708   } else {
10709     newsplaynode->lchild = splayroot->lchild;
10710     newsplaynode->rchild = splayroot;
10711     splayroot->lchild = (struct splaynode *) NULL;
10712   }
10713   return newsplaynode;
10714 }
10715 
10716 #endif /* not REDUCED */
10717 
10718 #ifndef REDUCED
10719 
10720 #ifdef ANSI_DECLARATORS
10721 struct splaynode *circletopinsert(struct mesh *m, struct behavior *b,
10722                                   struct splaynode *splayroot,
10723                                   struct otri *newkey,
10724                                   vertex pa, vertex pb, vertex pc, REAL topy)
10725 #else /* not ANSI_DECLARATORS */
10726 struct splaynode *circletopinsert(m, b, splayroot, newkey, pa, pb, pc, topy)
10727 struct mesh *m;
10728 struct behavior *b;
10729 struct splaynode *splayroot;
10730 struct otri *newkey;
10731 vertex pa;
10732 vertex pb;
10733 vertex pc;
10734 REAL topy;
10735 #endif /* not ANSI_DECLARATORS */
10736 
10737 {
10738   REAL ccwabc;
10739   REAL xac, yac, xbc, ybc;
10740   REAL aclen2, bclen2;
10741   REAL searchpoint[2];
10742   struct otri dummytri;
10743 
10744   ccwabc = counterclockwise(m, b, pa, pb, pc);
10745   xac = pa[0] - pc[0];
10746   yac = pa[1] - pc[1];
10747   xbc = pb[0] - pc[0];
10748   ybc = pb[1] - pc[1];
10749   aclen2 = xac * xac + yac * yac;
10750   bclen2 = xbc * xbc + ybc * ybc;
10751   searchpoint[0] = pc[0] - (yac * bclen2 - ybc * aclen2) / (2.0 * ccwabc);
10752   searchpoint[1] = topy;
10753   return splayinsert(m, splay(m, splayroot, (vertex) searchpoint, &dummytri),
10754                      newkey, (vertex) searchpoint);
10755 }
10756 
10757 #endif /* not REDUCED */
10758 
10759 #ifndef REDUCED
10760 
10761 #ifdef ANSI_DECLARATORS
10762 struct splaynode *frontlocate(struct mesh *m, struct splaynode *splayroot,
10763                               struct otri *bottommost, vertex searchvertex,
10764                               struct otri *searchtri, int *farright)
10765 #else /* not ANSI_DECLARATORS */
10766 struct splaynode *frontlocate(m, splayroot, bottommost, searchvertex,
10767                               searchtri, farright)
10768 struct mesh *m;
10769 struct splaynode *splayroot;
10770 struct otri *bottommost;
10771 vertex searchvertex;
10772 struct otri *searchtri;
10773 int *farright;
10774 #endif /* not ANSI_DECLARATORS */
10775 
10776 {
10777   int farrightflag;
10778   triangle ptr;                       /* Temporary variable used by onext(). */
10779 
10780   otricopy(*bottommost, *searchtri);
10781   splayroot = splay(m, splayroot, searchvertex, searchtri);
10782 
10783   farrightflag = 0;
10784   while (!farrightflag && rightofhyperbola(m, searchtri, searchvertex)) {
10785     onextself(*searchtri);
10786     farrightflag = otriequal(*searchtri, *bottommost);
10787   }
10788   *farright = farrightflag;
10789   return splayroot;
10790 }
10791 
10792 #endif /* not REDUCED */
10793 
10794 #ifndef REDUCED
10795 
10796 #ifdef ANSI_DECLARATORS
10797 long sweeplinedelaunay(struct mesh *m, struct behavior *b)
10798 #else /* not ANSI_DECLARATORS */
10799 long sweeplinedelaunay(m, b)
10800 struct mesh *m;
10801 struct behavior *b;
10802 #endif /* not ANSI_DECLARATORS */
10803 
10804 {
10805   struct event **eventheap;
10806   struct event *events;
10807   struct event *freeevents;
10808   struct event *nextevent;
10809   struct event *newevent;
10810   struct splaynode *splayroot;
10811   struct otri bottommost;
10812   struct otri searchtri;
10813   struct otri fliptri;
10814   struct otri lefttri, righttri, farlefttri, farrighttri;
10815   struct otri inserttri;
10816   vertex firstvertex, secondvertex;
10817   vertex nextvertex, lastvertex;
10818   vertex connectvertex;
10819   vertex leftvertex, midvertex, rightvertex;
10820   REAL lefttest, righttest;
10821   int heapsize;
10822   int check4events, farrightflag;
10823   triangle ptr;   /* Temporary variable used by sym(), onext(), and oprev(). */
10824 
10825   poolinit(&m->splaynodes, sizeof(struct splaynode), SPLAYNODEPERBLOCK,
10826            SPLAYNODEPERBLOCK, 0);
10827   splayroot = (struct splaynode *) NULL;
10828 
10829   if (b->verbose) {
10830     printf("  Placing vertices in event heap.\n");
10831   }
10832   createeventheap(m, &eventheap, &events, &freeevents);
10833   heapsize = m->invertices;
10834 
10835   if (b->verbose) {
10836     printf("  Forming triangulation.\n");
10837   }
10838   maketriangle(m, b, &lefttri);
10839   maketriangle(m, b, &righttri);
10840   bond(lefttri, righttri);
10841   lnextself(lefttri);
10842   lprevself(righttri);
10843   bond(lefttri, righttri);
10844   lnextself(lefttri);
10845   lprevself(righttri);
10846   bond(lefttri, righttri);
10847   firstvertex = (vertex) eventheap[0]->eventptr;
10848   eventheap[0]->eventptr = (void *) freeevents;
10849   freeevents = eventheap[0];
10850   eventheapdelete(eventheap, heapsize, 0);
10851   heapsize--;
10852   do {
10853     if (heapsize == 0) {
10854       printf("Error:  Input vertices are all identical.\n");
10855       triexit(1);
10856     }
10857     secondvertex = (vertex) eventheap[0]->eventptr;
10858     eventheap[0]->eventptr = (void *) freeevents;
10859     freeevents = eventheap[0];
10860     eventheapdelete(eventheap, heapsize, 0);
10861     heapsize--;
10862     if ((firstvertex[0] == secondvertex[0]) &&
10863         (firstvertex[1] == secondvertex[1])) {
10864       if (!b->quiet) {
10865         printf(
10866 "Warning:  A duplicate vertex at (%.12g, %.12g) appeared and was ignored.\n",
10867                secondvertex[0], secondvertex[1]);
10868       }
10869       setvertextype(secondvertex, UNDEADVERTEX);
10870       m->undeads++;
10871     }
10872   } while ((firstvertex[0] == secondvertex[0]) &&
10873            (firstvertex[1] == secondvertex[1]));
10874   setorg(lefttri, firstvertex);
10875   setdest(lefttri, secondvertex);
10876   setorg(righttri, secondvertex);
10877   setdest(righttri, firstvertex);
10878   lprev(lefttri, bottommost);
10879   lastvertex = secondvertex;
10880   while (heapsize > 0) {
10881     nextevent = eventheap[0];
10882     eventheapdelete(eventheap, heapsize, 0);
10883     heapsize--;
10884     check4events = 1;
10885     if (nextevent->xkey < m->xmin) {
10886       decode(nextevent->eventptr, fliptri);
10887       oprev(fliptri, farlefttri);
10888       check4deadevent(&farlefttri, &freeevents, eventheap, &heapsize);
10889       onext(fliptri, farrighttri);
10890       check4deadevent(&farrighttri, &freeevents, eventheap, &heapsize);
10891 
10892       if (otriequal(farlefttri, bottommost)) {
10893         lprev(fliptri, bottommost);
10894       }
10895       flip(m, b, &fliptri);
10896       setapex(fliptri, NULL);
10897       lprev(fliptri, lefttri);
10898       lnext(fliptri, righttri);
10899       sym(lefttri, farlefttri);
10900 
10901       if (randomnation(SAMPLERATE) == 0) {
10902         symself(fliptri);
10903         dest(fliptri, leftvertex);
10904         apex(fliptri, midvertex);
10905         org(fliptri, rightvertex);
10906         splayroot = circletopinsert(m, b, splayroot, &lefttri, leftvertex,
10907                                     midvertex, rightvertex, nextevent->ykey);
10908       }
10909     } else {
10910       nextvertex = (vertex) nextevent->eventptr;
10911       if ((nextvertex[0] == lastvertex[0]) &&
10912           (nextvertex[1] == lastvertex[1])) {
10913         if (!b->quiet) {
10914           printf(
10915 "Warning:  A duplicate vertex at (%.12g, %.12g) appeared and was ignored.\n",
10916                  nextvertex[0], nextvertex[1]);
10917         }
10918         setvertextype(nextvertex, UNDEADVERTEX);
10919         m->undeads++;
10920         check4events = 0;
10921       } else {
10922         lastvertex = nextvertex;
10923 
10924         splayroot = frontlocate(m, splayroot, &bottommost, nextvertex,
10925                                 &searchtri, &farrightflag);
10926 /*
10927         otricopy(bottommost, searchtri);
10928         farrightflag = 0;
10929         while (!farrightflag && rightofhyperbola(m, &searchtri, nextvertex)) {
10930           onextself(searchtri);
10931           farrightflag = otriequal(searchtri, bottommost);
10932         }
10933 */
10934 
10935         check4deadevent(&searchtri, &freeevents, eventheap, &heapsize);
10936 
10937         otricopy(searchtri, farrighttri);
10938         sym(searchtri, farlefttri);
10939         maketriangle(m, b, &lefttri);
10940         maketriangle(m, b, &righttri);
10941         dest(farrighttri, connectvertex);
10942         setorg(lefttri, connectvertex);
10943         setdest(lefttri, nextvertex);
10944         setorg(righttri, nextvertex);
10945         setdest(righttri, connectvertex);
10946         bond(lefttri, righttri);
10947         lnextself(lefttri);
10948         lprevself(righttri);
10949         bond(lefttri, righttri);
10950         lnextself(lefttri);
10951         lprevself(righttri);
10952         bond(lefttri, farlefttri);
10953         bond(righttri, farrighttri);
10954         if (!farrightflag && otriequal(farrighttri, bottommost)) {
10955           otricopy(lefttri, bottommost);
10956         }
10957 
10958         if (randomnation(SAMPLERATE) == 0) {
10959           splayroot = splayinsert(m, splayroot, &lefttri, nextvertex);
10960         } else if (randomnation(SAMPLERATE) == 0) {
10961           lnext(righttri, inserttri);
10962           splayroot = splayinsert(m, splayroot, &inserttri, nextvertex);
10963         }
10964       }
10965     }
10966     nextevent->eventptr = (void *) freeevents;
10967     freeevents = nextevent;
10968 
10969     if (check4events) {
10970       apex(farlefttri, leftvertex);
10971       dest(lefttri, midvertex);
10972       apex(lefttri, rightvertex);
10973       lefttest = counterclockwise(m, b, leftvertex, midvertex, rightvertex);
10974       if (lefttest > 0.0) {
10975         newevent = freeevents;
10976         freeevents = (struct event *) freeevents->eventptr;
10977         newevent->xkey = m->xminextreme;
10978         newevent->ykey = circletop(m, leftvertex, midvertex, rightvertex,
10979                                    lefttest);
10980         newevent->eventptr = (void *) encode(lefttri);
10981         eventheapinsert(eventheap, heapsize, newevent);
10982         heapsize++;
10983         setorg(lefttri, newevent);
10984       }
10985       apex(righttri, leftvertex);
10986       org(righttri, midvertex);
10987       apex(farrighttri, rightvertex);
10988       righttest = counterclockwise(m, b, leftvertex, midvertex, rightvertex);
10989       if (righttest > 0.0) {
10990         newevent = freeevents;
10991         freeevents = (struct event *) freeevents->eventptr;
10992         newevent->xkey = m->xminextreme;
10993         newevent->ykey = circletop(m, leftvertex, midvertex, rightvertex,
10994                                    righttest);
10995         newevent->eventptr = (void *) encode(farrighttri);
10996         eventheapinsert(eventheap, heapsize, newevent);
10997         heapsize++;
10998         setorg(farrighttri, newevent);
10999       }
11000     }
11001   }
11002 
11003   pooldeinit(&m->splaynodes);
11004   lprevself(bottommost);
11005   return removeghosts(m, b, &bottommost);
11006 }
11007 
11008 #endif /* not REDUCED */
11009 
11010 /**                                                                         **/
11011 /**                                                                         **/
11012 /********* Sweepline Delaunay triangulation ends here                *********/
11013 
11014 /********* General mesh construction routines begin here             *********/
11015 /**                                                                         **/
11016 /**                                                                         **/
11017 
11018 /*****************************************************************************/
11019 /*                                                                           */
11020 /*  delaunay()   Form a Delaunay triangulation.                              */
11021 /*                                                                           */
11022 /*****************************************************************************/
11023 
11024 #ifdef ANSI_DECLARATORS
11025 long delaunay(struct mesh *m, struct behavior *b)
11026 #else /* not ANSI_DECLARATORS */
11027 long delaunay(m, b)
11028 struct mesh *m;
11029 struct behavior *b;
11030 #endif /* not ANSI_DECLARATORS */
11031 
11032 {
11033   long hulledges;
11034 
11035   m->eextras = 0;
11036   initializetrisubpools(m, b);
11037 
11038 #ifdef REDUCED
11039   if (!b->quiet) {
11040     printf(
11041       "Constructing Delaunay triangulation by divide-and-conquer method.\n");
11042   }
11043   hulledges = divconqdelaunay(m, b);
11044 #else /* not REDUCED */
11045   if (!b->quiet) {
11046     printf("Constructing Delaunay triangulation ");
11047     if (b->incremental) {
11048       printf("by incremental method.\n");
11049     } else if (b->sweepline) {
11050       printf("by sweepline method.\n");
11051     } else {
11052       printf("by divide-and-conquer method.\n");
11053     }
11054   }
11055   if (b->incremental) {
11056     hulledges = incrementaldelaunay(m, b);
11057   } else if (b->sweepline) {
11058     hulledges = sweeplinedelaunay(m, b);
11059   } else {
11060     hulledges = divconqdelaunay(m, b);
11061   }
11062 #endif /* not REDUCED */
11063 
11064   if (m->triangles.items == 0) {
11065     /* The input vertices were all collinear, so there are no triangles. */
11066     return 0l;
11067   } else {
11068     return hulledges;
11069   }
11070 }
11071 
11072 /*****************************************************************************/
11073 /*                                                                           */
11074 /*  reconstruct()   Reconstruct a triangulation from its .ele (and possibly  */
11075 /*                  .poly) file.  Used when the -r switch is used.           */
11076 /*                                                                           */
11077 /*  Reads an .ele file and reconstructs the original mesh.  If the -p switch */
11078 /*  is used, this procedure will also read a .poly file and reconstruct the  */
11079 /*  subsegments of the original mesh.  If the -a switch is used, this        */
11080 /*  procedure will also read an .area file and set a maximum area constraint */
11081 /*  on each triangle.                                                        */
11082 /*                                                                           */
11083 /*  Vertices that are not corners of triangles, such as nodes on edges of    */
11084 /*  subparametric elements, are discarded.                                   */
11085 /*                                                                           */
11086 /*  This routine finds the adjacencies between triangles (and subsegments)   */
11087 /*  by forming one stack of triangles for each vertex.  Each triangle is on  */
11088 /*  three different stacks simultaneously.  Each triangle's subsegment       */
11089 /*  pointers are used to link the items in each stack.  This memory-saving   */
11090 /*  feature makes the code harder to read.  The most important thing to keep */
11091 /*  in mind is that each triangle is removed from a stack precisely when     */
11092 /*  the corresponding pointer is adjusted to refer to a subsegment rather    */
11093 /*  than the next triangle of the stack.                                     */
11094 /*                                                                           */
11095 /*****************************************************************************/
11096 
11097 #ifndef CDT_ONLY
11098 
11099 #ifdef TRILIBRARY
11100 
11101 #ifdef ANSI_DECLARATORS
11102 int reconstruct(struct mesh *m, struct behavior *b, int *trianglelist,
11103                 REAL *triangleattriblist, REAL *trianglearealist,
11104                 int elements, int corners, int attribs,
11105                 int *segmentlist,int *segmentmarkerlist, int numberofsegments)
11106 #else /* not ANSI_DECLARATORS */
11107 int reconstruct(m, b, trianglelist, triangleattriblist, trianglearealist,
11108                 elements, corners, attribs, segmentlist, segmentmarkerlist,
11109                 numberofsegments)
11110 struct mesh *m;
11111 struct behavior *b;
11112 int *trianglelist;
11113 REAL *triangleattriblist;
11114 REAL *trianglearealist;
11115 int elements;
11116 int corners;
11117 int attribs;
11118 int *segmentlist;
11119 int *segmentmarkerlist;
11120 int numberofsegments;
11121 #endif /* not ANSI_DECLARATORS */
11122 
11123 #else /* not TRILIBRARY */
11124 
11125 #ifdef ANSI_DECLARATORS
11126 long reconstruct(struct mesh *m, struct behavior *b, char *elefilename,
11127                  char *areafilename, char *polyfilename, FILE *polyfile)
11128 #else /* not ANSI_DECLARATORS */
11129 long reconstruct(m, b, elefilename, areafilename, polyfilename, polyfile)
11130 struct mesh *m;
11131 struct behavior *b;
11132 char *elefilename;
11133 char *areafilename;
11134 char *polyfilename;
11135 FILE *polyfile;
11136 #endif /* not ANSI_DECLARATORS */
11137 
11138 #endif /* not TRILIBRARY */
11139 
11140 {
11141 #ifdef TRILIBRARY
11142   int vertexindex;
11143   int attribindex;
11144 #else /* not TRILIBRARY */
11145   FILE *elefile;
11146   FILE *areafile;
11147   char inputline[INPUTLINESIZE];
11148   char *stringptr;
11149   int areaelements;
11150 #endif /* not TRILIBRARY */
11151   struct otri triangleloop;
11152   struct otri triangleleft;
11153   struct otri checktri;
11154   struct otri checkleft;
11155   struct otri checkneighbor;
11156   struct osub subsegloop;
11157   triangle *vertexarray;
11158   triangle *prevlink;
11159   triangle nexttri;
11160   vertex tdest, tapex;
11161   vertex checkdest, checkapex;
11162   vertex shorg;
11163   vertex killvertex;
11164   vertex segmentorg, segmentdest;
11165   REAL area;
11166   int corner[3];
11167   int end[2];
11168   int killvertexindex;
11169   int incorners;
11170   int segmentmarkers;
11171   int boundmarker;
11172   int aroundvertex;
11173   long hullsize;
11174   int notfound;
11175   long elementnumber, segmentnumber;
11176   int i, j;
11177   triangle ptr;                         /* Temporary variable used by sym(). */
11178 
11179 #ifdef TRILIBRARY
11180   m->inelements = elements;
11181   incorners = corners;
11182   if (incorners < 3) {
11183     printf("Error:  Triangles must have at least 3 vertices.\n");
11184     triexit(1);
11185   }
11186   m->eextras = attribs;
11187 #else /* not TRILIBRARY */
11188   /* Read the triangles from an .ele file. */
11189   if (!b->quiet) {
11190     printf("Opening %s.\n", elefilename);
11191   }
11192   elefile = fopen(elefilename, "r");
11193   if (elefile == (FILE *) NULL) {
11194     printf("  Error:  Cannot access file %s.\n", elefilename);
11195     triexit(1);
11196   }
11197   /* Read number of triangles, number of vertices per triangle, and */
11198   /*   number of triangle attributes from .ele file.                */
11199   stringptr = readline(inputline, elefile, elefilename);
11200   m->inelements = (int) strtol(stringptr, &stringptr, 0);
11201   stringptr = findfield(stringptr);
11202   if (*stringptr == '\0') {
11203     incorners = 3;
11204   } else {
11205     incorners = (int) strtol(stringptr, &stringptr, 0);
11206     if (incorners < 3) {
11207       printf("Error:  Triangles in %s must have at least 3 vertices.\n",
11208              elefilename);
11209       triexit(1);
11210     }
11211   }
11212   stringptr = findfield(stringptr);
11213   if (*stringptr == '\0') {
11214     m->eextras = 0;
11215   } else {
11216     m->eextras = (int) strtol(stringptr, &stringptr, 0);
11217   }
11218 #endif /* not TRILIBRARY */
11219 
11220   initializetrisubpools(m, b);
11221 
11222   /* Create the triangles. */
11223   for (elementnumber = 1; elementnumber <= m->inelements; elementnumber++) {
11224     maketriangle(m, b, &triangleloop);
11225     /* Mark the triangle as living. */
11226     triangleloop.tri[3] = (triangle) triangleloop.tri;
11227   }
11228 
11229   segmentmarkers = 0;
11230   if (b->poly) {
11231 #ifdef TRILIBRARY
11232     m->insegments = numberofsegments;
11233     segmentmarkers = segmentmarkerlist != (int *) NULL;
11234 #else /* not TRILIBRARY */
11235     /* Read number of segments and number of segment */
11236     /*   boundary markers from .poly file.           */
11237     stringptr = readline(inputline, polyfile, b->inpolyfilename);
11238     m->insegments = (int) strtol(stringptr, &stringptr, 0);
11239     stringptr = findfield(stringptr);
11240     if (*stringptr != '\0') {
11241       segmentmarkers = (int) strtol(stringptr, &stringptr, 0);
11242     }
11243 #endif /* not TRILIBRARY */
11244 
11245     /* Create the subsegments. */
11246     for (segmentnumber = 1; segmentnumber <= m->insegments; segmentnumber++) {
11247       makesubseg(m, &subsegloop);
11248       /* Mark the subsegment as living. */
11249       subsegloop.ss[2] = (subseg) subsegloop.ss;
11250     }
11251   }
11252 
11253 #ifdef TRILIBRARY
11254   vertexindex = 0;
11255   attribindex = 0;
11256 #else /* not TRILIBRARY */
11257   if (b->vararea) {
11258     /* Open an .area file, check for consistency with the .ele file. */
11259     if (!b->quiet) {
11260       printf("Opening %s.\n", areafilename);
11261     }
11262     areafile = fopen(areafilename, "r");
11263     if (areafile == (FILE *) NULL) {
11264       printf("  Error:  Cannot access file %s.\n", areafilename);
11265       triexit(1);
11266     }
11267     stringptr = readline(inputline, areafile, areafilename);
11268     areaelements = (int) strtol(stringptr, &stringptr, 0);
11269     if (areaelements != m->inelements) {
11270       printf("Error:  %s and %s disagree on number of triangles.\n",
11271              elefilename, areafilename);
11272       triexit(1);
11273     }
11274   }
11275 #endif /* not TRILIBRARY */
11276 
11277   if (!b->quiet) {
11278     printf("Reconstructing mesh.\n");
11279   }
11280   /* Allocate a temporary array that maps each vertex to some adjacent */
11281   /*   triangle.  I took care to allocate all the permanent memory for */
11282   /*   triangles and subsegments first.                                */
11283   vertexarray = (triangle *) trimalloc(m->vertices.items *
11284                                        (int) sizeof(triangle));
11285   /* Each vertex is initially unrepresented. */
11286   for (i = 0; i < m->vertices.items; i++) {
11287     vertexarray[i] = (triangle) m->dummytri;
11288   }
11289 
11290   if (b->verbose) {
11291     printf("  Assembling triangles.\n");
11292   }
11293   /* Read the triangles from the .ele file, and link */
11294   /*   together those that share an edge.            */
11295   traversalinit(&m->triangles);
11296   triangleloop.tri = triangletraverse(m);
11297   elementnumber = b->firstnumber;
11298   while (triangleloop.tri != (triangle *) NULL) {
11299 #ifdef TRILIBRARY
11300     /* Copy the triangle's three corners. */
11301     for (j = 0; j < 3; j++) {
11302       corner[j] = trianglelist[vertexindex++];
11303       if ((corner[j] < b->firstnumber) ||
11304           (corner[j] >= b->firstnumber + m->invertices)) {
11305         printf("Error:  Triangle %ld has an invalid vertex index.\n",
11306                elementnumber);
11307         triexit(1);
11308       }
11309     }
11310 #else /* not TRILIBRARY */
11311     /* Read triangle number and the triangle's three corners. */
11312     stringptr = readline(inputline, elefile, elefilename);
11313     for (j = 0; j < 3; j++) {
11314       stringptr = findfield(stringptr);
11315       if (*stringptr == '\0') {
11316         printf("Error:  Triangle %ld is missing vertex %d in %s.\n",
11317                elementnumber, j + 1, elefilename);
11318         triexit(1);
11319       } else {
11320         corner[j] = (int) strtol(stringptr, &stringptr, 0);
11321         if ((corner[j] < b->firstnumber) ||
11322             (corner[j] >= b->firstnumber + m->invertices)) {
11323           printf("Error:  Triangle %ld has an invalid vertex index.\n",
11324                  elementnumber);
11325           triexit(1);
11326         }
11327       }
11328     }
11329 #endif /* not TRILIBRARY */
11330 
11331     /* Find out about (and throw away) extra nodes. */
11332     for (j = 3; j < incorners; j++) {
11333 #ifdef TRILIBRARY
11334       killvertexindex = trianglelist[vertexindex++];
11335 #else /* not TRILIBRARY */
11336       stringptr = findfield(stringptr);
11337       if (*stringptr != '\0') {
11338         killvertexindex = (int) strtol(stringptr, &stringptr, 0);
11339 #endif /* not TRILIBRARY */
11340         if ((killvertexindex >= b->firstnumber) &&
11341             (killvertexindex < b->firstnumber + m->invertices)) {
11342           /* Delete the non-corner vertex if it's not already deleted. */
11343           killvertex = getvertex(m, b, killvertexindex);
11344           if (vertextype(killvertex) != DEADVERTEX) {
11345             vertexdealloc(m, killvertex);
11346           }
11347         }
11348 #ifndef TRILIBRARY
11349       }
11350 #endif /* not TRILIBRARY */
11351     }
11352 
11353     /* Read the triangle's attributes. */
11354     for (j = 0; j < m->eextras; j++) {
11355 #ifdef TRILIBRARY
11356       setelemattribute(triangleloop, j, triangleattriblist[attribindex++]);
11357 #else /* not TRILIBRARY */
11358       stringptr = findfield(stringptr);
11359       if (*stringptr == '\0') {
11360         setelemattribute(triangleloop, j, 0);
11361       } else {
11362         setelemattribute(triangleloop, j,
11363                          (REAL) strtod(stringptr, &stringptr));
11364       }
11365 #endif /* not TRILIBRARY */
11366     }
11367 
11368     if (b->vararea) {
11369 #ifdef TRILIBRARY
11370       area = trianglearealist[elementnumber - b->firstnumber];
11371 #else /* not TRILIBRARY */
11372       /* Read an area constraint from the .area file. */
11373       stringptr = readline(inputline, areafile, areafilename);
11374       stringptr = findfield(stringptr);
11375       if (*stringptr == '\0') {
11376         area = -1.0;                      /* No constraint on this triangle. */
11377       } else {
11378         area = (REAL) strtod(stringptr, &stringptr);
11379       }
11380 #endif /* not TRILIBRARY */
11381       setareabound(triangleloop, area);
11382     }
11383 
11384     /* Set the triangle's vertices. */
11385     triangleloop.orient = 0;
11386     setorg(triangleloop, getvertex(m, b, corner[0]));
11387     setdest(triangleloop, getvertex(m, b, corner[1]));
11388     setapex(triangleloop, getvertex(m, b, corner[2]));
11389     /* Try linking the triangle to others that share these vertices. */
11390     for (triangleloop.orient = 0; triangleloop.orient < 3;
11391          triangleloop.orient++) {
11392       /* Take the number for the origin of triangleloop. */
11393       aroundvertex = corner[triangleloop.orient];
11394       /* Look for other triangles having this vertex. */
11395       nexttri = vertexarray[aroundvertex - b->firstnumber];
11396       /* Link the current triangle to the next one in the stack. */
11397       triangleloop.tri[6 + triangleloop.orient] = nexttri;
11398       /* Push the current triangle onto the stack. */
11399       vertexarray[aroundvertex - b->firstnumber] = encode(triangleloop);
11400       decode(nexttri, checktri);
11401       if (checktri.tri != m->dummytri) {
11402         dest(triangleloop, tdest);
11403         apex(triangleloop, tapex);
11404         /* Look for other triangles that share an edge. */
11405         do {
11406           dest(checktri, checkdest);
11407           apex(checktri, checkapex);
11408           if (tapex == checkdest) {
11409             /* The two triangles share an edge; bond them together. */
11410             lprev(triangleloop, triangleleft);
11411             bond(triangleleft, checktri);
11412           }
11413           if (tdest == checkapex) {
11414             /* The two triangles share an edge; bond them together. */
11415             lprev(checktri, checkleft);
11416             bond(triangleloop, checkleft);
11417           }
11418           /* Find the next triangle in the stack. */
11419           nexttri = checktri.tri[6 + checktri.orient];
11420           decode(nexttri, checktri);
11421         } while (checktri.tri != m->dummytri);
11422       }
11423     }
11424     triangleloop.tri = triangletraverse(m);
11425     elementnumber++;
11426   }
11427 
11428 #ifdef TRILIBRARY
11429   vertexindex = 0;
11430 #else /* not TRILIBRARY */
11431   fclose(elefile);
11432   if (b->vararea) {
11433     fclose(areafile);
11434   }
11435 #endif /* not TRILIBRARY */
11436 
11437   hullsize = 0;                      /* Prepare to count the boundary edges. */
11438   if (b->poly) {
11439     if (b->verbose) {
11440       printf("  Marking segments in triangulation.\n");
11441     }
11442     /* Read the segments from the .poly file, and link them */
11443     /*   to their neighboring triangles.                    */
11444     boundmarker = 0;
11445     traversalinit(&m->subsegs);
11446     subsegloop.ss = subsegtraverse(m);
11447     segmentnumber = b->firstnumber;
11448     while (subsegloop.ss != (subseg *) NULL) {
11449 #ifdef TRILIBRARY
11450       end[0] = segmentlist[vertexindex++];
11451       end[1] = segmentlist[vertexindex++];
11452       if (segmentmarkers) {
11453         boundmarker = segmentmarkerlist[segmentnumber - b->firstnumber];
11454       }
11455 #else /* not TRILIBRARY */
11456       /* Read the endpoints of each segment, and possibly a boundary marker. */
11457       stringptr = readline(inputline, polyfile, b->inpolyfilename);
11458       /* Skip the first (segment number) field. */
11459       stringptr = findfield(stringptr);
11460       if (*stringptr == '\0') {
11461         printf("Error:  Segment %ld has no endpoints in %s.\n", segmentnumber,
11462                polyfilename);
11463         triexit(1);
11464       } else {
11465         end[0] = (int) strtol(stringptr, &stringptr, 0);
11466       }
11467       stringptr = findfield(stringptr);
11468       if (*stringptr == '\0') {
11469         printf("Error:  Segment %ld is missing its second endpoint in %s.\n",
11470                segmentnumber, polyfilename);
11471         triexit(1);
11472       } else {
11473         end[1] = (int) strtol(stringptr, &stringptr, 0);
11474       }
11475       if (segmentmarkers) {
11476         stringptr = findfield(stringptr);
11477         if (*stringptr == '\0') {
11478           boundmarker = 0;
11479         } else {
11480           boundmarker = (int) strtol(stringptr, &stringptr, 0);
11481         }
11482       }
11483 #endif /* not TRILIBRARY */
11484       for (j = 0; j < 2; j++) {
11485         if ((end[j] < b->firstnumber) ||
11486             (end[j] >= b->firstnumber + m->invertices)) {
11487           printf("Error:  Segment %ld has an invalid vertex index.\n",
11488                  segmentnumber);
11489           triexit(1);
11490         }
11491       }
11492 
11493       /* set the subsegment's vertices. */
11494       subsegloop.ssorient = 0;
11495       segmentorg = getvertex(m, b, end[0]);
11496       segmentdest = getvertex(m, b, end[1]);
11497       setsorg(subsegloop, segmentorg);
11498       setsdest(subsegloop, segmentdest);
11499       setsegorg(subsegloop, segmentorg);
11500       setsegdest(subsegloop, segmentdest);
11501       setmark(subsegloop, boundmarker);
11502       /* Try linking the subsegment to triangles that share these vertices. */
11503       for (subsegloop.ssorient = 0; subsegloop.ssorient < 2;
11504            subsegloop.ssorient++) {
11505         /* Take the number for the destination of subsegloop. */
11506         aroundvertex = end[1 - subsegloop.ssorient];
11507         /* Look for triangles having this vertex. */
11508         prevlink = &vertexarray[aroundvertex - b->firstnumber];
11509         nexttri = vertexarray[aroundvertex - b->firstnumber];
11510         decode(nexttri, checktri);
11511         sorg(subsegloop, shorg);
11512         notfound = 1;
11513         /* Look for triangles having this edge.  Note that I'm only       */
11514         /*   comparing each triangle's destination with the subsegment;   */
11515         /*   each triangle's apex is handled through a different vertex.  */
11516         /*   Because each triangle appears on three vertices' lists, each */
11517         /*   occurrence of a triangle on a list can (and does) represent  */
11518         /*   an edge.  In this way, most edges are represented twice, and */
11519         /*   every triangle-subsegment bond is represented once.          */
11520         while (notfound && (checktri.tri != m->dummytri)) {
11521           dest(checktri, checkdest);
11522           if (shorg == checkdest) {
11523             /* We have a match.  Remove this triangle from the list. */
11524             *prevlink = checktri.tri[6 + checktri.orient];
11525             /* Bond the subsegment to the triangle. */
11526             tsbond(checktri, subsegloop);
11527             /* Check if this is a boundary edge. */
11528             sym(checktri, checkneighbor);
11529             if (checkneighbor.tri == m->dummytri) {
11530               /* The next line doesn't insert a subsegment (because there's */
11531               /*   already one there), but it sets the boundary markers of  */
11532               /*   the existing subsegment and its vertices.                */
11533               insertsubseg(m, b, &checktri, 1);
11534               hullsize++;
11535             }
11536             notfound = 0;
11537           }
11538           /* Find the next triangle in the stack. */
11539           prevlink = &checktri.tri[6 + checktri.orient];
11540           nexttri = checktri.tri[6 + checktri.orient];
11541           decode(nexttri, checktri);
11542         }
11543       }
11544       subsegloop.ss = subsegtraverse(m);
11545       segmentnumber++;
11546     }
11547   }
11548 
11549   /* Mark the remaining edges as not being attached to any subsegment. */
11550   /* Also, count the (yet uncounted) boundary edges.                   */
11551   for (i = 0; i < m->vertices.items; i++) {
11552     /* Search the stack of triangles adjacent to a vertex. */
11553     nexttri = vertexarray[i];
11554     decode(nexttri, checktri);
11555     while (checktri.tri != m->dummytri) {
11556       /* Find the next triangle in the stack before this */
11557       /*   information gets overwritten.                 */
11558       nexttri = checktri.tri[6 + checktri.orient];
11559       /* No adjacent subsegment.  (This overwrites the stack info.) */
11560       tsdissolve(checktri);
11561       sym(checktri, checkneighbor);
11562       if (checkneighbor.tri == m->dummytri) {
11563         insertsubseg(m, b, &checktri, 1);
11564         hullsize++;
11565       }
11566       decode(nexttri, checktri);
11567     }
11568   }
11569 
11570   trifree((void *) vertexarray);
11571   return hullsize;
11572 }
11573 
11574 #endif /* not CDT_ONLY */
11575 
11576 /**                                                                         **/
11577 /**                                                                         **/
11578 /********* General mesh construction routines end here               *********/
11579 
11580 /********* Segment insertion begins here                             *********/
11581 /**                                                                         **/
11582 /**                                                                         **/
11583 
11584 /*****************************************************************************/
11585 /*                                                                           */
11586 /*  finddirection()   Find the first triangle on the path from one point     */
11587 /*                    to another.                                            */
11588 /*                                                                           */
11589 /*  Finds the triangle that intersects a line segment drawn from the         */
11590 /*  origin of `searchtri' to the point `searchpoint', and returns the result */
11591 /*  in `searchtri'.  The origin of `searchtri' does not change, even though  */
11592 /*  the triangle returned may differ from the one passed in.  This routine   */
11593 /*  is used to find the direction to move in to get from one point to        */
11594 /*  another.                                                                 */
11595 /*                                                                           */
11596 /*  The return value notes whether the destination or apex of the found      */
11597 /*  triangle is collinear with the two points in question.                   */
11598 /*                                                                           */
11599 /*****************************************************************************/
11600 
11601 #ifdef ANSI_DECLARATORS
11602 enum finddirectionresult finddirection(struct mesh *m, struct behavior *b,
11603                                        struct otri *searchtri,
11604                                        vertex searchpoint)
11605 #else /* not ANSI_DECLARATORS */
11606 enum finddirectionresult finddirection(m, b, searchtri, searchpoint)
11607 struct mesh *m;
11608 struct behavior *b;
11609 struct otri *searchtri;
11610 vertex searchpoint;
11611 #endif /* not ANSI_DECLARATORS */
11612 
11613 {
11614   struct otri checktri;
11615   vertex startvertex;
11616   vertex leftvertex, rightvertex;
11617   REAL leftccw, rightccw;
11618   int leftflag, rightflag;
11619   triangle ptr;           /* Temporary variable used by onext() and oprev(). */
11620 
11621   org(*searchtri, startvertex);
11622   dest(*searchtri, rightvertex);
11623   apex(*searchtri, leftvertex);
11624   /* Is `searchpoint' to the left? */
11625   leftccw = counterclockwise(m, b, searchpoint, startvertex, leftvertex);
11626   leftflag = leftccw > 0.0;
11627   /* Is `searchpoint' to the right? */
11628   rightccw = counterclockwise(m, b, startvertex, searchpoint, rightvertex);
11629   rightflag = rightccw > 0.0;
11630   if (leftflag && rightflag) {
11631     /* `searchtri' faces directly away from `searchpoint'.  We could go left */
11632     /*   or right.  Ask whether it's a triangle or a boundary on the left.   */
11633     onext(*searchtri, checktri);
11634     if (checktri.tri == m->dummytri) {
11635       leftflag = 0;
11636     } else {
11637       rightflag = 0;
11638     }
11639   }
11640   while (leftflag) {
11641     /* Turn left until satisfied. */
11642     onextself(*searchtri);
11643     if (searchtri->tri == m->dummytri) {
11644       printf("Internal error in finddirection():  Unable to find a\n");
11645       printf("  triangle leading from (%.12g, %.12g) to", startvertex[0],
11646              startvertex[1]);
11647       printf("  (%.12g, %.12g).\n", searchpoint[0], searchpoint[1]);
11648       internalerror();
11649     }
11650     apex(*searchtri, leftvertex);
11651     rightccw = leftccw;
11652     leftccw = counterclockwise(m, b, searchpoint, startvertex, leftvertex);
11653     leftflag = leftccw > 0.0;
11654   }
11655   while (rightflag) {
11656     /* Turn right until satisfied. */
11657     oprevself(*searchtri);
11658     if (searchtri->tri == m->dummytri) {
11659       printf("Internal error in finddirection():  Unable to find a\n");
11660       printf("  triangle leading from (%.12g, %.12g) to", startvertex[0],
11661              startvertex[1]);
11662       printf("  (%.12g, %.12g).\n", searchpoint[0], searchpoint[1]);
11663       internalerror();
11664     }
11665     dest(*searchtri, rightvertex);
11666     leftccw = rightccw;
11667     rightccw = counterclockwise(m, b, startvertex, searchpoint, rightvertex);
11668     rightflag = rightccw > 0.0;
11669   }
11670   if (leftccw == 0.0) {
11671     return LEFTCOLLINEAR;
11672   } else if (rightccw == 0.0) {
11673     return RIGHTCOLLINEAR;
11674   } else {
11675     return WITHIN;
11676   }
11677 }
11678 
11679 /*****************************************************************************/
11680 /*                                                                           */
11681 /*  segmentintersection()   Find the intersection of an existing segment     */
11682 /*                          and a segment that is being inserted.  Insert    */
11683 /*                          a vertex at the intersection, splitting an       */
11684 /*                          existing subsegment.                             */
11685 /*                                                                           */
11686 /*  The segment being inserted connects the apex of splittri to endpoint2.   */
11687 /*  splitsubseg is the subsegment being split, and MUST adjoin splittri.     */
11688 /*  Hence, endpoints of the subsegment being split are the origin and        */
11689 /*  destination of splittri.                                                 */
11690 /*                                                                           */
11691 /*  On completion, splittri is a handle having the newly inserted            */
11692 /*  intersection point as its origin, and endpoint1 as its destination.      */
11693 /*                                                                           */
11694 /*****************************************************************************/
11695 
11696 #ifdef ANSI_DECLARATORS
11697 void segmentintersection(struct mesh *m, struct behavior *b,
11698                          struct otri *splittri, struct osub *splitsubseg,
11699                          vertex endpoint2)
11700 #else /* not ANSI_DECLARATORS */
11701 void segmentintersection(m, b, splittri, splitsubseg, endpoint2)
11702 struct mesh *m;
11703 struct behavior *b;
11704 struct otri *splittri;
11705 struct osub *splitsubseg;
11706 vertex endpoint2;
11707 #endif /* not ANSI_DECLARATORS */
11708 
11709 {
11710   struct osub opposubseg;
11711   vertex endpoint1;
11712   vertex torg, tdest;
11713   vertex leftvertex, rightvertex;
11714   vertex newvertex;
11715   enum insertvertexresult success;
11716   REAL ex, ey;
11717   REAL tx, ty;
11718   REAL etx, ety;
11719   REAL split, denom;
11720   int i;
11721   triangle ptr;                       /* Temporary variable used by onext(). */
11722   subseg sptr;                        /* Temporary variable used by snext(). */
11723 
11724   /* Find the other three segment endpoints. */
11725   apex(*splittri, endpoint1);
11726   org(*splittri, torg);
11727   dest(*splittri, tdest);
11728   /* Segment intersection formulae; see the Antonio reference. */
11729   tx = tdest[0] - torg[0];
11730   ty = tdest[1] - torg[1];
11731   ex = endpoint2[0] - endpoint1[0];
11732   ey = endpoint2[1] - endpoint1[1];
11733   etx = torg[0] - endpoint2[0];
11734   ety = torg[1] - endpoint2[1];
11735   denom = ty * ex - tx * ey;
11736   if (denom == 0.0) {
11737     printf("Internal error in segmentintersection():");
11738     printf("  Attempt to find intersection of parallel segments.\n");
11739     internalerror();
11740   }
11741   split = (ey * etx - ex * ety) / denom;
11742   /* Create the new vertex. */
11743   newvertex = (vertex) poolalloc(&m->vertices);
11744   /* Interpolate its coordinate and attributes. */
11745   for (i = 0; i < 2 + m->nextras; i++) {
11746     newvertex[i] = torg[i] + split * (tdest[i] - torg[i]);
11747   }
11748   setvertexmark(newvertex, mark(*splitsubseg));
11749   setvertextype(newvertex, INPUTVERTEX);
11750   if (b->verbose > 1) {
11751     printf(
11752   "  Splitting subsegment (%.12g, %.12g) (%.12g, %.12g) at (%.12g, %.12g).\n",
11753            torg[0], torg[1], tdest[0], tdest[1], newvertex[0], newvertex[1]);
11754   }
11755   /* Insert the intersection vertex.  This should always succeed. */
11756   success = insertvertex(m, b, newvertex, splittri, splitsubseg, 0, 0);
11757   if (success != SUCCESSFULVERTEX) {
11758     printf("Internal error in segmentintersection():\n");
11759     printf("  Failure to split a segment.\n");
11760     internalerror();
11761   }
11762   /* Record a triangle whose origin is the new vertex. */
11763   setvertex2tri(newvertex, encode(*splittri));
11764   if (m->steinerleft > 0) {
11765     m->steinerleft--;
11766   }
11767 
11768   /* Divide the segment into two, and correct the segment endpoints. */
11769   ssymself(*splitsubseg);
11770   spivot(*splitsubseg, opposubseg);
11771   sdissolve(*splitsubseg);
11772   sdissolve(opposubseg);
11773   do {
11774     setsegorg(*splitsubseg, newvertex);
11775     snextself(*splitsubseg);
11776   } while (splitsubseg->ss != m->dummysub);
11777   do {
11778     setsegorg(opposubseg, newvertex);
11779     snextself(opposubseg);
11780   } while (opposubseg.ss != m->dummysub);
11781 
11782   /* Inserting the vertex may have caused edge flips.  We wish to rediscover */
11783   /*   the edge connecting endpoint1 to the new intersection vertex.         */
11784   finddirection(m, b, splittri, endpoint1);
11785   dest(*splittri, rightvertex);
11786   apex(*splittri, leftvertex);
11787   if ((leftvertex[0] == endpoint1[0]) && (leftvertex[1] == endpoint1[1])) {
11788     onextself(*splittri);
11789   } else if ((rightvertex[0] != endpoint1[0]) ||
11790              (rightvertex[1] != endpoint1[1])) {
11791     printf("Internal error in segmentintersection():\n");
11792     printf("  Topological inconsistency after splitting a segment.\n");
11793     internalerror();
11794   }
11795   /* `splittri' should have destination endpoint1. */
11796 }
11797 
11798 /*****************************************************************************/
11799 /*                                                                           */
11800 /*  scoutsegment()   Scout the first triangle on the path from one endpoint  */
11801 /*                   to another, and check for completion (reaching the      */
11802 /*                   second endpoint), a collinear vertex, or the            */
11803 /*                   intersection of two segments.                           */
11804 /*                                                                           */
11805 /*  Returns one if the entire segment is successfully inserted, and zero if  */
11806 /*  the job must be finished by conformingedge() or constrainededge().       */
11807 /*                                                                           */
11808 /*  If the first triangle on the path has the second endpoint as its         */
11809 /*  destination or apex, a subsegment is inserted and the job is done.       */
11810 /*                                                                           */
11811 /*  If the first triangle on the path has a destination or apex that lies on */
11812 /*  the segment, a subsegment is inserted connecting the first endpoint to   */
11813 /*  the collinear vertex, and the search is continued from the collinear     */
11814 /*  vertex.                                                                  */
11815 /*                                                                           */
11816 /*  If the first triangle on the path has a subsegment opposite its origin,  */
11817 /*  then there is a segment that intersects the segment being inserted.      */
11818 /*  Their intersection vertex is inserted, splitting the subsegment.         */
11819 /*                                                                           */
11820 /*****************************************************************************/
11821 
11822 #ifdef ANSI_DECLARATORS
11823 int scoutsegment(struct mesh *m, struct behavior *b, struct otri *searchtri,
11824                  vertex endpoint2, int newmark)
11825 #else /* not ANSI_DECLARATORS */
11826 int scoutsegment(m, b, searchtri, endpoint2, newmark)
11827 struct mesh *m;
11828 struct behavior *b;
11829 struct otri *searchtri;
11830 vertex endpoint2;
11831 int newmark;
11832 #endif /* not ANSI_DECLARATORS */
11833 
11834 {
11835   struct otri crosstri;
11836   struct osub crosssubseg;
11837   vertex leftvertex, rightvertex;
11838   enum finddirectionresult collinear;
11839   subseg sptr;                      /* Temporary variable used by tspivot(). */
11840 
11841   collinear = finddirection(m, b, searchtri, endpoint2);
11842   dest(*searchtri, rightvertex);
11843   apex(*searchtri, leftvertex);
11844   if (((leftvertex[0] == endpoint2[0]) && (leftvertex[1] == endpoint2[1])) ||
11845       ((rightvertex[0] == endpoint2[0]) && (rightvertex[1] == endpoint2[1]))) {
11846     /* The segment is already an edge in the mesh. */
11847     if ((leftvertex[0] == endpoint2[0]) && (leftvertex[1] == endpoint2[1])) {
11848       lprevself(*searchtri);
11849     }
11850     /* Insert a subsegment, if there isn't already one there. */
11851     insertsubseg(m, b, searchtri, newmark);
11852     return 1;
11853   } else if (collinear == LEFTCOLLINEAR) {
11854     /* We've collided with a vertex between the segment's endpoints. */
11855     /* Make the collinear vertex be the triangle's origin. */
11856     lprevself(*searchtri);
11857     insertsubseg(m, b, searchtri, newmark);
11858     /* Insert the remainder of the segment. */
11859     return scoutsegment(m, b, searchtri, endpoint2, newmark);
11860   } else if (collinear == RIGHTCOLLINEAR) {
11861     /* We've collided with a vertex between the segment's endpoints. */
11862     insertsubseg(m, b, searchtri, newmark);
11863     /* Make the collinear vertex be the triangle's origin. */
11864     lnextself(*searchtri);
11865     /* Insert the remainder of the segment. */
11866     return scoutsegment(m, b, searchtri, endpoint2, newmark);
11867   } else {
11868     lnext(*searchtri, crosstri);
11869     tspivot(crosstri, crosssubseg);
11870     /* Check for a crossing segment. */
11871     if (crosssubseg.ss == m->dummysub) {
11872       return 0;
11873     } else {
11874       /* Insert a vertex at the intersection. */
11875       segmentintersection(m, b, &crosstri, &crosssubseg, endpoint2);
11876       otricopy(crosstri, *searchtri);
11877       insertsubseg(m, b, searchtri, newmark);
11878       /* Insert the remainder of the segment. */
11879       return scoutsegment(m, b, searchtri, endpoint2, newmark);
11880     }
11881   }
11882 }
11883 
11884 /*****************************************************************************/
11885 /*                                                                           */
11886 /*  conformingedge()   Force a segment into a conforming Delaunay            */
11887 /*                     triangulation by inserting a vertex at its midpoint,  */
11888 /*                     and recursively forcing in the two half-segments if   */
11889 /*                     necessary.                                            */
11890 /*                                                                           */
11891 /*  Generates a sequence of subsegments connecting `endpoint1' to            */
11892 /*  `endpoint2'.  `newmark' is the boundary marker of the segment, assigned  */
11893 /*  to each new splitting vertex and subsegment.                             */
11894 /*                                                                           */
11895 /*  Note that conformingedge() does not always maintain the conforming       */
11896 /*  Delaunay property.  Once inserted, segments are locked into place;       */
11897 /*  vertices inserted later (to force other segments in) may render these    */
11898 /*  fixed segments non-Delaunay.  The conforming Delaunay property will be   */
11899 /*  restored by enforcequality() by splitting encroached subsegments.        */
11900 /*                                                                           */
11901 /*****************************************************************************/
11902 
11903 #ifndef REDUCED
11904 #ifndef CDT_ONLY
11905 
11906 #ifdef ANSI_DECLARATORS
11907 void conformingedge(struct mesh *m, struct behavior *b,
11908                     vertex endpoint1, vertex endpoint2, int newmark)
11909 #else /* not ANSI_DECLARATORS */
11910 void conformingedge(m, b, endpoint1, endpoint2, newmark)
11911 struct mesh *m;
11912 struct behavior *b;
11913 vertex endpoint1;
11914 vertex endpoint2;
11915 int newmark;
11916 #endif /* not ANSI_DECLARATORS */
11917 
11918 {
11919   struct otri searchtri1, searchtri2;
11920   struct osub brokensubseg;
11921   vertex newvertex;
11922   vertex midvertex1, midvertex2;
11923   enum insertvertexresult success;
11924   int i;
11925   subseg sptr;                      /* Temporary variable used by tspivot(). */
11926 
11927   if (b->verbose > 2) {
11928     printf("Forcing segment into triangulation by recursive splitting:\n");
11929     printf("  (%.12g, %.12g) (%.12g, %.12g)\n", endpoint1[0], endpoint1[1],
11930            endpoint2[0], endpoint2[1]);
11931   }
11932   /* Create a new vertex to insert in the middle of the segment. */
11933   newvertex = (vertex) poolalloc(&m->vertices);
11934   /* Interpolate coordinates and attributes. */
11935   for (i = 0; i < 2 + m->nextras; i++) {
11936     newvertex[i] = 0.5 * (endpoint1[i] + endpoint2[i]);
11937   }
11938   setvertexmark(newvertex, newmark);
11939   setvertextype(newvertex, SEGMENTVERTEX);
11940   /* No known triangle to search from. */
11941   searchtri1.tri = m->dummytri;
11942   /* Attempt to insert the new vertex. */
11943   success = insertvertex(m, b, newvertex, &searchtri1, (struct osub *) NULL,
11944                          0, 0);
11945   if (success == DUPLICATEVERTEX) {
11946     if (b->verbose > 2) {
11947       printf("  Segment intersects existing vertex (%.12g, %.12g).\n",
11948              newvertex[0], newvertex[1]);
11949     }
11950     /* Use the vertex that's already there. */
11951     vertexdealloc(m, newvertex);
11952     org(searchtri1, newvertex);
11953   } else {
11954     if (success == VIOLATINGVERTEX) {
11955       if (b->verbose > 2) {
11956         printf("  Two segments intersect at (%.12g, %.12g).\n",
11957                newvertex[0], newvertex[1]);
11958       }
11959       /* By fluke, we've landed right on another segment.  Split it. */
11960       tspivot(searchtri1, brokensubseg);
11961       success = insertvertex(m, b, newvertex, &searchtri1, &brokensubseg,
11962                              0, 0);
11963       if (success != SUCCESSFULVERTEX) {
11964         printf("Internal error in conformingedge():\n");
11965         printf("  Failure to split a segment.\n");
11966         internalerror();
11967       }
11968     }
11969     /* The vertex has been inserted successfully. */
11970     if (m->steinerleft > 0) {
11971       m->steinerleft--;
11972     }
11973   }
11974   otricopy(searchtri1, searchtri2);
11975   /* `searchtri1' and `searchtri2' are fastened at their origins to         */
11976   /*   `newvertex', and will be directed toward `endpoint1' and `endpoint2' */
11977   /*   respectively.  First, we must get `searchtri2' out of the way so it  */
11978   /*   won't be invalidated during the insertion of the first half of the   */
11979   /*   segment.                                                             */
11980   finddirection(m, b, &searchtri2, endpoint2);
11981   if (!scoutsegment(m, b, &searchtri1, endpoint1, newmark)) {
11982     /* The origin of searchtri1 may have changed if a collision with an */
11983     /*   intervening vertex on the segment occurred.                    */
11984     org(searchtri1, midvertex1);
11985     conformingedge(m, b, midvertex1, endpoint1, newmark);
11986   }
11987   if (!scoutsegment(m, b, &searchtri2, endpoint2, newmark)) {
11988     /* The origin of searchtri2 may have changed if a collision with an */
11989     /*   intervening vertex on the segment occurred.                    */
11990     org(searchtri2, midvertex2);
11991     conformingedge(m, b, midvertex2, endpoint2, newmark);
11992   }
11993 }
11994 
11995 #endif /* not CDT_ONLY */
11996 #endif /* not REDUCED */
11997 
11998 /*****************************************************************************/
11999 /*                                                                           */
12000 /*  delaunayfixup()   Enforce the Delaunay condition at an edge, fanning out */
12001 /*                    recursively from an existing vertex.  Pay special      */
12002 /*                    attention to stacking inverted triangles.              */
12003 /*                                                                           */
12004 /*  This is a support routine for inserting segments into a constrained      */
12005 /*  Delaunay triangulation.                                                  */
12006 /*                                                                           */
12007 /*  The origin of fixuptri is treated as if it has just been inserted, and   */
12008 /*  the local Delaunay condition needs to be enforced.  It is only enforced  */
12009 /*  in one sector, however, that being the angular range defined by          */
12010 /*  fixuptri.                                                                */
12011 /*                                                                           */
12012 /*  This routine also needs to make decisions regarding the "stacking" of    */
12013 /*  triangles.  (Read the description of constrainededge() below before      */
12014 /*  reading on here, so you understand the algorithm.)  If the position of   */
12015 /*  the new vertex (the origin of fixuptri) indicates that the vertex before */
12016 /*  it on the polygon is a reflex vertex, then "stack" the triangle by       */
12017 /*  doing nothing.  (fixuptri is an inverted triangle, which is how stacked  */
12018 /*  triangles are identified.)                                               */
12019 /*                                                                           */
12020 /*  Otherwise, check whether the vertex before that was a reflex vertex.     */
12021 /*  If so, perform an edge flip, thereby eliminating an inverted triangle    */
12022 /*  (popping it off the stack).  The edge flip may result in the creation    */
12023 /*  of a new inverted triangle, depending on whether or not the new vertex   */
12024 /*  is visible to the vertex three edges behind on the polygon.              */
12025 /*                                                                           */
12026 /*  If neither of the two vertices behind the new vertex are reflex          */
12027 /*  vertices, fixuptri and fartri, the triangle opposite it, are not         */
12028 /*  inverted; hence, ensure that the edge between them is locally Delaunay.  */
12029 /*                                                                           */
12030 /*  `leftside' indicates whether or not fixuptri is to the left of the       */
12031 /*  segment being inserted.  (Imagine that the segment is pointing up from   */
12032 /*  endpoint1 to endpoint2.)                                                 */
12033 /*                                                                           */
12034 /*****************************************************************************/
12035 
12036 #ifdef ANSI_DECLARATORS
12037 void delaunayfixup(struct mesh *m, struct behavior *b,
12038                    struct otri *fixuptri, int leftside)
12039 #else /* not ANSI_DECLARATORS */
12040 void delaunayfixup(m, b, fixuptri, leftside)
12041 struct mesh *m;
12042 struct behavior *b;
12043 struct otri *fixuptri;
12044 int leftside;
12045 #endif /* not ANSI_DECLARATORS */
12046 
12047 {
12048   struct otri neartri;
12049   struct otri fartri;
12050   struct osub faredge;
12051   vertex nearvertex, leftvertex, rightvertex, farvertex;
12052   triangle ptr;                         /* Temporary variable used by sym(). */
12053   subseg sptr;                      /* Temporary variable used by tspivot(). */
12054 
12055   lnext(*fixuptri, neartri);
12056   sym(neartri, fartri);
12057   /* Check if the edge opposite the origin of fixuptri can be flipped. */
12058   if (fartri.tri == m->dummytri) {
12059     return;
12060   }
12061   tspivot(neartri, faredge);
12062   if (faredge.ss != m->dummysub) {
12063     return;
12064   }
12065   /* Find all the relevant vertices. */
12066   apex(neartri, nearvertex);
12067   org(neartri, leftvertex);
12068   dest(neartri, rightvertex);
12069   apex(fartri, farvertex);
12070   /* Check whether the previous polygon vertex is a reflex vertex. */
12071   if (leftside) {
12072     if (counterclockwise(m, b, nearvertex, leftvertex, farvertex) <= 0.0) {
12073       /* leftvertex is a reflex vertex too.  Nothing can */
12074       /*   be done until a convex section is found.      */
12075       return;
12076     }
12077   } else {
12078     if (counterclockwise(m, b, farvertex, rightvertex, nearvertex) <= 0.0) {
12079       /* rightvertex is a reflex vertex too.  Nothing can */
12080       /*   be done until a convex section is found.       */
12081       return;
12082     }
12083   }
12084   if (counterclockwise(m, b, rightvertex, leftvertex, farvertex) > 0.0) {
12085     /* fartri is not an inverted triangle, and farvertex is not a reflex */
12086     /*   vertex.  As there are no reflex vertices, fixuptri isn't an     */
12087     /*   inverted triangle, either.  Hence, test the edge between the    */
12088     /*   triangles to ensure it is locally Delaunay.                     */
12089     if (incircle(m, b, leftvertex, farvertex, rightvertex, nearvertex) <=
12090         0.0) {
12091       return;
12092     }
12093     /* Not locally Delaunay; go on to an edge flip. */
12094   }        /* else fartri is inverted; remove it from the stack by flipping. */
12095   flip(m, b, &neartri);
12096   lprevself(*fixuptri);    /* Restore the origin of fixuptri after the flip. */
12097   /* Recursively process the two triangles that result from the flip. */
12098   delaunayfixup(m, b, fixuptri, leftside);
12099   delaunayfixup(m, b, &fartri, leftside);
12100 }
12101 
12102 /*****************************************************************************/
12103 /*                                                                           */
12104 /*  constrainededge()   Force a segment into a constrained Delaunay          */
12105 /*                      triangulation by deleting the triangles it           */
12106 /*                      intersects, and triangulating the polygons that      */
12107 /*                      form on each side of it.                             */
12108 /*                                                                           */
12109 /*  Generates a single subsegment connecting `endpoint1' to `endpoint2'.     */
12110 /*  The triangle `starttri' has `endpoint1' as its origin.  `newmark' is the */
12111 /*  boundary marker of the segment.                                          */
12112 /*                                                                           */
12113 /*  To insert a segment, every triangle whose interior intersects the        */
12114 /*  segment is deleted.  The union of these deleted triangles is a polygon   */
12115 /*  (which is not necessarily monotone, but is close enough), which is       */
12116 /*  divided into two polygons by the new segment.  This routine's task is    */
12117 /*  to generate the Delaunay triangulation of these two polygons.            */
12118 /*                                                                           */
12119 /*  You might think of this routine's behavior as a two-step process.  The   */
12120 /*  first step is to walk from endpoint1 to endpoint2, flipping each edge    */
12121 /*  encountered.  This step creates a fan of edges connected to endpoint1,   */
12122 /*  including the desired edge to endpoint2.  The second step enforces the   */
12123 /*  Delaunay condition on each side of the segment in an incremental manner: */
12124 /*  proceeding along the polygon from endpoint1 to endpoint2 (this is done   */
12125 /*  independently on each side of the segment), each vertex is "enforced"    */
12126 /*  as if it had just been inserted, but affecting only the previous         */
12127 /*  vertices.  The result is the same as if the vertices had been inserted   */
12128 /*  in the order they appear on the polygon, so the result is Delaunay.      */
12129 /*                                                                           */
12130 /*  In truth, constrainededge() interleaves these two steps.  The procedure  */
12131 /*  walks from endpoint1 to endpoint2, and each time an edge is encountered  */
12132 /*  and flipped, the newly exposed vertex (at the far end of the flipped     */
12133 /*  edge) is "enforced" upon the previously flipped edges, usually affecting */
12134 /*  only one side of the polygon (depending upon which side of the segment   */
12135 /*  the vertex falls on).                                                    */
12136 /*                                                                           */
12137 /*  The algorithm is complicated by the need to handle polygons that are not */
12138 /*  convex.  Although the polygon is not necessarily monotone, it can be     */
12139 /*  triangulated in a manner similar to the stack-based algorithms for       */
12140 /*  monotone polygons.  For each reflex vertex (local concavity) of the      */
12141 /*  polygon, there will be an inverted triangle formed by one of the edge    */
12142 /*  flips.  (An inverted triangle is one with negative area - that is, its   */
12143 /*  vertices are arranged in clockwise order - and is best thought of as a   */
12144 /*  wrinkle in the fabric of the mesh.)  Each inverted triangle can be       */
12145 /*  thought of as a reflex vertex pushed on the stack, waiting to be fixed   */
12146 /*  later.                                                                   */
12147 /*                                                                           */
12148 /*  A reflex vertex is popped from the stack when a vertex is inserted that  */
12149 /*  is visible to the reflex vertex.  (However, if the vertex behind the     */
12150 /*  reflex vertex is not visible to the reflex vertex, a new inverted        */
12151 /*  triangle will take its place on the stack.)  These details are handled   */
12152 /*  by the delaunayfixup() routine above.                                    */
12153 /*                                                                           */
12154 /*****************************************************************************/
12155 
12156 #ifdef ANSI_DECLARATORS
12157 void constrainededge(struct mesh *m, struct behavior *b,
12158                      struct otri *starttri, vertex endpoint2, int newmark)
12159 #else /* not ANSI_DECLARATORS */
12160 void constrainededge(m, b, starttri, endpoint2, newmark)
12161 struct mesh *m;
12162 struct behavior *b;
12163 struct otri *starttri;
12164 vertex endpoint2;
12165 int newmark;
12166 #endif /* not ANSI_DECLARATORS */
12167 
12168 {
12169   struct otri fixuptri, fixuptri2;
12170   struct osub crosssubseg;
12171   vertex endpoint1;
12172   vertex farvertex;
12173   REAL area;
12174   int collision;
12175   int done;
12176   triangle ptr;             /* Temporary variable used by sym() and oprev(). */
12177   subseg sptr;                      /* Temporary variable used by tspivot(). */
12178 
12179   org(*starttri, endpoint1);
12180   lnext(*starttri, fixuptri);
12181   flip(m, b, &fixuptri);
12182   /* `collision' indicates whether we have found a vertex directly */
12183   /*   between endpoint1 and endpoint2.                            */
12184   collision = 0;
12185   done = 0;
12186   do {
12187     org(fixuptri, farvertex);
12188     /* `farvertex' is the extreme point of the polygon we are "digging" */
12189     /*   to get from endpoint1 to endpoint2.                           */
12190     if ((farvertex[0] == endpoint2[0]) && (farvertex[1] == endpoint2[1])) {
12191       oprev(fixuptri, fixuptri2);
12192       /* Enforce the Delaunay condition around endpoint2. */
12193       delaunayfixup(m, b, &fixuptri, 0);
12194       delaunayfixup(m, b, &fixuptri2, 1);
12195       done = 1;
12196     } else {
12197       /* Check whether farvertex is to the left or right of the segment */
12198       /*   being inserted, to decide which edge of fixuptri to dig      */
12199       /*   through next.                                                */
12200       area = counterclockwise(m, b, endpoint1, endpoint2, farvertex);
12201       if (area == 0.0) {
12202         /* We've collided with a vertex between endpoint1 and endpoint2. */
12203         collision = 1;
12204         oprev(fixuptri, fixuptri2);
12205         /* Enforce the Delaunay condition around farvertex. */
12206         delaunayfixup(m, b, &fixuptri, 0);
12207         delaunayfixup(m, b, &fixuptri2, 1);
12208         done = 1;
12209       } else {
12210         if (area > 0.0) {        /* farvertex is to the left of the segment. */
12211           oprev(fixuptri, fixuptri2);
12212           /* Enforce the Delaunay condition around farvertex, on the */
12213           /*   left side of the segment only.                        */
12214           delaunayfixup(m, b, &fixuptri2, 1);
12215           /* Flip the edge that crosses the segment.  After the edge is */
12216           /*   flipped, one of its endpoints is the fan vertex, and the */
12217           /*   destination of fixuptri is the fan vertex.               */
12218           lprevself(fixuptri);
12219         } else {                /* farvertex is to the right of the segment. */
12220           delaunayfixup(m, b, &fixuptri, 0);
12221           /* Flip the edge that crosses the segment.  After the edge is */
12222           /*   flipped, one of its endpoints is the fan vertex, and the */
12223           /*   destination of fixuptri is the fan vertex.               */
12224           oprevself(fixuptri);
12225         }
12226         /* Check for two intersecting segments. */
12227         tspivot(fixuptri, crosssubseg);
12228         if (crosssubseg.ss == m->dummysub) {
12229           flip(m, b, &fixuptri);    /* May create inverted triangle at left. */
12230         } else {
12231           /* We've collided with a segment between endpoint1 and endpoint2. */
12232           collision = 1;
12233           /* Insert a vertex at the intersection. */
12234           segmentintersection(m, b, &fixuptri, &crosssubseg, endpoint2);
12235           done = 1;
12236         }
12237       }
12238     }
12239   } while (!done);
12240   /* Insert a subsegment to make the segment permanent. */
12241   insertsubseg(m, b, &fixuptri, newmark);
12242   /* If there was a collision with an interceding vertex, install another */
12243   /*   segment connecting that vertex with endpoint2.                     */
12244   if (collision) {
12245     /* Insert the remainder of the segment. */
12246     if (!scoutsegment(m, b, &fixuptri, endpoint2, newmark)) {
12247       constrainededge(m, b, &fixuptri, endpoint2, newmark);
12248     }
12249   }
12250 }
12251 
12252 /*****************************************************************************/
12253 /*                                                                           */
12254 /*  insertsegment()   Insert a PSLG segment into a triangulation.            */
12255 /*                                                                           */
12256 /*****************************************************************************/
12257 
12258 #ifdef ANSI_DECLARATORS
12259 void insertsegment(struct mesh *m, struct behavior *b,
12260                    vertex endpoint1, vertex endpoint2, int newmark)
12261 #else /* not ANSI_DECLARATORS */
12262 void insertsegment(m, b, endpoint1, endpoint2, newmark)
12263 struct mesh *m;
12264 struct behavior *b;
12265 vertex endpoint1;
12266 vertex endpoint2;
12267 int newmark;
12268 #endif /* not ANSI_DECLARATORS */
12269 
12270 {
12271   struct otri searchtri1, searchtri2;
12272   triangle encodedtri;
12273   vertex checkvertex;
12274   triangle ptr;                         /* Temporary variable used by sym(). */
12275 
12276   if (b->verbose > 1) {
12277     printf("  Connecting (%.12g, %.12g) to (%.12g, %.12g).\n",
12278            endpoint1[0], endpoint1[1], endpoint2[0], endpoint2[1]);
12279   }
12280 
12281   /* Find a triangle whose origin is the segment's first endpoint. */
12282   checkvertex = (vertex) NULL;
12283   encodedtri = vertex2tri(endpoint1);
12284   if (encodedtri != (triangle) NULL) {
12285     decode(encodedtri, searchtri1);
12286     org(searchtri1, checkvertex);
12287   }
12288   if (checkvertex != endpoint1) {
12289     /* Find a boundary triangle to search from. */
12290     searchtri1.tri = m->dummytri;
12291     searchtri1.orient = 0;
12292     symself(searchtri1);
12293     /* Search for the segment's first endpoint by point location. */
12294     if (locate(m, b, endpoint1, &searchtri1) != ONVERTEX) {
12295       printf(
12296         "Internal error in insertsegment():  Unable to locate PSLG vertex\n");
12297       printf("  (%.12g, %.12g) in triangulation.\n",
12298              endpoint1[0], endpoint1[1]);
12299       internalerror();
12300     }
12301   }
12302   /* Remember this triangle to improve subsequent point location. */
12303   otricopy(searchtri1, m->recenttri);
12304   /* Scout the beginnings of a path from the first endpoint */
12305   /*   toward the second.                                   */
12306   if (scoutsegment(m, b, &searchtri1, endpoint2, newmark)) {
12307     /* The segment was easily inserted. */
12308     return;
12309   }
12310   /* The first endpoint may have changed if a collision with an intervening */
12311   /*   vertex on the segment occurred.                                      */
12312   org(searchtri1, endpoint1);
12313 
12314   /* Find a triangle whose origin is the segment's second endpoint. */
12315   checkvertex = (vertex) NULL;
12316   encodedtri = vertex2tri(endpoint2);
12317   if (encodedtri != (triangle) NULL) {
12318     decode(encodedtri, searchtri2);
12319     org(searchtri2, checkvertex);
12320   }
12321   if (checkvertex != endpoint2) {
12322     /* Find a boundary triangle to search from. */
12323     searchtri2.tri = m->dummytri;
12324     searchtri2.orient = 0;
12325     symself(searchtri2);
12326     /* Search for the segment's second endpoint by point location. */
12327     if (locate(m, b, endpoint2, &searchtri2) != ONVERTEX) {
12328       printf(
12329         "Internal error in insertsegment():  Unable to locate PSLG vertex\n");
12330       printf("  (%.12g, %.12g) in triangulation.\n",
12331              endpoint2[0], endpoint2[1]);
12332       internalerror();
12333     }
12334   }
12335   /* Remember this triangle to improve subsequent point location. */
12336   otricopy(searchtri2, m->recenttri);
12337   /* Scout the beginnings of a path from the second endpoint */
12338   /*   toward the first.                                     */
12339   if (scoutsegment(m, b, &searchtri2, endpoint1, newmark)) {
12340     /* The segment was easily inserted. */
12341     return;
12342   }
12343   /* The second endpoint may have changed if a collision with an intervening */
12344   /*   vertex on the segment occurred.                                       */
12345   org(searchtri2, endpoint2);
12346 
12347 #ifndef REDUCED
12348 #ifndef CDT_ONLY
12349   if (b->splitseg) {
12350     /* Insert vertices to force the segment into the triangulation. */
12351     conformingedge(m, b, endpoint1, endpoint2, newmark);
12352   } else {
12353 #endif /* not CDT_ONLY */
12354 #endif /* not REDUCED */
12355     /* Insert the segment directly into the triangulation. */
12356     constrainededge(m, b, &searchtri1, endpoint2, newmark);
12357 #ifndef REDUCED
12358 #ifndef CDT_ONLY
12359   }
12360 #endif /* not CDT_ONLY */
12361 #endif /* not REDUCED */
12362 }
12363 
12364 /*****************************************************************************/
12365 /*                                                                           */
12366 /*  markhull()   Cover the convex hull of a triangulation with subsegments.  */
12367 /*                                                                           */
12368 /*****************************************************************************/
12369 
12370 #ifdef ANSI_DECLARATORS
12371 void markhull(struct mesh *m, struct behavior *b)
12372 #else /* not ANSI_DECLARATORS */
12373 void markhull(m, b)
12374 struct mesh *m;
12375 struct behavior *b;
12376 #endif /* not ANSI_DECLARATORS */
12377 
12378 {
12379   struct otri hulltri;
12380   struct otri nexttri;
12381   struct otri starttri;
12382   triangle ptr;             /* Temporary variable used by sym() and oprev(). */
12383 
12384   /* Find a triangle handle on the hull. */
12385   hulltri.tri = m->dummytri;
12386   hulltri.orient = 0;
12387   symself(hulltri);
12388   /* Remember where we started so we know when to stop. */
12389   otricopy(hulltri, starttri);
12390   /* Go once counterclockwise around the convex hull. */
12391   do {
12392     /* Create a subsegment if there isn't already one here. */
12393     insertsubseg(m, b, &hulltri, 1);
12394     /* To find the next hull edge, go clockwise around the next vertex. */
12395     lnextself(hulltri);
12396     oprev(hulltri, nexttri);
12397     while (nexttri.tri != m->dummytri) {
12398       otricopy(nexttri, hulltri);
12399       oprev(hulltri, nexttri);
12400     }
12401   } while (!otriequal(hulltri, starttri));
12402 }
12403 
12404 /*****************************************************************************/
12405 /*                                                                           */
12406 /*  formskeleton()   Create the segments of a triangulation, including PSLG  */
12407 /*                   segments and edges on the convex hull.                  */
12408 /*                                                                           */
12409 /*  The PSLG segments are read from a .poly file.  The return value is the   */
12410 /*  number of segments in the file.                                          */
12411 /*                                                                           */
12412 /*****************************************************************************/
12413 
12414 #ifdef TRILIBRARY
12415 
12416 #ifdef ANSI_DECLARATORS
12417 void formskeleton(struct mesh *m, struct behavior *b, int *segmentlist,
12418                   int *segmentmarkerlist, int numberofsegments)
12419 #else /* not ANSI_DECLARATORS */
12420 void formskeleton(m, b, segmentlist, segmentmarkerlist, numberofsegments)
12421 struct mesh *m;
12422 struct behavior *b;
12423 int *segmentlist;
12424 int *segmentmarkerlist;
12425 int numberofsegments;
12426 #endif /* not ANSI_DECLARATORS */
12427 
12428 #else /* not TRILIBRARY */
12429 
12430 #ifdef ANSI_DECLARATORS
12431 void formskeleton(struct mesh *m, struct behavior *b,
12432                   FILE *polyfile, char *polyfilename)
12433 #else /* not ANSI_DECLARATORS */
12434 void formskeleton(m, b, polyfile, polyfilename)
12435 struct mesh *m;
12436 struct behavior *b;
12437 FILE *polyfile;
12438 char *polyfilename;
12439 #endif /* not ANSI_DECLARATORS */
12440 
12441 #endif /* not TRILIBRARY */
12442 
12443 {
12444 #ifdef TRILIBRARY
12445   char polyfilename[6];
12446   int index;
12447 #else /* not TRILIBRARY */
12448   char inputline[INPUTLINESIZE];
12449   char *stringptr;
12450 #endif /* not TRILIBRARY */
12451   vertex endpoint1, endpoint2;
12452   int segmentmarkers;
12453   int end1, end2;
12454   int boundmarker;
12455   int i;
12456 
12457   if (b->poly) {
12458     if (!b->quiet) {
12459       printf("Recovering segments in Delaunay triangulation.\n");
12460     }
12461 #ifdef TRILIBRARY
12462     strcpy(polyfilename, "input");
12463     m->insegments = numberofsegments;
12464     segmentmarkers = segmentmarkerlist != (int *) NULL;
12465     index = 0;
12466 #else /* not TRILIBRARY */
12467     /* Read the segments from a .poly file. */
12468     /* Read number of segments and number of boundary markers. */
12469     stringptr = readline(inputline, polyfile, polyfilename);
12470     m->insegments = (int) strtol(stringptr, &stringptr, 0);
12471     stringptr = findfield(stringptr);
12472     if (*stringptr == '\0') {
12473       segmentmarkers = 0;
12474     } else {
12475       segmentmarkers = (int) strtol(stringptr, &stringptr, 0);
12476     }
12477 #endif /* not TRILIBRARY */
12478     /* If the input vertices are collinear, there is no triangulation, */
12479     /*   so don't try to insert segments.                              */
12480     if (m->triangles.items == 0) {
12481       return;
12482     }
12483 
12484     /* If segments are to be inserted, compute a mapping */
12485     /*   from vertices to triangles.                     */
12486     if (m->insegments > 0) {
12487       makevertexmap(m, b);
12488       if (b->verbose) {
12489         printf("  Recovering PSLG segments.\n");
12490       }
12491     }
12492 
12493     boundmarker = 0;
12494     /* Read and insert the segments. */
12495     for (i = 0; i < m->insegments; i++) {
12496 #ifdef TRILIBRARY
12497       end1 = segmentlist[index++];
12498       end2 = segmentlist[index++];
12499       if (segmentmarkers) {
12500         boundmarker = segmentmarkerlist[i];
12501       }
12502 #else /* not TRILIBRARY */
12503       stringptr = readline(inputline, polyfile, b->inpolyfilename);
12504       stringptr = findfield(stringptr);
12505       if (*stringptr == '\0') {
12506         printf("Error:  Segment %d has no endpoints in %s.\n",
12507                b->firstnumber + i, polyfilename);
12508         triexit(1);
12509       } else {
12510         end1 = (int) strtol(stringptr, &stringptr, 0);
12511       }
12512       stringptr = findfield(stringptr);
12513       if (*stringptr == '\0') {
12514         printf("Error:  Segment %d is missing its second endpoint in %s.\n",
12515                b->firstnumber + i, polyfilename);
12516         triexit(1);
12517       } else {
12518         end2 = (int) strtol(stringptr, &stringptr, 0);
12519       }
12520       if (segmentmarkers) {
12521         stringptr = findfield(stringptr);
12522         if (*stringptr == '\0') {
12523           boundmarker = 0;
12524         } else {
12525           boundmarker = (int) strtol(stringptr, &stringptr, 0);
12526         }
12527       }
12528 #endif /* not TRILIBRARY */
12529       if ((end1 < b->firstnumber) ||
12530           (end1 >= b->firstnumber + m->invertices)) {
12531         if (!b->quiet) {
12532           printf("Warning:  Invalid first endpoint of segment %d in %s.\n",
12533                  b->firstnumber + i, polyfilename);
12534         }
12535       } else if ((end2 < b->firstnumber) ||
12536                  (end2 >= b->firstnumber + m->invertices)) {
12537         if (!b->quiet) {
12538           printf("Warning:  Invalid second endpoint of segment %d in %s.\n",
12539                  b->firstnumber + i, polyfilename);
12540         }
12541       } else {
12542         /* Find the vertices numbered `end1' and `end2'. */
12543         endpoint1 = getvertex(m, b, end1);
12544         endpoint2 = getvertex(m, b, end2);
12545         if ((endpoint1[0] == endpoint2[0]) && (endpoint1[1] == endpoint2[1])) {
12546           if (!b->quiet) {
12547             printf("Warning:  Endpoints of segment %d are coincident in %s.\n",
12548                    b->firstnumber + i, polyfilename);
12549           }
12550         } else {
12551           insertsegment(m, b, endpoint1, endpoint2, boundmarker);
12552         }
12553       }
12554     }
12555   } else {
12556     m->insegments = 0;
12557   }
12558   if (b->convex || !b->poly) {
12559     /* Enclose the convex hull with subsegments. */
12560     if (b->verbose) {
12561       printf("  Enclosing convex hull with segments.\n");
12562     }
12563     markhull(m, b);
12564   }
12565 }
12566 
12567 /**                                                                         **/
12568 /**                                                                         **/
12569 /********* Segment insertion ends here                               *********/
12570 
12571 /********* Carving out holes and concavities begins here             *********/
12572 /**                                                                         **/
12573 /**                                                                         **/
12574 
12575 /*****************************************************************************/
12576 /*                                                                           */
12577 /*  infecthull()   Virally infect all of the triangles of the convex hull    */
12578 /*                 that are not protected by subsegments.  Where there are   */
12579 /*                 subsegments, set boundary markers as appropriate.         */
12580 /*                                                                           */
12581 /*****************************************************************************/
12582 
12583 #ifdef ANSI_DECLARATORS
12584 void infecthull(struct mesh *m, struct behavior *b)
12585 #else /* not ANSI_DECLARATORS */
12586 void infecthull(m, b)
12587 struct mesh *m;
12588 struct behavior *b;
12589 #endif /* not ANSI_DECLARATORS */
12590 
12591 {
12592   struct otri hulltri;
12593   struct otri nexttri;
12594   struct otri starttri;
12595   struct osub hullsubseg;
12596   triangle **deadtriangle;
12597   vertex horg, hdest;
12598   triangle ptr;                         /* Temporary variable used by sym(). */
12599   subseg sptr;                      /* Temporary variable used by tspivot(). */
12600 
12601   if (b->verbose) {
12602     printf("  Marking concavities (external triangles) for elimination.\n");
12603   }
12604   /* Find a triangle handle on the hull. */
12605   hulltri.tri = m->dummytri;
12606   hulltri.orient = 0;
12607   symself(hulltri);
12608   /* Remember where we started so we know when to stop. */
12609   otricopy(hulltri, starttri);
12610   /* Go once counterclockwise around the convex hull. */
12611   do {
12612     /* Ignore triangles that are already infected. */
12613     if (!infected(hulltri)) {
12614       /* Is the triangle protected by a subsegment? */
12615       tspivot(hulltri, hullsubseg);
12616       if (hullsubseg.ss == m->dummysub) {
12617         /* The triangle is not protected; infect it. */
12618         if (!infected(hulltri)) {
12619           infect(hulltri);
12620           deadtriangle = (triangle **) poolalloc(&m->viri);
12621           *deadtriangle = hulltri.tri;
12622         }
12623       } else {
12624         /* The triangle is protected; set boundary markers if appropriate. */
12625         if (mark(hullsubseg) == 0) {
12626           setmark(hullsubseg, 1);
12627           org(hulltri, horg);
12628           dest(hulltri, hdest);
12629           if (vertexmark(horg) == 0) {
12630             setvertexmark(horg, 1);
12631           }
12632           if (vertexmark(hdest) == 0) {
12633             setvertexmark(hdest, 1);
12634           }
12635         }
12636       }
12637     }
12638     /* To find the next hull edge, go clockwise around the next vertex. */
12639     lnextself(hulltri);
12640     oprev(hulltri, nexttri);
12641     while (nexttri.tri != m->dummytri) {
12642       otricopy(nexttri, hulltri);
12643       oprev(hulltri, nexttri);
12644     }
12645   } while (!otriequal(hulltri, starttri));
12646 }
12647 
12648 /*****************************************************************************/
12649 /*                                                                           */
12650 /*  plague()   Spread the virus from all infected triangles to any neighbors */
12651 /*             not protected by subsegments.  Delete all infected triangles. */
12652 /*                                                                           */
12653 /*  This is the procedure that actually creates holes and concavities.       */
12654 /*                                                                           */
12655 /*  This procedure operates in two phases.  The first phase identifies all   */
12656 /*  the triangles that will die, and marks them as infected.  They are       */
12657 /*  marked to ensure that each triangle is added to the virus pool only      */
12658 /*  once, so the procedure will terminate.                                   */
12659 /*                                                                           */
12660 /*  The second phase actually eliminates the infected triangles.  It also    */
12661 /*  eliminates orphaned vertices.                                            */
12662 /*                                                                           */
12663 /*****************************************************************************/
12664 
12665 #ifdef ANSI_DECLARATORS
12666 void plague(struct mesh *m, struct behavior *b)
12667 #else /* not ANSI_DECLARATORS */
12668 void plague(m, b)
12669 struct mesh *m;
12670 struct behavior *b;
12671 #endif /* not ANSI_DECLARATORS */
12672 
12673 {
12674   struct otri testtri;
12675   struct otri neighbor;
12676   triangle **virusloop;
12677   triangle **deadtriangle;
12678   struct osub neighborsubseg;
12679   vertex testvertex;
12680   vertex norg, ndest;
12681   vertex deadorg, deaddest, deadapex;
12682   int killorg;
12683   triangle ptr;             /* Temporary variable used by sym() and onext(). */
12684   subseg sptr;                      /* Temporary variable used by tspivot(). */
12685 
12686   if (b->verbose) {
12687     printf("  Marking neighbors of marked triangles.\n");
12688   }
12689   /* Loop through all the infected triangles, spreading the virus to */
12690   /*   their neighbors, then to their neighbors' neighbors.          */
12691   traversalinit(&m->viri);
12692   virusloop = (triangle **) traverse(&m->viri);
12693   while (virusloop != (triangle **) NULL) {
12694     testtri.tri = *virusloop;
12695     /* A triangle is marked as infected by messing with one of its pointers */
12696     /*   to subsegments, setting it to an illegal value.  Hence, we have to */
12697     /*   temporarily uninfect this triangle so that we can examine its      */
12698     /*   adjacent subsegments.                                              */
12699     uninfect(testtri);
12700     if (b->verbose > 2) {
12701       /* Assign the triangle an orientation for convenience in */
12702       /*   checking its vertices.                              */
12703       testtri.orient = 0;
12704       org(testtri, deadorg);
12705       dest(testtri, deaddest);
12706       apex(testtri, deadapex);
12707       printf("    Checking (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
12708              deadorg[0], deadorg[1], deaddest[0], deaddest[1],
12709              deadapex[0], deadapex[1]);
12710     }
12711     /* Check each of the triangle's three neighbors. */
12712     for (testtri.orient = 0; testtri.orient < 3; testtri.orient++) {
12713       /* Find the neighbor. */
12714       sym(testtri, neighbor);
12715       /* Check for a subsegment between the triangle and its neighbor. */
12716       tspivot(testtri, neighborsubseg);
12717       /* Check if the neighbor is nonexistent or already infected. */
12718       if ((neighbor.tri == m->dummytri) || infected(neighbor)) {
12719         if (neighborsubseg.ss != m->dummysub) {
12720           /* There is a subsegment separating the triangle from its      */
12721           /*   neighbor, but both triangles are dying, so the subsegment */
12722           /*   dies too.                                                 */
12723           subsegdealloc(m, neighborsubseg.ss);
12724           if (neighbor.tri != m->dummytri) {
12725             /* Make sure the subsegment doesn't get deallocated again */
12726             /*   later when the infected neighbor is visited.         */
12727             uninfect(neighbor);
12728             tsdissolve(neighbor);
12729             infect(neighbor);
12730           }
12731         }
12732       } else {                   /* The neighbor exists and is not infected. */
12733         if (neighborsubseg.ss == m->dummysub) {
12734           /* There is no subsegment protecting the neighbor, so */
12735           /*   the neighbor becomes infected.                   */
12736           if (b->verbose > 2) {
12737             org(neighbor, deadorg);
12738             dest(neighbor, deaddest);
12739             apex(neighbor, deadapex);
12740             printf(
12741               "    Marking (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
12742                    deadorg[0], deadorg[1], deaddest[0], deaddest[1],
12743                    deadapex[0], deadapex[1]);
12744           }
12745           infect(neighbor);
12746           /* Ensure that the neighbor's neighbors will be infected. */
12747           deadtriangle = (triangle **) poolalloc(&m->viri);
12748           *deadtriangle = neighbor.tri;
12749         } else {               /* The neighbor is protected by a subsegment. */
12750           /* Remove this triangle from the subsegment. */
12751           stdissolve(neighborsubseg);
12752           /* The subsegment becomes a boundary.  Set markers accordingly. */
12753           if (mark(neighborsubseg) == 0) {
12754             setmark(neighborsubseg, 1);
12755           }
12756           org(neighbor, norg);
12757           dest(neighbor, ndest);
12758           if (vertexmark(norg) == 0) {
12759             setvertexmark(norg, 1);
12760           }
12761           if (vertexmark(ndest) == 0) {
12762             setvertexmark(ndest, 1);
12763           }
12764         }
12765       }
12766     }
12767     /* Remark the triangle as infected, so it doesn't get added to the */
12768     /*   virus pool again.                                             */
12769     infect(testtri);
12770     virusloop = (triangle **) traverse(&m->viri);
12771   }
12772 
12773   if (b->verbose) {
12774     printf("  Deleting marked triangles.\n");
12775   }
12776 
12777   traversalinit(&m->viri);
12778   virusloop = (triangle **) traverse(&m->viri);
12779   while (virusloop != (triangle **) NULL) {
12780     testtri.tri = *virusloop;
12781 
12782     /* Check each of the three corners of the triangle for elimination. */
12783     /*   This is done by walking around each vertex, checking if it is  */
12784     /*   still connected to at least one live triangle.                 */
12785     for (testtri.orient = 0; testtri.orient < 3; testtri.orient++) {
12786       org(testtri, testvertex);
12787       /* Check if the vertex has already been tested. */
12788       if (testvertex != (vertex) NULL) {
12789         killorg = 1;
12790         /* Mark the corner of the triangle as having been tested. */
12791         setorg(testtri, NULL);
12792         /* Walk counterclockwise about the vertex. */
12793         onext(testtri, neighbor);
12794         /* Stop upon reaching a boundary or the starting triangle. */
12795         while ((neighbor.tri != m->dummytri) &&
12796                (!otriequal(neighbor, testtri))) {
12797           if (infected(neighbor)) {
12798             /* Mark the corner of this triangle as having been tested. */
12799             setorg(neighbor, NULL);
12800           } else {
12801             /* A live triangle.  The vertex survives. */
12802             killorg = 0;
12803           }
12804           /* Walk counterclockwise about the vertex. */
12805           onextself(neighbor);
12806         }
12807         /* If we reached a boundary, we must walk clockwise as well. */
12808         if (neighbor.tri == m->dummytri) {
12809           /* Walk clockwise about the vertex. */
12810           oprev(testtri, neighbor);
12811           /* Stop upon reaching a boundary. */
12812           while (neighbor.tri != m->dummytri) {
12813             if (infected(neighbor)) {
12814             /* Mark the corner of this triangle as having been tested. */
12815               setorg(neighbor, NULL);
12816             } else {
12817               /* A live triangle.  The vertex survives. */
12818               killorg = 0;
12819             }
12820             /* Walk clockwise about the vertex. */
12821             oprevself(neighbor);
12822           }
12823         }
12824         if (killorg) {
12825           if (b->verbose > 1) {
12826             printf("    Deleting vertex (%.12g, %.12g)\n",
12827                    testvertex[0], testvertex[1]);
12828           }
12829           setvertextype(testvertex, UNDEADVERTEX);
12830           m->undeads++;
12831         }
12832       }
12833     }
12834 
12835     /* Record changes in the number of boundary edges, and disconnect */
12836     /*   dead triangles from their neighbors.                         */
12837     for (testtri.orient = 0; testtri.orient < 3; testtri.orient++) {
12838       sym(testtri, neighbor);
12839       if (neighbor.tri == m->dummytri) {
12840         /* There is no neighboring triangle on this edge, so this edge    */
12841         /*   is a boundary edge.  This triangle is being deleted, so this */
12842         /*   boundary edge is deleted.                                    */
12843         m->hullsize--;
12844       } else {
12845         /* Disconnect the triangle from its neighbor. */
12846         dissolve(neighbor);
12847         /* There is a neighboring triangle on this edge, so this edge */
12848         /*   becomes a boundary edge when this triangle is deleted.   */
12849         m->hullsize++;
12850       }
12851     }
12852     /* Return the dead triangle to the pool of triangles. */
12853     triangledealloc(m, testtri.tri);
12854     virusloop = (triangle **) traverse(&m->viri);
12855   }
12856   /* Empty the virus pool. */
12857   poolrestart(&m->viri);
12858 }
12859 
12860 /*****************************************************************************/
12861 /*                                                                           */
12862 /*  regionplague()   Spread regional attributes and/or area constraints      */
12863 /*                   (from a .poly file) throughout the mesh.                */
12864 /*                                                                           */
12865 /*  This procedure operates in two phases.  The first phase spreads an       */
12866 /*  attribute and/or an area constraint through a (segment-bounded) region.  */
12867 /*  The triangles are marked to ensure that each triangle is added to the    */
12868 /*  virus pool only once, so the procedure will terminate.                   */
12869 /*                                                                           */
12870 /*  The second phase uninfects all infected triangles, returning them to     */
12871 /*  normal.                                                                  */
12872 /*                                                                           */
12873 /*****************************************************************************/
12874 
12875 #ifdef ANSI_DECLARATORS
12876 void regionplague(struct mesh *m, struct behavior *b,
12877                   REAL attribute, REAL area)
12878 #else /* not ANSI_DECLARATORS */
12879 void regionplague(m, b, attribute, area)
12880 struct mesh *m;
12881 struct behavior *b;
12882 REAL attribute;
12883 REAL area;
12884 #endif /* not ANSI_DECLARATORS */
12885 
12886 {
12887   struct otri testtri;
12888   struct otri neighbor;
12889   triangle **virusloop;
12890   triangle **regiontri;
12891   struct osub neighborsubseg;
12892   vertex regionorg, regiondest, regionapex;
12893   triangle ptr;             /* Temporary variable used by sym() and onext(). */
12894   subseg sptr;                      /* Temporary variable used by tspivot(). */
12895 
12896   if (b->verbose > 1) {
12897     printf("  Marking neighbors of marked triangles.\n");
12898   }
12899   /* Loop through all the infected triangles, spreading the attribute      */
12900   /*   and/or area constraint to their neighbors, then to their neighbors' */
12901   /*   neighbors.                                                          */
12902   traversalinit(&m->viri);
12903   virusloop = (triangle **) traverse(&m->viri);
12904   while (virusloop != (triangle **) NULL) {
12905     testtri.tri = *virusloop;
12906     /* A triangle is marked as infected by messing with one of its pointers */
12907     /*   to subsegments, setting it to an illegal value.  Hence, we have to */
12908     /*   temporarily uninfect this triangle so that we can examine its      */
12909     /*   adjacent subsegments.                                              */
12910     uninfect(testtri);
12911     if (b->regionattrib) {
12912       /* Set an attribute. */
12913       setelemattribute(testtri, m->eextras, attribute);
12914     }
12915     if (b->vararea) {
12916       /* Set an area constraint. */
12917       setareabound(testtri, area);
12918     }
12919     if (b->verbose > 2) {
12920       /* Assign the triangle an orientation for convenience in */
12921       /*   checking its vertices.                              */
12922       testtri.orient = 0;
12923       org(testtri, regionorg);
12924       dest(testtri, regiondest);
12925       apex(testtri, regionapex);
12926       printf("    Checking (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
12927              regionorg[0], regionorg[1], regiondest[0], regiondest[1],
12928              regionapex[0], regionapex[1]);
12929     }
12930     /* Check each of the triangle's three neighbors. */
12931     for (testtri.orient = 0; testtri.orient < 3; testtri.orient++) {
12932       /* Find the neighbor. */
12933       sym(testtri, neighbor);
12934       /* Check for a subsegment between the triangle and its neighbor. */
12935       tspivot(testtri, neighborsubseg);
12936       /* Make sure the neighbor exists, is not already infected, and */
12937       /*   isn't protected by a subsegment.                          */
12938       if ((neighbor.tri != m->dummytri) && !infected(neighbor)
12939           && (neighborsubseg.ss == m->dummysub)) {
12940         if (b->verbose > 2) {
12941           org(neighbor, regionorg);
12942           dest(neighbor, regiondest);
12943           apex(neighbor, regionapex);
12944           printf("    Marking (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
12945                  regionorg[0], regionorg[1], regiondest[0], regiondest[1],
12946                  regionapex[0], regionapex[1]);
12947         }
12948         /* Infect the neighbor. */
12949         infect(neighbor);
12950         /* Ensure that the neighbor's neighbors will be infected. */
12951         regiontri = (triangle **) poolalloc(&m->viri);
12952         *regiontri = neighbor.tri;
12953       }
12954     }
12955     /* Remark the triangle as infected, so it doesn't get added to the */
12956     /*   virus pool again.                                             */
12957     infect(testtri);
12958     virusloop = (triangle **) traverse(&m->viri);
12959   }
12960 
12961   /* Uninfect all triangles. */
12962   if (b->verbose > 1) {
12963     printf("  Unmarking marked triangles.\n");
12964   }
12965   traversalinit(&m->viri);
12966   virusloop = (triangle **) traverse(&m->viri);
12967   while (virusloop != (triangle **) NULL) {
12968     testtri.tri = *virusloop;
12969     uninfect(testtri);
12970     virusloop = (triangle **) traverse(&m->viri);
12971   }
12972   /* Empty the virus pool. */
12973   poolrestart(&m->viri);
12974 }
12975 
12976 /*****************************************************************************/
12977 /*                                                                           */
12978 /*  carveholes()   Find the holes and infect them.  Find the area            */
12979 /*                 constraints and infect them.  Infect the convex hull.     */
12980 /*                 Spread the infection and kill triangles.  Spread the      */
12981 /*                 area constraints.                                         */
12982 /*                                                                           */
12983 /*  This routine mainly calls other routines to carry out all these          */
12984 /*  functions.                                                               */
12985 /*                                                                           */
12986 /*****************************************************************************/
12987 
12988 #ifdef ANSI_DECLARATORS
12989 void carveholes(struct mesh *m, struct behavior *b, REAL *holelist, int holes,
12990                 REAL *regionlist, int regions)
12991 #else /* not ANSI_DECLARATORS */
12992 void carveholes(m, b, holelist, holes, regionlist, regions)
12993 struct mesh *m;
12994 struct behavior *b;
12995 REAL *holelist;
12996 int holes;
12997 REAL *regionlist;
12998 int regions;
12999 #endif /* not ANSI_DECLARATORS */
13000 
13001 {
13002   struct otri searchtri;
13003   struct otri triangleloop;
13004   struct otri *regiontris;
13005   triangle **holetri;
13006   triangle **regiontri;
13007   vertex searchorg, searchdest;
13008   enum locateresult intersect;
13009   int i;
13010   triangle ptr;                         /* Temporary variable used by sym(). */
13011 
13012   if (!(b->quiet || (b->noholes && b->convex))) {
13013     printf("Removing unwanted triangles.\n");
13014     if (b->verbose && (holes > 0)) {
13015       printf("  Marking holes for elimination.\n");
13016     }
13017   }
13018 
13019   if (regions > 0) {
13020     /* Allocate storage for the triangles in which region points fall. */
13021     regiontris = (struct otri *) trimalloc(regions *
13022                                            (int) sizeof(struct otri));
13023   } else {
13024     regiontris = (struct otri *) NULL;
13025   }
13026 
13027   if (((holes > 0) && !b->noholes) || !b->convex || (regions > 0)) {
13028     /* Initialize a pool of viri to be used for holes, concavities, */
13029     /*   regional attributes, and/or regional area constraints.     */
13030     poolinit(&m->viri, sizeof(triangle *), VIRUSPERBLOCK, VIRUSPERBLOCK, 0);
13031   }
13032 
13033   if (!b->convex) {
13034     /* Mark as infected any unprotected triangles on the boundary. */
13035     /*   This is one way by which concavities are created.         */
13036     infecthull(m, b);
13037   }
13038 
13039   if ((holes > 0) && !b->noholes) {
13040     /* Infect each triangle in which a hole lies. */
13041     for (i = 0; i < 2 * holes; i += 2) {
13042       /* Ignore holes that aren't within the bounds of the mesh. */
13043       if ((holelist[i] >= m->xmin) && (holelist[i] <= m->xmax)
13044           && (holelist[i + 1] >= m->ymin) && (holelist[i + 1] <= m->ymax)) {
13045         /* Start searching from some triangle on the outer boundary. */
13046         searchtri.tri = m->dummytri;
13047         searchtri.orient = 0;
13048         symself(searchtri);
13049         /* Ensure that the hole is to the left of this boundary edge; */
13050         /*   otherwise, locate() will falsely report that the hole    */
13051         /*   falls within the starting triangle.                      */
13052         org(searchtri, searchorg);
13053         dest(searchtri, searchdest);
13054         if (counterclockwise(m, b, searchorg, searchdest, &holelist[i]) >
13055             0.0) {
13056           /* Find a triangle that contains the hole. */
13057           intersect = locate(m, b, &holelist[i], &searchtri);
13058           if ((intersect != OUTSIDE) && (!infected(searchtri))) {
13059             /* Infect the triangle.  This is done by marking the triangle  */
13060             /*   as infected and including the triangle in the virus pool. */
13061             infect(searchtri);
13062             holetri = (triangle **) poolalloc(&m->viri);
13063             *holetri = searchtri.tri;
13064           }
13065         }
13066       }
13067     }
13068   }
13069 
13070   /* Now, we have to find all the regions BEFORE we carve the holes, because */
13071   /*   locate() won't work when the triangulation is no longer convex.       */
13072   /*   (Incidentally, this is the reason why regional attributes and area    */
13073   /*   constraints can't be used when refining a preexisting mesh, which     */
13074   /*   might not be convex; they can only be used with a freshly             */
13075   /*   triangulated PSLG.)                                                   */
13076   if (regions > 0) {
13077     /* Find the starting triangle for each region. */
13078     for (i = 0; i < regions; i++) {
13079       regiontris[i].tri = m->dummytri;
13080       /* Ignore region points that aren't within the bounds of the mesh. */
13081       if ((regionlist[4 * i] >= m->xmin) && (regionlist[4 * i] <= m->xmax) &&
13082           (regionlist[4 * i + 1] >= m->ymin) &&
13083           (regionlist[4 * i + 1] <= m->ymax)) {
13084         /* Start searching from some triangle on the outer boundary. */
13085         searchtri.tri = m->dummytri;
13086         searchtri.orient = 0;
13087         symself(searchtri);
13088         /* Ensure that the region point is to the left of this boundary */
13089         /*   edge; otherwise, locate() will falsely report that the     */
13090         /*   region point falls within the starting triangle.           */
13091         org(searchtri, searchorg);
13092         dest(searchtri, searchdest);
13093         if (counterclockwise(m, b, searchorg, searchdest, &regionlist[4 * i]) >
13094             0.0) {
13095           /* Find a triangle that contains the region point. */
13096           intersect = locate(m, b, &regionlist[4 * i], &searchtri);
13097           if ((intersect != OUTSIDE) && (!infected(searchtri))) {
13098             /* Record the triangle for processing after the */
13099             /*   holes have been carved.                    */
13100             otricopy(searchtri, regiontris[i]);
13101           }
13102         }
13103       }
13104     }
13105   }
13106 
13107   if (m->viri.items > 0) {
13108     /* Carve the holes and concavities. */
13109     plague(m, b);
13110   }
13111   /* The virus pool should be empty now. */
13112 
13113   if (regions > 0) {
13114     if (!b->quiet) {
13115       if (b->regionattrib) {
13116         if (b->vararea) {
13117           printf("Spreading regional attributes and area constraints.\n");
13118         } else {
13119           printf("Spreading regional attributes.\n");
13120         }
13121       } else {
13122         printf("Spreading regional area constraints.\n");
13123       }
13124     }
13125     if (b->regionattrib && !b->refine) {
13126       /* Assign every triangle a regional attribute of zero. */
13127       traversalinit(&m->triangles);
13128       triangleloop.orient = 0;
13129       triangleloop.tri = triangletraverse(m);
13130       while (triangleloop.tri != (triangle *) NULL) {
13131         setelemattribute(triangleloop, m->eextras, 0.0);
13132         triangleloop.tri = triangletraverse(m);
13133       }
13134     }
13135     for (i = 0; i < regions; i++) {
13136       if (regiontris[i].tri != m->dummytri) {
13137         /* Make sure the triangle under consideration still exists. */
13138         /*   It may have been eaten by the virus.                   */
13139         if (!deadtri(regiontris[i].tri)) {
13140           /* Put one triangle in the virus pool. */
13141           infect(regiontris[i]);
13142           regiontri = (triangle **) poolalloc(&m->viri);
13143           *regiontri = regiontris[i].tri;
13144           /* Apply one region's attribute and/or area constraint. */
13145           regionplague(m, b, regionlist[4 * i + 2], regionlist[4 * i + 3]);
13146           /* The virus pool should be empty now. */
13147         }
13148       }
13149     }
13150     if (b->regionattrib && !b->refine) {
13151       /* Note the fact that each triangle has an additional attribute. */
13152       m->eextras++;
13153     }
13154   }
13155 
13156   /* Free up memory. */
13157   if (((holes > 0) && !b->noholes) || !b->convex || (regions > 0)) {
13158     pooldeinit(&m->viri);
13159   }
13160   if (regions > 0) {
13161     trifree((void *) regiontris);
13162   }
13163 }
13164 
13165 /**                                                                         **/
13166 /**                                                                         **/
13167 /********* Carving out holes and concavities ends here               *********/
13168 
13169 /********* Mesh quality maintenance begins here                      *********/
13170 /**                                                                         **/
13171 /**                                                                         **/
13172 
13173 /*****************************************************************************/
13174 /*                                                                           */
13175 /*  tallyencs()   Traverse the entire list of subsegments, and check each    */
13176 /*                to see if it is encroached.  If so, add it to the list.    */
13177 /*                                                                           */
13178 /*****************************************************************************/
13179 
13180 #ifndef CDT_ONLY
13181 
13182 #ifdef ANSI_DECLARATORS
13183 void tallyencs(struct mesh *m, struct behavior *b)
13184 #else /* not ANSI_DECLARATORS */
13185 void tallyencs(m, b)
13186 struct mesh *m;
13187 struct behavior *b;
13188 #endif /* not ANSI_DECLARATORS */
13189 
13190 {
13191   struct osub subsegloop;
13192 
13193   traversalinit(&m->subsegs);
13194   subsegloop.ssorient = 0;
13195   subsegloop.ss = subsegtraverse(m);
13196   while (subsegloop.ss != (subseg *) NULL) {
13197     /* If the segment is encroached, add it to the list. */
13198     checkseg4encroach(m, b, &subsegloop);
13199     subsegloop.ss = subsegtraverse(m);
13200   }
13201 }
13202 
13203 #endif /* not CDT_ONLY */
13204 
13205 /*****************************************************************************/
13206 /*                                                                           */
13207 /*  precisionerror()  Print an error message for precision problems.         */
13208 /*                                                                           */
13209 /*****************************************************************************/
13210 
13211 #ifndef CDT_ONLY
13212 
13213 void precisionerror()
13214 {
13215   printf("Try increasing the area criterion and/or reducing the minimum\n");
13216   printf("  allowable angle so that tiny triangles are not created.\n");
13217 #ifdef SINGLE
13218   printf("Alternatively, try recompiling me with double precision\n");
13219   printf("  arithmetic (by removing \"#define SINGLE\" from the\n");
13220   printf("  source file or \"-DSINGLE\" from the makefile).\n");
13221 #endif /* SINGLE */
13222 }
13223 
13224 #endif /* not CDT_ONLY */
13225 
13226 /*****************************************************************************/
13227 /*                                                                           */
13228 /*  splitencsegs()   Split all the encroached subsegments.                   */
13229 /*                                                                           */
13230 /*  Each encroached subsegment is repaired by splitting it - inserting a     */
13231 /*  vertex at or near its midpoint.  Newly inserted vertices may encroach    */
13232 /*  upon other subsegments; these are also repaired.                         */
13233 /*                                                                           */
13234 /*  `triflaws' is a flag that specifies whether one should take note of new  */
13235 /*  bad triangles that result from inserting vertices to repair encroached   */
13236 /*  subsegments.                                                             */
13237 /*                                                                           */
13238 /*****************************************************************************/
13239 
13240 #ifndef CDT_ONLY
13241 
13242 #ifdef ANSI_DECLARATORS
13243 void splitencsegs(struct mesh *m, struct behavior *b, int triflaws)
13244 #else /* not ANSI_DECLARATORS */
13245 void splitencsegs(m, b, triflaws)
13246 struct mesh *m;
13247 struct behavior *b;
13248 int triflaws;
13249 #endif /* not ANSI_DECLARATORS */
13250 
13251 {
13252   struct otri enctri;
13253   struct otri testtri;
13254   struct osub testsh;
13255   struct osub currentenc;
13256   struct badsubseg *encloop;
13257   vertex eorg, edest, eapex;
13258   vertex newvertex;
13259   enum insertvertexresult success;
13260   REAL segmentlength, nearestpoweroftwo;
13261   REAL split;
13262   REAL multiplier, divisor;
13263   int acuteorg, acuteorg2, acutedest, acutedest2;
13264   int i;
13265   triangle ptr;                     /* Temporary variable used by stpivot(). */
13266   subseg sptr;                        /* Temporary variable used by snext(). */
13267 
13268   /* Note that steinerleft == -1 if an unlimited number */
13269   /*   of Steiner points is allowed.                    */
13270   while ((m->badsubsegs.items > 0) && (m->steinerleft != 0)) {
13271     traversalinit(&m->badsubsegs);
13272     encloop = badsubsegtraverse(m);
13273     while ((encloop != (struct badsubseg *) NULL) && (m->steinerleft != 0)) {
13274       sdecode(encloop->encsubseg, currentenc);
13275       sorg(currentenc, eorg);
13276       sdest(currentenc, edest);
13277       /* Make sure that this segment is still the same segment it was   */
13278       /*   when it was determined to be encroached.  If the segment was */
13279       /*   enqueued multiple times (because several newly inserted      */
13280       /*   vertices encroached it), it may have already been split.     */
13281       if (!deadsubseg(currentenc.ss) &&
13282           (eorg == encloop->subsegorg) && (edest == encloop->subsegdest)) {
13283         /* To decide where to split a segment, we need to know if the   */
13284         /*   segment shares an endpoint with an adjacent segment.       */
13285         /*   The concern is that, if we simply split every encroached   */
13286         /*   segment in its center, two adjacent segments with a small  */
13287         /*   angle between them might lead to an infinite loop; each    */
13288         /*   vertex added to split one segment will encroach upon the   */
13289         /*   other segment, which must then be split with a vertex that */
13290         /*   will encroach upon the first segment, and so on forever.   */
13291         /* To avoid this, imagine a set of concentric circles, whose    */
13292         /*   radii are powers of two, about each segment endpoint.      */
13293         /*   These concentric circles determine where the segment is    */
13294         /*   split.  (If both endpoints are shared with adjacent        */
13295         /*   segments, split the segment in the middle, and apply the   */
13296         /*   concentric circles for later splittings.)                  */
13297 
13298         /* Is the origin shared with another segment? */
13299         stpivot(currentenc, enctri);
13300         lnext(enctri, testtri);
13301         tspivot(testtri, testsh);
13302         acuteorg = testsh.ss != m->dummysub;
13303         /* Is the destination shared with another segment? */
13304         lnextself(testtri);
13305         tspivot(testtri, testsh);
13306         acutedest = testsh.ss != m->dummysub;
13307 
13308         /* If we're using Chew's algorithm (rather than Ruppert's) */
13309         /*   to define encroachment, delete free vertices from the */
13310         /*   subsegment's diametral circle.                        */
13311         if (!b->conformdel && !acuteorg && !acutedest) {
13312           apex(enctri, eapex);
13313           while ((vertextype(eapex) == FREEVERTEX) &&
13314                  ((eorg[0] - eapex[0]) * (edest[0] - eapex[0]) +
13315                   (eorg[1] - eapex[1]) * (edest[1] - eapex[1]) < 0.0)) {
13316             deletevertex(m, b, &testtri);
13317             stpivot(currentenc, enctri);
13318             apex(enctri, eapex);
13319             lprev(enctri, testtri);
13320           }
13321         }
13322 
13323         /* Now, check the other side of the segment, if there's a triangle */
13324         /*   there.                                                        */
13325         sym(enctri, testtri);
13326         if (testtri.tri != m->dummytri) {
13327           /* Is the destination shared with another segment? */
13328           lnextself(testtri);
13329           tspivot(testtri, testsh);
13330           acutedest2 = testsh.ss != m->dummysub;
13331           acutedest = acutedest || acutedest2;
13332           /* Is the origin shared with another segment? */
13333           lnextself(testtri);
13334           tspivot(testtri, testsh);
13335           acuteorg2 = testsh.ss != m->dummysub;
13336           acuteorg = acuteorg || acuteorg2;
13337 
13338           /* Delete free vertices from the subsegment's diametral circle. */
13339           if (!b->conformdel && !acuteorg2 && !acutedest2) {
13340             org(testtri, eapex);
13341             while ((vertextype(eapex) == FREEVERTEX) &&
13342                    ((eorg[0] - eapex[0]) * (edest[0] - eapex[0]) +
13343                     (eorg[1] - eapex[1]) * (edest[1] - eapex[1]) < 0.0)) {
13344               deletevertex(m, b, &testtri);
13345               sym(enctri, testtri);
13346               apex(testtri, eapex);
13347               lprevself(testtri);
13348             }
13349           }
13350         }
13351 
13352         /* Use the concentric circles if exactly one endpoint is shared */
13353         /*   with another adjacent segment.                             */
13354         if (acuteorg || acutedest) {
13355           segmentlength = sqrt((edest[0] - eorg[0]) * (edest[0] - eorg[0]) +
13356                                (edest[1] - eorg[1]) * (edest[1] - eorg[1]));
13357           /* Find the power of two that most evenly splits the segment.  */
13358           /*   The worst case is a 2:1 ratio between subsegment lengths. */
13359           nearestpoweroftwo = 1.0;
13360           while (segmentlength > 3.0 * nearestpoweroftwo) {
13361             nearestpoweroftwo *= 2.0;
13362           }
13363           while (segmentlength < 1.5 * nearestpoweroftwo) {
13364             nearestpoweroftwo *= 0.5;
13365           }
13366           /* Where do we split the segment? */
13367           split = nearestpoweroftwo / segmentlength;
13368           if (acutedest) {
13369             split = 1.0 - split;
13370           }
13371         } else {
13372           /* If we're not worried about adjacent segments, split */
13373           /*   this segment in the middle.                       */
13374           split = 0.5;
13375         }
13376 
13377         /* Create the new vertex. */
13378         newvertex = (vertex) poolalloc(&m->vertices);
13379         /* Interpolate its coordinate and attributes. */
13380         for (i = 0; i < 2 + m->nextras; i++) {
13381           newvertex[i] = eorg[i] + split * (edest[i] - eorg[i]);
13382         }
13383 
13384         if (!b->noexact) {
13385           /* Roundoff in the above calculation may yield a `newvertex'   */
13386           /*   that is not precisely collinear with `eorg' and `edest'.  */
13387           /*   Improve collinearity by one step of iterative refinement. */
13388           multiplier = counterclockwise(m, b, eorg, edest, newvertex);
13389           divisor = ((eorg[0] - edest[0]) * (eorg[0] - edest[0]) +
13390                      (eorg[1] - edest[1]) * (eorg[1] - edest[1]));
13391           if ((multiplier != 0.0) && (divisor != 0.0)) {
13392             multiplier = multiplier / divisor;
13393             /* Watch out for NANs. */
13394             if (multiplier == multiplier) {
13395               newvertex[0] += multiplier * (edest[1] - eorg[1]);
13396               newvertex[1] += multiplier * (eorg[0] - edest[0]);
13397             }
13398           }
13399         }
13400 
13401         setvertexmark(newvertex, mark(currentenc));
13402         setvertextype(newvertex, SEGMENTVERTEX);
13403         if (b->verbose > 1) {
13404           printf(
13405   "  Splitting subsegment (%.12g, %.12g) (%.12g, %.12g) at (%.12g, %.12g).\n",
13406                  eorg[0], eorg[1], edest[0], edest[1],
13407                  newvertex[0], newvertex[1]);
13408         }
13409         /* Check whether the new vertex lies on an endpoint. */
13410         if (((newvertex[0] == eorg[0]) && (newvertex[1] == eorg[1])) ||
13411             ((newvertex[0] == edest[0]) && (newvertex[1] == edest[1]))) {
13412           printf("Error:  Ran out of precision at (%.12g, %.12g).\n",
13413                  newvertex[0], newvertex[1]);
13414           printf("I attempted to split a segment to a smaller size than\n");
13415           printf("  can be accommodated by the finite precision of\n");
13416           printf("  floating point arithmetic.\n");
13417           precisionerror();
13418           triexit(1);
13419         }
13420         /* Insert the splitting vertex.  This should always succeed. */
13421         success = insertvertex(m, b, newvertex, &enctri, &currentenc,
13422                                1, triflaws);
13423         if ((success != SUCCESSFULVERTEX) && (success != ENCROACHINGVERTEX)) {
13424           printf("Internal error in splitencsegs():\n");
13425           printf("  Failure to split a segment.\n");
13426           internalerror();
13427         }
13428         if (m->steinerleft > 0) {
13429           m->steinerleft--;
13430         }
13431         /* Check the two new subsegments to see if they're encroached. */
13432         checkseg4encroach(m, b, &currentenc);
13433         snextself(currentenc);
13434         checkseg4encroach(m, b, &currentenc);
13435       }
13436 
13437       badsubsegdealloc(m, encloop);
13438       encloop = badsubsegtraverse(m);
13439     }
13440   }
13441 }
13442 
13443 #endif /* not CDT_ONLY */
13444 
13445 /*****************************************************************************/
13446 /*                                                                           */
13447 /*  tallyfaces()   Test every triangle in the mesh for quality measures.     */
13448 /*                                                                           */
13449 /*****************************************************************************/
13450 
13451 #ifndef CDT_ONLY
13452 
13453 #ifdef ANSI_DECLARATORS
13454 void tallyfaces(struct mesh *m, struct behavior *b)
13455 #else /* not ANSI_DECLARATORS */
13456 void tallyfaces(m, b)
13457 struct mesh *m;
13458 struct behavior *b;
13459 #endif /* not ANSI_DECLARATORS */
13460 
13461 {
13462   struct otri triangleloop;
13463 
13464   if (b->verbose) {
13465     printf("  Making a list of bad triangles.\n");
13466   }
13467   traversalinit(&m->triangles);
13468   triangleloop.orient = 0;
13469   triangleloop.tri = triangletraverse(m);
13470   while (triangleloop.tri != (triangle *) NULL) {
13471     /* If the triangle is bad, enqueue it. */
13472     testtriangle(m, b, &triangleloop);
13473     triangleloop.tri = triangletraverse(m);
13474   }
13475 }
13476 
13477 #endif /* not CDT_ONLY */
13478 
13479 /*****************************************************************************/
13480 /*                                                                           */
13481 /*  splittriangle()   Inserts a vertex at the circumcenter of a triangle.    */
13482 /*                    Deletes the newly inserted vertex if it encroaches     */
13483 /*                    upon a segment.                                        */
13484 /*                                                                           */
13485 /*****************************************************************************/
13486 
13487 #ifndef CDT_ONLY
13488 
13489 #ifdef ANSI_DECLARATORS
13490 void splittriangle(struct mesh *m, struct behavior *b,
13491                    struct badtriang *badtri)
13492 #else /* not ANSI_DECLARATORS */
13493 void splittriangle(m, b, badtri)
13494 struct mesh *m;
13495 struct behavior *b;
13496 struct badtriang *badtri;
13497 #endif /* not ANSI_DECLARATORS */
13498 
13499 {
13500   struct otri badotri;
13501   vertex borg, bdest, bapex;
13502   vertex newvertex;
13503   REAL xi, eta;
13504   enum insertvertexresult success;
13505   int errorflag;
13506   int i;
13507 
13508   decode(badtri->poortri, badotri);
13509   org(badotri, borg);
13510   dest(badotri, bdest);
13511   apex(badotri, bapex);
13512   /* Make sure that this triangle is still the same triangle it was      */
13513   /*   when it was tested and determined to be of bad quality.           */
13514   /*   Subsequent transformations may have made it a different triangle. */
13515   if (!deadtri(badotri.tri) && (borg == badtri->triangorg) &&
13516       (bdest == badtri->triangdest) && (bapex == badtri->triangapex)) {
13517     if (b->verbose > 1) {
13518       printf("  Splitting this triangle at its circumcenter:\n");
13519       printf("    (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n", borg[0],
13520              borg[1], bdest[0], bdest[1], bapex[0], bapex[1]);
13521     }
13522 
13523     errorflag = 0;
13524     /* Create a new vertex at the triangle's circumcenter. */
13525     newvertex = (vertex) poolalloc(&m->vertices);
13526     findcircumcenter(m, b, borg, bdest, bapex, newvertex, &xi, &eta, 1);
13527 
13528     /* Check whether the new vertex lies on a triangle vertex. */
13529     if (((newvertex[0] == borg[0]) && (newvertex[1] == borg[1])) ||
13530         ((newvertex[0] == bdest[0]) && (newvertex[1] == bdest[1])) ||
13531         ((newvertex[0] == bapex[0]) && (newvertex[1] == bapex[1]))) {
13532       if (!b->quiet) {
13533         printf(
13534              "Warning:  New vertex (%.12g, %.12g) falls on existing vertex.\n",
13535                newvertex[0], newvertex[1]);
13536         errorflag = 1;
13537       }
13538       vertexdealloc(m, newvertex);
13539     } else {
13540       for (i = 2; i < 2 + m->nextras; i++) {
13541         /* Interpolate the vertex attributes at the circumcenter. */
13542         newvertex[i] = borg[i] + xi * (bdest[i] - borg[i])
13543                               + eta * (bapex[i] - borg[i]);
13544       }
13545       /* The new vertex must be in the interior, and therefore is a */
13546       /*   free vertex with a marker of zero.                       */
13547       setvertexmark(newvertex, 0);
13548       setvertextype(newvertex, FREEVERTEX);
13549 
13550       /* Ensure that the handle `badotri' does not represent the longest  */
13551       /*   edge of the triangle.  This ensures that the circumcenter must */
13552       /*   fall to the left of this edge, so point location will work.    */
13553       /*   (If the angle org-apex-dest exceeds 90 degrees, then the       */
13554       /*   circumcenter lies outside the org-dest edge, and eta is        */
13555       /*   negative.  Roundoff error might prevent eta from being         */
13556       /*   negative when it should be, so I test eta against xi.)         */
13557       if (eta < xi) {
13558         lprevself(badotri);
13559       }
13560 
13561       /* Insert the circumcenter, searching from the edge of the triangle, */
13562       /*   and maintain the Delaunay property of the triangulation.        */
13563       success = insertvertex(m, b, newvertex, &badotri, (struct osub *) NULL,
13564                              1, 1);
13565       if (success == SUCCESSFULVERTEX) {
13566         if (m->steinerleft > 0) {
13567           m->steinerleft--;
13568         }
13569       } else if (success == ENCROACHINGVERTEX) {
13570         /* If the newly inserted vertex encroaches upon a subsegment, */
13571         /*   delete the new vertex.                                   */
13572         undovertex(m, b);
13573         if (b->verbose > 1) {
13574           printf("  Rejecting (%.12g, %.12g).\n", newvertex[0], newvertex[1]);
13575         }
13576         vertexdealloc(m, newvertex);
13577       } else if (success == VIOLATINGVERTEX) {
13578         /* Failed to insert the new vertex, but some subsegment was */
13579         /*   marked as being encroached.                            */
13580         vertexdealloc(m, newvertex);
13581       } else {                                 /* success == DUPLICATEVERTEX */
13582         /* Couldn't insert the new vertex because a vertex is already there. */
13583         if (!b->quiet) {
13584           printf(
13585             "Warning:  New vertex (%.12g, %.12g) falls on existing vertex.\n",
13586                  newvertex[0], newvertex[1]);
13587           errorflag = 1;
13588         }
13589         vertexdealloc(m, newvertex);
13590       }
13591     }
13592     if (errorflag) {
13593       if (b->verbose) {
13594         printf("  The new vertex is at the circumcenter of triangle\n");
13595         printf("    (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
13596                borg[0], borg[1], bdest[0], bdest[1], bapex[0], bapex[1]);
13597       }
13598       printf("This probably means that I am trying to refine triangles\n");
13599       printf("  to a smaller size than can be accommodated by the finite\n");
13600       printf("  precision of floating point arithmetic.  (You can be\n");
13601       printf("  sure of this if I fail to terminate.)\n");
13602       precisionerror();
13603     }
13604   }
13605 }
13606 
13607 #endif /* not CDT_ONLY */
13608 
13609 /*****************************************************************************/
13610 /*                                                                           */
13611 /*  enforcequality()   Remove all the encroached subsegments and bad         */
13612 /*                     triangles from the triangulation.                     */
13613 /*                                                                           */
13614 /*****************************************************************************/
13615 
13616 #ifndef CDT_ONLY
13617 
13618 #ifdef ANSI_DECLARATORS
13619 void enforcequality(struct mesh *m, struct behavior *b)
13620 #else /* not ANSI_DECLARATORS */
13621 void enforcequality(m, b)
13622 struct mesh *m;
13623 struct behavior *b;
13624 #endif /* not ANSI_DECLARATORS */
13625 
13626 {
13627   struct badtriang *badtri;
13628   int i;
13629 
13630   if (!b->quiet) {
13631     printf("Adding Steiner points to enforce quality.\n");
13632   }
13633   /* Initialize the pool of encroached subsegments. */
13634   poolinit(&m->badsubsegs, sizeof(struct badsubseg), BADSUBSEGPERBLOCK,
13635            BADSUBSEGPERBLOCK, 0);
13636   if (b->verbose) {
13637     printf("  Looking for encroached subsegments.\n");
13638   }
13639   /* Test all segments to see if they're encroached. */
13640   tallyencs(m, b);
13641   if (b->verbose && (m->badsubsegs.items > 0)) {
13642     printf("  Splitting encroached subsegments.\n");
13643   }
13644   /* Fix encroached subsegments without noting bad triangles. */
13645   splitencsegs(m, b, 0);
13646   /* At this point, if we haven't run out of Steiner points, the */
13647   /*   triangulation should be (conforming) Delaunay.            */
13648 
13649   /* Next, we worry about enforcing triangle quality. */
13650   if ((b->minangle > 0.0) || b->vararea || b->fixedarea || b->usertest) {
13651     /* Initialize the pool of bad triangles. */
13652     poolinit(&m->badtriangles, sizeof(struct badtriang), BADTRIPERBLOCK,
13653              BADTRIPERBLOCK, 0);
13654     /* Initialize the queues of bad triangles. */
13655     for (i = 0; i < 4096; i++) {
13656       m->queuefront[i] = (struct badtriang *) NULL;
13657     }
13658     m->firstnonemptyq = -1;
13659     /* Test all triangles to see if they're bad. */
13660     tallyfaces(m, b);
13661     /* Initialize the pool of recently flipped triangles. */
13662     poolinit(&m->flipstackers, sizeof(struct flipstacker), FLIPSTACKERPERBLOCK,
13663              FLIPSTACKERPERBLOCK, 0);
13664     m->checkquality = 1;
13665     if (b->verbose) {
13666       printf("  Splitting bad triangles.\n");
13667     }
13668     while ((m->badtriangles.items > 0) && (m->steinerleft != 0)) {
13669       /* Fix one bad triangle by inserting a vertex at its circumcenter. */
13670       badtri = dequeuebadtriang(m);
13671       splittriangle(m, b, badtri);
13672       if (m->badsubsegs.items > 0) {
13673         /* Put bad triangle back in queue for another try later. */
13674         enqueuebadtriang(m, b, badtri);
13675         /* Fix any encroached subsegments that resulted. */
13676         /*   Record any new bad triangles that result.   */
13677         splitencsegs(m, b, 1);
13678       } else {
13679         /* Return the bad triangle to the pool. */
13680         pooldealloc(&m->badtriangles, (void *) badtri);
13681       }
13682     }
13683   }
13684   /* At this point, if the "-D" switch was selected and we haven't run out  */
13685   /*   of Steiner points, the triangulation should be (conforming) Delaunay */
13686   /*   and have no low-quality triangles.                                   */
13687 
13688   /* Might we have run out of Steiner points too soon? */
13689   if (!b->quiet && b->conformdel && (m->badsubsegs.items > 0) &&
13690       (m->steinerleft == 0)) {
13691     printf("\nWarning:  I ran out of Steiner points, but the mesh has\n");
13692     if (m->badsubsegs.items == 1) {
13693       printf("  one encroached subsegment, and therefore might not be truly\n"
13694              );
13695     } else {
13696       printf("  %ld encroached subsegments, and therefore might not be truly\n"
13697              , m->badsubsegs.items);
13698     }
13699     printf("  Delaunay.  If the Delaunay property is important to you,\n");
13700     printf("  try increasing the number of Steiner points (controlled by\n");
13701     printf("  the -S switch) slightly and try again.\n\n");
13702   }
13703 }
13704 
13705 #endif /* not CDT_ONLY */
13706 
13707 /**                                                                         **/
13708 /**                                                                         **/
13709 /********* Mesh quality maintenance ends here                        *********/
13710 
13711 /*****************************************************************************/
13712 /*                                                                           */
13713 /*  highorder()   Create extra nodes for quadratic subparametric elements.   */
13714 /*                                                                           */
13715 /*****************************************************************************/
13716 
13717 #ifdef ANSI_DECLARATORS
13718 void highorder(struct mesh *m, struct behavior *b)
13719 #else /* not ANSI_DECLARATORS */
13720 void highorder(m, b)
13721 struct mesh *m;
13722 struct behavior *b;
13723 #endif /* not ANSI_DECLARATORS */
13724 
13725 {
13726   struct otri triangleloop, trisym;
13727   struct osub checkmark;
13728   vertex newvertex;
13729   vertex torg, tdest;
13730   int i;
13731   triangle ptr;                         /* Temporary variable used by sym(). */
13732   subseg sptr;                      /* Temporary variable used by tspivot(). */
13733 
13734   if (!b->quiet) {
13735     printf("Adding vertices for second-order triangles.\n");
13736   }
13737   /* The following line ensures that dead items in the pool of nodes    */
13738   /*   cannot be allocated for the extra nodes associated with high     */
13739   /*   order elements.  This ensures that the primary nodes (at the     */
13740   /*   corners of elements) will occur earlier in the output files, and */
13741   /*   have lower indices, than the extra nodes.                        */
13742   m->vertices.deaditemstack = (void *) NULL;
13743 
13744   traversalinit(&m->triangles);
13745   triangleloop.tri = triangletraverse(m);
13746   /* To loop over the set of edges, loop over all triangles, and look at   */
13747   /*   the three edges of each triangle.  If there isn't another triangle  */
13748   /*   adjacent to the edge, operate on the edge.  If there is another     */
13749   /*   adjacent triangle, operate on the edge only if the current triangle */
13750   /*   has a smaller pointer than its neighbor.  This way, each edge is    */
13751   /*   considered only once.                                               */
13752   while (triangleloop.tri != (triangle *) NULL) {
13753     for (triangleloop.orient = 0; triangleloop.orient < 3;
13754          triangleloop.orient++) {
13755       sym(triangleloop, trisym);
13756       if ((triangleloop.tri < trisym.tri) || (trisym.tri == m->dummytri)) {
13757         org(triangleloop, torg);
13758         dest(triangleloop, tdest);
13759         /* Create a new node in the middle of the edge.  Interpolate */
13760         /*   its attributes.                                         */
13761         newvertex = (vertex) poolalloc(&m->vertices);
13762         for (i = 0; i < 2 + m->nextras; i++) {
13763           newvertex[i] = 0.5 * (torg[i] + tdest[i]);
13764         }
13765         /* Set the new node's marker to zero or one, depending on */
13766         /*   whether it lies on a boundary.                       */
13767         setvertexmark(newvertex, trisym.tri == m->dummytri);
13768         setvertextype(newvertex,
13769                       trisym.tri == m->dummytri ? FREEVERTEX : SEGMENTVERTEX);
13770         if (b->usesegments) {
13771           tspivot(triangleloop, checkmark);
13772           /* If this edge is a segment, transfer the marker to the new node. */
13773           if (checkmark.ss != m->dummysub) {
13774             setvertexmark(newvertex, mark(checkmark));
13775             setvertextype(newvertex, SEGMENTVERTEX);
13776           }
13777         }
13778         if (b->verbose > 1) {
13779           printf("  Creating (%.12g, %.12g).\n", newvertex[0], newvertex[1]);
13780         }
13781         /* Record the new node in the (one or two) adjacent elements. */
13782         triangleloop.tri[m->highorderindex + triangleloop.orient] =
13783                 (triangle) newvertex;
13784         if (trisym.tri != m->dummytri) {
13785           trisym.tri[m->highorderindex + trisym.orient] = (triangle) newvertex;
13786         }
13787       }
13788     }
13789     triangleloop.tri = triangletraverse(m);
13790   }
13791 }
13792 
13793 /********* File I/O routines begin here                              *********/
13794 /**                                                                         **/
13795 /**                                                                         **/
13796 
13797 /*****************************************************************************/
13798 /*                                                                           */
13799 /*  readline()   Read a nonempty line from a file.                           */
13800 /*                                                                           */
13801 /*  A line is considered "nonempty" if it contains something that looks like */
13802 /*  a number.  Comments (prefaced by `#') are ignored.                       */
13803 /*                                                                           */
13804 /*****************************************************************************/
13805 
13806 #ifndef TRILIBRARY
13807 
13808 #ifdef ANSI_DECLARATORS
13809 char *readline(char *string, FILE *infile, char *infilename)
13810 #else /* not ANSI_DECLARATORS */
13811 char *readline(string, infile, infilename)
13812 char *string;
13813 FILE *infile;
13814 char *infilename;
13815 #endif /* not ANSI_DECLARATORS */
13816 
13817 {
13818   char *result;
13819 
13820   /* Search for something that looks like a number. */
13821   do {
13822     result = fgets(string, INPUTLINESIZE, infile);
13823     if (result == (char *) NULL) {
13824       printf("  Error:  Unexpected end of file in %s.\n", infilename);
13825       triexit(1);
13826     }
13827     /* Skip anything that doesn't look like a number, a comment, */
13828     /*   or the end of a line.                                   */
13829     while ((*result != '\0') && (*result != '#')
13830            && (*result != '.') && (*result != '+') && (*result != '-')
13831            && ((*result < '0') || (*result > '9'))) {
13832       result++;
13833     }
13834   /* If it's a comment or end of line, read another line and try again. */
13835   } while ((*result == '#') || (*result == '\0'));
13836   return result;
13837 }
13838 
13839 #endif /* not TRILIBRARY */
13840 
13841 /*****************************************************************************/
13842 /*                                                                           */
13843 /*  findfield()   Find the next field of a string.                           */
13844 /*                                                                           */
13845 /*  Jumps past the current field by searching for whitespace, then jumps     */
13846 /*  past the whitespace to find the next field.                              */
13847 /*                                                                           */
13848 /*****************************************************************************/
13849 
13850 #ifndef TRILIBRARY
13851 
13852 #ifdef ANSI_DECLARATORS
13853 char *findfield(char *string)
13854 #else /* not ANSI_DECLARATORS */
13855 char *findfield(string)
13856 char *string;
13857 #endif /* not ANSI_DECLARATORS */
13858 
13859 {
13860   char *result;
13861 
13862   result = string;
13863   /* Skip the current field.  Stop upon reaching whitespace. */
13864   while ((*result != '\0') && (*result != '#')
13865          && (*result != ' ') && (*result != '\t')) {
13866     result++;
13867   }
13868   /* Now skip the whitespace and anything else that doesn't look like a */
13869   /*   number, a comment, or the end of a line.                         */
13870   while ((*result != '\0') && (*result != '#')
13871          && (*result != '.') && (*result != '+') && (*result != '-')
13872          && ((*result < '0') || (*result > '9'))) {
13873     result++;
13874   }
13875   /* Check for a comment (prefixed with `#'). */
13876   if (*result == '#') {
13877     *result = '\0';
13878   }
13879   return result;
13880 }
13881 
13882 #endif /* not TRILIBRARY */
13883 
13884 /*****************************************************************************/
13885 /*                                                                           */
13886 /*  readnodes()   Read the vertices from a file, which may be a .node or     */
13887 /*                .poly file.                                                */
13888 /*                                                                           */
13889 /*****************************************************************************/
13890 
13891 #ifndef TRILIBRARY
13892 
13893 #ifdef ANSI_DECLARATORS
13894 void readnodes(struct mesh *m, struct behavior *b, char *nodefilename,
13895                char *polyfilename, FILE **polyfile)
13896 #else /* not ANSI_DECLARATORS */
13897 void readnodes(m, b, nodefilename, polyfilename, polyfile)
13898 struct mesh *m;
13899 struct behavior *b;
13900 char *nodefilename;
13901 char *polyfilename;
13902 FILE **polyfile;
13903 #endif /* not ANSI_DECLARATORS */
13904 
13905 {
13906   FILE *infile;
13907   vertex vertexloop;
13908   char inputline[INPUTLINESIZE];
13909   char *stringptr;
13910   char *infilename;
13911   REAL x, y;
13912   int firstnode;
13913   int nodemarkers;
13914   int currentmarker;
13915   int i, j;
13916 
13917   if (b->poly) {
13918     /* Read the vertices from a .poly file. */
13919     if (!b->quiet) {
13920       printf("Opening %s.\n", polyfilename);
13921     }
13922     *polyfile = fopen(polyfilename, "r");
13923     if (*polyfile == (FILE *) NULL) {
13924       printf("  Error:  Cannot access file %s.\n", polyfilename);
13925       triexit(1);
13926     }
13927     /* Read number of vertices, number of dimensions, number of vertex */
13928     /*   attributes, and number of boundary markers.                   */
13929     stringptr = readline(inputline, *polyfile, polyfilename);
13930     m->invertices = (int) strtol(stringptr, &stringptr, 0);
13931     stringptr = findfield(stringptr);
13932     if (*stringptr == '\0') {
13933       m->mesh_dim = 2;
13934     } else {
13935       m->mesh_dim = (int) strtol(stringptr, &stringptr, 0);
13936     }
13937     stringptr = findfield(stringptr);
13938     if (*stringptr == '\0') {
13939       m->nextras = 0;
13940     } else {
13941       m->nextras = (int) strtol(stringptr, &stringptr, 0);
13942     }
13943     stringptr = findfield(stringptr);
13944     if (*stringptr == '\0') {
13945       nodemarkers = 0;
13946     } else {
13947       nodemarkers = (int) strtol(stringptr, &stringptr, 0);
13948     }
13949     if (m->invertices > 0) {
13950       infile = *polyfile;
13951       infilename = polyfilename;
13952       m->readnodefile = 0;
13953     } else {
13954       /* If the .poly file claims there are zero vertices, that means that */
13955       /*   the vertices should be read from a separate .node file.         */
13956       m->readnodefile = 1;
13957       infilename = nodefilename;
13958     }
13959   } else {
13960     m->readnodefile = 1;
13961     infilename = nodefilename;
13962     *polyfile = (FILE *) NULL;
13963   }
13964 
13965   if (m->readnodefile) {
13966     /* Read the vertices from a .node file. */
13967     if (!b->quiet) {
13968       printf("Opening %s.\n", nodefilename);
13969     }
13970     infile = fopen(nodefilename, "r");
13971     if (infile == (FILE *) NULL) {
13972       printf("  Error:  Cannot access file %s.\n", nodefilename);
13973       triexit(1);
13974     }
13975     /* Read number of vertices, number of dimensions, number of vertex */
13976     /*   attributes, and number of boundary markers.                   */
13977     stringptr = readline(inputline, infile, nodefilename);
13978     m->invertices = (int) strtol(stringptr, &stringptr, 0);
13979     stringptr = findfield(stringptr);
13980     if (*stringptr == '\0') {
13981       m->mesh_dim = 2;
13982     } else {
13983       m->mesh_dim = (int) strtol(stringptr, &stringptr, 0);
13984     }
13985     stringptr = findfield(stringptr);
13986     if (*stringptr == '\0') {
13987       m->nextras = 0;
13988     } else {
13989       m->nextras = (int) strtol(stringptr, &stringptr, 0);
13990     }
13991     stringptr = findfield(stringptr);
13992     if (*stringptr == '\0') {
13993       nodemarkers = 0;
13994     } else {
13995       nodemarkers = (int) strtol(stringptr, &stringptr, 0);
13996     }
13997   }
13998 
13999   if (m->invertices < 3) {
14000     printf("Error:  Input must have at least three input vertices.\n");
14001     triexit(1);
14002   }
14003   if (m->mesh_dim != 2) {
14004     printf("Error:  Triangle only works with two-dimensional meshes.\n");
14005     triexit(1);
14006   }
14007   if (m->nextras == 0) {
14008     b->weighted = 0;
14009   }
14010 
14011   initializevertexpool(m, b);
14012 
14013   /* Read the vertices. */
14014   for (i = 0; i < m->invertices; i++) {
14015     vertexloop = (vertex) poolalloc(&m->vertices);
14016     stringptr = readline(inputline, infile, infilename);
14017     if (i == 0) {
14018       firstnode = (int) strtol(stringptr, &stringptr, 0);
14019       if ((firstnode == 0) || (firstnode == 1)) {
14020         b->firstnumber = firstnode;
14021       }
14022     }
14023     stringptr = findfield(stringptr);
14024     if (*stringptr == '\0') {
14025       printf("Error:  Vertex %d has no x coordinate.\n", b->firstnumber + i);
14026       triexit(1);
14027     }
14028     x = (REAL) strtod(stringptr, &stringptr);
14029     stringptr = findfield(stringptr);
14030     if (*stringptr == '\0') {
14031       printf("Error:  Vertex %d has no y coordinate.\n", b->firstnumber + i);
14032       triexit(1);
14033     }
14034     y = (REAL) strtod(stringptr, &stringptr);
14035     vertexloop[0] = x;
14036     vertexloop[1] = y;
14037     /* Read the vertex attributes. */
14038     for (j = 2; j < 2 + m->nextras; j++) {
14039       stringptr = findfield(stringptr);
14040       if (*stringptr == '\0') {
14041         vertexloop[j] = 0.0;
14042       } else {
14043         vertexloop[j] = (REAL) strtod(stringptr, &stringptr);
14044       }
14045     }
14046     if (nodemarkers) {
14047       /* Read a vertex marker. */
14048       stringptr = findfield(stringptr);
14049       if (*stringptr == '\0') {
14050         setvertexmark(vertexloop, 0);
14051       } else {
14052         currentmarker = (int) strtol(stringptr, &stringptr, 0);
14053         setvertexmark(vertexloop, currentmarker);
14054       }
14055     } else {
14056       /* If no markers are specified in the file, they default to zero. */
14057       setvertexmark(vertexloop, 0);
14058     }
14059     setvertextype(vertexloop, INPUTVERTEX);
14060     /* Determine the smallest and largest x and y coordinates. */
14061     if (i == 0) {
14062       m->xmin = m->xmax = x;
14063       m->ymin = m->ymax = y;
14064     } else {
14065       m->xmin = (x < m->xmin) ? x : m->xmin;
14066       m->xmax = (x > m->xmax) ? x : m->xmax;
14067       m->ymin = (y < m->ymin) ? y : m->ymin;
14068       m->ymax = (y > m->ymax) ? y : m->ymax;
14069     }
14070   }
14071   if (m->readnodefile) {
14072     fclose(infile);
14073   }
14074 
14075   /* Nonexistent x value used as a flag to mark circle events in sweepline */
14076   /*   Delaunay algorithm.                                                 */
14077   m->xminextreme = 10 * m->xmin - 9 * m->xmax;
14078 }
14079 
14080 #endif /* not TRILIBRARY */
14081 
14082 /*****************************************************************************/
14083 /*                                                                           */
14084 /*  transfernodes()   Read the vertices from memory.                         */
14085 /*                                                                           */
14086 /*****************************************************************************/
14087 
14088 #ifdef TRILIBRARY
14089 
14090 #ifdef ANSI_DECLARATORS
14091 void transfernodes(struct mesh *m, struct behavior *b, REAL *pointlist,
14092                    REAL *pointattriblist, int *pointmarkerlist,
14093                    int numberofpoints, int numberofpointattribs)
14094 #else /* not ANSI_DECLARATORS */
14095 void transfernodes(m, b, pointlist, pointattriblist, pointmarkerlist,
14096                    numberofpoints, numberofpointattribs)
14097 struct mesh *m;
14098 struct behavior *b;
14099 REAL *pointlist;
14100 REAL *pointattriblist;
14101 int *pointmarkerlist;
14102 int numberofpoints;
14103 int numberofpointattribs;
14104 #endif /* not ANSI_DECLARATORS */
14105 
14106 {
14107   vertex vertexloop;
14108   REAL x, y;
14109   int i, j;
14110   int coordindex;
14111   int attribindex;
14112 
14113   m->invertices = numberofpoints;
14114   m->mesh_dim = 2;
14115   m->nextras = numberofpointattribs;
14116   m->readnodefile = 0;
14117   if (m->invertices < 3) {
14118     printf("Error:  Input must have at least three input vertices.\n");
14119     triexit(1);
14120   }
14121   if (m->nextras == 0) {
14122     b->weighted = 0;
14123   }
14124 
14125   initializevertexpool(m, b);
14126 
14127   /* Read the vertices. */
14128   coordindex = 0;
14129   attribindex = 0;
14130   for (i = 0; i < m->invertices; i++) {
14131     vertexloop = (vertex) poolalloc(&m->vertices);
14132     /* Read the vertex coordinates. */
14133     x = vertexloop[0] = pointlist[coordindex++];
14134     y = vertexloop[1] = pointlist[coordindex++];
14135     /* Read the vertex attributes. */
14136     for (j = 0; j < numberofpointattribs; j++) {
14137       vertexloop[2 + j] = pointattriblist[attribindex++];
14138     }
14139     if (pointmarkerlist != (int *) NULL) {
14140       /* Read a vertex marker. */
14141       setvertexmark(vertexloop, pointmarkerlist[i]);
14142     } else {
14143       /* If no markers are specified, they default to zero. */
14144       setvertexmark(vertexloop, 0);
14145     }
14146     setvertextype(vertexloop, INPUTVERTEX);
14147     /* Determine the smallest and largest x and y coordinates. */
14148     if (i == 0) {
14149       m->xmin = m->xmax = x;
14150       m->ymin = m->ymax = y;
14151     } else {
14152       m->xmin = (x < m->xmin) ? x : m->xmin;
14153       m->xmax = (x > m->xmax) ? x : m->xmax;
14154       m->ymin = (y < m->ymin) ? y : m->ymin;
14155       m->ymax = (y > m->ymax) ? y : m->ymax;
14156     }
14157   }
14158 
14159   /* Nonexistent x value used as a flag to mark circle events in sweepline */
14160   /*   Delaunay algorithm.                                                 */
14161   m->xminextreme = 10 * m->xmin - 9 * m->xmax;
14162 }
14163 
14164 #endif /* TRILIBRARY */
14165 
14166 /*****************************************************************************/
14167 /*                                                                           */
14168 /*  readholes()   Read the holes, and possibly regional attributes and area  */
14169 /*                constraints, from a .poly file.                            */
14170 /*                                                                           */
14171 /*****************************************************************************/
14172 
14173 #ifndef TRILIBRARY
14174 
14175 #ifdef ANSI_DECLARATORS
14176 void readholes(struct mesh *m, struct behavior *b,
14177                FILE *polyfile, char *polyfilename, REAL **hlist, int *holes,
14178                REAL **rlist, int *regions)
14179 #else /* not ANSI_DECLARATORS */
14180 void readholes(m, b, polyfile, polyfilename, hlist, holes, rlist, regions)
14181 struct mesh *m;
14182 struct behavior *b;
14183 FILE *polyfile;
14184 char *polyfilename;
14185 REAL **hlist;
14186 int *holes;
14187 REAL **rlist;
14188 int *regions;
14189 #endif /* not ANSI_DECLARATORS */
14190 
14191 {
14192   REAL *holelist;
14193   REAL *regionlist;
14194   char inputline[INPUTLINESIZE];
14195   char *stringptr;
14196   int index;
14197   int i;
14198 
14199   /* Read the holes. */
14200   stringptr = readline(inputline, polyfile, polyfilename);
14201   *holes = (int) strtol(stringptr, &stringptr, 0);
14202   if (*holes > 0) {
14203     holelist = (REAL *) trimalloc(2 * *holes * (int) sizeof(REAL));
14204     *hlist = holelist;
14205     for (i = 0; i < 2 * *holes; i += 2) {
14206       stringptr = readline(inputline, polyfile, polyfilename);
14207       stringptr = findfield(stringptr);
14208       if (*stringptr == '\0') {
14209         printf("Error:  Hole %d has no x coordinate.\n",
14210                b->firstnumber + (i >> 1));
14211         triexit(1);
14212       } else {
14213         holelist[i] = (REAL) strtod(stringptr, &stringptr);
14214       }
14215       stringptr = findfield(stringptr);
14216       if (*stringptr == '\0') {
14217         printf("Error:  Hole %d has no y coordinate.\n",
14218                b->firstnumber + (i >> 1));
14219         triexit(1);
14220       } else {
14221         holelist[i + 1] = (REAL) strtod(stringptr, &stringptr);
14222       }
14223     }
14224   } else {
14225     *hlist = (REAL *) NULL;
14226   }
14227 
14228 #ifndef CDT_ONLY
14229   if ((b->regionattrib || b->vararea) && !b->refine) {
14230     /* Read the area constraints. */
14231     stringptr = readline(inputline, polyfile, polyfilename);
14232     *regions = (int) strtol(stringptr, &stringptr, 0);
14233     if (*regions > 0) {
14234       regionlist = (REAL *) trimalloc(4 * *regions * (int) sizeof(REAL));
14235       *rlist = regionlist;
14236       index = 0;
14237       for (i = 0; i < *regions; i++) {
14238         stringptr = readline(inputline, polyfile, polyfilename);
14239         stringptr = findfield(stringptr);
14240         if (*stringptr == '\0') {
14241           printf("Error:  Region %d has no x coordinate.\n",
14242                  b->firstnumber + i);
14243           triexit(1);
14244         } else {
14245           regionlist[index++] = (REAL) strtod(stringptr, &stringptr);
14246         }
14247         stringptr = findfield(stringptr);
14248         if (*stringptr == '\0') {
14249           printf("Error:  Region %d has no y coordinate.\n",
14250                  b->firstnumber + i);
14251           triexit(1);
14252         } else {
14253           regionlist[index++] = (REAL) strtod(stringptr, &stringptr);
14254         }
14255         stringptr = findfield(stringptr);
14256         if (*stringptr == '\0') {
14257           printf(
14258             "Error:  Region %d has no region attribute or area constraint.\n",
14259                  b->firstnumber + i);
14260           triexit(1);
14261         } else {
14262           regionlist[index++] = (REAL) strtod(stringptr, &stringptr);
14263         }
14264         stringptr = findfield(stringptr);
14265         if (*stringptr == '\0') {
14266           regionlist[index] = regionlist[index - 1];
14267         } else {
14268           regionlist[index] = (REAL) strtod(stringptr, &stringptr);
14269         }
14270         index++;
14271       }
14272     }
14273   } else {
14274     /* Set `*regions' to zero to avoid an accidental free() later. */
14275     *regions = 0;
14276     *rlist = (REAL *) NULL;
14277   }
14278 #endif /* not CDT_ONLY */
14279 
14280   fclose(polyfile);
14281 }
14282 
14283 #endif /* not TRILIBRARY */
14284 
14285 /*****************************************************************************/
14286 /*                                                                           */
14287 /*  finishfile()   Write the command line to the output file so the user     */
14288 /*                 can remember how the file was generated.  Close the file. */
14289 /*                                                                           */
14290 /*****************************************************************************/
14291 
14292 #ifndef TRILIBRARY
14293 
14294 #ifdef ANSI_DECLARATORS
14295 void finishfile(FILE *outfile, int argc, char **argv)
14296 #else /* not ANSI_DECLARATORS */
14297 void finishfile(outfile, argc, argv)
14298 FILE *outfile;
14299 int argc;
14300 char **argv;
14301 #endif /* not ANSI_DECLARATORS */
14302 
14303 {
14304   int i;
14305 
14306   fprintf(outfile, "# Generated by");
14307   for (i = 0; i < argc; i++) {
14308     fprintf(outfile, " ");
14309     fputs(argv[i], outfile);
14310   }
14311   fprintf(outfile, "\n");
14312   fclose(outfile);
14313 }
14314 
14315 #endif /* not TRILIBRARY */
14316 
14317 /*****************************************************************************/
14318 /*                                                                           */
14319 /*  writenodes()   Number the vertices and write them to a .node file.       */
14320 /*                                                                           */
14321 /*  To save memory, the vertex numbers are written over the boundary markers */
14322 /*  after the vertices are written to a file.                                */
14323 /*                                                                           */
14324 /*****************************************************************************/
14325 
14326 #ifdef TRILIBRARY
14327 
14328 #ifdef ANSI_DECLARATORS
14329 void writenodes(struct mesh *m, struct behavior *b, REAL **pointlist,
14330                 REAL **pointattriblist, int **pointmarkerlist)
14331 #else /* not ANSI_DECLARATORS */
14332 void writenodes(m, b, pointlist, pointattriblist, pointmarkerlist)
14333 struct mesh *m;
14334 struct behavior *b;
14335 REAL **pointlist;
14336 REAL **pointattriblist;
14337 int **pointmarkerlist;
14338 #endif /* not ANSI_DECLARATORS */
14339 
14340 #else /* not TRILIBRARY */
14341 
14342 #ifdef ANSI_DECLARATORS
14343 void writenodes(struct mesh *m, struct behavior *b, char *nodefilename,
14344                 int argc, char **argv)
14345 #else /* not ANSI_DECLARATORS */
14346 void writenodes(m, b, nodefilename, argc, argv)
14347 struct mesh *m;
14348 struct behavior *b;
14349 char *nodefilename;
14350 int argc;
14351 char **argv;
14352 #endif /* not ANSI_DECLARATORS */
14353 
14354 #endif /* not TRILIBRARY */
14355 
14356 {
14357 #ifdef TRILIBRARY
14358   REAL *plist;
14359   REAL *palist;
14360   int *pmlist;
14361   int coordindex;
14362   int attribindex;
14363 #else /* not TRILIBRARY */
14364   FILE *outfile;
14365 #endif /* not TRILIBRARY */
14366   vertex vertexloop;
14367   long outvertices;
14368   int vertexnumber;
14369   int i;
14370 
14371   if (b->jettison) {
14372     outvertices = m->vertices.items - m->undeads;
14373   } else {
14374     outvertices = m->vertices.items;
14375   }
14376 
14377 #ifdef TRILIBRARY
14378   if (!b->quiet) {
14379     printf("Writing vertices.\n");
14380   }
14381   /* Allocate memory for output vertices if necessary. */
14382   if (*pointlist == (REAL *) NULL) {
14383     *pointlist = (REAL *) trimalloc((int) (outvertices * 2 * sizeof(REAL)));
14384   }
14385   /* Allocate memory for output vertex attributes if necessary. */
14386   if ((m->nextras > 0) && (*pointattriblist == (REAL *) NULL)) {
14387     *pointattriblist = (REAL *) trimalloc((int) (outvertices * m->nextras *
14388                                                  sizeof(REAL)));
14389   }
14390   /* Allocate memory for output vertex markers if necessary. */
14391   if (!b->nobound && (*pointmarkerlist == (int *) NULL)) {
14392     *pointmarkerlist = (int *) trimalloc((int) (outvertices * sizeof(int)));
14393   }
14394   plist = *pointlist;
14395   palist = *pointattriblist;
14396   pmlist = *pointmarkerlist;
14397   coordindex = 0;
14398   attribindex = 0;
14399 #else /* not TRILIBRARY */
14400   if (!b->quiet) {
14401     printf("Writing %s.\n", nodefilename);
14402   }
14403   outfile = fopen(nodefilename, "w");
14404   if (outfile == (FILE *) NULL) {
14405     printf("  Error:  Cannot create file %s.\n", nodefilename);
14406     triexit(1);
14407   }
14408   /* Number of vertices, number of dimensions, number of vertex attributes, */
14409   /*   and number of boundary markers (zero or one).                        */
14410   fprintf(outfile, "%ld  %d  %d  %d\n", outvertices, m->mesh_dim,
14411           m->nextras, 1 - b->nobound);
14412 #endif /* not TRILIBRARY */
14413 
14414   traversalinit(&m->vertices);
14415   vertexnumber = b->firstnumber;
14416   vertexloop = vertextraverse(m);
14417   while (vertexloop != (vertex) NULL) {
14418     if (!b->jettison || (vertextype(vertexloop) != UNDEADVERTEX)) {
14419 #ifdef TRILIBRARY
14420       /* X and y coordinates. */
14421       plist[coordindex++] = vertexloop[0];
14422       plist[coordindex++] = vertexloop[1];
14423       /* Vertex attributes. */
14424       for (i = 0; i < m->nextras; i++) {
14425         palist[attribindex++] = vertexloop[2 + i];
14426       }
14427       if (!b->nobound) {
14428         /* Copy the boundary marker. */
14429         pmlist[vertexnumber - b->firstnumber] = vertexmark(vertexloop);
14430       }
14431 #else /* not TRILIBRARY */
14432       /* Vertex number, x and y coordinates. */
14433       fprintf(outfile, "%4d    %.17g  %.17g", vertexnumber, vertexloop[0],
14434               vertexloop[1]);
14435       for (i = 0; i < m->nextras; i++) {
14436         /* Write an attribute. */
14437         fprintf(outfile, "  %.17g", vertexloop[i + 2]);
14438       }
14439       if (b->nobound) {
14440         fprintf(outfile, "\n");
14441       } else {
14442         /* Write the boundary marker. */
14443         fprintf(outfile, "    %d\n", vertexmark(vertexloop));
14444       }
14445 #endif /* not TRILIBRARY */
14446 
14447       setvertexmark(vertexloop, vertexnumber);
14448       vertexnumber++;
14449     }
14450     vertexloop = vertextraverse(m);
14451   }
14452 
14453 #ifndef TRILIBRARY
14454   finishfile(outfile, argc, argv);
14455 #endif /* not TRILIBRARY */
14456 }
14457 
14458 /*****************************************************************************/
14459 /*                                                                           */
14460 /*  numbernodes()   Number the vertices.                                     */
14461 /*                                                                           */
14462 /*  Each vertex is assigned a marker equal to its number.                    */
14463 /*                                                                           */
14464 /*  Used when writenodes() is not called because no .node file is written.   */
14465 /*                                                                           */
14466 /*****************************************************************************/
14467 
14468 #ifdef ANSI_DECLARATORS
14469 void numbernodes(struct mesh *m, struct behavior *b)
14470 #else /* not ANSI_DECLARATORS */
14471 void numbernodes(m, b)
14472 struct mesh *m;
14473 struct behavior *b;
14474 #endif /* not ANSI_DECLARATORS */
14475 
14476 {
14477   vertex vertexloop;
14478   int vertexnumber;
14479 
14480   traversalinit(&m->vertices);
14481   vertexnumber = b->firstnumber;
14482   vertexloop = vertextraverse(m);
14483   while (vertexloop != (vertex) NULL) {
14484     setvertexmark(vertexloop, vertexnumber);
14485     if (!b->jettison || (vertextype(vertexloop) != UNDEADVERTEX)) {
14486       vertexnumber++;
14487     }
14488     vertexloop = vertextraverse(m);
14489   }
14490 }
14491 
14492 /*****************************************************************************/
14493 /*                                                                           */
14494 /*  writeelements()   Write the triangles to an .ele file.                   */
14495 /*                                                                           */
14496 /*****************************************************************************/
14497 
14498 #ifdef TRILIBRARY
14499 
14500 #ifdef ANSI_DECLARATORS
14501 void writeelements(struct mesh *m, struct behavior *b,
14502                    int **trianglelist, REAL **triangleattriblist)
14503 #else /* not ANSI_DECLARATORS */
14504 void writeelements(m, b, trianglelist, triangleattriblist)
14505 struct mesh *m;
14506 struct behavior *b;
14507 int **trianglelist;
14508 REAL **triangleattriblist;
14509 #endif /* not ANSI_DECLARATORS */
14510 
14511 #else /* not TRILIBRARY */
14512 
14513 #ifdef ANSI_DECLARATORS
14514 void writeelements(struct mesh *m, struct behavior *b, char *elefilename,
14515                    int argc, char **argv)
14516 #else /* not ANSI_DECLARATORS */
14517 void writeelements(m, b, elefilename, argc, argv)
14518 struct mesh *m;
14519 struct behavior *b;
14520 char *elefilename;
14521 int argc;
14522 char **argv;
14523 #endif /* not ANSI_DECLARATORS */
14524 
14525 #endif /* not TRILIBRARY */
14526 
14527 {
14528 #ifdef TRILIBRARY
14529   int *tlist;
14530   REAL *talist;
14531   int vertexindex;
14532   int attribindex;
14533 #else /* not TRILIBRARY */
14534   FILE *outfile;
14535 #endif /* not TRILIBRARY */
14536   struct otri triangleloop;
14537   vertex p1, p2, p3;
14538   vertex mid1, mid2, mid3;
14539   long elementnumber;
14540   int i;
14541 
14542 #ifdef TRILIBRARY
14543   if (!b->quiet) {
14544     printf("Writing triangles.\n");
14545   }
14546   /* Allocate memory for output triangles if necessary. */
14547   if (*trianglelist == (int *) NULL) {
14548     *trianglelist = (int *) trimalloc((int) (m->triangles.items *
14549                                              ((b->order + 1) * (b->order + 2) /
14550                                               2) * sizeof(int)));
14551   }
14552   /* Allocate memory for output triangle attributes if necessary. */
14553   if ((m->eextras > 0) && (*triangleattriblist == (REAL *) NULL)) {
14554     *triangleattriblist = (REAL *) trimalloc((int) (m->triangles.items *
14555                                                     m->eextras *
14556                                                     sizeof(REAL)));
14557   }
14558   tlist = *trianglelist;
14559   talist = *triangleattriblist;
14560   vertexindex = 0;
14561   attribindex = 0;
14562 #else /* not TRILIBRARY */
14563   if (!b->quiet) {
14564     printf("Writing %s.\n", elefilename);
14565   }
14566   outfile = fopen(elefilename, "w");
14567   if (outfile == (FILE *) NULL) {
14568     printf("  Error:  Cannot create file %s.\n", elefilename);
14569     triexit(1);
14570   }
14571   /* Number of triangles, vertices per triangle, attributes per triangle. */
14572   fprintf(outfile, "%ld  %d  %d\n", m->triangles.items,
14573           (b->order + 1) * (b->order + 2) / 2, m->eextras);
14574 #endif /* not TRILIBRARY */
14575 
14576   traversalinit(&m->triangles);
14577   triangleloop.tri = triangletraverse(m);
14578   triangleloop.orient = 0;
14579   elementnumber = b->firstnumber;
14580   while (triangleloop.tri != (triangle *) NULL) {
14581     org(triangleloop, p1);
14582     dest(triangleloop, p2);
14583     apex(triangleloop, p3);
14584     if (b->order == 1) {
14585 #ifdef TRILIBRARY
14586       tlist[vertexindex++] = vertexmark(p1);
14587       tlist[vertexindex++] = vertexmark(p2);
14588       tlist[vertexindex++] = vertexmark(p3);
14589 #else /* not TRILIBRARY */
14590       /* Triangle number, indices for three vertices. */
14591       fprintf(outfile, "%4ld    %4d  %4d  %4d", elementnumber,
14592               vertexmark(p1), vertexmark(p2), vertexmark(p3));
14593 #endif /* not TRILIBRARY */
14594     } else {
14595       mid1 = (vertex) triangleloop.tri[m->highorderindex + 1];
14596       mid2 = (vertex) triangleloop.tri[m->highorderindex + 2];
14597       mid3 = (vertex) triangleloop.tri[m->highorderindex];
14598 #ifdef TRILIBRARY
14599       tlist[vertexindex++] = vertexmark(p1);
14600       tlist[vertexindex++] = vertexmark(p2);
14601       tlist[vertexindex++] = vertexmark(p3);
14602       tlist[vertexindex++] = vertexmark(mid1);
14603       tlist[vertexindex++] = vertexmark(mid2);
14604       tlist[vertexindex++] = vertexmark(mid3);
14605 #else /* not TRILIBRARY */
14606       /* Triangle number, indices for six vertices. */
14607       fprintf(outfile, "%4ld    %4d  %4d  %4d  %4d  %4d  %4d", elementnumber,
14608               vertexmark(p1), vertexmark(p2), vertexmark(p3), vertexmark(mid1),
14609               vertexmark(mid2), vertexmark(mid3));
14610 #endif /* not TRILIBRARY */
14611     }
14612 
14613 #ifdef TRILIBRARY
14614     for (i = 0; i < m->eextras; i++) {
14615       talist[attribindex++] = elemattribute(triangleloop, i);
14616     }
14617 #else /* not TRILIBRARY */
14618     for (i = 0; i < m->eextras; i++) {
14619       fprintf(outfile, "  %.17g", elemattribute(triangleloop, i));
14620     }
14621     fprintf(outfile, "\n");
14622 #endif /* not TRILIBRARY */
14623 
14624     triangleloop.tri = triangletraverse(m);
14625     elementnumber++;
14626   }
14627 
14628 #ifndef TRILIBRARY
14629   finishfile(outfile, argc, argv);
14630 #endif /* not TRILIBRARY */
14631 }
14632 
14633 /*****************************************************************************/
14634 /*                                                                           */
14635 /*  writepoly()   Write the segments and holes to a .poly file.              */
14636 /*                                                                           */
14637 /*****************************************************************************/
14638 
14639 #ifdef TRILIBRARY
14640 
14641 #ifdef ANSI_DECLARATORS
14642 void writepoly(struct mesh *m, struct behavior *b,
14643                int **segmentlist, int **segmentmarkerlist)
14644 #else /* not ANSI_DECLARATORS */
14645 void writepoly(m, b, segmentlist, segmentmarkerlist)
14646 struct mesh *m;
14647 struct behavior *b;
14648 int **segmentlist;
14649 int **segmentmarkerlist;
14650 #endif /* not ANSI_DECLARATORS */
14651 
14652 #else /* not TRILIBRARY */
14653 
14654 #ifdef ANSI_DECLARATORS
14655 void writepoly(struct mesh *m, struct behavior *b, char *polyfilename,
14656                REAL *holelist, int holes, REAL *regionlist, int regions,
14657                int argc, char **argv)
14658 #else /* not ANSI_DECLARATORS */
14659 void writepoly(m, b, polyfilename, holelist, holes, regionlist, regions,
14660                argc, argv)
14661 struct mesh *m;
14662 struct behavior *b;
14663 char *polyfilename;
14664 REAL *holelist;
14665 int holes;
14666 REAL *regionlist;
14667 int regions;
14668 int argc;
14669 char **argv;
14670 #endif /* not ANSI_DECLARATORS */
14671 
14672 #endif /* not TRILIBRARY */
14673 
14674 {
14675 #ifdef TRILIBRARY
14676   int *slist;
14677   int *smlist;
14678   int index;
14679 #else /* not TRILIBRARY */
14680   FILE *outfile;
14681   long holenumber, regionnumber;
14682 #endif /* not TRILIBRARY */
14683   struct osub subsegloop;
14684   vertex endpoint1, endpoint2;
14685   long subsegnumber;
14686 
14687 #ifdef TRILIBRARY
14688   if (!b->quiet) {
14689     printf("Writing segments.\n");
14690   }
14691   /* Allocate memory for output segments if necessary. */
14692   if (*segmentlist == (int *) NULL) {
14693     *segmentlist = (int *) trimalloc((int) (m->subsegs.items * 2 *
14694                                             sizeof(int)));
14695   }
14696   /* Allocate memory for output segment markers if necessary. */
14697   if (!b->nobound && (*segmentmarkerlist == (int *) NULL)) {
14698     *segmentmarkerlist = (int *) trimalloc((int) (m->subsegs.items *
14699                                                   sizeof(int)));
14700   }
14701   slist = *segmentlist;
14702   smlist = *segmentmarkerlist;
14703   index = 0;
14704 #else /* not TRILIBRARY */
14705   if (!b->quiet) {
14706     printf("Writing %s.\n", polyfilename);
14707   }
14708   outfile = fopen(polyfilename, "w");
14709   if (outfile == (FILE *) NULL) {
14710     printf("  Error:  Cannot create file %s.\n", polyfilename);
14711     triexit(1);
14712   }
14713   /* The zero indicates that the vertices are in a separate .node file. */
14714   /*   Followed by number of dimensions, number of vertex attributes,   */
14715   /*   and number of boundary markers (zero or one).                    */
14716   fprintf(outfile, "%d  %d  %d  %d\n", 0, m->mesh_dim, m->nextras,
14717           1 - b->nobound);
14718   /* Number of segments, number of boundary markers (zero or one). */
14719   fprintf(outfile, "%ld  %d\n", m->subsegs.items, 1 - b->nobound);
14720 #endif /* not TRILIBRARY */
14721 
14722   traversalinit(&m->subsegs);
14723   subsegloop.ss = subsegtraverse(m);
14724   subsegloop.ssorient = 0;
14725   subsegnumber = b->firstnumber;
14726   while (subsegloop.ss != (subseg *) NULL) {
14727     sorg(subsegloop, endpoint1);
14728     sdest(subsegloop, endpoint2);
14729 #ifdef TRILIBRARY
14730     /* Copy indices of the segment's two endpoints. */
14731     slist[index++] = vertexmark(endpoint1);
14732     slist[index++] = vertexmark(endpoint2);
14733     if (!b->nobound) {
14734       /* Copy the boundary marker. */
14735       smlist[subsegnumber - b->firstnumber] = mark(subsegloop);
14736     }
14737 #else /* not TRILIBRARY */
14738     /* Segment number, indices of its two endpoints, and possibly a marker. */
14739     if (b->nobound) {
14740       fprintf(outfile, "%4ld    %4d  %4d\n", subsegnumber,
14741               vertexmark(endpoint1), vertexmark(endpoint2));
14742     } else {
14743       fprintf(outfile, "%4ld    %4d  %4d    %4d\n", subsegnumber,
14744               vertexmark(endpoint1), vertexmark(endpoint2), mark(subsegloop));
14745     }
14746 #endif /* not TRILIBRARY */
14747 
14748     subsegloop.ss = subsegtraverse(m);
14749     subsegnumber++;
14750   }
14751 
14752 #ifndef TRILIBRARY
14753 #ifndef CDT_ONLY
14754   fprintf(outfile, "%d\n", holes);
14755   if (holes > 0) {
14756     for (holenumber = 0; holenumber < holes; holenumber++) {
14757       /* Hole number, x and y coordinates. */
14758       fprintf(outfile, "%4ld   %.17g  %.17g\n", b->firstnumber + holenumber,
14759               holelist[2 * holenumber], holelist[2 * holenumber + 1]);
14760     }
14761   }
14762   if (regions > 0) {
14763     fprintf(outfile, "%d\n", regions);
14764     for (regionnumber = 0; regionnumber < regions; regionnumber++) {
14765       /* Region number, x and y coordinates, attribute, maximum area. */
14766       fprintf(outfile, "%4ld   %.17g  %.17g  %.17g  %.17g\n",
14767               b->firstnumber + regionnumber,
14768               regionlist[4 * regionnumber], regionlist[4 * regionnumber + 1],
14769               regionlist[4 * regionnumber + 2],
14770               regionlist[4 * regionnumber + 3]);
14771     }
14772   }
14773 #endif /* not CDT_ONLY */
14774 
14775   finishfile(outfile, argc, argv);
14776 #endif /* not TRILIBRARY */
14777 }
14778 
14779 /*****************************************************************************/
14780 /*                                                                           */
14781 /*  writeedges()   Write the edges to an .edge file.                         */
14782 /*                                                                           */
14783 /*****************************************************************************/
14784 
14785 #ifdef TRILIBRARY
14786 
14787 #ifdef ANSI_DECLARATORS
14788 void writeedges(struct mesh *m, struct behavior *b,
14789                 int **edgelist, int **edgemarkerlist)
14790 #else /* not ANSI_DECLARATORS */
14791 void writeedges(m, b, edgelist, edgemarkerlist)
14792 struct mesh *m;
14793 struct behavior *b;
14794 int **edgelist;
14795 int **edgemarkerlist;
14796 #endif /* not ANSI_DECLARATORS */
14797 
14798 #else /* not TRILIBRARY */
14799 
14800 #ifdef ANSI_DECLARATORS
14801 void writeedges(struct mesh *m, struct behavior *b, char *edgefilename,
14802                 int argc, char **argv)
14803 #else /* not ANSI_DECLARATORS */
14804 void writeedges(m, b, edgefilename, argc, argv)
14805 struct mesh *m;
14806 struct behavior *b;
14807 char *edgefilename;
14808 int argc;
14809 char **argv;
14810 #endif /* not ANSI_DECLARATORS */
14811 
14812 #endif /* not TRILIBRARY */
14813 
14814 {
14815 #ifdef TRILIBRARY
14816   int *elist;
14817   int *emlist;
14818   int index;
14819 #else /* not TRILIBRARY */
14820   FILE *outfile;
14821 #endif /* not TRILIBRARY */
14822   struct otri triangleloop, trisym;
14823   struct osub checkmark;
14824   vertex p1, p2;
14825   long edgenumber;
14826   triangle ptr;                         /* Temporary variable used by sym(). */
14827   subseg sptr;                      /* Temporary variable used by tspivot(). */
14828 
14829 #ifdef TRILIBRARY
14830   if (!b->quiet) {
14831     printf("Writing edges.\n");
14832   }
14833   /* Allocate memory for edges if necessary. */
14834   if (*edgelist == (int *) NULL) {
14835     *edgelist = (int *) trimalloc((int) (m->edges * 2 * sizeof(int)));
14836   }
14837   /* Allocate memory for edge markers if necessary. */
14838   if (!b->nobound && (*edgemarkerlist == (int *) NULL)) {
14839     *edgemarkerlist = (int *) trimalloc((int) (m->edges * sizeof(int)));
14840   }
14841   elist = *edgelist;
14842   emlist = *edgemarkerlist;
14843   index = 0;
14844 #else /* not TRILIBRARY */
14845   if (!b->quiet) {
14846     printf("Writing %s.\n", edgefilename);
14847   }
14848   outfile = fopen(edgefilename, "w");
14849   if (outfile == (FILE *) NULL) {
14850     printf("  Error:  Cannot create file %s.\n", edgefilename);
14851     triexit(1);
14852   }
14853   /* Number of edges, number of boundary markers (zero or one). */
14854   fprintf(outfile, "%ld  %d\n", m->edges, 1 - b->nobound);
14855 #endif /* not TRILIBRARY */
14856 
14857   traversalinit(&m->triangles);
14858   triangleloop.tri = triangletraverse(m);
14859   edgenumber = b->firstnumber;
14860   /* To loop over the set of edges, loop over all triangles, and look at   */
14861   /*   the three edges of each triangle.  If there isn't another triangle  */
14862   /*   adjacent to the edge, operate on the edge.  If there is another     */
14863   /*   adjacent triangle, operate on the edge only if the current triangle */
14864   /*   has a smaller pointer than its neighbor.  This way, each edge is    */
14865   /*   considered only once.                                               */
14866   while (triangleloop.tri != (triangle *) NULL) {
14867     for (triangleloop.orient = 0; triangleloop.orient < 3;
14868          triangleloop.orient++) {
14869       sym(triangleloop, trisym);
14870       if ((triangleloop.tri < trisym.tri) || (trisym.tri == m->dummytri)) {
14871         org(triangleloop, p1);
14872         dest(triangleloop, p2);
14873 #ifdef TRILIBRARY
14874         elist[index++] = vertexmark(p1);
14875         elist[index++] = vertexmark(p2);
14876 #endif /* TRILIBRARY */
14877         if (b->nobound) {
14878 #ifndef TRILIBRARY
14879           /* Edge number, indices of two endpoints. */
14880           fprintf(outfile, "%4ld   %d  %d\n", edgenumber,
14881                   vertexmark(p1), vertexmark(p2));
14882 #endif /* not TRILIBRARY */
14883         } else {
14884           /* Edge number, indices of two endpoints, and a boundary marker. */
14885           /*   If there's no subsegment, the boundary marker is zero.      */
14886           if (b->usesegments) {
14887             tspivot(triangleloop, checkmark);
14888             if (checkmark.ss == m->dummysub) {
14889 #ifdef TRILIBRARY
14890               emlist[edgenumber - b->firstnumber] = 0;
14891 #else /* not TRILIBRARY */
14892               fprintf(outfile, "%4ld   %d  %d  %d\n", edgenumber,
14893                       vertexmark(p1), vertexmark(p2), 0);
14894 #endif /* not TRILIBRARY */
14895             } else {
14896 #ifdef TRILIBRARY
14897               emlist[edgenumber - b->firstnumber] = mark(checkmark);
14898 #else /* not TRILIBRARY */
14899               fprintf(outfile, "%4ld   %d  %d  %d\n", edgenumber,
14900                       vertexmark(p1), vertexmark(p2), mark(checkmark));
14901 #endif /* not TRILIBRARY */
14902             }
14903           } else {
14904 #ifdef TRILIBRARY
14905             emlist[edgenumber - b->firstnumber] = trisym.tri == m->dummytri;
14906 #else /* not TRILIBRARY */
14907             fprintf(outfile, "%4ld   %d  %d  %d\n", edgenumber,
14908                     vertexmark(p1), vertexmark(p2), trisym.tri == m->dummytri);
14909 #endif /* not TRILIBRARY */
14910           }
14911         }
14912         edgenumber++;
14913       }
14914     }
14915     triangleloop.tri = triangletraverse(m);
14916   }
14917 
14918 #ifndef TRILIBRARY
14919   finishfile(outfile, argc, argv);
14920 #endif /* not TRILIBRARY */
14921 }
14922 
14923 /*****************************************************************************/
14924 /*                                                                           */
14925 /*  writevoronoi()   Write the Voronoi diagram to a .v.node and .v.edge      */
14926 /*                   file.                                                   */
14927 /*                                                                           */
14928 /*  The Voronoi diagram is the geometric dual of the Delaunay triangulation. */
14929 /*  Hence, the Voronoi vertices are listed by traversing the Delaunay        */
14930 /*  triangles, and the Voronoi edges are listed by traversing the Delaunay   */
14931 /*  edges.                                                                   */
14932 /*                                                                           */
14933 /*  WARNING:  In order to assign numbers to the Voronoi vertices, this       */
14934 /*  procedure messes up the subsegments or the extra nodes of every          */
14935 /*  element.  Hence, you should call this procedure last.                    */
14936 /*                                                                           */
14937 /*****************************************************************************/
14938 
14939 #ifdef TRILIBRARY
14940 
14941 #ifdef ANSI_DECLARATORS
14942 void writevoronoi(struct mesh *m, struct behavior *b, REAL **vpointlist,
14943                   REAL **vpointattriblist, int **vpointmarkerlist,
14944                   int **vedgelist, int **vedgemarkerlist, REAL **vnormlist)
14945 #else /* not ANSI_DECLARATORS */
14946 void writevoronoi(m, b, vpointlist, vpointattriblist, vpointmarkerlist,
14947                   vedgelist, vedgemarkerlist, vnormlist)
14948 struct mesh *m;
14949 struct behavior *b;
14950 REAL **vpointlist;
14951 REAL **vpointattriblist;
14952 int **vpointmarkerlist;
14953 int **vedgelist;
14954 int **vedgemarkerlist;
14955 REAL **vnormlist;
14956 #endif /* not ANSI_DECLARATORS */
14957 
14958 #else /* not TRILIBRARY */
14959 
14960 #ifdef ANSI_DECLARATORS
14961 void writevoronoi(struct mesh *m, struct behavior *b, char *vnodefilename,
14962                   char *vedgefilename, int argc, char **argv)
14963 #else /* not ANSI_DECLARATORS */
14964 void writevoronoi(m, b, vnodefilename, vedgefilename, argc, argv)
14965 struct mesh *m;
14966 struct behavior *b;
14967 char *vnodefilename;
14968 char *vedgefilename;
14969 int argc;
14970 char **argv;
14971 #endif /* not ANSI_DECLARATORS */
14972 
14973 #endif /* not TRILIBRARY */
14974 
14975 {
14976 #ifdef TRILIBRARY
14977   REAL *plist;
14978   REAL *palist;
14979   int *elist;
14980   REAL *normlist;
14981   int coordindex;
14982   int attribindex;
14983 #else /* not TRILIBRARY */
14984   FILE *outfile;
14985 #endif /* not TRILIBRARY */
14986   struct otri triangleloop, trisym;
14987   vertex torg, tdest, tapex;
14988   REAL circumcenter[2];
14989   REAL xi, eta;
14990   long vnodenumber, vedgenumber;
14991   int p1, p2;
14992   int i;
14993   triangle ptr;                         /* Temporary variable used by sym(). */
14994 
14995 #ifdef TRILIBRARY
14996   if (!b->quiet) {
14997     printf("Writing Voronoi vertices.\n");
14998   }
14999   /* Allocate memory for Voronoi vertices if necessary. */
15000   if (*vpointlist == (REAL *) NULL) {
15001     *vpointlist = (REAL *) trimalloc((int) (m->triangles.items * 2 *
15002                                             sizeof(REAL)));
15003   }
15004   /* Allocate memory for Voronoi vertex attributes if necessary. */
15005   if (*vpointattriblist == (REAL *) NULL) {
15006     *vpointattriblist = (REAL *) trimalloc((int) (m->triangles.items *
15007                                                   m->nextras * sizeof(REAL)));
15008   }
15009   *vpointmarkerlist = (int *) NULL;
15010   plist = *vpointlist;
15011   palist = *vpointattriblist;
15012   coordindex = 0;
15013   attribindex = 0;
15014 #else /* not TRILIBRARY */
15015   if (!b->quiet) {
15016     printf("Writing %s.\n", vnodefilename);
15017   }
15018   outfile = fopen(vnodefilename, "w");
15019   if (outfile == (FILE *) NULL) {
15020     printf("  Error:  Cannot create file %s.\n", vnodefilename);
15021     triexit(1);
15022   }
15023   /* Number of triangles, two dimensions, number of vertex attributes, */
15024   /*   no markers.                                                     */
15025   fprintf(outfile, "%ld  %d  %d  %d\n", m->triangles.items, 2, m->nextras, 0);
15026 #endif /* not TRILIBRARY */
15027 
15028   traversalinit(&m->triangles);
15029   triangleloop.tri = triangletraverse(m);
15030   triangleloop.orient = 0;
15031   vnodenumber = b->firstnumber;
15032   while (triangleloop.tri != (triangle *) NULL) {
15033     org(triangleloop, torg);
15034     dest(triangleloop, tdest);
15035     apex(triangleloop, tapex);
15036     findcircumcenter(m, b, torg, tdest, tapex, circumcenter, &xi, &eta, 0);
15037 #ifdef TRILIBRARY
15038     /* X and y coordinates. */
15039     plist[coordindex++] = circumcenter[0];
15040     plist[coordindex++] = circumcenter[1];
15041     for (i = 2; i < 2 + m->nextras; i++) {
15042       /* Interpolate the vertex attributes at the circumcenter. */
15043       palist[attribindex++] = torg[i] + xi * (tdest[i] - torg[i])
15044                                      + eta * (tapex[i] - torg[i]);
15045     }
15046 #else /* not TRILIBRARY */
15047     /* Voronoi vertex number, x and y coordinates. */
15048     fprintf(outfile, "%4ld    %.17g  %.17g", vnodenumber, circumcenter[0],
15049             circumcenter[1]);
15050     for (i = 2; i < 2 + m->nextras; i++) {
15051       /* Interpolate the vertex attributes at the circumcenter. */
15052       fprintf(outfile, "  %.17g", torg[i] + xi * (tdest[i] - torg[i])
15053                                          + eta * (tapex[i] - torg[i]));
15054     }
15055     fprintf(outfile, "\n");
15056 #endif /* not TRILIBRARY */
15057 
15058     * (int *) (triangleloop.tri + 6) = (int) vnodenumber;
15059     triangleloop.tri = triangletraverse(m);
15060     vnodenumber++;
15061   }
15062 
15063 #ifndef TRILIBRARY
15064   finishfile(outfile, argc, argv);
15065 #endif /* not TRILIBRARY */
15066 
15067 #ifdef TRILIBRARY
15068   if (!b->quiet) {
15069     printf("Writing Voronoi edges.\n");
15070   }
15071   /* Allocate memory for output Voronoi edges if necessary. */
15072   if (*vedgelist == (int *) NULL) {
15073     *vedgelist = (int *) trimalloc((int) (m->edges * 2 * sizeof(int)));
15074   }
15075   *vedgemarkerlist = (int *) NULL;
15076   /* Allocate memory for output Voronoi norms if necessary. */
15077   if (*vnormlist == (REAL *) NULL) {
15078     *vnormlist = (REAL *) trimalloc((int) (m->edges * 2 * sizeof(REAL)));
15079   }
15080   elist = *vedgelist;
15081   normlist = *vnormlist;
15082   coordindex = 0;
15083 #else /* not TRILIBRARY */
15084   if (!b->quiet) {
15085     printf("Writing %s.\n", vedgefilename);
15086   }
15087   outfile = fopen(vedgefilename, "w");
15088   if (outfile == (FILE *) NULL) {
15089     printf("  Error:  Cannot create file %s.\n", vedgefilename);
15090     triexit(1);
15091   }
15092   /* Number of edges, zero boundary markers. */
15093   fprintf(outfile, "%ld  %d\n", m->edges, 0);
15094 #endif /* not TRILIBRARY */
15095 
15096   traversalinit(&m->triangles);
15097   triangleloop.tri = triangletraverse(m);
15098   vedgenumber = b->firstnumber;
15099   /* To loop over the set of edges, loop over all triangles, and look at   */
15100   /*   the three edges of each triangle.  If there isn't another triangle  */
15101   /*   adjacent to the edge, operate on the edge.  If there is another     */
15102   /*   adjacent triangle, operate on the edge only if the current triangle */
15103   /*   has a smaller pointer than its neighbor.  This way, each edge is    */
15104   /*   considered only once.                                               */
15105   while (triangleloop.tri != (triangle *) NULL) {
15106     for (triangleloop.orient = 0; triangleloop.orient < 3;
15107          triangleloop.orient++) {
15108       sym(triangleloop, trisym);
15109       if ((triangleloop.tri < trisym.tri) || (trisym.tri == m->dummytri)) {
15110         /* Find the number of this triangle (and Voronoi vertex). */
15111         p1 = * (int *) (triangleloop.tri + 6);
15112         if (trisym.tri == m->dummytri) {
15113           org(triangleloop, torg);
15114           dest(triangleloop, tdest);
15115 #ifdef TRILIBRARY
15116           /* Copy an infinite ray.  Index of one endpoint, and -1. */
15117           elist[coordindex] = p1;
15118           normlist[coordindex++] = tdest[1] - torg[1];
15119           elist[coordindex] = -1;
15120           normlist[coordindex++] = torg[0] - tdest[0];
15121 #else /* not TRILIBRARY */
15122           /* Write an infinite ray.  Edge number, index of one endpoint, -1, */
15123           /*   and x and y coordinates of a vector representing the          */
15124           /*   direction of the ray.                                         */
15125           fprintf(outfile, "%4ld   %d  %d   %.17g  %.17g\n", vedgenumber,
15126                   p1, -1, tdest[1] - torg[1], torg[0] - tdest[0]);
15127 #endif /* not TRILIBRARY */
15128         } else {
15129           /* Find the number of the adjacent triangle (and Voronoi vertex). */
15130           p2 = * (int *) (trisym.tri + 6);
15131           /* Finite edge.  Write indices of two endpoints. */
15132 #ifdef TRILIBRARY
15133           elist[coordindex] = p1;
15134           normlist[coordindex++] = 0.0;
15135           elist[coordindex] = p2;
15136           normlist[coordindex++] = 0.0;
15137 #else /* not TRILIBRARY */
15138           fprintf(outfile, "%4ld   %d  %d\n", vedgenumber, p1, p2);
15139 #endif /* not TRILIBRARY */
15140         }
15141         vedgenumber++;
15142       }
15143     }
15144     triangleloop.tri = triangletraverse(m);
15145   }
15146 
15147 #ifndef TRILIBRARY
15148   finishfile(outfile, argc, argv);
15149 #endif /* not TRILIBRARY */
15150 }
15151 
15152 #ifdef TRILIBRARY
15153 
15154 #ifdef ANSI_DECLARATORS
15155 void writeneighbors(struct mesh *m, struct behavior *b, int **neighborlist)
15156 #else /* not ANSI_DECLARATORS */
15157 void writeneighbors(m, b, neighborlist)
15158 struct mesh *m;
15159 struct behavior *b;
15160 int **neighborlist;
15161 #endif /* not ANSI_DECLARATORS */
15162 
15163 #else /* not TRILIBRARY */
15164 
15165 #ifdef ANSI_DECLARATORS
15166 void writeneighbors(struct mesh *m, struct behavior *b, char *neighborfilename,
15167                     int argc, char **argv)
15168 #else /* not ANSI_DECLARATORS */
15169 void writeneighbors(m, b, neighborfilename, argc, argv)
15170 struct mesh *m;
15171 struct behavior *b;
15172 char *neighborfilename;
15173 int argc;
15174 char **argv;
15175 #endif /* not ANSI_DECLARATORS */
15176 
15177 #endif /* not TRILIBRARY */
15178 
15179 {
15180 #ifdef TRILIBRARY
15181   int *nlist;
15182   int index;
15183 #else /* not TRILIBRARY */
15184   FILE *outfile;
15185 #endif /* not TRILIBRARY */
15186   struct otri triangleloop, trisym;
15187   long elementnumber;
15188   int neighbor1, neighbor2, neighbor3;
15189   triangle ptr;                         /* Temporary variable used by sym(). */
15190 
15191 #ifdef TRILIBRARY
15192   if (!b->quiet) {
15193     printf("Writing neighbors.\n");
15194   }
15195   /* Allocate memory for neighbors if necessary. */
15196   if (*neighborlist == (int *) NULL) {
15197     *neighborlist = (int *) trimalloc((int) (m->triangles.items * 3 *
15198                                              sizeof(int)));
15199   }
15200   nlist = *neighborlist;
15201   index = 0;
15202 #else /* not TRILIBRARY */
15203   if (!b->quiet) {
15204     printf("Writing %s.\n", neighborfilename);
15205   }
15206   outfile = fopen(neighborfilename, "w");
15207   if (outfile == (FILE *) NULL) {
15208     printf("  Error:  Cannot create file %s.\n", neighborfilename);
15209     triexit(1);
15210   }
15211   /* Number of triangles, three neighbors per triangle. */
15212   fprintf(outfile, "%ld  %d\n", m->triangles.items, 3);
15213 #endif /* not TRILIBRARY */
15214 
15215   traversalinit(&m->triangles);
15216   triangleloop.tri = triangletraverse(m);
15217   triangleloop.orient = 0;
15218   elementnumber = b->firstnumber;
15219   while (triangleloop.tri != (triangle *) NULL) {
15220     * (int *) (triangleloop.tri + 6) = (int) elementnumber;
15221     triangleloop.tri = triangletraverse(m);
15222     elementnumber++;
15223   }
15224   * (int *) (m->dummytri + 6) = -1;
15225 
15226   traversalinit(&m->triangles);
15227   triangleloop.tri = triangletraverse(m);
15228   elementnumber = b->firstnumber;
15229   while (triangleloop.tri != (triangle *) NULL) {
15230     triangleloop.orient = 1;
15231     sym(triangleloop, trisym);
15232     neighbor1 = * (int *) (trisym.tri + 6);
15233     triangleloop.orient = 2;
15234     sym(triangleloop, trisym);
15235     neighbor2 = * (int *) (trisym.tri + 6);
15236     triangleloop.orient = 0;
15237     sym(triangleloop, trisym);
15238     neighbor3 = * (int *) (trisym.tri + 6);
15239 #ifdef TRILIBRARY
15240     nlist[index++] = neighbor1;
15241     nlist[index++] = neighbor2;
15242     nlist[index++] = neighbor3;
15243 #else /* not TRILIBRARY */
15244     /* Triangle number, neighboring triangle numbers. */
15245     fprintf(outfile, "%4ld    %d  %d  %d\n", elementnumber,
15246             neighbor1, neighbor2, neighbor3);
15247 #endif /* not TRILIBRARY */
15248 
15249     triangleloop.tri = triangletraverse(m);
15250     elementnumber++;
15251   }
15252 
15253 #ifndef TRILIBRARY
15254   finishfile(outfile, argc, argv);
15255 #endif /* not TRILIBRARY */
15256 }
15257 
15258 /*****************************************************************************/
15259 /*                                                                           */
15260 /*  writeoff()   Write the triangulation to an .off file.                    */
15261 /*                                                                           */
15262 /*  OFF stands for the Object File Format, a format used by the Geometry     */
15263 /*  Center's Geomview package.                                               */
15264 /*                                                                           */
15265 /*****************************************************************************/
15266 
15267 #ifndef TRILIBRARY
15268 
15269 #ifdef ANSI_DECLARATORS
15270 void writeoff(struct mesh *m, struct behavior *b, char *offfilename,
15271               int argc, char **argv)
15272 #else /* not ANSI_DECLARATORS */
15273 void writeoff(m, b, offfilename, argc, argv)
15274 struct mesh *m;
15275 struct behavior *b;
15276 char *offfilename;
15277 int argc;
15278 char **argv;
15279 #endif /* not ANSI_DECLARATORS */
15280 
15281 {
15282   FILE *outfile;
15283   struct otri triangleloop;
15284   vertex vertexloop;
15285   vertex p1, p2, p3;
15286   long outvertices;
15287 
15288   if (!b->quiet) {
15289     printf("Writing %s.\n", offfilename);
15290   }
15291 
15292   if (b->jettison) {
15293     outvertices = m->vertices.items - m->undeads;
15294   } else {
15295     outvertices = m->vertices.items;
15296   }
15297 
15298   outfile = fopen(offfilename, "w");
15299   if (outfile == (FILE *) NULL) {
15300     printf("  Error:  Cannot create file %s.\n", offfilename);
15301     triexit(1);
15302   }
15303   /* Number of vertices, triangles, and edges. */
15304   fprintf(outfile, "OFF\n%ld  %ld  %ld\n", outvertices, m->triangles.items,
15305           m->edges);
15306 
15307   /* Write the vertices. */
15308   traversalinit(&m->vertices);
15309   vertexloop = vertextraverse(m);
15310   while (vertexloop != (vertex) NULL) {
15311     if (!b->jettison || (vertextype(vertexloop) != UNDEADVERTEX)) {
15312       /* The "0.0" is here because the OFF format uses 3D coordinates. */
15313       fprintf(outfile, " %.17g  %.17g  %.17g\n", vertexloop[0], vertexloop[1],
15314               0.0);
15315     }
15316     vertexloop = vertextraverse(m);
15317   }
15318 
15319   /* Write the triangles. */
15320   traversalinit(&m->triangles);
15321   triangleloop.tri = triangletraverse(m);
15322   triangleloop.orient = 0;
15323   while (triangleloop.tri != (triangle *) NULL) {
15324     org(triangleloop, p1);
15325     dest(triangleloop, p2);
15326     apex(triangleloop, p3);
15327     /* The "3" means a three-vertex polygon. */
15328     fprintf(outfile, " 3   %4d  %4d  %4d\n", vertexmark(p1) - b->firstnumber,
15329             vertexmark(p2) - b->firstnumber, vertexmark(p3) - b->firstnumber);
15330     triangleloop.tri = triangletraverse(m);
15331   }
15332   finishfile(outfile, argc, argv);
15333 }
15334 
15335 #endif /* not TRILIBRARY */
15336 
15337 /**                                                                         **/
15338 /**                                                                         **/
15339 /********* File I/O routines end here                                *********/
15340 
15341 /*****************************************************************************/
15342 /*                                                                           */
15343 /*  quality_statistics()   Print statistics about the quality of the mesh.   */
15344 /*                                                                           */
15345 /*****************************************************************************/
15346 
15347 #ifdef ANSI_DECLARATORS
15348 void quality_statistics(struct mesh *m, struct behavior *b)
15349 #else /* not ANSI_DECLARATORS */
15350 void quality_statistics(m, b)
15351 struct mesh *m;
15352 struct behavior *b;
15353 #endif /* not ANSI_DECLARATORS */
15354 
15355 {
15356   struct otri triangleloop;
15357   vertex p[3];
15358   REAL cossquaretable[8];
15359   REAL ratiotable[16];
15360   REAL dx[3], dy[3];
15361   REAL edgelength[3];
15362   REAL dotproduct;
15363   REAL cossquare;
15364   REAL triarea;
15365   REAL shortest, longest;
15366   REAL trilongest2;
15367   REAL smallestarea, biggestarea;
15368   REAL triminaltitude2;
15369   REAL minaltitude;
15370   REAL triaspect2;
15371   REAL worstaspect;
15372   REAL smallestangle, biggestangle;
15373   REAL radconst, degconst;
15374   int angletable[18];
15375   int aspecttable[16];
15376   int aspectindex;
15377   int tendegree;
15378   int acutebiggest;
15379   int i, ii, j, k;
15380 
15381   printf("Mesh quality statistics:\n\n");
15382   radconst = PI / 18.0;
15383   degconst = 180.0 / PI;
15384   for (i = 0; i < 8; i++) {
15385     cossquaretable[i] = cos(radconst * (REAL) (i + 1));
15386     cossquaretable[i] = cossquaretable[i] * cossquaretable[i];
15387   }
15388   for (i = 0; i < 18; i++) {
15389     angletable[i] = 0;
15390   }
15391 
15392   ratiotable[0]  =      1.5;      ratiotable[1]  =     2.0;
15393   ratiotable[2]  =      2.5;      ratiotable[3]  =     3.0;
15394   ratiotable[4]  =      4.0;      ratiotable[5]  =     6.0;
15395   ratiotable[6]  =     10.0;      ratiotable[7]  =    15.0;
15396   ratiotable[8]  =     25.0;      ratiotable[9]  =    50.0;
15397   ratiotable[10] =    100.0;      ratiotable[11] =   300.0;
15398   ratiotable[12] =   1000.0;      ratiotable[13] = 10000.0;
15399   ratiotable[14] = 100000.0;      ratiotable[15] =     0.0;
15400   for (i = 0; i < 16; i++) {
15401     aspecttable[i] = 0;
15402   }
15403 
15404   minaltitude = m->xmax - m->xmin + m->ymax - m->ymin;
15405   minaltitude = minaltitude * minaltitude;
15406   shortest = minaltitude;
15407   longest = 0.0;
15408   smallestarea = minaltitude;
15409   biggestarea = 0.0;
15410   worstaspect = 0.0;
15411   smallestangle = 0.0;
15412   biggestangle = 2.0;
15413   acutebiggest = 1;
15414 
15415   traversalinit(&m->triangles);
15416   triangleloop.tri = triangletraverse(m);
15417   triangleloop.orient = 0;
15418   while (triangleloop.tri != (triangle *) NULL) {
15419     org(triangleloop, p[0]);
15420     dest(triangleloop, p[1]);
15421     apex(triangleloop, p[2]);
15422     trilongest2 = 0.0;
15423 
15424     for (i = 0; i < 3; i++) {
15425       j = plus1mod3[i];
15426       k = minus1mod3[i];
15427       dx[i] = p[j][0] - p[k][0];
15428       dy[i] = p[j][1] - p[k][1];
15429       edgelength[i] = dx[i] * dx[i] + dy[i] * dy[i];
15430       if (edgelength[i] > trilongest2) {
15431         trilongest2 = edgelength[i];
15432       }
15433       if (edgelength[i] > longest) {
15434         longest = edgelength[i];
15435       }
15436       if (edgelength[i] < shortest) {
15437         shortest = edgelength[i];
15438       }
15439     }
15440 
15441     triarea = counterclockwise(m, b, p[0], p[1], p[2]);
15442     if (triarea < smallestarea) {
15443       smallestarea = triarea;
15444     }
15445     if (triarea > biggestarea) {
15446       biggestarea = triarea;
15447     }
15448     triminaltitude2 = triarea * triarea / trilongest2;
15449     if (triminaltitude2 < minaltitude) {
15450       minaltitude = triminaltitude2;
15451     }
15452     triaspect2 = trilongest2 / triminaltitude2;
15453     if (triaspect2 > worstaspect) {
15454       worstaspect = triaspect2;
15455     }
15456     aspectindex = 0;
15457     while ((triaspect2 > ratiotable[aspectindex] * ratiotable[aspectindex])
15458            && (aspectindex < 15)) {
15459       aspectindex++;
15460     }
15461     aspecttable[aspectindex]++;
15462 
15463     for (i = 0; i < 3; i++) {
15464       j = plus1mod3[i];
15465       k = minus1mod3[i];
15466       dotproduct = dx[j] * dx[k] + dy[j] * dy[k];
15467       cossquare = dotproduct * dotproduct / (edgelength[j] * edgelength[k]);
15468       tendegree = 8;
15469       for (ii = 7; ii >= 0; ii--) {
15470         if (cossquare > cossquaretable[ii]) {
15471           tendegree = ii;
15472         }
15473       }
15474       if (dotproduct <= 0.0) {
15475         angletable[tendegree]++;
15476         if (cossquare > smallestangle) {
15477           smallestangle = cossquare;
15478         }
15479         if (acutebiggest && (cossquare < biggestangle)) {
15480           biggestangle = cossquare;
15481         }
15482       } else {
15483         angletable[17 - tendegree]++;
15484         if (acutebiggest || (cossquare > biggestangle)) {
15485           biggestangle = cossquare;
15486           acutebiggest = 0;
15487         }
15488       }
15489     }
15490     triangleloop.tri = triangletraverse(m);
15491   }
15492 
15493   shortest = sqrt(shortest);
15494   longest = sqrt(longest);
15495   minaltitude = sqrt(minaltitude);
15496   worstaspect = sqrt(worstaspect);
15497   smallestarea *= 0.5;
15498   biggestarea *= 0.5;
15499   if (smallestangle >= 1.0) {
15500     smallestangle = 0.0;
15501   } else {
15502     smallestangle = degconst * acos(sqrt(smallestangle));
15503   }
15504   if (biggestangle >= 1.0) {
15505     biggestangle = 180.0;
15506   } else {
15507     if (acutebiggest) {
15508       biggestangle = degconst * acos(sqrt(biggestangle));
15509     } else {
15510       biggestangle = 180.0 - degconst * acos(sqrt(biggestangle));
15511     }
15512   }
15513 
15514   printf("  Smallest area: %16.5g   |  Largest area: %16.5g\n",
15515          smallestarea, biggestarea);
15516   printf("  Shortest edge: %16.5g   |  Longest edge: %16.5g\n",
15517          shortest, longest);
15518   printf("  Shortest altitude: %12.5g   |  Largest aspect ratio: %8.5g\n\n",
15519          minaltitude, worstaspect);
15520 
15521   printf("  Triangle aspect ratio histogram:\n");
15522   printf("  1.1547 - %-6.6g    :  %8d    | %6.6g - %-6.6g     :  %8d\n",
15523          ratiotable[0], aspecttable[0], ratiotable[7], ratiotable[8],
15524          aspecttable[8]);
15525   for (i = 1; i < 7; i++) {
15526     printf("  %6.6g - %-6.6g    :  %8d    | %6.6g - %-6.6g     :  %8d\n",
15527            ratiotable[i - 1], ratiotable[i], aspecttable[i],
15528            ratiotable[i + 7], ratiotable[i + 8], aspecttable[i + 8]);
15529   }
15530   printf("  %6.6g - %-6.6g    :  %8d    | %6.6g -            :  %8d\n",
15531          ratiotable[6], ratiotable[7], aspecttable[7], ratiotable[14],
15532          aspecttable[15]);
15533   printf("  (Aspect ratio is longest edge divided by shortest altitude)\n\n");
15534 
15535   printf("  Smallest angle: %15.5g   |  Largest angle: %15.5g\n\n",
15536          smallestangle, biggestangle);
15537 
15538   printf("  Angle histogram:\n");
15539   for (i = 0; i < 9; i++) {
15540     printf("    %3d - %3d degrees:  %8d    |    %3d - %3d degrees:  %8d\n",
15541            i * 10, i * 10 + 10, angletable[i],
15542            i * 10 + 90, i * 10 + 100, angletable[i + 9]);
15543   }
15544   printf("\n");
15545 }
15546 
15547 /*****************************************************************************/
15548 /*                                                                           */
15549 /*  statistics()   Print all sorts of cool facts.                            */
15550 /*                                                                           */
15551 /*****************************************************************************/
15552 
15553 #ifdef ANSI_DECLARATORS
15554 void statistics(struct mesh *m, struct behavior *b)
15555 #else /* not ANSI_DECLARATORS */
15556 void statistics(m, b)
15557 struct mesh *m;
15558 struct behavior *b;
15559 #endif /* not ANSI_DECLARATORS */
15560 
15561 {
15562   printf("\nStatistics:\n\n");
15563   printf("  Input vertices: %d\n", m->invertices);
15564   if (b->refine) {
15565     printf("  Input triangles: %d\n", m->inelements);
15566   }
15567   if (b->poly) {
15568     printf("  Input segments: %d\n", m->insegments);
15569     if (!b->refine) {
15570       printf("  Input holes: %d\n", m->holes);
15571     }
15572   }
15573 
15574   printf("\n  Mesh vertices: %ld\n", m->vertices.items - m->undeads);
15575   printf("  Mesh triangles: %ld\n", m->triangles.items);
15576   printf("  Mesh edges: %ld\n", m->edges);
15577   printf("  Mesh exterior boundary edges: %ld\n", m->hullsize);
15578   if (b->poly || b->refine) {
15579     printf("  Mesh interior boundary edges: %ld\n",
15580            m->subsegs.items - m->hullsize);
15581     printf("  Mesh subsegments (constrained edges): %ld\n",
15582            m->subsegs.items);
15583   }
15584   printf("\n");
15585 
15586   if (b->verbose) {
15587     quality_statistics(m, b);
15588     printf("Memory allocation statistics:\n\n");
15589     printf("  Maximum number of vertices: %ld\n", m->vertices.maxitems);
15590     printf("  Maximum number of triangles: %ld\n", m->triangles.maxitems);
15591     if (m->subsegs.maxitems > 0) {
15592       printf("  Maximum number of subsegments: %ld\n", m->subsegs.maxitems);
15593     }
15594     if (m->viri.maxitems > 0) {
15595       printf("  Maximum number of viri: %ld\n", m->viri.maxitems);
15596     }
15597     if (m->badsubsegs.maxitems > 0) {
15598       printf("  Maximum number of encroached subsegments: %ld\n",
15599              m->badsubsegs.maxitems);
15600     }
15601     if (m->badtriangles.maxitems > 0) {
15602       printf("  Maximum number of bad triangles: %ld\n",
15603              m->badtriangles.maxitems);
15604     }
15605     if (m->flipstackers.maxitems > 0) {
15606       printf("  Maximum number of stacked triangle flips: %ld\n",
15607              m->flipstackers.maxitems);
15608     }
15609     if (m->splaynodes.maxitems > 0) {
15610       printf("  Maximum number of splay tree nodes: %ld\n",
15611              m->splaynodes.maxitems);
15612     }
15613     printf("  Approximate heap memory use (bytes): %ld\n\n",
15614            m->vertices.maxitems * m->vertices.itembytes +
15615            m->triangles.maxitems * m->triangles.itembytes +
15616            m->subsegs.maxitems * m->subsegs.itembytes +
15617            m->viri.maxitems * m->viri.itembytes +
15618            m->badsubsegs.maxitems * m->badsubsegs.itembytes +
15619            m->badtriangles.maxitems * m->badtriangles.itembytes +
15620            m->flipstackers.maxitems * m->flipstackers.itembytes +
15621            m->splaynodes.maxitems * m->splaynodes.itembytes);
15622 
15623     printf("Algorithmic statistics:\n\n");
15624     if (!b->weighted) {
15625       printf("  Number of incircle tests: %ld\n", m->incirclecount);
15626     } else {
15627       printf("  Number of 3D orientation tests: %ld\n", m->orient3dcount);
15628     }
15629     printf("  Number of 2D orientation tests: %ld\n", m->counterclockcount);
15630     if (m->hyperbolacount > 0) {
15631       printf("  Number of right-of-hyperbola tests: %ld\n",
15632              m->hyperbolacount);
15633     }
15634     if (m->circletopcount > 0) {
15635       printf("  Number of circle top computations: %ld\n",
15636              m->circletopcount);
15637     }
15638     if (m->circumcentercount > 0) {
15639       printf("  Number of triangle circumcenter computations: %ld\n",
15640              m->circumcentercount);
15641     }
15642     printf("\n");
15643   }
15644 }
15645 
15646 /*****************************************************************************/
15647 /*                                                                           */
15648 /*  main() or triangulate()   Gosh, do everything.                           */
15649 /*                                                                           */
15650 /*  The sequence is roughly as follows.  Many of these steps can be skipped, */
15651 /*  depending on the command line switches.                                  */
15652 /*                                                                           */
15653 /*  - Initialize constants and parse the command line.                       */
15654 /*  - Read the vertices from a file and either                               */
15655 /*    - triangulate them (no -r), or                                         */
15656 /*    - read an old mesh from files and reconstruct it (-r).                 */
15657 /*  - Insert the PSLG segments (-p), and possibly segments on the convex     */
15658 /*      hull (-c).                                                           */
15659 /*  - Read the holes (-p), regional attributes (-pA), and regional area      */
15660 /*      constraints (-pa).  Carve the holes and concavities, and spread the  */
15661 /*      regional attributes and area constraints.                            */
15662 /*  - Enforce the constraints on minimum angle (-q) and maximum area (-a).   */
15663 /*      Also enforce the conforming Delaunay property (-q and -a).           */
15664 /*  - Compute the number of edges in the resulting mesh.                     */
15665 /*  - Promote the mesh's linear triangles to higher order elements (-o).     */
15666 /*  - Write the output files and print the statistics.                       */
15667 /*  - Check the consistency and Delaunay property of the mesh (-C).          */
15668 /*                                                                           */
15669 /*****************************************************************************/
15670 
15671 #ifdef TRILIBRARY
15672 
15673 #ifdef ANSI_DECLARATORS
15674 void triangulate(const char *const triswitches, struct triangulateio *in,
15675                  struct triangulateio *out, struct triangulateio *vorout)
15676 #else /* not ANSI_DECLARATORS */
15677 void triangulate(triswitches, in, out, vorout)
15678 const char *const triswitches;
15679 struct triangulateio *in;
15680 struct triangulateio *out;
15681 struct triangulateio *vorout;
15682 #endif /* not ANSI_DECLARATORS */
15683 
15684 #else /* not TRILIBRARY */
15685 
15686 #ifdef ANSI_DECLARATORS
15687 int main(int argc, char **argv)
15688 #else /* not ANSI_DECLARATORS */
15689 int main(argc, argv)
15690 int argc;
15691 char **argv;
15692 #endif /* not ANSI_DECLARATORS */
15693 
15694 #endif /* not TRILIBRARY */
15695 
15696 {
15697   struct mesh m;
15698   struct behavior b;
15699   REAL *holearray;                                        /* Array of holes. */
15700   REAL *regionarray;   /* Array of regional attributes and area constraints. */
15701 #ifndef TRILIBRARY
15702   FILE *polyfile;
15703 #endif /* not TRILIBRARY */
15704 #ifndef NO_TIMER
15705   /* Variables for timing the performance of Triangle.  The types are */
15706   /*   defined in sys/time.h.                                         */
15707   struct timeval tv0, tv1, tv2, tv3, tv4, tv5, tv6;
15708   struct timezone tz;
15709 #endif /* not NO_TIMER */
15710 
15711 #ifndef NO_TIMER
15712   gettimeofday(&tv0, &tz);
15713 #endif /* not NO_TIMER */
15714 
15715   triangleinit(&m);
15716 #ifdef TRILIBRARY
15717   parsecommandline(1, &triswitches, &b);
15718 #else /* not TRILIBRARY */
15719   parsecommandline(argc, argv, &b);
15720 #endif /* not TRILIBRARY */
15721   m.steinerleft = b.steiner;
15722 
15723 #ifdef TRILIBRARY
15724   transfernodes(&m, &b, in->pointlist, in->pointattributelist,
15725                 in->pointmarkerlist, in->numberofpoints,
15726                 in->numberofpointattributes);
15727 #else /* not TRILIBRARY */
15728   readnodes(&m, &b, b.innodefilename, b.inpolyfilename, &polyfile);
15729 #endif /* not TRILIBRARY */
15730 
15731 #ifndef NO_TIMER
15732   if (!b.quiet) {
15733     gettimeofday(&tv1, &tz);
15734   }
15735 #endif /* not NO_TIMER */
15736 
15737 #ifdef CDT_ONLY
15738   m.hullsize = delaunay(&m, &b);                /* Triangulate the vertices. */
15739 #else /* not CDT_ONLY */
15740   if (b.refine) {
15741     /* Read and reconstruct a mesh. */
15742 #ifdef TRILIBRARY
15743     m.hullsize = reconstruct(&m, &b, in->trianglelist,
15744                              in->triangleattributelist, in->trianglearealist,
15745                              in->numberoftriangles, in->numberofcorners,
15746                              in->numberoftriangleattributes,
15747                              in->segmentlist, in->segmentmarkerlist,
15748                              in->numberofsegments);
15749 #else /* not TRILIBRARY */
15750     m.hullsize = reconstruct(&m, &b, b.inelefilename, b.areafilename,
15751                              b.inpolyfilename, polyfile);
15752 #endif /* not TRILIBRARY */
15753   } else {
15754     m.hullsize = delaunay(&m, &b);              /* Triangulate the vertices. */
15755   }
15756 #endif /* not CDT_ONLY */
15757 
15758 #ifndef NO_TIMER
15759   if (!b.quiet) {
15760     gettimeofday(&tv2, &tz);
15761     if (b.refine) {
15762       printf("Mesh reconstruction");
15763     } else {
15764       printf("Delaunay");
15765     }
15766     printf(" milliseconds:  %ld\n", 1000l * (tv2.tv_sec - tv1.tv_sec) +
15767            (tv2.tv_usec - tv1.tv_usec) / 1000l);
15768   }
15769 #endif /* not NO_TIMER */
15770 
15771   /* Ensure that no vertex can be mistaken for a triangular bounding */
15772   /*   box vertex in insertvertex().                                 */
15773   m.infvertex1 = (vertex) NULL;
15774   m.infvertex2 = (vertex) NULL;
15775   m.infvertex3 = (vertex) NULL;
15776 
15777   if (b.usesegments) {
15778     m.checksegments = 1;                /* Segments will be introduced next. */
15779     if (!b.refine) {
15780       /* Insert PSLG segments and/or convex hull segments. */
15781 #ifdef TRILIBRARY
15782       formskeleton(&m, &b, in->segmentlist,
15783                    in->segmentmarkerlist, in->numberofsegments);
15784 #else /* not TRILIBRARY */
15785       formskeleton(&m, &b, polyfile, b.inpolyfilename);
15786 #endif /* not TRILIBRARY */
15787     }
15788   }
15789 
15790 #ifndef NO_TIMER
15791   if (!b.quiet) {
15792     gettimeofday(&tv3, &tz);
15793     if (b.usesegments && !b.refine) {
15794       printf("Segment milliseconds:  %ld\n",
15795              1000l * (tv3.tv_sec - tv2.tv_sec) +
15796              (tv3.tv_usec - tv2.tv_usec) / 1000l);
15797     }
15798   }
15799 #endif /* not NO_TIMER */
15800 
15801   if (b.poly && (m.triangles.items > 0)) {
15802 #ifdef TRILIBRARY
15803     holearray = in->holelist;
15804     m.holes = in->numberofholes;
15805     regionarray = in->regionlist;
15806     m.regions = in->numberofregions;
15807 #else /* not TRILIBRARY */
15808     readholes(&m, &b, polyfile, b.inpolyfilename, &holearray, &m.holes,
15809               &regionarray, &m.regions);
15810 #endif /* not TRILIBRARY */
15811     if (!b.refine) {
15812       /* Carve out holes and concavities. */
15813       carveholes(&m, &b, holearray, m.holes, regionarray, m.regions);
15814     }
15815   } else {
15816     /* Without a PSLG, there can be no holes or regional attributes   */
15817     /*   or area constraints.  The following are set to zero to avoid */
15818     /*   an accidental free() later.                                  */
15819     m.holes = 0;
15820     m.regions = 0;
15821   }
15822 
15823 #ifndef NO_TIMER
15824   if (!b.quiet) {
15825     gettimeofday(&tv4, &tz);
15826     if (b.poly && !b.refine) {
15827       printf("Hole milliseconds:  %ld\n", 1000l * (tv4.tv_sec - tv3.tv_sec) +
15828              (tv4.tv_usec - tv3.tv_usec) / 1000l);
15829     }
15830   }
15831 #endif /* not NO_TIMER */
15832 
15833 #ifndef CDT_ONLY
15834   if (b.quality && (m.triangles.items > 0)) {
15835     enforcequality(&m, &b);           /* Enforce angle and area constraints. */
15836   }
15837 #endif /* not CDT_ONLY */
15838 
15839 #ifndef NO_TIMER
15840   if (!b.quiet) {
15841     gettimeofday(&tv5, &tz);
15842 #ifndef CDT_ONLY
15843     if (b.quality) {
15844       printf("Quality milliseconds:  %ld\n",
15845              1000l * (tv5.tv_sec - tv4.tv_sec) +
15846              (tv5.tv_usec - tv4.tv_usec) / 1000l);
15847     }
15848 #endif /* not CDT_ONLY */
15849   }
15850 #endif /* not NO_TIMER */
15851 
15852   /* Calculate the number of edges. */
15853   m.edges = (3l * m.triangles.items + m.hullsize) / 2l;
15854 
15855   if (b.order > 1) {
15856     highorder(&m, &b);       /* Promote elements to higher polynomial order. */
15857   }
15858   if (!b.quiet) {
15859     printf("\n");
15860   }
15861 
15862 #ifdef TRILIBRARY
15863   if (b.jettison) {
15864     out->numberofpoints = m.vertices.items - m.undeads;
15865   } else {
15866     out->numberofpoints = m.vertices.items;
15867   }
15868   out->numberofpointattributes = m.nextras;
15869   out->numberoftriangles = m.triangles.items;
15870   out->numberofcorners = (b.order + 1) * (b.order + 2) / 2;
15871   out->numberoftriangleattributes = m.eextras;
15872   out->numberofedges = m.edges;
15873   if (b.usesegments) {
15874     out->numberofsegments = m.subsegs.items;
15875   } else {
15876     out->numberofsegments = m.hullsize;
15877   }
15878   if (vorout != (struct triangulateio *) NULL) {
15879     vorout->numberofpoints = m.triangles.items;
15880     vorout->numberofpointattributes = m.nextras;
15881     vorout->numberofedges = m.edges;
15882   }
15883 #endif /* TRILIBRARY */
15884   /* If not using iteration numbers, don't write a .node file if one was */
15885   /*   read, because the original one would be overwritten!              */
15886   if (b.nonodewritten || (b.noiterationnum && m.readnodefile)) {
15887     if (!b.quiet) {
15888 #ifdef TRILIBRARY
15889       printf("NOT writing vertices.\n");
15890 #else /* not TRILIBRARY */
15891       printf("NOT writing a .node file.\n");
15892 #endif /* not TRILIBRARY */
15893     }
15894     numbernodes(&m, &b);         /* We must remember to number the vertices. */
15895   } else {
15896     /* writenodes() numbers the vertices too. */
15897 #ifdef TRILIBRARY
15898     writenodes(&m, &b, &out->pointlist, &out->pointattributelist,
15899                &out->pointmarkerlist);
15900 #else /* not TRILIBRARY */
15901     writenodes(&m, &b, b.outnodefilename, argc, argv);
15902 #endif /* TRILIBRARY */
15903   }
15904   if (b.noelewritten) {
15905     if (!b.quiet) {
15906 #ifdef TRILIBRARY
15907       printf("NOT writing triangles.\n");
15908 #else /* not TRILIBRARY */
15909       printf("NOT writing an .ele file.\n");
15910 #endif /* not TRILIBRARY */
15911     }
15912   } else {
15913 #ifdef TRILIBRARY
15914     writeelements(&m, &b, &out->trianglelist, &out->triangleattributelist);
15915 #else /* not TRILIBRARY */
15916     writeelements(&m, &b, b.outelefilename, argc, argv);
15917 #endif /* not TRILIBRARY */
15918   }
15919   /* The -c switch (convex switch) causes a PSLG to be written */
15920   /*   even if none was read.                                  */
15921   if (b.poly || b.convex) {
15922     /* If not using iteration numbers, don't overwrite the .poly file. */
15923     if (b.nopolywritten || b.noiterationnum) {
15924       if (!b.quiet) {
15925 #ifdef TRILIBRARY
15926         printf("NOT writing segments.\n");
15927 #else /* not TRILIBRARY */
15928         printf("NOT writing a .poly file.\n");
15929 #endif /* not TRILIBRARY */
15930       }
15931     } else {
15932 #ifdef TRILIBRARY
15933       writepoly(&m, &b, &out->segmentlist, &out->segmentmarkerlist);
15934       out->numberofholes = m.holes;
15935       out->numberofregions = m.regions;
15936       if (b.poly) {
15937         out->holelist = in->holelist;
15938         out->regionlist = in->regionlist;
15939       } else {
15940         out->holelist = (REAL *) NULL;
15941         out->regionlist = (REAL *) NULL;
15942       }
15943 #else /* not TRILIBRARY */
15944       writepoly(&m, &b, b.outpolyfilename, holearray, m.holes, regionarray,
15945                 m.regions, argc, argv);
15946 #endif /* not TRILIBRARY */
15947     }
15948   }
15949 #ifndef TRILIBRARY
15950 #ifndef CDT_ONLY
15951   if (m.regions > 0) {
15952     trifree((void *) regionarray);
15953   }
15954 #endif /* not CDT_ONLY */
15955   if (m.holes > 0) {
15956     trifree((void *) holearray);
15957   }
15958   if (b.geomview) {
15959     writeoff(&m, &b, b.offfilename, argc, argv);
15960   }
15961 #endif /* not TRILIBRARY */
15962   if (b.edgesout) {
15963 #ifdef TRILIBRARY
15964     writeedges(&m, &b, &out->edgelist, &out->edgemarkerlist);
15965 #else /* not TRILIBRARY */
15966     writeedges(&m, &b, b.edgefilename, argc, argv);
15967 #endif /* not TRILIBRARY */
15968   }
15969   if (b.voronoi) {
15970 #ifdef TRILIBRARY
15971     writevoronoi(&m, &b, &vorout->pointlist, &vorout->pointattributelist,
15972                  &vorout->pointmarkerlist, &vorout->edgelist,
15973                  &vorout->edgemarkerlist, &vorout->normlist);
15974 #else /* not TRILIBRARY */
15975     writevoronoi(&m, &b, b.vnodefilename, b.vedgefilename, argc, argv);
15976 #endif /* not TRILIBRARY */
15977   }
15978   if (b.neighbors) {
15979 #ifdef TRILIBRARY
15980     writeneighbors(&m, &b, &out->neighborlist);
15981 #else /* not TRILIBRARY */
15982     writeneighbors(&m, &b, b.neighborfilename, argc, argv);
15983 #endif /* not TRILIBRARY */
15984   }
15985 
15986   if (!b.quiet) {
15987 #ifndef NO_TIMER
15988     gettimeofday(&tv6, &tz);
15989     printf("\nOutput milliseconds:  %ld\n",
15990            1000l * (tv6.tv_sec - tv5.tv_sec) +
15991            (tv6.tv_usec - tv5.tv_usec) / 1000l);
15992     printf("Total running milliseconds:  %ld\n",
15993            1000l * (tv6.tv_sec - tv0.tv_sec) +
15994            (tv6.tv_usec - tv0.tv_usec) / 1000l);
15995 #endif /* not NO_TIMER */
15996 
15997     statistics(&m, &b);
15998   }
15999 
16000 #ifndef REDUCED
16001   if (b.docheck) {
16002     checkmesh(&m, &b);
16003     checkdelaunay(&m, &b);
16004   }
16005 #endif /* not REDUCED */
16006 
16007   triangledeinit(&m, &b);
16008 #ifndef TRILIBRARY
16009   return 0;
16010 #endif /* not TRILIBRARY */
16011 };
16012