source: src/tesselation.cpp@ 7dea7c

Action_Thermostats Add_AtomRandomPerturbation Add_FitFragmentPartialChargesAction Add_RotateAroundBondAction Add_SelectAtomByNameAction Added_ParseSaveFragmentResults AddingActions_SaveParseParticleParameters Adding_Graph_to_ChangeBondActions Adding_MD_integration_tests Adding_ParticleName_to_Atom Adding_StructOpt_integration_tests AtomFragments Automaking_mpqc_open AutomationFragmentation_failures Candidate_v1.5.4 Candidate_v1.6.0 Candidate_v1.6.1 Candidate_v1.7.0 ChangeBugEmailaddress ChangingTestPorts ChemicalSpaceEvaluator CombiningParticlePotentialParsing Combining_Subpackages Debian_Package_split Debian_package_split_molecuildergui_only Disabling_MemDebug Docu_Python_wait EmpiricalPotential_contain_HomologyGraph EmpiricalPotential_contain_HomologyGraph_documentation Enable_parallel_make_install Enhance_userguide Enhanced_StructuralOptimization Enhanced_StructuralOptimization_continued Example_ManyWaysToTranslateAtom Exclude_Hydrogens_annealWithBondGraph FitPartialCharges_GlobalError Fix_BoundInBox_CenterInBox_MoleculeActions Fix_ChargeSampling_PBC Fix_ChronosMutex Fix_FitPartialCharges Fix_FitPotential_needs_atomicnumbers Fix_ForceAnnealing Fix_IndependentFragmentGrids Fix_ParseParticles Fix_ParseParticles_split_forward_backward_Actions Fix_PopActions Fix_QtFragmentList_sorted_selection Fix_Restrictedkeyset_FragmentMolecule Fix_StatusMsg Fix_StepWorldTime_single_argument Fix_Verbose_Codepatterns Fix_fitting_potentials Fixes ForceAnnealing_goodresults ForceAnnealing_oldresults ForceAnnealing_tocheck ForceAnnealing_with_BondGraph ForceAnnealing_with_BondGraph_continued ForceAnnealing_with_BondGraph_continued_betteresults ForceAnnealing_with_BondGraph_contraction-expansion FragmentAction_writes_AtomFragments FragmentMolecule_checks_bonddegrees GeometryObjects Gui_Fixes Gui_displays_atomic_force_velocity ImplicitCharges IndependentFragmentGrids IndependentFragmentGrids_IndividualZeroInstances IndependentFragmentGrids_IntegrationTest IndependentFragmentGrids_Sole_NN_Calculation JobMarket_RobustOnKillsSegFaults JobMarket_StableWorkerPool JobMarket_unresolvable_hostname_fix MoreRobust_FragmentAutomation ODR_violation_mpqc_open PartialCharges_OrthogonalSummation PdbParser_setsAtomName PythonUI_with_named_parameters QtGui_reactivate_TimeChanged_changes Recreated_GuiChecks Rewrite_FitPartialCharges RotateToPrincipalAxisSystem_UndoRedo SaturateAtoms_findBestMatching SaturateAtoms_singleDegree StoppableMakroAction Subpackage_CodePatterns Subpackage_JobMarket Subpackage_LinearAlgebra Subpackage_levmar Subpackage_mpqc_open Subpackage_vmg Switchable_LogView ThirdParty_MPQC_rebuilt_buildsystem TrajectoryDependenant_MaxOrder TremoloParser_IncreasedPrecision TremoloParser_MultipleTimesteps TremoloParser_setsAtomName Ubuntu_1604_changes stable
Last change on this file since 7dea7c was 7dea7c, checked in by Frederik Heber <heber@…>, 16 years ago

Fixes to the (Non)ConvexTesselation, working with 1_2_dimethoxyethylene

minor changes:

major changes:

  • Property mode set to 100644
