source: src/tesselation.cpp@ b70721

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 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 b70721 was c0f6c6, checked in by Frederik Heber <heber@…>, 16 years ago

Refactored tesselationhelpers.cpp with respect to ticket #38 (make const what is const).
Signed-off-by: Frederik Heber <heber@…>

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