source: src/tesselation.cpp@ b9947d

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 b9947d was e138de, checked in by Frederik Heber <heber@…>, 15 years ago

Huge change from ofstream * (const) out --> Log().

  • first shift was done via regular expressions
  • then via error messages from the code
  • note that class atom, class element and class molecule kept in parts their output stream, was they print to file.
  • make check runs fine
  • MISSING: Verbosity is not fixed for everything (i.e. if no endl; is present and next has Verbose(0) ...)

Signed-off-by: Frederik Heber <heber@…>

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