File size: 153.9 KB
Line 
1/*
2 * tesselation.cpp
3 *
4 * Created on: Aug 3, 2009
5 * Author: heber
6 */
7
8#include "helpers.hpp"
9#include "linkedcell.hpp"
10#include "tesselation.hpp"
11#include "tesselationhelpers.hpp"
12#include "vector.hpp"
13
14class molecule;
15
16// ======================================== Points on Boundary =================================
17
18/** Constructor of BoundaryPointSet.
19 */
20BoundaryPointSet::BoundaryPointSet()
21{
22 LinesCount = 0;
23 Nr = -1;
24 value = 0.;
25};
26
27/** Constructor of BoundaryPointSet with Tesselpoint.
28 * \param *Walker TesselPoint this boundary point represents
29 */
30BoundaryPointSet::BoundaryPointSet(TesselPoint *Walker)
31{
32 node = Walker;
33 LinesCount = 0;
34 Nr = Walker->nr;
35 value = 0.;
36};
37
38/** Destructor of BoundaryPointSet.
39 * Sets node to NULL to avoid removing the original, represented TesselPoint.
40 * \note When removing point from a class Tesselation, use RemoveTesselationPoint()
41 */
42BoundaryPointSet::~BoundaryPointSet()
43{
44 //cout << Verbose(5) << "Erasing point nr. " << Nr << "." << endl;
45 if (!lines.empty())
46 cerr << "WARNING: Memory Leak! I " << *this << " am still connected to some lines." << endl;
47 node = NULL;
48};
49
50/** Add a line to the LineMap of this point.
51 * \param *line line to add
52 */
53void BoundaryPointSet::AddLine(class BoundaryLineSet *line)
54{
55 cout << Verbose(6) << "Adding " << *this << " to line " << *line << "."
56 << endl;
57 if (line->endpoints[0] == this)
58 {
59 lines.insert(LinePair(line->endpoints[1]->Nr, line));
60 }
61 else
62 {
63 lines.insert(LinePair(line->endpoints[0]->Nr, line));
64 }
65 LinesCount++;
66};
67
68/** output operator for BoundaryPointSet.
69 * \param &ost output stream
70 * \param &a boundary point
71 */
72ostream & operator <<(ostream &ost, BoundaryPointSet &a)
73{
74 ost << "[" << a.Nr << "|" << a.node->Name << " at " << *a.node->node << "]";
75 return ost;
76}
77;
78
79// ======================================== Lines on Boundary =================================
80
81/** Constructor of BoundaryLineSet.
82 */
83BoundaryLineSet::BoundaryLineSet()
84{
85 for (int i = 0; i < 2; i++)
86 endpoints[i] = NULL;
87 Nr = -1;
88};
89
90/** Constructor of BoundaryLineSet with two endpoints.
91 * Adds line automatically to each endpoints' LineMap
92 * \param *Point[2] array of two boundary points
93 * \param number number of the list
94 */
95BoundaryLineSet::BoundaryLineSet(class BoundaryPointSet *Point[2], int number)
96{
97 // set number
98 Nr = number;
99 // set endpoints in ascending order
100 SetEndpointsOrdered(endpoints, Point[0], Point[1]);
101 // add this line to the hash maps of both endpoints
102 Point[0]->AddLine(this); //Taken out, to check whether we can avoid unwanted double adding.
103 Point[1]->AddLine(this); //
104 // clear triangles list
105 cout << Verbose(5) << "New Line with endpoints " << *this << "." << endl;
106};
107
108/** Destructor for BoundaryLineSet.
109 * Removes itself from each endpoints' LineMap, calling RemoveTrianglePoint() when point not connected anymore.
110 * \note When removing lines from a class Tesselation, use RemoveTesselationLine()
111 */
112BoundaryLineSet::~BoundaryLineSet()
113{
114 int Numbers[2];
115
116 // get other endpoint number of finding copies of same line
117 if (endpoints[1] != NULL)
118 Numbers[0] = endpoints[1]->Nr;
119 else
120 Numbers[0] = -1;
121 if (endpoints[0] != NULL)
122 Numbers[1] = endpoints[0]->Nr;
123 else
124 Numbers[1] = -1;
125
126 for (int i = 0; i < 2; i++) {
127 if (endpoints[i] != NULL) {
128 if (Numbers[i] != -1) { // as there may be multiple lines with same endpoints, we have to go through each and find in the endpoint's line list this line set
129 pair<LineMap::iterator, LineMap::iterator> erasor = endpoints[i]->lines.equal_range(Numbers[i]);
130 for (LineMap::iterator Runner = erasor.first; Runner != erasor.second; Runner++)
131 if ((*Runner).second == this) {
132 //cout << Verbose(5) << "Removing Line Nr. " << Nr << " in boundary point " << *endpoints[i] << "." << endl;
133 endpoints[i]->lines.erase(Runner);
134 break;
135 }
136 } else { // there's just a single line left
137 if (endpoints[i]->lines.erase(Nr)) {
138 //cout << Verbose(5) << "Removing Line Nr. " << Nr << " in boundary point " << *endpoints[i] << "." << endl;
139 }
140 }
141 if (endpoints[i]->lines.empty()) {
142 //cout << Verbose(5) << *endpoints[i] << " has no more lines it's attached to, erasing." << endl;
143 if (endpoints[i] != NULL) {
144 delete(endpoints[i]);
145 endpoints[i] = NULL;
146 }
147 }
148 }
149 }
150 if (!triangles.empty())
151 cerr << "WARNING: Memory Leak! I " << *this << " am still connected to some triangles." << endl;
152};
153
154/** Add triangle to TriangleMap of this boundary line.
155 * \param *triangle to add
156 */
157void BoundaryLineSet::AddTriangle(class BoundaryTriangleSet *triangle)
158{
159 cout << Verbose(6) << "Add " << triangle->Nr << " to line " << *this << "." << endl;
160 triangles.insert(TrianglePair(triangle->Nr, triangle));
161};
162
163/** Checks whether we have a common endpoint with given \a *line.
164 * \param *line other line to test
165 * \return true - common endpoint present, false - not connected
166 */
167bool BoundaryLineSet::IsConnectedTo(class BoundaryLineSet *line)
168{
169 if ((endpoints[0] == line->endpoints[0]) || (endpoints[1] == line->endpoints[0]) || (endpoints[0] == line->endpoints[1]) || (endpoints[1] == line->endpoints[1]))
170 return true;
171 else
172 return false;
173};
174
175/** Checks whether the adjacent triangles of a baseline are convex or not.
176 * We sum the two angles of each height vector with respect to the center of the baseline.
177 * If greater/equal M_PI than we are convex.
178 * \param *out output stream for debugging
179 * \return true - triangles are convex, false - concave or less than two triangles connected
180 */
181bool BoundaryLineSet::CheckConvexityCriterion(ofstream *out)
182{
183 Vector BaseLineCenter, BaseLineNormal, BaseLine, helper[2], NormalCheck;
184 // get the two triangles
185 if (triangles.size() != 2) {
186 *out << Verbose(1) << "ERROR: Baseline " << *this << " is connected to less than two triangles, Tesselation incomplete!" << endl;
187 return true;
188 }
189 // check normal vectors
190 // have a normal vector on the base line pointing outwards
191 //*out << Verbose(3) << "INFO: " << *this << " has vectors at " << *(endpoints[0]->node->node) << " and at " << *(endpoints[1]->node->node) << "." << endl;
192 BaseLineCenter.CopyVector(endpoints[0]->node->node);
193 BaseLineCenter.AddVector(endpoints[1]->node->node);
194 BaseLineCenter.Scale(1./2.);
195 BaseLine.CopyVector(endpoints[0]->node->node);
196 BaseLine.SubtractVector(endpoints[1]->node->node);
197 //*out << Verbose(3) << "INFO: Baseline is " << BaseLine << " and its center is at " << BaseLineCenter << "." << endl;
198
199 BaseLineNormal.Zero();
200 NormalCheck.Zero();
201 double sign = -1.;
202 int i=0;
203 class BoundaryPointSet *node = NULL;
204 for(TriangleMap::iterator runner = triangles.begin(); runner != triangles.end(); runner++) {
205 //*out << Verbose(3) << "INFO: NormalVector of " << *(runner->second) << " is " << runner->second->NormalVector << "." << endl;
206 NormalCheck.AddVector(&runner->second->NormalVector);
207 NormalCheck.Scale(sign);
208 sign = -sign;
209 if (runner->second->NormalVector.NormSquared() > MYEPSILON)
210 BaseLineNormal.CopyVector(&runner->second->NormalVector); // yes, copy second on top of first
211 else {
212 *out << Verbose(1) << "CRITICAL: Triangle " << *runner->second << " has zero normal vector!" << endl;
213 exit(255);
214 }
215 node = runner->second->GetThirdEndpoint(this);
216 if (node != NULL) {
217 //*out << Verbose(3) << "INFO: Third node for triangle " << *(runner->second) << " is " << *node << " at " << *(node->node->node) << "." << endl;
218 helper[i].CopyVector(node->node->node);
219 helper[i].SubtractVector(&BaseLineCenter);
220 helper[i].MakeNormalVector(&BaseLine); // we want to compare the triangle's heights' angles!
221 //*out << Verbose(4) << "INFO: Height vector with respect to baseline is " << helper[i] << "." << endl;
222 i++;
223 } else {
224 //*out << Verbose(2) << "ERROR: I cannot find third node in triangle, something's wrong." << endl;
225 return true;
226 }
227 }
228 //*out << Verbose(3) << "INFO: BaselineNormal is " << BaseLineNormal << "." << endl;
229 if (NormalCheck.NormSquared() < MYEPSILON) {
230 *out << Verbose(3) << "ACCEPT: Normalvectors of both triangles are the same: convex." << endl;
231 return true;
232 }
233 BaseLineNormal.Scale(-1.);
234 double angle = GetAngle(helper[0], helper[1], BaseLineNormal);
235 if ((angle - M_PI) > -MYEPSILON) {
236 *out << Verbose(3) << "ACCEPT: Angle is greater than pi: convex." << endl;
237 return true;
238 } else {
239 *out << Verbose(3) << "REJECT: Angle is less than pi: concave." << endl;
240 return false;
241 }
242}
243
244/** Checks whether point is any of the two endpoints this line contains.
245 * \param *point point to test
246 * \return true - point is of the line, false - is not
247 */
248bool BoundaryLineSet::ContainsBoundaryPoint(class BoundaryPointSet *point)
249{
250 for(int i=0;i<2;i++)
251 if (point == endpoints[i])
252 return true;
253 return false;
254};
255
256/** Returns other endpoint of the line.
257 * \param *point other endpoint
258 * \return NULL - if endpoint not contained in BoundaryLineSet, or pointer to BoundaryPointSet otherwise
259 */
260class BoundaryPointSet *BoundaryLineSet::GetOtherEndpoint(class BoundaryPointSet *point)
261{
262 if (endpoints[0] == point)
263 return endpoints[1];
264 else if (endpoints[1] == point)
265 return endpoints[0];
266 else
267 return NULL;
268};
269
270/** output operator for BoundaryLineSet.
271 * \param &ost output stream
272 * \param &a boundary line
273 */
274ostream & operator <<(ostream &ost, BoundaryLineSet &a)
275{
276 ost << "[" << a.Nr << "|" << a.endpoints[0]->node->Name << " at " << *a.endpoints[0]->node->node << "," << a.endpoints[1]->node->Name << " at " << *a.endpoints[1]->node->node << "]";
277 return ost;
278};
279
280// ======================================== Triangles on Boundary =================================
281
282/** Constructor for BoundaryTriangleSet.
283 */
284BoundaryTriangleSet::BoundaryTriangleSet()
285{
286 for (int i = 0; i < 3; i++)
287 {
288 endpoints[i] = NULL;
289 lines[i] = NULL;
290 }
291 Nr = -1;
292};
293
294/** Constructor for BoundaryTriangleSet with three lines.
295 * \param *line[3] lines that make up the triangle
296 * \param number number of triangle
297 */
298BoundaryTriangleSet::BoundaryTriangleSet(class BoundaryLineSet *line[3], int number)
299{
300 // set number
301 Nr = number;
302 // set lines
303 cout << Verbose(5) << "New triangle " << Nr << ":" << endl;
304 for (int i = 0; i < 3; i++)
305 {
306 lines[i] = line[i];
307 lines[i]->AddTriangle(this);
308 }
309 // get ascending order of endpoints
310 map<int, class BoundaryPointSet *> OrderMap;
311 for (int i = 0; i < 3; i++)
312 // for all three lines
313 for (int j = 0; j < 2; j++)
314 { // for both endpoints
315 OrderMap.insert(pair<int, class BoundaryPointSet *> (
316 line[i]->endpoints[j]->Nr, line[i]->endpoints[j]));
317 // and we don't care whether insertion fails
318 }
319 // set endpoints
320 int Counter = 0;
321 cout << Verbose(6) << " with end points ";
322 for (map<int, class BoundaryPointSet *>::iterator runner = OrderMap.begin(); runner
323 != OrderMap.end(); runner++)
324 {
325 endpoints[Counter] = runner->second;
326 cout << " " << *endpoints[Counter];
327 Counter++;
328 }
329 if (Counter < 3)
330 {
331 cerr << "ERROR! We have a triangle with only two distinct endpoints!"
332 << endl;
333 //exit(1);
334 }
335 cout << "." << endl;
336};
337
338/** Destructor of BoundaryTriangleSet.
339 * Removes itself from each of its lines' LineMap and removes them if necessary.
340 * \note When removing triangles from a class Tesselation, use RemoveTesselationTriangle()
341 */
342BoundaryTriangleSet::~BoundaryTriangleSet()
343{
344 for (int i = 0; i < 3; i++) {
345 if (lines[i] != NULL) {
346 if (lines[i]->triangles.erase(Nr)) {
347 //cout << Verbose(5) << "Triangle Nr." << Nr << " erased in line " << *lines[i] << "." << endl;
348 }
349 if (lines[i]->triangles.empty()) {
350 //cout << Verbose(5) << *lines[i] << " is no more attached to any triangle, erasing." << endl;
351 delete (lines[i]);
352 lines[i] = NULL;
353 }
354 }
355 }
356 //cout << Verbose(5) << "Erasing triangle Nr." << Nr << " itself." << endl;
357};
358
359/** Calculates the normal vector for this triangle.
360 * Is made unique by comparison with \a OtherVector to point in the other direction.
361 * \param &OtherVector direction vector to make normal vector unique.
362 */
363void BoundaryTriangleSet::GetNormalVector(Vector &OtherVector)
364{
365 // get normal vector
366 NormalVector.MakeNormalVector(endpoints[0]->node->node, endpoints[1]->node->node, endpoints[2]->node->node);
367
368 // make it always point inward (any offset vector onto plane projected onto normal vector suffices)
369 if (NormalVector.ScalarProduct(&OtherVector) > 0.)
370 NormalVector.Scale(-1.);
371};
372
373/** Finds the point on the triangle \a *BTS the line defined by \a *MolCenter and \a *x crosses through.
374 * We call Vector::GetIntersectionWithPlane() to receive the intersection point with the plane
375 * This we test if it's really on the plane and whether it's inside the triangle on the plane or not.
376 * The latter is done as follows: We calculate the cross point of one of the triangle's baseline with the line
377 * given by the intersection and the third basepoint. Then, we check whether it's on the baseline (i.e. between
378 * the first two basepoints) or not.
379 * \param *out output stream for debugging
380 * \param *MolCenter offset vector of line
381 * \param *x second endpoint of line, minus \a *MolCenter is directional vector of line
382 * \param *Intersection intersection on plane on return
383 * \return true - \a *Intersection contains intersection on plane defined by triangle, false - zero vector if outside of triangle.
384 */
385bool BoundaryTriangleSet::GetIntersectionInsideTriangle(ofstream *out, Vector *MolCenter, Vector *x, Vector *Intersection)
386{
387 Vector CrossPoint;
388 Vector helper;
389
390 if (!Intersection->GetIntersectionWithPlane(out, &NormalVector, endpoints[0]->node->node, MolCenter, x)) {
391 *out << Verbose(1) << "Alas! Intersection with plane failed - at least numerically - the intersection is not on the plane!" << endl;
392 return false;
393 }
394
395 // Calculate cross point between one baseline and the line from the third endpoint to intersection
396 int i=0;
397 do {
398 if (CrossPoint.GetIntersectionOfTwoLinesOnPlane(out, endpoints[i%3]->node->node, endpoints[(i+1)%3]->node->node, endpoints[(i+2)%3]->node->node, Intersection, &NormalVector)) {
399 helper.CopyVector(endpoints[(i+1)%3]->node->node);
400 helper.SubtractVector(endpoints[i%3]->node->node);
401 } else
402 i++;
403 if (i>2)
404 break;
405 } while (CrossPoint.NormSquared() < MYEPSILON);
406 if (i==3) {
407 *out << Verbose(1) << "ERROR: Could not find any cross points, something's utterly wrong here!" << endl;
408 exit(255);
409 }
410 CrossPoint.SubtractVector(endpoints[i%3]->node->node); // cross point was returned as absolute vector
411
412 // check whether intersection is inside or not by comparing length of intersection and length of cross point
413 if ((CrossPoint.NormSquared() - helper.NormSquared()) < MYEPSILON) { // inside
414 return true;
415 } else { // outside!
416 Intersection->Zero();
417 return false;
418 }
419};
420
421/** Checks whether lines is any of the three boundary lines this triangle contains.
422 * \param *line line to test
423 * \return true - line is of the triangle, false - is not
424 */
425bool BoundaryTriangleSet::ContainsBoundaryLine(class BoundaryLineSet *line)
426{
427 for(int i=0;i<3;i++)
428 if (line == lines[i])
429 return true;
430 return false;
431};
432
433/** Checks whether point is any of the three endpoints this triangle contains.
434 * \param *point point to test
435 * \return true - point is of the triangle, false - is not
436 */
437bool BoundaryTriangleSet::ContainsBoundaryPoint(class BoundaryPointSet *point)
438{
439 for(int i=0;i<3;i++)
440 if (point == endpoints[i])
441 return true;
442 return false;
443};
444
445/** Checks whether point is any of the three endpoints this triangle contains.
446 * \param *point TesselPoint to test
447 * \return true - point is of the triangle, false - is not
448 */
449bool BoundaryTriangleSet::ContainsBoundaryPoint(class TesselPoint *point)
450{
451 for(int i=0;i<3;i++)
452 if (point == endpoints[i]->node)
453 return true;
454 return false;
455};
456
457/** Checks whether three given \a *Points coincide with triangle's endpoints.
458 * \param *Points[3] pointer to BoundaryPointSet
459 * \return true - is the very triangle, false - is not
460 */
461bool BoundaryTriangleSet::IsPresentTupel(class BoundaryPointSet *Points[3])
462{
463 return (((endpoints[0] == Points[0])
464 || (endpoints[0] == Points[1])
465 || (endpoints[0] == Points[2])
466 ) && (
467 (endpoints[1] == Points[0])
468 || (endpoints[1] == Points[1])
469 || (endpoints[1] == Points[2])
470 ) && (
471 (endpoints[2] == Points[0])
472 || (endpoints[2] == Points[1])
473 || (endpoints[2] == Points[2])
474
475 ));
476};
477
478/** Checks whether three given \a *Points coincide with triangle's endpoints.
479 * \param *Points[3] pointer to BoundaryPointSet
480 * \return true - is the very triangle, false - is not
481 */
482bool BoundaryTriangleSet::IsPresentTupel(class BoundaryTriangleSet *T)
483{
484 return (((endpoints[0] == T->endpoints[0])
485 || (endpoints[0] == T->endpoints[1])
486 || (endpoints[0] == T->endpoints[2])
487 ) && (
488 (endpoints[1] == T->endpoints[0])
489 || (endpoints[1] == T->endpoints[1])
490 || (endpoints[1] == T->endpoints[2])
491 ) && (
492 (endpoints[2] == T->endpoints[0])
493 || (endpoints[2] == T->endpoints[1])
494 || (endpoints[2] == T->endpoints[2])
495
496 ));
497};
498
499/** Returns the endpoint which is not contained in the given \a *line.
500 * \param *line baseline defining two endpoints
501 * \return pointer third endpoint or NULL if line does not belong to triangle.
502 */
503class BoundaryPointSet *BoundaryTriangleSet::GetThirdEndpoint(class BoundaryLineSet *line)
504{
505 // sanity check
506 if (!ContainsBoundaryLine(line))
507 return NULL;
508 for(int i=0;i<3;i++)
509 if (!line->ContainsBoundaryPoint(endpoints[i]))
510 return endpoints[i];
511 // actually, that' impossible :)
512 return NULL;
513};
514
515/** Calculates the center point of the triangle.
516 * Is third of the sum of all endpoints.
517 * \param *center central point on return.
518 */
519void BoundaryTriangleSet::GetCenter(Vector *center)
520{
521 center->Zero();
522 for(int i=0;i<3;i++)
523 center->AddVector(endpoints[i]->node->node);
524 center->Scale(1./3.);
525}
526
527/** output operator for BoundaryTriangleSet.
528 * \param &ost output stream
529 * \param &a boundary triangle
530 */
531ostream &operator <<(ostream &ost, BoundaryTriangleSet &a)
532{
533 ost << "[" << a.Nr << "|" << a.endpoints[0]->node->Name << " at " << *a.endpoints[0]->node->node << ","
534 << a.endpoints[1]->node->Name << " at " << *a.endpoints[1]->node->node << "," << a.endpoints[2]->node->Name << " at " << *a.endpoints[2]->node->node << "]";
535 return ost;
536};
537
538// =========================================================== class TESSELPOINT ===========================================
539
540/** Constructor of class TesselPoint.
541 */
542TesselPoint::TesselPoint()
543{
544 node = NULL;
545 nr = -1;
546 Name = NULL;
547};
548
549/** Destructor for class TesselPoint.
550 */
551TesselPoint::~TesselPoint()
552{
553};
554
555/** Prints LCNode to screen.
556 */
557ostream & operator << (ostream &ost, const TesselPoint &a)
558{
559 ost << "[" << (a.Name) << "|" << a.Name << " at " << *a.node << "]";
560 return ost;
561};
562
563/** Prints LCNode to screen.
564 */
565ostream & TesselPoint::operator << (ostream &ost)
566{
567 ost << "[" << (Name) << "|" << this << "]";
568 return ost;
569};
570
571
572// =========================================================== class POINTCLOUD ============================================
573
574/** Constructor of class PointCloud.
575 */
576PointCloud::PointCloud()
577{
578
579};
580
581/** Destructor for class PointCloud.
582 */
583PointCloud::~PointCloud()
584{
585
586};
587
588// ============================ CandidateForTesselation =============================
589
590/** Constructor of class CandidateForTesselation.
591 */
592CandidateForTesselation::CandidateForTesselation(TesselPoint *candidate, BoundaryLineSet* line, Vector OptCandidateCenter, Vector OtherOptCandidateCenter) {
593 point = candidate;
594 BaseLine = line;
595 OptCenter.CopyVector(&OptCandidateCenter);
596 OtherOptCenter.CopyVector(&OtherOptCandidateCenter);
597};
598
599/** Destructor for class CandidateForTesselation.
600 */
601CandidateForTesselation::~CandidateForTesselation() {
602 point = NULL;
603 BaseLine = NULL;
604};
605
606// =========================================================== class TESSELATION ===========================================
607
608/** Constructor of class Tesselation.
609 */
610Tesselation::Tesselation()
611{
612 PointsOnBoundaryCount = 0;
613 LinesOnBoundaryCount = 0;
614 TrianglesOnBoundaryCount = 0;
615 InternalPointer = PointsOnBoundary.begin();
616 LastTriangle = NULL;
617 TriangleFilesWritten = 0;
618}
619;
620
621/** Destructor of class Tesselation.
622 * We have to free all points, lines and triangles.
623 */
624Tesselation::~Tesselation()
625{
626 cout << Verbose(1) << "Free'ing TesselStruct ... " << endl;
627 for (TriangleMap::iterator runner = TrianglesOnBoundary.begin(); runner != TrianglesOnBoundary.end(); runner++) {
628 if (runner->second != NULL) {
629 delete (runner->second);
630 runner->second = NULL;
631 } else
632 cerr << "ERROR: The triangle " << runner->first << " has already been free'd." << endl;
633 }
634 cout << "This envelope was written to file " << TriangleFilesWritten << " times(s)." << endl;
635}
636;
637
638/** PointCloud implementation of GetCenter
639 * Uses PointsOnBoundary and STL stuff.
640 */
641Vector * Tesselation::GetCenter(ofstream *out)
642{
643 Vector *Center = new Vector(0.,0.,0.);
644 int num=0;
645 for (GoToFirst(); (!IsEnd()); GoToNext()) {
646 Center->AddVector(GetPoint()->node);
647 num++;
648 }
649 Center->Scale(1./num);
650 return Center;
651};
652
653/** PointCloud implementation of GoPoint
654 * Uses PointsOnBoundary and STL stuff.
655 */
656TesselPoint * Tesselation::GetPoint()
657{
658 return (InternalPointer->second->node);
659};
660
661/** PointCloud implementation of GetTerminalPoint.
662 * Uses PointsOnBoundary and STL stuff.
663 */
664TesselPoint * Tesselation::GetTerminalPoint()
665{
666 PointMap::iterator Runner = PointsOnBoundary.end();
667 Runner--;
668 return (Runner->second->node);
669};
670
671/** PointCloud implementation of GoToNext.
672 * Uses PointsOnBoundary and STL stuff.
673 */
674void Tesselation::GoToNext()
675{
676 if (InternalPointer != PointsOnBoundary.end())
677 InternalPointer++;
678};
679
680/** PointCloud implementation of GoToPrevious.
681 * Uses PointsOnBoundary and STL stuff.
682 */
683void Tesselation::GoToPrevious()
684{
685 if (InternalPointer != PointsOnBoundary.begin())
686 InternalPointer--;
687};
688
689/** PointCloud implementation of GoToFirst.
690 * Uses PointsOnBoundary and STL stuff.
691 */
692void Tesselation::GoToFirst()
693{
694 InternalPointer = PointsOnBoundary.begin();
695};
696
697/** PointCloud implementation of GoToLast.
698 * Uses PointsOnBoundary and STL stuff.
699 */
700void Tesselation::GoToLast()
701{
702 InternalPointer = PointsOnBoundary.end();
703 InternalPointer--;
704};
705
706/** PointCloud implementation of IsEmpty.
707 * Uses PointsOnBoundary and STL stuff.
708 */
709bool Tesselation::IsEmpty()
710{
711 return (PointsOnBoundary.empty());
712};
713
714/** PointCloud implementation of IsLast.
715 * Uses PointsOnBoundary and STL stuff.
716 */
717bool Tesselation::IsEnd()
718{
719 return (InternalPointer == PointsOnBoundary.end());
720};
721
722
723/** Gueses first starting triangle of the convex envelope.
724 * We guess the starting triangle by taking the smallest distance between two points and looking for a fitting third.
725 * \param *out output stream for debugging
726 * \param PointsOnBoundary set of boundary points defining the convex envelope of the cluster
727 */
728void
729Tesselation::GuessStartingTriangle(ofstream *out)
730{
731 // 4b. create a starting triangle
732 // 4b1. create all distances
733 DistanceMultiMap DistanceMMap;
734 double distance, tmp;
735 Vector PlaneVector, TrialVector;
736 PointMap::iterator A, B, C; // three nodes of the first triangle
737 A = PointsOnBoundary.begin(); // the first may be chosen arbitrarily
738
739 // with A chosen, take each pair B,C and sort
740 if (A != PointsOnBoundary.end())
741 {
742 B = A;
743 B++;
744 for (; B != PointsOnBoundary.end(); B++)
745 {
746 C = B;
747 C++;
748 for (; C != PointsOnBoundary.end(); C++)
749 {
750 tmp = A->second->node->node->DistanceSquared(B->second->node->node);
751 distance = tmp * tmp;
752 tmp = A->second->node->node->DistanceSquared(C->second->node->node);
753 distance += tmp * tmp;
754 tmp = B->second->node->node->DistanceSquared(C->second->node->node);
755 distance += tmp * tmp;
756 DistanceMMap.insert(DistanceMultiMapPair(distance, pair<PointMap::iterator, PointMap::iterator> (B, C)));
757 }
758 }
759 }
760 // // listing distances
761 // *out << Verbose(1) << "Listing DistanceMMap:";
762 // for(DistanceMultiMap::iterator runner = DistanceMMap.begin(); runner != DistanceMMap.end(); runner++) {
763 // *out << " " << runner->first << "(" << *runner->second.first->second << ", " << *runner->second.second->second << ")";
764 // }
765 // *out << endl;
766 // 4b2. pick three baselines forming a triangle
767 // 1. we take from the smallest sum of squared distance as the base line BC (with peak A) onward as the triangle candidate
768 DistanceMultiMap::iterator baseline = DistanceMMap.begin();
769 for (; baseline != DistanceMMap.end(); baseline++)
770 {
771 // we take from the smallest sum of squared distance as the base line BC (with peak A) onward as the triangle candidate
772 // 2. next, we have to check whether all points reside on only one side of the triangle
773 // 3. construct plane vector
774 PlaneVector.MakeNormalVector(A->second->node->node,
775 baseline->second.first->second->node->node,
776 baseline->second.second->second->node->node);
777 *out << Verbose(2) << "Plane vector of candidate triangle is ";
778 PlaneVector.Output(out);
779 *out << endl;
780 // 4. loop over all points
781 double sign = 0.;
782 PointMap::iterator checker = PointsOnBoundary.begin();
783 for (; checker != PointsOnBoundary.end(); checker++)
784 {
785 // (neglecting A,B,C)
786 if ((checker == A) || (checker == baseline->second.first) || (checker
787 == baseline->second.second))
788 continue;
789 // 4a. project onto plane vector
790 TrialVector.CopyVector(checker->second->node->node);
791 TrialVector.SubtractVector(A->second->node->node);
792 distance = TrialVector.ScalarProduct(&PlaneVector);
793 if (fabs(distance) < 1e-4) // we need to have a small epsilon around 0 which is still ok
794 continue;
795 *out << Verbose(3) << "Projection of " << checker->second->node->Name
796 << " yields distance of " << distance << "." << endl;
797 tmp = distance / fabs(distance);
798 // 4b. Any have different sign to than before? (i.e. would lie outside convex hull with this starting triangle)
799 if ((sign != 0) && (tmp != sign))
800 {
801 // 4c. If so, break 4. loop and continue with next candidate in 1. loop
802 *out << Verbose(2) << "Current candidates: "
803 << A->second->node->Name << ","
804 << baseline->second.first->second->node->Name << ","
805 << baseline->second.second->second->node->Name << " leaves "
806 << checker->second->node->Name << " outside the convex hull."
807 << endl;
808 break;
809 }
810 else
811 { // note the sign for later
812 *out << Verbose(2) << "Current candidates: "
813 << A->second->node->Name << ","
814 << baseline->second.first->second->node->Name << ","
815 << baseline->second.second->second->node->Name << " leave "
816 << checker->second->node->Name << " inside the convex hull."
817 << endl;
818 sign = tmp;
819 }
820 // 4d. Check whether the point is inside the triangle (check distance to each node
821 tmp = checker->second->node->node->DistanceSquared(A->second->node->node);
822 int innerpoint = 0;
823 if ((tmp < A->second->node->node->DistanceSquared(
824 baseline->second.first->second->node->node)) && (tmp
825 < A->second->node->node->DistanceSquared(
826 baseline->second.second->second->node->node)))
827 innerpoint++;
828 tmp = checker->second->node->node->DistanceSquared(
829 baseline->second.first->second->node->node);
830 if ((tmp < baseline->second.first->second->node->node->DistanceSquared(
831 A->second->node->node)) && (tmp
832 < baseline->second.first->second->node->node->DistanceSquared(
833 baseline->second.second->second->node->node)))
834 innerpoint++;
835 tmp = checker->second->node->node->DistanceSquared(
836 baseline->second.second->second->node->node);
837 if ((tmp < baseline->second.second->second->node->node->DistanceSquared(
838 baseline->second.first->second->node->node)) && (tmp
839 < baseline->second.second->second->node->node->DistanceSquared(
840 A->second->node->node)))
841 innerpoint++;
842 // 4e. If so, break 4. loop and continue with next candidate in 1. loop
843 if (innerpoint == 3)
844 break;
845 }
846 // 5. come this far, all on same side? Then break 1. loop and construct triangle
847 if (checker == PointsOnBoundary.end())
848 {
849 *out << "Looks like we have a candidate!" << endl;
850 break;
851 }
852 }
853 if (baseline != DistanceMMap.end())
854 {
855 BPS[0] = baseline->second.first->second;
856 BPS[1] = baseline->second.second->second;
857 BLS[0] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
858 BPS[0] = A->second;
859 BPS[1] = baseline->second.second->second;
860 BLS[1] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
861 BPS[0] = baseline->second.first->second;
862 BPS[1] = A->second;
863 BLS[2] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
864
865 // 4b3. insert created triangle
866 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
867 TrianglesOnBoundary.insert(TrianglePair(TrianglesOnBoundaryCount, BTS));
868 TrianglesOnBoundaryCount++;
869 for (int i = 0; i < NDIM; i++)
870 {
871 LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount, BTS->lines[i]));
872 LinesOnBoundaryCount++;
873 }
874
875 *out << Verbose(1) << "Starting triangle is " << *BTS << "." << endl;
876 }
877 else
878 {
879 *out << Verbose(1) << "No starting triangle found." << endl;
880 exit(255);
881 }
882}
883;
884
885/** Tesselates the convex envelope of a cluster from a single starting triangle.
886 * The starting triangle is made out of three baselines. Each line in the final tesselated cluster may belong to at most
887 * 2 triangles. Hence, we go through all current lines:
888 * -# if the lines contains to only one triangle
889 * -# We search all points in the boundary
890 * -# if the triangle is in forward direction of the baseline (at most 90 degrees angle between vector orthogonal to
891 * baseline in triangle plane pointing out of the triangle and normal vector of new triangle)
892 * -# if the triangle with the baseline and the current point has the smallest of angles (comparison between normal vectors)
893 * -# then we have a new triangle, whose baselines we again add (or increase their TriangleCount)
894 * \param *out output stream for debugging
895 * \param *configuration for IsAngstroem
896 * \param *cloud cluster of points
897 */
898void Tesselation::TesselateOnBoundary(ofstream *out, PointCloud *cloud)
899{
900 bool flag;
901 PointMap::iterator winner;
902 class BoundaryPointSet *peak = NULL;
903 double SmallestAngle, TempAngle;
904 Vector NormalVector, VirtualNormalVector, CenterVector, TempVector, helper, PropagationVector, *Center = NULL;
905 LineMap::iterator LineChecker[2];
906
907 Center = cloud->GetCenter(out);
908 // create a first tesselation with the given BoundaryPoints
909 do {
910 flag = false;
911 for (LineMap::iterator baseline = LinesOnBoundary.begin(); baseline != LinesOnBoundary.end(); baseline++)
912 if (baseline->second->triangles.size() == 1) {
913 // 5a. go through each boundary point if not _both_ edges between either endpoint of the current line and this point exist (and belong to 2 triangles)
914 SmallestAngle = M_PI;
915
916 // get peak point with respect to this base line's only triangle
917 BTS = baseline->second->triangles.begin()->second; // there is only one triangle so far
918 *out << Verbose(2) << "Current baseline is between " << *(baseline->second) << "." << endl;
919 for (int i = 0; i < 3; i++)
920 if ((BTS->endpoints[i] != baseline->second->endpoints[0]) && (BTS->endpoints[i] != baseline->second->endpoints[1]))
921 peak = BTS->endpoints[i];
922 *out << Verbose(3) << " and has peak " << *peak << "." << endl;
923
924 // prepare some auxiliary vectors
925 Vector BaseLineCenter, BaseLine;
926 BaseLineCenter.CopyVector(baseline->second->endpoints[0]->node->node);
927 BaseLineCenter.AddVector(baseline->second->endpoints[1]->node->node);
928 BaseLineCenter.Scale(1. / 2.); // points now to center of base line
929 BaseLine.CopyVector(baseline->second->endpoints[0]->node->node);
930 BaseLine.SubtractVector(baseline->second->endpoints[1]->node->node);
931
932 // offset to center of triangle
933 CenterVector.Zero();
934 for (int i = 0; i < 3; i++)
935 CenterVector.AddVector(BTS->endpoints[i]->node->node);
936 CenterVector.Scale(1. / 3.);
937 *out << Verbose(4) << "CenterVector of base triangle is " << CenterVector << endl;
938
939 // normal vector of triangle
940 NormalVector.CopyVector(Center);
941 NormalVector.SubtractVector(&CenterVector);
942 BTS->GetNormalVector(NormalVector);
943 NormalVector.CopyVector(&BTS->NormalVector);
944 *out << Verbose(4) << "NormalVector of base triangle is " << NormalVector << endl;
945
946 // vector in propagation direction (out of triangle)
947 // project center vector onto triangle plane (points from intersection plane-NormalVector to plane-CenterVector intersection)
948 PropagationVector.MakeNormalVector(&BaseLine, &NormalVector);
949 TempVector.CopyVector(&CenterVector);
950 TempVector.SubtractVector(baseline->second->endpoints[0]->node->node); // TempVector is vector on triangle plane pointing from one baseline egde towards center!
951 //*out << Verbose(2) << "Projection of propagation onto temp: " << PropagationVector.Projection(&TempVector) << "." << endl;
952 if (PropagationVector.ScalarProduct(&TempVector) > 0) // make sure normal propagation vector points outward from baseline
953 PropagationVector.Scale(-1.);
954 *out << Verbose(4) << "PropagationVector of base triangle is " << PropagationVector << endl;
955 winner = PointsOnBoundary.end();
956
957 // loop over all points and calculate angle between normal vector of new and present triangle
958 for (PointMap::iterator target = PointsOnBoundary.begin(); target != PointsOnBoundary.end(); target++) {
959 if ((target->second != baseline->second->endpoints[0]) && (target->second != baseline->second->endpoints[1])) { // don't take the same endpoints
960 *out << Verbose(3) << "Target point is " << *(target->second) << ":" << endl;
961
962 // first check direction, so that triangles don't intersect
963 VirtualNormalVector.CopyVector(target->second->node->node);
964 VirtualNormalVector.SubtractVector(&BaseLineCenter); // points from center of base line to target
965 VirtualNormalVector.ProjectOntoPlane(&NormalVector);
966 TempAngle = VirtualNormalVector.Angle(&PropagationVector);
967 *out << Verbose(4) << "VirtualNormalVector is " << VirtualNormalVector << " and PropagationVector is " << PropagationVector << "." << endl;
968 if (TempAngle > (M_PI/2.)) { // no bends bigger than Pi/2 (90 degrees)
969 *out << Verbose(4) << "Angle on triangle plane between propagation direction and base line to " << *(target->second) << " is " << TempAngle << ", bad direction!" << endl;
970 continue;
971 } else
972 *out << Verbose(4) << "Angle on triangle plane between propagation direction and base line to " << *(target->second) << " is " << TempAngle << ", good direction!" << endl;
973
974 // check first and second endpoint (if any connecting line goes to target has at least not more than 1 triangle)
975 LineChecker[0] = baseline->second->endpoints[0]->lines.find(target->first);
976 LineChecker[1] = baseline->second->endpoints[1]->lines.find(target->first);
977 if (((LineChecker[0] != baseline->second->endpoints[0]->lines.end()) && (LineChecker[0]->second->triangles.size() == 2))) {
978 *out << Verbose(4) << *(baseline->second->endpoints[0]) << " has line " << *(LineChecker[0]->second) << " to " << *(target->second) << " as endpoint with " << LineChecker[0]->second->triangles.size() << " triangles." << endl;
979 continue;
980 }
981 if (((LineChecker[1] != baseline->second->endpoints[1]->lines.end()) && (LineChecker[1]->second->triangles.size() == 2))) {
982 *out << Verbose(4) << *(baseline->second->endpoints[1]) << " has line " << *(LineChecker[1]->second) << " to " << *(target->second) << " as endpoint with " << LineChecker[1]->second->triangles.size() << " triangles." << endl;
983 continue;
984 }
985
986 // check whether the envisaged triangle does not already exist (if both lines exist and have same endpoint)
987 if ((((LineChecker[0] != baseline->second->endpoints[0]->lines.end()) && (LineChecker[1] != baseline->second->endpoints[1]->lines.end()) && (GetCommonEndpoint(LineChecker[0]->second, LineChecker[1]->second) == peak)))) {
988 *out << Verbose(4) << "Current target is peak!" << endl;
989 continue;
990 }
991
992 // check for linear dependence
993 TempVector.CopyVector(baseline->second->endpoints[0]->node->node);
994 TempVector.SubtractVector(target->second->node->node);
995 helper.CopyVector(baseline->second->endpoints[1]->node->node);
996 helper.SubtractVector(target->second->node->node);
997 helper.ProjectOntoPlane(&TempVector);
998 if (fabs(helper.NormSquared()) < MYEPSILON) {
999 *out << Verbose(4) << "Chosen set of vectors is linear dependent." << endl;
1000 continue;
1001 }
1002
1003 // in case NOT both were found, create virtually this triangle, get its normal vector, calculate angle
1004 flag = true;
1005 VirtualNormalVector.MakeNormalVector(baseline->second->endpoints[0]->node->node, baseline->second->endpoints[1]->node->node, target->second->node->node);
1006 TempVector.CopyVector(baseline->second->endpoints[0]->node->node);
1007 TempVector.AddVector(baseline->second->endpoints[1]->node->node);
1008 TempVector.AddVector(target->second->node->node);
1009 TempVector.Scale(1./3.);
1010 TempVector.SubtractVector(Center);
1011 // make it always point outward
1012 if (VirtualNormalVector.ScalarProduct(&TempVector) < 0)
1013 VirtualNormalVector.Scale(-1.);
1014 // calculate angle
1015 TempAngle = NormalVector.Angle(&VirtualNormalVector);
1016 *out << Verbose(4) << "NormalVector is " << VirtualNormalVector << " and the angle is " << TempAngle << "." << endl;
1017 if ((SmallestAngle - TempAngle) > MYEPSILON) { // set to new possible winner
1018 SmallestAngle = TempAngle;
1019 winner = target;
1020 *out << Verbose(4) << "New winner " << *winner->second->node << " due to smaller angle between normal vectors." << endl;
1021 } else if (fabs(SmallestAngle - TempAngle) < MYEPSILON) { // check the angle to propagation, both possible targets are in one plane! (their normals have same angle)
1022 // hence, check the angles to some normal direction from our base line but in this common plane of both targets...
1023 helper.CopyVector(target->second->node->node);
1024 helper.SubtractVector(&BaseLineCenter);
1025 helper.ProjectOntoPlane(&BaseLine);
1026 // ...the one with the smaller angle is the better candidate
1027 TempVector.CopyVector(target->second->node->node);
1028 TempVector.SubtractVector(&BaseLineCenter);
1029 TempVector.ProjectOntoPlane(&VirtualNormalVector);
1030 TempAngle = TempVector.Angle(&helper);
1031 TempVector.CopyVector(winner->second->node->node);
1032 TempVector.SubtractVector(&BaseLineCenter);
1033 TempVector.ProjectOntoPlane(&VirtualNormalVector);
1034 if (TempAngle < TempVector.Angle(&helper)) {
1035 TempAngle = NormalVector.Angle(&VirtualNormalVector);
1036 SmallestAngle = TempAngle;
1037 winner = target;
1038 *out << Verbose(4) << "New winner " << *winner->second->node << " due to smaller angle " << TempAngle << " to propagation direction." << endl;
1039 } else
1040 *out << Verbose(4) << "Keeping old winner " << *winner->second->node << " due to smaller angle to propagation direction." << endl;
1041 } else
1042 *out << Verbose(4) << "Keeping old winner " << *winner->second->node << " due to smaller angle between normal vectors." << endl;
1043 }
1044 } // end of loop over all boundary points
1045
1046 // 5b. The point of the above whose triangle has the greatest angle with the triangle the current line belongs to (it only belongs to one, remember!): New triangle
1047 if (winner != PointsOnBoundary.end()) {
1048 *out << Verbose(2) << "Winning target point is " << *(winner->second) << " with angle " << SmallestAngle << "." << endl;
1049 // create the lins of not yet present
1050 BLS[0] = baseline->second;
1051 // 5c. add lines to the line set if those were new (not yet part of a triangle), delete lines that belong to two triangles)
1052 LineChecker[0] = baseline->second->endpoints[0]->lines.find(winner->first);
1053 LineChecker[1] = baseline->second->endpoints[1]->lines.find(winner->first);
1054 if (LineChecker[0] == baseline->second->endpoints[0]->lines.end()) { // create
1055 BPS[0] = baseline->second->endpoints[0];
1056 BPS[1] = winner->second;
1057 BLS[1] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
1058 LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount, BLS[1]));
1059 LinesOnBoundaryCount++;
1060 } else
1061 BLS[1] = LineChecker[0]->second;
1062 if (LineChecker[1] == baseline->second->endpoints[1]->lines.end()) { // create
1063 BPS[0] = baseline->second->endpoints[1];
1064 BPS[1] = winner->second;
1065 BLS[2] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
1066 LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount, BLS[2]));
1067 LinesOnBoundaryCount++;
1068 } else
1069 BLS[2] = LineChecker[1]->second;
1070 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
1071 BTS->GetCenter(&helper);
1072 helper.SubtractVector(Center);
1073 helper.Scale(-1);
1074 BTS->GetNormalVector(helper);
1075 TrianglesOnBoundary.insert(TrianglePair(TrianglesOnBoundaryCount, BTS));
1076 TrianglesOnBoundaryCount++;
1077 } else {
1078 *out << Verbose(1) << "I could not determine a winner for this baseline " << *(baseline->second) << "." << endl;
1079 }
1080
1081 // 5d. If the set of lines is not yet empty, go to 5. and continue
1082 } else
1083 *out << Verbose(2) << "Baseline candidate " << *(baseline->second) << " has a triangle count of " << baseline->second->triangles.size() << "." << endl;
1084 } while (flag);
1085
1086 // exit
1087 delete(Center);
1088};
1089
1090/** Inserts all points outside of the tesselated surface into it by adding new triangles.
1091 * \param *out output stream for debugging
1092 * \param *cloud cluster of points
1093 * \param *LC LinkedCell structure to find nearest point quickly
1094 * \return true - all straddling points insert, false - something went wrong
1095 */
1096bool Tesselation::InsertStraddlingPoints(ofstream *out, PointCloud *cloud, LinkedCell *LC)
1097{
1098 Vector Intersection, Normal;
1099 TesselPoint *Walker = NULL;
1100 Vector *Center = cloud->GetCenter(out);
1101 list<BoundaryTriangleSet*> *triangles = NULL;
1102 bool AddFlag = false;
1103 LinkedCell *BoundaryPoints = NULL;
1104
1105 *out << Verbose(1) << "Begin of InsertStraddlingPoints" << endl;
1106
1107 cloud->GoToFirst();
1108 BoundaryPoints = new LinkedCell(this, 5.);
1109 while (!cloud->IsEnd()) { // we only have to go once through all points, as boundary can become only bigger
1110 if (AddFlag) {
1111 delete(BoundaryPoints);
1112 BoundaryPoints = new LinkedCell(this, 5.);
1113 AddFlag = false;
1114 }
1115 Walker = cloud->GetPoint();
1116 *out << Verbose(2) << "Current point is " << *Walker << "." << endl;
1117 // get the next triangle
1118 triangles = FindClosestTrianglesToPoint(out, Walker->node, BoundaryPoints);
1119 BTS = triangles->front();
1120 if ((triangles == NULL) || (BTS->ContainsBoundaryPoint(Walker))) {
1121 *out << Verbose(2) << "No triangles found, probably a tesselation point itself." << endl;
1122 cloud->GoToNext();
1123 continue;
1124 } else {
1125 }
1126 *out << Verbose(2) << "Closest triangle is " << *BTS << "." << endl;
1127 // get the intersection point
1128 if (BTS->GetIntersectionInsideTriangle(out, Center, Walker->node, &Intersection)) {
1129 *out << Verbose(2) << "We have an intersection at " << Intersection << "." << endl;
1130 // we have the intersection, check whether in- or outside of boundary
1131 if ((Center->DistanceSquared(Walker->node) - Center->DistanceSquared(&Intersection)) < -MYEPSILON) {
1132 // inside, next!
1133 *out << Verbose(2) << *Walker << " is inside wrt triangle " << *BTS << "." << endl;
1134 } else {
1135 // outside!
1136 *out << Verbose(2) << *Walker << " is outside wrt triangle " << *BTS << "." << endl;
1137 class BoundaryLineSet *OldLines[3], *NewLines[3];
1138 class BoundaryPointSet *OldPoints[3], *NewPoint;
1139 // store the three old lines and old points
1140 for (int i=0;i<3;i++) {
1141 OldLines[i] = BTS->lines[i];
1142 OldPoints[i] = BTS->endpoints[i];
1143 }
1144 Normal.CopyVector(&BTS->NormalVector);
1145 // add Walker to boundary points
1146 *out << Verbose(2) << "Adding " << *Walker << " to BoundaryPoints." << endl;
1147 AddFlag = true;
1148 if (AddBoundaryPoint(Walker,0))
1149 NewPoint = BPS[0];
1150 else
1151 continue;
1152 // remove triangle
1153 *out << Verbose(2) << "Erasing triangle " << *BTS << "." << endl;
1154 TrianglesOnBoundary.erase(BTS->Nr);
1155 delete(BTS);
1156 // create three new boundary lines
1157 for (int i=0;i<3;i++) {
1158 BPS[0] = NewPoint;
1159 BPS[1] = OldPoints[i];
1160 NewLines[i] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
1161 *out << Verbose(3) << "Creating new line " << *NewLines[i] << "." << endl;
1162 LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount, NewLines[i])); // no need for check for unique insertion as BPS[0] is definitely a new one
1163 LinesOnBoundaryCount++;
1164 }
1165 // create three new triangle with new point
1166 for (int i=0;i<3;i++) { // find all baselines
1167 BLS[0] = OldLines[i];
1168 int n = 1;
1169 for (int j=0;j<3;j++) {
1170 if (NewLines[j]->IsConnectedTo(BLS[0])) {
1171 if (n>2) {
1172 *out << Verbose(1) << "ERROR: " << BLS[0] << " connects to all of the new lines?!" << endl;
1173 return false;
1174 } else
1175 BLS[n++] = NewLines[j];
1176 }
1177 }
1178 // create the triangle
1179 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
1180 Normal.Scale(-1.);
1181 BTS->GetNormalVector(Normal);
1182 Normal.Scale(-1.);
1183 *out << Verbose(2) << "Created new triangle " << *BTS << "." << endl;
1184 TrianglesOnBoundary.insert(TrianglePair(TrianglesOnBoundaryCount, BTS));
1185 TrianglesOnBoundaryCount++;
1186 }
1187 }
1188 } else { // something is wrong with FindClosestTriangleToPoint!
1189 *out << Verbose(1) << "ERROR: The closest triangle did not produce an intersection!" << endl;
1190 return false;
1191 }
1192 cloud->GoToNext();
1193 }
1194
1195 // exit
1196 delete(Center);
1197 *out << Verbose(1) << "End of InsertStraddlingPoints" << endl;
1198 return true;
1199};
1200
1201/** Adds a point to the tesselation::PointsOnBoundary list.
1202 * \param *Walker point to add
1203 * \param n TesselStruct::BPS index to put pointer into
1204 * \return true - new point was added, false - point already present
1205 */
1206bool
1207Tesselation::AddBoundaryPoint(TesselPoint *Walker, int n)
1208{
1209 PointTestPair InsertUnique;
1210 BPS[n] = new class BoundaryPointSet(Walker);
1211 InsertUnique = PointsOnBoundary.insert(PointPair(Walker->nr, BPS[n]));
1212 if (InsertUnique.second) { // if new point was not present before, increase counter
1213 PointsOnBoundaryCount++;
1214 return true;
1215 } else {
1216 delete(BPS[n]);
1217 BPS[n] = InsertUnique.first->second;
1218 return false;
1219 }
1220}
1221;
1222
1223/** Adds point to Tesselation::PointsOnBoundary if not yet present.
1224 * Tesselation::TPS is set to either this new BoundaryPointSet or to the existing one of not unique.
1225 * @param Candidate point to add
1226 * @param n index for this point in Tesselation::TPS array
1227 */
1228void
1229Tesselation::AddTesselationPoint(TesselPoint* Candidate, int n)
1230{
1231 PointTestPair InsertUnique;
1232 TPS[n] = new class BoundaryPointSet(Candidate);
1233 InsertUnique = PointsOnBoundary.insert(PointPair(Candidate->nr, TPS[n]));
1234 if (InsertUnique.second) { // if new point was not present before, increase counter
1235 PointsOnBoundaryCount++;
1236 } else {
1237 delete TPS[n];
1238 cout << Verbose(4) << "Node " << *((InsertUnique.first)->second->node) << " is already present in PointsOnBoundary." << endl;
1239 TPS[n] = (InsertUnique.first)->second;
1240 }
1241}
1242;
1243
1244/** Function tries to add line from current Points in BPS to BoundaryLineSet.
1245 * If successful it raises the line count and inserts the new line into the BLS,
1246 * if unsuccessful, it writes the line which had been present into the BLS, deleting the new constructed one.
1247 * @param *a first endpoint
1248 * @param *b second endpoint
1249 * @param n index of Tesselation::BLS giving the line with both endpoints
1250 */
1251void Tesselation::AddTesselationLine(class BoundaryPointSet *a, class BoundaryPointSet *b, int n) {
1252 bool insertNewLine = true;
1253
1254 if (a->lines.find(b->node->nr) != a->lines.end()) {
1255 LineMap::iterator FindLine = a->lines.find(b->node->nr);
1256 pair<LineMap::iterator,LineMap::iterator> FindPair;
1257 FindPair = a->lines.equal_range(b->node->nr);
1258 cout << Verbose(5) << "INFO: There is at least one line between " << *a << " and " << *b << ": " << *(FindLine->second) << "." << endl;
1259
1260 for (FindLine = FindPair.first; FindLine != FindPair.second; FindLine++) {
1261 // If there is a line with less than two attached triangles, we don't need a new line.
1262 if (FindLine->second->triangles.size() < 2) {
1263 insertNewLine = false;
1264 cout << Verbose(4) << "Using existing line " << *FindLine->second << endl;
1265
1266 BPS[0] = FindLine->second->endpoints[0];
1267 BPS[1] = FindLine->second->endpoints[1];
1268 BLS[n] = FindLine->second;
1269
1270 break;
1271 }
1272 }
1273 }
1274
1275 if (insertNewLine) {
1276 AlwaysAddTesselationTriangleLine(a, b, n);
1277 }
1278}
1279;
1280
1281/**
1282 * Adds lines from each of the current points in the BPS to BoundaryLineSet.
1283 * Raises the line count and inserts the new line into the BLS.
1284 *
1285 * @param *a first endpoint
1286 * @param *b second endpoint
1287 * @param n index of Tesselation::BLS giving the line with both endpoints
1288 */
1289void Tesselation::AlwaysAddTesselationTriangleLine(class BoundaryPointSet *a, class BoundaryPointSet *b, int n)
1290{
1291 cout << Verbose(4) << "Adding line [" << LinesOnBoundaryCount << "|" << *(a->node) << " and " << *(b->node) << "." << endl;
1292 BPS[0] = a;
1293 BPS[1] = b;
1294 BLS[n] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount); // this also adds the line to the local maps
1295 // add line to global map
1296 LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount, BLS[n]));
1297 // increase counter
1298 LinesOnBoundaryCount++;
1299};
1300
1301/** Function adds triangle to global list.
1302 * Furthermore, the triangle receives the next free id and id counter \a TrianglesOnBoundaryCount is increased.
1303 */
1304void Tesselation::AddTesselationTriangle()
1305{
1306 cout << Verbose(1) << "Adding triangle to global TrianglesOnBoundary map." << endl;
1307
1308 // add triangle to global map
1309 TrianglesOnBoundary.insert(TrianglePair(TrianglesOnBoundaryCount, BTS));
1310 TrianglesOnBoundaryCount++;
1311
1312 // set as last new triangle
1313 LastTriangle = BTS;
1314
1315 // NOTE: add triangle to local maps is done in constructor of BoundaryTriangleSet
1316};
1317
1318/** Function adds triangle to global list.
1319 * Furthermore, the triangle number is set to \a nr.
1320 * \param nr triangle number
1321 */
1322void Tesselation::AddTesselationTriangle(int nr)
1323{
1324 cout << Verbose(1) << "Adding triangle to global TrianglesOnBoundary map." << endl;
1325
1326 // add triangle to global map
1327 TrianglesOnBoundary.insert(TrianglePair(nr, BTS));
1328
1329 // set as last new triangle
1330 LastTriangle = BTS;
1331
1332 // NOTE: add triangle to local maps is done in constructor of BoundaryTriangleSet
1333};
1334
1335/** Removes a triangle from the tesselation.
1336 * Removes itself from the TriangleMap's of its lines, calls for them RemoveTriangleLine() if they are no more connected.
1337 * Removes itself from memory.
1338 * \param *triangle to remove
1339 */
1340void Tesselation::RemoveTesselationTriangle(class BoundaryTriangleSet *triangle)
1341{
1342 if (triangle == NULL)
1343 return;
1344 for (int i = 0; i < 3; i++) {
1345 if (triangle->lines[i] != NULL) {
1346 cout << Verbose(5) << "Removing triangle Nr." << triangle->Nr << " in line " << *triangle->lines[i] << "." << endl;
1347 triangle->lines[i]->triangles.erase(triangle->Nr);
1348 if (triangle->lines[i]->triangles.empty()) {
1349 cout << Verbose(5) << *triangle->lines[i] << " is no more attached to any triangle, erasing." << endl;
1350 RemoveTesselationLine(triangle->lines[i]);
1351 } else {
1352 cout << Verbose(5) << *triangle->lines[i] << " is still attached to another triangle: ";
1353 for(TriangleMap::iterator TriangleRunner = triangle->lines[i]->triangles.begin(); TriangleRunner != triangle->lines[i]->triangles.end(); TriangleRunner++)
1354 cout << "[" << (TriangleRunner->second)->Nr << "|" << *((TriangleRunner->second)->endpoints[0]) << ", " << *((TriangleRunner->second)->endpoints[1]) << ", " << *((TriangleRunner->second)->endpoints[2]) << "] \t";
1355 cout << endl;
1356// for (int j=0;j<2;j++) {
1357// cout << Verbose(5) << "Lines of endpoint " << *(triangle->lines[i]->endpoints[j]) << ": ";
1358// for(LineMap::iterator LineRunner = triangle->lines[i]->endpoints[j]->lines.begin(); LineRunner != triangle->lines[i]->endpoints[j]->lines.end(); LineRunner++)
1359// cout << "[" << *(LineRunner->second) << "] \t";
1360// cout << endl;
1361// }
1362 }
1363 triangle->lines[i] = NULL; // free'd or not: disconnect
1364 } else
1365 cerr << "ERROR: This line " << i << " has already been free'd." << endl;
1366 }
1367
1368 if (TrianglesOnBoundary.erase(triangle->Nr))
1369 cout << Verbose(5) << "Removing triangle Nr. " << triangle->Nr << "." << endl;
1370 delete(triangle);
1371};
1372
1373/** Removes a line from the tesselation.
1374 * Removes itself from each endpoints' LineMap, then removes itself from global LinesOnBoundary list and free's the line.
1375 * \param *line line to remove
1376 */
1377void Tesselation::RemoveTesselationLine(class BoundaryLineSet *line)
1378{
1379 int Numbers[2];
1380
1381 if (line == NULL)
1382 return;
1383 // get other endpoint number for finding copies of same line
1384 if (line->endpoints[1] != NULL)
1385 Numbers[0] = line->endpoints[1]->Nr;
1386 else
1387 Numbers[0] = -1;
1388 if (line->endpoints[0] != NULL)
1389 Numbers[1] = line->endpoints[0]->Nr;
1390 else
1391 Numbers[1] = -1;
1392
1393 for (int i = 0; i < 2; i++) {
1394 if (line->endpoints[i] != NULL) {
1395 if (Numbers[i] != -1) { // as there may be multiple lines with same endpoints, we have to go through each and find in the endpoint's line list this line set
1396 pair<LineMap::iterator, LineMap::iterator> erasor = line->endpoints[i]->lines.equal_range(Numbers[i]);
1397 for (LineMap::iterator Runner = erasor.first; Runner != erasor.second; Runner++)
1398 if ((*Runner).second == line) {
1399 cout << Verbose(5) << "Removing Line Nr. " << line->Nr << " in boundary point " << *line->endpoints[i] << "." << endl;
1400 line->endpoints[i]->lines.erase(Runner);
1401 break;
1402 }
1403 } else { // there's just a single line left
1404 if (line->endpoints[i]->lines.erase(line->Nr))
1405 cout << Verbose(5) << "Removing Line Nr. " << line->Nr << " in boundary point " << *line->endpoints[i] << "." << endl;
1406 }
1407 if (line->endpoints[i]->lines.empty()) {
1408 cout << Verbose(5) << *line->endpoints[i] << " has no more lines it's attached to, erasing." << endl;
1409 RemoveTesselationPoint(line->endpoints[i]);
1410 } else {
1411 cout << Verbose(5) << *line->endpoints[i] << " has still lines it's attached to: ";
1412 for(LineMap::iterator LineRunner = line->endpoints[i]->lines.begin(); LineRunner != line->endpoints[i]->lines.end(); LineRunner++)
1413 cout << "[" << *(LineRunner->second) << "] \t";
1414 cout << endl;
1415 }
1416 line->endpoints[i] = NULL; // free'd or not: disconnect
1417 } else
1418 cerr << "ERROR: Endpoint " << i << " has already been free'd." << endl;
1419 }
1420 if (!line->triangles.empty())
1421 cerr << "WARNING: Memory Leak! I " << *line << " am still connected to some triangles." << endl;
1422
1423 if (LinesOnBoundary.erase(line->Nr))
1424 cout << Verbose(5) << "Removing line Nr. " << line->Nr << "." << endl;
1425 delete(line);
1426};
1427
1428/** Removes a point from the tesselation.
1429 * Checks whether there are still lines connected, removes from global PointsOnBoundary list, then free's the point.
1430 * \note If a point should be removed, while keep the tesselated surface intact (i.e. closed), use RemovePointFromTesselatedSurface()
1431 * \param *point point to remove
1432 */
1433void Tesselation::RemoveTesselationPoint(class BoundaryPointSet *point)
1434{
1435 if (point == NULL)
1436 return;
1437 if (PointsOnBoundary.erase(point->Nr))
1438 cout << Verbose(5) << "Removing point Nr. " << point->Nr << "." << endl;
1439 delete(point);
1440};
1441
1442/** Checks whether the triangle consisting of the three points is already present.
1443 * Searches for the points in Tesselation::PointsOnBoundary and checks their
1444 * lines. If any of the three edges already has two triangles attached, false is
1445 * returned.
1446 * \param *out output stream for debugging
1447 * \param *Candidates endpoints of the triangle candidate
1448 * \return integer 0 if no triangle exists, 1 if one triangle exists, 2 if two
1449 * triangles exist which is the maximum for three points
1450 */
1451int Tesselation::CheckPresenceOfTriangle(ofstream *out, TesselPoint *Candidates[3]) {
1452 int adjacentTriangleCount = 0;
1453 class BoundaryPointSet *Points[3];
1454
1455 *out << Verbose(2) << "Begin of CheckPresenceOfTriangle" << endl;
1456 // builds a triangle point set (Points) of the end points
1457 for (int i = 0; i < 3; i++) {
1458 PointMap::iterator FindPoint = PointsOnBoundary.find(Candidates[i]->nr);
1459 if (FindPoint != PointsOnBoundary.end()) {
1460 Points[i] = FindPoint->second;
1461 } else {
1462 Points[i] = NULL;
1463 }
1464 }
1465
1466 // checks lines between the points in the Points for their adjacent triangles
1467 for (int i = 0; i < 3; i++) {
1468 if (Points[i] != NULL) {
1469 for (int j = i; j < 3; j++) {
1470 if (Points[j] != NULL) {
1471 LineMap::iterator FindLine = Points[i]->lines.find(Points[j]->node->nr);
1472 for (; (FindLine != Points[i]->lines.end()) && (FindLine->first == Points[j]->node->nr); FindLine++) {
1473 TriangleMap *triangles = &FindLine->second->triangles;
1474 *out << Verbose(3) << "Current line is " << FindLine->first << ": " << *(FindLine->second) << " with triangles " << triangles << "." << endl;
1475 for (TriangleMap::iterator FindTriangle = triangles->begin(); FindTriangle != triangles->end(); FindTriangle++) {
1476 if (FindTriangle->second->IsPresentTupel(Points)) {
1477 adjacentTriangleCount++;
1478 }
1479 }
1480 *out << Verbose(3) << "end." << endl;
1481 }
1482 // Only one of the triangle lines must be considered for the triangle count.
1483 //*out << Verbose(2) << "Found " << adjacentTriangleCount << " adjacent triangles for the point set." << endl;
1484 //return adjacentTriangleCount;
1485 }
1486 }
1487 }
1488 }
1489
1490 *out << Verbose(2) << "Found " << adjacentTriangleCount << " adjacent triangles for the point set." << endl;
1491 *out << Verbose(2) << "End of CheckPresenceOfTriangle" << endl;
1492 return adjacentTriangleCount;
1493};
1494
1495/** Checks whether the triangle consisting of the three points is already present.
1496 * Searches for the points in Tesselation::PointsOnBoundary and checks their
1497 * lines. If any of the three edges already has two triangles attached, false is
1498 * returned.
1499 * \param *out output stream for debugging
1500 * \param *Candidates endpoints of the triangle candidate
1501 * \return NULL - none found or pointer to triangle
1502 */
1503class BoundaryTriangleSet * Tesselation::GetPresentTriangle(ofstream *out, TesselPoint *Candidates[3])
1504{
1505 class BoundaryTriangleSet *triangle = NULL;
1506 class BoundaryPointSet *Points[3];
1507
1508 // builds a triangle point set (Points) of the end points
1509 for (int i = 0; i < 3; i++) {
1510 PointMap::iterator FindPoint = PointsOnBoundary.find(Candidates[i]->nr);
1511 if (FindPoint != PointsOnBoundary.end()) {
1512 Points[i] = FindPoint->second;
1513 } else {
1514 Points[i] = NULL;
1515 }
1516 }
1517
1518 // checks lines between the points in the Points for their adjacent triangles
1519 for (int i = 0; i < 3; i++) {
1520 if (Points[i] != NULL) {
1521 for (int j = i; j < 3; j++) {
1522 if (Points[j] != NULL) {
1523 LineMap::iterator FindLine = Points[i]->lines.find(Points[j]->node->nr);
1524 for (; (FindLine != Points[i]->lines.end()) && (FindLine->first == Points[j]->node->nr); FindLine++) {
1525 TriangleMap *triangles = &FindLine->second->triangles;
1526 for (TriangleMap::iterator FindTriangle = triangles->begin(); FindTriangle != triangles->end(); FindTriangle++) {
1527 if (FindTriangle->second->IsPresentTupel(Points)) {
1528 if ((triangle == NULL) || (triangle->Nr > FindTriangle->second->Nr))
1529 triangle = FindTriangle->second;
1530 }
1531 }
1532 }
1533 // Only one of the triangle lines must be considered for the triangle count.
1534 //*out << Verbose(2) << "Found " << adjacentTriangleCount << " adjacent triangles for the point set." << endl;
1535 //return adjacentTriangleCount;
1536 }
1537 }
1538 }
1539 }
1540
1541 return triangle;
1542};
1543
1544
1545/** Finds the starting triangle for FindNonConvexBorder().
1546 * Looks at the outermost point per axis, then FindSecondPointForTesselation()
1547 * for the second and FindNextSuitablePointViaAngleOfSphere() for the third
1548 * point are called.
1549 * \param *out output stream for debugging
1550 * \param RADIUS radius of virtual rolling sphere
1551 * \param *LC LinkedCell structure with neighbouring TesselPoint's
1552 */
1553void Tesselation::FindStartingTriangle(ofstream *out, const double RADIUS, LinkedCell *LC)
1554{
1555 cout << Verbose(1) << "Begin of FindStartingTriangle\n";
1556 int i = 0;
1557 LinkedNodes *List = NULL;
1558 TesselPoint* FirstPoint = NULL;
1559 TesselPoint* SecondPoint = NULL;
1560 TesselPoint* MaxPoint[NDIM];
1561 double maxCoordinate[NDIM];
1562 Vector Oben;
1563 Vector helper;
1564 Vector Chord;
1565 Vector SearchDirection;
1566
1567 Oben.Zero();
1568
1569 for (i = 0; i < 3; i++) {
1570 MaxPoint[i] = NULL;
1571 maxCoordinate[i] = -1;
1572 }
1573
1574 // 1. searching topmost point with respect to each axis
1575 for (int i=0;i<NDIM;i++) { // each axis
1576 LC->n[i] = LC->N[i]-1; // current axis is topmost cell
1577 for (LC->n[(i+1)%NDIM]=0;LC->n[(i+1)%NDIM]<LC->N[(i+1)%NDIM];LC->n[(i+1)%NDIM]++)
1578 for (LC->n[(i+2)%NDIM]=0;LC->n[(i+2)%NDIM]<LC->N[(i+2)%NDIM];LC->n[(i+2)%NDIM]++) {
1579 List = LC->GetCurrentCell();
1580 //cout << Verbose(2) << "Current cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " with No. " << LC->index << "." << endl;
1581 if (List != NULL) {
1582 for (LinkedNodes::iterator Runner = List->begin();Runner != List->end();Runner++) {
1583 if ((*Runner)->node->x[i] > maxCoordinate[i]) {
1584 cout << Verbose(2) << "New maximal for axis " << i << " node is " << *(*Runner) << " at " << *(*Runner)->node << "." << endl;
1585 maxCoordinate[i] = (*Runner)->node->x[i];
1586 MaxPoint[i] = (*Runner);
1587 }
1588 }
1589 } else {
1590 cerr << "ERROR: The current cell " << LC->n[0] << "," << LC->n[1] << "," << LC->n[2] << " is invalid!" << endl;
1591 }
1592 }
1593 }
1594
1595 cout << Verbose(2) << "Found maximum coordinates: ";
1596 for (int i=0;i<NDIM;i++)
1597 cout << i << ": " << *MaxPoint[i] << "\t";
1598 cout << endl;
1599
1600 BTS = NULL;
1601 CandidateList *OptCandidates = new CandidateList();
1602 for (int k=0;k<NDIM;k++) {
1603 Oben.Zero();
1604 Oben.x[k] = 1.;
1605 FirstPoint = MaxPoint[k];
1606 cout << Verbose(1) << "Coordinates of start node at " << *FirstPoint->node << "." << endl;
1607
1608 double ShortestAngle;
1609 TesselPoint* OptCandidate = NULL;
1610 ShortestAngle = 999999.; // This will contain the angle, which will be always positive (when looking for second point), when looking for third point this will be the quadrant.
1611
1612 FindSecondPointForTesselation(FirstPoint, Oben, OptCandidate, &ShortestAngle, RADIUS, LC); // we give same point as next candidate as its bonds are looked into in find_second_...
1613 SecondPoint = OptCandidate;
1614 if (SecondPoint == NULL) // have we found a second point?
1615 continue;
1616
1617 helper.CopyVector(FirstPoint->node);
1618 helper.SubtractVector(SecondPoint->node);
1619 helper.Normalize();
1620 Oben.ProjectOntoPlane(&helper);
1621 Oben.Normalize();
1622 helper.VectorProduct(&Oben);
1623 ShortestAngle = 2.*M_PI; // This will indicate the quadrant.
1624
1625 Chord.CopyVector(FirstPoint->node); // bring into calling function
1626 Chord.SubtractVector(SecondPoint->node);
1627 double radius = Chord.ScalarProduct(&Chord);
1628 double CircleRadius = sqrt(RADIUS*RADIUS - radius/4.);
1629 helper.CopyVector(&Oben);
1630 helper.Scale(CircleRadius);
1631 // Now, oben and helper are two orthonormalized vectors in the plane defined by Chord (not normalized)
1632
1633 // look in one direction of baseline for initial candidate
1634 SearchDirection.MakeNormalVector(&Chord, &Oben); // whether we look "left" first or "right" first is not important ...
1635
1636 // adding point 1 and point 2 and add the line between them
1637 cout << Verbose(1) << "Coordinates of start node at " << *FirstPoint->node << "." << endl;
1638 AddTesselationPoint(FirstPoint, 0);
1639 cout << Verbose(1) << "Found second point is at " << *SecondPoint->node << ".\n";
1640 AddTesselationPoint(SecondPoint, 1);
1641 AddTesselationLine(TPS[0], TPS[1], 0);
1642
1643 //cout << Verbose(2) << "INFO: OldSphereCenter is at " << helper << ".\n";
1644 FindThirdPointForTesselation(
1645 Oben, SearchDirection, helper, BLS[0], NULL, *&OptCandidates, &ShortestAngle, RADIUS, LC
1646 );
1647 cout << Verbose(1) << "List of third Points is ";
1648 for (CandidateList::iterator it = OptCandidates->begin(); it != OptCandidates->end(); ++it) {
1649 cout << " " << *(*it)->point;
1650 }
1651 cout << endl;
1652
1653 for (CandidateList::iterator it = OptCandidates->begin(); it != OptCandidates->end(); ++it) {
1654 // add third triangle point
1655 AddTesselationPoint((*it)->point, 2);
1656 // add the second and third line
1657 AddTesselationLine(TPS[1], TPS[2], 1);
1658 AddTesselationLine(TPS[0], TPS[2], 2);
1659 // ... and triangles to the Maps of the Tesselation class
1660 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
1661 AddTesselationTriangle();
1662 // ... and calculate its normal vector (with correct orientation)
1663 (*it)->OptCenter.Scale(-1.);
1664 cout << Verbose(2) << "Anti-Oben is currently " << (*it)->OptCenter << "." << endl;
1665 BTS->GetNormalVector((*it)->OptCenter); // vector to compare with should point inwards
1666 cout << Verbose(0) << "==> Found starting triangle consists of " << *FirstPoint << ", " << *SecondPoint << " and "
1667 << *(*it)->point << " with normal vector " << BTS->NormalVector << ".\n";
1668
1669 // if we do not reach the end with the next step of iteration, we need to setup a new first line
1670 if (it != OptCandidates->end()--) {
1671 FirstPoint = (*it)->BaseLine->endpoints[0]->node;
1672 SecondPoint = (*it)->point;
1673 // adding point 1 and point 2 and the line between them
1674 AddTesselationPoint(FirstPoint, 0);
1675 AddTesselationPoint(SecondPoint, 1);
1676 AddTesselationLine(TPS[0], TPS[1], 0);
1677 }
1678 cout << Verbose(2) << "Projection is " << BTS->NormalVector.ScalarProduct(&Oben) << "." << endl;
1679 }
1680 if (BTS != NULL) // we have created one starting triangle
1681 break;
1682 else {
1683 // remove all candidates from the list and then the list itself
1684 class CandidateForTesselation *remover = NULL;
1685 for (CandidateList::iterator it = OptCandidates->begin(); it != OptCandidates->end(); ++it) {
1686 remover = *it;
1687 delete(remover);
1688 }
1689 OptCandidates->clear();
1690 }
1691 }
1692
1693 // remove all candidates from the list and then the list itself
1694 class CandidateForTesselation *remover = NULL;
1695 for (CandidateList::iterator it = OptCandidates->begin(); it != OptCandidates->end(); ++it) {
1696 remover = *it;
1697 delete(remover);
1698 }
1699 delete(OptCandidates);
1700 cout << Verbose(1) << "End of FindStartingTriangle\n";
1701};
1702
1703
1704/** This function finds a triangle to a line, adjacent to an existing one.
1705 * @param out output stream for debugging
1706 * @param Line current baseline to search from
1707 * @param T current triangle which \a Line is edge of
1708 * @param RADIUS radius of the rolling ball
1709 * @param N number of found triangles
1710 * @param *LC LinkedCell structure with neighbouring points
1711 */
1712bool Tesselation::FindNextSuitableTriangle(ofstream *out, BoundaryLineSet &Line, BoundaryTriangleSet &T, const double& RADIUS, LinkedCell *LC)
1713{
1714 cout << Verbose(0) << "Begin of FindNextSuitableTriangle\n";
1715 bool result = true;
1716 CandidateList *OptCandidates = new CandidateList();
1717
1718 Vector CircleCenter;
1719 Vector CirclePlaneNormal;
1720 Vector OldSphereCenter;
1721 Vector SearchDirection;
1722 Vector helper;
1723 TesselPoint *ThirdNode = NULL;
1724 LineMap::iterator testline;
1725 double ShortestAngle = 2.*M_PI; // This will indicate the quadrant.
1726 double radius, CircleRadius;
1727
1728 cout << Verbose(1) << "Current baseline is " << Line << " of triangle " << T << "." << endl;
1729 for (int i=0;i<3;i++)
1730 if ((T.endpoints[i]->node != Line.endpoints[0]->node) && (T.endpoints[i]->node != Line.endpoints[1]->node))
1731 ThirdNode = T.endpoints[i]->node;
1732
1733 // construct center of circle
1734 CircleCenter.CopyVector(Line.endpoints[0]->node->node);
1735 CircleCenter.AddVector(Line.endpoints[1]->node->node);
1736 CircleCenter.Scale(0.5);
1737
1738 // construct normal vector of circle
1739 CirclePlaneNormal.CopyVector(Line.endpoints[0]->node->node);
1740 CirclePlaneNormal.SubtractVector(Line.endpoints[1]->node->node);
1741
1742 // calculate squared radius of circle
1743 radius = CirclePlaneNormal.ScalarProduct(&CirclePlaneNormal);
1744 if (radius/4. < RADIUS*RADIUS) {
1745 CircleRadius = RADIUS*RADIUS - radius/4.;
1746 CirclePlaneNormal.Normalize();
1747 //cout << Verbose(2) << "INFO: CircleCenter is at " << CircleCenter << ", CirclePlaneNormal is " << CirclePlaneNormal << " with circle radius " << sqrt(CircleRadius) << "." << endl;
1748
1749 // construct old center
1750 GetCenterofCircumcircle(&OldSphereCenter, T.endpoints[0]->node->node, T.endpoints[1]->node->node, T.endpoints[2]->node->node);
1751 helper.CopyVector(&T.NormalVector); // normal vector ensures that this is correct center of the two possible ones
1752 radius = Line.endpoints[0]->node->node->DistanceSquared(&OldSphereCenter);
1753 helper.Scale(sqrt(RADIUS*RADIUS - radius));
1754 OldSphereCenter.AddVector(&helper);
1755 OldSphereCenter.SubtractVector(&CircleCenter);
1756 //cout << Verbose(2) << "INFO: OldSphereCenter is at " << OldSphereCenter << "." << endl;
1757
1758 // construct SearchDirection
1759 SearchDirection.MakeNormalVector(&T.NormalVector, &CirclePlaneNormal);
1760 helper.CopyVector(Line.endpoints[0]->node->node);
1761 helper.SubtractVector(ThirdNode->node);
1762 if (helper.ScalarProduct(&SearchDirection) < -HULLEPSILON)// ohoh, SearchDirection points inwards!
1763 SearchDirection.Scale(-1.);
1764 SearchDirection.ProjectOntoPlane(&OldSphereCenter);
1765 SearchDirection.Normalize();
1766 cout << Verbose(2) << "INFO: SearchDirection is " << SearchDirection << "." << endl;
1767 if (fabs(OldSphereCenter.ScalarProduct(&SearchDirection)) > HULLEPSILON) {
1768 // rotated the wrong way!
1769 cerr << "ERROR: SearchDirection and RelativeOldSphereCenter are still not orthogonal!" << endl;
1770 }
1771
1772 // add third point
1773 FindThirdPointForTesselation(
1774 T.NormalVector, SearchDirection, OldSphereCenter, &Line, ThirdNode, OptCandidates,
1775 &ShortestAngle, RADIUS, LC
1776 );
1777
1778 } else {
1779 cout << Verbose(1) << "Circumcircle for base line " << Line << " and base triangle " << T << " is too big!" << endl;
1780 }
1781
1782 if (OptCandidates->begin() == OptCandidates->end()) {
1783 cerr << "WARNING: Could not find a suitable candidate." << endl;
1784 return false;
1785 }
1786 cout << Verbose(1) << "Third Points are ";
1787 for (CandidateList::iterator it = OptCandidates->begin(); it != OptCandidates->end(); ++it) {
1788 cout << " " << *(*it)->point;
1789 }
1790 cout << endl;
1791
1792 BoundaryLineSet *BaseRay = &Line;
1793 for (CandidateList::iterator it = OptCandidates->begin(); it != OptCandidates->end(); ++it) {
1794 cout << Verbose(1) << " Third point candidate is " << *(*it)->point
1795 << " with circumsphere's center at " << (*it)->OptCenter << "." << endl;
1796 cout << Verbose(1) << " Baseline is " << *BaseRay << endl;
1797
1798 // check whether all edges of the new triangle still have space for one more triangle (i.e. TriangleCount <2)
1799 TesselPoint *PointCandidates[3];
1800 PointCandidates[0] = (*it)->point;
1801 PointCandidates[1] = BaseRay->endpoints[0]->node;
1802 PointCandidates[2] = BaseRay->endpoints[1]->node;
1803 int existentTrianglesCount = CheckPresenceOfTriangle(out, PointCandidates);
1804
1805 BTS = NULL;
1806 // If there is no triangle, add it regularly.
1807 if (existentTrianglesCount == 0) {
1808 AddTesselationPoint((*it)->point, 0);
1809 AddTesselationPoint(BaseRay->endpoints[0]->node, 1);
1810 AddTesselationPoint(BaseRay->endpoints[1]->node, 2);
1811
1812 if (CheckLineCriteriaForDegeneratedTriangle(TPS)) {
1813 AddTesselationLine(TPS[0], TPS[1], 0);
1814 AddTesselationLine(TPS[0], TPS[2], 1);
1815 AddTesselationLine(TPS[1], TPS[2], 2);
1816
1817 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
1818 AddTesselationTriangle();
1819 (*it)->OptCenter.Scale(-1.);
1820 BTS->GetNormalVector((*it)->OptCenter);
1821 (*it)->OptCenter.Scale(-1.);
1822
1823 cout << "--> New triangle with " << *BTS << " and normal vector " << BTS->NormalVector
1824 << " for this triangle ... " << endl;
1825 //cout << Verbose(1) << "We have "<< TrianglesOnBoundaryCount << " for line " << *BaseRay << "." << endl;
1826 } else {
1827 cout << Verbose(1) << "WARNING: This triangle consisting of ";
1828 cout << *(*it)->point << ", ";
1829 cout << *BaseRay->endpoints[0]->node << " and ";
1830 cout << *BaseRay->endpoints[1]->node << " ";
1831 cout << "exists and is not added, as it does not seem helpful!" << endl;
1832 result = false;
1833 }
1834 } else if ((existentTrianglesCount >= 1) && (existentTrianglesCount <= 3)) { // If there is a planar region within the structure, we need this triangle a second time.
1835 AddTesselationPoint((*it)->point, 0);
1836 AddTesselationPoint(BaseRay->endpoints[0]->node, 1);
1837 AddTesselationPoint(BaseRay->endpoints[1]->node, 2);
1838
1839 // We demand that at most one new degenerate line is created and that this line also already exists (which has to be the case due to existentTrianglesCount == 1)
1840 // i.e. at least one of the three lines must be present with TriangleCount <= 1
1841 if (CheckLineCriteriaForDegeneratedTriangle(TPS)) {
1842 AddTesselationLine(TPS[0], TPS[1], 0);
1843 AddTesselationLine(TPS[0], TPS[2], 1);
1844 AddTesselationLine(TPS[1], TPS[2], 2);
1845
1846 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
1847 AddTesselationTriangle(); // add to global map
1848
1849 (*it)->OtherOptCenter.Scale(-1.);
1850 BTS->GetNormalVector((*it)->OtherOptCenter);
1851 (*it)->OtherOptCenter.Scale(-1.);
1852
1853 cout << "--> WARNING: Special new triangle with " << *BTS << " and normal vector " << BTS->NormalVector
1854 << " for this triangle ... " << endl;
1855 cout << Verbose(1) << "We have "<< BaseRay->triangles.size() << " for line " << BaseRay << "." << endl;
1856 } else {
1857 cout << Verbose(1) << "WARNING: This triangle consisting of ";
1858 cout << *(*it)->point << ", ";
1859 cout << *BaseRay->endpoints[0]->node << " and ";
1860 cout << *BaseRay->endpoints[1]->node << " ";
1861 cout << "exists and is not added, as it does not seem helpful!" << endl;
1862 result = false;
1863 }
1864 } else {
1865 cout << Verbose(1) << "This triangle consisting of ";
1866 cout << *(*it)->point << ", ";
1867 cout << *BaseRay->endpoints[0]->node << " and ";
1868 cout << *BaseRay->endpoints[1]->node << " ";
1869 cout << "is invalid!" << endl;
1870 result = false;
1871 }
1872
1873 // set baseline to new ray from ref point (here endpoints[0]->node) to current candidate (here (*it)->point))
1874 BaseRay = BLS[0];
1875 if ((BTS != NULL) && (BTS->NormalVector.NormSquared() < MYEPSILON)) {
1876 *out << Verbose(1) << "CRITICAL: Triangle " << *BTS << " has zero normal vector!" << endl;
1877 exit(255);
1878 }
1879
1880 }
1881
1882 // remove all candidates from the list and then the list itself
1883 class CandidateForTesselation *remover = NULL;
1884 for (CandidateList::iterator it = OptCandidates->begin(); it != OptCandidates->end(); ++it) {
1885 remover = *it;
1886 delete(remover);
1887 }
1888 delete(OptCandidates);
1889 cout << Verbose(0) << "End of FindNextSuitableTriangle\n";
1890 return result;
1891};
1892
1893/** Checks whether the quadragon of the two triangles connect to \a *Base is convex.
1894 * We look whether the closest point on \a *Base with respect to the other baseline is outside
1895 * of the segment formed by both endpoints (concave) or not (convex).
1896 * \param *out output stream for debugging
1897 * \param *Base line to be flipped
1898 * \return NULL - convex, otherwise endpoint that makes it concave
1899 */
1900class BoundaryPointSet *Tesselation::IsConvexRectangle(ofstream *out, class BoundaryLineSet *Base)
1901{
1902 class BoundaryPointSet *Spot = NULL;
1903 class BoundaryLineSet *OtherBase;
1904 Vector *ClosestPoint;
1905
1906 int m=0;
1907 for(TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++)
1908 for (int j=0;j<3;j++) // all of their endpoints and baselines
1909 if (!Base->ContainsBoundaryPoint(runner->second->endpoints[j])) // and neither of its endpoints
1910 BPS[m++] = runner->second->endpoints[j];
1911 OtherBase = new class BoundaryLineSet(BPS,-1);
1912
1913 *out << Verbose(3) << "INFO: Current base line is " << *Base << "." << endl;
1914 *out << Verbose(3) << "INFO: Other base line is " << *OtherBase << "." << endl;
1915
1916 // get the closest point on each line to the other line
1917 ClosestPoint = GetClosestPointBetweenLine(out, Base, OtherBase);
1918
1919 // delete the temporary other base line
1920 delete(OtherBase);
1921
1922 // get the distance vector from Base line to OtherBase line
1923 Vector DistanceToIntersection[2], BaseLine;
1924 double distance[2];
1925 BaseLine.CopyVector(Base->endpoints[1]->node->node);
1926 BaseLine.SubtractVector(Base->endpoints[0]->node->node);
1927 for (int i=0;i<2;i++) {
1928 DistanceToIntersection[i].CopyVector(ClosestPoint);
1929 DistanceToIntersection[i].SubtractVector(Base->endpoints[i]->node->node);
1930 distance[i] = BaseLine.ScalarProduct(&DistanceToIntersection[i]);
1931 }
1932 delete(ClosestPoint);
1933 if ((distance[0] * distance[1]) > 0) { // have same sign?
1934 *out << Verbose(3) << "REJECT: Both SKPs have same sign: " << distance[0] << " and " << distance[1] << ". " << *Base << "' rectangle is concave." << endl;
1935 if (distance[0] < distance[1]) {
1936 Spot = Base->endpoints[0];
1937 } else {
1938 Spot = Base->endpoints[1];
1939 }
1940 return Spot;
1941 } else { // different sign, i.e. we are in between
1942 *out << Verbose(3) << "ACCEPT: Rectangle of triangles of base line " << *Base << " is convex." << endl;
1943 return NULL;
1944 }
1945
1946};
1947
1948void Tesselation::PrintAllBoundaryPoints(ofstream *out)
1949{
1950 // print all lines
1951 *out << Verbose(1) << "Printing all boundary points for debugging:" << endl;
1952 for (PointMap::iterator PointRunner = PointsOnBoundary.begin();PointRunner != PointsOnBoundary.end(); PointRunner++)
1953 *out << Verbose(2) << *(PointRunner->second) << endl;
1954};
1955
1956void Tesselation::PrintAllBoundaryLines(ofstream *out)
1957{
1958 // print all lines
1959 *out << Verbose(1) << "Printing all boundary lines for debugging:" << endl;
1960 for (LineMap::iterator LineRunner = LinesOnBoundary.begin(); LineRunner != LinesOnBoundary.end(); LineRunner++)
1961 *out << Verbose(2) << *(LineRunner->second) << endl;
1962};
1963
1964void Tesselation::PrintAllBoundaryTriangles(ofstream *out)
1965{
1966 // print all triangles
1967 *out << Verbose(1) << "Printing all boundary triangles for debugging:" << endl;
1968 for (TriangleMap::iterator TriangleRunner = TrianglesOnBoundary.begin(); TriangleRunner != TrianglesOnBoundary.end(); TriangleRunner++)
1969 *out << Verbose(2) << *(TriangleRunner->second) << endl;
1970};
1971
1972/** For a given boundary line \a *Base and its two triangles, picks the central baseline that is "higher".
1973 * \param *out output stream for debugging
1974 * \param *Base line to be flipped
1975 * \return volume change due to flipping (0 - then no flipped occured)
1976 */
1977double Tesselation::PickFarthestofTwoBaselines(ofstream *out, class BoundaryLineSet *Base)
1978{
1979 class BoundaryLineSet *OtherBase;
1980 Vector *ClosestPoint[2];
1981 double volume;
1982
1983 int m=0;
1984 for(TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++)
1985 for (int j=0;j<3;j++) // all of their endpoints and baselines
1986 if (!Base->ContainsBoundaryPoint(runner->second->endpoints[j])) // and neither of its endpoints
1987 BPS[m++] = runner->second->endpoints[j];
1988 OtherBase = new class BoundaryLineSet(BPS,-1);
1989
1990 *out << Verbose(3) << "INFO: Current base line is " << *Base << "." << endl;
1991 *out << Verbose(3) << "INFO: Other base line is " << *OtherBase << "." << endl;
1992
1993 // get the closest point on each line to the other line
1994 ClosestPoint[0] = GetClosestPointBetweenLine(out, Base, OtherBase);
1995 ClosestPoint[1] = GetClosestPointBetweenLine(out, OtherBase, Base);
1996
1997 // get the distance vector from Base line to OtherBase line
1998 Vector Distance;
1999 Distance.CopyVector(ClosestPoint[1]);
2000 Distance.SubtractVector(ClosestPoint[0]);
2001
2002 // calculate volume
2003 volume = CalculateVolumeofGeneralTetraeder(Base->endpoints[1]->node->node, OtherBase->endpoints[0]->node->node, OtherBase->endpoints[1]->node->node, Base->endpoints[0]->node->node);
2004
2005 // delete the temporary other base line and the closest points
2006 delete(ClosestPoint[0]);
2007 delete(ClosestPoint[1]);
2008 delete(OtherBase);
2009
2010 if (Distance.NormSquared() < MYEPSILON) { // check for intersection
2011 *out << Verbose(3) << "REJECT: Both lines have an intersection: Nothing to do." << endl;
2012 return false;
2013 } else { // check for sign against BaseLineNormal
2014 Vector BaseLineNormal;
2015 BaseLineNormal.Zero();
2016 if (Base->triangles.size() < 2) {
2017 *out << Verbose(2) << "ERROR: Less than two triangles are attached to this baseline!" << endl;
2018 return 0.;
2019 }
2020 for (TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++) {
2021 *out << Verbose(4) << "INFO: Adding NormalVector " << runner->second->NormalVector << " of triangle " << *(runner->second) << "." << endl;
2022 BaseLineNormal.AddVector(&(runner->second->NormalVector));
2023 }
2024 BaseLineNormal.Scale(1./2.);
2025
2026 if (Distance.ScalarProduct(&BaseLineNormal) > MYEPSILON) { // Distance points outwards, hence OtherBase higher than Base -> flip
2027 *out << Verbose(2) << "ACCEPT: Other base line would be higher: Flipping baseline." << endl;
2028 // calculate volume summand as a general tetraeder
2029 return volume;
2030 } else { // Base higher than OtherBase -> do nothing
2031 *out << Verbose(2) << "REJECT: Base line is higher: Nothing to do." << endl;
2032 return 0.;
2033 }
2034 }
2035};
2036
2037/** For a given baseline and its two connected triangles, flips the baseline.
2038 * I.e. we create the new baseline between the other two endpoints of these four
2039 * endpoints and reconstruct the two triangles accordingly.
2040 * \param *out output stream for debugging
2041 * \param *Base line to be flipped
2042 * \return pointer to allocated new baseline - flipping successful, NULL - something went awry
2043 */
2044class BoundaryLineSet * Tesselation::FlipBaseline(ofstream *out, class BoundaryLineSet *Base)
2045{
2046 class BoundaryLineSet *OldLines[4], *NewLine;
2047 class BoundaryPointSet *OldPoints[2];
2048 Vector BaseLineNormal;
2049 int OldTriangleNrs[2], OldBaseLineNr;
2050 int i,m;
2051
2052 *out << Verbose(1) << "Begin of FlipBaseline" << endl;
2053
2054 // calculate NormalVector for later use
2055 BaseLineNormal.Zero();
2056 if (Base->triangles.size() < 2) {
2057 *out << Verbose(2) << "ERROR: Less than two triangles are attached to this baseline!" << endl;
2058 return NULL;
2059 }
2060 for (TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++) {
2061 *out << Verbose(4) << "INFO: Adding NormalVector " << runner->second->NormalVector << " of triangle " << *(runner->second) << "." << endl;
2062 BaseLineNormal.AddVector(&(runner->second->NormalVector));
2063 }
2064 BaseLineNormal.Scale(-1./2.); // has to point inside for BoundaryTriangleSet::GetNormalVector()
2065
2066 // get the two triangles
2067 // gather four endpoints and four lines
2068 for (int j=0;j<4;j++)
2069 OldLines[j] = NULL;
2070 for (int j=0;j<2;j++)
2071 OldPoints[j] = NULL;
2072 i=0;
2073 m=0;
2074 *out << Verbose(3) << "The four old lines are: ";
2075 for(TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++)
2076 for (int j=0;j<3;j++) // all of their endpoints and baselines
2077 if (runner->second->lines[j] != Base) { // pick not the central baseline
2078 OldLines[i++] = runner->second->lines[j];
2079 *out << *runner->second->lines[j] << "\t";
2080 }
2081 *out << endl;
2082 *out << Verbose(3) << "The two old points are: ";
2083 for(TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++)
2084 for (int j=0;j<3;j++) // all of their endpoints and baselines
2085 if (!Base->ContainsBoundaryPoint(runner->second->endpoints[j])) { // and neither of its endpoints
2086 OldPoints[m++] = runner->second->endpoints[j];
2087 *out << *runner->second->endpoints[j] << "\t";
2088 }
2089 *out << endl;
2090
2091 // check whether everything is in place to create new lines and triangles
2092 if (i<4) {
2093 *out << Verbose(1) << "ERROR: We have not gathered enough baselines!" << endl;
2094 return NULL;
2095 }
2096 for (int j=0;j<4;j++)
2097 if (OldLines[j] == NULL) {
2098 *out << Verbose(1) << "ERROR: We have not gathered enough baselines!" << endl;
2099 return NULL;
2100 }
2101 for (int j=0;j<2;j++)
2102 if (OldPoints[j] == NULL) {
2103 *out << Verbose(1) << "ERROR: We have not gathered enough endpoints!" << endl;
2104 return NULL;
2105 }
2106
2107 // remove triangles and baseline removes itself
2108 *out << Verbose(3) << "INFO: Deleting baseline " << *Base << " from global list." << endl;
2109 OldBaseLineNr = Base->Nr;
2110 m=0;
2111 for(TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++) {
2112 *out << Verbose(3) << "INFO: Deleting triangle " << *(runner->second) << "." << endl;
2113 OldTriangleNrs[m++] = runner->second->Nr;
2114 RemoveTesselationTriangle(runner->second);
2115 }
2116
2117 // construct new baseline (with same number as old one)
2118 BPS[0] = OldPoints[0];
2119 BPS[1] = OldPoints[1];
2120 NewLine = new class BoundaryLineSet(BPS, OldBaseLineNr);
2121 LinesOnBoundary.insert(LinePair(OldBaseLineNr, NewLine)); // no need for check for unique insertion as NewLine is definitely a new one
2122 *out << Verbose(3) << "INFO: Created new baseline " << *NewLine << "." << endl;
2123
2124 // construct new triangles with flipped baseline
2125 i=-1;
2126 if (OldLines[0]->IsConnectedTo(OldLines[2]))
2127 i=2;
2128 if (OldLines[0]->IsConnectedTo(OldLines[3]))
2129 i=3;
2130 if (i!=-1) {
2131 BLS[0] = OldLines[0];
2132 BLS[1] = OldLines[i];
2133 BLS[2] = NewLine;
2134 BTS = new class BoundaryTriangleSet(BLS, OldTriangleNrs[0]);
2135 BTS->GetNormalVector(BaseLineNormal);
2136 AddTesselationTriangle(OldTriangleNrs[0]);
2137 *out << Verbose(3) << "INFO: Created new triangle " << *BTS << "." << endl;
2138
2139 BLS[0] = (i==2 ? OldLines[3] : OldLines[2]);
2140 BLS[1] = OldLines[1];
2141 BLS[2] = NewLine;
2142 BTS = new class BoundaryTriangleSet(BLS, OldTriangleNrs[1]);
2143 BTS->GetNormalVector(BaseLineNormal);
2144 AddTesselationTriangle(OldTriangleNrs[1]);
2145 *out << Verbose(3) << "INFO: Created new triangle " << *BTS << "." << endl;
2146 } else {
2147 *out << Verbose(1) << "The four old lines do not connect, something's utterly wrong here!" << endl;
2148 return NULL;
2149 }
2150
2151 *out << Verbose(1) << "End of FlipBaseline" << endl;
2152 return NewLine;
2153};
2154
2155
2156/** Finds the second point of starting triangle.
2157 * \param *a first node
2158 * \param Oben vector indicating the outside
2159 * \param OptCandidate reference to recommended candidate on return
2160 * \param Storage[3] array storing angles and other candidate information
2161 * \param RADIUS radius of virtual sphere
2162 * \param *LC LinkedCell structure with neighbouring points
2163 */
2164void Tesselation::FindSecondPointForTesselation(TesselPoint* a, Vector Oben, TesselPoint*& OptCandidate, double Storage[3], double RADIUS, LinkedCell *LC)
2165{
2166 cout << Verbose(2) << "Begin of FindSecondPointForTesselation" << endl;
2167 Vector AngleCheck;
2168 class TesselPoint* Candidate = NULL;
2169 double norm = -1., angle;
2170 LinkedNodes *List = NULL;
2171 int N[NDIM], Nlower[NDIM], Nupper[NDIM];
2172
2173 if (LC->SetIndexToNode(a)) { // get cell for the starting point
2174 for(int i=0;i<NDIM;i++) // store indices of this cell
2175 N[i] = LC->n[i];
2176 } else {
2177 cerr << "ERROR: Point " << *a << " is not found in cell " << LC->index << "." << endl;
2178 return;
2179 }
2180 // then go through the current and all neighbouring cells and check the contained points for possible candidates
2181 cout << Verbose(3) << "LC Intervals from [";
2182 for (int i=0;i<NDIM;i++) {
2183 cout << " " << N[i] << "<->" << LC->N[i];
2184 }
2185 cout << "] :";
2186 for (int i=0;i<NDIM;i++) {
2187 Nlower[i] = ((N[i]-1) >= 0) ? N[i]-1 : 0;
2188 Nupper[i] = ((N[i]+1) < LC->N[i]) ? N[i]+1 : LC->N[i]-1;
2189 cout << " [" << Nlower[i] << "," << Nupper[i] << "] ";
2190 }
2191 cout << endl;
2192
2193
2194 for (LC->n[0] = Nlower[0]; LC->n[0] <= Nupper[0]; LC->n[0]++)
2195 for (LC->n[1] = Nlower[1]; LC->n[1] <= Nupper[1]; LC->n[1]++)
2196 for (LC->n[2] = Nlower[2]; LC->n[2] <= Nupper[2]; LC->n[2]++) {
2197 List = LC->GetCurrentCell();
2198 //cout << Verbose(2) << "Current cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " with No. " << LC->index << "." << endl;
2199 if (List != NULL) {
2200 for (LinkedNodes::iterator Runner = List->begin(); Runner != List->end(); Runner++) {
2201 Candidate = (*Runner);
2202 // check if we only have one unique point yet ...
2203 if (a != Candidate) {
2204 // Calculate center of the circle with radius RADIUS through points a and Candidate
2205 Vector OrthogonalizedOben, aCandidate, Center;
2206 double distance, scaleFactor;
2207
2208 OrthogonalizedOben.CopyVector(&Oben);
2209 aCandidate.CopyVector(a->node);
2210 aCandidate.SubtractVector(Candidate->node);
2211 OrthogonalizedOben.ProjectOntoPlane(&aCandidate);
2212 OrthogonalizedOben.Normalize();
2213 distance = 0.5 * aCandidate.Norm();
2214 scaleFactor = sqrt(((RADIUS * RADIUS) - (distance * distance)));
2215 OrthogonalizedOben.Scale(scaleFactor);
2216
2217 Center.CopyVector(Candidate->node);
2218 Center.AddVector(a->node);
2219 Center.Scale(0.5);
2220 Center.AddVector(&OrthogonalizedOben);
2221
2222 AngleCheck.CopyVector(&Center);
2223 AngleCheck.SubtractVector(a->node);
2224 norm = aCandidate.Norm();
2225 // second point shall have smallest angle with respect to Oben vector
2226 if (norm < RADIUS*2.) {
2227 angle = AngleCheck.Angle(&Oben);
2228 if (angle < Storage[0]) {
2229 //cout << Verbose(3) << "Old values of Storage: %lf %lf \n", Storage[0], Storage[1]);
2230 cout << Verbose(3) << "Current candidate is " << *Candidate << ": Is a better candidate with distance " << norm << " and angle " << angle << " to oben " << Oben << ".\n";
2231 OptCandidate = Candidate;
2232 Storage[0] = angle;
2233 //cout << Verbose(3) << "Changing something in Storage: %lf %lf. \n", Storage[0], Storage[2]);
2234 } else {
2235 //cout << Verbose(3) << "Current candidate is " << *Candidate << ": Looses with angle " << angle << " to a better candidate " << *OptCandidate << endl;
2236 }
2237 } else {
2238 //cout << Verbose(3) << "Current candidate is " << *Candidate << ": Refused due to Radius " << norm << endl;
2239 }
2240 } else {
2241 //cout << Verbose(3) << "Current candidate is " << *Candidate << ": Candidate is equal to first endpoint." << *a << "." << endl;
2242 }
2243 }
2244 } else {
2245 cout << Verbose(3) << "Linked cell list is empty." << endl;
2246 }
2247 }
2248 cout << Verbose(2) << "End of FindSecondPointForTesselation" << endl;
2249};
2250
2251
2252/** This recursive function finds a third point, to form a triangle with two given ones.
2253 * Note that this function is for the starting triangle.
2254 * The idea is as follows: A sphere with fixed radius is (almost) uniquely defined in space by three points
2255 * that sit on its boundary. Hence, when two points are given and we look for the (next) third point, then
2256 * the center of the sphere is still fixed up to a single parameter. The band of possible values
2257 * describes a circle in 3D-space. The old center of the sphere for the current base triangle gives
2258 * us the "null" on this circle, the new center of the candidate point will be some way along this
2259 * circle. The shorter the way the better is the candidate. Note that the direction is clearly given
2260 * by the normal vector of the base triangle that always points outwards by construction.
2261 * Hence, we construct a Center of this circle which sits right in the middle of the current base line.
2262 * We construct the normal vector that defines the plane this circle lies in, it is just in the
2263 * direction of the baseline. And finally, we need the radius of the circle, which is given by the rest
2264 * with respect to the length of the baseline and the sphere's fixed \a RADIUS.
2265 * Note that there is one difficulty: The circumcircle is uniquely defined, but for the circumsphere's center
2266 * there are two possibilities which becomes clear from the construction as seen below. Hence, we must check
2267 * both.
2268 * Note also that the acos() function is not unique on [0, 2.*M_PI). Hence, we need an additional check
2269 * to decide for one of the two possible angles. Therefore we need a SearchDirection and to make this check
2270 * sensible we need OldSphereCenter to be orthogonal to it. Either we construct SearchDirection orthogonal
2271 * right away, or -- what we do here -- we rotate the relative sphere centers such that this orthogonality
2272 * holds. Then, the normalized projection onto the SearchDirection is either +1 or -1 and thus states whether
2273 * the angle is uniquely in either (0,M_PI] or [M_PI, 2.*M_PI).
2274 * @param NormalVector normal direction of the base triangle (here the unit axis vector, \sa FindStartingTriangle())
2275 * @param SearchDirection general direction where to search for the next point, relative to center of BaseLine
2276 * @param OldSphereCenter center of sphere for base triangle, relative to center of BaseLine, giving null angle for the parameter circle
2277 * @param BaseLine BoundaryLineSet with the current base line
2278 * @param ThirdNode third point to avoid in search
2279 * @param candidates list of equally good candidates to return
2280 * @param ShortestAngle the current path length on this circle band for the current OptCandidate
2281 * @param RADIUS radius of sphere
2282 * @param *LC LinkedCell structure with neighbouring points
2283 */
2284void Tesselation::FindThirdPointForTesselation(Vector NormalVector, Vector SearchDirection, Vector OldSphereCenter, class BoundaryLineSet *BaseLine, class TesselPoint *ThirdNode, CandidateList* &candidates, double *ShortestAngle, const double RADIUS, LinkedCell *LC)
2285{
2286 Vector CircleCenter; // center of the circle, i.e. of the band of sphere's centers
2287 Vector CirclePlaneNormal; // normal vector defining the plane this circle lives in
2288 Vector SphereCenter;
2289 Vector NewSphereCenter; // center of the sphere defined by the two points of BaseLine and the one of Candidate, first possibility
2290 Vector OtherNewSphereCenter; // center of the sphere defined by the two points of BaseLine and the one of Candidate, second possibility
2291 Vector NewNormalVector; // normal vector of the Candidate's triangle
2292 Vector helper, OptCandidateCenter, OtherOptCandidateCenter;
2293 LinkedNodes *List = NULL;
2294 double CircleRadius; // radius of this circle
2295 double radius;
2296 double alpha, Otheralpha; // angles (i.e. parameter for the circle).
2297 int N[NDIM], Nlower[NDIM], Nupper[NDIM];
2298 TesselPoint *Candidate = NULL;
2299 CandidateForTesselation *optCandidate = NULL;
2300
2301 cout << Verbose(1) << "Begin of FindThirdPointForTesselation" << endl;
2302
2303 cout << Verbose(2) << "INFO: NormalVector of BaseTriangle is " << NormalVector << "." << endl;
2304
2305 // construct center of circle
2306 CircleCenter.CopyVector(BaseLine->endpoints[0]->node->node);
2307 CircleCenter.AddVector(BaseLine->endpoints[1]->node->node);
2308 CircleCenter.Scale(0.5);
2309
2310 // construct normal vector of circle
2311 CirclePlaneNormal.CopyVector(BaseLine->endpoints[0]->node->node);
2312 CirclePlaneNormal.SubtractVector(BaseLine->endpoints[1]->node->node);
2313
2314 // calculate squared radius TesselPoint *ThirdNode,f circle
2315 radius = CirclePlaneNormal.ScalarProduct(&CirclePlaneNormal);
2316 if (radius/4. < RADIUS*RADIUS) {
2317 CircleRadius = RADIUS*RADIUS - radius/4.;
2318 CirclePlaneNormal.Normalize();
2319 //cout << Verbose(2) << "INFO: CircleCenter is at " << CircleCenter << ", CirclePlaneNormal is " << CirclePlaneNormal << " with circle radius " << sqrt(CircleRadius) << "." << endl;
2320
2321 // test whether old center is on the band's plane
2322 if (fabs(OldSphereCenter.ScalarProduct(&CirclePlaneNormal)) > HULLEPSILON) {
2323 cerr << "ERROR: Something's very wrong here: OldSphereCenter is not on the band's plane as desired by " << fabs(OldSphereCenter.ScalarProduct(&CirclePlaneNormal)) << "!" << endl;
2324 OldSphereCenter.ProjectOntoPlane(&CirclePlaneNormal);
2325 }
2326 radius = OldSphereCenter.ScalarProduct(&OldSphereCenter);
2327 if (fabs(radius - CircleRadius) < HULLEPSILON) {
2328 //cout << Verbose(2) << "INFO: OldSphereCenter is at " << OldSphereCenter << "." << endl;
2329
2330 // check SearchDirection
2331 //cout << Verbose(2) << "INFO: SearchDirection is " << SearchDirection << "." << endl;
2332 if (fabs(OldSphereCenter.ScalarProduct(&SearchDirection)) > HULLEPSILON) { // rotated the wrong way!
2333 cerr << "ERROR: SearchDirection and RelativeOldSphereCenter are not orthogonal!" << endl;
2334 }
2335
2336 // get cell for the starting point
2337 if (LC->SetIndexToVector(&CircleCenter)) {
2338 for(int i=0;i<NDIM;i++) // store indices of this cell
2339 N[i] = LC->n[i];
2340 //cout << Verbose(2) << "INFO: Center cell is " << N[0] << ", " << N[1] << ", " << N[2] << " with No. " << LC->index << "." << endl;
2341 } else {
2342 cerr << "ERROR: Vector " << CircleCenter << " is outside of LinkedCell's bounding box." << endl;
2343 return;
2344 }
2345 // then go through the current and all neighbouring cells and check the contained points for possible candidates
2346 //cout << Verbose(2) << "LC Intervals:";
2347 for (int i=0;i<NDIM;i++) {
2348 Nlower[i] = ((N[i]-1) >= 0) ? N[i]-1 : 0;
2349 Nupper[i] = ((N[i]+1) < LC->N[i]) ? N[i]+1 : LC->N[i]-1;
2350 //cout << " [" << Nlower[i] << "," << Nupper[i] << "] ";
2351 }
2352 //cout << endl;
2353 for (LC->n[0] = Nlower[0]; LC->n[0] <= Nupper[0]; LC->n[0]++)
2354 for (LC->n[1] = Nlower[1]; LC->n[1] <= Nupper[1]; LC->n[1]++)
2355 for (LC->n[2] = Nlower[2]; LC->n[2] <= Nupper[2]; LC->n[2]++) {
2356 List = LC->GetCurrentCell();
2357 //cout << Verbose(2) << "Current cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " with No. " << LC->index << "." << endl;
2358 if (List != NULL) {
2359 for (LinkedNodes::iterator Runner = List->begin(); Runner != List->end(); Runner++) {
2360 Candidate = (*Runner);
2361
2362 // check for three unique points
2363 //cout << Verbose(2) << "INFO: Current Candidate is " << *Candidate << " at " << Candidate->node << "." << endl;
2364 if ((Candidate != BaseLine->endpoints[0]->node) && (Candidate != BaseLine->endpoints[1]->node) ){
2365
2366 // construct both new centers
2367 GetCenterofCircumcircle(&NewSphereCenter, BaseLine->endpoints[0]->node->node, BaseLine->endpoints[1]->node->node, Candidate->node);
2368 OtherNewSphereCenter.CopyVector(&NewSphereCenter);
2369
2370 if ((NewNormalVector.MakeNormalVector(BaseLine->endpoints[0]->node->node, BaseLine->endpoints[1]->node->node, Candidate->node))
2371 && (fabs(NewNormalVector.ScalarProduct(&NewNormalVector)) > HULLEPSILON)
2372 ) {
2373 helper.CopyVector(&NewNormalVector);
2374 //cout << Verbose(2) << "INFO: NewNormalVector is " << NewNormalVector << "." << endl;
2375 radius = BaseLine->endpoints[0]->node->node->DistanceSquared(&NewSphereCenter);
2376 if (radius < RADIUS*RADIUS) {
2377 helper.Scale(sqrt(RADIUS*RADIUS - radius));
2378 //cout << Verbose(2) << "INFO: Distance of NewCircleCenter to NewSphereCenter is " << helper.Norm() << " with sphere radius " << RADIUS << "." << endl;
2379 NewSphereCenter.AddVector(&helper);
2380 NewSphereCenter.SubtractVector(&CircleCenter);
2381 //cout << Verbose(2) << "INFO: NewSphereCenter is at " << NewSphereCenter << "." << endl;
2382
2383 // OtherNewSphereCenter is created by the same vector just in the other direction
2384 helper.Scale(-1.);
2385 OtherNewSphereCenter.AddVector(&helper);
2386 OtherNewSphereCenter.SubtractVector(&CircleCenter);
2387 //cout << Verbose(2) << "INFO: OtherNewSphereCenter is at " << OtherNewSphereCenter << "." << endl;
2388
2389 alpha = GetPathLengthonCircumCircle(CircleCenter, CirclePlaneNormal, CircleRadius, NewSphereCenter, OldSphereCenter, NormalVector, SearchDirection);
2390 Otheralpha = GetPathLengthonCircumCircle(CircleCenter, CirclePlaneNormal, CircleRadius, OtherNewSphereCenter, OldSphereCenter, NormalVector, SearchDirection);
2391 alpha = min(alpha, Otheralpha);
2392 // if there is a better candidate, drop the current list and add the new candidate
2393 // otherwise ignore the new candidate and keep the list
2394 if (*ShortestAngle > (alpha - HULLEPSILON)) {
2395 optCandidate = new CandidateForTesselation(Candidate, BaseLine, OptCandidateCenter, OtherOptCandidateCenter);
2396 if (fabs(alpha - Otheralpha) > MYEPSILON) {
2397 optCandidate->OptCenter.CopyVector(&NewSphereCenter);
2398 optCandidate->OtherOptCenter.CopyVector(&OtherNewSphereCenter);
2399 } else {
2400 optCandidate->OptCenter.CopyVector(&OtherNewSphereCenter);
2401 optCandidate->OtherOptCenter.CopyVector(&NewSphereCenter);
2402 }
2403 // if there is an equal candidate, add it to the list without clearing the list
2404 if ((*ShortestAngle - HULLEPSILON) < alpha) {
2405 candidates->push_back(optCandidate);
2406 cout << Verbose(2) << "ACCEPT: We have found an equally good candidate: " << *(optCandidate->point) << " with "
2407 << alpha << " and circumsphere's center at " << optCandidate->OptCenter << "." << endl;
2408 } else {
2409 // remove all candidates from the list and then the list itself
2410 class CandidateForTesselation *remover = NULL;
2411 for (CandidateList::iterator it = candidates->begin(); it != candidates->end(); ++it) {
2412 remover = *it;
2413 delete(remover);
2414 }
2415 candidates->clear();
2416 candidates->push_back(optCandidate);
2417 cout << Verbose(2) << "ACCEPT: We have found a better candidate: " << *(optCandidate->point) << " with "
2418 << alpha << " and circumsphere's center at " << optCandidate->OptCenter << "." << endl;
2419 }
2420 *ShortestAngle = alpha;
2421 //cout << Verbose(2) << "INFO: There are " << candidates->size() << " candidates in the list now." << endl;
2422 } else {
2423 if ((optCandidate != NULL) && (optCandidate->point != NULL)) {
2424 //cout << Verbose(2) << "REJECT: Old candidate " << *(optCandidate->point) << " with " << *ShortestAngle << " is better than new one " << *Candidate << " with " << alpha << " ." << endl;
2425 } else {
2426 //cout << Verbose(2) << "REJECT: Candidate " << *Candidate << " with " << alpha << " was rejected." << endl;
2427 }
2428 }
2429
2430 } else {
2431 //cout << Verbose(2) << "REJECT: NewSphereCenter " << NewSphereCenter << " for " << *Candidate << " is too far away: " << radius << "." << endl;
2432 }
2433 } else {
2434 //cout << Verbose(2) << "REJECT: Three points from " << *BaseLine << " and Candidate " << *Candidate << " are linear-dependent." << endl;
2435 }
2436 } else {
2437 if (ThirdNode != NULL) {
2438 //cout << Verbose(2) << "REJECT: Base triangle " << *BaseLine << " and " << *ThirdNode << " contains Candidate " << *Candidate << "." << endl;
2439 } else {
2440 //cout << Verbose(2) << "REJECT: Base triangle " << *BaseLine << " contains Candidate " << *Candidate << "." << endl;
2441 }
2442 }
2443 }
2444 }
2445 }
2446 } else {
2447 cerr << Verbose(2) << "ERROR: The projected center of the old sphere has radius " << radius << " instead of " << CircleRadius << "." << endl;
2448 }
2449 } else {
2450 if (ThirdNode != NULL)
2451 cout << Verbose(2) << "Circumcircle for base line " << *BaseLine << " and third node " << *ThirdNode << " is too big!" << endl;
2452 else
2453 cout << Verbose(2) << "Circumcircle for base line " << *BaseLine << " is too big!" << endl;
2454 }
2455
2456 //cout << Verbose(2) << "INFO: Sorting candidate list ..." << endl;
2457 if (candidates->size() > 1) {
2458 candidates->unique();
2459 candidates->sort(SortCandidates);
2460 }
2461
2462 cout << Verbose(1) << "End of FindThirdPointForTesselation" << endl;
2463};
2464
2465/** Finds the endpoint two lines are sharing.
2466 * \param *line1 first line
2467 * \param *line2 second line
2468 * \return point which is shared or NULL if none
2469 */
2470class BoundaryPointSet *Tesselation::GetCommonEndpoint(class BoundaryLineSet * line1, class BoundaryLineSet * line2)
2471{
2472 class BoundaryLineSet * lines[2] =
2473 { line1, line2 };
2474 class BoundaryPointSet *node = NULL;
2475 map<int, class BoundaryPointSet *> OrderMap;
2476 pair<map<int, class BoundaryPointSet *>::iterator, bool> OrderTest;
2477 for (int i = 0; i < 2; i++)
2478 // for both lines
2479 for (int j = 0; j < 2; j++)
2480 { // for both endpoints
2481 OrderTest = OrderMap.insert(pair<int, class BoundaryPointSet *> (
2482 lines[i]->endpoints[j]->Nr, lines[i]->endpoints[j]));
2483 if (!OrderTest.second)
2484 { // if insertion fails, we have common endpoint
2485 node = OrderTest.first->second;
2486 cout << Verbose(5) << "Common endpoint of lines " << *line1
2487 << " and " << *line2 << " is: " << *node << "." << endl;
2488 j = 2;
2489 i = 2;
2490 break;
2491 }
2492 }
2493 return node;
2494};
2495
2496/** Finds the triangle that is closest to a given Vector \a *x.
2497 * \param *out output stream for debugging
2498 * \param *x Vector to look from
2499 * \return list of BoundaryTriangleSet of nearest triangles or NULL in degenerate case.
2500 */
2501list<BoundaryTriangleSet*> * Tesselation::FindClosestTrianglesToPoint(ofstream *out, Vector *x, LinkedCell* LC)
2502{
2503 TesselPoint *trianglePoints[3];
2504 TesselPoint *SecondPoint = NULL;
2505 list<BoundaryTriangleSet*> *triangles = NULL;
2506
2507 if (LinesOnBoundary.empty()) {
2508 *out << Verbose(0) << "Error: There is no tesselation structure to compare the point with, please create one first.";
2509 return NULL;
2510 }
2511
2512 trianglePoints[0] = FindClosestPoint(x, SecondPoint, LC);
2513
2514 // check whether closest point is "too close" :), then it's inside
2515 if (trianglePoints[0] == NULL) {
2516 *out << Verbose(2) << "Is the only point, no one else is closeby." << endl;
2517 return NULL;
2518 }
2519 if (trianglePoints[0]->node->DistanceSquared(x) < MYEPSILON) {
2520 *out << Verbose(3) << "Point is right on a tesselation point, no nearest triangle." << endl;
2521 PointMap::iterator PointRunner = PointsOnBoundary.find(trianglePoints[0]->nr);
2522 triangles = new list<BoundaryTriangleSet*>;
2523 if (PointRunner != PointsOnBoundary.end()) {
2524 for(LineMap::iterator LineRunner = PointRunner->second->lines.begin(); LineRunner != PointRunner->second->lines.end(); LineRunner++)
2525 for(TriangleMap::iterator TriangleRunner = LineRunner->second->triangles.begin(); TriangleRunner != LineRunner->second->triangles.end(); TriangleRunner++)
2526 triangles->push_back(TriangleRunner->second);
2527 triangles->sort();
2528 triangles->unique();
2529 } else {
2530 PointRunner = PointsOnBoundary.find(SecondPoint->nr);
2531 trianglePoints[0] = SecondPoint;
2532 if (PointRunner != PointsOnBoundary.end()) {
2533 for(LineMap::iterator LineRunner = PointRunner->second->lines.begin(); LineRunner != PointRunner->second->lines.end(); LineRunner++)
2534 for(TriangleMap::iterator TriangleRunner = LineRunner->second->triangles.begin(); TriangleRunner != LineRunner->second->triangles.end(); TriangleRunner++)
2535 triangles->push_back(TriangleRunner->second);
2536 triangles->sort();
2537 triangles->unique();
2538 } else {
2539 *out << Verbose(1) << "ERROR: I cannot find a boundary point to the tessel point " << *trianglePoints[0] << "." << endl;
2540 return NULL;
2541 }
2542 }
2543 } else {
2544 list<TesselPoint*> *connectedClosestPoints = GetCircleOfConnectedPoints(out, trianglePoints[0], x);
2545 trianglePoints[1] = connectedClosestPoints->front();
2546 trianglePoints[2] = connectedClosestPoints->back();
2547 for (int i=0;i<3;i++) {
2548 if (trianglePoints[i] == NULL) {
2549 *out << Verbose(1) << "ERROR: IsInnerPoint encounters serious error, point " << i << " not found." << endl;
2550 }
2551 //*out << Verbose(2) << "List of triangle points:" << endl;
2552 //*out << Verbose(3) << *trianglePoints[i] << endl;
2553 }
2554
2555 triangles = FindTriangles(trianglePoints);
2556 *out << Verbose(2) << "List of possible triangles:" << endl;
2557 for(list<BoundaryTriangleSet*>::iterator Runner = triangles->begin(); Runner != triangles->end(); Runner++)
2558 *out << Verbose(3) << **Runner << endl;
2559
2560 delete(connectedClosestPoints);
2561 }
2562
2563 if (triangles->empty()) {
2564 *out << Verbose(0) << "ERROR: There is no nearest triangle. Please check the tesselation structure.";
2565 delete(triangles);
2566 return NULL;
2567 } else
2568 return triangles;
2569};
2570
2571/** Finds closest triangle to a point.
2572 * This basically just takes care of the degenerate case, which is not handled in FindClosestTrianglesToPoint().
2573 * \param *out output stream for debugging
2574 * \param *x Vector to look from
2575 * \return list of BoundaryTriangleSet of nearest triangles or NULL.
2576 */
2577class BoundaryTriangleSet * Tesselation::FindClosestTriangleToPoint(ofstream *out, Vector *x, LinkedCell* LC)
2578{
2579 class BoundaryTriangleSet *result = NULL;
2580 list<BoundaryTriangleSet*> *triangles = FindClosestTrianglesToPoint(out, x, LC);
2581 Vector Center;
2582
2583 if (triangles == NULL)
2584 return NULL;
2585
2586 if (triangles->size() == 1) { // there is no degenerate case
2587 result = triangles->front();
2588 *out << Verbose(2) << "Normal Vector of this triangle is " << result->NormalVector << "." << endl;
2589 } else {
2590 result = triangles->front();
2591 result->GetCenter(&Center);
2592 Center.SubtractVector(x);
2593 *out << Verbose(2) << "Normal Vector of this front side is " << result->NormalVector << "." << endl;
2594 if (Center.ScalarProduct(&result->NormalVector) < 0) {
2595 result = triangles->back();
2596 *out << Verbose(2) << "Normal Vector of this back side is " << result->NormalVector << "." << endl;
2597 if (Center.ScalarProduct(&result->NormalVector) < 0) {
2598 *out << Verbose(1) << "ERROR: Front and back side yield NormalVector in wrong direction!" << endl;
2599 }
2600 }
2601 }
2602 delete(triangles);
2603 return result;
2604};
2605
2606/** Checks whether the provided Vector is within the tesselation structure.
2607 *
2608 * @param point of which to check the position
2609 * @param *LC LinkedCell structure
2610 *
2611 * @return true if the point is inside the tesselation structure, false otherwise
2612 */
2613bool Tesselation::IsInnerPoint(ofstream *out, Vector Point, LinkedCell* LC)
2614{
2615 class BoundaryTriangleSet *result = FindClosestTriangleToPoint(out, &Point, LC);
2616 Vector Center;
2617
2618 if (result == NULL) {// is boundary point or only point in point cloud?
2619 *out << Verbose(1) << Point << " is the only point in vicinity." << endl;
2620 return false;
2621 }
2622
2623 result->GetCenter(&Center);
2624 *out << Verbose(3) << "INFO: Central point of the triangle is " << Center << "." << endl;
2625 Center.SubtractVector(&Point);
2626 *out << Verbose(3) << "INFO: Vector from center to point to test is " << Center << "." << endl;
2627 if (Center.ScalarProduct(&result->NormalVector) > -MYEPSILON) {
2628 *out << Verbose(1) << Point << " is an inner point." << endl;
2629 return true;
2630 } else {
2631 *out << Verbose(1) << Point << " is NOT an inner point." << endl;
2632 return false;
2633 }
2634}
2635
2636/** Checks whether the provided TesselPoint is within the tesselation structure.
2637 *
2638 * @param *Point of which to check the position
2639 * @param *LC Linked Cell structure
2640 *
2641 * @return true if the point is inside the tesselation structure, false otherwise
2642 */
2643bool Tesselation::IsInnerPoint(ofstream *out, TesselPoint *Point, LinkedCell* LC)
2644{
2645 return IsInnerPoint(out, *(Point->node), LC);
2646}
2647
2648/** Gets all points connected to the provided point by triangulation lines.
2649 *
2650 * @param *Point of which get all connected points
2651 *
2652 * @return set of the all points linked to the provided one
2653 */
2654set<TesselPoint*> * Tesselation::GetAllConnectedPoints(ofstream *out, TesselPoint* Point)
2655{
2656 set<TesselPoint*> *connectedPoints = new set<TesselPoint*>;
2657 class BoundaryPointSet *ReferencePoint = NULL;
2658 TesselPoint* current;
2659 bool takePoint = false;
2660
2661 // find the respective boundary point
2662 PointMap::iterator PointRunner = PointsOnBoundary.find(Point->nr);
2663 if (PointRunner != PointsOnBoundary.end()) {
2664 ReferencePoint = PointRunner->second;
2665 } else {
2666 *out << Verbose(2) << "GetAllConnectedPoints() could not find the BoundaryPoint belonging to " << *Point << "." << endl;
2667 ReferencePoint = NULL;
2668 }
2669
2670 // little trick so that we look just through lines connect to the BoundaryPoint
2671 // OR fall-back to look through all lines if there is no such BoundaryPoint
2672 LineMap *Lines = &LinesOnBoundary;
2673 if (ReferencePoint != NULL)
2674 Lines = &(ReferencePoint->lines);
2675 LineMap::iterator findLines = Lines->begin();
2676 while (findLines != Lines->end()) {
2677 takePoint = false;
2678
2679 if (findLines->second->endpoints[0]->Nr == Point->nr) {
2680 takePoint = true;
2681 current = findLines->second->endpoints[1]->node;
2682 } else if (findLines->second->endpoints[1]->Nr == Point->nr) {
2683 takePoint = true;
2684 current = findLines->second->endpoints[0]->node;
2685 }
2686
2687 if (takePoint) {
2688 *out << Verbose(5) << "INFO: Endpoint " << *current << " of line " << *(findLines->second) << " is enlisted." << endl;
2689 connectedPoints->insert(current);
2690 }
2691
2692 findLines++;
2693 }
2694
2695 if (connectedPoints->size() == 0) { // if have not found any points
2696 *out << Verbose(1) << "ERROR: We have not found any connected points to " << *Point<< "." << endl;
2697 return NULL;
2698 }
2699
2700 return connectedPoints;
2701};
2702
2703
2704/** Gets all points connected to the provided point by triangulation lines, ordered such that we have the circle round the point.
2705 * Maps them down onto the plane designated by the axis \a *Point and \a *Reference. The center of all points
2706 * connected in the tesselation to \a *Point is mapped to spherical coordinates with the zero angle being given
2707 * by the mapped down \a *Reference. Hence, the biggest and the smallest angles are those of the two shanks of the
2708 * triangle we are looking for.
2709 *
2710 * @param *out output stream for debugging
2711 * @param *Point of which get all connected points
2712 * @param *Reference Reference vector for zero angle or NULL for no preference
2713 * @return list of the all points linked to the provided one
2714 */
2715list<TesselPoint*> * Tesselation::GetCircleOfConnectedPoints(ofstream *out, TesselPoint* Point, Vector *Reference)
2716{
2717 map<double, TesselPoint*> anglesOfPoints;
2718 set<TesselPoint*> *connectedPoints = GetAllConnectedPoints(out, Point);
2719 list<TesselPoint*> *connectedCircle = new list<TesselPoint*>;
2720 Vector center;
2721 Vector PlaneNormal;
2722 Vector AngleZero;
2723 Vector OrthogonalVector;
2724 Vector helper;
2725
2726 // calculate central point
2727 for (set<TesselPoint*>::iterator TesselRunner = connectedPoints->begin(); TesselRunner != connectedPoints->end(); TesselRunner++)
2728 center.AddVector((*TesselRunner)->node);
2729 //*out << "Summed vectors " << center << "; number of points " << connectedPoints.size()
2730 // << "; scale factor " << 1.0/connectedPoints.size();
2731 center.Scale(1.0/connectedPoints->size());
2732 *out << Verbose(4) << "INFO: Calculated center of all circle points is " << center << "." << endl;
2733
2734 // projection plane of the circle is at the closes Point and normal is pointing away from center of all circle points
2735 PlaneNormal.CopyVector(Point->node);
2736 PlaneNormal.SubtractVector(&center);
2737 PlaneNormal.Normalize();
2738 *out << Verbose(4) << "INFO: Calculated plane normal of circle is " << PlaneNormal << "." << endl;
2739
2740 // construct one orthogonal vector
2741 if (Reference != NULL)
2742 AngleZero.CopyVector(Reference);
2743 else
2744 AngleZero.CopyVector((*connectedPoints->begin())->node);
2745 AngleZero.SubtractVector(Point->node);
2746 AngleZero.ProjectOntoPlane(&PlaneNormal);
2747 *out << Verbose(4) << "INFO: Reference vector on this plane representing angle 0 is " << AngleZero << "." << endl;
2748 OrthogonalVector.MakeNormalVector(&PlaneNormal, &AngleZero);
2749 *out << Verbose(4) << "INFO: OrthogonalVector on plane is " << OrthogonalVector << "." << endl;
2750
2751 // go through all connected points and calculate angle
2752 for (set<TesselPoint*>::iterator listRunner = connectedPoints->begin(); listRunner != connectedPoints->end(); listRunner++) {
2753 helper.CopyVector((*listRunner)->node);
2754 helper.SubtractVector(Point->node);
2755 helper.ProjectOntoPlane(&PlaneNormal);
2756 double angle = GetAngle(helper, AngleZero, OrthogonalVector);
2757 *out << Verbose(3) << "INFO: Calculated angle is " << angle << " for point " << **listRunner << "." << endl;
2758 anglesOfPoints.insert(pair<double, TesselPoint*>(angle, (*listRunner)));
2759 }
2760
2761 for(map<double, TesselPoint*>::iterator AngleRunner = anglesOfPoints.begin(); AngleRunner != anglesOfPoints.end(); AngleRunner++) {
2762 connectedCircle->push_back(AngleRunner->second);
2763 }
2764
2765 delete(connectedPoints);
2766 return connectedCircle;
2767}
2768
2769/** Gets all points connected to the provided point by triangulation lines, ordered such that we walk along a closed path.
2770 *
2771 * @param *out output stream for debugging
2772 * @param *Point of which get all connected points
2773 * @return list of the all points linked to the provided one
2774 */
2775list<list<TesselPoint*> *> * Tesselation::GetPathsOfConnectedPoints(ofstream *out, TesselPoint* Point)
2776{
2777 map<double, TesselPoint*> anglesOfPoints;
2778 list<list<TesselPoint*> *> *ListOfPaths = new list<list<TesselPoint*> *>;
2779 list<TesselPoint*> *connectedPath = NULL;
2780 Vector center;
2781 Vector PlaneNormal;
2782 Vector AngleZero;
2783 Vector OrthogonalVector;
2784 Vector helper;
2785 class BoundaryPointSet *ReferencePoint = NULL;
2786 class BoundaryPointSet *CurrentPoint = NULL;
2787 class BoundaryTriangleSet *triangle = NULL;
2788 class BoundaryLineSet *CurrentLine = NULL;
2789 class BoundaryLineSet *StartLine = NULL;
2790
2791 // find the respective boundary point
2792 PointMap::iterator PointRunner = PointsOnBoundary.find(Point->nr);
2793 if (PointRunner != PointsOnBoundary.end()) {
2794 ReferencePoint = PointRunner->second;
2795 } else {
2796 *out << Verbose(2) << "ERROR: GetPathOfConnectedPoints() could not find the BoundaryPoint belonging to " << *Point << "." << endl;
2797 return NULL;
2798 }
2799
2800 map <class BoundaryLineSet *, bool> TouchedLine;
2801 map <class BoundaryTriangleSet *, bool> TouchedTriangle;
2802 map <class BoundaryLineSet *, bool>::iterator LineRunner;
2803 map <class BoundaryTriangleSet *, bool>::iterator TriangleRunner;
2804 for (LineMap::iterator Runner = ReferencePoint->lines.begin(); Runner != ReferencePoint->lines.end(); Runner++) {
2805 TouchedLine.insert( pair <class BoundaryLineSet *, bool>(Runner->second, false) );
2806 for (TriangleMap::iterator Sprinter = Runner->second->triangles.begin(); Sprinter != Runner->second->triangles.end(); Sprinter++)
2807 TouchedTriangle.insert( pair <class BoundaryTriangleSet *, bool>(Sprinter->second, false) );
2808 }
2809 if (!ReferencePoint->lines.empty()) {
2810 for (LineMap::iterator runner = ReferencePoint->lines.begin(); runner != ReferencePoint->lines.end(); runner++) {
2811 LineRunner = TouchedLine.find(runner->second);
2812 if (LineRunner == TouchedLine.end()) {
2813 *out << Verbose(2) << "ERROR: I could not find " << *runner->second << " in the touched list." << endl;
2814 } else if (!LineRunner->second) {
2815 LineRunner->second = true;
2816 connectedPath = new list<TesselPoint*>;
2817 triangle = NULL;
2818 CurrentLine = runner->second;
2819 StartLine = CurrentLine;
2820 CurrentPoint = CurrentLine->GetOtherEndpoint(ReferencePoint);
2821 *out << Verbose(3)<< "INFO: Beginning path retrieval at " << *CurrentPoint << " of line " << *CurrentLine << "." << endl;
2822 do {
2823 // push current one
2824 *out << Verbose(3) << "INFO: Putting " << *CurrentPoint << " at end of path." << endl;
2825 connectedPath->push_back(CurrentPoint->node);
2826
2827 // find next triangle
2828 for (TriangleMap::iterator Runner = CurrentLine->triangles.begin(); Runner != CurrentLine->triangles.end(); Runner++) {
2829 *out << Verbose(3) << "INFO: Inspecting triangle " << *Runner->second << "." << endl;
2830 if ((Runner->second != triangle)) { // look for first triangle not equal to old one
2831 triangle = Runner->second;
2832 TriangleRunner = TouchedTriangle.find(triangle);
2833 if (TriangleRunner != TouchedTriangle.end()) {
2834 if (!TriangleRunner->second) {
2835 TriangleRunner->second = true;
2836 *out << Verbose(3) << "INFO: Connecting triangle is " << *triangle << "." << endl;
2837 break;
2838 } else {
2839 *out << Verbose(3) << "INFO: Skipping " << *triangle << ", as we have already visited it." << endl;
2840 triangle = NULL;
2841 }
2842 } else {
2843 *out << Verbose(2) << "ERROR: I could not find " << *triangle << " in the touched list." << endl;
2844 triangle = NULL;
2845 }
2846 }
2847 }
2848 if (triangle == NULL)
2849 break;
2850 // find next line
2851 for (int i=0;i<3;i++) {
2852 if ((triangle->lines[i] != CurrentLine) && (triangle->lines[i]->ContainsBoundaryPoint(ReferencePoint))) { // not the current line and still containing Point
2853 CurrentLine = triangle->lines[i];
2854 *out << Verbose(3) << "INFO: Connecting line is " << *CurrentLine << "." << endl;
2855 break;
2856 }
2857 }
2858 LineRunner = TouchedLine.find(CurrentLine);
2859 if (LineRunner == TouchedLine.end())
2860 *out << Verbose(2) << "ERROR: I could not find " << *CurrentLine << " in the touched list." << endl;
2861 else
2862 LineRunner->second = true;
2863 // find next point
2864 CurrentPoint = CurrentLine->GetOtherEndpoint(ReferencePoint);
2865
2866 } while (CurrentLine != StartLine);
2867 // last point is missing, as it's on start line
2868 *out << Verbose(3) << "INFO: Putting " << *CurrentPoint << " at end of path." << endl;
2869 if (StartLine->GetOtherEndpoint(ReferencePoint)->node != connectedPath->back())
2870 connectedPath->push_back(StartLine->GetOtherEndpoint(ReferencePoint)->node);
2871
2872 ListOfPaths->push_back(connectedPath);
2873 } else {
2874 *out << Verbose(3) << "INFO: Skipping " << *runner->second << ", as we have already visited it." << endl;
2875 }
2876 }
2877 } else {
2878 *out << Verbose(1) << "ERROR: There are no lines attached to " << *ReferencePoint << "." << endl;
2879 }
2880
2881 return ListOfPaths;
2882}
2883
2884/** Gets all closed paths on the circle of points connected to the provided point by triangulation lines, if this very point is removed.
2885 * From GetPathsOfConnectedPoints() extracts all single loops of intracrossing paths in the list of closed paths.
2886 * @param *out output stream for debugging
2887 * @param *Point of which get all connected points
2888 * @return list of the closed paths
2889 */
2890list<list<TesselPoint*> *> * Tesselation::GetClosedPathsOfConnectedPoints(ofstream *out, TesselPoint* Point)
2891{
2892 list<list<TesselPoint*> *> *ListofPaths = GetPathsOfConnectedPoints(out, Point);
2893 list<list<TesselPoint*> *> *ListofClosedPaths = new list<list<TesselPoint*> *>;
2894 list<TesselPoint*> *connectedPath = NULL;
2895 list<TesselPoint*> *newPath = NULL;
2896 int count = 0;
2897
2898
2899 list<TesselPoint*>::iterator CircleRunner;
2900 list<TesselPoint*>::iterator CircleStart;
2901
2902 for(list<list<TesselPoint*> *>::iterator ListRunner = ListofPaths->begin(); ListRunner != ListofPaths->end(); ListRunner++) {
2903 connectedPath = *ListRunner;
2904
2905 *out << Verbose(2) << "INFO: Current path is " << connectedPath << "." << endl;
2906
2907 // go through list, look for reappearance of starting Point and count
2908 CircleStart = connectedPath->begin();
2909
2910 // go through list, look for reappearance of starting Point and create list
2911 list<TesselPoint*>::iterator Marker = CircleStart;
2912 for (CircleRunner = CircleStart; CircleRunner != connectedPath->end(); CircleRunner++) {
2913 if ((*CircleRunner == *CircleStart) && (CircleRunner != CircleStart)) { // is not the very first point
2914 // we have a closed circle from Marker to new Marker
2915 *out << Verbose(3) << count+1 << ". closed path consists of: ";
2916 newPath = new list<TesselPoint*>;
2917 list<TesselPoint*>::iterator CircleSprinter = Marker;
2918 for (; CircleSprinter != CircleRunner; CircleSprinter++) {
2919 newPath->push_back(*CircleSprinter);
2920 *out << (**CircleSprinter) << " <-> ";
2921 }
2922 *out << ".." << endl;
2923 count++;
2924 Marker = CircleRunner;
2925
2926 // add to list
2927 ListofClosedPaths->push_back(newPath);
2928 }
2929 }
2930 }
2931 *out << Verbose(3) << "INFO: " << count << " closed additional path(s) have been created." << endl;
2932
2933 // delete list of paths
2934 while (!ListofPaths->empty()) {
2935 connectedPath = *(ListofPaths->begin());
2936 ListofPaths->remove(connectedPath);
2937 delete(connectedPath);
2938 }
2939 delete(ListofPaths);
2940
2941 // exit
2942 return ListofClosedPaths;
2943};
2944
2945
2946/** Gets all belonging triangles for a given BoundaryPointSet.
2947 * \param *out output stream for debugging
2948 * \param *Point BoundaryPoint
2949 * \return pointer to allocated list of triangles
2950 */
2951set<BoundaryTriangleSet*> *Tesselation::GetAllTriangles(ofstream *out, class BoundaryPointSet *Point)
2952{
2953 set<BoundaryTriangleSet*> *connectedTriangles = new set<BoundaryTriangleSet*>;
2954
2955 if (Point == NULL) {
2956 *out << Verbose(1) << "ERROR: Point given is NULL." << endl;
2957 } else {
2958 // go through its lines and insert all triangles
2959 for (LineMap::iterator LineRunner = Point->lines.begin(); LineRunner != Point->lines.end(); LineRunner++)
2960 for (TriangleMap::iterator TriangleRunner = (LineRunner->second)->triangles.begin(); TriangleRunner != (LineRunner->second)->triangles.end(); TriangleRunner++) {
2961 connectedTriangles->insert(TriangleRunner->second);
2962 }
2963 }
2964
2965 return connectedTriangles;
2966};
2967
2968
2969/** Removes a boundary point from the envelope while keeping it closed.
2970 * We remove the old triangles connected to the point and re-create new triangles to close the surface following this ansatz:
2971 * -# a closed path(s) of boundary points surrounding the point to be removed is constructed
2972 * -# on each closed path, we pick three adjacent points, create a triangle with them and subtract the middle point from the path
2973 * -# we advance two points (i.e. the next triangle will start at the ending point of the last triangle) and continue as before
2974 * -# the surface is closed, when the path is empty
2975 * Thereby, we (hopefully) make sure that the removed points remains beneath the surface (this is checked via IsInnerPoint eventually).
2976 * \param *out output stream for debugging
2977 * \param *point point to be removed
2978 * \return volume added to the volume inside the tesselated surface by the removal
2979 */
2980double Tesselation::RemovePointFromTesselatedSurface(ofstream *out, class BoundaryPointSet *point) {
2981 class BoundaryLineSet *line = NULL;
2982 class BoundaryTriangleSet *triangle = NULL;
2983 Vector OldPoint, NormalVector;
2984 double volume = 0;
2985 int count = 0;
2986
2987 if (point == NULL) {
2988 *out << Verbose(1) << "ERROR: Cannot remove the point " << point << ", it's NULL!" << endl;
2989 return 0.;
2990 } else
2991 *out << Verbose(2) << "Removing point " << *point << " from tesselated boundary ..." << endl;
2992
2993 // copy old location for the volume
2994 OldPoint.CopyVector(point->node->node);
2995
2996 // get list of connected points
2997 if (point->lines.empty()) {
2998 *out << Verbose(1) << "ERROR: Cannot remove the point " << *point << ", it's connected to no lines!" << endl;
2999 return 0.;
3000 }
3001
3002 list<list<TesselPoint*> *> *ListOfClosedPaths = GetClosedPathsOfConnectedPoints(out, point->node);
3003 list<TesselPoint*> *connectedPath = NULL;
3004
3005 // gather all triangles
3006 for (LineMap::iterator LineRunner = point->lines.begin(); LineRunner != point->lines.end(); LineRunner++)
3007 count+=LineRunner->second->triangles.size();
3008 map<class BoundaryTriangleSet *, int> Candidates;
3009 for (LineMap::iterator LineRunner = point->lines.begin(); LineRunner != point->lines.end(); LineRunner++) {
3010 line = LineRunner->second;
3011 for (TriangleMap::iterator TriangleRunner = line->triangles.begin(); TriangleRunner != line->triangles.end(); TriangleRunner++) {
3012 triangle = TriangleRunner->second;
3013 Candidates.insert( pair<class BoundaryTriangleSet *, int> (triangle, triangle->Nr) );
3014 }
3015 }
3016
3017 // remove all triangles
3018 count=0;
3019 NormalVector.Zero();
3020 for (map<class BoundaryTriangleSet *, int>::iterator Runner = Candidates.begin(); Runner != Candidates.end(); Runner++) {
3021 *out << Verbose(3) << "INFO: Removing triangle " << *(Runner->first) << "." << endl;
3022 NormalVector.SubtractVector(&Runner->first->NormalVector); // has to point inward
3023 RemoveTesselationTriangle(Runner->first);
3024 count++;
3025 }
3026 *out << Verbose(1) << count << " triangles were removed." << endl;
3027
3028 list<list<TesselPoint*> *>::iterator ListAdvance = ListOfClosedPaths->begin();
3029 list<list<TesselPoint*> *>::iterator ListRunner = ListAdvance;
3030 map<class BoundaryTriangleSet *, int>::iterator NumberRunner = Candidates.begin();
3031 list<TesselPoint*>::iterator StartNode, MiddleNode, EndNode;
3032 double angle;
3033 double smallestangle;
3034 Vector Point, Reference, OrthogonalVector;
3035 if (count > 2) { // less than three triangles, then nothing will be created
3036 class TesselPoint *TriangleCandidates[3];
3037 count = 0;
3038 for ( ; ListRunner != ListOfClosedPaths->end(); ListRunner = ListAdvance) { // go through all closed paths
3039 if (ListAdvance != ListOfClosedPaths->end())
3040 ListAdvance++;
3041
3042 connectedPath = *ListRunner;
3043
3044 // re-create all triangles by going through connected points list
3045 list<class BoundaryLineSet *> NewLines;
3046 for (;!connectedPath->empty();) {
3047 // search middle node with widest angle to next neighbours
3048 EndNode = connectedPath->end();
3049 smallestangle = 0.;
3050 for (MiddleNode = connectedPath->begin(); MiddleNode != connectedPath->end(); MiddleNode++) {
3051 cout << Verbose(3) << "INFO: MiddleNode is " << **MiddleNode << "." << endl;
3052 // construct vectors to next and previous neighbour
3053 StartNode = MiddleNode;
3054 if (StartNode == connectedPath->begin())
3055 StartNode = connectedPath->end();
3056 StartNode--;
3057 //cout << Verbose(3) << "INFO: StartNode is " << **StartNode << "." << endl;
3058 Point.CopyVector((*StartNode)->node);
3059 Point.SubtractVector((*MiddleNode)->node);
3060 StartNode = MiddleNode;
3061 StartNode++;
3062 if (StartNode == connectedPath->end())
3063 StartNode = connectedPath->begin();
3064 //cout << Verbose(3) << "INFO: EndNode is " << **StartNode << "." << endl;
3065 Reference.CopyVector((*StartNode)->node);
3066 Reference.SubtractVector((*MiddleNode)->node);
3067 OrthogonalVector.CopyVector((*MiddleNode)->node);
3068 OrthogonalVector.SubtractVector(&OldPoint);
3069 OrthogonalVector.MakeNormalVector(&Reference);
3070 angle = GetAngle(Point, Reference, OrthogonalVector);
3071 //if (angle < M_PI) // no wrong-sided triangles, please?
3072 if(fabs(angle - M_PI) < fabs(smallestangle - M_PI)) { // get straightest angle (i.e. construct those triangles with smallest area first)
3073 smallestangle = angle;
3074 EndNode = MiddleNode;
3075 }
3076 }
3077 MiddleNode = EndNode;
3078 if (MiddleNode == connectedPath->end()) {
3079 cout << Verbose(1) << "CRITICAL: Could not find a smallest angle!" << endl;
3080 exit(255);
3081 }
3082 StartNode = MiddleNode;
3083 if (StartNode == connectedPath->begin())
3084 StartNode = connectedPath->end();
3085 StartNode--;
3086 EndNode++;
3087 if (EndNode == connectedPath->end())
3088 EndNode = connectedPath->begin();
3089 cout << Verbose(4) << "INFO: StartNode is " << **StartNode << "." << endl;
3090 cout << Verbose(4) << "INFO: MiddleNode is " << **MiddleNode << "." << endl;
3091 cout << Verbose(4) << "INFO: EndNode is " << **EndNode << "." << endl;
3092 *out << Verbose(3) << "INFO: Attempting to create triangle " << (*StartNode)->Name << ", " << (*MiddleNode)->Name << " and " << (*EndNode)->Name << "." << endl;
3093 TriangleCandidates[0] = *StartNode;
3094 TriangleCandidates[1] = *MiddleNode;
3095 TriangleCandidates[2] = *EndNode;
3096 triangle = GetPresentTriangle(out, TriangleCandidates);
3097 if (triangle != NULL) {
3098 cout << Verbose(1) << "WARNING: New triangle already present, skipping!" << endl;
3099 StartNode++;
3100 MiddleNode++;
3101 EndNode++;
3102 if (StartNode == connectedPath->end())
3103 StartNode = connectedPath->begin();
3104 if (MiddleNode == connectedPath->end())
3105 MiddleNode = connectedPath->begin();
3106 if (EndNode == connectedPath->end())
3107 EndNode = connectedPath->begin();
3108 continue;
3109 }
3110 *out << Verbose(5) << "Adding new triangle points."<< endl;
3111 AddTesselationPoint(*StartNode, 0);
3112 AddTesselationPoint(*MiddleNode, 1);
3113 AddTesselationPoint(*EndNode, 2);
3114 *out << Verbose(5) << "Adding new triangle lines."<< endl;
3115 AddTesselationLine(TPS[0], TPS[1], 0);
3116 AddTesselationLine(TPS[0], TPS[2], 1);
3117 NewLines.push_back(BLS[1]);
3118 AddTesselationLine(TPS[1], TPS[2], 2);
3119 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
3120 BTS->GetNormalVector(NormalVector);
3121 AddTesselationTriangle();
3122 // calculate volume summand as a general tetraeder
3123 volume += CalculateVolumeofGeneralTetraeder(TPS[0]->node->node, TPS[1]->node->node, TPS[2]->node->node, &OldPoint);
3124 // advance number
3125 count++;
3126
3127 // prepare nodes for next triangle
3128 StartNode = EndNode;
3129 cout << Verbose(4) << "Removing " << **MiddleNode << " from closed path, remaining points: " << connectedPath->size() << "." << endl;
3130 connectedPath->remove(*MiddleNode); // remove the middle node (it is surrounded by triangles)
3131 if (connectedPath->size() == 2) { // we are done
3132 connectedPath->remove(*StartNode); // remove the start node
3133 connectedPath->remove(*EndNode); // remove the end node
3134 break;
3135 } else if (connectedPath->size() < 2) { // something's gone wrong!
3136 cout << Verbose(1) << "CRITICAL: There are only two endpoints left!" << endl;
3137 exit(255);
3138 } else {
3139 MiddleNode = StartNode;
3140 MiddleNode++;
3141 if (MiddleNode == connectedPath->end())
3142 MiddleNode = connectedPath->begin();
3143 EndNode = MiddleNode;
3144 EndNode++;
3145 if (EndNode == connectedPath->end())
3146 EndNode = connectedPath->begin();
3147 }
3148 }
3149 // maximize the inner lines (we preferentially created lines with a huge angle, which is for the tesselation not wanted though useful for the closing)
3150 if (NewLines.size() > 1) {
3151 list<class BoundaryLineSet *>::iterator Candidate;
3152 class BoundaryLineSet *OtherBase = NULL;
3153 double tmp, maxgain;
3154 do {
3155 maxgain = 0;
3156 for(list<class BoundaryLineSet *>::iterator Runner = NewLines.begin(); Runner != NewLines.end(); Runner++) {
3157 tmp = PickFarthestofTwoBaselines(out, *Runner);
3158 if (maxgain < tmp) {
3159 maxgain = tmp;
3160 Candidate = Runner;
3161 }
3162 }
3163 if (maxgain != 0) {
3164 volume += maxgain;
3165 cout << Verbose(3) << "Flipping baseline with highest volume" << **Candidate << "." << endl;
3166 OtherBase = FlipBaseline(out, *Candidate);
3167 NewLines.erase(Candidate);
3168 NewLines.push_back(OtherBase);
3169 }
3170 } while (maxgain != 0.);
3171 }
3172
3173 ListOfClosedPaths->remove(connectedPath);
3174 delete(connectedPath);
3175 }
3176 *out << Verbose(1) << count << " triangles were created." << endl;
3177 } else {
3178 while (!ListOfClosedPaths->empty()) {
3179 ListRunner = ListOfClosedPaths->begin();
3180 connectedPath = *ListRunner;
3181 ListOfClosedPaths->remove(connectedPath);
3182 delete(connectedPath);
3183 }
3184 *out << Verbose(1) << "No need to create any triangles." << endl;
3185 }
3186 delete(ListOfClosedPaths);
3187
3188 *out << Verbose(1) << "Removed volume is " << volume << "." << endl;
3189
3190 return volume;
3191};
3192
3193
3194
3195/**
3196 * Finds triangles belonging to the three provided points.
3197 *
3198 * @param *Points[3] list, is expected to contain three points
3199 *
3200 * @return triangles which belong to the provided points, will be empty if there are none,
3201 * will usually be one, in case of degeneration, there will be two
3202 */
3203list<BoundaryTriangleSet*> *Tesselation::FindTriangles(TesselPoint* Points[3])
3204{
3205 list<BoundaryTriangleSet*> *result = new list<BoundaryTriangleSet*>;
3206 LineMap::iterator FindLine;
3207 PointMap::iterator FindPoint;
3208 TriangleMap::iterator FindTriangle;
3209 class BoundaryPointSet *TrianglePoints[3];
3210
3211 for (int i = 0; i < 3; i++) {
3212 FindPoint = PointsOnBoundary.find(Points[i]->nr);
3213 if (FindPoint != PointsOnBoundary.end()) {
3214 TrianglePoints[i] = FindPoint->second;
3215 } else {
3216 TrianglePoints[i] = NULL;
3217 }
3218 }
3219
3220 // checks lines between the points in the Points for their adjacent triangles
3221 for (int i = 0; i < 3; i++) {
3222 if (TrianglePoints[i] != NULL) {
3223 for (int j = i; j < 3; j++) {
3224 if (TrianglePoints[j] != NULL) {
3225 FindLine = TrianglePoints[i]->lines.find(TrianglePoints[j]->node->nr);
3226 if (FindLine != TrianglePoints[i]->lines.end()) {
3227 for (; FindLine->first == TrianglePoints[j]->node->nr; FindLine++) {
3228 FindTriangle = FindLine->second->triangles.begin();
3229 for (; FindTriangle != FindLine->second->triangles.end(); FindTriangle++) {
3230 if (FindTriangle->second->IsPresentTupel(TrianglePoints)) {
3231 result->push_back(FindTriangle->second);
3232 }
3233 }
3234 }
3235 // Is it sufficient to consider one of the triangle lines for this.
3236 return result;
3237
3238 }
3239 }
3240 }
3241 }
3242 }
3243
3244 return result;
3245}
3246
3247/**
3248 * Finds all degenerated lines within the tesselation structure.
3249 *
3250 * @return map of keys of degenerated line pairs, each line occurs twice
3251 * in the list, once as key and once as value
3252 */
3253map<int, int> * Tesselation::FindAllDegeneratedLines()
3254{
3255 map<int, class BoundaryLineSet *> AllLines;
3256 map<int, int> * DegeneratedLines = new map<int, int>;
3257
3258 // sanity check
3259 if (LinesOnBoundary.empty()) {
3260 cout << Verbose(1) << "Warning: FindAllDegeneratedTriangles() was called without any tesselation structure.";
3261 return DegeneratedLines;
3262 }
3263
3264 LineMap::iterator LineRunner1;
3265 pair<LineMap::iterator, bool> tester;
3266 for (LineRunner1 = LinesOnBoundary.begin(); LineRunner1 != LinesOnBoundary.end(); ++LineRunner1) {
3267 tester = AllLines.insert( pair<int,BoundaryLineSet *> (LineRunner1->second->endpoints[0]->Nr, LineRunner1->second) );
3268 if ((!tester.second) && (tester.first->second->endpoints[1]->Nr == LineRunner1->second->endpoints[1]->Nr)) { // found degenerated line
3269 DegeneratedLines->insert ( pair<int, int> (LineRunner1->second->Nr, tester.first->second->Nr) );
3270 DegeneratedLines->insert ( pair<int, int> (tester.first->second->Nr, LineRunner1->second->Nr) );
3271 }
3272 }
3273
3274 AllLines.clear();
3275
3276 cout << Verbose(1) << "FindAllDegeneratedLines() found " << DegeneratedLines->size() << " lines." << endl;
3277 map<int,int>::iterator it;
3278 for (it = DegeneratedLines->begin(); it != DegeneratedLines->end(); it++)
3279 cout << Verbose(2) << (*it).first << " => " << (*it).second << endl;
3280
3281 return DegeneratedLines;
3282}
3283
3284/**
3285 * Finds all degenerated triangles within the tesselation structure.
3286 *
3287 * @return map of keys of degenerated triangle pairs, each triangle occurs twice
3288 * in the list, once as key and once as value
3289 */
3290map<int, int> * Tesselation::FindAllDegeneratedTriangles()
3291{
3292 map<int, int> * DegeneratedLines = FindAllDegeneratedLines();
3293 map<int, int> * DegeneratedTriangles = new map<int, int>;
3294
3295 TriangleMap::iterator TriangleRunner1, TriangleRunner2;
3296 LineMap::iterator Liner;
3297 class BoundaryLineSet *line1 = NULL, *line2 = NULL;
3298
3299 for (map<int, int>::iterator LineRunner = DegeneratedLines->begin(); LineRunner != DegeneratedLines->end(); ++LineRunner) {
3300 // run over both lines' triangles
3301 Liner = LinesOnBoundary.find(LineRunner->first);
3302 if (Liner != LinesOnBoundary.end())
3303 line1 = Liner->second;
3304 Liner = LinesOnBoundary.find(LineRunner->second);
3305 if (Liner != LinesOnBoundary.end())
3306 line2 = Liner->second;
3307 for (TriangleRunner1 = line1->triangles.begin(); TriangleRunner1 != line1->triangles.end(); ++TriangleRunner1) {
3308 for (TriangleRunner2 = line2->triangles.begin(); TriangleRunner2 != line2->triangles.end(); ++TriangleRunner2) {
3309 if ((TriangleRunner1->second != TriangleRunner2->second)
3310 && (TriangleRunner1->second->IsPresentTupel(TriangleRunner2->second))) {
3311 DegeneratedTriangles->insert( pair<int, int> (TriangleRunner1->second->Nr, TriangleRunner2->second->Nr) );
3312 DegeneratedTriangles->insert( pair<int, int> (TriangleRunner2->second->Nr, TriangleRunner1->second->Nr) );
3313 }
3314 }
3315 }
3316 }
3317 delete(DegeneratedLines);
3318
3319 cout << Verbose(1) << "FindAllDegeneratedTriangles() found " << DegeneratedTriangles->size() << " triangles:" << endl;
3320 map<int,int>::iterator it;
3321 for (it = DegeneratedTriangles->begin(); it != DegeneratedTriangles->end(); it++)
3322 cout << Verbose(2) << (*it).first << " => " << (*it).second << endl;
3323
3324 return DegeneratedTriangles;
3325}
3326
3327/**
3328 * Purges degenerated triangles from the tesselation structure if they are not
3329 * necessary to keep a single point within the structure.
3330 */
3331void Tesselation::RemoveDegeneratedTriangles()
3332{
3333 map<int, int> * DegeneratedTriangles = FindAllDegeneratedTriangles();
3334 TriangleMap::iterator finder;
3335 BoundaryTriangleSet *triangle = NULL, *partnerTriangle = NULL;
3336 int count = 0;
3337
3338 cout << Verbose(1) << "Begin of RemoveDegeneratedTriangles" << endl;
3339
3340 for (map<int, int>::iterator TriangleKeyRunner = DegeneratedTriangles->begin();
3341 TriangleKeyRunner != DegeneratedTriangles->end(); ++TriangleKeyRunner
3342 ) {
3343 finder = TrianglesOnBoundary.find(TriangleKeyRunner->first);
3344 if (finder != TrianglesOnBoundary.end())
3345 triangle = finder->second;
3346 else
3347 break;
3348 finder = TrianglesOnBoundary.find(TriangleKeyRunner->second);
3349 if (finder != TrianglesOnBoundary.end())
3350 partnerTriangle = finder->second;
3351 else
3352 break;
3353
3354 bool trianglesShareLine = false;
3355 for (int i = 0; i < 3; ++i)
3356 for (int j = 0; j < 3; ++j)
3357 trianglesShareLine = trianglesShareLine || triangle->lines[i] == partnerTriangle->lines[j];
3358
3359 if (trianglesShareLine
3360 && (triangle->endpoints[1]->LinesCount > 2)
3361 && (triangle->endpoints[2]->LinesCount > 2)
3362 && (triangle->endpoints[0]->LinesCount > 2)
3363 ) {
3364 // check whether we have to fix lines
3365 BoundaryTriangleSet *Othertriangle = NULL;
3366 BoundaryTriangleSet *OtherpartnerTriangle = NULL;
3367 TriangleMap::iterator TriangleRunner;
3368 for (int i = 0; i < 3; ++i)
3369 for (int j = 0; j < 3; ++j)
3370 if (triangle->lines[i] != partnerTriangle->lines[j]) {
3371 // get the other two triangles
3372 for (TriangleRunner = triangle->lines[i]->triangles.begin(); TriangleRunner != triangle->lines[i]->triangles.end(); ++TriangleRunner)
3373 if (TriangleRunner->second != triangle) {
3374 Othertriangle = TriangleRunner->second;
3375 }
3376 for (TriangleRunner = partnerTriangle->lines[i]->triangles.begin(); TriangleRunner != partnerTriangle->lines[i]->triangles.end(); ++TriangleRunner)
3377 if (TriangleRunner->second != partnerTriangle) {
3378 OtherpartnerTriangle = TriangleRunner->second;
3379 }
3380 /// interchanges their lines so that triangle->lines[i] == partnerTriangle->lines[j]
3381 // the line of triangle receives the degenerated ones
3382 triangle->lines[i]->triangles.erase(Othertriangle->Nr);
3383 triangle->lines[i]->triangles.insert( TrianglePair( partnerTriangle->Nr, partnerTriangle) );
3384 for (int k=0;k<3;k++)
3385 if (triangle->lines[i] == Othertriangle->lines[k]) {
3386 Othertriangle->lines[k] = partnerTriangle->lines[j];
3387 break;
3388 }
3389 // the line of partnerTriangle receives the non-degenerated ones
3390 partnerTriangle->lines[j]->triangles.erase( partnerTriangle->Nr);
3391 partnerTriangle->lines[j]->triangles.insert( TrianglePair( Othertriangle->Nr, Othertriangle) );
3392 partnerTriangle->lines[j] = triangle->lines[i];
3393 }
3394
3395 // erase the pair
3396 count += (int) DegeneratedTriangles->erase(triangle->Nr);
3397 cout << Verbose(1) << "RemoveDegeneratedTriangles() removes triangle " << *triangle << "." << endl;
3398 RemoveTesselationTriangle(triangle);
3399 count += (int) DegeneratedTriangles->erase(partnerTriangle->Nr);
3400 cout << Verbose(1) << "RemoveDegeneratedTriangles() removes triangle " << *partnerTriangle << "." << endl;
3401 RemoveTesselationTriangle(partnerTriangle);
3402 } else {
3403 cout << Verbose(1) << "RemoveDegeneratedTriangles() does not remove triangle " << *triangle
3404 << " and its partner " << *partnerTriangle << " because it is essential for at"
3405 << " least one of the endpoints to be kept in the tesselation structure." << endl;
3406 }
3407 }
3408 delete(DegeneratedTriangles);
3409
3410 cout << Verbose(1) << "RemoveDegeneratedTriangles() removed " << count << " triangles:" << endl;
3411 cout << Verbose(1) << "End of RemoveDegeneratedTriangles" << endl;
3412}
3413
3414/** Adds an outside Tesselpoint to the envelope via (two) degenerated triangles.
3415 * We look for the closest point on the boundary, we look through its connected boundary lines and
3416 * seek the one with the minimum angle between its center point and the new point and this base line.
3417 * We open up the line by adding a degenerated triangle, whose other side closes the base line again.
3418 * \param *out output stream for debugging
3419 * \param *point point to add
3420 * \param *LC Linked Cell structure to find nearest point
3421 */
3422void Tesselation::AddBoundaryPointByDegeneratedTriangle(ofstream *out, class TesselPoint *point, LinkedCell *LC)
3423{
3424 *out << Verbose(2) << "Begin of AddBoundaryPointByDegeneratedTriangle" << endl;
3425
3426 // find nearest boundary point
3427 class TesselPoint *BackupPoint = NULL;
3428 class TesselPoint *NearestPoint = FindClosestPoint(point->node, BackupPoint, LC);
3429 class BoundaryPointSet *NearestBoundaryPoint = NULL;
3430 PointMap::iterator PointRunner;
3431
3432 if (NearestPoint == point)
3433 NearestPoint = BackupPoint;
3434 PointRunner = PointsOnBoundary.find(NearestPoint->nr);
3435 if (PointRunner != PointsOnBoundary.end()) {
3436 NearestBoundaryPoint = PointRunner->second;
3437 } else {
3438 *out << Verbose(1) << "ERROR: I cannot find the boundary point." << endl;
3439 return;
3440 }
3441 *out << Verbose(2) << "Nearest point on boundary is " << NearestPoint->Name << "." << endl;
3442
3443 // go through its lines and find the best one to split
3444 Vector CenterToPoint;
3445 Vector BaseLine;
3446 double angle, BestAngle = 0.;
3447 class BoundaryLineSet *BestLine = NULL;
3448 for (LineMap::iterator Runner = NearestBoundaryPoint->lines.begin(); Runner != NearestBoundaryPoint->lines.end(); Runner++) {
3449 BaseLine.CopyVector(Runner->second->endpoints[0]->node->node);
3450 BaseLine.SubtractVector(Runner->second->endpoints[1]->node->node);
3451 CenterToPoint.CopyVector(Runner->second->endpoints[0]->node->node);
3452 CenterToPoint.AddVector(Runner->second->endpoints[1]->node->node);
3453 CenterToPoint.Scale(0.5);
3454 CenterToPoint.SubtractVector(point->node);
3455 angle = CenterToPoint.Angle(&BaseLine);
3456 if (fabs(angle - M_PI/2.) < fabs(BestAngle - M_PI/2.)) {
3457 BestAngle = angle;
3458 BestLine = Runner->second;
3459 }
3460 }
3461
3462 // remove one triangle from the chosen line
3463 class BoundaryTriangleSet *TempTriangle = (BestLine->triangles.begin())->second;
3464 BestLine->triangles.erase(TempTriangle->Nr);
3465 int nr = -1;
3466 for (int i=0;i<3; i++) {
3467 if (TempTriangle->lines[i] == BestLine) {
3468 nr = i;
3469 break;
3470 }
3471 }
3472
3473 // create new triangle to connect point (connects automatically with the missing spot of the chosen line)
3474 *out << Verbose(5) << "Adding new triangle points."<< endl;
3475 AddTesselationPoint((BestLine->endpoints[0]->node), 0);
3476 AddTesselationPoint((BestLine->endpoints[1]->node), 1);
3477 AddTesselationPoint(point, 2);
3478 *out << Verbose(5) << "Adding new triangle lines."<< endl;
3479 AddTesselationLine(TPS[0], TPS[1], 0);
3480 AddTesselationLine(TPS[0], TPS[2], 1);
3481 AddTesselationLine(TPS[1], TPS[2], 2);
3482 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
3483 BTS->GetNormalVector(TempTriangle->NormalVector);
3484 BTS->NormalVector.Scale(-1.);
3485 *out << Verbose(3) << "INFO: NormalVector of new triangle is " << BTS->NormalVector << "." << endl;
3486 AddTesselationTriangle();
3487
3488 // create other side of this triangle and close both new sides of the first created triangle
3489 *out << Verbose(5) << "Adding new triangle points."<< endl;
3490 AddTesselationPoint((BestLine->endpoints[0]->node), 0);
3491 AddTesselationPoint((BestLine->endpoints[1]->node), 1);
3492 AddTesselationPoint(point, 2);
3493 *out << Verbose(5) << "Adding new triangle lines."<< endl;
3494 AddTesselationLine(TPS[0], TPS[1], 0);
3495 AddTesselationLine(TPS[0], TPS[2], 1);
3496 AddTesselationLine(TPS[1], TPS[2], 2);
3497 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
3498 BTS->GetNormalVector(TempTriangle->NormalVector);
3499 *out << Verbose(3) << "INFO: NormalVector of other new triangle is " << BTS->NormalVector << "." << endl;
3500 AddTesselationTriangle();
3501
3502 // add removed triangle to the last open line of the second triangle
3503 for (int i=0;i<3;i++) { // look for the same line as BestLine (only it's its degenerated companion)
3504 if ((BTS->lines[i]->ContainsBoundaryPoint(BestLine->endpoints[0])) && (BTS->lines[i]->ContainsBoundaryPoint(BestLine->endpoints[1]))) {
3505 if (BestLine == BTS->lines[i]){
3506 *out << Verbose(1) << "CRITICAL: BestLine is same as found line, something's wrong here!" << endl;
3507 exit(255);
3508 }
3509 BTS->lines[i]->triangles.insert( pair<int, class BoundaryTriangleSet *> (TempTriangle->Nr, TempTriangle) );
3510 TempTriangle->lines[nr] = BTS->lines[i];
3511 break;
3512 }
3513 }
3514
3515 // exit
3516 *out << Verbose(2) << "End of AddBoundaryPointByDegeneratedTriangle" << endl;
3517};
3518
3519/** Writes the envelope to file.
3520 * \param *out otuput stream for debugging
3521 * \param *filename basename of output file
3522 * \param *cloud PointCloud structure with all nodes
3523 */
3524void Tesselation::Output(ofstream *out, const char *filename, PointCloud *cloud)
3525{
3526 ofstream *tempstream = NULL;
3527 string NameofTempFile;
3528 char NumberName[255];
3529
3530 if (LastTriangle != NULL) {
3531 sprintf(NumberName, "-%04d-%s_%s_%s", (int)TrianglesOnBoundary.size(), LastTriangle->endpoints[0]->node->Name, LastTriangle->endpoints[1]->node->Name, LastTriangle->endpoints[2]->node->Name);
3532 if (DoTecplotOutput) {
3533 string NameofTempFile(filename);
3534 NameofTempFile.append(NumberName);
3535 for(size_t npos = NameofTempFile.find_first_of(' '); npos != string::npos; npos = NameofTempFile.find(' ', npos))
3536 NameofTempFile.erase(npos, 1);
3537 NameofTempFile.append(TecplotSuffix);
3538 *out << Verbose(1) << "Writing temporary non convex hull to file " << NameofTempFile << ".\n";
3539 tempstream = new ofstream(NameofTempFile.c_str(), ios::trunc);
3540 WriteTecplotFile(out, tempstream, this, cloud, TriangleFilesWritten);
3541 tempstream->close();
3542 tempstream->flush();
3543 delete(tempstream);
3544 }
3545
3546 if (DoRaster3DOutput) {
3547 string NameofTempFile(filename);
3548 NameofTempFile.append(NumberName);
3549 for(size_t npos = NameofTempFile.find_first_of(' '); npos != string::npos; npos = NameofTempFile.find(' ', npos))
3550 NameofTempFile.erase(npos, 1);
3551 NameofTempFile.append(Raster3DSuffix);
3552 *out << Verbose(1) << "Writing temporary non convex hull to file " << NameofTempFile << ".\n";
3553 tempstream = new ofstream(NameofTempFile.c_str(), ios::trunc);
3554 WriteRaster3dFile(out, tempstream, this, cloud);
3555 IncludeSphereinRaster3D(out, tempstream, this, cloud);
3556 tempstream->close();
3557 tempstream->flush();
3558 delete(tempstream);
3559 }
3560 }
3561 if (DoTecplotOutput || DoRaster3DOutput)
3562 TriangleFilesWritten++;
3563};
Note: See TracBrowser for help on using the repository browser.