Debian Codegraph @

tools/physicalModeling/mesh2faust/vega/libraries/mesher/delaunayMesher.cpp

raw symbols SCIP
1 /*************************************************************************
2 * *
3 * Vega FEM Simulation Library Version 3.1 *
4 * *
5 * "mesher" library , Copyright (C) 2016 USC *
6 * All rights reserved. *
7 * *
8 * Code authors: Danyong Zhao, Yijing Li, Jernej Barbic *
9 * http://www.jernejbarbic.com/code *
10 * *
11 * Funding: National Science Foundation *
12 * *
13 * This library is free software; you can redistribute it and/or *
14 * modify it under the terms of the BSD-style license that is *
15 * included with this library in the file LICENSE.txt *
16 * *
17 * This library is distributed in the hope that it will be useful, *
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the file *
20 * LICENSE.TXT for more details. *
21 * *
22 *************************************************************************/
23
24 #include <algorithm>
25 #include <queue>
26 #include <iostream>
27 #include <cassert>
28 #include <cmath>
29
30 using namespace std;
31
32 #include "delaunayMesher.h"
33 #include "mat3d.h"
34 #include "windingNumber.h"
35 #include "verticesQueryFiltered.h"
36
37 static vector<bool> * processed;
38
39 DelaunayMesher::DelaunayMesher()
40 {
41 //total = 0;
42 query = NULL;
43 computeVEdgeModification = false;
44 queryType = Query::DOUBLE;
45 boundaryMesh = NULL;
46 boundaryOctree = NULL;
47 nextBallLabel = 0;
48 }
49
50 DelaunayMesher::~DelaunayMesher()
51 {
52 clear();
53 }
54
55 void DelaunayMesher::clear()
56 {
57 for (BallIter itr = ballsToDelete.begin(); itr != ballsToDelete.end(); itr++)
58 delete *itr;
59 ballsToDelete.clear();
60 for (BallIter itr = balls.begin(); itr != balls.end(); itr++)
61 delete *itr;
62 balls.clear();
63 ballsAdded.clear(); // this is a subset of "balls", so no need to do a separate clearing for loop for it
64 delete query;
65 query = NULL;
66 epsilon = 0.0;
67 inputVertices.clear();
68 queryType = Query::DOUBLE;
69 vEdgeDeleted.clear();
70 vEdgeAdded.clear();
71
72 delete boundaryMesh;
73 boundaryMesh = NULL;
74 delete boundaryOctree;
75 boundaryOctree = NULL;
76
77 verticesSet.clear();
78 // boundaryTriangles.clear();
79 }
80
81 //Warning: the first 4 vertices should not be coplanar to allow successful construction
82 bool DelaunayMesher::computeDelaunayTetrahedralization(const std::vector<Vec3d> & vertices, double ep, Query::Type qt)
83 {
84 const bool useInfo = true;
85 if (vertices.size() < 4 || ep < 0.0)
86 return false;
87 // clear internal data first
88 clear();
89
90 // remove duplicate vertices
91 vector<Vec3d> uniqueVertices;
92 for (size_t i = 0; i < vertices.size(); i++)
93 {
94 const Vec3d & v = vertices[i];
95 if (verticesSet.find(v) == verticesSet.end())
96 {
97 verticesSet.insert(v);
98 uniqueVertices.push_back(v);
99 }
100 }
101 if (uniqueVertices.size() != vertices.size())
102 {
103 size_t num = vertices.size() - uniqueVertices.size();
104 cout << "Remove " << num << " duplicate " << (num > 1 ? "vertices" : "vertex") << " in DelaunayMesher." << endl;
105 }
106
107 if (uniqueVertices.size() < 4)
108 {
109 cout << "Unique vertices < 4. Cannot generate Delaunay mesh." << endl;
110 return false;
111 }
112
113 int numVertices = uniqueVertices.size();
114 epsilon = ep;
115 queryType = qt;
116
117 inputVertices.resize(uniqueVertices.size());
118 vertex2ball.resize(uniqueVertices.size());
119 for (int i = 0; i < numVertices; i++)
120 inputVertices[i] = uniqueVertices[i];
121
122 buildQuery();
123
124 VerticesQuery::Information info;
125 if (useInfo)
126 {
127 query->getInformation(epsilon, info);
128 if (info.dimension != 3)
129 {
130 cout << "Delaunay input dimension is not 3 but " << info.dimension << endl;
131 return false;
132 }
133 if (!info.extremeCCW)
134 swap(info.extreme[2], info.extreme[3]);
135 }
136 else
137 {
138 }
139 // Insert the (nondegenerate) tetrahedron constructed by the call to
140 // GetInformation. This is necessary for the circumsphere-visibility
141 // algorithm to work correctly.
142 if (initialize(info.extreme[0], info.extreme[1], info.extreme[2], info.extreme[3]) == false)
143 {
144 cout << "Failed to initialize Delaunay" << endl;
145 return false;
146 }
147
148 // Incrementally update the tetrahedralization. The set of processed
149 // points is maintained to eliminate duplicates, either in the original
150 // input points or in the points obtained by snap rounding.
151 vector <bool> processed(numVertices, false);
152 for (int i = 0; i < 4; ++i)
153 processed[info.extreme[i]] = true;
154
155 bool computeVEdge = computeVEdgeModification;
156 computeVEdgeModification = false; // shut down VEdge computation in the loop below
157 for (int i = 0; i < numVertices; ++i)
158 {
159 if (processed[i] == false)
160 {
161 for (BallIter itr = getBallToDeleteSetBegin(); itr != getBallToDeletelSetEnd(); itr++)
162 delete *itr;
163 ballsToDelete.clear();
164 update(i);
165 processed[i] = true;
166 }
167 }
168
169
170 computeVEdgeModification = computeVEdge;
171 if (computeVEdgeModification)
172 {
173 vEdgeAdded.clear();
174 vEdgeDeleted.clear();
175 for (BallIter it = balls.begin(); it != balls.end(); it++)
176 {
177 DelaunayBall * ball = *it;
178 for (int j = 0; j < 4; j++)
179 {
180 UTriKey face = ball->uFaceKey(j);
181 if (DelaunayBall::isFaceRegular(face) == false)
182 continue; // we don't consider infinite face as Voronoi edge
183 VEdgeIter vit = vEdgeAdded.find(face);
184 if (vit == vEdgeAdded.end())
185 vEdgeAdded[face] = ball->getVoronoiEdge(j);
186 }
187 }
188 }
189
190 // cout << balls.size() << " balls inside Delaunay"<< endl;
191
192 return true;
193 }
194
195 bool DelaunayMesher::addOnePoint(const Vec3d & p)
196 {
197
198 if (computeVEdgeModification)
199 {
200 vEdgeAdded.clear();
201 vEdgeDeleted.clear();
202 }
203
204 for (BallIter itr = getBallToDeleteSetBegin(); itr != getBallToDeletelSetEnd(); itr++)
205 delete *itr;
206 ballsToDelete.clear();
207 ballsAdded.clear();
208
209 if (verticesSet.insert(p).second == false) // insertion failure. P is already in verticesSet
210 return false;
211
212 if (boundaryOctree && boundaryMesh)
213 {
214 // for CDT
215 if (fabs(WindingNumber::computeWindingNumber(boundaryMesh, p)) < 0.5)
216 return false;
217 }
218
219 int index = inputVertices.size();
220 inputVertices.push_back(p);
221 vertex2ball.push_back(NULL);
222
223 query->addVertex(p);
224
225 return update(index);
226 }
227
228 bool DelaunayMesher::update(int newVtxInd)
229 {
230 // find balls containing the newly added point; these balls will be deleted
231 if (ballsToDelete.empty())
232 {
233 if (boundaryOctree == NULL)
234 getBallsContainingPoint(newVtxInd, ballsToDelete);
235 else
236 {
237 Vec3d p = inputVertices[newVtxInd];
238 for (BallIter it = balls.begin(); it != balls.end(); it++)
239 {
240 DelaunayBall * ball = *it;
241 if (ball->isInfinite())
242 continue; // infinite ball will never be erased in CDT
243 if (ball->contain(p) <= 0 && ball->visibleTo(p)) // if the point is visible to the ball
244 ballsToDelete.insert(ball);
245 }
246 }
247 }
248
249 if (ballsToDelete.empty())
250 return false;
251
252 // because some balls (tets) are deleted, some faces of their neighbors are exposed
253 // those exposed faces form a polygon (the boundary of the "cavity")
254 // build the exposed faces
255 //faces are stored by giving the three integer indices of the vertices of the triangle, and the two neighboring balls (one is the deleted one, the other will not be deleted as it is outside of the cavity)
256 vector<pair<OTriKey, pair<DelaunayBall *, DelaunayBall *> > > exposedFaces;
257 // note: there is no particular reason for going backwards here
258 for (BallSet::reverse_iterator iter = ballsToDelete.rbegin(); iter != ballsToDelete.rend(); iter++)
259 {
260 DelaunayBall * ball = *iter;
261 //const int *v = ball.getVertex();
262 //printf("Delete %d %d %d %d\n", v[0] + 1, v[1] + 1, v[2] + 1, v[3] + 1);
263 for (int j = 0; j < 4; j++)
264 {
265 OTriKey face = ball->oFaceKey(j); // this face has orientation pointing outside the tet
266 DelaunayBall * neighborBall = ball->nbr[j];
267 if (ballsToDelete.find(neighborBall) == ballsToDelete.end()) // if neighbor is not in deleted balls
268 {
269 pair<OTriKey, pair<DelaunayBall *, DelaunayBall *> > exposedFace(face, pair<DelaunayBall *, DelaunayBall *>(neighborBall, ball));
270 exposedFaces.push_back(exposedFace);
271 }
272
273 if (computeVEdgeModification && DelaunayBall::isFaceRegular(face))
274 {
275 UTriKey uface = ball->uFaceKey(j);
276 if (vEdgeDeleted.find(uface) == vEdgeDeleted.end())
277 vEdgeDeleted[uface] = ball->getVoronoiEdge(j);
278 }
279 }
280 //ball.faces.clear();
281 }
282
283 //this map is used to assist finding neighbors for the new balls
284 map<UTriKey, DelaunayBall *> neighboringStructure;
285
286 ballsAdded.clear();
287 // add new balls connecting the new point and the exposed faces
288 for (size_t i = 0; i < exposedFaces.size(); i++)
289 {
290 OTriKey & face = exposedFaces[i].first; // this face points outside the deleted polyhedron
291 DelaunayBall * neighborBall = exposedFaces[i].second.first;
292 DelaunayBall * deletedBall = exposedFaces[i].second.second; // the deleted ball
293 // printf("Patching %d %d %d\n", face.v[0], face.v[1], face.v[2]);
294 // create the new ball, this ball has the correct orientation
295 DelaunayBall * ball = createBall(newVtxInd, face[0], face[1], face[2]);
296
297 if (ball->isRegular() == false) // an infinite ball. This means that face.third < 0, and face.first and face.second give the edge that is on the boundary of the cavity
298 {
299 const int * v = deletedBall->getInfiniteBallTriangle(); //The indices v[0],v[1],v[2] of an infinite ball give the triangle that this ball represents
300 int otherVtx = v[0] ^ v[1] ^ v[2] ^ face[1] ^ face[2]; // xor
301 //printf("Addition %d\n", otherVtx);
302 if ((otherVtx != v[0]) && (otherVtx != v[1]) && (otherVtx != v[2]))
303 // this should never happen
304 return false;
305 // assert (ball->contains(otherVtx) != 1); // a vtx of the deleted ball should not be inside the new ball. This means that the normal of the new ball is incorrect
306 }
307 else
308 {
309 vertex2ball[face[0]] = ball;
310 vertex2ball[face[1]] = ball;
311 vertex2ball[face[2]] = ball;
312 }
313 // build neighboring structure for the new ball
314 UTriKey uface(face[0], face[1], face[2]);
315 int nbrind = ball->getNeighborIndex(uface);
316 assert(nbrind >= 0);
317 ball->nbr[nbrind] = neighborBall;
318 nbrind = neighborBall->getNeighborIndex(uface);
319 assert(nbrind >= 0);
320 neighborBall->nbr[nbrind] = ball;
321 if (computeVEdgeModification && DelaunayBall::isFaceRegular(uface))
322 vEdgeAdded[uface] = neighborBall->getVoronoiEdge(nbrind);
323
324 buildNeighbor(newVtxInd, face[1], face[2], ball, neighboringStructure);
325 buildNeighbor(newVtxInd, face[0], face[2], ball, neighboringStructure);
326 buildNeighbor(newVtxInd, face[1], face[0], ball, neighboringStructure);
327
328 //printf("Inserting ball: %d %d %d %d\n", ball->v[0], ball->v[1], ball->v[2], ball->v[3]);
329 // cout << "inserting " << *ball << endl;
330 balls.insert(ball);
331 ballsAdded.insert(ball);
332 }
333
334 //int tail = balls.size();
335 for (BallSet::iterator itr = ballsToDelete.begin(); itr != ballsToDelete.end(); itr++)
336 balls.erase(*itr);
337
338 vertex2ball[newVtxInd] = *ballsAdded.begin();
339 if (neighboringStructure.size() != 0) //error here
340 {
341 printf("Neighbor structure error\n");
342 return false;
343 }
344 return true;
345 }
346
347 void DelaunayMesher::getBallsContainingPoint(int vtx, BallSet & containingBalls)
348 {
349 containingBalls.clear();
350 // first, get one that contains the given point
351 DelaunayBall * ball = getOneBallContainingPoint(vtx);
352 BallSet unknown;
353 if (ball)
354 {
355 // search for its neighboring tets to go over all the balls that contains the point
356 BallSet candidates;
357 candidates.insert(ball);
358 while (candidates.size() > 0)
359 {
360 DelaunayBall * ball = *candidates.begin();
361 candidates.erase(candidates.begin());
362
363 for (int j = 0; j < 4; j++)
364 {
365 DelaunayBall * adj = ball->nbr[j];
366 if (adj && candidates.find(adj) == candidates.end() && containingBalls.find(adj) == containingBalls.end())
367 {
368 int loc = adj->contains(vtx);
369 if (loc < 0) // adj contains vtx
370 candidates.insert(adj);
371 else if (loc == 0)
372 {
373 assert(adj->isInfinite());
374 unknown.insert(adj);
375 }
376 }
377 }
378 //if (ball->label == 120)
379 //cout << ball->contains(vtx) << ball->getPosition(1) << ball->getPosition(2) << ball->getPosition(3) << endl;
380 containingBalls.insert(ball);
381 }
382 }
383 else
384 cout << "Error: no balls contain the input point: " << vtx << " " << inputVertices[vtx] << endl;
385 for (BallCIter itr = unknown.begin(); itr != unknown.end(); itr++)
386 if (containingBalls.find((*itr)->nbr[0]) != containingBalls.end())
387 containingBalls.insert(*itr);
388 return;
389 }
390
391 DelaunayMesher::DelaunayBall * DelaunayMesher::getOneBallContainingPoint(int vtx)
392 {
393 // find a regular ball to begin searching
394 DelaunayBall * ball = *balls.begin();
395 if (ball->isInfinite())
396 {
397 // infinite ball must have a regular neighbor
398 for (int i = 0; i < 4; i++)
399 if (ball->nbr[i]->isRegular())
400 {
401 ball = ball->nbr[i];
402 break;
403 }
404 }
405
406 size_t numTet = balls.size();
407 for (size_t i = 0; i < numTet; i++)
408 {
409 assert(ball->isRegular());
410 int j = 0;
411 for (j = 0; j < 4; j++)
412 {
413 OTriKey face = ball->oFaceKey(j);
414 if (query->toPlane(vtx, face[0], face[1], face[2]) > 0)
415 {
416 // vtx sees face <v0,v1,v2> from outside the tetrahedron.
417 DelaunayBall * nbrBall = ball->nbr[j];
418 ball = nbrBall;
419 if (nbrBall->isRegular()) // tetra has adjacent tet on that face
420 break; // Traverse to the tetrahedron sharing the face.
421 else
422 return ball; // We reached a surface face, so the point is outside the hull
423 }
424 }
425
426 if (j == 4)
427 return ball; // The point is inside all four faces, so the point is inside a tetrahedron.
428 }
429 // this should never be reached
430 return NULL;
431 }
432
433 // use neighboringStructure to connect ball with its neighbors
434 int DelaunayMesher::buildNeighbor(const UTriKey & face, DelaunayBall * ball, map<UTriKey, DelaunayBall *> & neighboringStructure)
435 {
436 map<UTriKey, DelaunayBall *>::iterator itr = neighboringStructure.find(face);
437 if (itr == neighboringStructure.end())
438 {
439 neighboringStructure[face] = ball;
440 return 1;
441 }
442 else
443 {
444 DelaunayBall * nbrBall = itr->second;
445 int nbrind = nbrBall->getNeighborIndex(face);
446 assert(nbrind >= 0);
447 nbrBall->nbr[nbrind] = ball;
448 nbrind = ball->getNeighborIndex(face);
449 ball->nbr[nbrind] = nbrBall;
450 neighboringStructure.erase(itr);
451 if (computeVEdgeModification && DelaunayBall::isFaceRegular(face))
452 vEdgeAdded[face] = ball->getVoronoiEdge(nbrind);
453 return 0;
454 }
455 }
456
457 bool DelaunayMesher::initialize(int v0, int v1, int v2, int v3)
458 {
459 Vec3d a = inputVertices[v0];
460 Vec3d b = inputVertices[v1];
461 Vec3d c = inputVertices[v2];
462 Vec3d d = inputVertices[v3];
463 double volume = dot(b - a, cross(c - a, d - a)); //compute volume
464 if (volume <= 0)
465 return false;
466
467 DelaunayBall * ball0 = NULL, *ball1 = NULL, *ball2 = NULL, *ball3 = NULL, *ball4 = NULL;
468
469 ball0 = createBall(v0, v1, v2, v3); // form a regular ball
470 ball1 = createBall(-1, v0, v1, v2);
471 ball2 = createBall(-1, v0, v3, v1);
472 ball3 = createBall(-1, v0, v2, v3);
473 ball4 = createBall(-1, v1, v3, v2);
474
475 balls.insert(ball0);
476 balls.insert(ball1);
477 balls.insert(ball2);
478 balls.insert(ball3);
479 balls.insert(ball4);
480
481 assert(ball0->getNeighborIndex(UTriKey(v0, v1, v2)) >= 0);
482
483 // build neighboring structure
484 #define ASSIGN_NEIGHBOR(a, b, v0, v1, v2) do { \
485 a->nbr[a->getNeighborIndex(UTriKey(v0,v1,v2))] = b; \
486 b->nbr[b->getNeighborIndex(UTriKey(v0,v1,v2))] = a; } while(0)
487
488 ASSIGN_NEIGHBOR(ball0, ball1, v0, v1, v2);
489 // ball0->nbr[ball0->getNeighborIndex(UTriKey(v0,v1,v2))] = ball1;
490 ASSIGN_NEIGHBOR(ball0, ball2, v0, v3, v1);
491 ASSIGN_NEIGHBOR(ball0, ball3, v0, v2, v3);
492 ASSIGN_NEIGHBOR(ball0, ball4, v1, v3, v2);
493 ASSIGN_NEIGHBOR(ball1, ball2, -1, v0, v1);
494 ASSIGN_NEIGHBOR(ball1, ball3, -1, v0, v2);
495 ASSIGN_NEIGHBOR(ball1, ball4, -1, v1, v2);
496 ASSIGN_NEIGHBOR(ball2, ball3, -1, v0, v3);
497 ASSIGN_NEIGHBOR(ball2, ball4, -1, v1, v3);
498 ASSIGN_NEIGHBOR(ball3, ball4, -1, v2, v3);
499 assert(ball0->nbr[0] != NULL);
500 vertex2ball[v0] = ball0;
501 vertex2ball[v1] = ball0;
502 vertex2ball[v2] = ball0;
503 vertex2ball[v3] = ball0;
504 return true;
505 }
506
507 TetMesh * DelaunayMesher::getMesh() const
508 {
509 // return NULL;
510 vector<int> ele;
511 // cout << "Building mesh: " << endl;
512 for (set<DelaunayBall *, DelaunayBallCompare>::const_iterator i = balls.begin(); i != balls.end(); i++)
513 {
514 DelaunayBall * ball = *i;
515 if (ball->isRegular())
516 {
517 const int * vtx = ball->v;
518 for (int k = 0; k < 4; k++)
519 ele.push_back(vtx[k]);
520 // cout << *ball << endl;
521 }
522 }
523 vector<double> vertices(3 * inputVertices.size());
524 for (unsigned int i = 0; i < inputVertices.size(); i++)
525 inputVertices[i].convertToArray(&vertices[i * 3]);
526 //printf("%d\n", ele.size());
527 return new TetMesh(inputVertices.size(), &vertices[0], ele.size() / 4, &ele[0]);
528 }
529
530 void DelaunayMesher::buildQuery()
531 {
532 if (queryType != Query::RATIONAL && queryType != Query::FILTERED)
533 {
534 // No scaling for floating point.
535 query = new VerticesQuery(inputVertices.size(), inputVertices.data());
536 //cout << "Using floating point precision" << endl;
537 }
538 else if (queryType == Query::RATIONAL)
539 {
540 query = new VerticesQueryRational(inputVertices.size(), inputVertices.data());
541 //cout << "Using exact precision" << endl;
542 }
543 else
544 {
545 query = new VerticesQueryFiltered(inputVertices.size(), inputVertices.data(), epsilon);
546 //cout << "Using filtered precision with epsilon " << epsilon << endl;
547 }
548 }
549
550 // Constructor assumes that the incoming vtx has correct orientation
551 // Regular ball: v3 is on the positive side of plane(v0, v1, v2)
552 // Infinite ball: Other vertices on the positive side of (v1, v2, v3)
553 DelaunayMesher::DelaunayBall::DelaunayBall(int v0, int v1, int v2, int v3, DelaunayMesher * p, label_t l)
554 : OTetKey(v0, v1, v2, v3), parent(*p), label(l)
555 {
556 // const double DEGENERATE_RADIUS = 1e10;
557
558 memset(nbr, 0, sizeof(nbr));
559
560 Vec3d p1 = parent.inputVertices[v[1]];
561 Vec3d p2 = parent.inputVertices[v[2]];
562 Vec3d p3 = parent.inputVertices[v[3]];
563
564 if (v[0] >= 0) //regular ball
565 {
566 Vec3d p0 = parent.inputVertices[v[0]];
567 // double vol = TetMesh::getTetVolume(&p0,&p1,&p2,&p3);
568 // if (vol < 1e-10)
569 // cout << "problem: tet volume too small: " << vol << endl;
570
571 center = parent.circumcenter(p0, p1, p2, p3);
572 }
573 else
574 {
575 }
576 }
577
578 int DelaunayMesher::DelaunayBall::getNeighborIndex(const UTriKey & key) const
579 {
580 for (int i = 0; i < 4; i++)
581 {
582 UTriKey uface = uFaceKey(i);
583 if (uface == key)
584 return i;
585 }
586 return -1;
587 }
588
589 int DelaunayMesher::DelaunayBall::getNeighborIndex(const OTriKey & key) const
590 {
591 for (int i = 0; i < 4; i++)
592 {
593 OTriKey oface = oFaceKey(i);
594 if (oface == key)
595 return i;
596 }
597 return -1;
598 }
599
600 void DelaunayMesher::DelaunayBall::setNeighbor(const UTriKey & key, DelaunayBall * nbrBall)
601 {
602 int ind = getNeighborIndex(key);
603 if (ind >= 0)
604 nbr[ind] = nbrBall;
605 }
606
607 //return value:
608 //1 means that the point is outside the ball
609 //0 means that the point is on the ball
610 //-1 means that the point is inside the ball
611 int DelaunayMesher::DelaunayBall::contains(int newVtx) const
612 {
613 int result = 0;
614 if (isRegular())
615 {
616 int query = parent.query->toCircumsphere(newVtx, v[0], v[1], v[2], v[3]);
617 if (query)
618 return query;
619 int tmpVtx[5];
620 memcpy(tmpVtx, v, sizeof(v[0]) * 4);
621 tmpVtx[4] = newVtx;
622
623 //Using buble sort
624 int numSwaps = 0; // Record the total number of swaps.
625
626 for (int i = 0; i < 5; i++)
627 for (int j = 4; j > i; j--)
628 if (tmpVtx[j] < tmpVtx[j - 1])
629 {
630 numSwaps++;
631 swap(tmpVtx[j], tmpVtx[j - 1]);
632 }
633
634 int oriA = parent.query->toPlane(tmpVtx[4], tmpVtx[1], tmpVtx[2], tmpVtx[3]);
635 if (oriA != 0)
636 return (numSwaps & 1? oriA: -oriA);
637
638 int oriB = -parent.query->toPlane(tmpVtx[4], tmpVtx[0], tmpVtx[2], tmpVtx[3]);
639 // Flip the sign if there are odd number of swaps.
640 if (!oriB)
641 {
642 cout << *this << newVtx << endl;
643 cout << parent.inputVertices[v[0]] << parent.inputVertices[v[1]] << parent.inputVertices[v[2]] << parent.inputVertices[v[3]] << parent.inputVertices[newVtx] << endl;
644 cout << query << " " << oriA << " " << oriB << endl;
645 exit(-9);
646 }
647 return (numSwaps & 1? oriB: -oriB);
648 }
649 else
650 {
651 const int * vtx = getInfiniteBallTriangle();
652 // ret = +1: point outside infinite ball
653 // ret = -1: point inside infinite ball
654 result = parent.query->toPlane(newVtx, vtx[0], vtx[1], vtx[2]);
655 return result;
656 if (result == 0)
657 {
658 // For infinite ball, the matters are more complicated when the point is on the plane of the boundary triangle
659 // In this case, we further test whether the point is inside the circumcircle of the triangle on that plane
660 result = parent.query->toCircumsphere(newVtx, vtx[0], vtx[1], vtx[2]);
661 return result;
662 }
663 }
664 return result;
665 }
666
667 int DelaunayMesher::DelaunayBall::contain(const Vec3d & p) const
668 {
669 int result = 0;
670 if (isRegular())
671 return parent.query->toCircumsphere(p, v[0], v[1], v[2], v[3]);
672 else
673 {
674 const int * vtx = getInfiniteBallTriangle();
675 result = parent.query->toPlane(p, vtx[0], vtx[1], vtx[2]);
676 if (!result)
677 return result; // Not on the plane
678 // If on the plane, check whether it is inside the circumcircle
679 return parent.query->toCircumsphere(p, vtx[0], vtx[1], vtx[2]);
680 }
681 }
682
683 bool DelaunayMesher::DelaunayBall::visibleTo(const Vec3d & p) const
684 {
685 if (parent.boundaryOctree == NULL)
686 return true;
687 vector<TriangleBasic*> triangles;
688 if (isRegular())
689 {
690 for (unsigned int j = 0; j < 4; j++)
691 {
692 Vec3d vtx = parent.inputVertices[v[j]];
693 parent.boundaryOctree->lineSegmentIntersection(triangles, p, vtx + (p - vtx) * 1e-10);
694 if (triangles.empty() == false)
695 return false;
696 }
697 }
698 else // infinity ball case:
699 return false; //in CDT, the boundary can't be removed
700 return true;
701 }
702
703 // vertices a, b, c, d have the same distance to circumcenter
704 // so the circumcenter lies on the perpendicular plane for each edge of the tet
705 // for edge (ab), the equation for this perpendicular plane is: dot((b - a), (x,y,z)) = dot((b - a), (a+b)/2)
706 // Form a 3x3 linear systemn with three equations for three edges (ab, ac, ad)
707 Vec3d DelaunayMesher::circumcenter(const Vec3d & a, const Vec3d & b, const Vec3d & c, const Vec3d & d)
708 {
709 Vec3d n1 = b - a;
710 Vec3d n2 = c - a;
711 Vec3d n3 = d - a;
712
713 #ifdef USE_MAT3D
714 Mat3d mat(n1,n2,n3); //system matrix
715 Vec3d rhs = Vec3d(dot(n1, (a + b)), dot(n2, (a + c)), dot(n3, (a + d))) / 2.;
716 return inv(mat) * rhs;
717 #else
718 // Cramer rule for solving linear equations
719 Vec3d rhs = Vec3d(dot(n1, (a + b)), dot(n2, (a + c)), dot(n3, (a + d)));
720 Vec3d _a = Vec3d(n1[0], n2[0], n3[0]);
721 Vec3d _b = Vec3d(n1[1], n2[1], n3[1]);
722 Vec3d _c = Vec3d(n1[2], n2[2], n3[2]);
723
724 double _w = det(_a, _b, _c) * 2;
725 Vec3d ret = Vec3d(det(rhs, _b, _c), det(_a, rhs, _c), det(_a, _b, rhs)) / _w;
726 return ret;
727 #endif
728 }
729
730 bool DelaunayMesher::checkDelaunay() const
731 {
732 cout << "Checking delaunay " << endl;
733 for (BallIter it = balls.begin(); it != balls.end(); it++)
734 {
735 // cout << "check ball " << count << endl;
736 DelaunayBall * ball = *it;
737 for (size_t i = 0; i < inputVertices.size(); i++)
738 {
739 if (!processed->at(i)) continue;
740 int j = i;
741 const int * v = ball->getVertices();
742 if (j == v[0] || j == v[1] || j == v[2] || j == v[3])
743 continue;
744
745 if (ball->contains(j) == -1) //point is inside the ball
746 {
747 cout << "point " << j << " " << inputVertices[j] << " is inside ball: ";
748 if (ball->isRegular())
749 {
750 cout << " center: " << ball->center << ", r=" << len(ball->getPosition(v[0]) - ball->center) << " length from point to center: " << len(inputVertices[j] - ball->center) << endl;
751 cout << "regular ball " << *ball << endl;
752 }
753 else
754 {
755 cout << "Infinite " << ball->v[1] << inputVertices[ball->v[1]] << " " << ball->v[2] << inputVertices[ball->v[2]] << " " << ball->v[3] << inputVertices[ball->v[3]] << endl;
756 }
757 return false;
758 }
759 }
760 }
761 return true;
762 }
763
764 Vec3d DelaunayMesher::getFaceNormal(const OTriKey & face) const
765 {
766 const Vec3d & v0 = inputVertices[face[0]];
767 const Vec3d & v1 = inputVertices[face[1]];
768 const Vec3d v2 = inputVertices[face[2]];
769 return norm(cross(v1 - v0, v2 - v0));
770 }
771
772 DelaunayMesher::VoronoiEdge::VoronoiEdge(bool isFinite, const Vec3d & s, const Vec3d & other) : finite(isFinite), start(s)
773 {
774 if (isFinite)
775 {
776 end = other;
777 direction = Vec3d(0.0);
778 }
779 else
780 {
781 direction = other;
782 end = Vec3d(0.0);
783 }
784 }
785
786 DelaunayMesher::VoronoiEdge DelaunayMesher::DelaunayBall::getVoronoiEdge(int faceIndex) const
787 {
788 VoronoiEdge vedge;
789 UTriKey uface = uFaceKey(faceIndex);
790 assert(isFaceRegular(uface));
791 const DelaunayBall * nbrBall = nbr[faceIndex];
792 assert(nbrBall);
793 if (isRegular() && nbrBall->isRegular())
794 {
795 vedge.finite = true;
796 vedge.start = center;
797 vedge.end = nbrBall->center;
798 }
799 else
800 {
801 vedge.finite = false;
802 OTriKey oface = oFaceKey(faceIndex);
803 if (isRegular() == false)
804 {
805 assert(nbrBall->isRegular());
806 vedge.start = nbrBall->center;
807 vedge.direction = (-1) * parent.getFaceNormal(oface);
808 }
809 else
810 {
811 vedge.start = center;
812 vedge.direction = parent.getFaceNormal(oface);
813 }
814 }
815 //assert(vedge.end.hasNaN() == false);
816 //assert(vedge.direction.hasNaN() == false);
817 return vedge;
818 }
819
820 bool DelaunayMesher::initializeCDT(TetMesh * inputMesh, double ep, Query::Type qt)
821 {
822 // clean previous data
823 clear();
824 TetMesh tetMesh(*inputMesh);
825 tetMesh.orient();
826 epsilon = ep;
827 queryType = qt;
828 if (tetMesh.getNumVertices() < 4)
829 return false;
830
831 // check whether tetMesh is face-manifold
832 map<UTriKey, int> faceCount;
833 for (int i = 0; i < tetMesh.getNumElements(); i++)
834 {
835 OTetKey tet(tetMesh.getVertexIndex(i, 0), tetMesh.getVertexIndex(i, 1), tetMesh.getVertexIndex(i, 2), tetMesh.getVertexIndex(i, 3));
836 for (int j = 0; j < 4; j++)
837 {
838 UTriKey face = tet.uFaceKey(j);
839 faceCount[face]++;
840 }
841 }
842 for (map<UTriKey, int>::iterator it = faceCount.begin(); it != faceCount.end(); it++)
843 {
844 if (it->second > 2)
845 {
846 // non-manifold faces found
847 return false;
848 }
849 }
850
851 // add all points
852 inputVertices.resize(tetMesh.getNumVertices());
853 for (int i = 0; i < tetMesh.getNumVertices(); i++)
854 inputVertices[i] = tetMesh.getVertex(i);
855 buildQuery();
856
857 for (int i = 0; i < tetMesh.getNumElements(); i++)
858 balls.insert(createBall(tetMesh.getVertexIndex(i, 0), tetMesh.getVertexIndex(i, 1), tetMesh.getVertexIndex(i, 2), tetMesh.getVertexIndex(i, 3)));
859
860 //this map is used to assist in finding neighbors for the new regular balls
861 map<UTriKey, DelaunayBall *> neighboringStructure;
862 for (BallIter it = balls.begin(); it != balls.end(); it++)
863 {
864 DelaunayBall * ball = *it;
865 for (int j = 0; j < 4; j++)
866 {
867 UTriKey face = ball->uFaceKey(j);
868 buildNeighbor(face, ball, neighboringStructure);
869 }
870 }
871
872 int * edge = new int[neighboringStructure.size() * 3];
873 int k = 0;
874 map <UTriKey, DelaunayBall *> infiniteNeighboring; //assist finding neighbors for the new infinite balls
875
876 // for all the surface triangles, we'll consturct its neighboring infinite balls
877 for (map<UTriKey, DelaunayBall *>::iterator itr = neighboringStructure.begin(); itr != neighboringStructure.end(); itr++)
878 {
879 const UTriKey & face = itr->first;
880 DelaunayBall * ball = itr->second;
881
882 int faceind = ball->getNeighborIndex(face);
883 OTriKey oface = ball->oFaceKey(faceind);
884
885 // record the surface face of the tetMesh
886 edge[k++] = oface[0];
887 edge[k++] = oface[1];
888 edge[k++] = oface[2];
889
890 oface.reverse(); // reverse the oriented face to let it become the neighboring infinity ball's face
891
892 DelaunayBall * newBall = createBall(-1, oface[0], oface[1], oface[2]);
893 ball->setNeighbor(face, newBall);
894 newBall->setNeighbor(face, ball);
895
896 balls.insert(newBall);
897
898 //build all the neighboring structure for new infinite balls
899 const int * v = oface.indices();
900 buildNeighbor(-1, v[0], v[1], newBall, infiniteNeighboring);
901 buildNeighbor(-1, v[1], v[2], newBall, infiniteNeighboring);
902 buildNeighbor(-1, v[0], v[2], newBall, infiniteNeighboring);
903 }
904
905 vector<double> vertices(3 * inputVertices.size());
906 for (size_t i = 0; i < inputVertices.size(); i++)
907 inputVertices[i].convertToArray(&vertices[i * 3]);
908
909 boundaryMesh = new ObjMesh(inputVertices.size(), &vertices[0], neighboringStructure.size(), edge);
910 // boundaryMesh->save("boundary.obj");
911 boundaryOctree = new ObjMeshOctree<TriangleBasic>(boundaryMesh, 5, 10, 0);
912 printf("Octree built\n");
913 delete [] edge;
914
915 return true;
916 }
917
918 std::ostream & operator <<(std::ostream & o, const DelaunayMesher::DelaunayBall & ball)
919 {
920 o << "(" << ball.v[0] << "," << ball.v[1] << "," << ball.v[2] << "," << ball.v[3] << ")";
921 return o;
922 }
923
924 DelaunayMesher::DelaunayBall * DelaunayMesher::createBall(int v0, int v1, int v2, int v3)
925 {
926 return new DelaunayBall(v0, v1, v2, v3, this, nextBallLabel++);
927 }
928
929 bool DelaunayMesher::isTetMeshFaceManifold(const TetMesh * tetMesh)
930 {
931 map<UTriKey, int> faceCount;
932 for(int i = 0; i < tetMesh->getNumElements(); i++)
933 {
934 OTetKey tet(tetMesh->getVertexIndices(i));
935 for(int j = 0; j < 4; j++)
936 {
937 UTriKey face = tet.uFaceKey(j);
938 faceCount[face]++;
939 }
940 }
941 for(map<UTriKey, int>::iterator it = faceCount.begin(); it != faceCount.end(); it++)
942 {
943 if(it->second > 2)
944 return false; // non-manifold faces found
945 }
946 return true;
947 }
948
949 // Remove a ball from the delaunay mesh
950 void DelaunayMesher::removeBall(DelaunayBall * ball)
951 {
952 if (balls.find(ball) == balls.end())
953 return;
954 for (int i = 0; i < 4; i++)
955 {
956 UTriKey key = ball->uFaceKey(i);
957 map<UTriKey, DelaunayBall *>::iterator itr = neighboringStructure.find(key);
958 if (itr == neighboringStructure.end())
959 {
960 neighboringStructure.insert(make_pair(key, ball->nbr[i])); // A face loses its one neighbor, save it as a hanging face
961 ball->nbr[i]->setNeighbor(key, NULL);
962 }
963 else
964 {
965 assert(itr->second == ball);
966 neighboringStructure.erase(itr); // A face has no neighbor, remove it
967 }
968 }
969 balls.erase(ball);
970 delete ball;
971 }
972
973 DelaunayMesher::DelaunayBall * DelaunayMesher::addBall(const int v0, const int v1, const int v2, const int v3)
974 {
975 DelaunayBall * ball = createBall(v0, v1, v2, v3);
976 if (v0 >= 0)
977 vertex2ball[v0] = ball;
978 if (v1 >= 0)
979 vertex2ball[v1] = ball;
980 if (v2 >= 0)
981 vertex2ball[v2] = ball;
982 if (v3 >= 0)
983 vertex2ball[v3] = ball;
984 if (balls.find(ball) != balls.end())
985 return ball;
986 balls.insert(ball);
987 for (int i = 0; i < 4; i++)
988 {
989 UTriKey key = ball->uFaceKey(i);
990 map<UTriKey, DelaunayBall *>::iterator itr = neighboringStructure.find(key);
991 if (itr == neighboringStructure.end())
992 neighboringStructure.insert(make_pair(key, ball)); // A face has only one neighbor, save it as a hanging face
993 else // Build neighbor relationship
994 {
995 ball->nbr[i] = itr->second;
996 itr->second->setNeighbor(key, ball);
997 neighboringStructure.erase(itr);
998 }
999 }
1000 return ball;
1001 }
1002
1003 DelaunayMesher::DelaunayBall * DelaunayMesher::addBall(const int* v)
1004 {
1005 return addBall(v[0], v[1], v[2], v[3]);
1006 }
1007
1008 int DelaunayMesher::buildCDT()
1009 {
1010 map<UTriKey, DelaunayBall *>::iterator faceKey = neighboringStructure.begin();
1011
1012 int * edge = (int*)malloc(neighboringStructure.size() * 3 * sizeof(int));
1013
1014 int edgeSize = 0;
1015 // Building infinite ball and neighboring information
1016 while (faceKey != neighboringStructure.end())
1017 {
1018 // Create an infinite ball
1019 DelaunayBall * regularBall = faceKey->second;
1020 int faceIndex = regularBall->getNeighborIndex(faceKey->first);
1021
1022 OTriKey okey = regularBall->oFaceKey(faceIndex);
1023 edge[edgeSize++] = okey[0];
1024 edge[edgeSize++] = okey[1];
1025 edge[edgeSize++] = okey[2];
1026 DelaunayBall * infiniteBall = createBall(-1, faceKey->first[0], faceKey->first[1], faceKey->first[2]);
1027 faceKey++;
1028 balls.insert(infiniteBall);
1029 for (int i = 0; i < 4; i++)
1030 {
1031 UTriKey key = infiniteBall->uFaceKey(i);
1032 map<UTriKey, DelaunayBall *>::iterator itr = neighboringStructure.find(key);
1033 if (itr == neighboringStructure.end())
1034 neighboringStructure.insert(make_pair(key, infiniteBall));
1035 else
1036 {
1037 infiniteBall->nbr[i] = itr->second;
1038 itr->second->setNeighbor(key, infiniteBall);
1039 neighboringStructure.erase(itr);
1040 }
1041 }
1042 }
1043
1044 vector<double> vertices(3 * inputVertices.size());
1045 for (size_t i = 0; i < inputVertices.size(); i++)
1046 inputVertices[i].convertToArray(&vertices[i * 3]);
1047
1048 boundaryMesh = new ObjMesh(inputVertices.size(), vertices.data(), edgeSize / 3, edge);
1049
1050 boundaryOctree = new ObjMeshOctree<TriangleBasic>(boundaryMesh, 5, 10, 0);
1051 free(edge);
1052 return 0;
1053 }
1054
1055 static const int SECT_FACE = 0;
1056 static const int ON_FACE = 1;
1057 static const int SECT_EDGE = 2;
1058 static const int ON_EDGE = 3;
1059 static const int SECT_VERTEX = 4;
1060 static const int ON_VERTEX = 5;
1061 static const int IN_TET = 6;
1062
1063 /*
1064 * Test whether seg(v0,v1) intersect face(f0,f1,f2), Assume that Volume(f0,f1,f2,v0) must be non-negative
1065 * 0: seg (f1, f2) causes unflippable
1066 * 1: seg (f2, f0) causes unflippable
1067 * 2: seg (f0, f1) causes unflippable
1068 * 3: flippable
1069 */
1070
1071 //Permute origin vtx table, first column of each row is the index of the origin
1072 static const int permute[4][4] = { {0, 1, 2, 3}, {1, 2, 0, 3}, {2, 0, 1, 3}, {3, 1, 0, 2} };
1073
1074 static const int FLIPPABLE = 8;
1075 static const int SEMI_FLIPPABLE = 4;
1076
1077 // test wheter seg(v0,v1) intersects face
1078 // if intersect of the boundary of the face, return SEMI_FLIPPABLE + which edge of the face the segement intersects
1079 static int flippable(VerticesQuery * query, const OTriKey &face, const int v0, const int v1)
1080 {
1081 int onFace = FLIPPABLE;
1082 for (int i = 0; i < 3; i++)
1083 {
1084 OEdgeKey edge = face.oEdgeKey(i);
1085 int result = query->toPlane(v1, edge[0], edge[1], v0);
1086 if (result == 1)
1087 return i;
1088 else if (result == 0)
1089 onFace = i;
1090 }
1091 return (onFace == FLIPPABLE? FLIPPABLE: SEMI_FLIPPABLE + onFace);
1092 }
1093
1094 // face is on ball1, the opposite face is on ball0
1095 int DelaunayMesher::flip23(const OTriKey& face, DelaunayBall * ball0, DelaunayBall * ball1, int requestNewBallIdx, DelaunayBall ** newBallAroundEdge, int allowFlat)
1096 {
1097 if (ball0->isInfinite() != ball1->isInfinite())
1098 return 1; // Can't flip boundary face
1099 UTriKey uface = UTriKey(face.indices());
1100 int n0 = ball0->getNeighborIndex(uface);
1101 int v0 = ball0->getVtx(n0);
1102 int n1 = ball1->getNeighborIndex(uface);
1103 int v1 = ball1->getVtx(n1);
1104 // v0 must on the positive side of face
1105 if (face[0] >= 0)
1106 { // a triangular face
1107 if (query->toPlane(v0, face[0], face[1], face[2]) == -1)
1108 {
1109 swap(v0, v1);
1110 }
1111 // test whether the face is flippable
1112 int flippableResult = flippable(query, face, v0, v1);
1113 if (flippableResult < SEMI_FLIPPABLE)
1114 return flippableResult;
1115 if (flippableResult != SEMI_FLIPPABLE + allowFlat && flippableResult != FLIPPABLE)
1116 return flippableResult;
1117 for (int i = 0; i < 4; i++)
1118 if (i != n0)
1119 {
1120 OTriKey f = ball0->oFaceKey(i);
1121 if (query->toPlane(v1, f[0], f[1], f[2]) == 1) // not flippable
1122 return i;
1123 }
1124 }
1125 else // a boundary edge
1126 {
1127 }
1128
1129 // if it is flippable, remove 2 original tets and add 3 new tets
1130 removeBall(ball0);
1131 removeBall(ball1);
1132 DelaunayBall * newBall[3];
1133 for (int i = 0; i < 3; i++)
1134 {
1135 newBall[i] = addBall(face[OTriKey::triEdgeIndex[i][0]], face[OTriKey::triEdgeIndex[i][1]], v1, v0);
1136 }
1137 if (newBallAroundEdge)
1138 *newBallAroundEdge = newBall[requestNewBallIdx];
1139
1140 return FLIPPABLE;
1141 }
1142
1143 static void getOtherTwoIndices(const int a, const int b, int & c, int & d)
1144 {
1145 if (a + b == 3)
1146 { //segment is (0,3) or (1,2)
1147 c = (a + 2) & 3;
1148 d = (b + 2) & 3;
1149 }
1150 else
1151 { // segment isn't (0,3) or (1,2)
1152 c = 3 - a;
1153 d = 3 - b;
1154 }
1155 }
1156
1157 //Get a face number which contains the two vertices, the other vertex is accessed via transpose
1158 static const int faceLookUpTableByTwoVertices[4][4] = { {-1, 2, 3, 1}, {3, -1, 0, 2}, {1, 3, -1, 0}, {2, 0, 1, -1} };
1159
1160 static map<int, int> eleCounter;
1161
1162 int DelaunayMesher::clearCounter(const DelaunayMesher::TetAroundEdge & tetsAroundEdge)
1163 {
1164 for (DelaunayMesher::TetAroundEdge::const_iterator itr = tetsAroundEdge.begin(); itr != tetsAroundEdge.end(); itr++)
1165 {
1166 if (balls.find(itr->third) == balls.end())
1167 cout << "Missing " << *(itr->third) << endl;
1168 eleCounter[itr->third->label]--;
1169 }
1170 return 0;
1171 }
1172
1173 int DelaunayMesher::getTetsAroundEdge(const OEdgeKey& edge, TetAroundEdge & tetsAroundEdge)
1174 {
1175 if ((getOneBallBySegment(edge[0], edge[1]) & 255) != ON_VERTEX)
1176 {
1177 return 0;
1178 }
1179
1180 // Store all Balls with this edge
1181 DelaunayBall *& ball = vertex2ball[edge[0]];
1182
1183 // The initial ball, keep its neighbors
1184 int v0 = ball->getInd(edge[0]);
1185 int v1 = ball->getInd(edge[1]);
1186 int currentFaceNumber = faceLookUpTableByTwoVertices[v0][v1];
1187 int nextFaceNumber = faceLookUpTableByTwoVertices[v1][v0];
1188 tetsAroundEdge.push_back(make_triple(ball->getVtx(currentFaceNumber), ball->oFaceKey(nextFaceNumber), ball));
1189 //eleCounter[ball->label]++;
1190 DelaunayBall * firstBall = ball;
1191 while (true)
1192 {
1193 //cout << *ball << nextFaceNumber << endl;
1194 //DelaunayBall * pre = ball;
1195 ball = ball->nbr[nextFaceNumber];
1196 if (ball == firstBall)
1197 break; // All balls visited
1198
1199 v0 = ball->getInd(edge[0]);
1200 v1 = ball->getInd(edge[1]);
1201 currentFaceNumber = faceLookUpTableByTwoVertices[v0][v1];
1202 nextFaceNumber = faceLookUpTableByTwoVertices[v1][v0];
1203 tetsAroundEdge.push_back(make_triple(ball->getVtx(currentFaceNumber), ball->oFaceKey(nextFaceNumber), ball));
1204 //eleCounter[ball->label]++;
1205 }
1206 return tetsAroundEdge.size();
1207 }
1208
1209 int DelaunayMesher::flip32(const OEdgeKey& edge, const TetAroundEdge & tetsAroundEdge)
1210 {
1211 vector <int> f;
1212 TetAroundEdge::const_iterator itr = tetsAroundEdge.begin();
1213 DelaunayBall * ball0 = itr->third;
1214 f.push_back((itr++)->first);
1215 DelaunayBall * ball1 = itr->third;
1216 f.push_back((itr++)->first);
1217 DelaunayBall * ball2 = itr->third;
1218 f.push_back((itr++)->first);
1219
1220 int v0, v1;
1221 int flippableResult;
1222
1223 v0 = edge[1]; v1 = edge[0];
1224 if (f[0] >= 0 && f[1] >= 0 && f[1] >= 0) // Regular face
1225 {
1226 swap(v0, v1);
1227 }
1228
1229 flippableResult = flippable(query, OTriKey(f.data()), v0, v1);
1230 if (flippableResult != FLIPPABLE && flippableResult != SEMI_FLIPPABLE && flippableResult != SEMI_FLIPPABLE+1 && flippableResult != SEMI_FLIPPABLE+2)
1231 return flippableResult;
1232
1233 // Remove 3 original tets and add 2 new tets
1234 removeBall(ball0);
1235 removeBall(ball1);
1236 removeBall(ball2);
1237 addBall(f[0], f[1], f[2], v0);
1238 addBall(f[0], f[2], f[1], v1);
1239 return FLIPPABLE;
1240 }
1241
1242 int DelaunayMesher::getTwoBallsByFace(const OTriKey& face, std::pair<DelaunayBall*, DelaunayBall*> & twoBalls)
1243 {
1244 DelaunayBall * ball = getOneBallByFace(face);
1245 if (!ball)
1246 return -1;
1247 int ind = ball->getNeighborIndex(face);
1248 if (ind == -1)
1249 return -2;
1250 twoBalls = make_pair(ball, ball->nbr[ind]);
1251 return 0;
1252 }
1253
1254 DelaunayMesher::DelaunayBall* DelaunayMesher::getOneBallByFace(const OTriKey& face)
1255 {
1256 // Find the segment
1257 int result = getOneBallBySegment(face[0], face[1]);
1258 DelaunayBall * & ball = vertex2ball[face[0]];
1259
1260 if ((result & 255) != ON_VERTEX) // the end point must be on the ball
1261 {
1262 printf("Failed to find the segment (%d, %d) in tetmesh\n", face[0], face[1]);
1263 cout << *ball << endl;
1264 return NULL;
1265 }
1266 else
1267 {
1268 while (true)
1269 {
1270 // get the two indices of vertices in the ball
1271 int v0 = ball->getInd(face[0]);
1272 int v1 = ball->getInd(face[1]);
1273 int f0, f1;
1274 getOtherTwoIndices(v0, v1, f0, f1);
1275 OTriKey f = ball->oFaceKey(f0);
1276 if (query->toPlane(face[2], f[0], f[1], f[2]) > 0)
1277 ball = ball->nbr[f0];
1278 else
1279 {
1280 f = ball->oFaceKey(f1);
1281 if (query->toPlane(face[2], f[0], f[1], f[2]) > 0)
1282 ball = ball->nbr[f1];
1283 else
1284 return ball;
1285 }
1286 }
1287 }
1288 }
1289
1290 /*
1291 0: intersect with face
1292 1: on a face
1293 2: intersect with edge
1294 3: on an edge
1295 4: intersect with vertex
1296 5: on a vertex
1297 6: in the tet
1298 */
1299
1300 int DelaunayMesher::getOneBallBySegment(const int start, const int end)
1301 {
1302 if (start == end) // it's not a segment
1303 return -6;
1304
1305 DelaunayBall * & ball = vertex2ball[start];
1306 if (ball->isInfinite())
1307 {
1308 ball = ball->nbr[0];
1309 }
1310 int i;
1311 while (true)
1312 {
1313 if (!ball)
1314 cout << "Null pointer" << endl;
1315 int originInd = ball->getInd(start);
1316 if (ball->isInfinite())
1317 {
1318 printf("Infinite ball\n");
1319 return -2;
1320 }
1321 if (originInd == -1)
1322 return -1;
1323
1324 //OFaceKey
1325 int sign[4];
1326 for (i = 1; i < 4; i++)
1327 {
1328 OTriKey face = ball->oFaceKey(permute[originInd][i]);
1329 if ((sign[i] = query->toPlane(end, face[0], face[1], face[2])) == 1)
1330 break;
1331 }
1332 if (i < 4)
1333 {
1334 ball = ball->nbr[permute[originInd][i]]; // go to its neighbor ball
1335 }
1336 else
1337 {
1338 OTriKey face = ball->oFaceKey(permute[originInd][0]);
1339 sign[0] = query->toPlane(end, face[0], face[1], face[2]);
1340 int sumSign = -(sign[1] + sign[2] + sign[3]);
1341 if (sign[0] == 1)
1342 {
1343 switch (sumSign)
1344 {
1345 case 1:
1346 return SECT_VERTEX;
1347 case 2:
1348 if (sign[1] == 0)
1349 {
1350 return (permute[originInd][2] << 8) | (permute[originInd][3] << 12) | SECT_EDGE;
1351 }
1352 else if (sign[2] == 0)
1353 return (permute[originInd][3] << 8) | (permute[originInd][1] << 12) | SECT_EDGE;
1354 else //if (sign[3] == 0)
1355 return (permute[originInd][1] << 8) | (permute[originInd][2] << 12) | SECT_EDGE;
1356 case 3:
1357 return SECT_FACE | (permute[originInd][0] << 8);
1358 default:
1359 return -3;
1360 }
1361 }
1362 else
1363 {
1364 sumSign -= sign[0];
1365 switch (sumSign)
1366 {
1367 //TODO: consider a degenerated tet
1368 case 1:
1369 return ON_VERTEX;
1370 case 2:
1371 return ON_EDGE;
1372 case 3:
1373 return ON_FACE;
1374 case 4:
1375 return IN_TET;
1376 default:
1377 return -4;
1378 }
1379 }
1380 }
1381 }
1382 return -5;
1383 }
1384
1385 int DelaunayMesher::segmentRecoveryUsingFlip(const OEdgeKey & lineSegment, int depth)
1386 {
1387 const int maxIterations = 100; // needed to avoid an infinite loop
1388 int iter = -1;
1389 while (true)
1390 {
1391 iter++;
1392 if (iter >= maxIterations)
1393 return -3;
1394
1395 //printf("*"); fflush(NULL);
1396 OEdgeKey edgeToBeRemoved;
1397 // find a tet such that the vertex lineSegment[0] is a tet vertex, and the line segment goes through the tet
1398 // result stores how the line segment goes through the tet
1399 // ON_VERTEX: the line segment goes down a tet edge and ends at another tet vertex
1400 // SECT_EDGE: the line segment goes down an interior of a tet face, and exits through an edge
1401 // SECT_FACE: the line segment goes through the interior of the tet, and exits through the opposite tet interior face
1402 int result = getOneBallBySegment(lineSegment[0], lineSegment[1]);
1403 int locationType = result & 255;
1404 if (locationType == ON_VERTEX)
1405 {
1406 recoveredEdge.insert(UEdgeKey(lineSegment[0], lineSegment[1]));
1407 return 0; // this edge is already recovered; no more work needed
1408 }
1409 else if (locationType == SECT_FACE)
1410 {
1411 // line segment intersects the interior of the face, try flip23
1412 int originIdx = vertex2ball[lineSegment[0]]->getInd(lineSegment[0]);
1413 OTriKey face = vertex2ball[lineSegment[0]]->oFaceKey(originIdx);
1414 int flipResult = flip23(face, vertex2ball[lineSegment[0]]->nbr[originIdx], vertex2ball[lineSegment[0]]);
1415 if (flipResult == FLIPPABLE)
1416 continue; // successfully flipped, search for the next face
1417 else
1418 {
1419 // flip23 did not succeed
1420 if (flipResult >= SEMI_FLIPPABLE)
1421 flipResult -= SEMI_FLIPPABLE;
1422 edgeToBeRemoved = face.oEdgeKey(flipResult);
1423 }
1424 }
1425 else if (locationType == SECT_EDGE)
1426 {
1427 int v0 = vertex2ball[lineSegment[0]]->getVtx((result >> 8) & 15);
1428 int v1 = vertex2ball[lineSegment[0]]->getVtx((result >> 12) & 15);
1429 edgeToBeRemoved = OEdgeKey(v0, v1);
1430 }
1431
1432 if (segmentRemovalUsingFlip(edgeToBeRemoved, depth) != 0)
1433 {
1434 // removal failed
1435 return -2;
1436 }
1437 }
1438 return -1;
1439 }
1440
1441 ostream & operator << (ostream &out, const UTriKey & key)
1442 {
1443 out << "(" << key[0] << ", " << key[1] << ", " << key[2] << ")";
1444 return out;
1445 }
1446
1447 int DelaunayMesher::segmentRemovalUsingFlip(const OEdgeKey & edge, int depth)
1448 {
1449 if (recoveredEdge.find(UEdgeKey(edge[0], edge[1])) != recoveredEdge.end())
1450 return -8; // a recovered edge can't be removed
1451 if (--depth < 0)
1452 return -9;
1453
1454 TetAroundEdge tetsAroundEdge;
1455 if (getTetsAroundEdge(edge, tetsAroundEdge) < 3)
1456 {
1457 //assert(0);
1458 return -1;
1459 }
1460 for (TetAroundEdge::iterator itr = tetsAroundEdge.begin(); itr != tetsAroundEdge.end(); itr++)
1461 ++eleCounter[itr->third->label]; // add one reference of the tet
1462
1463 size_t k = tetsAroundEdge.size() + 1;
1464 while (tetsAroundEdge.size() > 3)
1465 {
1466 if (tetsAroundEdge.size() >= k)
1467 return 5;
1468 k = tetsAroundEdge.size();
1469 TetAroundEdge::iterator itr;
1470 for (itr = tetsAroundEdge.begin(); itr != tetsAroundEdge.end(); itr++)
1471 {
1472 DelaunayBall * ball = itr->third;
1473 TetAroundEdge::iterator nextItr = itr;
1474 if (++nextItr == tetsAroundEdge.end())
1475 nextItr = tetsAroundEdge.begin();
1476 DelaunayBall * nextBall = nextItr->third;
1477 if (ball->isInfinite() != nextBall->isInfinite() || (tetsAroundEdge.size() > 4 && ball->isInfinite()))
1478 continue;
1479 if (eleCounter[ball->label] > 1 || eleCounter[nextBall->label] > 1)
1480 continue;
1481 OTriKey f = itr->second;
1482
1483 int vIdx = f.getInd(itr->first);
1484 DelaunayBall * newBallAroundEdge;
1485 int allowFlat = -1;
1486 if (tetsAroundEdge.size() == 4)
1487 {
1488 allowFlat = vIdx;
1489 }
1490 if (flip23(f, nextBall, ball, vIdx, &newBallAroundEdge, allowFlat) == FLIPPABLE)
1491 {
1492 // Insert the new tet
1493 vIdx = 3 - nextItr->second.getInd(edge[0]) - nextItr->second.getInd(edge[1]);
1494 tetsAroundEdge.insert(itr, make_triple(nextItr->second[vIdx], nextItr->second, newBallAroundEdge));
1495 eleCounter[newBallAroundEdge->label]++;
1496 //cout << *newBallAroundEdge << endl;
1497 // Remove the old two tets
1498 tetsAroundEdge.erase(itr);
1499 tetsAroundEdge.erase(nextItr);
1500
1501 break;
1502 }
1503 }
1504 if (itr == tetsAroundEdge.end())
1505 {
1506 // No face is flippable
1507 if (depth > 0)
1508 {
1509 // Try to remove an edge
1510 for (TetAroundEdge::iterator itr = tetsAroundEdge.begin(); itr != tetsAroundEdge.end(); itr++)
1511 {
1512 DelaunayBall * ball = itr->third;
1513 TetAroundEdge::iterator nextItr = itr;
1514 if (++nextItr == tetsAroundEdge.end())
1515 nextItr = tetsAroundEdge.begin();
1516 DelaunayBall * nextBall = nextItr->third;
1517 if (ball->isInfinite() || nextBall->isInfinite())
1518 continue;
1519 if (eleCounter[ball->label] > 1 || eleCounter[nextBall->label] > 1)
1520 continue;
1521 OTriKey f = itr->second;
1522 int flipResult = flip23(f, nextBall, ball);
1523 if (flipResult >= 4 && flipResult < 8)
1524 flipResult -= 4;
1525 if (flipResult >= 0 && flipResult < 3)
1526 {
1527 OEdgeKey e = f.oEdgeKey(flipResult);
1528 if (segmentRemovalUsingFlip(e, depth) == 0)
1529 {
1530
1531 tetsAroundEdge.erase(itr);
1532 tetsAroundEdge.erase(nextItr);
1533 break;
1534 }
1535 }
1536 }
1537 }
1538 if (itr == tetsAroundEdge.end())
1539 {
1540 clearCounter(tetsAroundEdge);
1541 return -4;
1542 }
1543 else
1544 {
1545 return -5;
1546 }
1547 }
1548 }
1549 if ((flip32(edge, tetsAroundEdge)) == FLIPPABLE)
1550 {
1551 return 0;
1552 }
1553 else
1554 {
1555 clearCounter(tetsAroundEdge);
1556 cout << "FLIP32 fail" << endl;
1557 return -1;
1558 }
1559 }
1560
1561 int DelaunayMesher::segmentRecoveryUsingSteinerPoint(const OEdgeKey& edge)
1562 {
1563 int result = getOneBallBySegment(edge[0], edge[1]);
1564 int locationType = result & 255;
1565
1566 OEdgeKey removalEdge;
1567 if (locationType != SECT_EDGE)
1568 return 200;
1569 if (locationType == SECT_EDGE)
1570 {
1571 int v0 = vertex2ball[edge[0]]->getVtx((result >> 8) & 15);
1572 int v1 = vertex2ball[edge[0]]->getVtx((result >> 12) & 15);
1573 removalEdge = OEdgeKey(v0, v1);
1574 }
1575 TetAroundEdge tetAroundEdge;
1576 vertex2ball[removalEdge[0]] = vertex2ball[edge[0]];
1577 DelaunayBall *& ball = vertex2ball[removalEdge[0]];
1578 if (ball->isInfinite())
1579 ball = ball->nbr[0];
1580
1581 int v0 = ball->getInd(removalEdge[0]);
1582 int v1 = ball->getInd(removalEdge[1]);
1583 int currentFaceNumber = faceLookUpTableByTwoVertices[v0][v1];
1584 if (ball->getVtx(currentFaceNumber) != edge[0])
1585 {
1586 ball = ball->nbr[currentFaceNumber];
1587 }
1588 v0 = ball->getInd(removalEdge[0]);
1589 v1 = ball->getInd(removalEdge[1]);
1590 currentFaceNumber = faceLookUpTableByTwoVertices[v0][v1];
1591 assert( ball->getVtx(currentFaceNumber) == edge[0]);
1592 vertex2ball[removalEdge[0]] = ball;
1593 getTetsAroundEdge(removalEdge, tetAroundEdge);
1594
1595 assert(tetAroundEdge.begin()->first == edge[0]);
1596
1597 int idx = 0;
1598 int e = -1;
1599 int reverse = 0;
1600 assert(tetAroundEdge.size() >= 5);
1601 for (TetAroundEdge::const_iterator itr = tetAroundEdge.begin(); itr != tetAroundEdge.end(); itr++)
1602 {
1603 TetAroundEdge::const_iterator nextItr = itr;
1604 nextItr++;
1605 if (nextItr == tetAroundEdge.end())
1606 nextItr = tetAroundEdge.begin();
1607 if (itr->first == edge[1])
1608 e = idx;
1609 if (itr->first == -1 || nextItr->first == -1)
1610 {
1611 if (e != -1)
1612 reverse = 1;
1613 else
1614 reverse = -1;
1615 idx++;
1616 continue;
1617 }
1618 idx++;
1619 }
1620 if (reverse == 0)
1621 {
1622 if (e <= 2)
1623 {
1624 reverse = -1;
1625 }
1626 else
1627 reverse = 1;
1628 }
1629
1630 TetAroundEdge::const_iterator itr = tetAroundEdge.begin();
1631 if (reverse == -1)
1632 {
1633 tetAroundEdge.push_back(*tetAroundEdge.begin());
1634 while (tetAroundEdge.begin()->first != edge[1])
1635 tetAroundEdge.pop_front();
1636 }
1637 else
1638 {
1639 while ((int)tetAroundEdge.size() != e + 1)
1640 tetAroundEdge.pop_back();
1641 }
1642
1643 assert(tetAroundEdge.size() >= 4);
1644
1645 itr = tetAroundEdge.begin();
1646 map<OTriKey, DelaunayBall *> cavityNeighbors;
1647 for (itr++ ; itr != tetAroundEdge.end(); itr++)
1648 {
1649 OTriKey face(itr->first, itr->third->getVtxOpposeFace(itr->second), removalEdge[1]);
1650 cavityNeighbors.insert(make_pair(face, itr->third->getNeighborByFace(face)));
1651 face = OTriKey(itr->first, removalEdge[0], itr->third->getVtxOpposeFace(itr->second));
1652 cavityNeighbors.insert(make_pair(face, itr->third->getNeighborByFace(face)));
1653 }
1654
1655 tetAroundEdge.pop_front();
1656 if (reverse == 1)
1657 {
1658 OTriKey face(removalEdge[0], removalEdge[1], edge[0]);
1659 DelaunayBall * ball = (tetAroundEdge.begin())->third;
1660 assert(ball->getNeighborIndex(face) != -1);
1661 cavityNeighbors.insert(make_pair(face, ball->getNeighborByFace(face)));
1662 face = OTriKey(removalEdge[1], removalEdge[0], edge[1]);
1663 ball = (--tetAroundEdge.end())->third;
1664 assert(ball->getNeighborIndex(face) != -1);
1665 cavityNeighbors.insert(make_pair(face, ball->getNeighborByFace(face)));
1666 }
1667 else
1668 {
1669 OTriKey face(removalEdge[0], removalEdge[1], edge[1]);
1670 DelaunayBall * ball = (tetAroundEdge.begin())->third;
1671 assert(ball->getNeighborIndex(face) != -1);
1672 cavityNeighbors.insert(make_pair(face, ball->getNeighborByFace(face)));
1673 face = OTriKey(removalEdge[1], removalEdge[0], edge[0]);
1674 ball = (--tetAroundEdge.end())->third;
1675 assert(ball->getNeighborIndex(face) != -1);
1676 cavityNeighbors.insert(make_pair(face, ball->getNeighborByFace(face)));
1677 }
1678
1679 //Calculate the gravity center
1680
1681 Vec3d center(0, 0, 0);
1682 double volume = 0;
1683 for (itr = tetAroundEdge.begin(); itr != tetAroundEdge.end(); itr++)
1684 {
1685 DelaunayBall * ball = itr->third;
1686 Vec3d c = (ball->getPosition(0) + ball->getPosition(1) + ball->getPosition(2) + ball->getPosition(3)) / 4;
1687 double v = TetMesh::getTetVolume(ball->getPosition(0), ball->getPosition(1), ball->getPosition(2), ball->getPosition(3));
1688 assert(v > 0);
1689 center += c * v;
1690 volume += v;
1691 }
1692 center /= volume;
1693
1694 //Check all volumes
1695 for (map<OTriKey, DelaunayBall *>::iterator itr = cavityNeighbors.begin(); itr != cavityNeighbors.end(); itr++)
1696 {
1697 OTriKey face = itr->first;
1698 assert (query->toPlane(center, face[0], face[1], face[2]) == -1);
1699 }
1700
1701 // Add the Steiner point
1702 int newVtx = inputVertices.size();
1703 inputVertices.push_back(center);
1704 query->addVertex(center);
1705 vertex2ball.push_back(NULL);
1706
1707 // Remove old balls
1708
1709 for (itr = tetAroundEdge.begin(); itr != tetAroundEdge.end(); itr++)
1710 {
1711 DelaunayBall * ball = itr->third;
1712 balls.erase(ball);
1713 delete ball;
1714 }
1715
1716 // Add new balls
1717 map<UTriKey, DelaunayBall *> hangingFaces;
1718 for (map<OTriKey, DelaunayBall *>::iterator itr = cavityNeighbors.begin(); itr != cavityNeighbors.end(); itr++)
1719 {
1720
1721 OTriKey oface = itr->first;
1722 DelaunayBall * ball = createBall(oface[0], oface[2], oface[1], newVtx);
1723 balls.insert(ball);
1724 vertex2ball[oface[0]] = vertex2ball[oface[1]] = vertex2ball[oface[2]] = vertex2ball[newVtx] = ball;
1725 //set boundary neighbor
1726 UTriKey uface(oface[0], oface[1], oface[2]);
1727 assert(ball->getNeighborIndex(uface) != -1);
1728 ball->setNeighbor(uface, itr->second);
1729 itr->second->setNeighbor(uface, ball);
1730 assert(itr->second->getNeighborIndex(uface) != -1);
1731
1732 //set inter neighbor
1733 for (int i = 0; i < 4; i++)
1734 if (ball->nbr[i] == NULL)
1735 {
1736 UTriKey uface = ball->uFaceKey(i);
1737 map<UTriKey, DelaunayBall *>::iterator iter = hangingFaces.find(uface);
1738 if (iter == hangingFaces.end())
1739 hangingFaces.insert(make_pair(uface, ball));
1740 else
1741 {
1742 ball->nbr[i] = iter->second;
1743 iter->second->setNeighbor(uface, ball);
1744 hangingFaces.erase(iter);
1745 }
1746 }
1747 }
1748 // assert(hangingFaces.empty());
1749 return 100;
1750 }
1751