EIC Software
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
tetgen.h
Go to the documentation of this file. Or view the newest version in sPHENIX GitHub for file tetgen.h
1 
2 // //
3 // TetGen //
4 // //
5 // A Quality Tetrahedral Mesh Generator and A 3D Delaunay Triangulator //
6 // //
7 // Version 1.5 //
8 // November 4, 2013 //
9 // //
10 // TetGen is freely available through the website: http://www.tetgen.org. //
11 // It may be copied, modified, and redistributed for non-commercial use. //
12 // Please consult the file LICENSE for the detailed copyright notices. //
13 // //
15 
16 
17 #ifndef tetgenH
18 #define tetgenH
19 
20 // To compile TetGen as a library instead of an executable program, define
21 // the TETLIBRARY symbol.
22 
23 // #define TETLIBRARY
24 
25 // Uncomment the following line to disable assert macros. These macros were
26 // inserted in the code where I hoped to catch bugs. They may slow down the
27 // speed of TetGen.
28 
29 // #define NDEBUG
30 
31 // TetGen default uses the double precision (64 bit) for a real number.
32 // Alternatively, one can use the single precision (32 bit) 'float' if the
33 // memory is limited.
34 
35 #define REAL double // #define REAL float
36 
37 // Maximum number of characters in a file name (including the null).
38 
39 #define FILENAMESIZE 1024
40 
41 // Maximum number of chars in a line read from a file (including the null).
42 
43 #define INPUTLINESIZE 2048
44 
45 // TetGen only uses the C standard library.
46 
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <string.h>
50 #include <math.h>
51 #include <time.h>
52 #include <assert.h>
53 
54 // The types 'intptr_t' and 'uintptr_t' are signed and unsigned integer types,
55 // respectively. They are guaranteed to be the same width as a pointer.
56 // They are defined in <stdint.h> by the C99 Standard. However, Microsoft
57 // Visual C++ 2003 -- 2008 (Visual C++ 7.1 - 9) doesn't ship with this header
58 // file. In such case, we can define them by ourself.
59 // Update (learned from Stack Overflow): Visual Studio 2010 and Visual C++ 2010
60 // Express both have stdint.h
61 
62 // The following piece of code was provided by Steven Johnson (MIT). Define the
63 // symbol _MSC_VER if you are using Microsoft Visual C++. Moreover, define
64 // the _WIN64 symbol if you are running TetGen on Win64 systems.
65 
66 #ifdef _MSC_VER // Microsoft Visual C++
67 # ifdef _WIN64
68  typedef __int64 intptr_t;
69  typedef unsigned __int64 uintptr_t;
70 # else // not _WIN64
71  typedef int intptr_t;
72  typedef unsigned int uintptr_t;
73 # endif
74 #else // not Visual C++
75 # include <stdint.h>
76 #endif
77 
79 // //
80 // tetgenio //
81 // //
82 // A structure for transferring data into and out of TetGen's mesh structure,//
83 // 'tetgenmesh' (declared below). //
84 // //
85 // The input of TetGen is either a 3D point set, or a 3D piecewise linear //
86 // complex (PLC), or a tetrahedral mesh. Depending on the input object and //
87 // the specified options, the output of TetGen is either a Delaunay (or wei- //
88 // ghted Delaunay) tetrahedralization, or a constrained (Delaunay) tetrahed- //
89 // ralization, or a quality tetrahedral mesh. //
90 // //
91 // A piecewise linear complex (PLC) represents a 3D polyhedral domain with //
92 // possibly internal boundaries(subdomains). It is introduced in [Miller et //
93 // al, 1996]. Basically it is a set of "cells", i.e., vertices, edges, poly- //
94 // gons, and polyhedra, and the intersection of any two of its cells is the //
95 // union of other cells of it. //
96 // //
97 // TetGen uses a set of files to describe the inputs and outputs. Each file //
98 // is identified from its file extension (.node, .ele, .face, .edge, etc). //
99 // //
100 // The 'tetgenio' structure is a collection of arrays of data, i.e., points, //
101 // facets, tetrahedra, and so forth. It contains functions to read and write //
102 // (input and output) files of TetGen as well as other supported mesh files. //
103 // //
104 // Once an object of tetgenio is declared, no array is created. One has to //
105 // allocate enough memory for them. On deletion of this object, the memory //
106 // occupied by these arrays needs to be freed. The routine deinitialize() //
107 // will be automatically called. It frees the memory for an array if it is //
108 // not a NULL. Note that it assumes that the memory is allocated by the C++ //
109 // "new" operator. Otherwise, the user is responsible to free them and all //
110 // pointers must be NULL before the call of the destructor. //
111 // //
113 
114 class tetgenio {
115 
116 public:
117 
118  // A "polygon" describes a simple polygon (no holes). It is not necessarily
119  // convex. Each polygon contains a number of corners (points) and the same
120  // number of sides (edges). The points of the polygon must be given in
121  // either counterclockwise or clockwise order and they form a ring, so
122  // every two consecutive points forms an edge of the polygon.
123  typedef struct {
126  } polygon;
127 
128  // A "facet" describes a polygonal region possibly with holes, edges, and
129  // points floating in it. Each facet consists of a list of polygons and
130  // a list of hole points (which lie strictly inside holes).
131  typedef struct {
136  } facet;
137 
138  // A "voroedge" is an edge of the Voronoi diagram. It corresponds to a
139  // Delaunay face. Each voroedge is either a line segment connecting
140  // two Voronoi vertices or a ray starting from a Voronoi vertex to an
141  // "infinite vertex". 'v1' and 'v2' are two indices pointing to the
142  // list of Voronoi vertices. 'v1' must be non-negative, while 'v2' may
143  // be -1 if it is a ray, in this case, the unit normal of this ray is
144  // given in 'vnormal'.
145  typedef struct {
146  int v1, v2;
147  REAL vnormal[3];
148  } voroedge;
149 
150  // A "vorofacet" is an facet of the Voronoi diagram. It corresponds to a
151  // Delaunay edge. Each Voronoi facet is a convex polygon formed by a
152  // list of Voronoi edges, it may not be closed. 'c1' and 'c2' are two
153  // indices pointing into the list of Voronoi cells, i.e., the two cells
154  // share this facet. 'elist' is an array of indices pointing into the
155  // list of Voronoi edges, 'elist[0]' saves the number of Voronoi edges
156  // (including rays) of this facet.
157  typedef struct {
158  int c1, c2;
159  int *elist;
160  } vorofacet;
161 
162 
163  // Additional parameters associated with an input (or mesh) vertex.
164  // These informations are provided by CAD libraries.
165  typedef struct {
166  REAL uv[2];
167  int tag;
168  int type; // 0, 1, or 2.
169  } pointparam;
170 
171  // Callback functions for meshing PSCs.
172  typedef REAL (* GetVertexParamOnEdge)(void*, int, int);
173  typedef void (* GetSteinerOnEdge)(void*, int, REAL, REAL*);
174  typedef void (* GetVertexParamOnFace)(void*, int, int, REAL*);
175  typedef void (* GetEdgeSteinerParamOnFace)(void*, int, REAL, int, REAL*);
176  typedef void (* GetSteinerOnFace)(void*, int, REAL*, REAL*);
177 
178  // A callback function for mesh refinement.
179  typedef bool (* TetSizeFunc)(REAL*, REAL*, REAL*, REAL*, REAL*, REAL);
180 
181  // Items are numbered starting from 'firstnumber' (0 or 1), default is 0.
183 
184  // Dimension of the mesh (2 or 3), default is 3.
185  int mesh_dim;
186 
187  // Does the lines in .node file contain index or not, default is 1.
188  int useindex;
189 
190  // 'pointlist': An array of point coordinates. The first point's x
191  // coordinate is at index [0] and its y coordinate at index [1], its
192  // z coordinate is at index [2], followed by the coordinates of the
193  // remaining points. Each point occupies three REALs.
194  // 'pointattributelist': An array of point attributes. Each point's
195  // attributes occupy 'numberofpointattributes' REALs.
196  // 'pointmtrlist': An array of metric tensors at points. Each point's
197  // tensor occupies 'numberofpointmtr' REALs.
198  // 'pointmarkerlist': An array of point markers; one integer per point.
207 
208  // 'tetrahedronlist': An array of tetrahedron corners. The first
209  // tetrahedron's first corner is at index [0], followed by its other
210  // corners, followed by six nodes on the edges of the tetrahedron if the
211  // second order option (-o2) is applied. Each tetrahedron occupies
212  // 'numberofcorners' ints. The second order nodes are ouput only.
213  // 'tetrahedronattributelist': An array of tetrahedron attributes. Each
214  // tetrahedron's attributes occupy 'numberoftetrahedronattributes' REALs.
215  // 'tetrahedronvolumelist': An array of constraints, i.e. tetrahedron's
216  // volume; one REAL per element. Input only.
217  // 'neighborlist': An array of tetrahedron neighbors; 4 ints per element.
218  // Output only.
226 
227  // 'facetlist': An array of facets. Each entry is a structure of facet.
228  // 'facetmarkerlist': An array of facet markers; one int per facet.
232 
233  // 'holelist': An array of holes (in volume). Each hole is given by a
234  // seed (point) which lies strictly inside it. The first seed's x, y and z
235  // coordinates are at indices [0], [1] and [2], followed by the
236  // remaining seeds. Three REALs per hole.
239 
240  // 'regionlist': An array of regions (subdomains). Each region is given by
241  // a seed (point) which lies strictly inside it. The first seed's x, y and
242  // z coordinates are at indices [0], [1] and [2], followed by the regional
243  // attribute at index [3], followed by the maximum volume at index [4].
244  // Five REALs per region.
245  // Note that each regional attribute is used only if you select the 'A'
246  // switch, and each volume constraint is used only if you select the
247  // 'a' switch (with no number following).
250 
251  // 'facetconstraintlist': An array of facet constraints. Each constraint
252  // specifies a maximum area bound on the subfaces of that facet. The
253  // first facet constraint is given by a facet marker at index [0] and its
254  // maximum area bound at index [1], followed by the remaining facet con-
255  // straints. Two REALs per facet constraint. Note: the facet marker is
256  // actually an integer.
259 
260  // 'segmentconstraintlist': An array of segment constraints. Each constraint
261  // specifies a maximum length bound on the subsegments of that segment.
262  // The first constraint is given by the two endpoints of the segment at
263  // index [0] and [1], and the maximum length bound at index [2], followed
264  // by the remaining segment constraints. Three REALs per constraint.
265  // Note the segment endpoints are actually integers.
268 
269 
270  // 'trifacelist': An array of face (triangle) corners. The first face's
271  // three corners are at indices [0], [1] and [2], followed by the remaining
272  // faces. Three ints per face.
273  // 'trifacemarkerlist': An array of face markers; one int per face.
274  // 'o2facelist': An array of second order nodes (on the edges) of the face.
275  // It is output only if the second order option (-o2) is applied. The
276  // first face's three second order nodes are at [0], [1], and [2],
277  // followed by the remaining faces. Three ints per face.
278  // 'adjtetlist': An array of adjacent tetrahedra to the faces. The first
279  // face's two adjacent tetrahedra are at indices [0] and [1], followed by
280  // the remaining faces. A '-1' indicates outside (no adj. tet). This list
281  // is output when '-nn' switch is used. Output only.
287 
288  // 'edgelist': An array of edge endpoints. The first edge's endpoints
289  // are at indices [0] and [1], followed by the remaining edges.
290  // Two ints per edge.
291  // 'edgemarkerlist': An array of edge markers; one int per edge.
292  // 'o2edgelist': An array of midpoints of edges. It is output only if the
293  // second order option (-o2) is applied. One int per edge.
294  // 'edgeadjtetlist': An array of adjacent tetrahedra to the edges. One
295  // tetrahedron (an integer) per edge.
296  int *edgelist;
301 
302  // 'vpointlist': An array of Voronoi vertex coordinates (like pointlist).
303  // 'vedgelist': An array of Voronoi edges. Each entry is a 'voroedge'.
304  // 'vfacetlist': An array of Voronoi facets. Each entry is a 'vorofacet'.
305  // 'vcelllist': An array of Voronoi cells. Each entry is an array of
306  // indices pointing into 'vfacetlist'. The 0th entry is used to store
307  // the length of this array.
311  int **vcelllist;
316 
317  // Variable (and callback functions) for meshing PSCs.
318  void *geomhandle;
324 
325  // A callback function.
327 
328  // Input & output routines.
329  bool load_node_call(FILE* infile, int markers, int uvflag, char*);
330  bool load_node(char*);
331  bool load_edge(char*);
332  bool load_face(char*);
333  bool load_tet(char*);
334  bool load_vol(char*);
335  bool load_var(char*);
336  bool load_mtr(char*);
337  bool load_pbc(char*);
338  bool load_poly(char*);
339  bool load_off(char*);
340  bool load_ply(char*);
341  bool load_stl(char*);
342  bool load_vtk(char*);
343  bool load_medit(char*, int);
344  bool load_plc(char*, int);
345  bool load_tetmesh(char*, int);
346  void save_nodes(char*);
347  void save_elements(char*);
348  void save_faces(char*);
349  void save_edges(char*);
350  void save_neighbors(char*);
351  void save_poly(char*);
352  void save_faces2smesh(char*);
353 
354  // Read line and parse string functions.
355  char *readline(char* string, FILE* infile, int *linenumber);
356  char *findnextfield(char* string);
357  char *readnumberline(char* string, FILE* infile, char* infilename);
358  char *findnextnumber(char* string);
359 
360  static void init(polygon* p) {
361  p->vertexlist = (int *) NULL;
362  p->numberofvertices = 0;
363  }
364 
365  static void init(facet* f) {
366  f->polygonlist = (polygon *) NULL;
367  f->numberofpolygons = 0;
368  f->holelist = (REAL *) NULL;
369  f->numberofholes = 0;
370  }
371 
372  // Initialize routine.
373  void initialize()
374  {
375  firstnumber = 0;
376  mesh_dim = 3;
377  useindex = 1;
378 
379  pointlist = (REAL *) NULL;
380  pointattributelist = (REAL *) NULL;
381  pointmtrlist = (REAL *) NULL;
382  pointmarkerlist = (int *) NULL;
383  pointparamlist = (pointparam *) NULL;
384  numberofpoints = 0;
386  numberofpointmtrs = 0;
387 
388  tetrahedronlist = (int *) NULL;
389  tetrahedronattributelist = (REAL *) NULL;
390  tetrahedronvolumelist = (REAL *) NULL;
391  neighborlist = (int *) NULL;
392  numberoftetrahedra = 0;
393  numberofcorners = 4;
395 
396  trifacelist = (int *) NULL;
397  trifacemarkerlist = (int *) NULL;
398  o2facelist = (int *) NULL;
399  adjtetlist = (int *) NULL;
400  numberoftrifaces = 0;
401 
402  edgelist = (int *) NULL;
403  edgemarkerlist = (int *) NULL;
404  o2edgelist = (int *) NULL;
405  edgeadjtetlist = (int *) NULL;
406  numberofedges = 0;
407 
408  facetlist = (facet *) NULL;
409  facetmarkerlist = (int *) NULL;
410  numberoffacets = 0;
411 
412  holelist = (REAL *) NULL;
413  numberofholes = 0;
414 
415  regionlist = (REAL *) NULL;
416  numberofregions = 0;
417 
418  facetconstraintlist = (REAL *) NULL;
420  segmentconstraintlist = (REAL *) NULL;
422 
423 
424  vpointlist = (REAL *) NULL;
425  vedgelist = (voroedge *) NULL;
426  vfacetlist = (vorofacet *) NULL;
427  vcelllist = (int **) NULL;
428  numberofvpoints = 0;
429  numberofvedges = 0;
430  numberofvfacets = 0;
431  numberofvcells = 0;
432 
433  tetunsuitable = NULL;
434 
435  geomhandle = NULL;
436  getvertexparamonedge = NULL;
437  getsteineronedge = NULL;
438  getvertexparamonface = NULL;
440  getsteineronface = NULL;
441  }
442 
443  // Free the memory allocated in 'tetgenio'. Note that it assumes that the
444  // memory was allocated by the "new" operator (C++).
446  {
447  int i, j;
448 
449  if (pointlist != (REAL *) NULL) {
450  delete [] pointlist;
451  }
452  if (pointattributelist != (REAL *) NULL) {
453  delete [] pointattributelist;
454  }
455  if (pointmtrlist != (REAL *) NULL) {
456  delete [] pointmtrlist;
457  }
458  if (pointmarkerlist != (int *) NULL) {
459  delete [] pointmarkerlist;
460  }
461  if (pointparamlist != (pointparam *) NULL) {
462  delete [] pointparamlist;
463  }
464 
465  if (tetrahedronlist != (int *) NULL) {
466  delete [] tetrahedronlist;
467  }
468  if (tetrahedronattributelist != (REAL *) NULL) {
469  delete [] tetrahedronattributelist;
470  }
471  if (tetrahedronvolumelist != (REAL *) NULL) {
472  delete [] tetrahedronvolumelist;
473  }
474  if (neighborlist != (int *) NULL) {
475  delete [] neighborlist;
476  }
477 
478  if (trifacelist != (int *) NULL) {
479  delete [] trifacelist;
480  }
481  if (trifacemarkerlist != (int *) NULL) {
482  delete [] trifacemarkerlist;
483  }
484  if (o2facelist != (int *) NULL) {
485  delete [] o2facelist;
486  }
487  if (adjtetlist != (int *) NULL) {
488  delete [] adjtetlist;
489  }
490 
491  if (edgelist != (int *) NULL) {
492  delete [] edgelist;
493  }
494  if (edgemarkerlist != (int *) NULL) {
495  delete [] edgemarkerlist;
496  }
497  if (o2edgelist != (int *) NULL) {
498  delete [] o2edgelist;
499  }
500  if (edgeadjtetlist != (int *) NULL) {
501  delete [] edgeadjtetlist;
502  }
503 
504  if (facetlist != (facet *) NULL) {
505  facet *f;
506  polygon *p;
507  for (i = 0; i < numberoffacets; i++) {
508  f = &facetlist[i];
509  for (j = 0; j < f->numberofpolygons; j++) {
510  p = &f->polygonlist[j];
511  delete [] p->vertexlist;
512  }
513  delete [] f->polygonlist;
514  if (f->holelist != (REAL *) NULL) {
515  delete [] f->holelist;
516  }
517  }
518  delete [] facetlist;
519  }
520  if (facetmarkerlist != (int *) NULL) {
521  delete [] facetmarkerlist;
522  }
523 
524  if (holelist != (REAL *) NULL) {
525  delete [] holelist;
526  }
527  if (regionlist != (REAL *) NULL) {
528  delete [] regionlist;
529  }
530  if (facetconstraintlist != (REAL *) NULL) {
531  delete [] facetconstraintlist;
532  }
533  if (segmentconstraintlist != (REAL *) NULL) {
534  delete [] segmentconstraintlist;
535  }
536  if (vpointlist != (REAL *) NULL) {
537  delete [] vpointlist;
538  }
539  if (vedgelist != (voroedge *) NULL) {
540  delete [] vedgelist;
541  }
542  if (vfacetlist != (vorofacet *) NULL) {
543  for (i = 0; i < numberofvfacets; i++) {
544  delete [] vfacetlist[i].elist;
545  }
546  delete [] vfacetlist;
547  }
548  if (vcelllist != (int **) NULL) {
549  for (i = 0; i < numberofvcells; i++) {
550  delete [] vcelllist[i];
551  }
552  delete [] vcelllist;
553  }
554  }
555 
556  // Constructor & destructor.
559 
560 }; // class tetgenio
561 
563 // //
564 // tetgenbehavior //
565 // //
566 // A structure for maintaining the switches and parameters used by TetGen's //
567 // mesh data structure and algorithms. //
568 // //
569 // All switches and parameters are initialized with default values. They can //
570 // be set by the command line arguments (a list of strings) of TetGen. //
571 // //
572 // NOTE: Some of the switches are incompatible. While some may depend on //
573 // other switches. The routine parse_commandline() sets the switches from //
574 // the command line (a list of strings) and checks the consistency of the //
575 // applied switches. //
576 // //
578 
580 
581 public:
582 
583  // Switches of TetGen.
584  int plc; // '-p', 0.
585  int psc; // '-s', 0.
586  int refine; // '-r', 0.
587  int quality; // '-q', 0.
588  int nobisect; // '-Y', 0.
589  int coarsen; // '-R', 0.
590  int weighted; // '-w', 0.
591  int brio_hilbert; // '-b', 1.
592  int incrflip; // '-l', 0.
593  int flipinsert; // '-L', 0.
594  int metric; // '-m', 0.
595  int varvolume; // '-a', 0.
596  int fixedvolume; // '-a', 0.
597  int regionattrib; // '-A', 0.
598  int conforming; // '-D', 0.
599  int insertaddpoints; // '-i', 0.
600  int diagnose; // '-d', 0.
601  int convex; // '-c', 0.
602  int nomergefacet; // '-M', 0.
603  int nomergevertex; // '-M', 0.
604  int noexact; // '-X', 0.
605  int nostaticfilter; // '-X', 0.
606  int zeroindex; // '-z', 0.
607  int facesout; // '-f', 0.
608  int edgesout; // '-e', 0.
609  int neighout; // '-n', 0.
610  int voroout; // '-v', 0.
611  int meditview; // '-g', 0.
612  int vtkview; // '-k', 0.
613  int nobound; // '-B', 0.
614  int nonodewritten; // '-N', 0.
615  int noelewritten; // '-E', 0.
616  int nofacewritten; // '-F', 0.
617  int noiterationnum; // '-I', 0.
618  int nojettison; // '-J', 0.
619  int reversetetori; // '-R', 0.
620  int docheck; // '-C', 0.
621  int quiet; // '-Q', 0.
622  int verbose; // '-V', 0.
623 
624  // Parameters of TetGen.
625  int vertexperblock; // '-x', 4092.
626  int tetrahedraperblock; // '-x', 8188.
627  int shellfaceperblock; // '-x', 2044.
628  int nobisect_param; // '-Y', 2.
629  int addsteiner_algo; // '-Y/', 1.
630  int coarsen_param; // '-R', 0.
631  int weighted_param; // '-w', 0.
632  int fliplinklevel; // -1.
633  int flipstarsize; // -1.
634  int fliplinklevelinc; // 1.
635  int reflevel; // '-D', 3.
636  int optlevel; // '-O', 2.
637  int optscheme; // '-O', 7.
638  int delmaxfliplevel; // 1.
639  int order; // '-o', 1.
640  int steinerleft; // '-S', 0.
641  int no_sort; // 0.
642  int hilbert_order; // '-b///', 52.
643  int hilbert_limit; // '-b//' 8.
644  int brio_threshold; // '-b' 64.
645  REAL brio_ratio; // '-b/' 0.125.
646  REAL facet_ang_tol; // '-p', 179.9.
647  REAL maxvolume; // '-a', -1.0.
648  REAL minratio; // '-q', 0.0.
649  REAL mindihedral; // '-q', 5.0.
650  REAL optmaxdihedral; // 165.0.
651  REAL optminsmtdihed; // 179.0.
652  REAL optminslidihed; // 179.0.
653  REAL epsilon; // '-T', 1.0e-8.
655  REAL coarsen_percent; // -R1/#, 1.0.
656 
657  // Strings of command line arguments and input/output file names.
658  char commandline[1024];
659  char infilename[1024];
660  char outfilename[1024];
661  char addinfilename[1024];
662  char bgmeshfilename[1024];
663 
664  // The input object of TetGen. They are recognized by either the input
665  // file extensions or by the specified options.
666  // Currently the following objects are supported:
667  // - NODES, a list of nodes (.node);
668  // - POLY, a piecewise linear complex (.poly or .smesh);
669  // - OFF, a polyhedron (.off, Geomview's file format);
670  // - PLY, a polyhedron (.ply, file format from gatech, only ASCII);
671  // - STL, a surface mesh (.stl, stereolithography format);
672  // - MEDIT, a surface mesh (.mesh, Medit's file format);
673  // - MESH, a tetrahedral mesh (.ele).
674  // If no extension is available, the imposed command line switch
675  // (-p or -r) implies the object.
677 
678 
679  void syntax();
680  void usage();
681 
682  // Command line parse routine.
683  bool parse_commandline(int argc, char **argv);
684  bool parse_commandline(char *switches) {
685  return parse_commandline(0, &switches);
686  }
687 
688  // Initialize all variables.
690  {
691  plc = 0;
692  psc = 0;
693  refine = 0;
694  quality = 0;
695  nobisect = 0;
696  coarsen = 0;
697  metric = 0;
698  weighted = 0;
699  brio_hilbert = 1;
700  incrflip = 0;
701  flipinsert = 0;
702  varvolume = 0;
703  fixedvolume = 0;
704  noexact = 0;
705  nostaticfilter = 0;
706  insertaddpoints = 0;
707  regionattrib = 0;
708  conforming = 0;
709  diagnose = 0;
710  convex = 0;
711  zeroindex = 0;
712  facesout = 0;
713  edgesout = 0;
714  neighout = 0;
715  voroout = 0;
716  meditview = 0;
717  vtkview = 0;
718  nobound = 0;
719  nonodewritten = 0;
720  noelewritten = 0;
721  nofacewritten = 0;
722  noiterationnum = 0;
723  nomergefacet = 0;
724  nomergevertex = 0;
725  nojettison = 0;
726  reversetetori = 0;
727  docheck = 0;
728  quiet = 0;
729  verbose = 0;
730 
731  vertexperblock = 4092;
732  tetrahedraperblock = 8188;
733  shellfaceperblock = 4092;
734  nobisect_param = 2;
735  addsteiner_algo = 1;
736  coarsen_param = 0;
737  weighted_param = 0;
738  fliplinklevel = -1; // No limit on linklevel.
739  flipstarsize = -1; // No limit on flip star size.
740  fliplinklevelinc = 1;
741  reflevel = 3;
742  optscheme = 7; // 1 & 2 & 4, // min_max_dihedral.
743  optlevel = 2;
744  delmaxfliplevel = 1;
745  order = 1;
746  steinerleft = -1;
747  no_sort = 0;
748  hilbert_order = 52; //-1;
749  hilbert_limit = 8;
750  brio_threshold = 64;
751  brio_ratio = 0.125;
752  facet_ang_tol = 179.9;
753  maxvolume = -1.0;
754  minratio = 2.0;
755  mindihedral = 0.0; // 5.0;
756  optmaxdihedral = 165.00; // without -q, default is 179.0
757  optminsmtdihed = 179.00; // without -q, default is 179.999
758  optminslidihed = 179.00; // without -q, default is 179.999
759  epsilon = 1.0e-8;
760  minedgelength = 0.0;
761  coarsen_percent = 1.0;
762  object = NODES;
763 
764  commandline[0] = '\0';
765  infilename[0] = '\0';
766  outfilename[0] = '\0';
767  addinfilename[0] = '\0';
768  bgmeshfilename[0] = '\0';
769 
770  }
771 
772 }; // class tetgenbehavior
773 
775 // //
776 // Robust Geometric predicates //
777 // //
778 // Geometric predicates are simple tests of spatial relations of a set of d- //
779 // dimensional points, such as the orientation test and the point-in-sphere //
780 // test. Each of these tests is performed by evaluating the sign of a deter- //
781 // minant of a matrix whose entries are the coordinates of these points. If //
782 // the computation is performed by using the floating-point numbers, e.g., //
783 // the single or double precision numbers in C/C++, roundoff error may cause //
784 // an incorrect result. This may either lead to a wrong result or eventually //
785 // lead to a failure of the program. Computing the predicates exactly will //
786 // avoid the error and make the program robust. //
787 // //
788 // The following routines are the robust geometric predicates for 3D orient- //
789 // ation test and point-in-sphere test. They were implemented by Shewchuk. //
790 // The source code are generously provided by him in the public domain, //
791 // http://www.cs.cmu.edu/~quake/robust.html. predicates.cxx is a C++ version //
792 // of the original C code. //
793 // //
794 // The original predicates of Shewchuk only use "dynamic filters", i.e., it //
795 // computes the error at run time step by step. TetGen first adds a "static //
796 // filter" in each predicate. It estimates the maximal possible error in all //
797 // cases. So it can safely and quickly answer many easy cases. //
798 // //
800 
801 void exactinit(int, int, int, REAL, REAL, REAL);
802 REAL orient3d(REAL *pa, REAL *pb, REAL *pc, REAL *pd);
803 REAL insphere(REAL *pa, REAL *pb, REAL *pc, REAL *pd, REAL *pe);
804 REAL orient4d(REAL *pa, REAL *pb, REAL *pc, REAL *pd, REAL *pe,
805  REAL ah, REAL bh, REAL ch, REAL dh, REAL eh);
806 
808 // //
809 // tetgenmesh //
810 // //
811 // A structure for creating and updating tetrahedral meshes. //
812 // //
814 
815 class tetgenmesh {
816 
817 public:
818 
820 // //
821 // Mesh data structure //
822 // //
823 // A tetrahedral mesh T of a 3D piecewise linear complex (PLC) X is a 3D //
824 // simplicial complex whose underlying space is equal to the space of X. T //
825 // contains a 2D subcomplex S which is a triangular mesh of the boundary of //
826 // X. S contains a 1D subcomplex L which is a linear mesh of the boundary of //
827 // S. Faces and edges in S and L are respectively called subfaces and segme- //
828 // nts to distinguish them from others in T. //
829 // //
830 // TetGen stores the tetrahedra and vertices of T. The basic structure of a //
831 // tetrahedron contains pointers to its vertices and adjacent tetrahedra. A //
832 // vertex stores its x-, y-, and z-coordinates, and a pointer to a tetrahed- //
833 // ron containing it. Both tetrahedra and vertices may contain user data. //
834 // //
835 // Each face of T belongs to either two tetrahedra or one tetrahedron. In //
836 // the latter case, the face is an exterior boundary face of T. TetGen adds //
837 // fictitious tetrahedra (one-to-one) at such faces, and connects them to an //
838 // "infinite vertex" (which has no geometric coordinates). One can imagine //
839 // such a vertex lies in 4D space and is visible by all exterior boundary //
840 // faces. The extended set of tetrahedra (including the infinite vertex) is //
841 // a tetrahedralization of a 3-pseudomanifold without boundary. It has the //
842 // property that every face is shared by exactly two tetrahedra. //
843 // //
844 // The current version of TetGen stores explicitly the subfaces and segments //
845 // (which are in surface mesh S and the linear mesh L), respectively. Extra //
846 // pointers are allocated in tetrahedra and subfaces to point each others. //
847 // //
849 
850  // The tetrahedron data structure. It includes the following fields:
851  // - a list of four adjoining tetrahedra;
852  // - a list of four vertices;
853  // - a pointer to a list of four subfaces (optional, for -p switch);
854  // - a pointer to a list of six segments (optional, for -p switch);
855  // - a list of user-defined floating-point attributes (optional);
856  // - a volume constraint (optional, for -a switch);
857  // - an integer of element marker (and flags);
858  // The structure of a tetrahedron is an array of pointers. Its actual size
859  // (the length of the array) is determined at runtime.
860 
861  typedef REAL **tetrahedron;
862 
863  // The subface data structure. It includes the following fields:
864  // - a list of three adjoining subfaces;
865  // - a list of three vertices;
866  // - a list of three adjoining segments;
867  // - two adjoining tetrahedra;
868  // - an area constraint (optional, for -q switch);
869  // - an integer for boundary marker;
870  // - an integer for type, flags, etc.
871 
872  typedef REAL **shellface;
873 
874  // The point data structure. It includes the following fields:
875  // - x, y and z coordinates;
876  // - a list of user-defined point attributes (optional);
877  // - u, v coordinates (optional, for -s switch);
878  // - a metric tensor (optional, for -q or -m switch);
879  // - a pointer to an adjacent tetrahedron;
880  // - a pointer to a parent (or a duplicate) point;
881  // - a pointer to an adjacent subface or segment (optional, -p switch);
882  // - a pointer to a tet in background mesh (optional, for -m switch);
883  // - an integer for boundary marker (point index);
884  // - an integer for point type (and flags).
885  // - an integer for geometry tag (optional, for -s switch).
886  // The structure of a point is an array of REALs. Its acutal size is
887  // determined at the runtime.
888 
889  typedef REAL *point;
890 
892 // //
893 // Handles //
894 // //
895 // Navigation and manipulation in a tetrahedralization are accomplished by //
896 // operating on structures referred as ``handles". A handle is a pair (t,v), //
897 // where t is a pointer to a tetrahedron, and v is a 4-bit integer, in the //
898 // range from 0 to 11. v is called the ``version'' of a tetrahedron, it rep- //
899 // resents a directed edge of a specific face of the tetrahedron. //
900 // //
901 // There are 12 even permutations of the four vertices, each of them corres- //
902 // ponds to a directed edge (a version) of the tetrahedron. The 12 versions //
903 // can be grouped into 4 distinct ``edge rings'' in 4 ``oriented faces'' of //
904 // this tetrahedron. One can encode each version (a directed edge) into a //
905 // 4-bit integer such that the two upper bits encode the index (from 0 to 2) //
906 // of this edge in the edge ring, and the two lower bits encode the index ( //
907 // from 0 to 3) of the oriented face which contains this edge. //
908 // //
909 // The four vertices of a tetrahedron are indexed from 0 to 3 (according to //
910 // their storage in the data structure). Give each face the same index as //
911 // the node opposite it in the tetrahedron. Denote the edge connecting face //
912 // i to face j as i/j. We number the twelve versions as follows: //
913 // //
914 // | edge 0 edge 1 edge 2 //
915 // --------|-------------------------------- //
916 // face 0 | 0 (0/1) 4 (0/3) 8 (0/2) //
917 // face 1 | 1 (1/2) 5 (1/3) 9 (1/0) //
918 // face 2 | 2 (2/3) 6 (2/1) 10 (2/0) //
919 // face 3 | 3 (3/0) 7 (3/1) 11 (3/2) //
920 // //
921 // Similarly, navigation and manipulation in a (boundary) triangulation are //
922 // done by using handles of triangles. Each handle is a pair (s, v), where s //
923 // is a pointer to a triangle, and v is a version in the range from 0 to 5. //
924 // Each version corresponds to a directed edge of this triangle. //
925 // //
926 // Number the three vertices of a triangle from 0 to 2 (according to their //
927 // storage in the data structure). Give each edge the same index as the node //
928 // opposite it in the triangle. The six versions of a triangle are: //
929 // //
930 // | edge 0 edge 1 edge 2 //
931 // ---------------|-------------------------- //
932 // ccw orieation | 0 2 4 //
933 // cw orieation | 1 3 5 //
934 // //
935 // In the following, a 'triface' is a handle of tetrahedron, and a 'face' is //
936 // a handle of a triangle. //
937 // //
939 
940  class triface {
941  public:
943  int ver; // Range from 0 to 11.
944  triface() : tet(0), ver(0) {}
946  tet = t.tet; ver = t.ver;
947  return *this;
948  }
949  };
950 
951  class face {
952  public:
954  int shver; // Range from 0 to 5.
955  face() : sh(0), shver(0) {}
956  face& operator=(const face& s) {
957  sh = s.sh; shver = s.shver;
958  return *this;
959  }
960  };
961 
963 // //
964 // Arraypool //
965 // //
966 // A dynamic linear array. (It is written by J. Shewchuk) //
967 // //
968 // Each arraypool contains an array of pointers to a number of blocks. Each //
969 // block contains the same fixed number of objects. Each index of the array //
970 // addresses a particular object in the pool. The most significant bits add- //
971 // ress the index of the block containing the object. The less significant //
972 // bits address this object within the block. //
973 // //
974 // 'objectbytes' is the size of one object in blocks; 'log2objectsperblock' //
975 // is the base-2 logarithm of 'objectsperblock'; 'objects' counts the number //
976 // of allocated objects; 'totalmemory' is the total memory in bytes. //
977 // //
979 
980  class arraypool {
981 
982  public:
983 
989  char **toparray;
990  long objects;
991  unsigned long totalmemory;
992 
993  void restart();
994  void poolinit(int sizeofobject, int log2objperblk);
995  char* getblock(int objectindex);
996  void* lookup(int objectindex);
997  int newindex(void **newptr);
998 
999  arraypool(int sizeofobject, int log2objperblk);
1000  ~arraypool();
1001  };
1002 
1003 // fastlookup() -- A fast, unsafe operation. Return the pointer to the object
1004 // with a given index. Note: The object's block must have been allocated,
1005 // i.e., by the function newindex().
1006 
1007 #define fastlookup(pool, index) \
1008  (void *) ((pool)->toparray[(index) >> (pool)->log2objectsperblock] + \
1009  ((index) & (pool)->objectsperblockmark) * (pool)->objectbytes)
1010 
1012 // //
1013 // Memorypool //
1014 // //
1015 // A structure for memory allocation. (It is written by J. Shewchuk) //
1016 // //
1017 // firstblock is the first block of items. nowblock is the block from which //
1018 // items are currently being allocated. nextitem points to the next slab //
1019 // of free memory for an item. deaditemstack is the head of a linked list //
1020 // (stack) of deallocated items that can be recycled. unallocateditems is //
1021 // the number of items that remain to be allocated from nowblock. //
1022 // //
1023 // Traversal is the process of walking through the entire list of items, and //
1024 // is separate from allocation. Note that a traversal will visit items on //
1025 // the "deaditemstack" stack as well as live items. pathblock points to //
1026 // the block currently being traversed. pathitem points to the next item //
1027 // to be traversed. pathitemsleft is the number of items that remain to //
1028 // be traversed in pathblock. //
1029 // //
1031 
1032  class memorypool {
1033 
1034  public:
1035 
1037  void *nextitem;
1039  void **pathblock;
1040  void *pathitem;
1047 
1048  memorypool();
1049  memorypool(int, int, int, int);
1050  ~memorypool();
1051 
1052  void poolinit(int, int, int, int);
1053  void restart();
1054  void *alloc();
1055  void dealloc(void*);
1056  void traversalinit();
1057  void *traverse();
1058  };
1059 
1061 // //
1062 // badface //
1063 // //
1064 // Despite of its name, a 'badface' can be used to represent one of the //
1065 // following objects: //
1066 // - a face of a tetrahedron which is (possibly) non-Delaunay; //
1067 // - an encroached subsegment or subface; //
1068 // - a bad-quality tetrahedron, i.e, has too large radius-edge ratio; //
1069 // - a sliver, i.e., has good radius-edge ratio but nearly zero volume; //
1070 // - a recently flipped face (saved for undoing the flip later). //
1071 // //
1073 
1074  class badface {
1075  public:
1078  REAL key, cent[6]; // circumcenter or cos(dihedral angles) at 6 edges.
1081  badface() : key(0), forg(0), fdest(0), fapex(0), foppo(0), noppo(0),
1082  nextitem(0) {}
1083  };
1084 
1086 // //
1087 // insertvertexflags //
1088 // //
1089 // A collection of flags that pass to the routine insertvertex(). //
1090 // //
1092 
1094 
1095  public:
1096 
1097  int iloc; // input/output.
1103 
1104  // Used by Delaunay refinement.
1105  int refineflag; // 0, 1, 2, 3
1108  int smlenflag; // for useinsertradius.
1109  REAL smlen; // for useinsertradius.
1111 
1113  iloc = bowywat = lawson = 0;
1115  rejflag = chkencflag = cdtflag = 0;
1116  assignmeshsize = 0;
1117  sloc = sbowywat = 0;
1118 
1119  refineflag = 0;
1120  refinetet.tet = NULL;
1121  refinesh.sh = NULL;
1122  smlenflag = 0;
1123  smlen = 0.0;
1124  }
1125  };
1126 
1128 // //
1129 // flipconstraints //
1130 // //
1131 // A structure of a collection of data (options and parameters) which pass //
1132 // to the edge flip function flipnm(). //
1133 // //
1135 
1137 
1138  public:
1139 
1140  // Elementary flip flags.
1141  int enqflag; // (= flipflag)
1143 
1144  // Control flags
1145  int unflip; // Undo the performed flips.
1146  int collectnewtets; // Collect the new tets created by flips.
1148 
1149  // Optimization flags.
1150  int remove_ndelaunay_edge; // Remove a non-Delaunay edge.
1151  REAL bak_tetprism_vol; // The value to be minimized.
1153  int remove_large_angle; // Remove a large dihedral angle at edge.
1154  REAL cosdihed_in; // The input cosine of the dihedral angle (> 0).
1155  REAL cosdihed_out; // The improved cosine of the dihedral angle.
1156 
1157  // Boundary recovery flags.
1159  point seg[2]; // A constraining edge to be recovered.
1160  point fac[3]; // A constraining face to be recovered.
1161  point remvert; // A vertex to be removed.
1162 
1163 
1165  enqflag = 0;
1166  chkencflag = 0;
1167 
1168  unflip = 0;
1169  collectnewtets = 0;
1170  collectencsegflag = 0;
1171 
1173  bak_tetprism_vol = 0.0;
1174  tetprism_vol_sum = 0.0;
1175  remove_large_angle = 0;
1176  cosdihed_in = 0.0;
1177  cosdihed_out = 0.0;
1178 
1180  seg[0] = NULL;
1181  fac[0] = NULL;
1182  remvert = NULL;
1183  }
1184  };
1185 
1187 // //
1188 // optparameters //
1189 // //
1190 // Optimization options and parameters. //
1191 // //
1193 
1195 
1196  public:
1197 
1198  // The one of goals of optimization.
1199  int max_min_volume; // Maximize the minimum volume.
1200  int max_min_aspectratio; // Maximize the minimum aspect ratio.
1201  int min_max_dihedangle; // Minimize the maximum dihedral angle.
1202 
1203  // The initial and improved value.
1205 
1208  int maxiter; // Maximum smoothing iterations (disabled by -1).
1209  int smthiter; // Performed iterations.
1210 
1211 
1213  max_min_volume = 0;
1214  max_min_aspectratio = 0;
1215  min_max_dihedangle = 0;
1216 
1217  initval = imprval = 0.0;
1218 
1219  numofsearchdirs = 10;
1220  searchstep = 0.01;
1221  maxiter = -1; // Unlimited smoothing iterations.
1222  smthiter = 0;
1223 
1224  }
1225  };
1226 
1227 
1229 // //
1230 // Labels (enumeration declarations) used by TetGen. //
1231 // //
1233 
1234  // Labels that signify the type of a vertex.
1238 
1239  // Labels that signify the result of triangle-triangle intersection test.
1243 
1244  // Labels that signify the result of point location.
1248 
1250 // //
1251 // Variables of TetGen //
1252 // //
1254 
1255  // Pointer to the input data (a set of nodes, a PLC, or a mesh).
1257 
1258  // Pointer to the switches and parameters.
1260 
1261  // Pointer to a background mesh (contains size specification map).
1263 
1264  // Memorypools to store mesh elements (points, tetrahedra, subfaces, and
1265  // segments) and extra pointers between tetrahedra, subfaces, and segments.
1268 
1269  // Memorypools to store bad-quality (or encroached) elements.
1271 
1272  // A memorypool to store faces to be flipped.
1276 
1277  // Arrays used for point insertion (the Bowyer-Watson algorithm).
1282 
1283  // Stacks used for CDT construction and boundary recovery.
1285 
1286  // Arrays of encroached segments and subfaces (for mesh refinement).
1288 
1289  // The map between facets to their vertices (for mesh refinement).
1292 
1293  // The map between segments to their endpoints (for mesh refinement).
1295 
1296  // The infinite vertex.
1298  // The recently visited tetrahedron, subface.
1301 
1302  // PI is the ratio of a circle's circumference to its diameter.
1303  static REAL PI;
1304 
1305  // Array (size = numberoftetrahedra * 6) for storing high-order nodes of
1306  // tetrahedra (only used when -o2 switch is selected).
1308 
1309  // Various variables.
1310  int numpointattrib; // Number of point attributes.
1311  int numelemattrib; // Number of tetrahedron attributes.
1312  int sizeoftensor; // Number of REALs per metric tensor.
1313  int pointmtrindex; // Index to find the metric tensor of a point.
1314  int pointparamindex; // Index to find the u,v coordinates of a point.
1315  int point2simindex; // Index to find a simplex adjacent to a point.
1316  int pointmarkindex; // Index to find boundary marker of a point.
1317  int elemattribindex; // Index to find attributes of a tetrahedron.
1318  int volumeboundindex; // Index to find volume bound of a tetrahedron.
1319  int elemmarkerindex; // Index to find marker of a tetrahedron.
1320  int shmarkindex; // Index to find boundary marker of a subface.
1321  int areaboundindex; // Index to find area bound of a subface.
1322  int checksubsegflag; // Are there segments in the tetrahedralization yet?
1323  int checksubfaceflag; // Are there subfaces in the tetrahedralization yet?
1324  int checkconstraints; // Are there variant (node, seg, facet) constraints?
1325  int nonconvex; // Is current mesh non-convex?
1326  int autofliplinklevel; // The increase of link levels, default is 1.
1327  int useinsertradius; // Save the insertion radius for Steiner points.
1328  long samples; // Number of random samples for point location.
1329  unsigned long randomseed; // Current random number seed.
1330  REAL cosmaxdihed, cosmindihed; // The cosine values of max/min dihedral.
1331  REAL cossmtdihed; // The cosine value of a bad dihedral to be smoothed.
1332  REAL cosslidihed; // The cosine value of the max dihedral of a sliver.
1333  REAL minfaceang, minfacetdihed; // The minimum input (dihedral) angles.
1334  REAL tetprism_vol_sum; // The total volume of tetrahedral-prisms (in 4D).
1335  REAL longest; // The longest possible edge length.
1336  REAL xmax, xmin, ymax, ymin, zmax, zmin; // Bounding box of points.
1337 
1338  // Counters.
1339  long insegments; // Number of input segments.
1340  long hullsize; // Number of exterior boundary faces.
1341  long meshedges; // Number of mesh edges.
1342  long meshhulledges; // Number of boundary mesh edges.
1343  long steinerleft; // Number of Steiner points not yet used.
1344  long dupverts; // Are there duplicated vertices?
1345  long unuverts; // Are there unused vertices?
1346  long nonregularcount; // Are there non-regular vertices?
1352  unsigned long totalworkmemory; // Total memory used by working arrays.
1353 
1354 
1356 // //
1357 // Mesh manipulation primitives //
1358 // //
1360 
1361  // Fast lookup tables for mesh manipulation primitives.
1362  static int bondtbl[12][12], fsymtbl[12][12];
1363  static int esymtbl[12], enexttbl[12], eprevtbl[12];
1364  static int enextesymtbl[12], eprevesymtbl[12];
1365  static int eorgoppotbl[12], edestoppotbl[12];
1366  static int facepivot1[12], facepivot2[12][12];
1367  static int orgpivot[12], destpivot[12], apexpivot[12], oppopivot[12];
1368  static int tsbondtbl[12][6], stbondtbl[12][6];
1369  static int tspivottbl[12][6], stpivottbl[12][6];
1370  static int ver2edge[12], edge2ver[6], epivot[12];
1371  static int sorgpivot [6], sdestpivot[6], sapexpivot[6];
1372  static int snextpivot[6];
1373 
1374  void inittables();
1375 
1376  // Primitives for tetrahedra.
1377  inline tetrahedron encode(triface& t);
1378  inline tetrahedron encode2(tetrahedron* ptr, int ver);
1379  inline void decode(tetrahedron ptr, triface& t);
1380  inline void bond(triface& t1, triface& t2);
1381  inline void dissolve(triface& t);
1382  inline void esym(triface& t1, triface& t2);
1383  inline void esymself(triface& t);
1384  inline void enext(triface& t1, triface& t2);
1385  inline void enextself(triface& t);
1386  inline void eprev(triface& t1, triface& t2);
1387  inline void eprevself(triface& t);
1388  inline void enextesym(triface& t1, triface& t2);
1389  inline void enextesymself(triface& t);
1390  inline void eprevesym(triface& t1, triface& t2);
1391  inline void eprevesymself(triface& t);
1392  inline void eorgoppo(triface& t1, triface& t2);
1393  inline void eorgoppoself(triface& t);
1394  inline void edestoppo(triface& t1, triface& t2);
1395  inline void edestoppoself(triface& t);
1396  inline void fsym(triface& t1, triface& t2);
1397  inline void fsymself(triface& t);
1398  inline void fnext(triface& t1, triface& t2);
1399  inline void fnextself(triface& t);
1400  inline point org (triface& t);
1401  inline point dest(triface& t);
1402  inline point apex(triface& t);
1403  inline point oppo(triface& t);
1404  inline void setorg (triface& t, point p);
1405  inline void setdest(triface& t, point p);
1406  inline void setapex(triface& t, point p);
1407  inline void setoppo(triface& t, point p);
1408  inline REAL elemattribute(tetrahedron* ptr, int attnum);
1409  inline void setelemattribute(tetrahedron* ptr, int attnum, REAL value);
1410  inline REAL volumebound(tetrahedron* ptr);
1411  inline void setvolumebound(tetrahedron* ptr, REAL value);
1412  inline int elemindex(tetrahedron* ptr);
1413  inline void setelemindex(tetrahedron* ptr, int value);
1414  inline int elemmarker(tetrahedron* ptr);
1415  inline void setelemmarker(tetrahedron* ptr, int value);
1416  inline void infect(triface& t);
1417  inline void uninfect(triface& t);
1418  inline bool infected(triface& t);
1419  inline void marktest(triface& t);
1420  inline void unmarktest(triface& t);
1421  inline bool marktested(triface& t);
1422  inline void markface(triface& t);
1423  inline void unmarkface(triface& t);
1424  inline bool facemarked(triface& t);
1425  inline void markedge(triface& t);
1426  inline void unmarkedge(triface& t);
1427  inline bool edgemarked(triface& t);
1428  inline void marktest2(triface& t);
1429  inline void unmarktest2(triface& t);
1430  inline bool marktest2ed(triface& t);
1431  inline int elemcounter(triface& t);
1432  inline void setelemcounter(triface& t, int value);
1433  inline void increaseelemcounter(triface& t);
1434  inline void decreaseelemcounter(triface& t);
1435  inline bool ishulltet(triface& t);
1436  inline bool isdeadtet(triface& t);
1437 
1438  // Primitives for subfaces and subsegments.
1439  inline void sdecode(shellface sptr, face& s);
1440  inline shellface sencode(face& s);
1441  inline shellface sencode2(shellface *sh, int shver);
1442  inline void spivot(face& s1, face& s2);
1443  inline void spivotself(face& s);
1444  inline void sbond(face& s1, face& s2);
1445  inline void sbond1(face& s1, face& s2);
1446  inline void sdissolve(face& s);
1447  inline point sorg(face& s);
1448  inline point sdest(face& s);
1449  inline point sapex(face& s);
1450  inline void setsorg(face& s, point pointptr);
1451  inline void setsdest(face& s, point pointptr);
1452  inline void setsapex(face& s, point pointptr);
1453  inline void sesym(face& s1, face& s2);
1454  inline void sesymself(face& s);
1455  inline void senext(face& s1, face& s2);
1456  inline void senextself(face& s);
1457  inline void senext2(face& s1, face& s2);
1458  inline void senext2self(face& s);
1459  inline REAL areabound(face& s);
1460  inline void setareabound(face& s, REAL value);
1461  inline int shellmark(face& s);
1462  inline void setshellmark(face& s, int value);
1463  inline void sinfect(face& s);
1464  inline void suninfect(face& s);
1465  inline bool sinfected(face& s);
1466  inline void smarktest(face& s);
1467  inline void sunmarktest(face& s);
1468  inline bool smarktested(face& s);
1469  inline void smarktest2(face& s);
1470  inline void sunmarktest2(face& s);
1471  inline bool smarktest2ed(face& s);
1472  inline void smarktest3(face& s);
1473  inline void sunmarktest3(face& s);
1474  inline bool smarktest3ed(face& s);
1475  inline void setfacetindex(face& f, int value);
1476  inline int getfacetindex(face& f);
1477 
1478  // Primitives for interacting tetrahedra and subfaces.
1479  inline void tsbond(triface& t, face& s);
1480  inline void tsdissolve(triface& t);
1481  inline void stdissolve(face& s);
1482  inline void tspivot(triface& t, face& s);
1483  inline void stpivot(face& s, triface& t);
1484 
1485  // Primitives for interacting tetrahedra and segments.
1486  inline void tssbond1(triface& t, face& seg);
1487  inline void sstbond1(face& s, triface& t);
1488  inline void tssdissolve1(triface& t);
1489  inline void sstdissolve1(face& s);
1490  inline void tsspivot1(triface& t, face& s);
1491  inline void sstpivot1(face& s, triface& t);
1492 
1493  // Primitives for interacting subfaces and segments.
1494  inline void ssbond(face& s, face& edge);
1495  inline void ssbond1(face& s, face& edge);
1496  inline void ssdissolve(face& s);
1497  inline void sspivot(face& s, face& edge);
1498 
1499  // Primitives for points.
1500  inline int pointmark(point pt);
1501  inline void setpointmark(point pt, int value);
1502  inline enum verttype pointtype(point pt);
1503  inline void setpointtype(point pt, enum verttype value);
1504  inline int pointgeomtag(point pt);
1505  inline void setpointgeomtag(point pt, int value);
1506  inline REAL pointgeomuv(point pt, int i);
1507  inline void setpointgeomuv(point pt, int i, REAL value);
1508  inline void pinfect(point pt);
1509  inline void puninfect(point pt);
1510  inline bool pinfected(point pt);
1511  inline void pmarktest(point pt);
1512  inline void punmarktest(point pt);
1513  inline bool pmarktested(point pt);
1514  inline void pmarktest2(point pt);
1515  inline void punmarktest2(point pt);
1516  inline bool pmarktest2ed(point pt);
1517  inline void pmarktest3(point pt);
1518  inline void punmarktest3(point pt);
1519  inline bool pmarktest3ed(point pt);
1520  inline tetrahedron point2tet(point pt);
1521  inline void setpoint2tet(point pt, tetrahedron value);
1522  inline shellface point2sh(point pt);
1523  inline void setpoint2sh(point pt, shellface value);
1524  inline point point2ppt(point pt);
1525  inline void setpoint2ppt(point pt, point value);
1526  inline tetrahedron point2bgmtet(point pt);
1527  inline void setpoint2bgmtet(point pt, tetrahedron value);
1528  inline void setpointinsradius(point pt, REAL value);
1529  inline REAL getpointinsradius(point pt);
1530 
1531  // Advanced primitives.
1532  inline void point2tetorg(point pt, triface& t);
1533  inline void point2shorg(point pa, face& s);
1534  inline point farsorg(face& seg);
1535  inline point farsdest(face& seg);
1536 
1538 // //
1539 // Memory managment //
1540 // //
1542 
1548  void pointdealloc(point);
1549  point pointtraverse();
1550 
1551  void makeindex2pointmap(point*&);
1552  void makepoint2submap(memorypool*, int*&, face*&);
1553  void maketetrahedron(triface*);
1554  void makeshellface(memorypool*, face*);
1555  void makepoint(point*, enum verttype);
1556 
1557  void initializepools();
1558 
1560 // //
1561 // Advanced geometric predicates and calculations //
1562 // //
1563 // TetGen uses a simplified symbolic perturbation scheme from Edelsbrunner, //
1564 // et al [*]. Hence the point-in-sphere test never returns a zero. The idea //
1565 // is to perturb the weights of vertices in the fourth dimension. TetGen //
1566 // uses the indices of the vertices decide the amount of perturbation. It is //
1567 // implemented in the routine insphere_s().
1568 // //
1569 // The routine tri_edge_test() determines whether or not a triangle and an //
1570 // edge intersect in 3D. If they intersect, their intersection type is also //
1571 // reported. This test is a combination of n 3D orientation tests (n is bet- //
1572 // ween 3 and 9). It uses the robust orient3d() test to make the branch dec- //
1573 // isions. The routine tri_tri_test() determines whether or not two triang- //
1574 // les intersect in 3D. It also uses the robust orient3d() test. //
1575 // //
1576 // There are a number of routines to calculate geometrical quantities, e.g., //
1577 // circumcenters, angles, dihedral angles, face normals, face areas, etc. //
1578 // They are so far done by the default floating-point arithmetics which are //
1579 // non-robust. They should be improved in the future. //
1580 // //
1582 
1583  // Symbolic perturbations (robust)
1584  REAL insphere_s(REAL*, REAL*, REAL*, REAL*, REAL*);
1585  REAL orient4d_s(REAL*, REAL*, REAL*, REAL*, REAL*,
1586  REAL, REAL, REAL, REAL, REAL);
1587 
1588  // Triangle-edge intersection test (robust)
1589  int tri_edge_2d(point, point, point, point, point, point, int, int*, int*);
1591  int*, int*);
1592  int tri_edge_test(point, point, point, point, point, point, int, int*, int*);
1593 
1594  // Triangle-triangle intersection test (robust)
1597 
1598  // Linear algebra functions
1599  inline REAL dot(REAL* v1, REAL* v2);
1600  inline void cross(REAL* v1, REAL* v2, REAL* n);
1601  bool lu_decmp(REAL lu[4][4], int n, int* ps, REAL* d, int N);
1602  void lu_solve(REAL lu[4][4], int n, int* ps, REAL* b, int N);
1603 
1604  // An embedded 2-dimensional geometric predicate (non-robust)
1605  REAL incircle3d(point pa, point pb, point pc, point pd);
1606 
1607  // Geometric calculations (non-robust)
1608  REAL orient3dfast(REAL *pa, REAL *pb, REAL *pc, REAL *pd);
1609  inline REAL norm2(REAL x, REAL y, REAL z);
1610  inline REAL distance(REAL* p1, REAL* p2);
1611  void facenormal(point pa, point pb, point pc, REAL *n, int pivot, REAL *lav);
1612  REAL shortdistance(REAL* p, REAL* e1, REAL* e2);
1613  REAL triarea(REAL* pa, REAL* pb, REAL* pc);
1614  REAL interiorangle(REAL* o, REAL* p1, REAL* p2, REAL* n);
1615  void projpt2edge(REAL* p, REAL* e1, REAL* e2, REAL* prj);
1616  void projpt2face(REAL* p, REAL* f1, REAL* f2, REAL* f3, REAL* prj);
1617  REAL facedihedral(REAL* pa, REAL* pb, REAL* pc1, REAL* pc2);
1618  bool tetalldihedral(point, point, point, point, REAL*, REAL*, REAL*);
1619  void tetallnormal(point, point, point, point, REAL N[4][3], REAL* volume);
1621  bool circumsphere(REAL*, REAL*, REAL*, REAL*, REAL* cent, REAL* radius);
1623  void planelineint(REAL*, REAL*, REAL*, REAL*, REAL*, REAL*, REAL*);
1624  int linelineint(REAL*, REAL*, REAL*, REAL*, REAL*, REAL*, REAL*, REAL*);
1625  REAL tetprismvol(REAL* pa, REAL* pb, REAL* pc, REAL* pd);
1628 
1630 // //
1631 // Local mesh transformations //
1632 // //
1633 // A local transformation replaces a small set of tetrahedra with another //
1634 // set of tetrahedra which fills the same space and the same boundaries. //
1635 // In 3D, the most simplest local transformations are the elementary flips //
1636 // performed within the convex hull of five vertices: 2-to-3, 3-to-2, 1-to-4,//
1637 // and 4-to-1 flips, where the numbers indicate the number of tetrahedra //
1638 // before and after each flip. The 1-to-4 and 4-to-1 flip involve inserting //
1639 // or deleting a vertex, respectively. //
1640 // There are complex local transformations which can be decomposed as a //
1641 // combination of elementary flips. For example,a 4-to-4 flip which replaces //
1642 // two coplanar edges can be regarded by a 2-to-3 flip and a 3-to-2 flip. //
1643 // Note that the first 2-to-3 flip will temporarily create a degenerate tet- //
1644 // rahedron which is removed immediately by the followed 3-to-2 flip. More //
1645 // generally, a n-to-m flip, where n > 3, m = (n - 2) * 2, which removes an //
1646 // edge can be done by first performing a sequence of (n - 3) 2-to-3 flips //
1647 // followed by a 3-to-2 flip. //
1648 // //
1649 // The routines flip23(), flip32(), and flip41() perform the three element- //
1650 // ray flips. The flip14() is available inside the routine insertpoint(). //
1651 // //
1652 // The routines flipnm() and flipnm_post() implement a generalized edge flip //
1653 // algorithm which uses a combination of elementary flips. //
1654 // //
1655 // The routine insertpoint() implements a variant of Bowyer-Watson's cavity //
1656 // algorithm to insert a vertex. It works for arbitrary tetrahedralization, //
1657 // either Delaunay, or constrained Delaunay, or non-Delaunay. //
1658 // //
1660 
1661  // The elementary flips.
1662  void flip23(triface*, int, flipconstraints* fc);
1663  void flip32(triface*, int, flipconstraints* fc);
1664  void flip41(triface*, int, flipconstraints* fc);
1665 
1666  // A generalized edge flip.
1667  int flipnm(triface*, int n, int level, int, flipconstraints* fc);
1668  int flipnm_post(triface*, int n, int nn, int, flipconstraints* fc);
1669 
1670  // Point insertion.
1673 
1675 // //
1676 // Delaunay tetrahedralization //
1677 // //
1678 // The routine incrementaldelaunay() implemented two incremental algorithms //
1679 // for constructing Delaunay tetrahedralizations (DTs): the Bowyer-Watson //
1680 // (B-W) algorithm and the incremental flip algorithm of Edelsbrunner and //
1681 // Shah, "Incremental topological flipping works for regular triangulation," //
1682 // Algorithmica, 15:233-241, 1996. //
1683 // //
1684 // The routine incrementalflip() implements the flip algorithm of [Edelsbru- //
1685 // nner and Shah, 1996]. It flips a queue of locally non-Delaunay faces (in //
1686 // an arbitrary order). The success is guaranteed when the Delaunay tetrah- //
1687 // edralization is constructed incrementally by adding one vertex at a time. //
1688 // //
1689 // The routine locate() finds a tetrahedron contains a new point in current //
1690 // DT. It uses a simple stochastic walk algorithm: starting from an arbitr- //
1691 // ary tetrahedron in DT, it finds the destination by visit one tetrahedron //
1692 // at a time, randomly chooses a tetrahedron if there are more than one //
1693 // choices. This algorithm terminates due to Edelsbrunner's acyclic theorem. //
1694 // Choose a good starting tetrahedron is crucial to the speed of the walk. //
1695 // TetGen originally uses the "jump-and-walk" algorithm of Muecke, E.P., //
1696 // Saias, I., and Zhu, B. "Fast Randomized Point Location Without Preproces- //
1697 // sing." In Proceedings of the 12th ACM Symposium on Computational Geometry,//
1698 // 274-283, 1996. It first randomly samples several tetrahedra in the DT //
1699 // and then choosing the closet one to start walking. //
1700 // The above algorithm slows download dramatically as the number of points //
1701 // grows -- reported in Amenta, N., Choi, S. and Rote, G., "Incremental //
1702 // construction con {BRIO}," In Proceedings of 19th ACM Symposium on //
1703 // Computational Geometry, 211-219, 2003. On the other hand, Liu and //
1704 // Snoeyink showed that the point location can be made in constant time if //
1705 // the points are pre-sorted so that the nearby points in space have nearby //
1706 // indices, then adding the points in this order. They sorted the points //
1707 // along the 3D Hilbert curve. //
1708 // //
1709 // The routine hilbert_sort3() sorts a set of 3D points along the 3D Hilbert //
1710 // curve. It recursively splits a point set according to the Hilbert indices //
1711 // mapped to the subboxes of the bounding box of the point set. //
1712 // The Hilbert indices is calculated by Butz's algorithm in 1971. A nice //
1713 // exposition of this algorithm can be found in the paper of Hamilton, C., //
1714 // "Compact Hilbert Indices", Technical Report CS-2006-07, Computer Science, //
1715 // Dalhousie University, 2006 (the Section 2). My implementation also refer- //
1716 // enced Steven Witham's implementation of "Hilbert walk" (hopefully, it is //
1717 // still available at: http://www.tiac.net/~sw/2008/10/Hilbert/). //
1718 // //
1719 // TetGen sorts the points using the method in the paper of Boissonnat,J.-D.,//
1720 // Devillers, O. and Hornus, S. "Incremental Construction of the Delaunay //
1721 // Triangulation and the Delaunay Graph in Medium Dimension," In Proceedings //
1722 // of the 25th ACM Symposium on Computational Geometry, 2009. //
1723 // It first randomly sorts the points into subgroups using the Biased Rand-//
1724 // omized Insertion Ordering (BRIO) of Amenta et al 2003, then sorts the //
1725 // points in each subgroup along the 3D Hilbert curve. Inserting points in //
1726 // this order ensures a randomized "sprinkling" of the points over the //
1727 // domain, while sorting of each subset ensures locality. //
1728 // //
1730 
1731  void transfernodes();
1732 
1733  // Point sorting.
1734  int transgc[8][3][8], tsb1mod3[8];
1735  void hilbert_init(int n);
1736  int hilbert_split(point* vertexarray, int arraysize, int gc0, int gc1,
1737  REAL, REAL, REAL, REAL, REAL, REAL);
1738  void hilbert_sort3(point* vertexarray, int arraysize, int e, int d,
1739  REAL, REAL, REAL, REAL, REAL, REAL, int depth);
1740  void brio_multiscale_sort(point*,int,int threshold,REAL ratio,int* depth);
1741 
1742  // Point location.
1743  unsigned long randomnation(unsigned int choices);
1744  void randomsample(point searchpt, triface *searchtet);
1745  enum locateresult locate(point searchpt, triface *searchtet);
1746 
1747  // Incremental flips.
1748  void flippush(badface*&, triface*);
1749  int incrementalflip(point newpt, int, flipconstraints *fc);
1750 
1751  // Incremental Delaunay construction.
1752  void initialdelaunay(point pa, point pb, point pc, point pd);
1753  void incrementaldelaunay(clock_t&);
1754 
1756 // //
1757 // Surface triangulation //
1758 // //
1760 
1761  void flipshpush(face*);
1762  void flip22(face*, int, int);
1763  void flip31(face*, int);
1764  long lawsonflip();
1765  int sinsertvertex(point newpt, face*, face*, int iloc, int bowywat, int);
1766  int sremovevertex(point delpt, face*, face*, int lawson);
1767 
1768  enum locateresult slocate(point, face*, int, int, int);
1770  void scarveholes(int, REAL*);
1771  void triangulate(int, arraypool*, arraypool*, int, REAL*);
1772 
1773  void unifysubfaces(face*, face*);
1774  void unifysegments();
1775  void mergefacets();
1776  void identifypscedges(point*);
1777  void meshsurface();
1778 
1779  void interecursive(shellface** subfacearray, int arraysize, int axis,
1780  REAL, REAL, REAL, REAL, REAL, REAL, int* internum);
1781  void detectinterfaces();
1782 
1784 // //
1785 // Constrained Delaunay tetrahedralization //
1786 // //
1787 // A constrained Delaunay tetrahedralization (CDT) is a variation of a Dela- //
1788 // unay tetrahedralization (DT) that is constrained to respect the boundary //
1789 // of a 3D PLC (domain). In a CDT of a 3D PLC, every vertex or edge of the //
1790 // PLC is also a vertex or an edge of the CDT, every polygon of the PLC is a //
1791 // union of triangles of the CDT. A crucial difference between a CDT and a //
1792 // DT is that triangles in the PLC's polygons are not required to be locally //
1793 // Delaunay, which frees the CDT to better respect the PLC's polygons. CDTs //
1794 // have optimal properties similar to those of DTs. //
1795 // //
1796 // Steiner Points and Steiner CDTs. It is known that even a simple 3D polyh- //
1797 // edron may not have a tetrahedralization which only uses its own vertices. //
1798 // Some extra points, so-called "Steiner points" are needed in order to form //
1799 // a tetrahedralization of such polyhedron. It is true for tetrahedralizing //
1800 // a 3D PLC as well. A Steiner CDT of a 3D PLC is a CDT containing Steiner //
1801 // points. The CDT algorithms of TetGen in general create Steiner CDTs. //
1802 // Almost all of the Steiner points are added in the edges of the PLC. They //
1803 // guarantee the existence of a CDT of the modified PLC. //
1804 // //
1805 // The routine constraineddelaunay() starts from a DT of the vertices of a //
1806 // PLC and creates a (Steiner) CDT of the PLC (including Steiner points). It //
1807 // is constructed by two steps, (1) segment recovery and (2) facet (polygon) //
1808 // recovery. Each step is accomplished by its own algorithm. //
1809 // //
1810 // The routine delaunizesegments() implements the segment recovery algorithm //
1811 // of Si, H. and Gaertner, K. "Meshing Piecewise Linear Complexes by Constr- //
1812 // ained Delaunay Tetrahedralizations," In Proceedings of the 14th Internat- //
1813 // ional Meshing Roundtable, 147--163, 2005. It adds Steiner points into //
1814 // non-Delaunay segments until all subsegments appear together in a DT. The //
1815 // running time of this algorithm is proportional to the number of added //
1816 // Steiner points. //
1817 // //
1818 // There are two incremental facet recovery algorithms: the cavity re-trian- //
1819 // gulation algorithm of Si, H. and Gaertner, K. "3D Boundary Recovery by //
1820 // Constrained Delaunay Tetrahedralization," International Journal for Numer-//
1821 // ical Methods in Engineering, 85:1341-1364, 2011, and the flip algorithm //
1822 // of Shewchuk, J. "Updating and Constructing Constrained Delaunay and //
1823 // Constrained Regular Triangulations by Flips." In Proceedings of the 19th //
1824 // ACM Symposium on Computational Geometry, 86-95, 2003. //
1825 // //
1826 // It is guaranteed in theory, no Steiner point is needed in both algorithms //
1827 // However, a facet with non-coplanar vertices might cause the additions of //
1828 // Steiner points. It is discussed in the paper of Si, H., and Shewchuk, J.,//
1829 // "Incrementally Constructing and Updating Constrained Delaunay //
1830 // Tetrahedralizations with Finite Precision Coordinates." In Proceedings of //
1831 // the 21th International Meshing Roundtable, 2012. //
1832 // //
1833 // Our implementation of the facet recovery algorithms recover a "missing //
1834 // region" at a time. Each missing region is a subset of connected interiors //
1835 // of a polygon. The routine formcavity() creates the cavity of crossing //
1836 // tetrahedra of the missing region. //
1837 // //
1838 // The cavity re-triangulation algorithm is implemented by three subroutines,//
1839 // delaunizecavity(), fillcavity(), and carvecavity(). Since it may fail due //
1840 // to non-coplanar vertices, the subroutine restorecavity() is used to rest- //
1841 // ore the original cavity. //
1842 // //
1843 // The routine flipinsertfacet() implements the flip algorithm. The subrout- //
1844 // ine flipcertify() is used to maintain the priority queue of flips. //
1845 // //
1846 // The routine refineregion() is called when the facet recovery algorithm //
1847 // fail to recover a missing region. It inserts Steiner points to refine the //
1848 // missing region. In order to avoid inserting Steiner points very close to //
1849 // existing segments. The classical encroachment rules of the Delaunay //
1850 // refinement algorithm are used to choose the Steiner points. //
1851 // //
1852 // The routine constrainedfacets() does the facet recovery by using either //
1853 // the cavity re-triangulation algorithm (default) or the flip algorithm. It //
1854 // results a CDT of the (modified) PLC (including Steiner points). //
1855 // //
1857 
1858  void makesegmentendpointsmap();
1859 
1860  enum interresult finddirection(triface* searchtet, point endpt);
1862  int getsteinerptonsegment(face* seg, point refpt, point steinpt);
1863  void delaunizesegments();
1864 
1865  enum interresult scoutsubface(face* searchsh, triface* searchtet);
1867  int scoutcrossedge(triface& crosstet, arraypool*, arraypool*);
1869  arraypool*, arraypool*);
1870 
1871  // Facet recovery by cavity re-triangulation [Si and Gaertner 2011].
1873  arraypool*, arraypool*);
1875  arraypool*, arraypool*, triface* crossedge);
1878 
1879  // Facet recovery by flips [Shewchuk 2003].
1880  void flipcertify(triface *chkface, badface **pqueue, point, point, point);
1882 
1883  bool fillregion(arraypool* missingshs, arraypool*, arraypool* newshs);
1884 
1887  arraypool*, arraypool*);
1889  arraypool*, arraypool*);
1890 
1891  void constrainedfacets();
1892 
1893  void constraineddelaunay(clock_t&);
1894 
1896 // //
1897 // Constrained tetrahedralizations. //
1898 // //
1900 
1901  int checkflipeligibility(int fliptype, point, point, point, point, point,
1902  int level, int edgepivot, flipconstraints* fc);
1903 
1906 
1907  int recoveredgebyflips(point, point, triface*, int fullsearch);
1908  int add_steinerpt_in_schoenhardtpoly(triface*, int, int chkencflag);
1909  int add_steinerpt_in_segment(face*, int searchlevel);
1910  int addsteiner4recoversegment(face*, int);
1911  int recoversegments(arraypool*, int fullsearch, int steinerflag);
1912 
1914  int recoversubfaces(arraypool*, int steinerflag);
1915 
1916  int getvertexstar(int, point searchpt, arraypool*, arraypool*, arraypool*);
1917  int getedge(point, point, triface*);
1918  int reduceedgesatvertex(point startpt, arraypool* endptlist);
1919  int removevertexbyflips(point steinerpt);
1920 
1921  int suppressbdrysteinerpoint(point steinerpt);
1922  int suppresssteinerpoints();
1923 
1924  void recoverboundary(clock_t&);
1925 
1927 // //
1928 // Mesh reconstruction //
1929 // //
1931 
1932  void carveholes();
1933 
1934  void reconstructmesh();
1935 
1936  int scoutpoint(point, triface*, int randflag);
1937  REAL getpointmeshsize(point, triface*, int iloc);
1938  void interpolatemeshsize();
1939 
1940  void insertconstrainedpoints(point *insertarray, int arylen, int rejflag);
1941  void insertconstrainedpoints(tetgenio *addio);
1942 
1943  void collectremovepoints(arraypool *remptlist);
1944  void meshcoarsening();
1945 
1947 // //
1948 // Mesh refinement //
1949 // //
1950 // The purpose of mesh refinement is to obtain a tetrahedral mesh with well- //
1951 // -shaped tetrahedra and appropriate mesh size. It is necessary to insert //
1952 // new Steiner points to achieve this property. The questions are (1) how to //
1953 // choose the Steiner points? and (2) how to insert them? //
1954 // //
1955 // Delaunay refinement is a technique first developed by Chew [1989] and //
1956 // Ruppert [1993, 1995] to generate quality triangular meshes in the plane. //
1957 // It provides guarantee on the smallest angle of the triangles. Rupper's //
1958 // algorithm guarantees that the mesh is size-optimal (to within a constant //
1959 // factor) among all meshes with the same quality. //
1960 // Shewchuk generalized Ruppert's algorithm into 3D in his PhD thesis //
1961 // [Shewchuk 1997]. A short version of his algorithm appears in "Tetrahedral //
1962 // Mesh Generation by Delaunay Refinement," In Proceedings of the 14th ACM //
1963 // Symposium on Computational Geometry, 86-95, 1998. It guarantees that all //
1964 // tetrahedra of the output mesh have a "radius-edge ratio" (equivalent to //
1965 // the minimal face angle) bounded. However, it does not remove slivers, a //
1966 // type of very flat tetrahedra which can have no small face angles but have //
1967 // very small (and large) dihedral angles. Moreover, it may not terminate if //
1968 // the input PLC contains "sharp features", e.g., two edges (or two facets) //
1969 // meet at an acute angle (or dihedral angle). //
1970 // //
1971 // TetGen uses the basic Delaunay refinement scheme to insert Steiner points.//
1972 // While it always maintains a constrained Delaunay mesh. The algorithm is //
1973 // described in Si, H., "Adaptive Constrained Delaunay Mesh Generation," //
1974 // International Journal for Numerical Methods in Engineering, 75:856-880. //
1975 // This algorithm always terminates and sharp features are easily preserved. //
1976 // The mesh has good quality (same as Shewchuk's Delaunay refinement algori- //
1977 // thm) in the bulk of the mesh domain. Moreover, it supports the generation //
1978 // of adaptive mesh according to a (isotropic) mesh sizing function. //
1979 // //
1981 
1982  void makefacetverticesmap();
1983  int segsegadjacent(face *, face *);
1984  int segfacetadjacent(face *checkseg, face *checksh);
1985  int facetfacetadjacent(face *, face *);
1986 
1987  int checkseg4encroach(point pa, point pb, point checkpt);
1988  int checkseg4split(face *chkseg, point&, int&);
1989  int splitsegment(face *splitseg, point encpt, REAL, point, point, int, int);
1990  void repairencsegs(int chkencflag);
1991 
1992  void enqueuesubface(memorypool*, face*);
1993  int checkfac4encroach(point, point, point, point checkpt, REAL*, REAL*);
1994  int checkfac4split(face *chkfac, point& encpt, int& qflag, REAL *ccent);
1995  int splitsubface(face *splitfac, point, point, int qflag, REAL *ccent, int);
1996  void repairencfacs(int chkencflag);
1997 
1998  void enqueuetetrahedron(triface*);
1999  int checktet4split(triface *chktet, int& qflag, REAL *ccent);
2000  int splittetrahedron(triface* splittet,int qflag,REAL *ccent, int);
2001  void repairbadtets(int chkencflag);
2002 
2003  void delaunayrefinement();
2004 
2006 // //
2007 // Mesh optimization //
2008 // //
2010 
2011  long lawsonflip3d(flipconstraints *fc);
2012  void recoverdelaunay();
2013 
2015  long improvequalitybyflips();
2016 
2017  int smoothpoint(point smtpt, arraypool*, int ccw, optparameters *opm);
2019 
2020  int splitsliver(triface *, REAL, int);
2021  long removeslivers(int);
2022 
2023  void optimizemesh();
2024 
2026 // //
2027 // Mesh check and statistics //
2028 // //
2030 
2031  // Mesh validations.
2032  int checkmesh(int topoflag);
2033  int checkshells();
2034  int checksegments();
2035  int checkdelaunay();
2036  int checkregular(int);
2037  int checkconforming(int);
2038 
2039  // Mesh statistics.
2040  void printfcomma(unsigned long n);
2041  void qualitystatistics();
2042  void memorystatistics();
2043  void statistics();
2044 
2046 // //
2047 // Mesh output //
2048 // //
2050 
2051  void jettisonnodes();
2052  void highorder();
2053  void numberedges();
2054  void outnodes(tetgenio*);
2055  void outmetrics(tetgenio*);
2056  void outelements(tetgenio*);
2057  void outfaces(tetgenio*);
2058  void outhullfaces(tetgenio*);
2059  void outsubfaces(tetgenio*);
2060  void outedges(tetgenio*);
2061  void outsubsegments(tetgenio*);
2062  void outneighbors(tetgenio*);
2063  void outvoronoi(tetgenio*);
2064  void outsmesh(char*);
2065  void outmesh2medit(char*);
2066  void outmesh2vtk(char*);
2067 
2068 
2069 
2071 // //
2072 // Constructor & destructor //
2073 // //
2075 
2077  {
2078  in = addin = NULL;
2079  b = NULL;
2080  bgm = NULL;
2081 
2082  tetrahedrons = subfaces = subsegs = points = NULL;
2084  tet2segpool = tet2subpool = NULL;
2085  flippool = NULL;
2086 
2087  dummypoint = NULL;
2088  flipstack = NULL;
2089  unflipqueue = NULL;
2090 
2093  caveencshlist = caveencseglist = NULL;
2095 
2097  encseglist = encshlist = NULL;
2098  idx2facetlist = NULL;
2099  facetverticeslist = NULL;
2100  segmentendpointslist = NULL;
2101 
2102  highordertable = NULL;
2103 
2105  sizeoftensor = 0;
2106  pointmtrindex = 0;
2107  pointparamindex = 0;
2108  pointmarkindex = 0;
2109  point2simindex = 0;
2110  elemattribindex = 0;
2111  volumeboundindex = 0;
2112  shmarkindex = 0;
2113  areaboundindex = 0;
2114  checksubsegflag = 0;
2115  checksubfaceflag = 0;
2116  checkconstraints = 0;
2117  nonconvex = 0;
2118  autofliplinklevel = 1;
2119  useinsertradius = 0;
2120  samples = 0l;
2121  randomseed = 1l;
2123  tetprism_vol_sum = 0.0;
2124  longest = 0.0;
2125  xmax = xmin = ymax = ymin = zmax = zmin = 0.0;
2126 
2127  insegments = 0l;
2128  hullsize = 0l;
2129  meshedges = meshhulledges = 0l;
2130  steinerleft = -1;
2131  dupverts = 0l;
2132  unuverts = 0l;
2133  nonregularcount = 0l;
2138  flip22count = flip31count = 0l;
2139  totalworkmemory = 0l;
2140 
2141 
2142  } // tetgenmesh()
2143 
2144  void freememory()
2145  {
2146  if (bgm != NULL) {
2147  delete bgm;
2148  }
2149 
2150  if (points != (memorypool *) NULL) {
2151  delete points;
2152  delete [] dummypoint;
2153  }
2154 
2155  if (tetrahedrons != (memorypool *) NULL) {
2156  delete tetrahedrons;
2157  }
2158 
2159  if (subfaces != (memorypool *) NULL) {
2160  delete subfaces;
2161  delete subsegs;
2162  }
2163 
2164  if (tet2segpool != NULL) {
2165  delete tet2segpool;
2166  delete tet2subpool;
2167  }
2168 
2169  if (flippool != NULL) {
2170  delete flippool;
2171  delete unflipqueue;
2172  }
2173 
2174  if (cavetetlist != NULL) {
2175  delete cavetetlist;
2176  delete cavebdrylist;
2177  delete caveoldtetlist;
2178  delete cavetetvertlist;
2179  }
2180 
2181  if (caveshlist != NULL) {
2182  delete caveshlist;
2183  delete caveshbdlist;
2184  delete cavesegshlist;
2185  delete cavetetshlist;
2186  delete cavetetseglist;
2187  delete caveencshlist;
2188  delete caveencseglist;
2189  }
2190 
2191  if (subsegstack != NULL) {
2192  delete subsegstack;
2193  delete subfacstack;
2194  delete subvertstack;
2195  }
2196 
2197  if (idx2facetlist != NULL) {
2198  delete [] idx2facetlist;
2199  delete [] facetverticeslist;
2200  }
2201 
2202  if (segmentendpointslist != NULL) {
2203  delete [] segmentendpointslist;
2204  }
2205 
2206  if (highordertable != NULL) {
2207  delete [] highordertable;
2208  }
2209  }
2210 
2212  {
2213  //@@@ freememory();
2214  } // ~tetgenmesh()
2215 
2216 }; // End of class tetgenmesh.
2217 
2219 // //
2220 // tetrahedralize() Interface for using TetGen's library to generate //
2221 // Delaunay tetrahedralizations, constrained Delaunay //
2222 // tetrahedralizations, quality tetrahedral meshes. //
2223 // //
2224 // 'in' is an object of 'tetgenio' which contains a PLC you want to tetrahed-//
2225 // ralize or a previously generated tetrahedral mesh you want to refine. It //
2226 // must not be a NULL. 'out' is another object of 'tetgenio' for storing the //
2227 // generated tetrahedral mesh. It can be a NULL. If so, the output will be //
2228 // saved to file(s). If 'bgmin' != NULL, it contains a background mesh which //
2229 // defines a mesh size function. //
2230 // //
2232 
2234  tetgenio *addin = NULL, tetgenio *bgmin = NULL);
2235 
2236 #ifdef TETLIBRARY
2237 void tetrahedralize(char *switches, tetgenio *in, tetgenio *out,
2238  tetgenio *addin = NULL, tetgenio *bgmin = NULL);
2239 #endif // #ifdef TETLIBRARY
2240 
2242 // //
2243 // terminatetetgen() Terminate TetGen with a given exit code. //
2244 // //
2246 
2247 inline void terminatetetgen(tetgenmesh *m, int x)
2248 {
2249  // Release the allocated memory.
2250  if (m) {
2251  m->freememory();
2252  }
2253 #ifdef TETLIBRARY
2254  throw x;
2255 #else
2256  switch (x) {
2257  case 1: // Out of memory.
2258  printf("Error: Out of memory.\n");
2259  break;
2260  case 2: // Encounter an internal error.
2261  printf("Please report this bug to Hang.Si@wias-berlin.de. Include\n");
2262  printf(" the message above, your input data set, and the exact\n");
2263  printf(" command line you used to run this program, thank you.\n");
2264  break;
2265  case 3:
2266  printf("A self-intersection was detected. Program stopped.\n");
2267  printf("Hint: use -d option to detect all self-intersections.\n");
2268  break;
2269  case 4:
2270  printf("A very small input feature size was detected. Program stopped.\n");
2271  printf("Hint: use -T option to set a smaller tolerance.\n");
2272  break;
2273  case 5:
2274  printf("Two very close input facets were detected. Program stopped.\n");
2275  printf("Hint: use -Y option to avoid adding Steiner points in boundary.\n");
2276  break;
2277  case 10:
2278  printf("An input error was detected. Program stopped.\n");
2279  break;
2280  } // switch (x)
2281  exit(x);
2282 #endif // #ifdef TETLIBRARY
2283 }
2284 
2286 // //
2287 // Primitives for tetrahedra //
2288 // //
2290 
2291 // encode() compress a handle into a single pointer. It relies on the
2292 // assumption that all addresses of tetrahedra are aligned to sixteen-
2293 // byte boundaries, so that the last four significant bits are zero.
2294 
2296  return (tetrahedron) ((uintptr_t) (t).tet | (uintptr_t) (t).ver);
2297 }
2298 
2300  return (tetrahedron) ((uintptr_t) (ptr) | (uintptr_t) (ver));
2301 }
2302 
2303 // decode() converts a pointer to a handle. The version is extracted from
2304 // the four least significant bits of the pointer.
2305 
2307  (t).ver = (int) ((uintptr_t) (ptr) & (uintptr_t) 15);
2308  (t).tet = (tetrahedron *) ((uintptr_t) (ptr) ^ (uintptr_t) (t).ver);
2309 }
2310 
2311 // bond() connects two tetrahedra together. (t1,v1) and (t2,v2) must
2312 // refer to the same face and the same edge.
2313 
2315  t1.tet[t1.ver & 3] = encode2(t2.tet, bondtbl[t1.ver][t2.ver]);
2316  t2.tet[t2.ver & 3] = encode2(t1.tet, bondtbl[t2.ver][t1.ver]);
2317 }
2318 
2319 
2320 // dissolve() a bond (from one side).
2321 
2323  t.tet[t.ver & 3] = NULL;
2324 }
2325 
2326 // enext() finds the next edge (counterclockwise) in the same face.
2327 
2329  t2.tet = t1.tet;
2330  t2.ver = enexttbl[t1.ver];
2331 }
2332 
2334  t.ver = enexttbl[t.ver];
2335 }
2336 
2337 // eprev() finds the next edge (clockwise) in the same face.
2338 
2340  t2.tet = t1.tet;
2341  t2.ver = eprevtbl[t1.ver];
2342 }
2343 
2345  t.ver = eprevtbl[t.ver];
2346 }
2347 
2348 // esym() finds the reversed edge. It is in the other face of the
2349 // same tetrahedron.
2350 
2352  (t2).tet = (t1).tet;
2353  (t2).ver = esymtbl[(t1).ver];
2354 }
2355 
2357  (t).ver = esymtbl[(t).ver];
2358 }
2359 
2360 // enextesym() finds the reversed edge of the next edge. It is in the other
2361 // face of the same tetrahedron. It is the combination esym() * enext().
2362 
2364  t2.tet = t1.tet;
2365  t2.ver = enextesymtbl[t1.ver];
2366 }
2367 
2369  t.ver = enextesymtbl[t.ver];
2370 }
2371 
2372 // eprevesym() finds the reversed edge of the previous edge.
2373 
2375  t2.tet = t1.tet;
2376  t2.ver = eprevesymtbl[t1.ver];
2377 }
2378 
2380  t.ver = eprevesymtbl[t.ver];
2381 }
2382 
2383 // eorgoppo() Finds the opposite face of the origin of the current edge.
2384 // Return the opposite edge of the current edge.
2385 
2387  t2.tet = t1.tet;
2388  t2.ver = eorgoppotbl[t1.ver];
2389 }
2390 
2392  t.ver = eorgoppotbl[t.ver];
2393 }
2394 
2395 // edestoppo() Finds the opposite face of the destination of the current
2396 // edge. Return the opposite edge of the current edge.
2397 
2399  t2.tet = t1.tet;
2400  t2.ver = edestoppotbl[t1.ver];
2401 }
2402 
2404  t.ver = edestoppotbl[t.ver];
2405 }
2406 
2407 // fsym() finds the adjacent tetrahedron at the same face and the same edge.
2408 
2410  decode((t1).tet[(t1).ver & 3], t2);
2411  t2.ver = fsymtbl[t1.ver][t2.ver];
2412 }
2413 
2414 
2415 #define fsymself(t) \
2416  t1ver = (t).ver; \
2417  decode((t).tet[(t).ver & 3], (t));\
2418  (t).ver = fsymtbl[t1ver][(t).ver]
2419 
2420 // fnext() finds the next face while rotating about an edge according to
2421 // a right-hand rule. The face is in the adjacent tetrahedron. It is
2422 // the combination: fsym() * esym().
2423 
2425  decode(t1.tet[facepivot1[t1.ver]], t2);
2426  t2.ver = facepivot2[t1.ver][t2.ver];
2427 }
2428 
2429 
2430 #define fnextself(t) \
2431  t1ver = (t).ver; \
2432  decode((t).tet[facepivot1[(t).ver]], (t)); \
2433  (t).ver = facepivot2[t1ver][(t).ver]
2434 
2435 
2436 // The following primtives get or set the origin, destination, face apex,
2437 // or face opposite of an ordered tetrahedron.
2438 
2440  return (point) (t).tet[orgpivot[(t).ver]];
2441 }
2442 
2444  return (point) (t).tet[destpivot[(t).ver]];
2445 }
2446 
2448  return (point) (t).tet[apexpivot[(t).ver]];
2449 }
2450 
2452  return (point) (t).tet[oppopivot[(t).ver]];
2453 }
2454 
2456  (t).tet[orgpivot[(t).ver]] = (tetrahedron) (p);
2457 }
2458 
2460  (t).tet[destpivot[(t).ver]] = (tetrahedron) (p);
2461 }
2462 
2464  (t).tet[apexpivot[(t).ver]] = (tetrahedron) (p);
2465 }
2466 
2468  (t).tet[oppopivot[(t).ver]] = (tetrahedron) (p);
2469 }
2470 
2471 #define setvertices(t, torg, tdest, tapex, toppo) \
2472  (t).tet[orgpivot[(t).ver]] = (tetrahedron) (torg);\
2473  (t).tet[destpivot[(t).ver]] = (tetrahedron) (tdest); \
2474  (t).tet[apexpivot[(t).ver]] = (tetrahedron) (tapex); \
2475  (t).tet[oppopivot[(t).ver]] = (tetrahedron) (toppo)
2476 
2477 // Check or set a tetrahedron's attributes.
2478 
2479 inline REAL tetgenmesh::elemattribute(tetrahedron* ptr, int attnum) {
2480  return ((REAL *) (ptr))[elemattribindex + attnum];
2481 }
2482 
2483 inline void tetgenmesh::setelemattribute(tetrahedron* ptr, int attnum,
2484  REAL value) {
2485  ((REAL *) (ptr))[elemattribindex + attnum] = value;
2486 }
2487 
2488 // Check or set a tetrahedron's maximum volume bound.
2489 
2491  return ((REAL *) (ptr))[volumeboundindex];
2492 }
2493 
2495  ((REAL *) (ptr))[volumeboundindex] = value;
2496 }
2497 
2498 // Get or set a tetrahedron's index (only used for output).
2499 // These two routines use the reserved slot ptr[10].
2500 
2502  int *iptr = (int *) &(ptr[10]);
2503  return iptr[0];
2504 }
2505 
2507  int *iptr = (int *) &(ptr[10]);
2508  iptr[0] = value;
2509 }
2510 
2511 // Get or set a tetrahedron's marker.
2512 // Set 'value = 0' cleans all the face/edge flags.
2513 
2515  return ((int *) (ptr))[elemmarkerindex];
2516 }
2517 
2519  ((int *) (ptr))[elemmarkerindex] = value;
2520 }
2521 
2522 // infect(), infected(), uninfect() -- primitives to flag or unflag a
2523 // tetrahedron. The last bit of the element marker is flagged (1)
2524 // or unflagged (0).
2525 
2527  ((int *) (t.tet))[elemmarkerindex] |= 1;
2528 }
2529 
2531  ((int *) (t.tet))[elemmarkerindex] &= ~1;
2532 }
2533 
2535  return (((int *) (t.tet))[elemmarkerindex] & 1) != 0;
2536 }
2537 
2538 // marktest(), marktested(), unmarktest() -- primitives to flag or unflag a
2539 // tetrahedron. Use the second lowerest bit of the element marker.
2540 
2542  ((int *) (t.tet))[elemmarkerindex] |= 2;
2543 }
2544 
2546  ((int *) (t.tet))[elemmarkerindex] &= ~2;
2547 }
2548 
2550  return (((int *) (t.tet))[elemmarkerindex] & 2) != 0;
2551 }
2552 
2553 // markface(), unmarkface(), facemarked() -- primitives to flag or unflag a
2554 // face of a tetrahedron. From the last 3rd to 6th bits are used for
2555 // face markers, e.g., the last third bit corresponds to loc = 0.
2556 
2558  ((int *) (t.tet))[elemmarkerindex] |= (4 << (t.ver & 3));
2559 }
2560 
2562  ((int *) (t.tet))[elemmarkerindex] &= ~(4 << (t.ver & 3));
2563 }
2564 
2566  return (((int *) (t.tet))[elemmarkerindex] & (4 << (t.ver & 3))) != 0;
2567 }
2568 
2569 // markedge(), unmarkedge(), edgemarked() -- primitives to flag or unflag an
2570 // edge of a tetrahedron. From the last 7th to 12th bits are used for
2571 // edge markers, e.g., the last 7th bit corresponds to the 0th edge, etc.
2572 // Remark: The last 7th bit is marked by 2^6 = 64.
2573 
2575  ((int *) (t.tet))[elemmarkerindex] |= (int) (64 << ver2edge[(t).ver]);
2576 }
2577 
2579  ((int *) (t.tet))[elemmarkerindex] &= ~(int) (64 << ver2edge[(t).ver]);
2580 }
2581 
2583  return (((int *) (t.tet))[elemmarkerindex] &
2584  (int) (64 << ver2edge[(t).ver])) != 0;
2585 }
2586 
2587 // marktest2(), unmarktest2(), marktest2ed() -- primitives to flag and unflag
2588 // a tetrahedron. The 13th bit (2^12 = 4096) is used for this flag.
2589 
2591  ((int *) (t.tet))[elemmarkerindex] |= (int) (4096);
2592 }
2593 
2595  ((int *) (t.tet))[elemmarkerindex] &= ~(int) (4096);
2596 }
2597 
2599  return (((int *) (t.tet))[elemmarkerindex] & (int) (4096)) != 0;
2600 }
2601 
2602 // elemcounter(), setelemcounter() -- primitives to read or ser a (small)
2603 // integer counter in this tet. It is saved from the 16th bit. On 32 bit
2604 // system, the range of the counter is [0, 2^15 = 32768].
2605 
2607  return (((int *) (t.tet))[elemmarkerindex]) >> 16;
2608 }
2609 
2611  int c = ((int *) (t.tet))[elemmarkerindex];
2612  // Clear the old counter while keep the other flags.
2613  c &= 65535; // sum_{i=0^15} 2^i
2614  c |= (value << 16);
2615  ((int *) (t.tet))[elemmarkerindex] = c;
2616 }
2617 
2619  int c = elemcounter(t);
2620  setelemcounter(t, c + 1);
2621 }
2622 
2624  int c = elemcounter(t);
2625  setelemcounter(t, c - 1);
2626 }
2627 
2628 // ishulltet() tests if t is a hull tetrahedron.
2629 
2631  return (point) (t).tet[7] == dummypoint;
2632 }
2633 
2634 // isdeadtet() tests if t is a tetrahedron is dead.
2635 
2637  return ((t.tet == NULL) || (t.tet[4] == NULL));
2638 }
2639 
2641 // //
2642 // Primitives for subfaces and subsegments //
2643 // //
2645 
2646 // Each subface contains three pointers to its neighboring subfaces, with
2647 // edge versions. To save memory, both information are kept in a single
2648 // pointer. To make this possible, all subfaces are aligned to eight-byte
2649 // boundaries, so that the last three bits of each pointer are zeros. An
2650 // edge version (in the range 0 to 5) is compressed into the last three
2651 // bits of each pointer by 'sencode()'. 'sdecode()' decodes a pointer,
2652 // extracting an edge version and a pointer to the beginning of a subface.
2653 
2654 inline void tetgenmesh::sdecode(shellface sptr, face& s) {
2655  s.shver = (int) ((uintptr_t) (sptr) & (uintptr_t) 7);
2656  s.sh = (shellface *) ((uintptr_t) (sptr) ^ (uintptr_t) (s.shver));
2657 }
2658 
2660  return (shellface) ((uintptr_t) s.sh | (uintptr_t) s.shver);
2661 }
2662 
2664  return (shellface) ((uintptr_t) sh | (uintptr_t) shver);
2665 }
2666 
2667 // sbond() bonds two subfaces (s1) and (s2) together. s1 and s2 must refer
2668 // to the same edge. No requirement is needed on their orientations.
2669 
2670 inline void tetgenmesh::sbond(face& s1, face& s2)
2671 {
2672  s1.sh[s1.shver >> 1] = sencode(s2);
2673  s2.sh[s2.shver >> 1] = sencode(s1);
2674 }
2675 
2676 // sbond1() bonds s1 <== s2, i.e., after bonding, s1 is pointing to s2,
2677 // but s2 is not pointing to s1. s1 and s2 must refer to the same edge.
2678 // No requirement is needed on their orientations.
2679 
2681 {
2682  s1.sh[s1.shver >> 1] = sencode(s2);
2683 }
2684 
2685 // Dissolve a subface bond (from one side). Note that the other subface
2686 // will still think it's connected to this subface.
2687 
2689 {
2690  s.sh[s.shver >> 1] = NULL;
2691 }
2692 
2693 // spivot() finds the adjacent subface (s2) for a given subface (s1).
2694 // s1 and s2 share at the same edge.
2695 
2697 {
2698  shellface sptr = s1.sh[s1.shver >> 1];
2699  sdecode(sptr, s2);
2700 }
2701 
2703 {
2704  shellface sptr = s.sh[s.shver >> 1];
2705  sdecode(sptr, s);
2706 }
2707 
2708 // These primitives determine or set the origin, destination, or apex
2709 // of a subface with respect to the edge version.
2710 
2712 {
2713  return (point) s.sh[sorgpivot[s.shver]];
2714 }
2715 
2717 {
2718  return (point) s.sh[sdestpivot[s.shver]];
2719 }
2720 
2722 {
2723  return (point) s.sh[sapexpivot[s.shver]];
2724 }
2725 
2726 inline void tetgenmesh::setsorg(face& s, point pointptr)
2727 {
2728  s.sh[sorgpivot[s.shver]] = (shellface) pointptr;
2729 }
2730 
2731 inline void tetgenmesh::setsdest(face& s, point pointptr)
2732 {
2733  s.sh[sdestpivot[s.shver]] = (shellface) pointptr;
2734 }
2735 
2736 inline void tetgenmesh::setsapex(face& s, point pointptr)
2737 {
2738  s.sh[sapexpivot[s.shver]] = (shellface) pointptr;
2739 }
2740 
2741 #define setshvertices(s, pa, pb, pc)\
2742  setsorg(s, pa);\
2743  setsdest(s, pb);\
2744  setsapex(s, pc)
2745 
2746 // sesym() reserves the direction of the lead edge.
2747 
2748 inline void tetgenmesh::sesym(face& s1, face& s2)
2749 {
2750  s2.sh = s1.sh;
2751  s2.shver = (s1.shver ^ 1); // Inverse the last bit.
2752 }
2753 
2755 {
2756  s.shver ^= 1;
2757 }
2758 
2759 // senext() finds the next edge (counterclockwise) in the same orientation
2760 // of this face.
2761 
2763 {
2764  s2.sh = s1.sh;
2765  s2.shver = snextpivot[s1.shver];
2766 }
2767 
2769 {
2770  s.shver = snextpivot[s.shver];
2771 }
2772 
2774 {
2775  s2.sh = s1.sh;
2776  s2.shver = snextpivot[snextpivot[s1.shver]];
2777 }
2778 
2780 {
2781  s.shver = snextpivot[snextpivot[s.shver]];
2782 }
2783 
2784 
2785 // Check or set a subface's maximum area bound.
2786 
2788 {
2789  return ((REAL *) (s.sh))[areaboundindex];
2790 }
2791 
2793 {
2794  ((REAL *) (s.sh))[areaboundindex] = value;
2795 }
2796 
2797 // These two primitives read or set a shell marker. Shell markers are used
2798 // to hold user boundary information.
2799 
2801 {
2802  return ((int *) (s.sh))[shmarkindex];
2803 }
2804 
2806 {
2807  ((int *) (s.sh))[shmarkindex] = value;
2808 }
2809 
2810 
2811 
2812 // sinfect(), sinfected(), suninfect() -- primitives to flag or unflag a
2813 // subface. The last bit of ((int *) ((s).sh))[shmarkindex+1] is flagged.
2814 
2816 {
2817  ((int *) ((s).sh))[shmarkindex+1] =
2818  (((int *) ((s).sh))[shmarkindex+1] | (int) 1);
2819 }
2820 
2822 {
2823  ((int *) ((s).sh))[shmarkindex+1] =
2824  (((int *) ((s).sh))[shmarkindex+1] & ~(int) 1);
2825 }
2826 
2827 // Test a subface for viral infection.
2828 
2830 {
2831  return (((int *) ((s).sh))[shmarkindex+1] & (int) 1) != 0;
2832 }
2833 
2834 // smarktest(), smarktested(), sunmarktest() -- primitives to flag or unflag
2835 // a subface. The last 2nd bit of the integer is flagged.
2836 
2838 {
2839  ((int *) ((s).sh))[shmarkindex+1] =
2840  (((int *)((s).sh))[shmarkindex+1] | (int) 2);
2841 }
2842 
2844 {
2845  ((int *) ((s).sh))[shmarkindex+1] =
2846  (((int *)((s).sh))[shmarkindex+1] & ~(int)2);
2847 }
2848 
2850 {
2851  return ((((int *) ((s).sh))[shmarkindex+1] & (int) 2) != 0);
2852 }
2853 
2854 // smarktest2(), smarktest2ed(), sunmarktest2() -- primitives to flag or
2855 // unflag a subface. The last 3rd bit of the integer is flagged.
2856 
2858 {
2859  ((int *) ((s).sh))[shmarkindex+1] =
2860  (((int *)((s).sh))[shmarkindex+1] | (int) 4);
2861 }
2862 
2864 {
2865  ((int *) ((s).sh))[shmarkindex+1] =
2866  (((int *)((s).sh))[shmarkindex+1] & ~(int)4);
2867 }
2868 
2870 {
2871  return ((((int *) ((s).sh))[shmarkindex+1] & (int) 4) != 0);
2872 }
2873 
2874 // The last 4th bit of ((int *) ((s).sh))[shmarkindex+1] is flagged.
2875 
2877 {
2878  ((int *) ((s).sh))[shmarkindex+1] =
2879  (((int *)((s).sh))[shmarkindex+1] | (int) 8);
2880 }
2881 
2883 {
2884  ((int *) ((s).sh))[shmarkindex+1] =
2885  (((int *)((s).sh))[shmarkindex+1] & ~(int)8);
2886 }
2887 
2889 {
2890  return ((((int *) ((s).sh))[shmarkindex+1] & (int) 8) != 0);
2891 }
2892 
2893 
2894 // Each facet has a unique index (automatically indexed). Starting from '0'.
2895 // We save this index in the same field of the shell type.
2896 
2898 {
2899  ((int *) (s.sh))[shmarkindex + 2] = value;
2900 }
2901 
2903 {
2904  return ((int *) (s.sh))[shmarkindex + 2];
2905 }
2906 
2908 // //
2909 // Primitives for interacting between tetrahedra and subfaces //
2910 // //
2912 
2913 // tsbond() bond a tetrahedron (t) and a subface (s) together.
2914 // Note that t and s must be the same face and the same edge. Moreover,
2915 // t and s have the same orientation.
2916 // Since the edge number in t and in s can be any number in {0,1,2}. We bond
2917 // the edge in s which corresponds to t's 0th edge, and vice versa.
2918 
2920 {
2921  if ((t).tet[9] == NULL) {
2922  // Allocate space for this tet.
2923  (t).tet[9] = (tetrahedron) tet2subpool->alloc();
2924  // Initialize.
2925  for (int i = 0; i < 4; i++) {
2926  ((shellface *) (t).tet[9])[i] = NULL;
2927  }
2928  }
2929  // Bond t <== s.
2930  ((shellface *) (t).tet[9])[(t).ver & 3] =
2931  sencode2((s).sh, tsbondtbl[t.ver][s.shver]);
2932  // Bond s <== t.
2933  s.sh[9 + ((s).shver & 1)] =
2934  (shellface) encode2((t).tet, stbondtbl[t.ver][s.shver]);
2935 }
2936 
2937 // tspivot() finds a subface (s) abutting on the given tetrahdera (t).
2938 // Return s.sh = NULL if there is no subface at t. Otherwise, return
2939 // the subface s, and s and t must be at the same edge wth the same
2940 // orientation.
2941 
2943 {
2944  if ((t).tet[9] == NULL) {
2945  (s).sh = NULL;
2946  return;
2947  }
2948  // Get the attached subface s.
2949  sdecode(((shellface *) (t).tet[9])[(t).ver & 3], (s));
2950  (s).shver = tspivottbl[t.ver][s.shver];
2951 }
2952 
2953 // Quickly check if the handle (t, v) is a subface.
2954 #define issubface(t) \
2955  ((t).tet[9] && ((t).tet[9])[(t).ver & 3])
2956 
2957 // stpivot() finds a tetrahedron (t) abutting a given subface (s).
2958 // Return the t (if it exists) with the same edge and the same
2959 // orientation of s.
2960 
2962 {
2963  decode((tetrahedron) s.sh[9 + (s.shver & 1)], t);
2964  if ((t).tet == NULL) {
2965  return;
2966  }
2967  (t).ver = stpivottbl[t.ver][s.shver];
2968 }
2969 
2970 // Quickly check if this subface is attached to a tetrahedron.
2971 
2972 #define isshtet(s) \
2973  ((s).sh[9 + ((s).shver & 1)])
2974 
2975 // tsdissolve() dissolve a bond (from the tetrahedron side).
2976 
2978 {
2979  if ((t).tet[9] != NULL) {
2980  ((shellface *) (t).tet[9])[(t).ver & 3] = NULL;
2981  }
2982 }
2983 
2984 // stdissolve() dissolve a bond (from the subface side).
2985 
2987 {
2988  (s).sh[9] = NULL;
2989  (s).sh[10] = NULL;
2990 }
2991 
2993 // //
2994 // Primitives for interacting between subfaces and segments //
2995 // //
2997 
2998 // ssbond() bond a subface to a subsegment.
2999 
3000 inline void tetgenmesh::ssbond(face& s, face& edge)
3001 {
3002  s.sh[6 + (s.shver >> 1)] = sencode(edge);
3003  edge.sh[0] = sencode(s);
3004 }
3005 
3006 inline void tetgenmesh::ssbond1(face& s, face& edge)
3007 {
3008  s.sh[6 + (s.shver >> 1)] = sencode(edge);
3009  //edge.sh[0] = sencode(s);
3010 }
3011 
3012 // ssdisolve() dissolve a bond (from the subface side)
3013 
3015 {
3016  s.sh[6 + (s.shver >> 1)] = NULL;
3017 }
3018 
3019 // sspivot() finds a subsegment abutting a subface.
3020 
3021 inline void tetgenmesh::sspivot(face& s, face& edge)
3022 {
3023  sdecode((shellface) s.sh[6 + (s.shver >> 1)], edge);
3024 }
3025 
3026 // Quickly check if the edge is a subsegment.
3027 
3028 #define isshsubseg(s) \
3029  ((s).sh[6 + ((s).shver >> 1)])
3030 
3032 // //
3033 // Primitives for interacting between tetrahedra and segments //
3034 // //
3036 
3038 {
3039  if ((t).tet[8] == NULL) {
3040  // Allocate space for this tet.
3041  (t).tet[8] = (tetrahedron) tet2segpool->alloc();
3042  // Initialization.
3043  for (int i = 0; i < 6; i++) {
3044  ((shellface *) (t).tet[8])[i] = NULL;
3045  }
3046  }
3047  ((shellface *) (t).tet[8])[ver2edge[(t).ver]] = sencode((s));
3048 }
3049 
3051 {
3052  ((tetrahedron *) (s).sh)[9] = encode(t);
3053 }
3054 
3056 {
3057  if ((t).tet[8] != NULL) {
3058  ((shellface *) (t).tet[8])[ver2edge[(t).ver]] = NULL;
3059  }
3060 }
3061 
3063 {
3064  ((tetrahedron *) (s).sh)[9] = NULL;
3065 }
3066 
3068 {
3069  if ((t).tet[8] != NULL) {
3070  sdecode(((shellface *) (t).tet[8])[ver2edge[(t).ver]], s);
3071  } else {
3072  (s).sh = NULL;
3073  }
3074 }
3075 
3076 // Quickly check whether 't' is a segment or not.
3077 
3078 #define issubseg(t) \
3079  ((t).tet[8] && ((t).tet[8])[ver2edge[(t).ver]])
3080 
3082 {
3083  decode((tetrahedron) s.sh[9], t);
3084 }
3085 
3087 // //
3088 // Primitives for points //
3089 // //
3091 
3092 inline int tetgenmesh::pointmark(point pt) {
3093  return ((int *) (pt))[pointmarkindex];
3094 }
3095 
3096 inline void tetgenmesh::setpointmark(point pt, int value) {
3097  ((int *) (pt))[pointmarkindex] = value;
3098 }
3099 
3100 
3101 // These two primitives set and read the type of the point.
3102 
3104  return (enum verttype) (((int *) (pt))[pointmarkindex + 1] >> (int) 8);
3105 }
3106 
3108  ((int *) (pt))[pointmarkindex + 1] =
3109  ((int) value << 8) + (((int *) (pt))[pointmarkindex + 1] & (int) 255);
3110 }
3111 
3112 // Read and set the geometry tag of the point (used by -s option).
3113 
3115  return ((int *) (pt))[pointmarkindex + 2];
3116 }
3117 
3119  ((int *) (pt))[pointmarkindex + 2] = value;
3120 }
3121 
3122 // Read and set the u,v coordinates of the point (used by -s option).
3123 
3125  return pt[pointparamindex + i];
3126 }
3127 
3128 inline void tetgenmesh::setpointgeomuv(point pt, int i, REAL value) {
3129  pt[pointparamindex + i] = value;
3130 }
3131 
3132 // pinfect(), puninfect(), pinfected() -- primitives to flag or unflag
3133 // a point. The last bit of the integer '[pointindex+1]' is flagged.
3134 
3135 inline void tetgenmesh::pinfect(point pt) {
3136  ((int *) (pt))[pointmarkindex + 1] |= (int) 1;
3137 }
3138 
3139 inline void tetgenmesh::puninfect(point pt) {
3140  ((int *) (pt))[pointmarkindex + 1] &= ~(int) 1;
3141 }
3142 
3143 inline bool tetgenmesh::pinfected(point pt) {
3144  return (((int *) (pt))[pointmarkindex + 1] & (int) 1) != 0;
3145 }
3146 
3147 // pmarktest(), punmarktest(), pmarktested() -- more primitives to
3148 // flag or unflag a point.
3149 
3150 inline void tetgenmesh::pmarktest(point pt) {
3151  ((int *) (pt))[pointmarkindex + 1] |= (int) 2;
3152 }
3153 
3155  ((int *) (pt))[pointmarkindex + 1] &= ~(int) 2;
3156 }
3157 
3159  return (((int *) (pt))[pointmarkindex + 1] & (int) 2) != 0;
3160 }
3161 
3163  ((int *) (pt))[pointmarkindex + 1] |= (int) 4;
3164 }
3165 
3167  ((int *) (pt))[pointmarkindex + 1] &= ~(int) 4;
3168 }
3169 
3171  return (((int *) (pt))[pointmarkindex + 1] & (int) 4) != 0;
3172 }
3173 
3175  ((int *) (pt))[pointmarkindex + 1] |= (int) 8;
3176 }
3177 
3179  ((int *) (pt))[pointmarkindex + 1] &= ~(int) 8;
3180 }
3181 
3183  return (((int *) (pt))[pointmarkindex + 1] & (int) 8) != 0;
3184 }
3185 
3186 // These following primitives set and read a pointer to a tetrahedron
3187 // a subface/subsegment, a point, or a tet of background mesh.
3188 
3190  return ((tetrahedron *) (pt))[point2simindex];
3191 }
3192 
3194  ((tetrahedron *) (pt))[point2simindex] = value;
3195 }
3196 
3198  return (point) ((tetrahedron *) (pt))[point2simindex + 1];
3199 }
3200 
3202  ((tetrahedron *) (pt))[point2simindex + 1] = (tetrahedron) value;
3203 }
3204 
3206  return (shellface) ((tetrahedron *) (pt))[point2simindex + 2];
3207 }
3208 
3210  ((tetrahedron *) (pt))[point2simindex + 2] = (tetrahedron) value;
3211 }
3212 
3213 
3215  return ((tetrahedron *) (pt))[point2simindex + 3];
3216 }
3217 
3219  ((tetrahedron *) (pt))[point2simindex + 3] = value;
3220 }
3221 
3222 
3223 // The primitives for saving and getting the insertion radius.
3225 {
3226  pt[pointmtrindex + sizeoftensor - 1] = value;
3227 }
3228 
3230 {
3231  return pt[pointmtrindex + sizeoftensor - 1];
3232 }
3233 
3234 // point2tetorg() Get the tetrahedron whose origin is the point.
3235 
3236 inline void tetgenmesh::point2tetorg(point pa, triface& searchtet)
3237 {
3238  decode(point2tet(pa), searchtet);
3239  if ((point) searchtet.tet[4] == pa) {
3240  searchtet.ver = 11;
3241  } else if ((point) searchtet.tet[5] == pa) {
3242  searchtet.ver = 3;
3243  } else if ((point) searchtet.tet[6] == pa) {
3244  searchtet.ver = 7;
3245  } else {
3246  assert((point) searchtet.tet[7] == pa); // SELF_CHECK
3247  searchtet.ver = 0;
3248  }
3249 }
3250 
3251 // point2shorg() Get the subface/segment whose origin is the point.
3252 
3253 inline void tetgenmesh::point2shorg(point pa, face& searchsh)
3254 {
3255  sdecode(point2sh(pa), searchsh);
3256  if ((point) searchsh.sh[3] == pa) {
3257  searchsh.shver = 0;
3258  } else if ((point) searchsh.sh[4] == pa) {
3259  searchsh.shver = (searchsh.sh[5] != NULL ? 2 : 1);
3260  } else {
3261  assert((point) searchsh.sh[5] == pa); // SELF_CHECK
3262  searchsh.shver = 4;
3263  }
3264 }
3265 
3266 // farsorg() Return the origin of the subsegment.
3267 // farsdest() Return the destination of the subsegment.
3268 
3270 {
3271  face travesh, neighsh;
3272 
3273  travesh = s;
3274  while (1) {
3275  senext2(travesh, neighsh);
3276  spivotself(neighsh);
3277  if (neighsh.sh == NULL) break;
3278  if (sorg(neighsh) != sorg(travesh)) sesymself(neighsh);
3279  senext2(neighsh, travesh);
3280  }
3281  return sorg(travesh);
3282 }
3283 
3285 {
3286  face travesh, neighsh;
3287 
3288  travesh = s;
3289  while (1) {
3290  senext(travesh, neighsh);
3291  spivotself(neighsh);
3292  if (neighsh.sh == NULL) break;
3293  if (sdest(neighsh) != sdest(travesh)) sesymself(neighsh);
3294  senext(neighsh, travesh);
3295  }
3296  return sdest(travesh);
3297 }
3298 
3300 // //
3301 // Linear algebra operators. //
3302 // //
3304 
3305 // dot() returns the dot product: v1 dot v2.
3307 {
3308  return v1[0] * v2[0] + v1[1] * v2[1] + v1[2] * v2[2];
3309 }
3310 
3311 // cross() computes the cross product: n = v1 cross v2.
3312 inline void tetgenmesh::cross(REAL* v1, REAL* v2, REAL* n)
3313 {
3314  n[0] = v1[1] * v2[2] - v2[1] * v1[2];
3315  n[1] = -(v1[0] * v2[2] - v2[0] * v1[2]);
3316  n[2] = v1[0] * v2[1] - v2[0] * v1[1];
3317 }
3318 
3319 // distance() computes the Euclidean distance between two points.
3321 {
3322  return sqrt((p2[0] - p1[0]) * (p2[0] - p1[0]) +
3323  (p2[1] - p1[1]) * (p2[1] - p1[1]) +
3324  (p2[2] - p1[2]) * (p2[2] - p1[2]));
3325 }
3326 
3328 {
3329  return (x) * (x) + (y) * (y) + (z) * (z);
3330 }
3331 
3332 
3333 #endif // #ifndef tetgenH
3334